text
stringlengths 424
69.5k
|
---|
### Prompt
Please formulate a CPP solution to the following problem:
You are given an array s consisting of n integers.
You have to find any array t of length k such that you can cut out maximum number of copies of array t from array s.
Cutting out the copy of t means that for each element t_i of array t you have to find t_i in s and remove it from s. If for some t_i you cannot find such element in s, then you cannot cut out one more copy of t. The both arrays can contain duplicate elements.
For example, if s = [1, 2, 3, 2, 4, 3, 1] and k = 3 then one of the possible answers is t = [1, 2, 3]. This array t can be cut out 2 times.
* To cut out the first copy of t you can use the elements [1, \underline{2}, 3, 2, 4, \underline{3}, \underline{1}] (use the highlighted elements). After cutting out the first copy of t the array s can look like [1, 3, 2, 4].
* To cut out the second copy of t you can use the elements [\underline{1}, \underline{3}, \underline{2}, 4]. After cutting out the second copy of t the array s will be [4].
Your task is to find such array t that you can cut out the copy of t from s maximum number of times. If there are multiple answers, you may choose any of them.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in s and the desired number of elements in t, respectively.
The second line of the input contains exactly n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 2 β
10^5).
Output
Print k integers β the elements of array t such that you can cut out maximum possible number of copies of this array from s. If there are multiple answers, print any of them. The required array t can contain duplicate elements. All the elements of t (t_1, t_2, ..., t_k) should satisfy the following condition: 1 β€ t_i β€ 2 β
10^5.
Examples
Input
7 3
1 2 3 2 4 3 1
Output
1 2 3
Input
10 4
1 3 1 3 10 3 7 7 12 3
Output
7 3 1 3
Input
15 2
1 2 1 1 1 2 1 1 2 1 2 1 1 1 1
Output
1 1
Note
The first example is described in the problem statement.
In the second example the only answer is [7, 3, 1, 3] and any its permutations. It can be shown that you cannot choose any other array such that the maximum number of copies you can cut out would be equal to 2.
In the third example the array t can be cut out 5 times.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<long long> v;
map<long long, long long> m;
bool ok(long long mid, long long k) {
v.clear();
for (auto x : m) {
long long sizeV = (long long)v.size();
for (long long i = 0; i < min(x.second / mid, k - sizeV); i++) {
v.push_back(x.first);
if ((long long)v.size() == k) return true;
}
if ((long long)v.size() == k) return true;
}
if ((long long)v.size() == k)
return true;
else
return false;
}
void solve() {
long long n, k;
cin >> n >> k;
vector<long long> a(n);
for (long long i = 0; i < n; i++) {
cin >> a[i];
m[a[i]]++;
}
long long l = 1, r = n;
vector<long long> ans;
long long best = 0;
while (l <= r) {
long long mid = l + (r - l) / 2;
if (ok(mid, k)) {
best = mid;
l = mid + 1;
v.clear();
} else {
r = mid - 1;
}
}
ok(best, k);
for (auto x : v) cout << x << " ";
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
;
long long t = 1;
while (t--) {
solve();
}
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Alice and Bob like games. And now they are ready to start a new game. They have placed n chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob β from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman.
How many bars each of the players will consume?
Input
The first line contains one integer n (1 β€ n β€ 105) β the amount of bars on the table. The second line contains a sequence t1, t2, ..., tn (1 β€ ti β€ 1000), where ti is the time (in seconds) needed to consume the i-th bar (in the order from left to right).
Output
Print two numbers a and b, where a is the amount of bars consumed by Alice, and b is the amount of bars consumed by Bob.
Examples
Input
5
2 9 8 2 7
Output
2 3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
signed main() {
deque<int> de;
int num, a = 0, b = 0, t, totala = 0, totalb = 0;
cin >> num;
for (int i = 0; i < num; i++) {
cin >> t;
de.push_back(t);
}
a += de.front();
de.pop_front();
totala++;
while (!de.empty()) {
if (b >= a) {
a += de.front();
de.pop_front();
totala++;
} else {
b += de.back();
de.pop_back();
totalb++;
}
}
cout << totala << " " << totalb << endl;
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and n.
Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
Input
The first line contains two integers n and d (2 β€ n β€ 100, 1 β€ d β€ n - 1) β the point, which the frog wants to reach, and the maximal length of the frog jump.
The second line contains a string s of length n, consisting of zeros and ones. If a character of the string s equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string s equal to one.
Output
If the frog can not reach the home, print -1.
In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point n from the point 1.
Examples
Input
8 4
10010101
Output
2
Input
4 2
1001
Output
-1
Input
8 4
11100101
Output
3
Input
12 3
101111100101
Output
4
Note
In the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).
In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
char a[200];
int main() {
int n, d, pos = 0, cnt = 0;
cin >> n >> d;
for (int i = 0; i < n; ++i) cin >> a[i];
while (pos != n - 1) {
int go;
for (int i = d; i >= 0; --i) {
if (pos + i < n && a[pos + i] - 48) {
go = i;
break;
}
}
if (!go) {
cout << "-1\n";
return 0;
}
pos += go;
++cnt;
}
cout << cnt << '\n';
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Karen has just arrived at school, and she has a math test today!
<image>
The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points.
There are n integers written on a row. Karen must alternately add and subtract each pair of adjacent integers, and write down the sums or differences on the next row. She must repeat this process on the values on the next row, and so on, until only one integer remains. The first operation should be addition.
Note that, if she ended the previous row by adding the integers, she should start the next row by subtracting, and vice versa.
The teachers will simply look at the last integer, and then if it is correct, Karen gets a perfect score, otherwise, she gets a zero for the test.
Karen has studied well for this test, but she is scared that she might make a mistake somewhere and it will cause her final answer to be wrong. If the process is followed, what number can she expect to be written on the last row?
Since this number can be quite large, output only the non-negative remainder after dividing it by 109 + 7.
Input
The first line of input contains a single integer n (1 β€ n β€ 200000), the number of numbers written on the first row.
The next line contains n integers. Specifically, the i-th one among these is ai (1 β€ ai β€ 109), the i-th number on the first row.
Output
Output a single integer on a line by itself, the number on the final row after performing the process above.
Since this number can be quite large, print only the non-negative remainder after dividing it by 109 + 7.
Examples
Input
5
3 6 9 12 15
Output
36
Input
4
3 7 5 2
Output
1000000006
Note
In the first test case, the numbers written on the first row are 3, 6, 9, 12 and 15.
Karen performs the operations as follows:
<image>
The non-negative remainder after dividing the final number by 109 + 7 is still 36, so this is the correct output.
In the second test case, the numbers written on the first row are 3, 7, 5 and 2.
Karen performs the operations as follows:
<image>
The non-negative remainder after dividing the final number by 109 + 7 is 109 + 6, so this is the correct output.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
int fac[N], inv[N];
int Inv(int a) {
int p = mod - 2;
int res = 1;
while (p) {
if (p & 1) res = (long long)res * a % mod;
p >>= 1;
a = (long long)a * a % mod;
}
return res;
}
int C(int n, int k) {
if (n < 0 || k < 0 || k > n) return 0;
return (long long)fac[n] * inv[k] % mod * inv[n - k] % mod;
}
int n;
vector<int> vec;
void work(bool plus) {
vector<int> tv;
for (int i = 0; i + 1 < vec.size(); i++) {
if (plus)
tv.push_back((vec[i] + vec[i + 1]) % mod);
else
tv.push_back((vec[i] - vec[i + 1] + mod) % mod);
plus = !plus;
}
vec = tv;
}
int solve() {
int m = (int)vec.size() / 2;
int ret = 0;
for (int i = 0; i < vec.size(); i += 2) {
ret = (ret + (long long)vec[i] * C(m, i / 2)) % mod;
}
return ret;
}
int main() {
fac[0] = inv[0] = 1;
for (int i = 1; i < N; i++) {
fac[i] = (long long)i * fac[i - 1] % mod;
inv[i] = Inv(fac[i]);
}
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
int a;
scanf("%d", &a);
vec.push_back(a);
}
bool plus = true;
while (1) {
if ((int)vec.size() % 4 == 1) {
printf("%d\n", solve());
break;
} else {
work(plus);
if ((int)vec.size() % 2) plus = !plus;
}
}
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
You need to execute several tasks, each associated with number of processors it needs, and the compute power it will consume.
You have sufficient number of analog computers, each with enough processors for any task. Each computer can execute up to one task at a time, and no more than two tasks total. The first task can be any, the second task on each computer must use strictly less power than the first. You will assign between 1 and 2 tasks to each computer. You will then first execute the first task on each computer, wait for all of them to complete, and then execute the second task on each computer that has two tasks assigned.
If the average compute power per utilized processor (the sum of all consumed powers for all tasks presently running divided by the number of utilized processors) across all computers exceeds some unknown threshold during the execution of the first tasks, the entire system will blow up. There is no restriction on the second tasks execution. Find the lowest threshold for which it is possible.
Due to the specifics of the task, you need to print the answer multiplied by 1000 and rounded up.
Input
The first line contains a single integer n (1 β€ n β€ 50) β the number of tasks.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 108), where ai represents the amount of power required for the i-th task.
The third line contains n integers b1, b2, ..., bn (1 β€ bi β€ 100), where bi is the number of processors that i-th task will utilize.
Output
Print a single integer value β the lowest threshold for which it is possible to assign all tasks in such a way that the system will not blow up after the first round of computation, multiplied by 1000 and rounded up.
Examples
Input
6
8 10 9 9 8 10
1 1 1 1 1 1
Output
9000
Input
6
8 10 9 9 8 10
1 10 5 5 1 10
Output
1160
Note
In the first example the best strategy is to run each task on a separate computer, getting average compute per processor during the first round equal to 9.
In the second task it is best to run tasks with compute 10 and 9 on one computer, tasks with compute 10 and 8 on another, and tasks with compute 9 and 8 on the last, averaging (10 + 10 + 9) / (10 + 10 + 5) = 1.16 compute power per processor during the first round.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 55;
struct data {
long long a, b;
} qx[N];
long long f[N][N];
int n;
bool cmp(data xx, data yy) {
if (xx.a != yy.a)
return xx.a > yy.a;
else
return xx.b < yy.b;
}
long long Min(long long &x, long long y) { x = min(x, y); }
bool check(long long x) {
int lt = 1;
memset(f, 0x3f, sizeof f);
f[0][0] = 0;
for (int i = 1; i <= n; ++i) {
lt = i;
while (lt + 1 <= n && qx[i].a == qx[lt + 1].a) lt++;
for (int k = 0; k <= i - 1; ++k)
for (int t = 0; t <= min(lt - i + 1, k); ++t) {
for (int j = i; j <= i + t - 1; ++j)
Min(f[j][k - (j - i + 1)], f[i - 1][k]);
long long sum = 0;
for (int j = i + t; j <= lt; ++j) {
sum += qx[j].a - x * qx[j].b;
int pos = k - t + (j - (i + t) + 1);
Min(f[j][pos], f[i - 1][k] + sum);
}
}
i = lt;
}
for (int i = 0; i <= n; ++i)
if (f[n][i] <= 0) return 1;
return 0;
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; ++i) scanf("%lld", &qx[i].a), qx[i].a *= 1000;
for (int i = 1; i <= n; ++i) scanf("%lld", &qx[i].b), qx[i].b;
sort(qx + 1, qx + 1 + n, cmp);
long long l = 0, r = 1e13, ans = -1;
while (l <= r) {
double mid = (l + r) >> 1;
if (check(mid))
ans = mid, r = mid - 1;
else
l = mid + 1;
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Yaroslav has an array that consists of n integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time.
Help Yaroslav.
Input
The first line contains integer n (1 β€ n β€ 100) β the number of elements in the array. The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 1000) β the array elements.
Output
In the single line print "YES" (without the quotes) if Yaroslav can obtain the array he needs, and "NO" (without the quotes) otherwise.
Examples
Input
1
1
Output
YES
Input
3
1 1 2
Output
YES
Input
4
7 7 7 7
Output
NO
Note
In the first sample the initial array fits well.
In the second sample Yaroslav can get array: 1, 2, 1. He can swap the last and the second last elements to obtain it.
In the third sample Yarosav can't get the array he needs.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; }
const int N = 105;
const int mod = 1e9 + 7;
bool flag = 0;
int a[N], b[N];
int main() {
std::ios::sync_with_stdio(false);
int n, t;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> t;
a[t]++;
if (a[t] > (n + 1) / 2) flag = 1;
}
if (flag)
cout << "NO" << endl;
else
cout << "YES" << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
The football season has just ended in Berland. According to the rules of Berland football, each match is played between two teams. The result of each match is either a draw, or a victory of one of the playing teams. If a team wins the match, it gets w points, and the opposing team gets 0 points. If the game results in a draw, both teams get d points.
The manager of the Berland capital team wants to summarize the results of the season, but, unfortunately, all information about the results of each match is lost. The manager only knows that the team has played n games and got p points for them.
You have to determine three integers x, y and z β the number of wins, draws and loses of the team. If there are multiple answers, print any of them. If there is no suitable triple (x, y, z), report about it.
Input
The first line contains four integers n, p, w and d (1 β€ n β€ 10^{12}, 0 β€ p β€ 10^{17}, 1 β€ d < w β€ 10^{5}) β the number of games, the number of points the team got, the number of points awarded for winning a match, and the number of points awarded for a draw, respectively. Note that w > d, so the number of points awarded for winning is strictly greater than the number of points awarded for draw.
Output
If there is no answer, print -1.
Otherwise print three non-negative integers x, y and z β the number of wins, draws and losses of the team. If there are multiple possible triples (x, y, z), print any of them. The numbers should meet the following conditions:
* x β
w + y β
d = p,
* x + y + z = n.
Examples
Input
30 60 3 1
Output
17 9 4
Input
10 51 5 4
Output
-1
Input
20 0 15 5
Output
0 0 20
Note
One of the possible answers in the first example β 17 wins, 9 draws and 4 losses. Then the team got 17 β
3 + 9 β
1 = 60 points in 17 + 9 + 4 = 30 games.
In the second example the maximum possible score is 10 β
5 = 50. Since p = 51, there is no answer.
In the third example the team got 0 points, so all 20 games were lost.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long n, p, w, d, y = -1, x = -1;
cin >> n >> p >> w >> d;
bool f1 = false, f2 = false, f3 = false;
for (long long i = 0; i <= 1000000; ++i) {
long long aux = (p - (i * d)) / w;
if (aux * w + i * d == p && aux >= 0) {
x = aux;
y = i;
break;
}
}
if (x != -1 && y != -1) {
long long res = n - (x + y);
if (res >= 0) {
cout << x << " " << y << " " << res << endl;
f1 = true;
}
}
if (!f1) {
if (p % w == 0) {
long long win = p / w;
long long res = n - win;
if (res >= 0) {
cout << win << " " << 0 << " " << res << '\n';
f2 = true;
}
}
}
if (!f2 && !f1) {
if (p % d == 0) {
long long win = p / d;
long long res = n - win;
if (res >= 0) {
cout << win << " " << 0 << " " << res << '\n';
f3 = true;
}
}
}
if (!f1 && !f2 && !f3) cout << -1 << '\n';
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Mike is trying rock climbing but he is awful at it.
There are n holds on the wall, i-th hold is at height ai off the ground. Besides, let the sequence ai increase, that is, ai < ai + 1 for all i from 1 to n - 1; we will call such sequence a track. Mike thinks that the track a1, ..., an has difficulty <image>. In other words, difficulty equals the maximum distance between two holds that are adjacent in height.
Today Mike decided to cover the track with holds hanging on heights a1, ..., an. To make the problem harder, Mike decided to remove one hold, that is, remove one element of the sequence (for example, if we take the sequence (1, 2, 3, 4, 5) and remove the third element from it, we obtain the sequence (1, 2, 4, 5)). However, as Mike is awful at climbing, he wants the final difficulty (i.e. the maximum difference of heights between adjacent holds after removing the hold) to be as small as possible among all possible options of removing a hold. The first and last holds must stay at their positions.
Help Mike determine the minimum difficulty of the track after removing one hold.
Input
The first line contains a single integer n (3 β€ n β€ 100) β the number of holds.
The next line contains n space-separated integers ai (1 β€ ai β€ 1000), where ai is the height where the hold number i hangs. The sequence ai is increasing (i.e. each element except for the first one is strictly larger than the previous one).
Output
Print a single number β the minimum difficulty of the track after removing a single hold.
Examples
Input
3
1 4 6
Output
5
Input
5
1 2 3 4 5
Output
2
Input
5
1 2 3 7 8
Output
4
Note
In the first sample you can remove only the second hold, then the sequence looks like (1, 6), the maximum difference of the neighboring elements equals 5.
In the second test after removing every hold the difficulty equals 2.
In the third test you can obtain sequences (1, 3, 7, 8), (1, 2, 7, 8), (1, 2, 3, 8), for which the difficulty is 4, 5 and 5, respectively. Thus, after removing the second element we obtain the optimal answer β 4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, vi[101], res[101], ansmin = 10000000, ansmax;
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &vi[i]);
for (int i = 0; i < n - 1; i++) res[i] = vi[i + 1] - vi[i];
for (int i = 0; i < n - 2; i++) {
ansmax = res[i] + res[i + 1];
for (int j = 0; j < n - 1; j++) ansmax = max(ansmax, res[j]);
ansmin = min(ansmin, ansmax);
}
printf("%d\n", ansmin);
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
You are given array a_1, a_2, ..., a_n. You need to split it into k subsegments (so every element is included in exactly one subsegment).
The weight of a subsegment a_l, a_{l+1}, ..., a_r is equal to (r - l + 1) β
max_{l β€ i β€ r}(a_i). The weight of a partition is a total weight of all its segments.
Find the partition of minimal weight.
Input
The first line contains two integers n and k (1 β€ n β€ 2 β
10^4, 1 β€ k β€ min(100, n)) β the length of the array a and the number of subsegments in the partition.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^4) β the array a.
Output
Print single integer β the minimal weight among all possible partitions.
Examples
Input
4 2
6 1 7 4
Output
25
Input
4 3
6 1 7 4
Output
21
Input
5 4
5 1 5 1 5
Output
21
Note
The optimal partition in the first example is next: 6 1 7 \bigg| 4.
The optimal partition in the second example is next: 6 \bigg| 1 \bigg| 7 4.
One of the optimal partitions in the third example is next: 5 \bigg| 1 5 \bigg| 1 \bigg| 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, K;
int a[20007];
int q[20007][27];
void ST() {
for (int i = 1; i <= n; i++) {
q[i][0] = i;
}
for (int j = 1; j <= 20; j++) {
for (int i = 1; i + (1 << j) - 1 <= n; i++) {
if (a[q[i][j - 1]] > a[q[i + (1 << (j - 1))][j - 1]]) {
q[i][j] = q[i][j - 1];
} else {
q[i][j] = q[i + (1 << (j - 1))][j - 1];
}
}
}
return;
}
inline int ask(const int &op, const int &ed) {
int l = log2(ed - op + 1);
if (a[q[op][l]] > a[q[ed - (1 << l) + 1][l]]) {
return q[op][l];
} else {
return q[ed - (1 << l) + 1][l];
}
}
struct Line {
long long k, b;
Line(long long K = 0, long long B = 0) {
k = K;
b = B;
}
};
Line tr[20007 << 2];
int vis[20007 << 2];
void build(int k, int l, int r) {
vis[k] = 0;
tr[k] = Line(0, 0);
if (l == r) return;
int mid = (l + r) >> 1;
build((k << 1), l, mid);
build((k << 1 | 1), mid + 1, r);
}
void pushdown(int k, int l, int r, Line s) {
if (!vis[k]) return (void)(vis[k] = 1, tr[k] = s);
long long l1 = s.k * l + s.b, r1 = s.k * r + s.b;
long long l2 = tr[k].k * l + tr[k].b, r2 = tr[k].k * r + tr[k].b;
if (l1 <= l2 && r1 <= r2) return (void)(tr[k] = s);
if (l1 >= l2 && r1 >= r2) return;
double pos = (s.b - tr[k].b) / (tr[k].k - s.k);
int mid = (l + r) >> 1;
if (pos <= mid)
pushdown((k << 1), l, mid, r1 < r2 ? tr[k] : s);
else
pushdown((k << 1 | 1), mid + 1, r, l1 < l2 ? tr[k] : s);
if ((pos <= mid && r1 < r2) || (pos > mid && l1 < l2)) tr[k] = s;
}
void insert(int k, int l, int r, int x, int y, Line s) {
if (x <= l && r <= y) return pushdown(k, l, r, s);
int mid = (l + r) >> 1;
if (x <= mid) insert((k << 1), l, mid, x, y, s);
if (y > mid) insert((k << 1 | 1), mid + 1, r, x, y, s);
}
long long query(int k, int l, int r, int x) {
long long ret = tr[k].k * x + tr[k].b;
if (!vis[k]) ret = 0x3f3f3f3f3f3f3f3f;
if (l == r) return ret;
int mid = (l + r) >> 1;
if (x <= mid)
ret = min(ret, query((k << 1), l, mid, x));
else
ret = min(ret, query((k << 1 | 1), mid + 1, r, x));
return ret;
}
struct Point {
long long x, y;
Point(){};
Point(long long a, long long b) : x(a), y(b){};
};
inline double Slope(const Point &a, const Point &b) {
return 1.0 * (b.y - a.y) / (b.x - a.x);
}
deque<Point> empty;
deque<Point> tmp[20007];
int ls[20007], top;
Line query(int id, long long k) {
if (!tmp[id].size()) return Line(0, 1e9);
while (tmp[id].size() > 1 && Slope(tmp[id][0], tmp[id][1]) <= k)
tmp[id].pop_front();
return Line(k, tmp[id][0].y - k * tmp[id][0].x);
}
void insertfront(int id, Point a) {
while (tmp[id].size() > 1) {
Point x = tmp[id][0], y = tmp[id][1];
if (Slope(a, y) >= Slope(x, y))
tmp[id].pop_front();
else
break;
}
tmp[id].push_front(a);
return;
}
void insertback(int id, Point a) {
while (tmp[id].size() > 1) {
int n = tmp[id].size();
Point x = tmp[id][n - 2], y = tmp[id][n - 1];
if (Slope(a, x) <= Slope(x, y))
tmp[id].pop_back();
else
break;
}
tmp[id].push_back(a);
return;
}
long long dp[107][20007];
int solve(int l, int r, const int &cur) {
if (l > r) return -1;
if (l == r) {
int id = ls[top--];
tmp[id].push_back(Point(l, dp[cur - 1][l]));
return id;
}
int pos = ask(l + 1, r);
int L = solve(l, pos - 1, cur);
insert(1, 1, n, pos, r, query(L, a[pos]));
if (L == -1) L = ls[top--];
dp[cur][pos] = query(1, 1, n, pos);
int R = solve(pos, r, cur);
if (tmp[R].size() <= tmp[L].size()) {
while (tmp[R].size()) {
insertback(L, tmp[R][0]);
tmp[R].pop_front();
}
ls[++top] = R;
return L;
} else {
while (tmp[L].size()) {
insertfront(R, tmp[L][tmp[L].size() - 1]);
tmp[L].pop_back();
}
ls[++top] = L;
return R;
}
}
int main() {
scanf("%d%d", &n, &K);
for (int i = 1; i <= n; i++) {
ls[i] = i;
}
top = n;
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
}
ST();
for (int i = 1; i <= n; i++) {
dp[1][i] = 1ll * i * a[ask(1, i)];
}
for (int i = 2; i <= K; i++) {
build(1, 1, n);
solve(i - 1, n, i);
}
printf("%lld\n", dp[K][n]);
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
10^{10^{10}} participants, including Takahashi, competed in two programming contests. In each contest, all participants had distinct ranks from first through 10^{10^{10}}-th.
The score of a participant is the product of his/her ranks in the two contests.
Process the following Q queries:
* In the i-th query, you are given two positive integers A_i and B_i. Assuming that Takahashi was ranked A_i-th in the first contest and B_i-th in the second contest, find the maximum possible number of participants whose scores are smaller than Takahashi's.
Constraints
* 1 \leq Q \leq 100
* 1\leq A_i,B_i\leq 10^9(1\leq i\leq Q)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
Q
A_1 B_1
:
A_Q B_Q
Output
For each query, print the maximum possible number of participants whose scores are smaller than Takahashi's.
Example
Input
8
1 4
10 5
3 3
4 11
8 9
22 40
8 36
314159265 358979323
Output
1
12
4
11
14
57
31
671644785
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int Q;
cin >> Q;
for (int i = 0; i < Q; i++) {
long long a, b, res;
cin >> a >> b;
long long q = ceil(sqrt(a * b));
if (a == b) {
res = 2 * (a - 1);
} else if(a * b > q * (q - 1)) {
res = 2 * (q - 1) - 1;
} else {
res = 2 * (q - 2);
}
cout << res << endl;
}
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Takahashi is meeting up with Aoki.
They have planned to meet at a place that is D meters away from Takahashi's house in T minutes from now.
Takahashi will leave his house now and go straight to the place at a speed of S meters per minute.
Will he arrive in time?
Constraints
* 1 \leq D \leq 10000
* 1 \leq T \leq 10000
* 1 \leq S \leq 10000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
D T S
Output
If Takahashi will reach the place in time, print `Yes`; otherwise, print `No`.
Examples
Input
1000 15 80
Output
Yes
Input
2000 20 100
Output
Yes
Input
10000 1 1
Output
No
### Response
```cpp
#include<stdio.h>
int d,t,s;
int main()
{
scanf("%d %d %d", &d, &t, &s);
d=d+s-1;
if(t>=(d/s))printf("Yes");
else printf("No");
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Write a program which reads a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and rotate specified elements by a list of the following operation:
* rotate($b, m, e$): For each integer $k$ ($0 \leq k < (e - b)$), move element $b + k$ to the place of element $b + ((k + (e - m)) \mod (e - b))$.
Constraints
* $1 \leq n \leq 1,000$
* $-1,000,000,000 \leq a_i \leq 1,000,000,000$
* $1 \leq q \leq 1,000$
* $0 \leq b_i \leq m_i < e_i \leq n$
Input
The input is given in the following format.
$n$
$a_0 \; a_1 \; ...,\; a_{n-1}$
$q$
$b_1 \; m_1 \; e_1$
$b_2 \; m_2 \; e_2$
:
$b_{q} \; m_{q} \; e_{q}$
In the first line, $n$ (the number of elements in $A$) is given. In the second line, $a_i$ (each element in $A$) are given. In the third line, the number of queries $q$ is given and each query is given by three integers $b_i \; m_i \; e_i$ in the following $q$ lines.
Output
Print all elements of $A$ in a line after performing the given operations. Put a single space character between adjacency elements and a newline at the end of the last element.
Example
Input
11
1 2 3 4 5 6 7 8 9 10 11
1
2 6 9
Output
1 2 7 8 9 3 4 5 6 10 11
### Response
```cpp
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
int n, q, b, m, e;
cin >> n;
vector<int> A(n);
vector<int>::iterator a = A.begin();
for(int i = 0;i < n;i++) cin >> A[i];
cin >> q;
for(int i = 0;i < q;i++){
cin >> b >> m >> e;
rotate(a + b, a + m, a + e);
}
for(int i = 0;i < n;i++){
cout << (i?" ":"");
cout << A[i];
}
cout << endl;
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Yaroslav calls an array of r integers a1, a2, ..., ar good, if it meets the following conditions: |a1 - a2| = 1, |a2 - a3| = 1, ..., |ar - 1 - ar| = 1, |ar - a1| = 1, at that <image>.
An array of integers b1, b2, ..., br is called great, if it meets the following conditions:
1. The elements in it do not decrease (bi β€ bi + 1).
2. If the inequalities 1 β€ r β€ n and 1 β€ bi β€ m hold.
3. If we can rearrange its elements and get at least one and at most k distinct good arrays.
Yaroslav has three integers n, m, k. He needs to count the number of distinct great arrays. Help Yaroslav! As the answer may be rather large, print the remainder after dividing it by 1000000007 (109 + 7).
Two arrays are considered distinct if there is a position in which they have distinct numbers.
Input
The single line contains three integers n, m, k (1 β€ n, m, k β€ 100).
Output
In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7).
Examples
Input
1 1 1
Output
0
Input
3 3 3
Output
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 105;
const long long mod = 1e9 + 7;
int n, m, tmp, k, now, last, dp[2][N][N][N], ans, K, c[N][N];
int main() {
scanf("%d%d%d", &n, &m, &K);
c[0][0] = 1;
for (int i = 1; i <= K; i++)
for (int j = 0; j <= i; j++) {
c[i][j] = (j ? c[i - 1][j - 1] : 0) + c[i - 1][j];
if (c[i][j] > K) c[i][j] = K + 1;
}
n++;
now = 1;
last = 0;
dp[now][0][1][1] = 1;
for (int i = 0; i <= m; i++) {
last = now;
now ^= 1;
if (i) {
tmp = 0;
for (int j = 2; j <= n; j++)
for (int l = 1; l <= K; l++) tmp = (tmp + dp[last][j][0][l]) % mod;
ans = (ans + (long long)tmp * (m - i + 1) % mod) % mod;
}
if (i == m) break;
memset(dp[now], 0, sizeof(dp[now]));
for (int j = 0; j <= n; j++)
for (int k = 1; k <= n; k++)
for (int l = 1; l <= K; l++)
if (dp[last][j][k][l])
for (int t = k; t <= n - j; t++)
if (l * c[t - 1][k - 1] <= K)
dp[now][j + t][t - k][l * c[t - 1][k - 1]] =
(dp[now][j + t][t - k][l * c[t - 1][k - 1]] +
dp[last][j][k][l]) %
mod;
}
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
There are N cards. The two sides of each of these cards are distinguishable. The i-th of these cards has an integer A_i printed on the front side, and another integer B_i printed on the back side. We will call the deck of these cards X. There are also N+1 cards of another kind. The i-th of these cards has an integer C_i printed on the front side, and nothing is printed on the back side. We will call this another deck of cards Y.
You will play Q rounds of a game. Each of these rounds is played independently. In the i-th round, you are given a new card. The two sides of this card are distinguishable. It has an integer D_i printed on the front side, and another integer E_i printed on the back side. A new deck of cards Z is created by adding this card to X. Then, you are asked to form N+1 pairs of cards, each consisting of one card from Z and one card from Y. Each card must belong to exactly one of the pairs. Additionally, for each card from Z, you need to specify which side to use. For each pair, the following condition must be met:
* (The integer printed on the used side of the card from Z) \leq (The integer printed on the card from Y)
If it is not possible to satisfy this condition regardless of how the pairs are formed and which sides are used, the score for the round will be -1. Otherwise, the score for the round will be the count of the cards from Z whose front side is used.
Find the maximum possible score for each round.
Constraints
* All input values are integers.
* 1 \leq N \leq 10^5
* 1 \leq Q \leq 10^5
* 1 \leq A_i ,B_i ,C_i ,D_i ,E_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 B_1
A_2 B_2
:
A_N B_N
C_1 C_2 .. C_{N+1}
Q
D_1 E_1
D_2 E_2
:
D_Q E_Q
Output
For each round, print the maximum possible score in its own line.
Examples
Input
3
4 1
5 3
3 1
1 2 3 4
3
5 4
4 3
2 3
Output
0
1
2
Input
5
7 1
9 7
13 13
11 8
12 9
16 7 8 6 9 11
7
6 11
7 10
9 3
12 9
18 16
8 9
10 15
Output
4
3
3
1
-1
3
2
Input
9
89 67
37 14
6 1
42 25
61 22
23 1
63 60
93 62
14 2
67 96 26 17 1 62 56 92 13 38
11
93 97
17 93
61 57
88 62
98 29
49 1
5 1
1 77
34 1
63 27
22 66
Output
7
9
8
7
7
9
9
10
9
7
9
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define mp make_pair
#define pii pair<int,int>
const int N=200005;
pii f[N],A[N];
int flag[N],l,n,a[N],b[N],c[N],tot,x,y,Ans[N],Q;
struct Tree{
int l,r,num,flag;
}T[N*4];
int cmp(pii x,pii y){
return x.se>y.se;
}
void build(int x,int l,int r){
T[x].l=l;T[x].r=r;
if (l==r)return;
int mid=(l+r)/2;
build(x*2,l,mid);
build(x*2+1,mid+1,r);
}
void down(int x){
T[x*2].num+=T[x].flag;
T[x*2+1].num+=T[x].flag;
T[x*2].flag+=T[x].flag;
T[x*2+1].flag+=T[x].flag;
T[x].flag=0;
}
void insert(int x,int l,int r,int z){
if (T[x].l>r||l>T[x].r)return;
if (T[x].l>=l&&T[x].r<=r){
T[x].num+=z;
T[x].flag+=z;
return;
}
down(x);
insert(x*2,l,r,z);
insert(x*2+1,l,r,z);
}
int find(int x,int y){
if (T[x].l==T[x].r)return T[x].num;
down(x);
int mid=(T[x].l+T[x].r)/2;
if (y<=mid)return find(x*2,y);
return find(x*2+1,y);
}
int ef(int x){
if (x<=c[0])return 0;
int l=0,r=n;
while (l<r){
int mid=(l+r+1)/2;
if (c[mid]<x)l=mid;
else r=mid-1;
}
return l+1;
}
void up(int x){
if (x==1)return;
if (f[x]<f[x/2]){
swap(f[x],f[x/2]);
up(x/2);
}
}
void down2(int x){
int i=x;
if (x*2<=l&&f[x*2]<f[x])i=x*2;
if (x*2<l&&f[x*2+1]<f[i])i=x*2+1;
if (i!=x){
swap(f[x],f[i]);
down2(i);
}
}
int main(){
scanf("%d",&n);
for (int i=1;i<=n;i++)scanf("%d%d",&a[i],&b[i]);
for (int i=0;i<=n;i++)scanf("%d",&c[i]);
sort(c,c+n+1);
for (int i=1;i<=n;i++)a[i]=ef(a[i]),b[i]=ef(b[i]);
build(1,0,n);
for (int i=0;i<=n;i++)insert(1,i,n,-1);
for (int i=1;i<=n;i++)insert(1,a[i],n,1);
for (int i=1;i<=n;i++)
if (b[i]<a[i])A[++tot]=mp(b[i],a[i]-1);
sort(A+1,A+tot+1,cmp);
int Flag=1,ans=n;
for (int i=n,j=1;i>=0;i--){
while (j<=tot&&A[j].se>=i){
f[++l]=mp(A[j].fi,j);
up(l);
j++;
}
while (find(1,i)<-1){
if (!l){
Flag=0;
break;
}
insert(1,A[f[1].se].fi,A[f[1].se].se,1);
flag[f[1].se]=1;
f[1]=f[l--];down2(1);ans--;
}
}
int num=0;
for (int i=1;i<=tot;i++)
if (!flag[i])A[++num]=A[i];
sort(A+1,A+num+1);
int Max=-1;
if (Flag)Ans[0]=ans;
else Ans[0]=-1e9;
for (int i=0,j=1;i<=n;i++){
while (j<=num&&A[j].fi<=i)Max=max(A[j].se,Max),j++;
if (find(1,i)==-1){
if (Max<i)Flag=0;
else {
ans--;
insert(1,i,Max,1);
Max=-1;
}
}
if (Flag)Ans[i+1]=ans;
else Ans[i+1]=-1e9;
}
scanf("%d",&Q);
while (Q--){
scanf("%d%d",&x,&y);
int ans=-1;
x=ef(x);y=ef(y);
ans=max(ans,Ans[x]+1);
ans=max(ans,Ans[y]);
printf("%d\n",ans);
}
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
You are given n strings s_1, s_2, β¦, s_n consisting of lowercase Latin letters.
In one operation you can remove a character from a string s_i and insert it to an arbitrary position in a string s_j (j may be equal to i). You may perform this operation any number of times. Is it possible to make all n strings equal?
Input
The first line contains t (1 β€ t β€ 10): the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 1000): the number of strings.
n lines follow, the i-th line contains s_i (1 β€ \lvert s_i \rvert β€ 1000).
The sum of lengths of all strings in all test cases does not exceed 1000.
Output
If it is possible to make the strings equal, print "YES" (without quotes).
Otherwise, print "NO" (without quotes).
You can output each character in either lowercase or uppercase.
Example
Input
4
2
caa
cbb
3
cba
cba
cbb
4
ccab
cbac
bca
acbcc
4
acb
caf
c
cbafc
Output
YES
NO
YES
NO
Note
In the first test case, you can do the following:
* Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively.
* Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab".
In the second test case, it is impossible to make all n strings equal.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int T;
T = 1;
cin >> T;
while (T--) {
int n, i, j, k = 0;
cin >> n;
int a[26];
memset(a, 0, sizeof(a));
for (int(i) = int(0); i < n; i++) {
string s;
cin >> s;
for (int(i) = int(0); i < s.length(); i++) {
a[s[i] - 'a']++;
}
}
for (int(i) = int(0); i < 26; i++) {
if (a[i] % n != 0) {
k = 1;
break;
}
}
if (k)
cout << "NO\n";
else {
cout << "YES\n";
}
}
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Squirrel Liss loves nuts. Liss asks you to plant some nut trees.
There are n positions (numbered 1 to n from west to east) to plant a tree along a street. Trees grow one meter per month. At the beginning of each month you should process one query. The query is one of the following types:
1. Plant a tree of height h at position p.
2. Cut down the x-th existent (not cut) tree from the west (where x is 1-indexed). When we cut the tree it drops down and takes all the available place at the position where it has stood. So no tree can be planted at this position anymore.
After processing each query, you should print the length of the longest increasing subsequence. A subset of existent trees is called an increasing subsequence if the height of the trees in the set is strictly increasing from west to east (for example, the westmost tree in the set must be the shortest in the set). The length of the increasing subsequence is the number of trees in it.
Note that Liss don't like the trees with the same heights, so it is guaranteed that at any time no two trees have the exactly same heights.
Input
The first line contains two integers: n and m (1 β€ n β€ 105; 1 β€ m β€ 2Β·105) β the number of positions and the number of queries.
Next m lines contains the information of queries by following formats:
* If the i-th query is type 1, the i-th line contains three integers: 1, pi, and hi (1 β€ pi β€ n, 1 β€ hi β€ 10), where pi is the position of the new tree and hi is the initial height of the new tree.
* If the i-th query is type 2, the i-th line contains two integers: 2 and xi (1 β€ xi β€ 10), where the xi is the index of the tree we want to cut.
The input is guaranteed to be correct, i.e.,
* For type 1 queries, pi will be pairwise distinct.
* For type 2 queries, xi will be less than or equal to the current number of trees.
* At any time no two trees have the exactly same heights.
In each line integers are separated by single spaces.
Output
Print m integers β the length of the longest increasing subsequence after each query. Separate the numbers by whitespaces.
Examples
Input
4 6
1 1 1
1 4 4
1 3 4
2 2
1 2 8
2 3
Output
1
2
3
2
2
2
Note
States of street after each query you can see on the following animation:
<image>
If your browser doesn't support animation png, please see the gif version here: http://212.193.37.254/codeforces/images/162/roadtree.gif
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 100010, M = 200020, D = 13;
class segment_tree {
struct node {
int l, r, maxv;
} t[M << 2];
int n;
void make_tree(int l, int r, int k) {
if (l != r) {
int mid = (l + r) >> 1;
make_tree(l, mid, k << 1);
make_tree(mid + 1, r, (k << 1) | 1);
}
t[k].l = l;
t[k].r = r;
t[k].maxv = 0;
}
void change(int pos, int c, int k) {
if (t[k].l == t[k].r) {
t[k].maxv = c;
return;
}
if (t[k << 1].r >= pos)
change(pos, c, k << 1);
else
change(pos, c, (k << 1) | 1);
t[k].maxv = max(t[k << 1].maxv, t[(k << 1) | 1].maxv);
}
int query(int l, int r, int k) {
if (t[k].l >= l && t[k].r <= r) return t[k].maxv;
int v = 0;
if (t[k << 1].r >= l) v = max(v, query(l, r, k << 1));
if (t[(k << 1) | 1].l <= r) v = max(v, query(l, r, (k << 1) | 1));
return v;
}
public:
void init(int size) { make_tree(1, n = size, 1); }
void change(int pos, int c) { change(pos, c, 1); }
int query(int l, int r) { return query(l, r, 1); }
} Tx, Ty;
map<int, int> s1, s2;
int n, m;
int main() {
scanf("%d%d", &n, &m);
Tx.init(m + D);
Ty.init(n);
for (int i = 1, type, p, h, x; i <= m; ++i) {
scanf("%d", &type);
if (type == 1) {
scanf("%d%d", &p, &h);
h += m - i;
s1[p] = h, s2[h] = p;
auto t = s2.find(h);
for (auto it = s2.begin(); it != t; ++it)
Tx.change(it->first, 0), Ty.change(it->second, 0);
Tx.change(t->first, 0), Ty.change(t->second, 0);
for (auto it = t; it != s2.begin(); --it) {
int tmp = Ty.query(it->second, n) + 1;
Ty.change(it->second, tmp);
Tx.change(it->first, tmp);
}
int tmp = Ty.query(s2.begin()->second, n) + 1;
Ty.change(s2.begin()->second, tmp);
Tx.change(s2.begin()->first, tmp);
}
if (type == 2) {
scanf("%d", &x);
auto t = s1.begin();
for (int i = 1; i < x; ++i) ++t;
for (auto it = s1.begin(); it != t; ++it)
Tx.change(it->second, 0), Ty.change(it->first, 0);
Tx.change(t->second, 0), Ty.change(t->first, 0);
auto del = *t;
s1.erase(del.first);
s2.erase(del.second);
t = s1.begin();
for (int i = 2; i < x; ++i) ++t;
if (x > 1) {
for (auto it = t; it != s1.begin(); --it) {
int tmp = Tx.query(it->second, m + D) + 1;
Tx.change(it->second, tmp);
Ty.change(it->first, tmp);
}
int tmp = Tx.query(s1.begin()->second, m + D) + 1;
Tx.change(s1.begin()->second, tmp);
Ty.change(s1.begin()->first, tmp);
}
}
printf("%d\n", Ty.query(1, n));
}
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string s, consisting of characters "x" and "y", and uses two following operations at runtime:
1. Find two consecutive characters in the string, such that the first of them equals "y", and the second one equals "x" and swap them. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string.
2. Find in the string two consecutive characters, such that the first of them equals "x" and the second one equals "y". Remove these characters from the string. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string.
The input for the new algorithm is string s, and the algorithm works as follows:
1. If you can apply at least one of the described operations to the string, go to step 2 of the algorithm. Otherwise, stop executing the algorithm and print the current string.
2. If you can apply operation 1, then apply it. Otherwise, apply operation 2. After you apply the operation, go to step 1 of the algorithm.
Now Vitaly wonders, what is going to be printed as the result of the algorithm's work, if the input receives string s.
Input
The first line contains a non-empty string s.
It is guaranteed that the string only consists of characters "x" and "y". It is guaranteed that the string consists of at most 106 characters. It is guaranteed that as the result of the algorithm's execution won't be an empty string.
Output
In the only line print the string that is printed as the result of the algorithm's work, if the input of the algorithm input receives string s.
Examples
Input
x
Output
x
Input
yxyxy
Output
y
Input
xxxxxy
Output
xxxx
Note
In the first test the algorithm will end after the first step of the algorithm, as it is impossible to apply any operation. Thus, the string won't change.
In the second test the transformation will be like this:
1. string "yxyxy" transforms into string "xyyxy";
2. string "xyyxy" transforms into string "xyxyy";
3. string "xyxyy" transforms into string "xxyyy";
4. string "xxyyy" transforms into string "xyy";
5. string "xyy" transforms into string "y".
As a result, we've got string "y".
In the third test case only one transformation will take place: string "xxxxxy" transforms into string "xxxx". Thus, the answer will be string "xxxx".
### Response
```cpp
#include <bits/stdc++.h>
int main() {
int i, x = 0, y = 0, l;
char s[1000005];
scanf("%s", s);
l = strlen(s);
for (i = 0; i < l; i++) {
if (s[i] == 'x')
x++;
else
y++;
}
if (x > y)
for (i = 1; i <= x - y; i++) printf("x");
else
for (i = 1; i <= y - x; i++) printf("y");
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
A tree of size n is an undirected connected graph consisting of n vertices without cycles.
Consider some tree with n vertices. We call a tree invariant relative to permutation p = p1p2... pn, if for any two vertices of the tree u and v the condition holds: "vertices u and v are connected by an edge if and only if vertices pu and pv are connected by an edge".
You are given permutation p of size n. Find some tree size n, invariant relative to the given permutation.
Input
The first line contains number n (1 β€ n β€ 105) β the size of the permutation (also equal to the size of the sought tree).
The second line contains permutation pi (1 β€ pi β€ n).
Output
If the sought tree does not exist, print "NO" (without the quotes).
Otherwise, print "YES", and then print n - 1 lines, each of which contains two integers β the numbers of vertices connected by an edge of the tree you found. The vertices are numbered from 1, the order of the edges and the order of the vertices within the edges does not matter.
If there are multiple solutions, output any of them.
Examples
Input
4
4 3 2 1
Output
YES
4 1
4 2
1 3
Input
3
3 1 2
Output
NO
Note
In the first sample test a permutation transforms edge (4, 1) into edge (1, 4), edge (4, 2) into edge (1, 3) and edge (1, 3) into edge (4, 2). These edges all appear in the resulting tree.
It can be shown that in the second sample test no tree satisfies the given condition.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 7;
int n, p[MAXN], d[MAXN] = {};
vector<int> comp[MAXN];
int main() {
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n;
for (int i = 1; i <= n; ++i) cin >> p[i];
int piv = 0;
for (int i = 1; i <= n; ++i) {
if (d[i]) continue;
int u = i;
comp[++piv].push_back(u);
while (1) {
if (p[u] == i) break;
u = p[u], d[u] = 1;
comp[piv].push_back(u);
}
}
int p1 = 0, p2 = 0;
for (int i = 1; i <= piv; ++i) {
int sz = (int)comp[i].size();
if (sz == 1) p1 = i;
if (sz == 2) p2 = i;
}
if (p1 == 0 && p2 == 0) return cout << "NO", 0;
if (p1) {
cout << "YES\n";
for (int i = 1; i <= n; ++i)
if (i != comp[p1].back()) cout << i << ' ' << comp[p1].back() << '\n';
return 0;
}
for (int i = 1; i <= piv; ++i)
if ((int)comp[i].size() & 1) return cout << "NO", 0;
cout << "YES\n";
for (int i = 1; i <= piv; ++i)
if (i != p2) {
int cur = 0;
for (auto u : comp[i]) {
cout << u << ' ' << comp[p2][cur] << '\n';
cur ^= 1;
}
}
cout << comp[p2][0] << ' ' << comp[p2][1];
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers.
Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of n cities with m bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads.
The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning.
The gang is going to rob a bank! The bank is located in city 1. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city n. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan.
First of all the path which they are going to use on their way back from city 1 to their headquarters n must be as short as possible, since it is important to finish operation as fast as possible.
Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional.
If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation.
Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired).
Can you help Walter complete his task and gain the gang's trust?
Input
The first line of input contains two integers n, m (2 β€ n β€ 105, <image>), the number of cities and number of roads respectively.
In following m lines there are descriptions of roads. Each description consists of three integers x, y, z (1 β€ x, y β€ n, <image>) meaning that there is a road connecting cities number x and y. If z = 1, this road is working, otherwise it is not.
Output
In the first line output one integer k, the minimum possible number of roads affected by gang.
In the following k lines output three integers describing roads that should be affected. Each line should contain three integers x, y, z (1 β€ x, y β€ n, <image>), cities connected by a road and the new state of a road. z = 1 indicates that the road between cities x and y should be repaired and z = 0 means that road should be blown up.
You may output roads in any order. Each affected road should appear exactly once. You may output cities connected by a single road in any order. If you output a road, it's original state should be different from z.
After performing all operations accroding to your plan, there should remain working only roads lying on some certain shortest past between city 1 and n.
If there are multiple optimal answers output any.
Examples
Input
2 1
1 2 0
Output
1
1 2 1
Input
4 4
1 2 1
1 3 0
2 3 1
3 4 1
Output
3
1 2 0
1 3 1
2 3 0
Input
8 9
1 2 0
8 3 0
2 3 1
1 4 1
8 7 0
1 5 1
4 6 1
5 7 0
6 8 0
Output
3
2 3 0
1 5 0
6 8 1
Note
In the first test the only path is 1 - 2
In the second test the only shortest path is 1 - 3 - 4
In the third test there are multiple shortest paths but the optimal is 1 - 4 - 6 - 8
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void _print() { cout << '\n'; }
template <typename T, typename... Ts>
void _print(const T& value, const Ts&... values) {
cout << ' ' << value;
_print(values...);
}
template <typename T, typename... Ts>
void print(const T& value, const Ts&... values) {
cout << value;
_print(values...);
}
const long long N = 1e5 + 5;
struct State {
long long u, dis, use;
bool operator<(const State& that) const {
if (dis != that.dis) return dis > that.dis;
return use < that.use;
}
};
long long n, m;
pair<long long, long long> dis[N];
pair<long long, long long> trace[N];
vector<pair<long long, long long> > a[N];
long long usable = 0;
void dijkstra() {
memset(dis, 127, sizeof(dis));
dis[1] = {0, 0};
priority_queue<State> pq;
dis[1] = {0, 0};
pq.push({1, dis[1].first, dis[1].second});
while (!pq.empty()) {
auto [u, d1, d2] = pq.top();
pq.pop();
if (make_pair(d1, d2) != dis[u]) continue;
for (auto [v, s] : a[u]) {
if (dis[v].first > dis[u].first + 1 ||
(dis[v].first == dis[u].first + 1 &&
dis[v].second < dis[u].second + s)) {
dis[v].first = dis[u].first + 1;
dis[v].second = dis[u].second + s;
pq.push({v, dis[v].first, dis[v].second});
trace[v] = {u, s};
}
}
}
}
map<pair<long long, long long>, long long> bef, aft;
void doTrace() {
long long u = n;
while (u != 1) {
long long v = trace[u].first;
aft[minmax(u, v)] = 1;
u = v;
}
cout << usable - (2 * dis[n].second - dis[n].first) << '\n';
for (auto it : bef) {
if (aft.find(it.first) != aft.end()) {
if (it.second == 0)
cout << it.first.first << ' ' << it.first.second << ' ' << 1 << '\n';
} else {
if (it.second == 1)
cout << it.first.first << ' ' << it.first.second << ' ' << 0 << '\n';
}
}
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m;
for (long long i = (1); i <= (m); i++) {
long long u, v, s;
cin >> u >> v >> s;
a[u].push_back({v, s});
a[v].push_back({u, s});
bef[minmax(u, v)] = s;
usable += s;
}
dijkstra();
doTrace();
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Let's look at the following process: initially you have an empty stack and an array s of the length l. You are trying to push array elements to the stack in the order s_1, s_2, s_3, ... s_{l}. Moreover, if the stack is empty or the element at the top of this stack is not equal to the current element, then you just push the current element to the top of the stack. Otherwise, you don't push the current element to the stack and, moreover, pop the top element of the stack.
If after this process the stack remains empty, the array s is considered stack exterminable.
There are samples of stack exterminable arrays:
* [1, 1];
* [2, 1, 1, 2];
* [1, 1, 2, 2];
* [1, 3, 3, 1, 2, 2];
* [3, 1, 3, 3, 1, 3];
* [3, 3, 3, 3, 3, 3];
* [5, 1, 2, 2, 1, 4, 4, 5];
Let's consider the changing of stack more details if s = [5, 1, 2, 2, 1, 4, 4, 5] (the top of stack is highlighted).
1. after pushing s_1 = 5 the stack turn into [5];
2. after pushing s_2 = 1 the stack turn into [5, 1];
3. after pushing s_3 = 2 the stack turn into [5, 1, 2];
4. after pushing s_4 = 2 the stack turn into [5, 1];
5. after pushing s_5 = 1 the stack turn into [5];
6. after pushing s_6 = 4 the stack turn into [5, 4];
7. after pushing s_7 = 4 the stack turn into [5];
8. after pushing s_8 = 5 the stack is empty.
You are given an array a_1, a_2, β¦, a_n. You have to calculate the number of its subarrays which are stack exterminable.
Note, that you have to answer q independent queries.
Input
The first line contains one integer q (1 β€ q β€ 3 β
10^5) β the number of queries.
The first line of each query contains one integer n (1 β€ n β€ 3 β
10^5) β the length of array a.
The second line of each query contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n) β the elements.
It is guaranteed that the sum of all n over all queries does not exceed 3 β
10^5.
Output
For each test case print one integer in single line β the number of stack exterminable subarrays of the array a.
Example
Input
3
5
2 1 1 2 2
6
1 2 1 1 3 2
9
3 1 2 2 1 6 6 3 3
Output
4
1
8
Note
In the first query there are four stack exterminable subarrays: a_{1 β¦ 4} = [2, 1, 1, 2], a_{2 β¦ 3} = [1, 1], a_{2 β¦ 5} = [1, 1, 2, 2], a_{4 β¦ 5} = [2, 2].
In the second query, only one subarray is exterminable subarray β a_{3 β¦ 4}.
In the third query, there are eight stack exterminable subarrays: a_{1 β¦ 8}, a_{2 β¦ 5}, a_{2 β¦ 7}, a_{2 β¦ 9}, a_{3 β¦ 4}, a_{6 β¦ 7}, a_{6 β¦ 9}, a_{8 β¦ 9}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int gcd(long long int a, long long int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
long long int cg(long long int n) { return n ^ (n >> 1); }
long long int SUM(long long int a) { return (a * (a + 1) / 2); }
bool CAN(int x, int y, int n, int m) {
if (x >= 0 && y >= 0 && x < n && y < m) {
return true;
}
return false;
}
double her(double x1, double arayikhalatyan, double x2, double y2) {
return sqrt((x1 - x2) * (x1 - x2) +
(arayikhalatyan - y2) * (arayikhalatyan - y2));
}
string strsum(string a, string b) {
int p = 0;
string c;
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
if (b.length() < a.length()) {
for (int i = b.length(); i < a.length(); i++) {
b += "0";
}
} else {
for (int i = a.length(); i < b.length(); i++) {
a += "0";
}
}
a += "0", b += "0";
for (int i = 0; i < a.length(); i++) {
c += (a[i] - '0' + b[i] - '0' + p) % 10 + '0';
p = (a[i] + b[i] - '0' - '0' + p) / 10;
}
if (c[c.length() - 1] == '0') c.erase(c.length() - 1, 1);
reverse(c.begin(), c.end());
return c;
}
string strmin(string a, string b) {
if (a.length() > b.length()) return b;
if (b.length() > a.length()) return a;
for (int i = 0; i < a.length(); i++) {
if (a[i] > b[i]) return b;
if (b[i] > a[i]) return a;
}
return a;
}
char vow[] = {'a', 'e', 'i', 'o', 'u'};
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
const int N = 3e5 + 30;
const long long int mod = 1e9 + 7;
int q, n, a[N], par[N];
long long int fp[N], pat;
map<int, int> sm[N];
struct el {
int val, par;
};
int l = 1;
el t[5 * N];
map<int, long long int> g[5 * N];
void rec(int l1, int r) {
int mid = (l1 + r) / 2;
stack<int> sm;
sm.push(0);
t[l].val = 0;
int ll = l;
int nw = l++;
g[l].clear();
for (int i = mid; i >= l1; i--) {
if (sm.top() == a[i]) {
nw = t[nw].par;
t[nw].val++;
sm.pop();
} else {
sm.push(a[i]);
if (g[nw][a[i]]) {
nw = g[nw][a[i]];
t[nw].val++;
} else {
t[l].val = 1;
t[l].par = nw;
g[nw][a[i]] = l;
nw = l++;
g[l].clear();
}
}
}
while (!sm.empty()) sm.pop();
nw = ll;
sm.push(0);
for (int i = mid + 1; i <= r; i++) {
if (sm.top() == a[i]) {
nw = t[nw].par;
pat += t[nw].val;
sm.pop();
} else {
sm.push(a[i]);
if (g[nw][a[i]]) {
nw = g[nw][a[i]];
pat += t[nw].val;
} else {
i++;
int i1 = sm.size() - 1;
while (i <= r && sm.size() != i1) {
if (sm.top() == a[i])
sm.pop();
else
sm.push(a[i]);
i++;
}
i--;
if (sm.size() == i1) pat += t[nw].val;
}
}
}
if (l1 < mid) rec(l1, mid);
if (mid + 1 < r) rec(mid + 1, r);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
;
cin >> q;
while (q--) {
pat = 0, fp[0] = 0;
int nw = 0;
stack<int> ss;
sm[0].clear();
cin >> n;
int l = 1;
fp[nw]++;
for (int i = 0; i < n; i++) {
cin >> a[i];
if (!ss.empty() && ss.top() == a[i]) {
ss.pop();
nw = par[nw];
} else {
if (sm[nw][a[i]])
nw = sm[nw][a[i]];
else {
sm[nw][a[i]] = l;
sm[l].clear();
par[l] = nw;
fp[l] = 0;
nw = l++;
}
ss.push(a[i]);
}
pat += fp[nw];
fp[nw]++;
}
cout << pat << endl;
}
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes.
As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters.
Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2Β·d, ..., nΒ·d meters.
Input
The first line contains two space-separated real numbers a and d (1 β€ a, d β€ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink.
The second line contains integer n (1 β€ n β€ 105) showing that Valera needs an extra drink n times.
Output
Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers iΒ·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4.
Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem.
Examples
Input
2 5
2
Output
1.0000000000 2.0000000000
2.0000000000 0.0000000000
Input
4.147 2.8819
6
Output
2.8819000000 0.0000000000
4.1470000000 1.6168000000
3.7953000000 4.1470000000
0.9134000000 4.1470000000
0.0000000000 2.1785000000
0.7034000000 0.0000000000
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, i, c, x1, o;
double a, d, x = 0, l, a1;
cin >> a >> d;
cin >> n;
cout << fixed << setprecision(4);
a1 = a * 4;
for (i = 0; i < n; i++) {
x += d;
x1 = int(x / a);
if (x1 % 4 == 0) cout << x - a * x1 << " " << 0.0000 << "\n";
if (x1 % 4 == 1) cout << a << " " << x - a * x1 << "\n";
if (x1 % 4 == 2) cout << a - (x - a * x1) << " " << a << "\n";
if (x1 % 4 == 3) cout << 0.0000 << " " << a - (x - a * x1) << "\n";
o = int(x / a1);
x = x - o * a1;
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
[3R2 as DJ Mashiro - Happiness Breeze](https://open.spotify.com/track/2qGqK8GRS65Wlf20qUBEak)
[Ice - DJ Mashiro is dead or alive](https://soundcloud.com/iceloki/dj-mashiro-is-dead-or-alive)
NEKO#Ξ¦ΟΞ¦ has just got a new maze game on her PC!
The game's main puzzle is a maze, in the forms of a 2 Γ n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1, 1) to the gate at (2, n) and escape the maze. The girl can only move between cells sharing a common side.
However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.
After hours of streaming, NEKO finally figured out there are only q such moments: the i-th moment toggles the state of cell (r_i, c_i) (either from ground to lava or vice versa).
Knowing this, NEKO wonders, after each of the q moments, whether it is still possible to move from cell (1, 1) to cell (2, n) without going through any lava cells.
Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?
Input
The first line contains integers n, q (2 β€ n β€ 10^5, 1 β€ q β€ 10^5).
The i-th of q following lines contains two integers r_i, c_i (1 β€ r_i β€ 2, 1 β€ c_i β€ n), denoting the coordinates of the cell to be flipped at the i-th moment.
It is guaranteed that cells (1, 1) and (2, n) never appear in the query list.
Output
For each moment, if it is possible to travel from cell (1, 1) to cell (2, n), print "Yes", otherwise print "No". There should be exactly q answers, one after every update.
You can print the words in any case (either lowercase, uppercase or mixed).
Example
Input
5 5
2 3
1 4
2 4
2 3
1 4
Output
Yes
No
No
No
Yes
Note
We'll crack down the example test here:
* After the first query, the girl still able to reach the goal. One of the shortest path ways should be: (1,1) β (1,2) β (1,3) β (1,4) β (1,5) β (2,5).
* After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1, 3).
* After the fourth query, the (2, 3) is not blocked, but now all the 4-th column is blocked, so she still can't reach the goal.
* After the fifth query, the column barrier has been lifted, thus she can go to the final goal again.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int LEN = 100000;
struct fastio {
int it, len;
char s[LEN + 5];
fastio() { it = len = 0; }
char get() {
if (it < len) return s[it++];
it = 0, len = fread(s, 1, LEN, stdin);
return len ? s[it++] : EOF;
}
bool notend() {
char c;
for (c = get(); c == ' ' || c == '\n'; c = get())
;
if (it) it--;
return c != EOF;
}
void put(char c) {
if (it == LEN) fwrite(s, 1, LEN, stdout), it = 0;
s[it++] = c;
}
void flush() { fwrite(s, 1, it, stdout); }
} buff, bufo;
inline int getint() {
char c;
int res = 0, sig = 1;
for (c = buff.get(); c < '0' || c > '9'; c = buff.get())
if (c == '-') sig = -1;
for (; c >= '0' && c <= '9'; c = buff.get()) res = res * 10 + (c - '0');
return sig * res;
}
inline long long getll() {
char c;
long long res = 0, sig = 1;
for (c = buff.get(); c < '0' || c > '9'; c = buff.get())
if (c == '-') sig = -1;
for (; c >= '0' && c <= '9'; c = buff.get()) res = res * 10 + (c - '0');
return sig * res;
}
inline void putint(int x, char suf) {
if (!x)
bufo.put('0');
else {
if (x < 0) bufo.put('-'), x = -x;
int k = 0;
char s[15];
while (x) {
s[++k] = x % 10 + '0';
x /= 10;
}
for (; k; k--) bufo.put(s[k]);
}
bufo.put(suf);
}
inline void putll(long long x, char suf) {
if (!x)
bufo.put('0');
else {
if (x < 0) bufo.put('-'), x = -x;
int k = 0;
char s[25];
while (x) {
s[++k] = x % 10 + '0';
x /= 10;
}
for (; k; k--) bufo.put(s[k]);
}
bufo.put(suf);
}
inline char get_char() {
char c;
for (c = buff.get(); c == ' ' || c == '\n'; c = buff.get())
;
return c;
}
int n, q, cnt;
bool lava[2][100005];
int main() {
n = getint(), q = getint();
for (int i = 1; i <= q; i++) {
int r = getint() - 1, c = getint();
if (lava[r][c]) {
for (int j = c - 1; j <= c + 1; j++) cnt -= lava[r ^ 1][j];
} else {
for (int j = c - 1; j <= c + 1; j++) cnt += lava[r ^ 1][j];
}
lava[r][c] ^= 1;
puts(cnt ? "No" : "Yes");
}
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Taro and Hanako are playing card games. They have n cards each, and they compete n turns. At each turn Taro and Hanako respectively puts out a card. The name of the animal consisting of alphabetical letters is written on each card, and the bigger one in lexicographical order becomes the winner of that turn. The winner obtains 3 points. In the case of a draw, they obtain 1 point each.
Write a program which reads a sequence of cards Taro and Hanako have and reports the final scores of the game.
Constraints
* n β€ 1000
* The length of the string β€ 100
Input
In the first line, the number of cards n is given. In the following n lines, the cards for n turns are given respectively. For each line, the first string represents the Taro's card and the second one represents Hanako's card.
Output
Print the final scores of Taro and Hanako respectively. Put a single space character between them.
Example
Input
3
cat dog
fish fish
lion tiger
Output
1 7
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int pts[2] = {};
for( int i = 0; i < n; ++i ) {
string c1, c2;
cin >> c1 >> c2;
if( c1 == c2 ) {
pts[0] += 1;
pts[1] += 1;
}
else {
pts[c1 < c2] += 3;
}
}
cout << pts[0] << ' ' << pts[1] << endl;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave ViΔkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town ViΔkopolis. He almost even fell into a depression from boredom!
Leha came up with a task for himself to relax a little. He chooses two integers A and B and then calculates the greatest common divisor of integers "A factorial" and "B factorial". Formally the hacker wants to find out GCD(A!, B!). It's well known that the factorial of an integer x is a product of all positive integers less than or equal to x. Thus x! = 1Β·2Β·3Β·...Β·(x - 1)Β·x. For example 4! = 1Β·2Β·3Β·4 = 24. Recall that GCD(x, y) is the largest positive integer q that divides (without a remainder) both x and y.
Leha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you?
Input
The first and single line contains two integers A and B (1 β€ A, B β€ 109, min(A, B) β€ 12).
Output
Print a single integer denoting the greatest common divisor of integers A! and B!.
Example
Input
4 3
Output
6
Note
Consider the sample.
4! = 1Β·2Β·3Β·4 = 24. 3! = 1Β·2Β·3 = 6. The greatest common divisor of integers 24 and 6 is exactly 6.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
int mini = min(a, b);
long long re = 1;
for (int i = mini; i >= 1; i--) re *= i;
cout << re;
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Given a string consisting of only numbers from 0 to 9, consider the operation of creating a new string from that string according to the following rules. Read the given string one character at a time from the left end. Go, if the same number a continues r, write the number r and the number a in this order without separating them with a space. Read to the right end of the given character string, and what is on the way to the end of the last writing Even if there are times of writing, all of them are counted as one operation. For the second and subsequent operations, the same operation is performed with the character string written out by the previous operation as the given character string. For example, "122244" If the character string "" is given, the character string obtained by one operation is "113224" and "44444444444" (11) because one 1, three 2, two 4s are given in order from the left end. In the case of 4), the obtained character string is β114β.
Create a program that outputs a string obtained by performing the above operation n times on a given string of 100 characters or less, where n β€ 20.
The input data consists of two lines, the first line contains the number of operations n, and the second line contains the first character string.
Input example
---
Five
11
Output example
13112221
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the character string that has been operated the specified number of times is output on one line.
Example
Input
5
11
5
11
0
Output
13112221
13112221
### Response
```cpp
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int n;
string s;
while (cin >> n){
if (n == 0){
break;
}
cin >> s;
for (int i = 0; i < n; i++){
ostringstream oss;
int j = 0;
while (j < s.length()){
int r = 0;
char c = s[j];
while (s[j] == c){
r++;
j++;
}
oss << r << c;
}
s = oss.str();
}
cout << s << endl;
}
return (0);
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.
Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?
The cost of sending the message is the sum of the costs of sending every word in it.
Input
The first line of input contains integers n, k and m (1 β€ k β€ n β€ 105, 1 β€ m β€ 105) β the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively.
The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct.
The third line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) where ai is the cost of sending the i-th word.
The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 β€ x β€ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group.
The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.
Output
The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.
Examples
Input
5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
107
Input
5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
116
Note
In the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.
In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int MOD(long long int a, long long int b) {
if (a > b)
return a - b;
else
return b - a;
}
long long int max3(long long int a, long long int b, long long int c) {
return max(c, max(a, b));
}
long long int power(long long int x, long long int y) {
long long int res = 1;
x = x;
while (y > 0) {
if (y & 1) res = (res * x);
y = y >> 1;
x = (x * x);
}
return res;
}
long long int logg(long long int a) {
long long int x = 0;
while (a > 1) {
x++;
a /= 2;
}
return x;
}
int main() {
int n, k, m;
cin >> n >> k >> m;
map<string, int> g;
vector<string> h;
for (int i = 0; i < n; i++) {
string str;
cin >> str;
h.push_back(str);
g.insert(pair<string, int>(str, 0));
}
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
vector<pair<int, int>> b[k];
for (int i = 0; i < k; i++) {
int x;
cin >> x;
for (int j = 0; j < x; j++) {
int temp;
cin >> temp;
b[i].push_back(make_pair(a[temp - 1], temp - 1));
}
}
for (int i = 0; i < k; i++) {
sort(b[i].begin(), b[i].end());
}
for (int i = 0; i < k; i++) {
int val = b[i][0].first;
for (int j = 0; j < b[i].size(); j++) {
g[h[b[i][j].second]] = val;
}
}
long long int ans = 0;
for (int i = 0; i < m; i++) {
string t;
cin >> t;
ans = ans + g[t];
}
cout << ans;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.
You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
Input
The first line of the input contains two integers, x, y (1 β€ x, y β€ 1018, xy > 1) β the number of oranges and apples that were initially in the bag.
Output
Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.
If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.
Examples
Input
1 4
Output
3B
Input
2 2
Output
Impossible
Input
3 2
Output
1A1B
Note
In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.
In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.
In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long x, y;
vector<long long> ans;
long long gcd(long long a, long long b) {
if (b == 0) return a;
ans.push_back(a / b);
return gcd(b, a % b);
}
int main() {
ans.clear();
scanf("%lld%lld", &x, &y);
long long k = gcd(x, y);
if (k != 1)
printf("Impossible\n");
else {
int n = ans.size();
ans[n - 1]--;
int v = x < y;
for (int i = 0; i < n; i++) {
if (ans[i] == 0) continue;
printf("%lld%c", ans[i], 'A' + v);
v ^= 1;
}
printf("\n");
}
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Karen is getting ready for a new school day!
<image>
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?
Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.
Input
The first and only line of input contains a single string in the format hh:mm (00 β€ hh β€ 23, 00 β€ mm β€ 59).
Output
Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome.
Examples
Input
05:39
Output
11
Input
13:31
Output
0
Input
23:59
Output
1
Note
In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome.
In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome.
In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool isPalin(int hour, int minu) {
int b = hour % 10;
hour /= 10;
int a = hour % 10;
int d = minu % 10;
minu /= 10;
int c = minu % 10;
if (a == d && b == c) return true;
return false;
}
int main() {
char s[6];
scanf(" %s", s);
int hour = (s[0] - '0') * 10 + (s[1] - '0');
int minu = (s[3] - '0') * 10 + (s[4] - '0');
int cont = 0;
while (!isPalin(hour, minu)) {
if (minu < 59)
minu++;
else {
if (hour < 23)
hour++;
else
hour = 0;
minu = 0;
}
cont++;
}
printf("%d\n", cont);
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
In this task you need to process a set of stock exchange orders and use them to create order book.
An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price pi, direction di β buy or sell, and integer qi. This means that the participant is ready to buy or sell qi stocks at price pi for one stock. A value qi is also known as a volume of an order.
All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders.
An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.
An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book.
You are given n stock exhange orders. Your task is to print order book of depth s for these orders.
Input
The input starts with two positive integers n and s (1 β€ n β€ 1000, 1 β€ s β€ 50), the number of orders and the book depth.
Next n lines contains a letter di (either 'B' or 'S'), an integer pi (0 β€ pi β€ 105) and an integer qi (1 β€ qi β€ 104) β direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order.
Output
Print no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input.
Examples
Input
6 2
B 10 3
S 50 2
S 40 1
S 50 6
B 20 4
B 25 10
Output
S 50 8
S 40 1
B 25 10
B 20 4
Note
Denote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two sell orders (50, 8), (40, 1) in the sample.
You need to print no more than two best orders for each direction, so you shouldn't print the order (10 3) having the worst price among buy orders.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool sortinrev(const pair<int, int> &a, const pair<int, int> &b) {
return (a.first > b.first);
}
int main() {
int n, k, i;
cin >> n >> k;
map<int, int> buy;
map<int, int> sell;
map<int, int>::iterator itr;
char c;
int a, b;
while (n--) {
cin >> c >> a >> b;
if (c == 'B')
buy[a] += b;
else
sell[a] += b;
}
vector<pair<int, int> > vec;
for (itr = sell.begin(); itr != sell.end(); itr++)
vec.push_back(make_pair(itr->first, itr->second));
sort(vec.begin(), vec.end(), sortinrev);
int l = vec.size();
l = min(l, k);
for (i = 0; i < l; i++)
cout << "S " << vec[vec.size() - l + i].first << " "
<< vec[vec.size() - l + i].second << "\n";
vec.clear();
for (itr = buy.begin(); itr != buy.end(); itr++)
vec.push_back(make_pair(itr->first, itr->second));
sort(vec.begin(), vec.end(), sortinrev);
l = vec.size();
l = min(l, k);
for (i = 0; i < l; i++)
cout << "B " << vec[i].first << " " << vec[i].second << "\n";
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Tachibana Kanade likes Mapo Tofu very much. One day, the canteen cooked all kinds of tofu to sell, but not all tofu is Mapo Tofu, only those spicy enough can be called Mapo Tofu.
Each piece of tofu in the canteen is given a m-based number, all numbers are in the range [l, r] (l and r being m-based numbers), and for every m-based integer in the range [l, r], there exists a piece of tofu with that number.
To judge what tofu is Mapo Tofu, Tachibana Kanade chose n m-based number strings, and assigned a value to each string. If a string appears in the number of a tofu, the value of the string will be added to the value of that tofu. If a string appears multiple times, then the value is also added that many times. Initially the value of each tofu is zero.
Tachibana Kanade considers tofu with values no more than k to be Mapo Tofu. So now Tachibana Kanade wants to know, how many pieces of tofu are Mapo Tofu?
Input
The first line contains three integers n, m and k (1 β€ n β€ 200; 2 β€ m β€ 20; 1 β€ k β€ 500). Where n denotes the number of strings, m denotes the base used, and k denotes the limit of the value for Mapo Tofu.
The second line represents the number l. The first integer in the line is len (1 β€ len β€ 200), describing the length (number of digits in base m) of l. Then follow len integers a1, a2, ..., alen (0 β€ ai < m; a1 > 0) separated by spaces, representing the digits of l, with a1 being the highest digit and alen being the lowest digit.
The third line represents the number r in the same format as l. It is guaranteed that 1 β€ l β€ r.
Then follow n lines, each line describing a number string. The i-th line contains the i-th number string and vi β the value of the i-th string (1 β€ vi β€ 200). All number strings are described in almost the same format as l, the only difference is number strings may contain necessary leading zeros (see the first example). The sum of the lengths of all number strings does not exceed 200.
Output
Output the number of pieces of Mapo Tofu modulo 1000000007 (109 + 7). The answer should be a decimal integer.
Examples
Input
2 10 1
1 1
3 1 0 0
1 1 1
1 0 1
Output
97
Input
2 10 12
2 5 9
6 6 3 5 4 9 7
2 0 6 1
3 6 7 2 1
Output
635439
Input
4 2 6
6 1 0 1 1 1 0
6 1 1 0 1 0 0
1 1 2
3 0 1 0 5
4 0 1 1 0 4
3 1 0 1 2
Output
2
Note
In the first sample, 10, 11 and 100 are the only three decimal numbers in [1, 100] with a value greater than 1. Here the value of 1 is 1 but not 2, since numbers cannot contain leading zeros and thus cannot be written as "01".
In the second sample, no numbers in the given interval have a value greater than 12.
In the third sample, 110000 and 110001 are the only two binary numbers in the given interval with a value no greater than 6.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m, k;
int lsize, rsize;
int l[205], r[205];
int len[205], str[205][205], p[205];
int nex[205][25];
int gain[205];
long long dp[2][505][205][2][2];
string al = "abcdefghijklmnopqrstuvwxyz";
vector<string> pfx;
void pre() {
for (int i = 0; i < n; i++) {
string s;
for (int j = 0; j <= len[i]; j++) {
pfx.push_back(s);
if (j != len[i]) s.push_back(('a' + str[i][j]));
}
}
sort(pfx.begin(), pfx.end());
pfx.erase(unique(pfx.begin(), pfx.end()), pfx.end());
int kk = pfx.size();
for (int i = 0; i < kk; i++) {
for (int j = 0; j < n; j++) {
if (pfx[i].size() < len[j]) continue;
bool ok = true;
for (int a = 0; a < len[j]; a++) {
if (('a' + str[j][len[j] - 1 - a]) != pfx[i][pfx[i].size() - 1 - a]) {
ok = false;
break;
}
}
if (ok) gain[i] += p[j];
}
for (int j = 0; j < m; j++) {
string s = pfx[i];
s.push_back('a' + j);
int x;
while (1) {
x = lower_bound(pfx.begin(), pfx.end(), s) - pfx.begin();
if (x < kk && pfx[x] == s) break;
s = s.substr(1);
}
nex[i][j] = x;
}
}
}
long long calcl() {
memset(dp, 0, sizeof(dp));
int cur = 0, nxt = 1;
dp[0][0][0][1][0] = 1;
for (int i = 0; i < lsize; i++) {
memset(dp[nxt], 0, sizeof(dp[nxt]));
for (int j = 0; j <= k; j++) {
for (int a = 0; a < pfx.size(); a++) {
if (!dp[cur][j][a][0][1]) goto nxt;
for (int ch = 0; ch < m; ch++) {
int tugi = nex[a][ch];
if (j + gain[tugi] > k) continue;
dp[nxt][j + gain[tugi]][tugi][0][1] =
(dp[nxt][j + gain[tugi]][tugi][0][1] + dp[cur][j][a][0][1]) %
1000000007;
}
nxt:;
if (!dp[cur][j][a][1][1]) goto nxt2;
for (int ch = 0; ch <= l[i]; ch++) {
int tugi = nex[a][ch];
if (j + gain[tugi] > k) continue;
dp[nxt][j + gain[tugi]][tugi][ch == l[i] ? 1 : 0][1] =
(dp[nxt][j + gain[tugi]][tugi][ch == l[i] ? 1 : 0][1] +
dp[cur][j][a][1][1]) %
1000000007;
}
nxt2:;
if (!dp[cur][j][a][0][0]) goto nxt3;
for (int ch = 0; ch < m; ch++) {
int tugi = nex[a][ch];
if (ch && j + gain[tugi] <= k) {
dp[nxt][j + gain[tugi]][tugi][0][!!ch] =
(dp[nxt][j + gain[tugi]][tugi][0][!!ch] + dp[cur][j][a][0][0]) %
1000000007;
} else if (!ch) {
dp[nxt][0][0][0][0] =
(dp[nxt][0][0][0][0] + dp[cur][j][a][0][0]) % 1000000007;
}
}
nxt3:;
if (!dp[cur][j][a][1][0]) continue;
for (int ch = 0; ch <= l[i]; ch++) {
int tugi = nex[a][ch];
if (ch && j + gain[tugi] <= k) {
dp[nxt][j + gain[tugi]][tugi][ch == l[i] ? 1 : 0][!!ch] =
(dp[nxt][j + gain[tugi]][tugi][ch == l[i] ? 1 : 0][!!ch] +
dp[cur][j][a][1][0]) %
1000000007;
} else if (!ch) {
dp[nxt][0][0][ch == l[i] ? 1 : 0][0] =
(dp[nxt][0][0][ch == l[i] ? 1 : 0][0] + dp[cur][j][a][1][0]) %
1000000007;
}
}
}
}
swap(cur, nxt);
}
long long res = 0LL;
for (int j = 0; j <= k; j++)
for (int a = 0; a < pfx.size(); a++)
res = (res + dp[cur][j][a][0][1] + dp[cur][j][a][1][1]) % 1000000007;
return res;
}
long long calcr() {
memset(dp, 0, sizeof(dp));
int cur = 0, nxt = 1;
dp[0][0][0][1][0] = 1;
for (int i = 0; i < rsize; i++) {
memset(dp[nxt], 0, sizeof(dp[nxt]));
for (int j = 0; j <= k; j++) {
for (int a = 0; a < pfx.size(); a++) {
if (!dp[cur][j][a][0][1]) goto nxtt;
for (int ch = 0; ch < m; ch++) {
int tugi = nex[a][ch];
if (j + gain[tugi] > k) continue;
dp[nxt][j + gain[tugi]][tugi][0][1] =
(dp[nxt][j + gain[tugi]][tugi][0][1] + dp[cur][j][a][0][1]) %
1000000007;
}
nxtt:;
if (!dp[cur][j][a][1][1]) goto nxtt2;
for (int ch = 0; ch <= r[i]; ch++) {
int tugi = nex[a][ch];
if (j + gain[tugi] > k) continue;
dp[nxt][j + gain[tugi]][tugi][ch == r[i] ? 1 : 0][1] =
(dp[nxt][j + gain[tugi]][tugi][ch == r[i] ? 1 : 0][1] +
dp[cur][j][a][1][1]) %
1000000007;
}
nxtt2:;
if (!dp[cur][j][a][0][0]) goto nxtt3;
for (int ch = 0; ch < m; ch++) {
int tugi = nex[a][ch];
if (ch && j + gain[tugi] <= k) {
dp[nxt][j + gain[tugi]][tugi][0][!!ch] =
(dp[nxt][j + gain[tugi]][tugi][0][!!ch] + dp[cur][j][a][0][0]) %
1000000007;
} else if (!ch) {
dp[nxt][0][0][0][0] =
(dp[nxt][0][0][0][0] + dp[cur][j][a][0][0]) % 1000000007;
}
}
nxtt3:;
if (!dp[cur][j][a][1][0]) continue;
for (int ch = 0; ch <= r[i]; ch++) {
int tugi = nex[a][ch];
if (ch && j + gain[tugi] <= k) {
dp[nxt][j + gain[tugi]][tugi][ch == r[i] ? 1 : 0][1] =
(dp[nxt][j + gain[tugi]][tugi][ch == r[i] ? 1 : 0][1] +
dp[cur][j][a][1][0]) %
1000000007;
} else if (!ch) {
dp[nxt][0][0][ch == r[i] ? 1 : 0][0] =
(dp[nxt][0][0][ch == r[i] ? 1 : 0][0] + dp[cur][j][a][1][0]) %
1000000007;
}
}
}
}
swap(cur, nxt);
}
long long res = 0LL;
for (int j = 0; j <= k; j++)
for (int a = 0; a < pfx.size(); a++)
res = (res + dp[cur][j][a][0][1] + dp[cur][j][a][1][1]) % 1000000007;
return res;
}
int main() {
scanf("%d%d%d", &n, &m, &k);
scanf("%d", &lsize);
for (int i = 0; i < lsize; i++) scanf("%d", &l[i]);
vector<int> vec;
l[lsize - 1]--;
for (int i = lsize - 1; i >= 0; i--) {
if (l[i] == -1) {
l[i] = m - 1;
l[i - 1]--;
} else {
break;
}
}
for (int i = 0; i < lsize; i++) vec.push_back(l[i]);
if (vec.size() == lsize) {
if (!vec[0]) {
lsize--;
for (int i = 0; i < lsize; i++) l[i] = vec[i + 1];
} else {
for (int i = 0; i < lsize; i++) l[i] = vec[i];
}
}
scanf("%d", &rsize);
for (int i = 0; i < rsize; i++) scanf("%d", &r[i]);
for (int i = 0; i < n; i++) {
scanf("%d", &len[i]);
for (int j = 0; j < len[i]; j++) {
scanf("%d", &str[i][j]);
}
scanf("%d", &p[i]);
}
pre();
printf("%lld\n", (calcr() - calcl() + 1000000007) % 1000000007);
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i. e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.
Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (n β€ k) values b1, b2, ..., bn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i. e. n < k. Note that the initial score wasn't announced.
Your task is to determine the number of options for the score the participant could have before the judges rated the participant.
Input
The first line contains two integers k and n (1 β€ n β€ k β€ 2 000) β the number of jury members and the number of scores Polycarp remembers.
The second line contains k integers a1, a2, ..., ak ( - 2 000 β€ ai β€ 2 000) β jury's marks in chronological order.
The third line contains n distinct integers b1, b2, ..., bn ( - 4 000 000 β€ bj β€ 4 000 000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order.
Output
Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes).
Examples
Input
4 1
-5 5 0 20
10
Output
3
Input
2 2
-2000 -2000
3998000 4000000
Output
1
Note
The answer for the first example is 3 because initially the participant could have - 10, 10 or 15 points.
In the second example there is only one correct initial score equaling to 4 002 000.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[2003], b[2003], s[2003];
int main() {
int n, k, ans = 0;
bool ok;
int a[2003], b[2003], s[2003], x[2003];
cin >> k >> n;
set<int> points;
multiset<int> res1, res;
for (int i = 0; i < k; i++) {
cin >> a[i];
s[i] = (i == 0) ? a[0] : s[i - 1] + a[i];
}
for (int i = 0; i < n; i++) {
cin >> x[i];
if (!i)
for (int j = 0; j < k; j++) points.insert(x[i] - s[j]);
}
int imposs = k - n, imposs1 = 0;
map<int, set<int> > pts;
for (set<int>::iterator it = points.begin(); it != points.end(); it++) {
ok = true;
for (int j = 0; j < k; j++) {
pts[*it].insert(*it + s[j]);
}
for (int j = 0; j < n; j++) {
if (pts[*it].find(x[j]) == pts[*it].end()) {
ok = false;
}
}
if (ok) ans++;
}
cout << ans;
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
You are given an array of positive integers a1, a2, ..., an Γ T of length n Γ T. We know that for any i > n it is true that ai = ai - n. Find the length of the longest non-decreasing sequence of the given array.
Input
The first line contains two space-separated integers: n, T (1 β€ n β€ 100, 1 β€ T β€ 107). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 300).
Output
Print a single number β the length of a sought sequence.
Examples
Input
4 3
3 1 4 2
Output
5
Note
The array given in the sample looks like that: 3, 1, 4, 2, 3, 1, 4, 2, 3, 1, 4, 2. The elements in bold form the largest non-decreasing subsequence.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int lis(vector<int>& a) {
if (a.empty()) return 0;
int n = a.size();
int INF = 1000;
vector<int> b(n + 1, INF);
b[0] = -INF;
for (int i = 0; i < n; ++i) {
int val = a[i];
int pos = upper_bound(b.begin(), b.end(), val) - b.begin();
b[pos] = min(b[pos], val);
}
int res = 0;
for (int j = n; j >= 0; --j)
if (b[j] != INF) {
res = j;
break;
}
return res;
}
int brute(int n, int t, vector<int> a) {
for (int i = 0; i < t - 1; ++i)
for (int j = 0; j < n; ++j) a.push_back(a[j]);
int res = lis(a);
return res;
}
int main() {
ios_base::sync_with_stdio(false);
int n, t;
cin >> n >> t;
vector<int> a(n);
for (int i = 0; i < n; ++i) cin >> a[i];
int t0 = 400;
int t1 = 401;
int res = -1;
if (t <= t0) {
res = brute(n, t, a);
} else {
int res0 = brute(n, t0, a);
int res1 = brute(n, t1, a);
res = res1 + (t - t1) * (res1 - res0);
}
cout << res << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Bizon the Champion is called the Champion for a reason.
Bizon the Champion has recently got a present β a new glass cupboard with n shelves and he decided to put all his presents there. All the presents can be divided into two types: medals and cups. Bizon the Champion has a1 first prize cups, a2 second prize cups and a3 third prize cups. Besides, he has b1 first prize medals, b2 second prize medals and b3 third prize medals.
Naturally, the rewards in the cupboard must look good, that's why Bizon the Champion decided to follow the rules:
* any shelf cannot contain both cups and medals at the same time;
* no shelf can contain more than five cups;
* no shelf can have more than ten medals.
Help Bizon the Champion find out if we can put all the rewards so that all the conditions are fulfilled.
Input
The first line contains integers a1, a2 and a3 (0 β€ a1, a2, a3 β€ 100). The second line contains integers b1, b2 and b3 (0 β€ b1, b2, b3 β€ 100). The third line contains integer n (1 β€ n β€ 100).
The numbers in the lines are separated by single spaces.
Output
Print "YES" (without the quotes) if all the rewards can be put on the shelves in the described manner. Otherwise, print "NO" (without the quotes).
Examples
Input
1 1 1
1 1 1
4
Output
YES
Input
1 1 3
2 3 4
2
Output
YES
Input
1 0 0
1 0 0
1
Output
NO
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a1, a2, a3, b1, b2, b3, n, m = 10, sc, sm, c = 5;
cin >> a1 >> a2 >> a3 >> b1 >> b2 >> b3 >> n;
sc = a1 + a2 + a3;
sm = b1 + b2 + b3;
sm % m == 0 ? m = sm / m : m = (sm / m) + 1;
sc % c == 0 ? c = sc / c : c = (sc / c) + 1;
(c + m) <= n ? cout << "YES" : cout << "NO";
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.
In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.
For each cell i you are given two values:
* li β cell containing previous element for the element in the cell i;
* ri β cell containing next element for the element in the cell i.
If cell i contains information about the element which has no previous element then li = 0. Similarly, if cell i contains information about the element which has no next element then ri = 0.
<image> Three lists are shown on the picture.
For example, for the picture above the values of l and r are the following: l1 = 4, r1 = 7; l2 = 5, r2 = 0; l3 = 0, r3 = 0; l4 = 6, r4 = 1; l5 = 0, r5 = 2; l6 = 0, r6 = 4; l7 = 1, r7 = 0.
Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values li, ri.
Any other action, other than joining the beginning of one list to the end of another, can not be performed.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of memory cells where the doubly linked lists are located.
Each of the following n lines contains two integers li, ri (0 β€ li, ri β€ n) β the cells of the previous and the next element of list for cell i. Value li = 0 if element in cell i has no previous element in its list. Value ri = 0 if element in cell i has no next element in its list.
It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells.
Output
Print n lines, the i-th line must contain two integers li and ri β the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them.
Example
Input
7
4 7
5 0
0 0
6 1
0 2
0 4
1 0
Output
4 7
5 6
0 5
6 1
3 2
2 4
1 0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n;
const int maxn = 105;
struct node {
int l, r;
void read() { cin >> l >> r; }
} a[maxn];
int head[maxn], rear[maxn];
int tot;
int main() {
tot = 0;
cin >> n;
for (int i = 1; i <= n; i++) {
scanf("%d%d", &a[i].l, &a[i].r);
}
for (int i = 1; i <= n; i++) {
if (a[i].l == 0) {
int j = i;
while (a[j].r != 0) {
j = a[j].r;
}
head[++tot] = i;
rear[tot] = j;
}
}
for (int i = 2; i <= tot; i++) {
int u = rear[1], v = head[i];
a[u].r = v;
a[v].l = u;
rear[1] = rear[i];
}
for (int i = 1; i <= n; i++) {
printf("%d %d\n", a[i].l, a[i].r);
}
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was rolled in the same way as Dice I. Write a program to print an integer on the right side face.
<image>
Constraints
* $0 \leq $ the integer assigned to a face $ \leq 100$
* The integers are all different
* $1 \leq q \leq 24$
Input
In the first line, six integers assigned to faces are given in ascending order of their corresponding labels. In the second line, the number of questions $q$ is given.
In the following $q$ lines, $q$ questions are given. Each question consists of two integers on the top face and the front face respectively.
Output
For each question, print the integer on the right side face.
Example
Input
1 2 3 4 5 6
3
6 5
1 3
3 2
Output
3
5
6
### Response
```cpp
#include<iostream>
#include<iomanip>
#include<cmath>
#include<string>
#include<iostream>
using namespace std;
int main() {
const int n = 6;
int dice[n];
int top, front;
int p;
int dice_result[6];
const int dice_tem[4][6] = { { 3,2,6,1,5,4 },{ 2,6,3,4,1,5 },
{ 5,1,3,4,6,2 },{ 4,2,1,6,5,3 } };
for (int i = 0; i < n; i++) {
cin >> dice[i];
}
int num;
cin >> num;
for (int v = 0; v < num; v++) {
cin >> top >> front;
for (int d = 0; dice[0] != top ; d++) {
if (d == 0)continue;
for (int i = 0; i < n; i++) {
dice_result[i] = dice[dice_tem[d % 2][i] - 1];
}
for (int i = 0; i < n; i++)dice[i] = dice_result[i];
}
for (p = 0; p < 4; p++) {
for (int i = 0; i < n; i++) {
dice_result[i] = dice[dice_tem[p][i]-1];
}
if (front == dice_result[0]) break;
}
int a = p == 0 ? 2 : p == 1 ? 0 : p == 2 ? 3 : p == 3 ? 1 : -1;
int y[6];
for (int i = 0; i < n; i++)y[i] = dice[dice_tem[a][i] - 1];
cout << y[0] << endl;
}
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length n such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The grasshopper wants to eat the insect.
Ostap knows that grasshopper is able to jump to any empty cell that is exactly k cells away from the current (to the left or to the right). Note that it doesn't matter whether intermediate cells are empty or not as the grasshopper makes a jump over them. For example, if k = 1 the grasshopper can jump to a neighboring cell only, and if k = 2 the grasshopper can jump over a single cell.
Your goal is to determine whether there is a sequence of jumps such that grasshopper will get from his initial position to the cell with an insect.
Input
The first line of the input contains two integers n and k (2 β€ n β€ 100, 1 β€ k β€ n - 1) β the number of cells in the line and the length of one grasshopper's jump.
The second line contains a string of length n consisting of characters '.', '#', 'G' and 'T'. Character '.' means that the corresponding cell is empty, character '#' means that the corresponding cell contains an obstacle and grasshopper can't jump there. Character 'G' means that the grasshopper starts at this position and, finally, 'T' means that the target insect is located at this cell. It's guaranteed that characters 'G' and 'T' appear in this line exactly once.
Output
If there exists a sequence of jumps (each jump of length k), such that the grasshopper can get from his initial position to the cell with the insect, print "YES" (without quotes) in the only line of the input. Otherwise, print "NO" (without quotes).
Examples
Input
5 2
#G#T#
Output
YES
Input
6 1
T....G
Output
YES
Input
7 3
T..#..G
Output
NO
Input
6 2
..GT..
Output
NO
Note
In the first sample, the grasshopper can make one jump to the right in order to get from cell 2 to cell 4.
In the second sample, the grasshopper is only able to jump to neighboring cells but the way to the insect is free β he can get there by jumping left 5 times.
In the third sample, the grasshopper can't make a single jump.
In the fourth sample, the grasshopper can only jump to the cells with odd indices, thus he won't be able to reach the insect.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
scanf("%d %d", &n, &k);
string input;
cin >> input;
int g_p, t_p;
for (int i = 0; i < n; i++) {
if (input[i] == 'G') {
g_p = i;
} else if (input[i] == 'T') {
t_p = i;
}
}
int first = g_p, second = g_p;
bool marker = false;
int i;
for (i = first; i >= 0; i -= k) {
if (input[i] == 'T') {
printf("YES\n");
return 0;
} else if (input[i] == '#') {
break;
}
}
i = second;
for (; i < n; i += k) {
if (input[i] == 'T') {
printf("YES\n");
return 0;
} else if (input[i] == '#') {
break;
}
}
printf("NO\n");
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Two players A and B have a list of n integers each. They both want to maximize the subtraction between their score and their opponent's score.
In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an element from his opponent's list (assuming his opponent's list is not empty).
Note, that in case there are equal elements in the list only one of them will be affected in the operations above. For example, if there are elements \{1, 2, 2, 3\} in a list and you decided to choose 2 for the next turn, only a single instance of 2 will be deleted (and added to the score, if necessary).
The player A starts the game and the game stops when both lists are empty. Find the difference between A's score and B's score at the end of the game, if both of the players are playing optimally.
Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves. In this problem, it means that each player, each time makes a move, which maximizes the final difference between his score and his opponent's score, knowing that the opponent is doing the same.
Input
The first line of input contains an integer n (1 β€ n β€ 100 000) β the sizes of the list.
The second line contains n integers a_i (1 β€ a_i β€ 10^6), describing the list of the player A, who starts the game.
The third line contains n integers b_i (1 β€ b_i β€ 10^6), describing the list of the player B.
Output
Output the difference between A's score and B's score (A-B) if both of them are playing optimally.
Examples
Input
2
1 4
5 1
Output
0
Input
3
100 100 100
100 100 100
Output
0
Input
2
2 1
5 6
Output
-3
Note
In the first example, the game could have gone as follows:
* A removes 5 from B's list.
* B removes 4 from A's list.
* A takes his 1.
* B takes his 1.
Hence, A's score is 1, B's score is 1 and difference is 0.
There is also another optimal way of playing:
* A removes 5 from B's list.
* B removes 4 from A's list.
* A removes 1 from B's list.
* B removes 1 from A's list.
The difference in the scores is still 0.
In the second example, irrespective of the moves the players make, they will end up with the same number of numbers added to their score, so the difference will be 0.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long n, x, scoreA = 0, scoreB = 0;
cin >> n;
vector<long long> a, b;
for (long long i = 0; i < n; i++) {
cin >> x;
a.push_back(x);
}
for (long long i = 0; i < n; i++) {
cin >> x;
b.push_back(x);
}
sort(a.begin(), a.end());
sort(b.begin(), b.end());
for (long long i = 0; i < 2 * n; i++) {
if (i % 2 == 0) {
if (a.size() == 0) {
b.pop_back();
} else if (b.size() == 0) {
scoreA = scoreA + a[a.size() - 1];
a.pop_back();
} else {
if (a[a.size() - 1] > b[b.size() - 1]) {
scoreA = scoreA + a[a.size() - 1];
a.pop_back();
} else {
b.pop_back();
}
}
} else {
if (b.size() == 0) {
a.pop_back();
} else if (a.size() == 0) {
scoreB = scoreB + b[b.size() - 1];
b.pop_back();
} else {
if (b[b.size() - 1] > a[a.size() - 1]) {
scoreB = scoreB + b[b.size() - 1];
b.pop_back();
} else {
a.pop_back();
}
}
}
}
cout << scoreA - scoreB << endl;
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.
The trajectory of a camel's spit is an arc, i.e. if the camel in position x spits d meters right, he can hit only the camel in position x + d, if such a camel exists.
Input
The first line contains integer n (1 β€ n β€ 100) β the amount of camels in the zoo. Each of the following n lines contains two integers xi and di ( - 104 β€ xi β€ 104, 1 β€ |di| β€ 2Β·104) β records in Bob's notepad. xi is a position of the i-th camel, and di is a distance at which the i-th camel spitted. Positive values of di correspond to the spits right, negative values correspond to the spits left. No two camels may stand in the same position.
Output
If there are two camels, which spitted at each other, output YES. Otherwise, output NO.
Examples
Input
2
0 1
1 -1
Output
YES
Input
3
0 1
1 1
2 -2
Output
NO
Input
5
2 -10
3 10
0 5
5 -5
10 1
Output
YES
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct node {
int pos, dis;
node() {}
node(int a, int b) {
pos = a;
dis = b;
}
};
vector<node> ve;
int main() {
int t, a, b;
scanf("%d", &t);
for (int i = 0; i < t; ++i) {
scanf("%d %d", &a, &b);
ve.push_back(node(a, b));
}
for (int i = 0; i < t; ++i) {
for (int j = 0; j < t; ++j) {
if (i == j) continue;
if (ve[i].pos + ve[i].dis == ve[j].pos &&
ve[j].pos + ve[j].dis == ve[i].pos) {
cout << "YES" << endl;
return 0;
}
}
}
cout << "NO" << endl;
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
You are given an array a consisting of 500000 integers (numbered from 1 to 500000). Initially all elements of a are zero.
You have to process two types of queries to this array:
* 1 x y β increase a_x by y;
* 2 x y β compute β_{i β R(x, y)} a_i, where R(x, y) is the set of all integers from 1 to 500000 which have remainder y modulo x.
Can you process all the queries?
Input
The first line contains one integer q (1 β€ q β€ 500000) β the number of queries.
Then q lines follow, each describing a query. The i-th line contains three integers t_i, x_i and y_i (1 β€ t_i β€ 2). If t_i = 1, then it is a query of the first type, 1 β€ x_i β€ 500000, and -1000 β€ y_i β€ 1000. If t_i = 2, then it it a query of the second type, 1 β€ x_i β€ 500000, and 0 β€ y_i < x_i.
It is guaranteed that there will be at least one query of type 2.
Output
For each query of type 2 print one integer β the answer to it.
Example
Input
5
1 3 4
2 3 0
2 4 3
1 4 -4
2 1 0
Output
4
4
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 100;
const int mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const long long llINF = 0x3f3f3f3f3f3f3f3f;
inline bool read(long long &num) {
char in;
bool IsN = false;
in = getchar();
if (in == EOF) return false;
while (in != '-' && (in < '0' || in > '9')) in = getchar();
if (in == '-') {
IsN = true;
num = 0;
} else
num = in - '0';
while (in = getchar(), in >= '0' && in <= '9') {
num *= 10, num += in - '0';
}
if (IsN) num = -num;
return true;
}
long long A[N], SUM[301][301];
int main() {
long long q, op, x, y;
read(q);
while (q--) {
read(op);
read(x);
read(y);
if (op == 1) {
A[x] += y;
for (int i = (1); i <= (300); i++) SUM[i][x % i] += y;
} else {
long long ans = 0;
if (x > 300) {
for (int i = y; i <= 500000; i += x) ans += A[i];
printf("%lld\n", ans);
} else {
printf("%lld\n", SUM[x][y]);
}
}
}
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
A rooted tree is a non-directed connected graph without any cycles with a distinguished vertex, which is called the tree root. Consider the vertices of a rooted tree, that consists of n vertices, numbered from 1 to n. In this problem the tree root is the vertex number 1.
Let's represent the length of the shortest by the number of edges path in the tree between vertices v and u as d(v, u).
A parent of vertex v in the rooted tree with the root in vertex r (v β r) is vertex pv, such that d(r, pv) + 1 = d(r, v) and d(pv, v) = 1. For example, on the picture the parent of vertex v = 5 is vertex p5 = 2.
One day Polycarpus came across a rooted tree, consisting of n vertices. The tree wasn't exactly ordinary: it had strings written on its edges. Polycarpus positioned the tree on the plane so as to make all edges lead from top to bottom if you go from the vertex parent to the vertex (see the picture). For any edge that lead from vertex pv to vertex v (1 < v β€ n), he knows string sv that is written on it. All strings are written on the edges from top to bottom. For example, on the picture s7="ba". The characters in the strings are numbered starting from 0.
<image> An example of Polycarpus's tree (corresponds to the example from the statement)
Polycarpus defines the position in this tree as a specific letter on a specific string. The position is written as a pair of integers (v, x) that means that the position is the x-th letter of the string sv (1 < v β€ n, 0 β€ x < |sv|), where |sv| is the length of string sv. For example, the highlighted letters are positions (2, 1) and (3, 1).
Let's consider the pair of positions (v, x) and (u, y) in Polycarpus' tree, such that the way from the first position to the second goes down on each step. We will consider that the pair of such positions defines string z. String z consists of all letters on the way from (v, x) to (u, y), written in the order of this path. For example, in the picture the highlighted positions define string "bacaba".
Polycarpus has a string t, he wants to know the number of pairs of positions that define string t. Note that the way from the first position to the second in the pair must go down everywhere. Help him with this challenging tree-string problem!
Input
The first line contains integer n (2 β€ n β€ 105) β the number of vertices of Polycarpus's tree. Next n - 1 lines contain the tree edges. The i-th of them contains number pi + 1 and string si + 1 (1 β€ pi + 1 β€ n; pi + 1 β (i + 1)). String si + 1 is non-empty and consists of lowercase English letters. The last line contains string t. String t consists of lowercase English letters, its length is at least 2.
It is guaranteed that the input contains at most 3Β·105 English letters.
Output
Print a single integer β the required number.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
7
1 ab
5 bacaba
1 abacaba
2 aca
5 ba
2 ba
aba
Output
6
Input
7
1 ab
5 bacaba
1 abacaba
2 aca
5 ba
2 ba
bacaba
Output
4
Note
In the first test case string "aba" is determined by the pairs of positions: (2, 0) and (5, 0); (5, 2) and (6, 1); (5, 2) and (3, 1); (4, 0) and (4, 2); (4, 4) and (4, 6); (3, 3) and (3, 5).
Note that the string is not defined by the pair of positions (7, 1) and (5, 0), as the way between them doesn't always go down.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int Maxs = 300 * 1000 + 5, Maxn = 100 * 1000 + 5;
int n, dp[Maxs], nxt[Maxs][26];
char s[Maxs];
long long ans;
string t;
vector<int> adj[Maxn];
vector<string> str[Maxn];
void kmp() {
dp[0] = -1;
for (int i = 0; i < (int)t.size(); i++) {
int pt = i;
while (dp[pt] != -1 && t[dp[pt]] != t[i]) pt = dp[pt];
dp[i + 1] = dp[pt] + 1;
}
return;
}
void dfs(int v, int indt) {
for (int i = 0; i < adj[v].size(); i++) {
int indt2 = indt;
for (int j = 0; j < (int)str[v][i].size(); j++) {
if (indt2 == (int)t.size()) ans++;
indt2 = nxt[indt2 + 1][str[v][i][j] - 'a'];
}
if (indt2 == (int)t.size()) {
ans++;
indt2 = dp[indt2];
}
dfs(adj[v][i], indt2);
}
return;
}
int main() {
scanf("%d", &n);
int par;
for (int i = 1; i < n; i++) {
scanf("%d%s", &par, s);
par--;
adj[par].push_back(i);
str[par].push_back(s);
}
scanf("%s", s);
t = s;
kmp();
for (int i = 1; i <= (int)t.size() + 1; i++) {
for (int j = 0; j < 26; j++) {
if (i <= (int)t.size() && t[i - 1] - 'a' == j)
nxt[i][j] = i;
else
nxt[i][j] = nxt[dp[i - 1] + 1][j];
}
}
dfs(0, 0);
cout << ans << endl;
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
The nation of Panel holds an annual show called The Number Games, where each district in the nation will be represented by one contestant.
The nation has n districts numbered from 1 to n, each district has exactly one path connecting it to every other district. The number of fans of a contestant from district i is equal to 2^i.
This year, the president decided to reduce the costs. He wants to remove k contestants from the games. However, the districts of the removed contestants will be furious and will not allow anyone to cross through their districts.
The president wants to ensure that all remaining contestants are from districts that can be reached from one another. He also wishes to maximize the total number of fans of the participating contestants.
Which contestants should the president remove?
Input
The first line of input contains two integers n and k (1 β€ k < n β€ 10^6) β the number of districts in Panel, and the number of contestants the president wishes to remove, respectively.
The next n-1 lines each contains two integers a and b (1 β€ a, b β€ n, a β b), that describe a road that connects two different districts a and b in the nation. It is guaranteed that there is exactly one path between every two districts.
Output
Print k space-separated integers: the numbers of the districts of which the contestants should be removed, in increasing order of district number.
Examples
Input
6 3
2 1
2 6
4 2
5 6
2 3
Output
1 3 4
Input
8 4
2 6
2 7
7 8
1 2
3 1
2 4
7 5
Output
1 3 4 5
Note
In the first sample, the maximum possible total number of fans is 2^2 + 2^5 + 2^6 = 100. We can achieve it by removing the contestants of the districts 1, 3, and 4.
### Response
```cpp
#include <bits/stdc++.h>
#pragma optimize("Ofast")
#pragma GCC optimize("-funsafe-loop-optimizations")
#pragma GCC optimize("-funroll-loops")
#pragma GCC optimize("-fwhole-program")
#pragma GCC optimize("-fthread-jumps")
#pragma GCC optimize("-falign-functions")
#pragma GCC optimize("-falign-jumps")
#pragma GCC optimize("-falign-loops")
#pragma GCC optimize("-falign-labels")
#pragma GCC optimize("-fcaller-saves")
#pragma GCC optimize("-fcrossjumping")
#pragma GCC optimize("-fcse-follow-jumps")
#pragma GCC optimize("-fcse-skip-blocks")
#pragma GCC optimize("-fdelete-null-pointer-checks")
#pragma GCC optimize("-fdevirtualize")
#pragma GCC optimize("-fexpensive-optimizations")
#pragma GCC optimize("-fgcse")
#pragma GCC optimize("-fgcse-lm")
#pragma GCC optimize("-fhoist-adjacent-loads")
#pragma GCC optimize("-finline-small-functions")
#pragma GCC optimize("-findirect-inlining")
#pragma GCC optimize("-fipa-sra")
#pragma GCC optimize("-foptimize-sibling-calls")
#pragma GCC optimize("-fpartial-inlining")
#pragma GCC optimize("-fpeephole2")
#pragma GCC optimize("-freorder-blocks")
#pragma GCC optimize("-freorder-functions")
#pragma GCC optimize("-frerun-cse-after-loop")
#pragma GCC optimize("-fsched-interblock")
#pragma GCC optimize("-fsched-spec")
#pragma GCC optimize("-fschedule-insns")
#pragma GCC optimize("-fschedule-insns2")
#pragma GCC optimize("-fstrict-aliasing")
#pragma GCC optimize("-fstrict-overflow")
#pragma GCC optimize("-ftree-switch-conversion")
#pragma GCC optimize("-ftree-tail-merge")
#pragma GCC optimize("-ftree-pre")
#pragma GCC optimize("-ftree-vrp")
using namespace std;
const int inf = 0x3f3f3f3f;
const long long inf2 = 0x3f3f3f3f3f3f3f3f;
const double eps = 1e-6;
const int mod = 1000000007;
namespace fastio {
char in[100000];
int itr = 0, llen = 0;
char get() {
if (itr == llen) llen = fread(in, 1, 100000, stdin), itr = 0;
if (llen == 0) return EOF;
return in[itr++];
}
char out[100000];
int itr2 = 0;
void put(char c) {
out[itr2++] = c;
if (itr2 == 100000) {
fwrite(out, 1, 100000, stdout);
itr2 = 0;
}
}
int clear() {
fwrite(out, 1, itr2, stdout);
itr2 = 0;
return 0;
}
int getint() {
int r = 0;
bool ng = 0;
char c;
c = get();
while (c != '-' && (c < '0' || c > '9')) c = get();
if (c == '-') ng = 1, c = get();
while (c >= '0' && c <= '9') r = r * 10 + c - '0', c = get();
return ng ? -r : r;
}
string getstr() {
string ret = "";
char ch = get();
while (ch == ' ' || ch == '\n') ch = get();
while (ch != ' ' && ch != '\n') ret.push_back(ch), ch = get();
return ret;
}
void putstr(string s) {
for (int i = 0; i < s.size(); i++) put(s[i]);
}
void putint(int x) {
if (x < 0) {
put('-');
x = -x;
}
if (x == 0) {
put('0');
return;
}
char c[20];
int pos = 0;
while (x) {
c[pos++] = '0' + x % 10;
x /= 10;
}
for (int i = pos - 1; i >= 0; i--) put(c[i]);
}
void getarr(int arrname[], int size) {
for (int i = 0; i < size; i++) arrname[i] = getint();
}
} // namespace fastio
using namespace fastio;
int number[1000005], BITN = 1e6;
void modify(int x, int y) {
while (x <= BITN) {
number[x] += y;
x += x & -x;
}
}
int sum(int x) {
int ret = 0;
while (x) {
ret += number[x];
x &= x - 1;
}
return ret;
}
void add(int l, int r, int v) {
modify(l, v);
modify(r, -v);
}
int qry(int x) { return sum(x); }
int n, k;
vector<int> g[1000005];
vector<int> ord;
int pos[1000005];
bool used[1000005];
int par[1000005];
int sz[1000005], depth[1000005];
void dfs(int x, int pr) {
depth[x] = x == n ? 0 : depth[pr] + 1;
pos[x] = ord.size() + 1;
ord.push_back(x);
sz[x] = 1;
for (auto to : g[x])
if (to != pr) par[to] = x, dfs(to, x), sz[x] += sz[to];
}
int main() {
n = getint();
k = getint();
for (int i = 1; i < n; i++) {
int a = getint(), b = getint();
g[a].push_back(b);
g[b].push_back(a);
}
dfs(n, 0);
for (int i = 0; i < ord.size(); i++) {
modify(i + 1, depth[ord[i]] - (i == 0 ? 0 : depth[ord[i - 1]]));
}
used[n] = true;
int rest = n - k - 1;
for (int v = n - 1; v > 0 && rest; v--) {
if (used[v]) continue;
int len = qry(pos[v]);
if (len <= rest) {
int cur = v;
while (!used[cur]) {
used[cur] = true;
add(pos[cur], pos[cur] + sz[cur], -1);
cur = par[cur];
rest--;
}
}
}
vector<int> ans;
for (int i = 1; i <= n; i++)
if (!used[i]) ans.push_back(i);
for (int i = 0; i < ans.size(); i++) putint(ans[i]), put(' ');
clear();
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
There are n cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from 1 to n.
It is known that, from the capital (the city with the number 1), you can reach any other city by moving along the roads.
The President of Berland plans to improve the country's road network. The budget is enough to repair exactly n-1 roads. The President plans to choose a set of n-1 roads such that:
* it is possible to travel from the capital to any other city along the n-1 chosen roads,
* if d_i is the number of roads needed to travel from the capital to city i, moving only along the n-1 chosen roads, then d_1 + d_2 + ... + d_n is minimized (i.e. as minimal as possible).
In other words, the set of n-1 roads should preserve the connectivity of the country, and the sum of distances from city 1 to all cities should be minimized (where you can only use the n-1 chosen roads).
The president instructed the ministry to prepare k possible options to choose n-1 roads so that both conditions above are met.
Write a program that will find k possible ways to choose roads for repair. If there are fewer than k ways, then the program should output all possible valid ways to choose roads.
Input
The first line of the input contains integers n, m and k (2 β€ n β€ 2β
10^5, n-1 β€ m β€ 2β
10^5, 1 β€ k β€ 2β
10^5), where n is the number of cities in the country, m is the number of roads and k is the number of options to choose a set of roads for repair. It is guaranteed that m β
k β€ 10^6.
The following m lines describe the roads, one road per line. Each line contains two integers a_i, b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the numbers of the cities that the i-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital.
Output
Print t (1 β€ t β€ k) β the number of ways to choose a set of roads for repair. Recall that you need to find k different options; if there are fewer than k of them, then you need to find all possible different valid options.
In the following t lines, print the options, one per line. Print an option as a string of m characters where the j-th character is equal to '1' if the j-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the t lines should be different.
Since it is guaranteed that m β
k β€ 10^6, the total length of all the t lines will not exceed 10^6.
If there are several answers, output any of them.
Examples
Input
4 4 3
1 2
2 3
1 4
4 3
Output
2
1110
1011
Input
4 6 3
1 2
2 3
1 4
4 3
2 4
1 3
Output
1
101001
Input
5 6 2
1 2
1 3
2 4
2 5
3 4
3 5
Output
2
111100
110110
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m, k;
vector<pair<int, int> > edge[200001];
vector<int> d;
vector<int> v_choose;
char choose[200001];
void read_data() {
cin >> n >> m >> k;
int a, b;
d.resize(n + 1);
for (int i = 0; i < m; i++) {
scanf("%d %d", &a, &b);
edge[a].push_back(make_pair(b, i));
edge[b].push_back(make_pair(a, i));
}
}
void deal() {
queue<int> q;
vector<bool> isv;
isv.resize(n + 1, 0);
d.resize(n + 1);
q.push(1);
d[1] = 0;
isv[1] = true;
while (!q.empty()) {
int u = q.front();
q.pop();
for (auto &i : edge[u]) {
int v = i.first;
if (!isv[v]) {
isv[v] = true;
d[v] = d[u] + 1;
q.push(v);
}
}
}
for (int v = 2; v <= n; v++) {
vector<pair<int, int> > all = edge[v];
edge[v].clear();
for (int l = 0; l < all.size(); l++) {
int u = all[l].first;
if (d[u] + 1 == d[v]) {
edge[v].push_back(make_pair(u, all[l].second));
}
}
}
long long int ans = 1;
for (int v = 2; v <= n; v++)
if (edge[v].size() > 0) {
ans = ans * edge[v].size();
if (ans > k) {
ans = k;
break;
}
}
cout << ans << endl;
memset(choose, '0', sizeof(choose));
choose[m] = 0;
v_choose.resize(n + 1);
for (int v = 2; v <= n; v++) {
v_choose[v] = 0;
choose[edge[v][0].second] = '1';
}
printf("%s\n", choose);
for (int i = 1; i < ans; i++) {
for (int v = n; v >= 2; v--) {
int evs = edge[v].size();
if (evs - 1 == v_choose[v]) {
choose[edge[v][evs - 1].second] = '0';
v_choose[v] = 0;
choose[edge[v][0].second] = '1';
} else {
int &vc = v_choose[v];
choose[edge[v][vc].second] = '0';
vc++;
choose[edge[v][vc].second] = '1';
break;
}
}
printf("%s\n", choose);
}
}
int main() {
read_data();
deal();
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
AtCoDeer the deer found two positive integers, a and b. Determine whether the product of a and b is even or odd.
Constraints
* 1 β€ a,b β€ 10000
* a and b are integers.
Input
Input is given from Standard Input in the following format:
a b
Output
If the product is odd, print `Odd`; if it is even, print `Even`.
Examples
Input
3 4
Output
Even
Input
1 21
Output
Odd
### Response
```cpp
#include <iostream>
using namespace std;
int main(){int a,b;cin>>a>>b;if(a&b&1)puts("Odd");else puts("Even");return 0;}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Takahashi has A untasty cookies containing antidotes, B tasty cookies containing antidotes and C tasty cookies containing poison.
Eating a cookie containing poison results in a stomachache, and eating a cookie containing poison while having a stomachache results in a death. As he wants to live, he cannot eat one in such a situation. Eating a cookie containing antidotes while having a stomachache cures it, and there is no other way to cure stomachaches.
Find the maximum number of tasty cookies that Takahashi can eat.
Constraints
* 0 \leq A,B,C \leq 10^9
* A,B and C are integers.
Input
Input is given from Standard Input in the following format:
A B C
Output
Print the maximum number of tasty cookies that Takahashi can eat.
Examples
Input
3 1 4
Output
5
Input
5 2 9
Output
10
Input
8 8 1
Output
9
### Response
```cpp
#include <iostream>
using namespace std;
int main() {
long a,b,c;
cin>>a>>b>>c;
if(a+b<c)cout<<a+2*b+1<<endl;
else cout<<b+c<<endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Let A = {a1, a2, ..., an} be any permutation of the first n natural numbers {1, 2, ..., n}. You are given a positive integer k and another sequence B = {b1, b2, ..., bn}, where bi is the number of elements aj in A to the left of the element at = i such that aj β₯ (i + k).
For example, if n = 5, a possible A is {5, 1, 4, 2, 3}. For k = 2, B is given by {1, 2, 1, 0, 0}. But if k = 3, then B = {1, 1, 0, 0, 0}.
For two sequences X = {x1, x2, ..., xn} and Y = {y1, y2, ..., yn}, let i-th elements be the first elements such that xi β yi. If xi < yi, then X is lexicographically smaller than Y, while if xi > yi, then X is lexicographically greater than Y.
Given n, k and B, you need to determine the lexicographically smallest A.
Input
The first line contains two space separated integers n and k (1 β€ n β€ 1000, 1 β€ k β€ n). On the second line are n integers specifying the values of B = {b1, b2, ..., bn}.
Output
Print on a single line n integers of A = {a1, a2, ..., an} such that A is lexicographically minimal. It is guaranteed that the solution exists.
Examples
Input
5 2
1 2 1 0 0
Output
4 1 5 2 3
Input
4 2
1 0 0 0
Output
2 3 1 4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2100;
int a[MAXN];
int b[MAXN];
int z[MAXN];
char used[MAXN];
int n;
int k;
int main() {
int i;
cin >> n >> k;
for (i = 1; i <= n; ++i) cin >> b[i];
memset(used, 0, sizeof(used));
int j;
for (i = 1; i <= n; ++i)
for (j = 1; j <= n; ++j) {
z[j]++;
if (!used[j] && b[j] == z[j + k]) {
a[i] = j;
used[j] = 1;
break;
}
}
for (i = 1; i <= n; ++i) cout << a[i] << ' ';
cout << endl;
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins.
You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have.
However, you don't want to lose any money so you want to choose the price in such a way that the sum of new prices is not less than the sum of the initial prices. It means that if you sell all n goods for the new price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.
On the other hand, you don't want to lose customers because of big prices so among all prices you can choose you need to choose the minimum one.
So you need to find the minimum possible equal price of all n goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 100) β the number of queries. Then q queries follow.
The first line of the query contains one integer n (1 β€ n β€ 100) β the number of goods. The second line of the query contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^7), where a_i is the price of the i-th good.
Output
For each query, print the answer for it β the minimum possible equal price of all n goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.
Example
Input
3
5
1 2 3 4 5
3
1 2 2
4
1 1 1 1
Output
3
2
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6;
void solve() {
int n;
cin >> n;
int arr[n];
long long maj = 0;
for (int i = 0; i < n; i++) {
cin >> arr[i];
maj += arr[i];
}
cout << (maj + n - 1) / n << endl;
}
int main() {
int t;
cin >> t;
while (t--) {
solve();
}
}
``` |
### Prompt
Generate a CPP solution to the following problem:
You are given names of two days of the week.
Please, determine whether it is possible that during some non-leap year the first day of some month was equal to the first day of the week you are given, while the first day of the next month was equal to the second day of the week you are given. Both months should belong to one year.
In this problem, we consider the Gregorian calendar to be used. The number of months in this calendar is equal to 12. The number of days in months during any non-leap year is: 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31.
Names of the days of the week are given with lowercase English letters: "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday".
Input
The input consists of two lines, each of them containing the name of exactly one day of the week. It's guaranteed that each string in the input is from the set "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday".
Output
Print "YES" (without quotes) if such situation is possible during some non-leap year. Otherwise, print "NO" (without quotes).
Examples
Input
monday
tuesday
Output
NO
Input
sunday
sunday
Output
YES
Input
saturday
tuesday
Output
YES
Note
In the second sample, one can consider February 1 and March 1 of year 2015. Both these days were Sundays.
In the third sample, one can consider July 1 and August 1 of year 2017. First of these two days is Saturday, while the second one is Tuesday.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int M = 1e6 + 15;
const int Q = 1e9 + 7;
int num(string x) {
if (x[0] == 'm') return 0;
if (x[0] == 't') {
if (x[1] == 'u') return 1;
return 3;
}
if (x[0] == 'w') return 2;
if (x[0] == 'f') return 4;
if (x[1] == 'a') return 5;
return 6;
}
int ar[11] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30};
int main() {
srand(time(NULL));
cin.tie(0);
ios_base::sync_with_stdio(0);
string ax, bx;
cin >> ax >> bx;
int a = num(ax), b = num(bx);
for (int i = 0; i < 11; i++) {
if ((ar[i] + a) % 7 == b) {
puts("YES");
return 0;
}
}
puts("NO");
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Let's call two numbers similar if their binary representations contain the same number of digits equal to 1. For example:
* 2 and 4 are similar (binary representations are 10 and 100);
* 1337 and 4213 are similar (binary representations are 10100111001 and 1000001110101);
* 3 and 2 are not similar (binary representations are 11 and 10);
* 42 and 13 are similar (binary representations are 101010 and 1101).
You are given an array of n integers a_1, a_2, ..., a_n. You may choose a non-negative integer x, and then get another array of n integers b_1, b_2, ..., b_n, where b_i = a_i β x (β denotes bitwise XOR).
Is it possible to obtain an array b where all numbers are similar to each other?
Input
The first line contains one integer n (2 β€ n β€ 100).
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 2^{30} - 1).
Output
If it is impossible to choose x so that all elements in the resulting array are similar to each other, print one integer -1.
Otherwise, print any non-negative integer not exceeding 2^{30} - 1 that can be used as x so that all elements in the resulting array are similar.
Examples
Input
2
7 2
Output
1
Input
4
3 17 6 0
Output
5
Input
3
1 2 3
Output
-1
Input
3
43 12 12
Output
1073709057
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("-O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
struct Node {
int value{0};
int x{-1};
Node* children[31]{};
Node() {
for (auto& child : children) {
child = nullptr;
}
}
};
Node* root = new Node();
int kol1[33000][110], kol2[33000][110], del[33000][110];
int main() {
std::cin.tie(nullptr);
std::cout.tie(nullptr);
std::ios_base::sync_with_stdio(false);
int n;
std::cin >> n;
std::vector<int> v(n);
for (int i = 0; i < n; i++) {
std::cin >> v[i];
}
for (int cur_x = 0; cur_x < (1 << 15); cur_x++) {
for (int i = 0; i < n; i++) {
int cur_kol = 0;
for (int bit_pos = 0; bit_pos < 15; bit_pos++) {
if (((cur_x & (1 << bit_pos)) > 0 && (v[i] & (1 << bit_pos)) == 0) ||
((cur_x & (1 << bit_pos)) == 0 && (v[i] & (1 << bit_pos)) > 0)) {
cur_kol++;
}
}
kol1[cur_x][i] = cur_kol;
}
for (int i = 0; i < n - 1; i++) {
del[cur_x][i] = kol1[cur_x][i + 1] - kol1[cur_x][i];
}
for (int i = 0; i < n; i++) {
int cur_kol = 0;
for (int bit_pos = 0; bit_pos < 15; bit_pos++) {
if (((cur_x & (1 << bit_pos)) > 0 &&
(v[i] & (1 << (bit_pos + 15))) == 0) ||
((cur_x & (1 << bit_pos)) == 0 &&
(v[i] & (1 << (bit_pos + 15))) > 0)) {
cur_kol++;
}
}
kol2[cur_x][i] = cur_kol;
}
Node* cur_node = root;
for (int i = 0; i < n - 1; i++) {
int to_add = kol2[cur_x][i + 1] - kol2[cur_x][i];
if (cur_node->children[to_add + 15] == nullptr) {
cur_node->children[to_add + 15] = new Node();
}
cur_node = cur_node->children[to_add + 15];
if (i + 1 == n - 1) {
cur_node->x = cur_x;
}
}
}
for (int cur_x = 0; cur_x < (1 << 15); cur_x++) {
Node* cur_node = root;
bool ok = true;
for (int i = 0; i < n - 1; i++) {
int to_find = del[cur_x][i];
if (cur_node->children[-to_find + 15] == nullptr) {
ok = false;
break;
}
cur_node = cur_node->children[-to_find + 15];
}
if (ok) {
std::cout << (cur_node->x << 15) + cur_x;
return 0;
}
}
std::cout << -1;
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n.
For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10.
Input
The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases in the input. Next, t test cases are given, one per line.
Each test case is two positive integers n (2 β€ n β€ 10^9) and k (1 β€ k β€ 10^9).
Output
For each test case print the k-th positive integer that is not divisible by n.
Example
Input
6
3 7
4 12
2 1000000000
7 97
1000000000 1000000000
2 1
Output
10
15
1999999999
113
1000000001
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
long long n, k;
cin >> n >> k;
int diff = (k - 1) / (n - 1);
cout << diff + k << "\n";
}
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".
To play Mau-Mau, you need a pack of 52 cards. Each card has a suit (Diamonds β D, Clubs β C, Spades β S, or Hearts β H), and a rank (2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, or A).
At the start of the game, there is one card on the table and you have five cards in your hand. You can play a card from your hand if and only if it has the same rank or the same suit as the card on the table.
In order to check if you'd be a good playing partner, Gennady has prepared a task for you. Given the card on the table and five cards in your hand, check if you can play at least one card.
Input
The first line of the input contains one string which describes the card on the table. The second line contains five strings which describe the cards in your hand.
Each string is two characters long. The first character denotes the rank and belongs to the set \{{\tt 2}, {\tt 3}, {\tt 4}, {\tt 5}, {\tt 6}, {\tt 7}, {\tt 8}, {\tt 9}, {\tt T}, {\tt J}, {\tt Q}, {\tt K}, {\tt A}\}. The second character denotes the suit and belongs to the set \{{\tt D}, {\tt C}, {\tt S}, {\tt H}\}.
All the cards in the input are different.
Output
If it is possible to play a card from your hand, print one word "YES". Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Examples
Input
AS
2H 4C TH JH AD
Output
YES
Input
2H
3D 4C AC KD AS
Output
NO
Input
4D
AS AC AD AH 5H
Output
YES
Note
In the first example, there is an Ace of Spades (AS) on the table. You can play an Ace of Diamonds (AD) because both of them are Aces.
In the second example, you cannot play any card.
In the third example, you can play an Ace of Diamonds (AD) because it has the same suit as a Four of Diamonds (4D), which lies on the table.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
int n = (int)s[0] - 48;
char rang = s[1];
for (int i = 0; i < 5; ++i) {
string s_i;
cin >> s_i;
int n_i = (int)s_i[0] - 48;
char rang_i = s_i[1];
if (n == n_i || rang == rang_i) {
cout << "YES";
return 0;
}
}
cout << "NO";
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.
The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "x bulls y cows". x represents the number of digits in the experimental number that occupy the same positions as in the sought number. y represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.
For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one).
When the guesser is answered "4 bulls 0 cows", the game is over.
Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.
Input
The first input line contains an integer n (1 β€ n β€ 10) which represents the number of already made guesses. Then follow n lines in the form of "ai bi ci", where ai is the i-th experimental number, bi is the number of bulls, ci is the number of cows (1 β€ i β€ n, 0 β€ bi, ci, bi + ci β€ 4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.
Output
If the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.
Examples
Input
2
1263 1 2
8103 2 1
Output
Need more data
Input
2
1234 2 2
1256 0 2
Output
2134
Input
2
0123 1 1
4567 1 2
Output
Incorrect data
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int ok[10];
int a[20][5];
int b[20][10];
int q[20];
int y[20];
int now[10];
int main() {
int n;
int ans = 0;
memset(q, 0, sizeof(q));
memset(y, 0, sizeof(y));
memset(b, 0, sizeof(b));
memset(a, 0, sizeof(a));
cin >> n;
int num = 0;
for (int i = 1; i <= n; i++) {
int e, r, t;
char p;
for (int j = 1; j <= 4; j++) {
p = getchar();
if (p == '\n') p = getchar();
a[i][j] = p - '0';
b[i][p - '0'] = 1;
}
cin >> r >> t;
q[i] = r;
y[i] = t;
}
for (int i = 1; i <= 9999; i++) {
int z = i;
memset(ok, 0, sizeof(ok));
memset(now, 0, sizeof(now));
int isok = 1;
for (int j = 1; j <= 4; j++) {
int g = z % 10;
if (ok[g]) {
isok = 0;
break;
} else {
ok[g] = 1;
now[j] = g;
}
z = z / 10;
}
if (!isok) continue;
for (int j = 1; j <= n; j++) {
int num1 = 0;
int num2 = 0;
for (int k = 1; k <= 4; k++) {
if (a[j][k] == now[5 - k]) {
num1++;
}
}
for (int k = 0; k <= 9; k++) {
if (ok[k] == 1 && b[j][k] == 1) num2++;
}
if (num1 != q[j] || (num2 - num1) != y[j]) {
isok = 0;
}
}
if (isok) {
num++;
ans = i;
}
}
if (num == 1) {
if (ans > 1000)
cout << ans << endl;
else
cout << "0" << ans << endl;
}
if (num == 0) cout << "Incorrect data" << endl;
if (num > 1) cout << "Need more data" << endl;
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Petr wants to make a calendar for current month. For this purpose he draws a table in which columns correspond to weeks (a week is seven consequent days from Monday to Sunday), rows correspond to weekdays, and cells contain dates. For example, a calendar for January 2017 should look like on the picture:
<image>
Petr wants to know how many columns his table should have given the month and the weekday of the first date of that month? Assume that the year is non-leap.
Input
The only line contain two integers m and d (1 β€ m β€ 12, 1 β€ d β€ 7) β the number of month (January is the first month, December is the twelfth) and the weekday of the first date of this month (1 is Monday, 7 is Sunday).
Output
Print single integer: the number of columns the table should have.
Examples
Input
1 7
Output
6
Input
1 1
Output
5
Input
11 6
Output
5
Note
The first example corresponds to the January 2017 shown on the picture in the statements.
In the second example 1-st January is Monday, so the whole month fits into 5 columns.
In the third example 1-st November is Saturday and 5 columns is enough.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int main() {
int m, d;
cin >> m >> d;
a[m] -= 7 - d + 1;
if (a[m] % 7 == 0)
cout << a[m] / 7 + 1 << endl;
else
cout << a[m] / 7 + 2 << endl;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Gerald found a table consisting of n rows and m columns. As a prominent expert on rectangular tables, he immediately counted the table's properties, that is, the minimum of the numbers in the corners of the table (minimum of four numbers). However, he did not like the final value β it seemed to be too small. And to make this value larger, he decided to crop the table a little: delete some columns on the left and some on the right, as well as some rows from the top and some from the bottom. Find what the maximum property of the table can be after such cropping. Note that the table should have at least two rows and at least two columns left in the end. The number of cropped rows or columns from each of the four sides can be zero.
Input
The first line contains two space-separated integers n and m (2 β€ n, m β€ 1000). The following n lines describe the table. The i-th of these lines lists the space-separated integers ai, 1, ai, 2, ..., ai, m (0 β€ ai, j β€ 109) β the m numbers standing in the i-th row of the table.
Output
Print the answer to the problem.
Examples
Input
2 2
1 2
3 4
Output
1
Input
3 3
1 0 0
0 1 1
1 0 0
Output
0
Note
In the first test case Gerald cannot crop the table β table contains only two rows and only two columns.
In the second test case if we'll crop the table, the table will contain zero in some corner cell. Also initially it contains two zeros in the corner cells, so the answer is 0.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m, N;
bool b[2000][2000], c[2000][2000];
struct num {
int x, y, v;
} a[2000000];
bool cpr(num x, num y) { return x.v > y.v; }
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= (n); ++i)
for (int j = 1; j <= (m); ++j) {
scanf("%d", &a[++N].v);
a[N].x = i, a[N].y = j;
}
sort(a + 1, a + N + 1, cpr);
for (int i = 1; i <= (N); ++i) {
for (int j = 1; j <= (m); ++j)
if (c[a[i].x][j]) {
if (b[j][a[i].y]) {
printf("%d\n", a[i].v);
return 0;
}
b[j][a[i].y] = b[a[i].y][j] = true;
}
c[a[i].x][a[i].y] = true;
}
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
You are given two integers n and k.
You need to construct k regular polygons having same [circumcircle](https://en.wikipedia.org/wiki/Circumscribed_circle), with distinct number of sides l between 3 and n.
<image> Illustration for the first example.
You can rotate them to minimize the total number of distinct points on the circle. Find the minimum number of such points.
Input
The only line of input contains two integers n and k (3 β€ n β€ 10^{6}, 1 β€ k β€ n-2), the maximum number of sides of a polygon and the number of polygons to construct, respectively.
Output
Print a single integer β the minimum number of points required for k polygons.
Examples
Input
6 2
Output
6
Input
200 50
Output
708
Note
In the first example, we have n = 6 and k = 2. So, we have 4 polygons with number of sides 3, 4, 5 and 6 to choose from and if we choose the triangle and the hexagon, then we can arrange them as shown in the picture in the statement.
Hence, the minimum number of points required on the circle is 6, which is also the minimum overall possible sets.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int INFi = 1e9 + 5;
const int maxN = 1e6 + 5;
const int md = 998244353;
const long long INF = 2e18;
double getTime() { return clock() / (double)CLOCKS_PER_SEC; }
int phi[maxN];
int mp[maxN];
vector<int> primes;
void init() {
for (int i = 2; i < maxN; ++i) {
if (!mp[i]) {
mp[i] = i;
primes.push_back(i);
phi[i] = i - 1;
}
for (auto &p : primes) {
if (1ll * p * i >= maxN || p > mp[i]) break;
mp[p * i] = p;
if (p == mp[i]) {
phi[p * i] = phi[i] * p;
} else {
phi[p * i] = phi[i] * (p - 1);
}
}
}
}
void solve() {
int n, k;
cin >> n >> k;
if (k == 1) {
cout << "3\n";
return;
}
init();
vector<int> ord;
k++;
for (int i = 2; i <= n; ++i) ord.push_back(phi[i]);
sort((ord).begin(), (ord).end());
ord.resize(k);
cout << accumulate((ord).begin(), (ord).end(), 0ll) + 1;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int tests = 1;
for (int _ = 0; _ < (tests); ++_) {
solve();
}
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Petya and Vasya decided to play a game. They have n cards (n is an even number). A single integer is written on each card.
Before the game Petya will choose an integer and after that Vasya will choose another integer (different from the number that Petya chose). During the game each player takes all the cards with number he chose. For example, if Petya chose number 5 before the game he will take all cards on which 5 is written and if Vasya chose number 10 before the game he will take all cards on which 10 is written.
The game is considered fair if Petya and Vasya can take all n cards, and the number of cards each player gets is the same.
Determine whether Petya and Vasya can choose integer numbers before the game so that the game is fair.
Input
The first line contains a single integer n (2 β€ n β€ 100) β number of cards. It is guaranteed that n is an even number.
The following n lines contain a sequence of integers a1, a2, ..., an (one integer per line, 1 β€ ai β€ 100) β numbers written on the n cards.
Output
If it is impossible for Petya and Vasya to choose numbers in such a way that the game will be fair, print "NO" (without quotes) in the first line. In this case you should not print anything more.
In the other case print "YES" (without quotes) in the first line. In the second line print two distinct integers β number that Petya should choose and the number that Vasya should choose to make the game fair. If there are several solutions, print any of them.
Examples
Input
4
11
27
27
11
Output
YES
11 27
Input
2
6
6
Output
NO
Input
6
10
20
30
20
10
20
Output
NO
Input
6
1
1
2
2
3
3
Output
NO
Note
In the first example the game will be fair if, for example, Petya chooses number 11, and Vasya chooses number 27. Then the will take all cards β Petya will take cards 1 and 4, and Vasya will take cards 2 and 3. Thus, each of them will take exactly two cards.
In the second example fair game is impossible because the numbers written on the cards are equal, but the numbers that Petya and Vasya should choose should be distinct.
In the third example it is impossible to take all cards. Petya and Vasya can take at most five cards β for example, Petya can choose number 10 and Vasya can choose number 20. But for the game to be fair it is necessary to take 6 cards.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int i, j = 0, k = 0, x, y, n, a[100];
cin >> n;
for (i = 0; i < n; i++) {
cin >> a[i];
}
x = a[0];
for (i = 1; i < n; i++) {
if (a[i] == x)
continue;
else {
y = a[i];
break;
}
}
for (i = 0; i < n; i++) {
if (a[i] == x)
j++;
else if (a[i] == y)
k++;
}
if (j == k and (j + k == n)) {
cout << "YES" << endl;
cout << x << " " << y;
} else
cout << "NO" << endl;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Unlike Knights of a Round Table, Knights of a Polygonal Table deprived of nobility and happy to kill each other. But each knight has some power and a knight can kill another knight if and only if his power is greater than the power of victim. However, even such a knight will torment his conscience, so he can kill no more than k other knights. Also, each knight has some number of coins. After a kill, a knight can pick up all victim's coins.
Now each knight ponders: how many coins he can have if only he kills other knights?
You should answer this question for each knight.
Input
The first line contains two integers n and k (1 β€ n β€ 10^5, 0 β€ k β€ min(n-1,10)) β the number of knights and the number k from the statement.
The second line contains n integers p_1, p_2 ,β¦,p_n (1 β€ p_i β€ 10^9) β powers of the knights. All p_i are distinct.
The third line contains n integers c_1, c_2 ,β¦,c_n (0 β€ c_i β€ 10^9) β the number of coins each knight has.
Output
Print n integers β the maximum number of coins each knight can have it only he kills other knights.
Examples
Input
4 2
4 5 9 7
1 2 11 33
Output
1 3 46 36
Input
5 1
1 2 3 4 5
1 2 3 4 5
Output
1 3 5 7 9
Input
1 0
2
3
Output
3
Note
Consider the first example.
* The first knight is the weakest, so he can't kill anyone. That leaves him with the only coin he initially has.
* The second knight can kill the first knight and add his coin to his own two.
* The third knight is the strongest, but he can't kill more than k = 2 other knights. It is optimal to kill the second and the fourth knights: 2+11+33 = 46.
* The fourth knight should kill the first and the second knights: 33+1+2 = 36.
In the second example the first knight can't kill anyone, while all the others should kill the one with the index less by one than their own.
In the third example there is only one knight, so he can't kill anyone.
### Response
```cpp
#include <bits/stdc++.h>
const int MAXN = 1e5 + 5;
std::map<int, int> set;
long long ret[MAXN]{};
int k, n;
struct Knight {
int c, i, p;
} kni[MAXN];
int main() {
scanf(" %d%d", &n, &k);
for (int i = 0; i < n; ++i) scanf("%d", &kni[i].p);
for (int i = 0; i < n; ++i) scanf("%d", &kni[i].c);
for (int i = 0; i < n; ++i) kni[i].i = i;
std::sort(kni, kni + n,
[](const Knight& lft, const Knight& rgt) { return lft.p < rgt.p; });
long long sum = 0LL;
for (int i = 0; i < n; ++i) {
++set[kni[i].c];
sum += kni[i].c;
ret[kni[i].i] = sum;
if (i >= k) {
int min = set.begin()->first;
if (!--set[min]) set.erase(min);
sum -= min;
}
}
for (int i = 0; i < n; ++i) printf("%lld\n", ret[i]);
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: <https://codeforces.com/blog/entry/45307>.
There is a city in which Dixit lives. In the city, there are n houses. There is exactly one directed road between every pair of houses. For example, consider two houses A and B, then there is a directed road either from A to B or from B to A but not both. The number of roads leading to the i-th house is k_i.
Two houses A and B are bi-reachable if A is reachable from B and B is reachable from A. We say that house B is reachable from house A when there is a path from house A to house B.
Dixit wants to buy two houses in the city, that is, one for living and one for studying. Of course, he would like to travel from one house to another. So, he wants to find a pair of bi-reachable houses A and B. Among all such pairs, he wants to choose one with the maximum value of |k_A - k_B|, where k_i is the number of roads leading to the house i. If more than one optimal pair exists, any of them is suitable.
Since Dixit is busy preparing CodeCraft, can you help him find the desired pair of houses, or tell him that no such houses exist?
In the problem input, you are not given the direction of each road. You are given β for each house β only the number of incoming roads to that house (k_i).
You are allowed to ask only one type of query from the judge: give two houses A and B, and the judge answers whether B is reachable from A. There is no upper limit on the number of queries. But, you cannot ask more queries after the judge answers "Yes" to any of your queries. Also, you cannot ask the same query twice.
Once you have exhausted all your queries (or the judge responds "Yes" to any of your queries), your program must output its guess for the two houses and quit.
See the Interaction section below for more details.
Input
The first line contains a single integer n (3 β€ n β€ 500) denoting the number of houses in the city. The next line contains n space-separated integers k_1, k_2, ..., k_n (0 β€ k_i β€ n - 1), the i-th of them represents the number of incoming roads to the i-th house.
Interaction
To ask a query, print "? A B" (1 β€ A,B β€ N, Aβ B). The judge will respond "Yes" if house B is reachable from house A, or "No" otherwise.
To output the final answer, print "! A B", where A and B are bi-reachable with the maximum possible value of |k_A - k_B|. If there does not exist such pair of houses A and B, output "! 0 0".
After outputting the final answer, your program must terminate immediately, otherwise you will receive Wrong Answer verdict.
You cannot ask the same query twice. There is no upper limit to the number of queries you ask, but, you cannot ask more queries after the judge answers "Yes" to any of your queries. Your program must now output the final answer ("! A B" or "! 0 0") and terminate.
If you ask a query in incorrect format or repeat a previous query, you will get Wrong Answer verdict.
After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get the Idleness limit exceeded error. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Examples
Input
3
1 1 1
Yes
Output
? 1 2
! 1 2
Input
4
1 2 0 3
No
No
No
No
No
No
Output
? 2 1
? 1 3
? 4 1
? 2 3
? 4 2
? 4 3
! 0 0
Note
In the first sample input, we are given a city of three houses with one incoming road each. The user program asks one query: "? 1 2": asking whether we can reach from house 1 to house 2. The judge responds with "Yes". The user program now concludes that this is sufficient information to determine the correct answer. So, it outputs "! 1 2" and quits.
In the second sample input, the user program queries for six different pairs of houses, and finally answers "! 0 0" as it is convinced that no two houses as desired in the question exist in this city.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template<typename A, typename B>
string to_string(pair<A, B> p);
template<typename A, typename B, typename C>
string to_string(tuple<A, B, C> p);
template<typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p);
string to_string(const string &s) {
return '"' + s + '"';
}
string to_string(const char *s) {
return to_string((string) s);
}
string to_string(bool b) {
return (b ? "true" : "false");
}
string to_string(vector<bool> v) {
bool first = true;
string res = "{";
for (int i = 0; i < static_cast<int>(v.size()); i++) {
if (!first) {
res += ", ";
}
first = false;
res += to_string(v[i]);
}
res += "}";
return res;
}
template<size_t N>
string to_string(bitset<N> v) {
string res = "";
for (size_t i = 0; i < N; i++) {
res += static_cast<char>('0' + v[i]);
}
return res;
}
template<typename A>
string to_string(A v) {
bool first = true;
string res = "{";
for (const auto &x : v) {
if (!first) {
res += ", ";
}
first = false;
res += to_string(x);
}
res += "}";
return res;
}
template<typename A, typename B>
string to_string(pair<A, B> p) {
return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}
template<typename A, typename B, typename C>
string to_string(tuple<A, B, C> p) {
return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", "
+ to_string(get<2>(p)) + ")";
}
template<typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p) {
return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", "
+ to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")";
}
void dbg_out() {
cout << endl;
}
template<typename Head, typename ... Tail>
void dbg_out(Head H, Tail ... T) {
cout << " " << to_string(H);
dbg_out(T...);
}
#ifndef ONLINE_JUDGE
#define dbg(...) cout << "[" << #__VA_ARGS__ << "]:", dbg_out(__VA_ARGS__)
#else
#define dbg(...) ;
#endif
#define import ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define read(x) cin >> x
#define out(x) cout << x
#define readInt(x) scanf("%d",&x)
#define readLong(x) scanf("%lld",&x)
#define readDouble(x) scanf("%Lf",&x)
#define readString(x) scanf("%s",&x)
#define outInt(x) printf("%d",x)
#define outLong(x) printf("%lld",x)
#define outDouble(x) printf("%Lf",x)
#define outString(x) printf("%s",x)
#define outLine(x) cout << x << endl
#define readArr(x,size) for(int i=0;i<size;i++)read(x[i])
#define outArr(x,size) for(int i=0;i<size;i++){cout << x[i] << " ";}out(endl)
#define ll long long
#define ld long double
#define pii pair<int,int>
#define len(s) (int)(s.length())
#define bitCnt(msk) __builtin_popcount(msk)
#define ff first
#define ss second
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int mrand(int a) {
return rng() % a;
}
void test_case() {
int n;
cin >> n;
vector<pair<int,int>>deg(n);
for(int i=0;i<n;i++){
int x;
cin >> x;
deg[i]=make_pair(x,i);
}
sort(deg.begin(),deg.end());
vector<pair<int,pair<int,int>>>arr(n*(n-1)/2);
int idx=0;
for(int c=n-1;c>=0;c--) {
int i=deg[c].second;
for(int o=0;o<c;o++) {
int j=deg[o].second;
pair<int,pair<int,int>>zz;
zz.first=-deg[c].first+deg[o].first;
zz.second=make_pair(i, j);
arr[idx++]=zz;
}
}
sort(arr.begin(),arr.end());
for(int c=0;c<arr.size();c++) {
int i=arr[c].second.first,j=arr[c].second.second;
cout << "? " << i+1 << " " << j+1 << endl;
string s;
cin >> s;
if(s[0]=='Y') {
cout << "! " << i+1 << " " << j+1 << endl;
return;
}
}
cout << "! 0 0" << endl;
}
int main() {
import;
// int tc = 1;
// readInt(tc);
// while (tc--)
test_case();
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Just in case somebody missed it: this winter is totally cold in Nvodsk! It is so cold that one gets funny thoughts. For example, let's say there are strings with the length exactly n, based on the alphabet of size m. Any its substring with length equal to k is a palindrome. How many such strings exist? Your task is to find their quantity modulo 1000000007 (109 + 7). Be careful and don't miss a string or two!
Let us remind you that a string is a palindrome if it can be read the same way in either direction, from the left to the right and from the right to the left.
Input
The first and only line contains three integers: n, m and k (1 β€ n, m, k β€ 2000).
Output
Print a single integer β the number of strings of the described type modulo 1000000007 (109 + 7).
Examples
Input
1 1 1
Output
1
Input
5 2 4
Output
2
Note
In the first sample only one string is valid: "a" (let's denote the only letter of our alphabet as "a").
In the second sample (if we denote the alphabet letters as "a" and "b") the following strings are valid: "aaaaa" and "bbbbb".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int power(long long int a, long long int b, long long int mod) {
if (b == 1) return a % mod;
if (b == 0) return 1;
long long int z = power((a * a) % mod, b / 2, mod);
if (b % 2) return (z * a) % mod;
return z % mod;
}
int main() {
long long int n, m, k;
cin >> n >> m >> k;
long long int mod = 1000000007;
if (k == 1 || k > n)
cout << power(m, n, mod) << endl;
else if (k == n)
cout << power(m, (n + 1) / 2, mod) << endl;
else if (k % 2 == 0)
cout << m % mod << endl;
else
cout << (m * m) % mod << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Nothing is eternal in the world, Kostya understood it on the 7-th of January when he saw partially dead four-color garland.
Now he has a goal to replace dead light bulbs, however he doesn't know how many light bulbs for each color are required. It is guaranteed that for each of four colors at least one light is working.
It is known that the garland contains light bulbs of four colors: red, blue, yellow and green. The garland is made as follows: if you take any four consecutive light bulbs then there will not be light bulbs with the same color among them. For example, the garland can look like "RYBGRYBGRY", "YBGRYBGRYBG", "BGRYB", but can not look like "BGRYG", "YBGRYBYGR" or "BGYBGY". Letters denote colors: 'R' β red, 'B' β blue, 'Y' β yellow, 'G' β green.
Using the information that for each color at least one light bulb still works count the number of dead light bulbs of each four colors.
Input
The first and the only line contains the string s (4 β€ |s| β€ 100), which describes the garland, the i-th symbol of which describes the color of the i-th light bulb in the order from the beginning of garland:
* 'R' β the light bulb is red,
* 'B' β the light bulb is blue,
* 'Y' β the light bulb is yellow,
* 'G' β the light bulb is green,
* '!' β the light bulb is dead.
The string s can not contain other symbols except those five which were described.
It is guaranteed that in the given string at least once there is each of four letters 'R', 'B', 'Y' and 'G'.
It is guaranteed that the string s is correct garland with some blown light bulbs, it means that for example the line "GRBY!!!B" can not be in the input data.
Output
In the only line print four integers kr, kb, ky, kg β the number of dead light bulbs of red, blue, yellow and green colors accordingly.
Examples
Input
RYBGRYBGR
Output
0 0 0 0
Input
!RGYB
Output
0 1 0 0
Input
!!!!YGRB
Output
1 1 1 1
Input
!GB!RG!Y!
Output
2 1 1 0
Note
In the first example there are no dead light bulbs.
In the second example it is obvious that one blue bulb is blown, because it could not be light bulbs of other colors on its place according to the statements.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
int sz = s.size();
vector<int> cnt(4, 0);
vector<char> c(4);
int r, g, y, b;
for (int a = 0; a < 4; a++)
for (int i = a; i < sz; i = i + 4)
if (s[i] != '!')
c[a] = s[i];
else
cnt[a] += 1;
for (int i = 0; i < 4; i++) {
if (c[i] == 'R')
r = cnt[i];
else if (c[i] == 'B')
b = cnt[i];
else if (c[i] == 'Y')
y = cnt[i];
else
g = cnt[i];
}
cout << r << " " << b << " " << y << " " << g;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Find the price of a product before tax such that, when the consumption tax rate is 8 percent and 10 percent, the amount of consumption tax levied on it is A yen and B yen, respectively. (Yen is the currency of Japan.)
Here, the price before tax must be a positive integer, and the amount of consumption tax is rounded down to the nearest integer.
If multiple prices satisfy the condition, print the lowest such price; if no price satisfies the condition, print `-1`.
Constraints
* 1 \leq A \leq B \leq 100
* A and B are integers.
Input
Input is given from Standard Input in the following format:
A B
Output
If there is a price that satisfies the condition, print an integer representing the lowest such price; otherwise, print `-1`.
Examples
Input
2 2
Output
25
Input
8 10
Output
100
Input
19 99
Output
-1
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int a,b;
int main()
{
cin>>a>>b;
for(int i=1;i<=10000;i++)
{
if(i*2/25==a&&i/10==b)
{
cout<<i;
return 0;
}
}
cout<<-1;
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends.
Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws n sticks in a row. After that the players take turns crossing out exactly k sticks from left or right in each turn. Sasha moves first, because he is the inventor of the game. If there are less than k sticks on the paper before some turn, the game ends. Sasha wins if he makes strictly more moves than Lena. Sasha wants to know the result of the game before playing, you are to help him.
Input
The first line contains two integers n and k (1 β€ n, k β€ 1018, k β€ n) β the number of sticks drawn by Sasha and the number k β the number of sticks to be crossed out on each turn.
Output
If Sasha wins, print "YES" (without quotes), otherwise print "NO" (without quotes).
You can print each letter in arbitrary case (upper of lower).
Examples
Input
1 1
Output
YES
Input
10 4
Output
NO
Note
In the first example Sasha crosses out 1 stick, and then there are no sticks. So Lena can't make a move, and Sasha wins.
In the second example Sasha crosses out 4 sticks, then Lena crosses out 4 sticks, and after that there are only 2 sticks left. Sasha can't make a move. The players make equal number of moves, so Sasha doesn't win.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int mod = 1e9 + 7;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long int n, k;
cin >> n >> k;
long long int ans = (n / k);
if (ans % 2 == 0) {
cout << "NO"
<< "\n";
} else
cout << "YES"
<< "\n";
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
The annual college sports-ball tournament is approaching, which for trademark reasons we'll refer to as Third Month Insanity. There are a total of 2N teams participating in the tournament, numbered from 1 to 2N. The tournament lasts N rounds, with each round eliminating half the teams. The first round consists of 2N - 1 games, numbered starting from 1. In game i, team 2Β·i - 1 will play against team 2Β·i. The loser is eliminated and the winner advances to the next round (there are no ties). Each subsequent round has half as many games as the previous round, and in game i the winner of the previous round's game 2Β·i - 1 will play against the winner of the previous round's game 2Β·i.
Every year the office has a pool to see who can create the best bracket. A bracket is a set of winner predictions for every game. For games in the first round you may predict either team to win, but for games in later rounds the winner you predict must also be predicted as a winner in the previous round. Note that the bracket is fully constructed before any games are actually played. Correct predictions in the first round are worth 1 point, and correct predictions in each subsequent round are worth twice as many points as the previous, so correct predictions in the final game are worth 2N - 1 points.
For every pair of teams in the league, you have estimated the probability of each team winning if they play against each other. Now you want to construct a bracket with the maximum possible expected score.
Input
Input will begin with a line containing N (2 β€ N β€ 6).
2N lines follow, each with 2N integers. The j-th column of the i-th row indicates the percentage chance that team i will defeat team j, unless i = j, in which case the value will be 0. It is guaranteed that the i-th column of the j-th row plus the j-th column of the i-th row will add to exactly 100.
Output
Print the maximum possible expected score over all possible brackets. Your answer must be correct to within an absolute or relative error of 10 - 9.
Formally, let your answer be a, and the jury's answer be b. Your answer will be considered correct, if <image>.
Examples
Input
2
0 40 100 100
60 0 40 40
0 60 0 45
0 60 55 0
Output
1.75
Input
3
0 0 100 0 100 0 0 0
100 0 100 0 0 0 100 100
0 0 0 100 100 0 0 0
100 100 0 0 0 0 100 100
0 100 0 100 0 0 100 0
100 100 100 100 100 0 0 0
100 0 100 0 0 100 0 0
100 0 100 0 100 100 100 0
Output
12
Input
2
0 21 41 26
79 0 97 33
59 3 0 91
74 67 9 0
Output
3.141592
Note
In the first example, you should predict teams 1 and 4 to win in round 1, and team 1 to win in round 2. Recall that the winner you predict in round 2 must also be predicted as a winner in round 1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n;
double p[100][100];
double w[10][100];
double s[10][100];
vector<int> opp[10][100];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
for (int k = 1; k <= (1 << n); k += (1 << i)) {
for (int j = k; j < k + (1 << (i - 1)); j++) {
for (int m = k + (1 << (i - 1)); m < k + (1 << i); m++)
opp[i][j].push_back(m);
}
for (int j = k + (1 << (i - 1)); j < k + (1 << i); j++) {
for (int m = k; m < k + (1 << (i - 1)); m++) opp[i][j].push_back(m);
}
}
}
for (int i = 1; i <= (1 << n); i++) {
for (int j = 1; j <= (1 << n); j++) {
scanf("%lf", &p[i][j]);
p[i][j] /= (double)100;
}
}
for (int i = 1; i <= (1 << n); i++) {
w[0][i] = 1;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= (1 << n); j++) {
for (auto k : opp[i][j]) w[i][j] += w[i - 1][j] * w[i - 1][k] * p[j][k];
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= (1 << n); j++) {
for (auto k : opp[i][j])
s[i][j] =
max(s[i][j], s[i - 1][k] + s[i - 1][j] + (1 << (i - 1)) * w[i][j]);
}
}
double ans = 0;
for (int i = 1; i <= (1 << n); i++) {
ans = max(ans, s[n][i]);
}
cout << fixed << setprecision(10) << ans << "\n";
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Nikola owns a large warehouse which is illuminated by N light bulbs, numbered 1 to N. At the exit of the warehouse, there are S light switches, numbered 1 to S. Each switch swaps the on/off state for some light bulbs, so if a light bulb is off, flipping the switch turns it on, and if the light bulb is on, flipping the switch turns it off.
At the end of the day, Nikola wants to turn all the lights off. To achieve this, he will flip some of the light switches at the exit of the warehouse, but since Nikola is lazy, he wants to flip the _minimum_ number of switches required to turn all the lights off. Since Nikola was not able to calculate the minimum number of switches, he asked you to help him. During a period of D days, Nikola noted which light bulbs were off and which were on at the end of each day. He wants you to tell him the minimum number of switches he needed to flip to turn all the lights off for each of the D days or tell him that it's impossible.
Input
First line contains three integers, N, S and D (1 β€ N β€ 10^3, 1 β€ S β€ 30, 1 β€ D β€ 10^3) β representing number of light bulbs, the number of light switches, and the number of days respectively.
The next S lines contain the description of each light switch as follows: The first number in the line, C_i (1 β€ C_i β€ N), represents the number of light bulbs for which the on/off state is swapped by light switch i, the next C_i numbers (sorted in increasing order) represent the indices of those light bulbs.
The next D lines contain the description of light bulbs for each day as follows: The first number in the line, T_i (1 β€ T_i β€ N), represents the number of light bulbs which are on at the end of day i, the next T_i numbers (sorted in increasing order) represent the indices of those light bulbs.
Output
Print D lines, one for each day. In the i^{th} line, print the minimum number of switches that need to be flipped on day i, or -1 if it's impossible to turn all the lights off.
Example
Input
4 3 4
2 1 2
2 2 3
1 2
1 1
2 1 3
3 1 2 3
3 1 2 4
Output
2
2
3
-1
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize(2)
using namespace std;
const int INF = 0x3f3f3f3f;
int n, s, d;
const int mod = 1145141;
struct Bitset {
unsigned long long a[16];
inline Bitset() { memset(a, 0, sizeof(a)); }
inline void reset() { memset(a, 0, sizeof(a)); }
inline void set(int i) { a[i >> 6] |= (1ull << (i & 63)); }
inline Bitset &operator^=(const Bitset &oth) {
for (int i = 0; i < 16; i++) a[i] ^= oth.a[i];
return *this;
}
inline Bitset operator^(const Bitset &oth) const {
Bitset ret;
for (int i = 0; i < 16; i++) ret.a[i] = a[i] ^ oth.a[i];
return ret;
}
inline int getval() const {
unsigned long long ret = 0;
for (int i = 0; i < 16; i++) {
ret = (ret + a[i] % mod * (i + 1) * (i + 1) % mod) % mod;
}
return ret;
}
inline bool operator==(const Bitset &oth) const {
for (int i = 0; i < 16; i++)
if (a[i] != oth.a[i]) return false;
return true;
}
};
namespace Hash_Table {
int head[1145141] = {0}, cnt, nxt[(1 << 20) + 1] = {0}, val[(1 << 20) + 1];
Bitset bs[(1 << 20) + 1];
void insert(Bitset NOW, int VAL) {
int valu = NOW.getval();
for (int now = head[valu]; now; now = nxt[now]) {
if (bs[now] == NOW) {
val[now] = min(val[now], VAL);
return;
}
}
++cnt;
val[cnt] = VAL;
bs[cnt] = NOW;
nxt[cnt] = head[valu];
head[valu] = cnt;
}
int query(Bitset NOW) {
int valu = NOW.getval();
for (int now = head[valu]; now; now = nxt[now]) {
if (bs[now] == NOW) {
return val[now];
}
}
return INF;
}
} // namespace Hash_Table
Bitset swi[31];
int bit_count[1 << 20];
Bitset full;
Bitset second_part[1 << 20];
int second_val[1 << 20];
int main() {
cin >> n >> s >> d;
for (int i = 1; i <= n; ++i) full.set(i);
for (int i = 0; i < 1 << 20; ++i) {
if (i) bit_count[i] = bit_count[i & (i - 1)] + 1;
}
for (int i = 0; i < s; ++i) {
int c;
scanf("%d", &c);
while (c--) {
int a;
scanf("%d", &a);
swi[i].set(a);
}
}
int two = min(10, s / 2), one = s - two;
for (int i = 0; i < 1 << one; ++i) {
Bitset now;
for (int j = 0; j < s; ++j) {
if ((i >> j) & 1) {
now ^= swi[j];
}
}
Hash_Table::insert(now, bit_count[i]);
}
for (int i = 0; i < 1 << two; ++i) {
Bitset now;
for (int j = 0; j < s; ++j) {
if ((i >> j) & 1) {
now ^= swi[j + one];
}
}
second_part[i] = now;
second_val[i] = bit_count[i];
}
for (int i = 1; i <= d; ++i) {
Bitset query;
int c;
scanf("%d", &c);
while (c--) {
int a;
scanf("%d", &a);
query.set(a);
}
int rest = INF;
for (int mask = 0; mask < 1 << two; ++mask) {
rest = min(rest, second_val[mask] +
Hash_Table::query(query ^ second_part[mask]));
}
if (rest >= INF) rest = -1;
printf("%d\n", rest);
}
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
In a far away kingdom lives a very greedy king. To defend his land, he built n guard towers. Apart from the towers the kingdom has two armies, each headed by a tyrannical and narcissistic general. The generals can't stand each other, specifically, they will never let soldiers of two armies be present in one tower.
During defence operations to manage a guard tower a general has to send part of his army to that tower. Each general asks some fee from the king for managing towers. As they live in a really far away kingdom, each general evaluates his fee in the following weird manner: he finds two remotest (the most distant) towers, where the soldiers of his army are situated and asks for the fee equal to the distance. Each tower is represented by a point on the plane with coordinates (x, y), and the distance between two points with coordinates (x1, y1) and (x2, y2) is determined in this kingdom as |x1 - x2| + |y1 - y2|.
The greedy king was not exactly satisfied with such a requirement from the generals, that's why he only agreed to pay one fee for two generals, equal to the maximum of two demanded fees. However, the king is still green with greed, and among all the ways to arrange towers between armies, he wants to find the cheapest one. Each tower should be occupied by soldiers of exactly one army.
He hired you for that. You should find the minimum amount of money that will be enough to pay the fees. And as the king is also very scrupulous, you should also count the number of arrangements that will cost the same amount of money. As their number can be quite large, it is enough for the king to know it as a remainder from dividing by 109 + 7.
Two arrangements are distinct if the sets of towers occupied by soldiers of the first general are distinct.
Input
The first line contains an integer n (2 β€ n β€ 5000), n is the number of guard towers. Then follow n lines, each of which contains two integers x, y β the coordinates of the i-th tower (0 β€ x, y β€ 5000). No two towers are present at one point.
Pretest 6 is one of the maximal tests for this problem.
Output
Print on the first line the smallest possible amount of money that will be enough to pay fees to the generals.
Print on the second line the number of arrangements that can be carried out using the smallest possible fee. This number should be calculated modulo 1000000007 (109 + 7).
Examples
Input
2
0 0
1 1
Output
0
2
Input
4
0 0
0 1
1 0
1 1
Output
1
4
Input
3
0 0
1000 1000
5000 5000
Output
2000
2
Note
In the first example there are only two towers, the distance between which is equal to 2. If we give both towers to one general, then we well have to pay 2 units of money. If each general receives a tower to manage, to fee will be equal to 0. That is the smallest possible fee. As you can easily see, we can obtain it in two ways.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, cnt, a[5001], b[5001], vis[5001];
int dfs(int x, int mid, int type) {
vis[x] = type;
for (int i = 1; i <= n; i++)
if (i != x && abs(a[i] - a[x]) + abs(b[i] - b[x]) > mid) {
if (vis[i] == -1)
if (!dfs(i, mid, type ^ 1)) return false;
if (vis[x] == vis[i]) return false;
}
return true;
}
int chk(int x) {
memset(vis, -1, sizeof(vis));
for (int i = 1; i <= n; i++)
if (vis[i] == -1)
if (!dfs(i, x, 0)) return false;
return true;
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d%d", &a[i], &b[i]);
int l = 0, r = 10000;
while (l < r) {
int mid = (l + r) >> 1;
if (chk(mid))
r = mid;
else
l = mid + 1;
}
memset(vis, -1, sizeof(vis));
for (int i = 1; i <= n; i++)
if (vis[i] == -1) dfs(i, r, 0), cnt++;
int ans = 1;
for (int i = 1; i <= cnt; i++) ans = (ans << 1) % 1000000007;
printf("%d\n%d\n", r, ans);
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
The only difference between easy and hard versions is the constraints.
Polycarp has to write a coursework. The coursework consists of m pages.
Polycarp also has n cups of coffee. The coffee in the i-th cup has a_i caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups in any order. Polycarp drinks each cup instantly and completely (i.e. he cannot split any cup into several days).
Surely, courseworks are not usually being written in a single day (in a perfect world of Berland, at least). Some of them require multiple days of hard work.
Let's consider some day of Polycarp's work. Consider Polycarp drinks k cups of coffee during this day and caffeine dosages of cups Polycarp drink during this day are a_{i_1}, a_{i_2}, ..., a_{i_k}. Then the first cup he drinks gives him energy to write a_{i_1} pages of coursework, the second cup gives him energy to write max(0, a_{i_2} - 1) pages, the third cup gives him energy to write max(0, a_{i_3} - 2) pages, ..., the k-th cup gives him energy to write max(0, a_{i_k} - k + 1) pages.
If Polycarp doesn't drink coffee during some day, he cannot write coursework at all that day.
Polycarp has to finish his coursework as soon as possible (spend the minimum number of days to do it). Your task is to find out this number of days or say that it is impossible.
Input
The first line of the input contains two integers n and m (1 β€ n β€ 100, 1 β€ m β€ 10^4) β the number of cups of coffee and the number of pages in the coursework.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 100), where a_i is the caffeine dosage of coffee in the i-th cup.
Output
If it is impossible to write the coursework, print -1. Otherwise print the minimum number of days Polycarp needs to do it.
Examples
Input
5 8
2 3 1 1 2
Output
4
Input
7 10
1 3 4 2 1 4 2
Output
2
Input
5 15
5 5 5 5 5
Output
1
Input
5 16
5 5 5 5 5
Output
2
Input
5 26
5 5 5 5 5
Output
-1
Note
In the first example Polycarp can drink fourth cup during first day (and write 1 page), first and second cups during second day (and write 2 + (3 - 1) = 4 pages), fifth cup during the third day (and write 2 pages) and third cup during the fourth day (and write 1 page) so the answer is 4. It is obvious that there is no way to write the coursework in three or less days in this test.
In the second example Polycarp can drink third, fourth and second cups during first day (and write 4 + (2 - 1) + (3 - 2) = 6 pages) and sixth cup during second day (and write 4 pages) so the answer is 2. It is obvious that Polycarp cannot write the whole coursework in one day in this test.
In the third example Polycarp can drink all cups of coffee during first day and write 5 + (5 - 1) + (5 - 2) + (5 - 3) + (5 - 4) = 15 pages of coursework.
In the fourth example Polycarp cannot drink all cups during first day and should drink one of them during the second day. So during first day he will write 5 + (5 - 1) + (5 - 2) + (5 - 3) = 14 pages of coursework and during second day he will write 5 pages of coursework. This is enough to complete it.
In the fifth example Polycarp cannot write the whole coursework at all, even if he will drink one cup of coffee during each day, so the answer is -1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long int N = 1e6;
long long int n, m;
vector<long long int> v(N);
bool check(long long int days) {
long long int pages = 0, k = 0;
for (long long int i = 0, j = 0; j < n; i++, j++) {
pages += max(0ll, v[j] - k);
if (i + 1 == days) i = -1, k++;
}
return pages >= m;
}
int32_t main() {
scanf("%lld", &n);
scanf("%lld", &m);
long long int sum = 0;
for (long long int i = 0; i < n; ++i) {
scanf("%lld", &v[i]);
sum += v[i];
}
if (sum < m) {
printf("-1");
return 0;
}
sort(v.begin(), v.end(), greater<long long int>());
long long int ans = n;
long long int low = 1;
long long int high = n;
while (low <= high) {
long long int mid = (low + high) / 2;
if (check(mid)) {
ans = min(ans, mid);
high = mid - 1;
} else {
low = mid + 1;
}
}
printf("%lld", ans);
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
You are given two arrays a and b of positive integers, with length n and m respectively.
Let c be an n Γ m matrix, where c_{i,j} = a_i β
b_j.
You need to find a subrectangle of the matrix c such that the sum of its elements is at most x, and its area (the total number of elements) is the largest possible.
Formally, you need to find the largest number s such that it is possible to choose integers x_1, x_2, y_1, y_2 subject to 1 β€ x_1 β€ x_2 β€ n, 1 β€ y_1 β€ y_2 β€ m, (x_2 - x_1 + 1) Γ (y_2 - y_1 + 1) = s, and $$$β_{i=x_1}^{x_2}{β_{j=y_1}^{y_2}{c_{i,j}}} β€ x.$$$
Input
The first line contains two integers n and m (1 β€ n, m β€ 2000).
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 2000).
The third line contains m integers b_1, b_2, β¦, b_m (1 β€ b_i β€ 2000).
The fourth line contains a single integer x (1 β€ x β€ 2 β
10^{9}).
Output
If it is possible to choose four integers x_1, x_2, y_1, y_2 such that 1 β€ x_1 β€ x_2 β€ n, 1 β€ y_1 β€ y_2 β€ m, and β_{i=x_1}^{x_2}{β_{j=y_1}^{y_2}{c_{i,j}}} β€ x, output the largest value of (x_2 - x_1 + 1) Γ (y_2 - y_1 + 1) among all such quadruplets, otherwise output 0.
Examples
Input
3 3
1 2 3
1 2 3
9
Output
4
Input
5 1
5 4 2 4 5
2
5
Output
1
Note
Matrix from the first sample and the chosen subrectangle (of blue color):
<image>
Matrix from the second sample and the chosen subrectangle (of blue color):
<image>
### Response
```cpp
#include <bits/stdc++.h>
long long int a[2100], b[2100], n, i, j, m, k, d[10000000], f[10000000], x, y,
z = 0;
int main() {
while (scanf("%lld %lld", &n, &m) != EOF) {
for (i = 1; i <= n; i++) {
scanf("%lld", &a[i]);
}
for (i = 1; i <= m; i++) {
scanf("%lld", &b[i]);
}
scanf("%lld", &k);
for (i = 1; i <= n; i++) {
a[i] = a[i] + a[i - 1];
}
for (i = 1; i <= m; i++) {
b[i] = b[i] + b[i - 1];
}
for (i = 1; i <= n; i++) {
d[i] = 300000000;
for (j = 1; j <= n; j++) {
if (i + j - 1 > n) {
break;
}
x = a[i + j - 1] - a[j - 1];
if (x < d[i]) {
d[i] = x;
}
}
}
for (i = 1; i <= m; i++) {
f[i] = 300000000;
for (j = 1; j <= m; j++) {
if (i + j - 1 > m) {
break;
}
y = b[i + j - 1] - b[j - 1];
if (y < f[i]) {
f[i] = y;
}
}
}
for (i = 1; i <= n; i++) {
for (j = 1; j <= m; j++) {
if (d[i] * f[j] <= k) {
if (i * j * 1 > z) {
z = i * j * 1;
}
if (i * j * 1 <= z) {
continue;
}
}
}
}
printf("%lld", z);
}
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Being bored of exploring the Moon over and over again Wall-B decided to explore something he is made of β binary numbers. He took a binary number and decided to count how many times different substrings of length two appeared. He stored those values in c_{00}, c_{01}, c_{10} and c_{11}, representing how many times substrings 00, 01, 10 and 11 appear in the number respectively. For example:
10111100 β c_{00} = 1, \ c_{01} = 1,\ c_{10} = 2,\ c_{11} = 3
10000 β c_{00} = 3,\ c_{01} = 0,\ c_{10} = 1,\ c_{11} = 0
10101001 β c_{00} = 1,\ c_{01} = 3,\ c_{10} = 3,\ c_{11} = 0
1 β c_{00} = 0,\ c_{01} = 0,\ c_{10} = 0,\ c_{11} = 0
Wall-B noticed that there can be multiple binary numbers satisfying the same c_{00}, c_{01}, c_{10} and c_{11} constraints. Because of that he wanted to count how many binary numbers satisfy the constraints c_{xy} given the interval [A, B]. Unfortunately, his processing power wasn't strong enough to handle large intervals he was curious about. Can you help him? Since this number can be large print it modulo 10^9 + 7.
Input
First two lines contain two positive binary numbers A and B (1 β€ A β€ B < 2^{100 000}), representing the start and the end of the interval respectively. Binary numbers A and B have no leading zeroes.
Next four lines contain decimal numbers c_{00}, c_{01}, c_{10} and c_{11} (0 β€ c_{00}, c_{01}, c_{10}, c_{11} β€ 100 000) representing the count of two-digit substrings 00, 01, 10 and 11 respectively.
Output
Output one integer number representing how many binary numbers in the interval [A, B] satisfy the constraints mod 10^9 + 7.
Examples
Input
10
1001
0
0
1
1
Output
1
Input
10
10001
1
2
3
4
Output
0
Note
Example 1: The binary numbers in the interval [10,1001] are 10,11,100,101,110,111,1000,1001. Only number 110 satisfies the constraints: c_{00} = 0, c_{01} = 0, c_{10} = 1, c_{11} = 1.
Example 2: No number in the interval satisfies the constraints
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline int read() {
register int p = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
p = p * 10 + ch - '0';
ch = getchar();
}
return p * f;
}
const int maxn = 100005;
const int mod = 1000000007;
long long qpow(long long a, long long b) {
long long res = 1;
while (b) {
if (b & 1) res = res * a % mod;
a = a * a % mod;
b >>= 1;
}
return res;
}
long long fac[maxn], invfac[maxn];
inline long long C(long long n, long long m) {
if (n == -1 && m == -1)
return 1;
else if (n < 0 || m < 0)
return 0;
if (n < m) return 0;
return fac[n] * invfac[n - m] % mod * invfac[m] % mod;
}
void init(int n) {
fac[0] = 1;
for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % mod;
invfac[n] = qpow(fac[n], mod - 2);
for (int i = n - 1; i >= 0; i--) invfac[i] = invfac[i + 1] * (i + 1) % mod;
}
long long solve(int n, int a, int b, int c, int d) {
if (n <= 1) return (a == 0 && b == 0 && c == 0 && d == 0);
int seg1, seg0, num1, num0;
if (b == c) {
seg1 = b + 1;
seg0 = b;
} else if (c == b + 1) {
seg1 = seg0 = c;
} else {
return 0;
}
num0 = a + seg0;
num1 = d + seg1;
if (num0 + num1 > n) {
return 0;
}
long long ans = C(num0 - 1, seg0 - 1) * C(num1 - 1, seg1 - 1) % mod;
return (ans + mod) % mod;
}
void jian(char *A) {
int len = strlen(A);
for (int i = len - 1; i >= 0; i--) {
if (A[i] == '1') {
A[i] = '0';
for (int j = i + 1; j < len; j++) A[j] = '1';
if (i == 0) {
for (int j = 0; j < len - 1; j++) A[j] = A[j + 1];
A[len - 1] = '\0';
}
break;
}
}
if (A[0] == '\0') A[0] = '0', A[1] = '\0';
}
long long solve0(int n, int a, int b, int c, int d) {
if (a < 0 || b < 0 || c < 0 || d < 0) return 0;
if (n <= 1) return (a == 0 && b == 0 && c == 0 && d == 0);
int seg1, seg0, num1, num0;
long long res = 0;
c--;
if (b == c) {
seg1 = b, seg0 = b + 1;
num0 = a + seg0, num1 = d + seg1;
if (num0 + num1 == n)
res = (res + C(num0 - 1, seg0 - 1) * C(num1 - 1, seg1 - 1) % mod) % mod;
} else if (c == b - 1) {
seg0 = seg1 = b;
num0 = a + seg0, num1 = d + seg1;
if (num0 + num1 == n)
res = (res + C(num0 - 1, seg0 - 1) * C(num1 - 1, seg1 - 1) % mod) % mod;
}
c++;
d--;
if (b == c) {
seg1 = b + 1, seg0 = b;
num0 = a + seg0, num1 = d + seg1;
if (num0 + num1 == n)
res = (res + C(num0 - 1, seg0 - 1) * C(num1 - 1, seg1 - 1) % mod) % mod;
} else if (b == c - 1) {
seg0 = seg1 = c;
num0 = a + seg0, num1 = d + seg1;
if (num0 + num1 == n)
res = (res + C(num0 - 1, seg0 - 1) * C(num1 - 1, seg1 - 1) % mod) % mod;
}
d++;
return res;
}
long long calc(char *A, int a, int b, int c, int d) {
if (A[0] == '0') return (a == 0 && b == 0 && c == 0 && d == 0);
int len = strlen(A);
long long ans = solve(len, a, b, c, d);
for (int i = 1; i < len; i++) {
if (A[i] == '0') {
if (A[i - 1] == '0')
b--;
else if (A[i - 1] == '1')
d--;
ans -= solve0(len - i - 1, a, b, c, d);
ans %= mod;
if (A[i - 1] == '0')
b++;
else if (A[i - 1] == '1')
d++;
}
if (A[i - 1] == '0' && A[i] == '0')
a--;
else if (A[i - 1] == '0' && A[i] == '1')
b--;
else if (A[i - 1] == '1' && A[i] == '0')
c--;
else if (A[i - 1] == '1' && A[i] == '1')
d--;
}
return ans;
}
inline bool ok(char *A, int na, int nb, int nc, int nd) {
int len = strlen(A);
int a = 0, b = 0, c = 0, d = 0;
for (int i = 0; i < len - 1; i++) {
if (A[i] == '0' && A[i + 1] == '0')
a++;
else if (A[i] == '0' && A[i + 1] == '1')
b++;
else if (A[i] == '1' && A[i + 1] == '0')
c++;
else if (A[i] == '1' && A[i + 1] == '1')
d++;
}
return (a == na && b == nb && c == nc && d == nd);
}
char A[maxn], B[maxn];
int main() {
init(maxn - 5);
scanf("%s%s", A, B);
int a = read(), b = read(), c = read(), d = read();
long long ans =
((calc(B, a, b, c, d) - calc(A, a, b, c, d)) % mod + mod) % mod;
if (ok(A, a, b, c, d)) ans++;
printf("%lld", (ans + mod) % mod);
}
``` |
### Prompt
Generate a cpp solution to the following problem:
When the river brought Gerda to the house of the Old Lady who Knew Magic, this lady decided to make Gerda her daughter. She wants Gerda to forget about Kay, so she puts all the roses from the garden underground.
Mole, who lives in this garden, now can watch the roses without going up to the surface. Typical mole is blind, but this mole was granted as special vision by the Old Lady. He can watch any underground objects on any distance, even through the obstacles and other objects. However, the quality of the picture depends on the Manhattan distance to object being observed.
Mole wants to find an optimal point to watch roses, that is such point with integer coordinates that the maximum Manhattan distance to the rose is minimum possible.
As usual, he asks you to help.
Manhattan distance between points (x1, y1, z1) and (x2, y2, z2) is defined as |x1 - x2| + |y1 - y2| + |z1 - z2|.
Input
The first line of the input contains an integer t t (1 β€ t β€ 100 000) β the number of test cases. Then follow exactly t blocks, each containing the description of exactly one test.
The first line of each block contains an integer ni (1 β€ ni β€ 100 000) β the number of roses in the test. Then follow ni lines, containing three integers each β the coordinates of the corresponding rose. Note that two or more roses may share the same position.
It's guaranteed that the sum of all ni doesn't exceed 100 000 and all coordinates are not greater than 1018 by their absolute value.
Output
For each of t test cases print three integers β the coordinates of the optimal point to watch roses. If there are many optimal answers, print any of them.
The coordinates of the optimal point may coincide with the coordinates of any rose.
Examples
Input
1
5
0 0 4
0 0 -4
0 4 0
4 0 0
1 1 1
Output
0 0 0
Input
2
1
3 5 9
2
3 5 9
3 5 9
Output
3 5 9
3 5 9
Note
In the first sample, the maximum Manhattan distance from the point to the rose is equal to 4.
In the second sample, the maximum possible distance is 0. Note that the positions of the roses may coincide with each other and with the position of the optimal point.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int __SIZE = 1 << 18;
char ibuf[__SIZE], *iS, *iT;
template <typename T>
inline void read(T &x) {
char ch, t = 0;
x = 0;
while (!isdigit(ch = (iS == iT
? (iT = (iS = ibuf) + fread(ibuf, 1, __SIZE, stdin),
(iS == iT ? EOF : *iS++))
: *iS++)))
t |= ch == '-';
while (isdigit(ch))
x = x * 10 + (ch ^ 48),
ch = (iS == iT ? (iT = (iS = ibuf) + fread(ibuf, 1, __SIZE, stdin),
(iS == iT ? EOF : *iS++))
: *iS++);
x = t ? -x : x;
}
inline char read_alpha() {
char c = (iS == iT ? (iT = (iS = ibuf) + fread(ibuf, 1, __SIZE, stdin),
(iS == iT ? EOF : *iS++))
: *iS++);
while (!isalpha(c) && c != EOF)
c = (iS == iT ? (iT = (iS = ibuf) + fread(ibuf, 1, __SIZE, stdin),
(iS == iT ? EOF : *iS++))
: *iS++);
return c;
}
inline int read_int() {
int x;
return read(x), x;
}
inline long long read_ll() {
long long x;
return read(x), x;
}
template <typename T>
inline void chkmin(T &a, T b) {
a = a < b ? a : b;
}
template <typename T>
inline void chkmax(T &a, T b) {
a = a > b ? a : b;
}
const int MAXN = 100010;
long long x[MAXN];
long long y[MAXN];
long long z[MAXN];
long long l[5], r[5];
inline int check(long long val, int n, int tp = 0) {
for (int i = 1; i < 5; i++) l[i] = -3e18, r[i] = 3e18;
for (int i = 1; i <= n; i++) {
chkmax(l[1], x[i] + y[i] + z[i] - val);
chkmin(r[1], x[i] + y[i] + z[i] + val);
chkmax(l[2], -x[i] + y[i] + z[i] - val);
chkmin(r[2], -x[i] + y[i] + z[i] + val);
chkmax(l[3], x[i] - y[i] + z[i] - val);
chkmin(r[3], x[i] - y[i] + z[i] + val);
chkmax(l[4], x[i] + y[i] - z[i] - val);
chkmin(r[4], x[i] + y[i] - z[i] + val);
}
for (int i = 1; i < 5; i++)
if (l[i] > r[i]) return 0;
for (int rt = 0; rt < 2; rt++) {
long long tl[5], tr[5];
tl[1] = (l[1] - 3 * rt + 1) >> 1, tr[1] = (r[1] - 3 * rt) >> 1;
for (int i = 2; i < 5; i++)
tl[i] = (l[i] - rt + 1) >> 1, tr[i] = (r[i] - rt) >> 1;
int flag = 1;
for (int i = 1; i < 5; i++)
if (tl[i] > tr[i]) flag = 0;
if (!flag) continue;
long long sl = tl[2] + tl[3] + tl[4];
long long sr = tr[2] + tr[3] + tr[4];
if (tl[1] <= sr && sl <= tr[1]) {
if (tp) {
long long a = tl[2], b = tl[3], c = tl[4], lim = tl[1];
if (a + b + c < lim) a += min(tr[2] - tl[2], lim - a - b - c);
if (a + b + c < lim) b += min(tr[3] - tl[3], lim - a - b - c);
if (a + b + c < lim) c += min(tr[4] - tl[4], lim - a - b - c);
printf("%lld %lld %lld\n", b + c + rt, a + c + rt, a + b + rt);
}
return 1;
}
}
return 0;
}
int main() {
int Cases = read_int();
while (Cases--) {
int n = read_int();
for (int i = 1; i <= n; i++)
x[i] = read_ll(), y[i] = read_ll(), z[i] = read_ll();
long long l = 0, r = 3e18, res;
while (l <= r) {
long long mid = (l + r) >> 1;
if (check(mid, n))
res = mid, r = mid - 1;
else
l = mid + 1;
}
check(res, n, 1);
}
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
There is a rectangular grid of size n Γ m. Each cell has a number written on it; the number on the cell (i, j) is a_{i, j}. Your task is to calculate the number of paths from the upper-left cell (1, 1) to the bottom-right cell (n, m) meeting the following constraints:
* You can move to the right or to the bottom only. Formally, from the cell (i, j) you may move to the cell (i, j + 1) or to the cell (i + 1, j). The target cell can't be outside of the grid.
* The xor of all the numbers on the path from the cell (1, 1) to the cell (n, m) must be equal to k (xor operation is the bitwise exclusive OR, it is represented as '^' in Java or C++ and "xor" in Pascal).
Find the number of such paths in the given grid.
Input
The first line of the input contains three integers n, m and k (1 β€ n, m β€ 20, 0 β€ k β€ 10^{18}) β the height and the width of the grid, and the number k.
The next n lines contain m integers each, the j-th element in the i-th line is a_{i, j} (0 β€ a_{i, j} β€ 10^{18}).
Output
Print one integer β the number of paths from (1, 1) to (n, m) with xor sum equal to k.
Examples
Input
3 3 11
2 1 5
7 10 0
12 6 4
Output
3
Input
3 4 2
1 3 3 3
0 3 3 2
3 0 1 1
Output
5
Input
3 4 1000000000000000000
1 3 3 3
0 3 3 2
3 0 1 1
Output
0
Note
All the paths from the first example:
* (1, 1) β (2, 1) β (3, 1) β (3, 2) β (3, 3);
* (1, 1) β (2, 1) β (2, 2) β (2, 3) β (3, 3);
* (1, 1) β (1, 2) β (2, 2) β (3, 2) β (3, 3).
All the paths from the second example:
* (1, 1) β (2, 1) β (3, 1) β (3, 2) β (3, 3) β (3, 4);
* (1, 1) β (2, 1) β (2, 2) β (3, 2) β (3, 3) β (3, 4);
* (1, 1) β (2, 1) β (2, 2) β (2, 3) β (2, 4) β (3, 4);
* (1, 1) β (1, 2) β (2, 2) β (2, 3) β (3, 3) β (3, 4);
* (1, 1) β (1, 2) β (1, 3) β (2, 3) β (3, 3) β (3, 4).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long MAXN = 24;
long long a[MAXN][MAXN];
long long n, m, k, ans;
map<long long, long long> mp[MAXN][MAXN], mp2[MAXN][MAXN];
int32_t main() {
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cerr << "HELLO WORLD :)\n";
cin >> n >> m >> k;
for (long long i = 1; i <= n; i++)
for (long long j = 1; j <= m; j++) cin >> a[i][j];
mp[1][1][a[1][1]]++;
for (long long i = 1; i <= n; i++)
for (long long j = 1; j <= m; j++)
if (i + j <= n) {
for (auto u : mp[i - 1][j]) mp[i][j][u.first ^ a[i][j]] += u.second;
for (auto u : mp[i][j - 1]) mp[i][j][u.first ^ a[i][j]] += u.second;
}
mp2[n][m][a[n][m]]++;
for (long long i = n; i; i--)
for (long long j = m; j; j--)
if (i + j >= n) {
for (auto u : mp2[i + 1][j]) mp2[i][j][u.first ^ a[i][j]] += u.second;
for (auto u : mp2[i][j + 1]) mp2[i][j][u.first ^ a[i][j]] += u.second;
}
if (n == 1 || m == 1) {
long long v = 0;
for (long long i = 1; i <= n; i++)
for (long long j = 1; j <= m; j++) v ^= a[i][j];
return cout << (v == k) << '\n', false;
}
for (long long i = 1; i <= n; i++)
for (long long j = 1; j <= m; j++)
if (i + j == n) {
for (auto u : mp[i][j])
ans += mp2[i][j][k ^ u.first ^ a[i][j]] * u.second;
}
return cout << ans << '\n', false;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Takahashi has come to a party as a special guest. There are N ordinary guests at the party. The i-th ordinary guest has a power of A_i.
Takahashi has decided to perform M handshakes to increase the happiness of the party (let the current happiness be 0). A handshake will be performed as follows:
* Takahashi chooses one (ordinary) guest x for his left hand and another guest y for his right hand (x and y can be the same).
* Then, he shakes the left hand of Guest x and the right hand of Guest y simultaneously to increase the happiness by A_x+A_y.
However, Takahashi should not perform the same handshake more than once. Formally, the following condition must hold:
* Assume that, in the k-th handshake, Takahashi shakes the left hand of Guest x_k and the right hand of Guest y_k. Then, there is no pair p, q (1 \leq p < q \leq M) such that (x_p,y_p)=(x_q,y_q).
What is the maximum possible happiness after M handshakes?
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq N^2
* 1 \leq A_i \leq 10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
A_1 A_2 ... A_N
Output
Print the maximum possible happiness after M handshakes.
Examples
Input
5 3
10 14 19 34 33
Output
202
Input
9 14
1 3 5 110 24 21 34 5 3
Output
1837
Input
9 73
67597 52981 5828 66249 75177 64141 40773 79105 16076
Output
8128170
### Response
```cpp
#include <bits/stdc++.h>
#define l_ength size
const int inf = (1<<30);
const int mod = 1000000007; // 998244353
using ll = long long;
using namespace std;
int n;
ll m;
vector<ll> a;
bool judge( int x ){
ll sum = 0;
for( auto k : a ){
sum += (ll)(a.end() - lower_bound( a.begin(), a.end(), x-k ));
}
return sum >= m;
}
int main(){
cin >> n >> m;
a.resize(n);
for( auto &k : a ) cin >> k;
sort( a.begin(), a.end() );
int ok = -1;
int ng = 2*a.back()+1;
while( abs(ok-ng) > 1 ){
int mid = (ok+ng)/2;
( judge(mid) ? ok : ng ) = mid;
}
vector<ll> sum(n+1, 0);
for( int i = 0; i < n; ++i ) sum[i+1] = sum[i] + a[i];
ll cnt = 0;
ll ans = 0;
for( auto x : a ){
int t = lower_bound( a.begin(), a.end(), ok-x ) - a.begin();
ans += sum[n]-sum[t]+((n-t)*x);
cnt += n-t;
}
ans -= ok*(cnt-m);
cout << ans << endl;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0.
You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i β€ c, d β€ r_i, and swap a_c and a_d.
Calculate the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end.
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of test cases. Then the description of t testcases follow.
The first line of each test case contains three integers n, x and m (1 β€ n β€ 10^9; 1 β€ m β€ 100; 1 β€ x β€ n).
Each of next m lines contains the descriptions of the operations; the i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ n).
Output
For each test case print one integer β the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end.
Example
Input
3
6 4 3
1 6
2 3
5 5
4 1 2
2 4
1 2
3 3 2
2 3
1 2
Output
6
2
3
Note
In the first test case, it is possible to achieve a_k = 1 for every k. To do so, you may use the following operations:
1. swap a_k and a_4;
2. swap a_2 and a_2;
3. swap a_5 and a_5.
In the second test case, only k = 1 and k = 2 are possible answers. To achieve a_1 = 1, you have to swap a_1 and a_1 during the second operation. To achieve a_2 = 1, you have to swap a_1 and a_2 during the second operation.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while (t--) {
int n, m, x, k = 0;
cin >> n >> x >> m;
int s1, s2;
s1 = x, s2 = x;
while (m--) {
int l, r;
cin >> l >> r;
if (l <= s1 && r >= s1) s1 = l;
if (l <= s2 && r >= s2) s2 = r;
}
cout << s2 - s1 + 1 << "\n";
}
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
One day Vasya was going home when he saw a box lying on the road. The box can be represented as a rectangular parallelepiped. Vasya needed no time to realize that the box is special, as all its edges are parallel to the coordinate axes, one of its vertices is at point (0, 0, 0), and the opposite one is at point (x1, y1, z1). The six faces of the box contain some numbers a1, a2, ..., a6, exactly one number right in the center of each face.
<image>
The numbers are located on the box like that:
* number a1 is written on the face that lies on the ZOX plane;
* a2 is written on the face, parallel to the plane from the previous point;
* a3 is written on the face that lies on the XOY plane;
* a4 is written on the face, parallel to the plane from the previous point;
* a5 is written on the face that lies on the YOZ plane;
* a6 is written on the face, parallel to the plane from the previous point.
At the moment Vasya is looking at the box from point (x, y, z). Find the sum of numbers that Vasya sees. Note that all faces of the box are not transparent and Vasya can't see the numbers through the box. The picture contains transparent faces just to make it easier to perceive. You can consider that if Vasya is looking from point, lying on the plane of some face, than he can not see the number that is written on this face. It is enough to see the center of a face to see the corresponding number for Vasya. Also note that Vasya always reads correctly the ai numbers that he sees, independently of their rotation, angle and other factors (that is, for example, if Vasya sees some ai = 6, then he can't mistake this number for 9 and so on).
Input
The fist input line contains three space-separated integers x, y and z (|x|, |y|, |z| β€ 106) β the coordinates of Vasya's position in space. The second line contains three space-separated integers x1, y1, z1 (1 β€ x1, y1, z1 β€ 106) β the coordinates of the box's vertex that is opposite to the vertex at point (0, 0, 0). The third line contains six space-separated integers a1, a2, ..., a6 (1 β€ ai β€ 106) β the numbers that are written on the box faces.
It is guaranteed that point (x, y, z) is located strictly outside the box.
Output
Print a single integer β the sum of all numbers on the box faces that Vasya sees.
Examples
Input
2 2 2
1 1 1
1 2 3 4 5 6
Output
12
Input
0 0 10
3 2 3
1 2 3 4 5 6
Output
4
Note
The first sample corresponds to perspective, depicted on the picture. Vasya sees numbers a2 (on the top face that is the darkest), a6 (on the right face that is the lightest) and a4 (on the left visible face).
In the second sample Vasya can only see number a4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long x, y, z;
long long x1, y1, z1;
vector<long long> a(6);
long long sum = 0;
cin >> x >> y >> z;
cin >> x1 >> y1 >> z1;
for (int i = 0; i < 6; ++i) {
long long b;
cin >> b;
a[i] = b;
}
if (x < 0) {
sum += a[4];
} else if (x > x1) {
sum += a[5];
}
if (y < 0) {
sum += a[0];
} else if (y > y1) {
sum += a[1];
}
if (z < 0) {
sum += a[2];
} else if (z > z1) {
sum += a[3];
}
cout << sum;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Polycarp loves ciphers. He has invented his own cipher called repeating.
Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 β€ m β€ 10), Polycarp uses the following algorithm:
* he writes down s_1 ones,
* he writes down s_2 twice,
* he writes down s_3 three times,
* ...
* he writes down s_m m times.
For example, if s="bab" the process is: "b" β "baa" β "baabbb". So the encrypted s="bab" is "baabbb".
Given string t β the result of encryption of some string s. Your task is to decrypt it, i. e. find the string s.
Input
The first line contains integer n (1 β€ n β€ 55) β the length of the encrypted string. The second line of the input contains t β the result of encryption of some string s. It contains only lowercase Latin letters. The length of t is exactly n.
It is guaranteed that the answer to the test exists.
Output
Print such string s that after encryption it equals t.
Examples
Input
6
baabbb
Output
bab
Input
10
ooopppssss
Output
oops
Input
1
z
Output
z
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
string t;
char a[100];
cin >> t;
a[0] = t[0];
int i, j, k;
for (i = 1, j = 0, k = 2; j < n; ++i, ++k) {
j = j + k;
a[i] = t[j];
}
a[i - 1] = '\0';
cout << a;
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
You've got an n Γ m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.
A picture is a barcode if the following conditions are fulfilled:
* All pixels in each column are of the same color.
* The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y.
Input
The first line contains four space-separated integers n, m, x and y (1 β€ n, m, x, y β€ 1000; x β€ y).
Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#".
Output
In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists.
Examples
Input
6 5 1 2
##.#.
.###.
###..
#...#
.##.#
###..
Output
11
Input
2 5 1 1
#####
.....
Output
5
Note
In the first test sample the picture after changing some colors can looks as follows:
.##..
.##..
.##..
.##..
.##..
.##..
In the second test sample the picture after changing some colors can looks as follows:
.#.#.
.#.#.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int32_t INFint = 1e9;
const long long INFll = 1e18;
const long long INF = 9e18;
const long double PI = acos(-1);
long long powersOfTwo[31] = {
1, 2, 4, 8, 16, 32, 64,
128, 256, 512, 1024, 2048, 4096, 8192,
16384, 32768, 65536, 131072, 262144, 524288, 1048576,
2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728,
268435456, 536870912, 1073741824};
long long power(long long x, long long y) {
long long r = 1;
while (y > 0) {
if (y & 1) r = r * x;
y = y >> 1;
x = x * x;
}
return r;
}
long long powerMod(long long x, long long y, long long p) {
long long res = 1;
x %= p;
while (y > 0) {
if (y & 1) res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
long long gcd(long long a, long long b) {
if (!b) return a;
return gcd(b, a % b);
}
long long lcm(long long a, long long b) { return (a * b) / gcd(a, b); }
long long n, m, x, y;
long long cnt[1010][1010];
long long dp[1010][1010][2];
long long solve(long long color, long long pos, long long width) {
if (pos == m) {
if (width == 1) return 0;
if ((width - 1 >= x && width - 1 <= y)) return 0;
return 1e12;
}
long long ans = dp[pos][width][color];
if (ans != -1) return dp[x][pos][width] = ans;
if (width < x) {
ans = cnt[color ^ 1][pos] + solve(color, pos + 1, width + 1);
} else if (width < y) {
ans = min(cnt[color ^ 1][pos] + solve(color, pos + 1, width + 1),
cnt[color ^ 1][pos] + solve(color ^ 1, pos + 1, 1));
} else
ans = cnt[color ^ 1][pos] + solve(color ^ 1, pos + 1, 1);
return dp[pos][width][color] = ans;
}
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
long long tt = 1;
while (tt--) {
cin >> n >> m >> x >> y;
char arr[n][m];
for (long long i = 0; i < n; i++) {
for (long long j = 0; j < m; j++) {
cin >> arr[i][j];
}
}
for (long long j = 0; j < m; j++) {
for (long long i = 0; i < n; i++) {
if (arr[i][j] == '.') cnt[0][j]++;
if (arr[i][j] == '#') cnt[1][j]++;
}
}
memset(dp, -1, sizeof(dp));
cout << min(solve(0, 0, 1), solve(1, 0, 1));
}
cerr << "Time : " << 1000 * (long double)clock() / (long double)CLOCKS_PER_SEC
<< "ms\n";
;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do n chores. Each chore is characterized by a single parameter β its complexity. The complexity of the i-th chore equals hi.
As Petya is older, he wants to take the chores with complexity larger than some value x (hi > x) to leave to Vasya the chores with complexity less than or equal to x (hi β€ x). The brothers have already decided that Petya will do exactly a chores and Vasya will do exactly b chores (a + b = n).
In how many ways can they choose an integer x so that Petya got exactly a chores and Vasya got exactly b chores?
Input
The first input line contains three integers n, a and b (2 β€ n β€ 2000; a, b β₯ 1; a + b = n) β the total number of chores, the number of Petya's chores and the number of Vasya's chores.
The next line contains a sequence of integers h1, h2, ..., hn (1 β€ hi β€ 109), hi is the complexity of the i-th chore. The numbers in the given sequence are not necessarily different.
All numbers on the lines are separated by single spaces.
Output
Print the required number of ways to choose an integer value of x. If there are no such ways, print 0.
Examples
Input
5 2 3
6 2 3 100 1
Output
3
Input
7 3 4
1 1 9 1 1 1 1
Output
0
Note
In the first sample the possible values of x are 3, 4 or 5.
In the second sample it is impossible to find such x, that Petya got 3 chores and Vasya got 4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, a, b, temp;
int h[2005];
while (cin >> n >> a >> b) {
for (int i = 0; i < n; i++) {
cin >> h[i];
}
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++) {
if (h[j] < h[j + 1]) {
temp = h[j];
h[j] = h[j + 1];
h[j + 1] = temp;
}
}
if (h[a - 1] > h[a])
cout << h[a - 1] - h[a] << endl;
else
cout << "0" << endl;
}
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Vasya lives in a round building, whose entrances are numbered sequentially by integers from 1 to n. Entrance n and entrance 1 are adjacent.
Today Vasya got bored and decided to take a walk in the yard. Vasya lives in entrance a and he decided that during his walk he will move around the house b entrances in the direction of increasing numbers (in this order entrance n should be followed by entrance 1). The negative value of b corresponds to moving |b| entrances in the order of decreasing numbers (in this order entrance 1 is followed by entrance n). If b = 0, then Vasya prefers to walk beside his entrance.
<image> Illustration for n = 6, a = 2, b = - 5.
Help Vasya to determine the number of the entrance, near which he will be at the end of his walk.
Input
The single line of the input contains three space-separated integers n, a and b (1 β€ n β€ 100, 1 β€ a β€ n, - 100 β€ b β€ 100) β the number of entrances at Vasya's place, the number of his entrance and the length of his walk, respectively.
Output
Print a single integer k (1 β€ k β€ n) β the number of the entrance where Vasya will be at the end of his walk.
Examples
Input
6 2 -5
Output
3
Input
5 1 3
Output
4
Input
3 2 7
Output
3
Note
The first example is illustrated by the picture in the statements.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, a, b;
cin >> n >> a >> b;
if (b < 0) {
b = b % n;
b += n;
}
if ((a + b) % n == 0)
cout << n;
else
cout << (a + b) % n;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
You are given two positive integers a and b. In one move you can increase a by 1 (replace a with a+1). Your task is to find the minimum number of moves you need to do in order to make a divisible by b. It is possible, that you have to make 0 moves, as a is already divisible by b. You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The only line of the test case contains two integers a and b (1 β€ a, b β€ 10^9).
Output
For each test case print the answer β the minimum number of moves you need to do in order to make a divisible by b.
Example
Input
5
10 4
13 9
100 13
123 456
92 46
Output
2
5
4
333
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
long long a, b, c;
cin >> a >> b;
if (a % b == 0) {
std::cout << 0 << std::endl;
continue;
}
if (a < b) {
cout << b - a << endl;
continue;
}
c = a / b;
cout << (b * (c + 1)) - a << endl;
}
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Tomorrow is a difficult day for Polycarp: he has to attend a lectures and b practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.
While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and draw everything he has to during all of the practical classes. Polycarp writes lectures using a pen (he can't use a pencil to write lectures!); he can write down c lectures using one pen, and after that it runs out of ink. During practical classes Polycarp draws blueprints with a pencil (he can't use a pen to draw blueprints!); one pencil is enough to draw all blueprints during d practical classes, after which it is unusable.
Polycarp's pencilcase can hold no more than k writing implements, so if Polycarp wants to take x pens and y pencils, they will fit in the pencilcase if and only if x + y β€ k.
Now Polycarp wants to know how many pens and pencils should he take. Help him to determine it, or tell that his pencilcase doesn't have enough room for all the implements he needs tomorrow!
Note that you don't have to minimize the number of writing implements (though their total number must not exceed k).
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases in the input. Then the test cases follow.
Each test case is described by one line containing five integers a, b, c, d and k, separated by spaces (1 β€ a, b, c, d, k β€ 100) β the number of lectures Polycarp has to attend, the number of practical classes Polycarp has to attend, the number of lectures which can be written down using one pen, the number of practical classes for which one pencil is enough, and the number of writing implements that can fit into Polycarp's pencilcase, respectively.
In hacks it is allowed to use only one test case in the input, so t = 1 should be satisfied.
Output
For each test case, print the answer as follows:
If the pencilcase can't hold enough writing implements to use them during all lectures and practical classes, print one integer -1. Otherwise, print two non-negative integers x and y β the number of pens and pencils Polycarp should put in his pencilcase. If there are multiple answers, print any of them. Note that you don't have to minimize the number of writing implements (though their total number must not exceed k).
Example
Input
3
7 5 4 5 8
7 5 4 5 2
20 53 45 26 4
Output
7 1
-1
1 3
Note
There are many different answers for the first test case; x = 7, y = 1 is only one of them. For example, x = 3, y = 1 is also correct.
x = 1, y = 3 is the only correct answer for the third test case.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void solve() {
int a, b, c, d, k;
cin >> a >> b >> c >> d >> k;
int pens;
if (a % c == 0)
pens = a / c;
else
pens = a / c + 1;
int pencils;
if (b % d == 0)
pencils = b / d;
else
pencils = b / d + 1;
if (pens + pencils > k)
cout << -1 << endl;
else
cout << pens << ' ' << pencils << endl;
}
int main(void) {
int t;
cin >> t;
while (t--) solve();
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).
q events are about to happen (in chronological order). They are of three types:
1. Application x generates a notification (this new notification is unread).
2. Thor reads all notifications generated so far by application x (he may re-read some notifications).
3. Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation.
Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone.
Input
The first line of input contains two integers n and q (1 β€ n, q β€ 300 000) β the number of applications and the number of events to happen.
The next q lines contain the events. The i-th of these lines starts with an integer typei β type of the i-th event. If typei = 1 or typei = 2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1 β€ typei β€ 3, 1 β€ xi β€ n, 1 β€ ti β€ q).
Output
Print the number of unread notifications after each event.
Examples
Input
3 4
1 3
1 1
1 2
2 3
Output
1
2
3
2
Input
4 6
1 2
1 4
1 2
3 3
1 3
1 3
Output
1
2
3
0
1
2
Note
In the first sample:
1. Application 3 generates a notification (there is 1 unread notification).
2. Application 1 generates a notification (there are 2 unread notifications).
3. Application 2 generates a notification (there are 3 unread notifications).
4. Thor reads the notification generated by application 3, there are 2 unread notifications left.
In the second sample test:
1. Application 2 generates a notification (there is 1 unread notification).
2. Application 4 generates a notification (there are 2 unread notifications).
3. Application 2 generates a notification (there are 3 unread notifications).
4. Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left.
5. Application 3 generates a notification (there is 1 unread notification).
6. Application 3 generates a notification (there are 2 unread notifications).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 300010;
int cnt = 0, n, ques, mark = 0, ans = 0;
queue<int> q[N];
bool vis[N];
int main() {
scanf("%d%d", &n, &ques);
memset(vis, false, sizeof(vis));
while (ques--) {
int op, x;
scanf("%d%d", &op, &x);
if (op == 1) {
q[x].push(++cnt);
ans++;
} else if (op == 2) {
while (!q[x].empty()) {
int u = q[x].front();
q[x].pop();
if (u > mark) {
ans--;
vis[u] = true;
}
}
} else {
for (int i = mark + 1; i <= x; i++) {
if (!vis[i]) ans--;
}
mark = max(mark, x);
}
printf("%d\n", ans);
}
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character.
Let's introduce several definitions:
* A substring s[i..j] (1 β€ i β€ j β€ |s|) of string s is string sisi + 1...sj.
* The prefix of string s of length l (1 β€ l β€ |s|) is string s[1..l].
* The suffix of string s of length l (1 β€ l β€ |s|) is string s[|s| - l + 1..|s|].
Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring.
Input
The single line contains a sequence of characters s1s2...s|s| (1 β€ |s| β€ 105) β string s. The string only consists of uppercase English letters.
Output
In the first line, print integer k (0 β€ k β€ |s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li.
Examples
Input
ABACABA
Output
3
1 4
3 2
7 1
Input
AAA
Output
3
1 3
2 2
3 1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
int n = s.length();
int p[n];
for (int i = 0; i < n; i++) p[i] = -1;
for (int i = 1; i < n; i++) {
int x = p[i - 1];
while (1) {
if (s[x + 1] == s[i]) {
p[i] = x + 1;
break;
} else if (x == -1) {
p[i] = -1;
break;
}
x = p[x];
}
}
int cnt[n];
for (int i = 0; i < n; i++) cnt[i] = 1;
for (int i = n - 1; i >= 0; i--)
if (p[i] != -1) cnt[p[i]] += cnt[i];
int last = n - 1;
vector<int> ans;
while (last != -1) {
ans.push_back(last);
last = p[last];
}
reverse(ans.begin(), ans.end());
cout << ans.size() << endl;
for (int i = 0; i < ans.size(); i++)
cout << ans[i] + 1 << " " << cnt[ans[i]] << endl;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
The hero of our story, Valera, and his best friend Arcady are still in school, and therefore they spend all the free time playing turn-based strategy "GAGA: Go And Go Again". The gameplay is as follows.
There are two armies on the playing field each of which consists of n men (n is always even). The current player specifies for each of her soldiers an enemy's soldier he will shoot (a target) and then all the player's soldiers shot simultaneously. This is a game world, and so each soldier shoots perfectly, that is he absolutely always hits the specified target. If an enemy soldier is hit, he will surely die. It may happen that several soldiers had been indicated the same target. Killed soldiers do not participate in the game anymore.
The game "GAGA" consists of three steps: first Valera makes a move, then Arcady, then Valera again and the game ends.
You are asked to calculate the maximum total number of soldiers that may be killed during the game.
Input
The input data consist of a single integer n (2 β€ n β€ 108, n is even). Please note that before the game starts there are 2n soldiers on the fields.
Output
Print a single number β a maximum total number of soldiers that could be killed in the course of the game in three turns.
Examples
Input
2
Output
3
Input
4
Output
6
Note
The first sample test:
1) Valera's soldiers 1 and 2 shoot at Arcady's soldier 1.
2) Arcady's soldier 2 shoots at Valera's soldier 1.
3) Valera's soldier 1 shoots at Arcady's soldier 2.
There are 3 soldiers killed in total: Valera's soldier 1 and Arcady's soldiers 1 and 2.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n, h;
void input() { cin >> n; }
void work() {
h = n / 4 + n / 4;
if (n % 4 != 0) h++;
}
void output() { cout << n * 2 - h; }
int main() {
input();
work();
output();
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.
Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.
The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.
Note that all these questions are independent from each other β the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
Input
The first line of the input contains a single number n (1 β€ n β€ 105) β the number of houses in the capital of Berland.
The second line contains n space-separated positive integers hi (1 β€ hi β€ 109), where hi equals the number of floors in the i-th house.
Output
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero.
All houses are numbered from left to right, starting from one.
Examples
Input
5
1 2 3 1 2
Output
3 2 0 2 0
Input
4
3 2 1 4
Output
2 3 4 0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long Nmax = 1000000000;
int n;
vector<long long> a;
vector<long long> tree;
void add(int x, int i, int l, int r, int pos) {
if (i < l || i > r) return;
if (l == r) {
tree[pos] = x;
return;
}
int mid = (l + r) / 2;
add(x, i, l, mid, pos * 2);
add(x, i, mid + 1, r, pos * 2 + 1);
tree[pos] = max(tree[pos * 2], tree[pos * 2 + 1]);
}
long long get_max(int u, int v, int l, int r, int pos) {
if (v < l || r < u) return -999999999999999999;
if (u <= l && r <= v) return tree[pos];
int mid = (l + r) / 2;
return max(get_max(u, v, l, mid, pos * 2),
get_max(u, v, mid + 1, r, pos * 2 + 1));
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n;
tree.assign(4 * n + 1, 0);
a.assign(n + 1, 0);
for (int i = 1; i <= n; ++i) {
cin >> a[i];
add(a[i], i, 1, n, 1);
}
for (int i = 1; i < n; ++i) {
long long v = get_max(i + 1, n, 1, n, 1);
if (a[i] > v)
cout << 0 << ' ';
else
cout << v + 1 - a[i] << ' ';
}
cout << 0 << ' ';
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Tavas is a strange creature. Usually "zzz" comes out of people's mouth while sleeping, but string s of length n comes out from Tavas' mouth instead.
<image>
Today Tavas fell asleep in Malekas' place. While he was sleeping, Malekas did a little process on s. Malekas has a favorite string p. He determined all positions x1 < x2 < ... < xk where p matches s. More formally, for each xi (1 β€ i β€ k) he condition sxisxi + 1... sxi + |p| - 1 = p is fullfilled.
Then Malekas wrote down one of subsequences of x1, x2, ... xk (possibly, he didn't write anything) on a piece of paper. Here a sequence b is a subsequence of sequence a if and only if we can turn a into b by removing some of its elements (maybe no one of them or all).
After Tavas woke up, Malekas told him everything. He couldn't remember string s, but he knew that both p and s only contains lowercase English letters and also he had the subsequence he had written on that piece of paper.
Tavas wonders, what is the number of possible values of s? He asked SaDDas, but he wasn't smart enough to solve this. So, Tavas asked you to calculate this number for him.
Answer can be very large, so Tavas wants you to print the answer modulo 109 + 7.
Input
The first line contains two integers n and m, the length of s and the length of the subsequence Malekas wrote down (1 β€ n β€ 106 and 0 β€ m β€ n - |p| + 1).
The second line contains string p (1 β€ |p| β€ n).
The next line contains m space separated integers y1, y2, ..., ym, Malekas' subsequence (1 β€ y1 < y2 < ... < ym β€ n - |p| + 1).
Output
In a single line print the answer modulo 1000 000 007.
Examples
Input
6 2
ioi
1 3
Output
26
Input
5 2
ioi
1 2
Output
0
Note
In the first sample test all strings of form "ioioi?" where the question mark replaces arbitrary English letter satisfy.
Here |x| denotes the length of string x.
Please note that it's possible that there is no such string (answer is 0).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[1000010];
char res[1000010];
vector<int> z_function(string s) {
int n = (int)s.length();
vector<int> z(n);
for (int i = 1, l = 0, r = 0; i < n; ++i) {
if (i <= r) z[i] = min(r - i + 1, z[i - l]);
while (i + z[i] < n && s[z[i]] == s[i + z[i]]) ++z[i];
if (i + z[i] - 1 > r) l = i, r = i + z[i] - 1;
}
return z;
}
int main() {
int N, M;
cin >> N >> M;
string s;
cin >> s;
vector<int> z = z_function(s + "#" + s);
for (int i = 0; i < M; i++) scanf("%d", &a[i]);
for (int i = 1; i <= N; i++) res[i] = '*';
int cur = 0;
for (int i = 0; i < M; i++) {
if (!i || a[i - 1] + (int)s.length() <= a[i]) {
for (int j = 0; j < (int)s.length(); j++) res[a[i] + j] = s[j];
} else {
int len = (int)s.length() - (a[i] - a[i - 1]);
if (z[(int)s.length() + (int)s.length() - len + 1] == len) {
for (int j = len; j < (int)s.length(); j++) res[a[i] + j] = s[j];
} else {
cout << 0 << endl;
return 0;
}
}
}
long long cnt = 1, mod = 1e9 + 7;
for (int i = 1; i <= N; i++) {
if (res[i] == '*') cnt = (cnt * 26) % mod;
}
cout << cnt << endl;
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Input
The first line contains a single integer n (1 β€ n β€ 1000) β the number of points on a plane.
Each of the next n lines contains two real coordinates xi and yi of the <image> point, specified with exactly 2 fractional digits. All coordinates are between - 1000 and 1000, inclusive.
Output
Output a single real number ΞΈ β the answer to the problem statement. The absolute or relative error of your answer should be at most 10 - 2.
Examples
Input
8
-2.14 2.06
-1.14 2.04
-2.16 1.46
-2.14 0.70
-1.42 0.40
-0.94 -0.48
-1.42 -1.28
-2.16 -1.62
Output
5.410
Input
5
2.26 1.44
2.28 0.64
2.30 -0.30
1.58 0.66
3.24 0.66
Output
5.620
Input
8
6.98 2.06
6.40 1.12
5.98 0.24
5.54 -0.60
7.16 0.30
7.82 1.24
8.34 0.24
8.74 -0.76
Output
5.480
Input
5
10.44 2.06
10.90 0.80
11.48 -0.48
12.06 0.76
12.54 2.06
Output
6.040
Input
8
16.94 2.42
15.72 2.38
14.82 1.58
14.88 0.50
15.76 -0.16
16.86 -0.20
17.00 0.88
16.40 0.92
Output
6.040
Input
7
20.62 3.00
21.06 2.28
21.56 1.36
21.66 0.56
21.64 -0.52
22.14 2.32
22.62 3.04
Output
6.720
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
int n;
cin >> n;
double x, y, avg = 0;
for (int i = 0; i < n; ++i) {
cin >> x >> y;
avg += y;
}
avg /= n;
avg += 5;
cout << setprecision(3) << fixed << avg << endl;
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Vasya has a string s of length n consisting only of digits 0 and 1. Also he has an array a of length n.
Vasya performs the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue together the remaining parts (any of them can be empty). For example, if he erases substring 111 from string 111110 he will get the string 110. Vasya gets a_x points for erasing substring of length x.
Vasya wants to maximize his total points, so help him with this!
Input
The first line contains one integer n (1 β€ n β€ 100) β the length of string s.
The second line contains string s, consisting only of digits 0 and 1.
The third line contains n integers a_1, a_2, ... a_n (1 β€ a_i β€ 10^9), where a_i is the number of points for erasing the substring of length i.
Output
Print one integer β the maximum total points Vasya can get.
Examples
Input
7
1101001
3 4 9 100 1 2 3
Output
109
Input
5
10101
3 10 15 15 15
Output
23
Note
In the first example the optimal sequence of erasings is: 1101001 β 111001 β 11101 β 1111 β β
.
In the second example the optimal sequence of erasings is: 10101 β 1001 β 11 β β
.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 110;
long long a[maxn];
long long dp[2][maxn][maxn][maxn];
long long ans[maxn][maxn];
int main() {
ios_base::sync_with_stdio(0);
int n;
string s;
cin >> n >> s;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= i; j++) {
a[i] = max(a[i], a[i - j] + a[j]);
}
}
for (int i = 1; i <= n; i++) {
for (int k = 1; k <= n; k++) {
dp[0][i][i][k] = -1e18;
dp[1][i][i][k] = -1e18;
dp[0][i + 1][i][k] = -1e18;
dp[1][i + 1][i][k] = -1e18;
}
if (s[i - 1] == '0') {
dp[0][i][i][1] = 0;
} else {
dp[1][i][i][1] = 0;
}
dp[0][i][i][0] = a[1];
dp[1][i][i][0] = a[1];
ans[i][i] = a[1];
}
for (int d = 1; d < n; d++) {
for (int le = 1; le <= n; le++) {
int ri = le + d;
if (ri > n) continue;
for (int k = 1; k <= n; k++) {
for (int dig = 0; dig < 2; dig++) {
dp[dig][le][ri][k] = -1e18;
for (int i = le; i <= ri; i++) {
if (s[i - 1] - '0' == dig) {
dp[dig][le][ri][k] =
max(dp[dig][le][ri][k],
ans[le][i - 1] + dp[dig][i + 1][ri][k - 1]);
}
}
}
}
ans[le][ri] = -1e18;
for (int k = 1; k <= n; k++) {
ans[le][ri] =
max(ans[le][ri], max(dp[0][le][ri][k], dp[1][le][ri][k]) + a[k]);
}
dp[0][le][ri][0] = ans[le][ri];
dp[1][le][ri][0] = ans[le][ri];
}
}
cout << ans[1][n] << "\n";
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
You are at the top left cell (1, 1) of an n Γ m labyrinth. Your goal is to get to the bottom right cell (n, m). You can only move right or down, one cell per step. Moving right from a cell (x, y) takes you to the cell (x, y + 1), while moving down takes you to the cell (x + 1, y).
Some cells of the labyrinth contain rocks. When you move to a cell with rock, the rock is pushed to the next cell in the direction you're moving. If the next cell contains a rock, it gets pushed further, and so on.
The labyrinth is surrounded by impenetrable walls, thus any move that would put you or any rock outside of the labyrinth is illegal.
Count the number of different legal paths you can take from the start to the goal modulo 10^9 + 7. Two paths are considered different if there is at least one cell that is visited in one path, but not visited in the other.
Input
The first line contains two integers n, m β dimensions of the labyrinth (1 β€ n, m β€ 2000).
Next n lines describe the labyrinth. Each of these lines contains m characters. The j-th character of the i-th of these lines is equal to "R" if the cell (i, j) contains a rock, or "." if the cell (i, j) is empty.
It is guaranteed that the starting cell (1, 1) is empty.
Output
Print a single integer β the number of different legal paths from (1, 1) to (n, m) modulo 10^9 + 7.
Examples
Input
1 1
.
Output
1
Input
2 3
...
..R
Output
0
Input
4 4
...R
.RR.
.RR.
R...
Output
4
Note
In the first sample case we can't (and don't have to) move, hence the only path consists of a single cell (1, 1).
In the second sample case the goal is blocked and is unreachable.
Illustrations for the third sample case can be found here: <https://assets.codeforces.com/rounds/1225/index.html>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
int sum(int a, int b) {
a += b;
if (a >= MOD) {
a -= MOD;
}
return a;
}
const int N = 2010;
int dp[N][N][2], pref0[N][N], pref1[N][N], calc1[N][N], calc0[N][N];
char c[N][N];
int get_sum1(int a, int l, int r) {
if (l > r) {
return 0;
}
int res = pref1[a][r] - pref1[a][l - 1];
if (res < 0) {
res += MOD;
}
return res;
}
int get_sum0(int a, int l, int r) {
if (l > r) {
return 0;
}
int res = pref0[a][r] - pref0[a][l - 1];
if (res < 0) {
res += MOD;
}
return res;
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
if (n == 1 && m == 1) {
cout << 1 << '\n';
exit(0);
}
int cnt0 = 0, cnt1 = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> c[i][j];
if (c[i][j] == 'R') {
if (i == 1) {
cnt1++;
}
if (j == 1) {
cnt0++;
}
}
}
}
for (int j = 1; j <= m; j++) {
int cnt = 0;
for (int i = n; i >= 1; i--) {
if (c[i][j] == 'R') {
cnt++;
calc1[j][cnt] = i;
}
}
for (int i = cnt + 1; i <= n; i++) {
calc1[j][i] = 1;
}
}
for (int i = 1; i <= n; i++) {
int cnt = 0;
for (int j = m; j >= 1; j--) {
if (c[i][j] == 'R') {
cnt++;
calc0[i][cnt] = j;
}
}
for (int j = cnt + 1; j <= m; j++) {
calc0[i][j] = 1;
}
}
for (int j = 2; j <= m; j++) {
if (cnt1 <= m - j) {
dp[1][j][1] = 1;
pref1[j][1] = 1;
}
}
for (int i = 2; i <= n; i++) {
if (cnt0 <= n - i) {
dp[i][1][0] = 1;
pref0[i][1] = 1;
}
}
for (int i = 2; i <= n; i++) {
for (int j = 2; j <= m; j++) {
int up = calc1[j][n - i + 1], lef = calc0[i][m - j + 1];
dp[i][j][0] = get_sum1(j, up, i - 1);
dp[i][j][1] = get_sum0(i, lef, j - 1);
pref1[j][i] = sum(pref1[j][i - 1], dp[i][j][1]);
pref0[i][j] = sum(pref0[i][j - 1], dp[i][j][0]);
}
}
cout << sum(dp[n][m][0], dp[n][m][1]) << '\n';
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Way to go! Heidi now knows how many brains there must be for her to get one. But throwing herself in the midst of a clutch of hungry zombies is quite a risky endeavor. Hence Heidi wonders: what is the smallest number of brains that must be in the chest for her to get out at all (possibly empty-handed, but alive)?
The brain dinner night will evolve just as in the previous subtask: the same crowd is present, the N - 1 zombies have the exact same mindset as before and Heidi is to make the first proposal, which must be accepted by at least half of the attendees for her to survive.
Input
The only line of input contains one integer: N, the number of attendees (1 β€ N β€ 109).
Output
Output one integer: the smallest number of brains in the chest which allows Heidi to merely survive.
Examples
Input
1
Output
0
Input
3
Output
1
Input
99
Output
49
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long unsigned int n, now, m;
cin >> n;
if (n % 2) {
cout << n / 2;
} else {
m = log2(n);
cout << (int)(n - pow(2, m)) / 2;
}
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Seisu-ya, a store specializing in non-negative integers, sells N non-negative integers. The i-th integer is A_i and has a utility of B_i. There may be multiple equal integers with different utilities.
Takahashi will buy some integers in this store. He can buy a combination of integers whose bitwise OR is less than or equal to K. He wants the sum of utilities of purchased integers to be as large as possible.
Find the maximum possible sum of utilities of purchased integers.
Constraints
* 1 \leq N \leq 10^5
* 0 \leq K < 2^{30}
* 0 \leq A_i < 2^{30}(1\leq i\leq N)
* 1 \leq B_i \leq 10^9(1\leq i\leq N)
* All input values are integers.
Inputs
Input is given from Standard Input in the following format:
N K
A_1 B_1
:
A_N B_N
Outputs
Print the maximum possible sum of utilities of purchased integers.
Examples
Input
3 5
3 3
4 4
2 5
Output
8
Input
3 6
3 3
4 4
2 5
Output
9
Input
7 14
10 5
7 4
11 4
9 8
3 6
6 2
8 9
Output
32
### Response
```cpp
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, k; cin >> n >> k;
vector<int> a(n), b(n);
for (int i = 0; i < n; i++) cin >> a[i] >> b[i];
auto calc = [&](int mask) {
long long sum = 0;
for (int j = 0; j < n; j++) if ((a[j] | mask) == mask) sum += b[j];
return sum;
};
long long ans = calc(k);
for (int i = 0; i < 31; i++) if (k >> i & 1) {
int mask = (k ^ (1 << i)) | ((1 << i) - 1);
ans = max(ans, calc(mask));
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the `0` key, the `1` key and the backspace key.
To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this string is empty. When each key on the keyboard is pressed, the following changes occur to the string:
* The `0` key: a letter `0` will be inserted to the right of the string.
* The `1` key: a letter `1` will be inserted to the right of the string.
* The backspace key: if the string is empty, nothing happens. Otherwise, the rightmost letter of the string is deleted.
Sig has launched the editor, and pressed these keys several times. You are given a string s, which is a record of his keystrokes in order. In this string, the letter `0` stands for the `0` key, the letter `1` stands for the `1` key and the letter `B` stands for the backspace key. What string is displayed in the editor now?
Constraints
* 1 β¦ |s| β¦ 10 (|s| denotes the length of s)
* s consists of the letters `0`, `1` and `B`.
* The correct answer is not an empty string.
Input
The input is given from Standard Input in the following format:
s
Output
Print the string displayed in the editor in the end.
Examples
Input
01B0
Output
00
Input
0BB1
Output
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int i,j;
string s,a;
int main()
{
for(cin>>s;i<s.size();i++){
if(s[i]=='B')a=a.substr(0,a.size()-1);
else a+=s[i];
}
cout<<a<<endl;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was n integers a1, a2, ..., an. These numbers mean that Greg needs to do exactly n exercises today. Besides, Greg should repeat the i-th in order exercise ai times.
Greg now only does three types of exercises: "chest" exercises, "biceps" exercises and "back" exercises. Besides, his training is cyclic, that is, the first exercise he does is a "chest" one, the second one is "biceps", the third one is "back", the fourth one is "chest", the fifth one is "biceps", and so on to the n-th exercise.
Now Greg wonders, which muscle will get the most exercise during his training. We know that the exercise Greg repeats the maximum number of times, trains the corresponding muscle the most. Help Greg, determine which muscle will get the most training.
Input
The first line contains integer n (1 β€ n β€ 20). The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 25) β the number of times Greg repeats the exercises.
Output
Print word "chest" (without the quotes), if the chest gets the most exercise, "biceps" (without the quotes), if the biceps gets the most exercise and print "back" (without the quotes) if the back gets the most exercise.
It is guaranteed that the input is such that the answer to the problem is unambiguous.
Examples
Input
2
2 8
Output
biceps
Input
3
5 1 10
Output
back
Input
7
3 3 2 7 9 6 8
Output
chest
Note
In the first sample Greg does 2 chest, 8 biceps and zero back exercises, so the biceps gets the most exercises.
In the second sample Greg does 5 chest, 1 biceps and 10 back exercises, so the back gets the most exercises.
In the third sample Greg does 18 chest, 12 biceps and 8 back exercises, so the chest gets the most exercise.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int sum1 = 0, sum2 = 0, sum3 = 0, n, b, c;
cin >> n;
int arr[n + 1];
for (int i = 1; i <= n; i++) {
cin >> arr[i];
}
if (n == 1) {
cout << "chest";
return 0;
} else if (n == 2) {
b = max(arr[1], arr[2]);
if (b == arr[1]) {
cout << "chest";
} else {
cout << "biceps";
}
return 0;
} else if (n > 2) {
for (int i = 1; i <= (n + 2) / 3; i++) {
sum1 += arr[3 * i - 2];
}
for (int i = 1; i <= (n + 1) / 3; i++) {
sum2 += arr[3 * i - 1];
}
for (int i = 1; i <= (n) / 3; i++) {
sum3 += arr[3 * i];
}
}
c = max(max(sum1, sum2), sum3);
if (c == sum1) {
cout << "chest";
} else if (c == sum2) {
cout << "biceps";
} else {
cout << "back";
}
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Snuke has two boards, each divided into a grid with N rows and N columns. For both of these boards, the square at the i-th row from the top and the j-th column from the left is called Square (i,j).
There is a lowercase English letter written in each square on the first board. The letter written in Square (i,j) is S_{i,j}. On the second board, nothing is written yet.
Snuke will write letters on the second board, as follows:
* First, choose two integers A and B ( 0 \leq A, B < N ).
* Write one letter in each square on the second board. Specifically, write the letter written in Square ( i+A, j+B ) on the first board into Square (i,j) on the second board. Here, the k-th row is also represented as the (N+k)-th row, and the k-th column is also represented as the (N+k)-th column.
After this operation, the second board is called a good board when, for every i and j ( 1 \leq i, j \leq N ), the letter in Square (i,j) and the letter in Square (j,i) are equal.
Find the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.
Constraints
* 1 \leq N \leq 300
* S_{i,j} ( 1 \leq i, j \leq N ) is a lowercase English letter.
Input
Input is given from Standard Input in the following format:
N
S_{1,1}S_{1,2}..S_{1,N}
S_{2,1}S_{2,2}..S_{2,N}
:
S_{N,1}S_{N,2}..S_{N,N}
Output
Print the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.
Examples
Input
2
ab
ca
Output
2
Input
4
aaaa
aaaa
aaaa
aaaa
Output
16
Input
5
abcde
fghij
klmno
pqrst
uvwxy
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 305;
int N;
char mat[MAXN][MAXN];
bool check(int diff) {
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
if (mat[i][j] != mat[(j + diff) % N][(i - diff + N) % N])
return false;
return true;
}
int main() {
scanf("%d", &N);
for (int i = 0; i < N; i++)
scanf("%s", mat[i]);
int sol = 0;
for (int i = 0; i < N; i++)
sol += check(i);
printf("%d\n", N * sol);
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
There are r red and g green blocks for construction of the red-green tower. Red-green tower can be built following next rules:
* Red-green tower is consisting of some number of levels;
* Let the red-green tower consist of n levels, then the first level of this tower should consist of n blocks, second level β of n - 1 blocks, the third one β of n - 2 blocks, and so on β the last level of such tower should consist of the one block. In other words, each successive level should contain one block less than the previous one;
* Each level of the red-green tower should contain blocks of the same color.
<image>
Let h be the maximum possible number of levels of red-green tower, that can be built out of r red and g green blocks meeting the rules above. The task is to determine how many different red-green towers having h levels can be built out of the available blocks.
Two red-green towers are considered different if there exists some level, that consists of red blocks in the one tower and consists of green blocks in the other tower.
You are to write a program that will find the number of different red-green towers of height h modulo 109 + 7.
Input
The only line of input contains two integers r and g, separated by a single space β the number of available red and green blocks respectively (0 β€ r, g β€ 2Β·105, r + g β₯ 1).
Output
Output the only integer β the number of different possible red-green towers of height h modulo 109 + 7.
Examples
Input
4 6
Output
2
Input
9 7
Output
6
Input
1 1
Output
2
Note
The image in the problem statement shows all possible red-green towers for the first sample.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <unsigned long long mod>
class modint {
public:
unsigned long long v;
modint(const long long x = 0) : v(x % mod) {}
modint operator+(const modint rhs) { return modint(*this) += rhs; }
modint operator-(const modint rhs) { return modint(*this) -= rhs; }
modint operator*(const modint rhs) { return modint(*this) *= rhs; }
modint operator/(const modint rhs) { return modint(*this) /= rhs; }
modint operator-() { return modint(mod - this->v); }
modint& operator+=(const modint rhs) {
v += rhs.v;
if (v >= mod) v -= mod;
return *this;
}
modint& operator-=(const modint rhs) {
if (v < rhs.v) v += mod;
v -= rhs.v;
return *this;
}
modint& operator*=(const modint rhs) {
v = v * rhs.v % mod;
return *this;
}
modint inverse(modint a) {
unsigned long long exp = mod - 2;
modint ret(1ULL);
while (exp) {
if (exp % 2) {
ret *= a;
}
a *= a;
exp >>= 1;
}
return ret;
}
modint& operator/=(modint rhs) {
(*this) *= inverse(rhs);
return *this;
}
friend ostream& operator<<(ostream& os, modint& u) {
os << u.v;
return (os);
}
friend istream& operator>>(istream& is, modint& u) {
is >> u.v;
return (is);
}
};
const int MOD = 1000000007;
using mint = modint<MOD>;
class Solution {
public:
void solve() {
int r, g;
cin >> r >> g;
int h = 0;
while ((h + 1) * (h + 2) <= (r + g) * 2) h++;
int rem = (r + g) - (h * (h + 1)) / 2;
vector<mint> dp(r + 1);
dp[0] = 1;
for (int i = 0; i < h; i++) {
for (int j = r - 1 - i; j >= 0; j--) {
dp[j + i + 1] += dp[j];
}
}
mint ans = 0;
for (int i = r; i >= max(r - rem, 0); i--) {
ans += dp[i];
}
cout << ans << "\n";
};
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
Solution solution;
solution.solve();
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
You are a car race organizer and would like to arrange some races in Linear Kingdom.
Linear Kingdom has n consecutive roads spanning from left to right. The roads are numbered from 1 to n from left to right, thus the roads follow in the order of their numbers' increasing. There will be several races that may be held on these roads. Each race will use a consecutive subset of these roads. Also, each race will pay some amount of money to you if this race is held. No races overlap in time, so some roads can be used in several races.
Unfortunately, some of the roads are in a bad condition and they need repair. Each road has repair costs associated with it, you are required to pay this cost to repair the road. A race can only take place if all the roads used in the race are renovated. Your task is to repair such roads (possibly all or none) that will maximize your profit. Your profit is defined as the total money you get from the races that are held minus the total money you spent to repair the roads. Note that you may decide not to repair any road and gain zero profit.
Print the maximum profit you can gain.
Input
The first line contains two single-space separated integers, n and m (1 β€ n, m β€ 2Β·105), denoting the number of roads and the number of races, respectively.
Then n lines follow, each line will contain a single non-negative integer not exceeding 109 denoting the cost to repair a road. The costs are given in order from road 1 to road n.
Finally, m lines follow. Each line is single-space-separated triplets of integers. Each triplet will be given as lb, ub, and p (1 β€ lb β€ ub β€ n, 1 β€ p β€ 109), which means that the race these three integers describe will use all the roads from lb to ub, inclusive, and if it's held you get p.
Output
Print a single integer denoting the maximum possible profit you can gain.
Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is recommended to use cin, cout stream (also you may use %I64d specificator).
Examples
Input
7 4
3
2
3
2
1
2
3
1 2 5
2 3 5
3 5 3
7 7 5
Output
4
Input
2 1
0
3
1 2 5
Output
2
Input
3 1
10
10
10
1 3 10
Output
0
Note
In the first sample the optimal solution is to repair roads 1, 2, 3, and 7. Three races will take place which nets you 15. The road repair costs 11, hence your profit is 4.
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize(2)
const long long MAXN = 2e5 + 10;
const long long MAXM = MAXN << 2;
struct Road {
long long l, u, p;
} e[MAXN];
long long n, m, root, a[MAXN], f[MAXN], sum[MAXN];
std::vector<std::pair<long long, long long> > node[MAXN];
namespace Segtree {
long long cnt, lazy[MAXM], max_num[MAXM], ls[MAXM], rs[MAXM], l[MAXM], r[MAXM];
inline void build(long long &cur, long long L, long long R) {
cur = ++cnt;
l[cur] = L, r[cur] = R;
if (L == R) {
max_num[L] = a[L];
return;
}
long long mid = (L + R) >> 1;
build(ls[cur], L, mid), build(rs[cur], mid + 1, R);
}
inline void push_down(long long cur) {
if (!lazy[cur]) return;
lazy[ls[cur]] += lazy[cur], lazy[rs[cur]] += lazy[cur];
max_num[ls[cur]] += lazy[cur], max_num[rs[cur]] += lazy[cur];
lazy[cur] = 0;
}
inline void Modification(long long L, long long R, long long cur,
long long add) {
if (L <= l[cur] and r[cur] <= R) {
lazy[cur] += add, max_num[cur] += add;
return;
}
push_down(cur);
long long mid = (l[cur] + r[cur]) >> 1;
if (L <= mid) Modification(L, R, ls[cur], add);
if (R > mid) Modification(L, R, rs[cur], add);
max_num[cur] = std::max(max_num[ls[cur]], max_num[rs[cur]]);
}
inline long long query(long long L, long long R, long long cur) {
if (L <= l[cur] and r[cur] <= R) return max_num[cur];
push_down(cur);
long long mid = (l[cur] + r[cur]) >> 1, res = 0;
if (L <= mid) res = std::max(res, query(L, R, ls[cur]));
if (R > mid) res = std::max(res, query(L, R, rs[cur]));
return res;
}
} // namespace Segtree
inline long long read() {
long long X = 0, flag = 0;
char ch = 0;
while (!isdigit(ch)) flag |= ch == '-', ch = getchar();
while (isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
return flag ? -X : X;
}
inline bool cmp(Road x, Road y) { return x.u < y.u; }
inline void write(long long X) {
if (X < 0) putchar('-'), X = -X;
if (X > 9) write(X / 10);
putchar(X % 10 + '0');
}
signed main() {
n = read(), m = read(), Segtree::build(root, 0, n);
for (register long long i = 1; i <= n; i++)
a[i] = read(), sum[i] = sum[i - 1] + a[i];
for (register long long i = 1; i <= m; i++) {
e[i].l = read(), e[i].u = read(), e[i].p = read();
node[e[i].u].push_back(std::make_pair(e[i].l, e[i].p));
}
std::sort(e + 1, e + n + 1, cmp);
for (register long long i = 1; i <= n; i++) {
Segtree::Modification(i, i, 1, Segtree::query(0, i - 1, 1));
for (register long long j = 0; j < node[i].size(); j++)
Segtree::Modification(0, node[i][j].first - 1, 1, node[i][j].second);
Segtree::Modification(0, i - 1, 1, -a[i]);
}
write(Segtree::max_num[1]);
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
There's a famous museum in the city where KleofΓ‘Ε‘ lives. In the museum, n exhibits (numbered 1 through n) had been displayed for a long time; the i-th of those exhibits has value vi and mass wi.
Then, the museum was bought by a large financial group and started to vary the exhibits. At about the same time, KleofΓ‘Ε‘... gained interest in the museum, so to say.
You should process q events of three types:
* type 1 β the museum displays an exhibit with value v and mass w; the exhibit displayed in the i-th event of this type is numbered n + i (see sample explanation for more details)
* type 2 β the museum removes the exhibit with number x and stores it safely in its vault
* type 3 β KleofΓ‘Ε‘ visits the museum and wonders (for no important reason at all, of course): if there was a robbery and exhibits with total mass at most m were stolen, what would their maximum possible total value be?
For each event of type 3, let s(m) be the maximum possible total value of stolen exhibits with total mass β€ m.
Formally, let D be the set of numbers of all exhibits that are currently displayed (so initially D = {1, ..., n}). Let P(D) be the set of all subsets of D and let
<image>
Then, s(m) is defined as
<image>
Compute s(m) for each <image>. Note that the output follows a special format.
Input
The first line of the input contains two space-separated integers n and k (1 β€ n β€ 5000, 1 β€ k β€ 1000) β the initial number of exhibits in the museum and the maximum interesting mass of stolen exhibits.
Then, n lines follow. The i-th of them contains two space-separated positive integers vi and wi (1 β€ vi β€ 1 000 000, 1 β€ wi β€ 1000) β the value and mass of the i-th exhibit.
The next line contains a single integer q (1 β€ q β€ 30 000) β the number of events.
Each of the next q lines contains the description of one event in the following format:
* 1 v w β an event of type 1, a new exhibit with value v and mass w has been added (1 β€ v β€ 1 000 000, 1 β€ w β€ 1000)
* 2 x β an event of type 2, the exhibit with number x has been removed; it's guaranteed that the removed exhibit had been displayed at that time
* 3 β an event of type 3, KleofΓ‘Ε‘ visits the museum and asks his question
There will be at most 10 000 events of type 1 and at least one event of type 3.
Output
As the number of values s(m) can get large, output the answers to events of type 3 in a special format.
For each event of type 3, consider the values s(m) computed for the question that KleofΓ‘Ε‘ asked in this event; print one line containing a single number
<image>
where p = 107 + 19 and q = 109 + 7.
Print the answers to events of type 3 in the order in which they appear in the input.
Examples
Input
3 10
30 4
60 6
5 1
9
3
1 42 5
1 20 3
3
2 2
2 4
3
1 40 6
3
Output
556674384
168191145
947033915
181541912
Input
3 1000
100 42
100 47
400 15
4
2 2
2 1
2 3
3
Output
0
Note
In the first sample, the numbers of displayed exhibits and values s(1), ..., s(10) for individual events of type 3 are, in order:
<image> <image> <image> <image>
The values of individual exhibits are v1 = 30, v2 = 60, v3 = 5, v4 = 42, v5 = 20, v6 = 40 and their masses are w1 = 4, w2 = 6, w3 = 1, w4 = 5, w5 = 3, w6 = 6.
In the second sample, the only question is asked after removing all exhibits, so s(m) = 0 for any m.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 30030, M = 5005000, L = 1010, oo = 1000000000, P = 10000019,
Q = 1000000007;
int i, j, k, n, m, nm, Tn, q, En, ch, last, o, x, An;
int f[22][L], h[N << 2], ans[N], p[N];
struct cc {
int l, r, v, w;
} A[N];
struct edge {
int s, n;
} E[M];
void R(int &x) {
x = 0;
ch = getchar();
while (ch < '0' || '9' < ch) ch = getchar();
while ('0' <= ch && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
}
int max(const int &x, const int &y) {
if (x > y) return x;
return y;
}
void E_add(int x, int y) {
E[++En].s = y;
E[En].n = h[x];
h[x] = En;
}
void T_add(int L, int R, int l, int r, int x, int k) {
if (L == l && R == r) {
E_add(k, x);
return;
}
int mid = (L + R) >> 1;
if (r <= mid)
T_add(L, mid, l, r, x, k << 1);
else {
if (l > mid)
T_add(mid + 1, R, l, r, x, k << 1 | 1);
else
T_add(L, mid, l, mid, x, k << 1),
T_add(mid + 1, R, mid + 1, r, x, k << 1 | 1);
}
}
void T_bl(int L, int R, int dp, int k) {
for (int i = 0; i <= m; i++) f[dp][i] = f[dp - 1][i];
for (int kk = h[k]; kk; kk = E[kk].n) {
int v = A[E[kk].s].v, w = A[E[kk].s].w;
for (int i = m; i >= w; i--) f[dp][i] = max(f[dp][i], f[dp][i - w] + v);
}
if (L == R) {
int &res = ans[L];
int pp = 1;
for (int i = 1; i <= m; i++) {
res = ((long long)f[dp][i] * pp + res) % Q;
pp = (long long)pp * P % Q;
}
return;
}
int mid = (L + R) >> 1;
T_bl(L, mid, dp + 1, k << 1);
T_bl(mid + 1, R, dp + 1, k << 1 | 1);
}
int main() {
R(n);
R(m);
for (i = 1; i <= n; i++) {
A[i].l = 1;
A[i].r = oo;
R(A[i].v);
R(A[i].w);
}
R(q);
An = n;
for (i = 1; i <= q; i++) {
last = o;
R(o);
if (o == 3) {
if (last == 3)
p[++nm] = Tn;
else
p[++nm] = ++Tn;
continue;
}
if (o == 1) {
An++;
A[An].l = Tn + 1;
A[An].r = oo;
R(A[An].v);
R(A[An].w);
continue;
}
if (o == 2) {
R(x);
A[x].r = Tn;
continue;
}
}
for (i = 1; i <= An; i++) {
if (A[i].r == oo) A[i].r = Tn;
if (1 <= A[i].l && A[i].l <= A[i].r && A[i].r <= Tn)
T_add(1, Tn, A[i].l, A[i].r, i, 1);
}
T_bl(1, Tn, 1, 1);
for (i = 1; i <= nm; i++) printf("%d\n", ans[p[i]]);
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.
Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" <image> "nastya" <image> "nastya" <image> "nastya" <image> "nastya" <image> "nastya" <image> "nastya".
Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.
It is guaranteed that the word p can be obtained by removing the letters from word t.
Input
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 β€ |p| < |t| β€ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t.
Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 β€ ai β€ |t|, all ai are distinct).
Output
Print a single integer number, the maximum number of letters that Nastya can remove.
Examples
Input
ababcba
abb
5 3 4 1 7 6 2
Output
3
Input
bbbabb
bb
1 6 3 4 2 5
Output
4
Note
In the first sample test sequence of removing made by Nastya looks like this:
"ababcba" <image> "ababcba" <image> "ababcba" <image> "ababcba"
Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".
So, Nastya will remove only three letters.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool isSubSequence(string str1, string str2, int m, int n) {
int j = 0;
for (int i = 0; i < n && j < m; i++)
if (str1[j] == str2[i]) j++;
return (j == m);
}
int main() {
string t, p;
cin >> t >> p;
int tlen = t.length();
int plen = p.length();
int a[tlen];
for (int i = 0; i < tlen; i++) cin >> a[i];
int l = -1, r = tlen - 1, mid = (l + r - 1) / 2;
int x;
int flag = 0, ans = 0;
while (l <= r) {
string temp;
mid = l + (r - l) / 2;
temp = t;
for (int i = 0; i <= mid; i++) {
flag = 0;
temp[a[i] - 1] = '*';
}
if (isSubSequence(p, temp, plen, tlen)) {
ans = mid;
l = mid + 1;
}
if (!(isSubSequence(p, temp, plen, tlen))) {
r = mid - 1;
}
}
cout << ans + 1 << endl;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
Input
The first line contains two integers a, b (1 β€ a, b β€ 1000), separated by a single space.
Output
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
Examples
Input
1 1
Output
NO
Input
5 5
Output
YES
2 1
5 5
-2 4
Input
5 10
Output
YES
-10 4
-2 -2
1 2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long fun(long long x) {
long long y = (long long)sqrt(x);
return y * y == x;
}
int solve() {
long long a, b;
cin >> a >> b;
for (long long int x1_sq = 1; x1_sq < a * a + 1; x1_sq++) {
long long y1_sq = a * a - x1_sq;
if (fun(y1_sq)) {
if ((y1_sq * b * b) % (a * a) == 0 && fun((y1_sq * b * b) / (a * a))) {
long long x2_sq = (y1_sq * b * b) / (a * a);
long long y2_sq = b * b - x2_sq;
if (fun(y2_sq) && y2_sq != y1_sq && x2_sq != 0 && x1_sq != 0 &&
y1_sq != 0 && y2_sq != 0) {
cout << "YES\n";
cout << "0 0\n";
cout << (long long)sqrt(x1_sq) << " " << (long long)sqrt(y1_sq)
<< "\n";
cout << -(long long)sqrt(x2_sq) << " " << (long long)sqrt(y2_sq)
<< "\n";
exit(0);
}
}
}
}
cout << "NO\n";
return 0;
}
int main() {
auto start = chrono::high_resolution_clock::now();
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long test_cases = 1;
while (test_cases--) solve();
auto stop = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<chrono::milliseconds>(stop - start);
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Just in case somebody missed it: this winter is totally cold in Nvodsk! It is so cold that one gets funny thoughts. For example, let's say there are strings with the length exactly n, based on the alphabet of size m. Any its substring with length equal to k is a palindrome. How many such strings exist? Your task is to find their quantity modulo 1000000007 (109 + 7). Be careful and don't miss a string or two!
Let us remind you that a string is a palindrome if it can be read the same way in either direction, from the left to the right and from the right to the left.
Input
The first and only line contains three integers: n, m and k (1 β€ n, m, k β€ 2000).
Output
Print a single integer β the number of strings of the described type modulo 1000000007 (109 + 7).
Examples
Input
1 1 1
Output
1
Input
5 2 4
Output
2
Note
In the first sample only one string is valid: "a" (let's denote the only letter of our alphabet as "a").
In the second sample (if we denote the alphabet letters as "a" and "b") the following strings are valid: "aaaaa" and "bbbbb".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long big = 1000000007;
long long ans = 1;
int n, m, k, f[2001];
void debug(int a) { cout << a << " "; }
int find(int x) { return f[x] == x ? x : f[x] = find(f[x]); }
void merge(int a, int b) {
if (a < b) swap(a, b);
f[find(a)] = find(b);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m >> k;
for (int i = 1; i <= n; i++) {
f[i] = i;
}
for (int i = 0; i + k <= n; i++)
for (int j = i + 1; j <= i + k; j++) {
int tmp = k + 2 * i - j + 1;
if (find(j) != find(tmp)) {
merge(j, tmp);
}
}
for (int i = 1; i <= n; i++) {
if (f[i] == i) {
ans = ans * m % big;
}
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Student Arseny likes to plan his life for n days ahead. He visits a canteen every day and he has already decided what he will order in each of the following n days. Prices in the canteen do not change and that means Arseny will spend ci rubles during the i-th day.
There are 1-ruble coins and 100-ruble notes in circulation. At this moment, Arseny has m coins and a sufficiently large amount of notes (you can assume that he has an infinite amount of them). Arseny loves modern technologies, so he uses his credit card everywhere except the canteen, but he has to pay in cash in the canteen because it does not accept cards.
Cashier always asks the student to pay change-free. However, it's not always possible, but Arseny tries to minimize the dissatisfaction of the cashier. Cashier's dissatisfaction for each of the days is determined by the total amount of notes and coins in the change. To be precise, if the cashier gives Arseny x notes and coins on the i-th day, his dissatisfaction for this day equals xΒ·wi. Cashier always gives change using as little coins and notes as possible, he always has enough of them to be able to do this.
<image> "Caution! Angry cashier"
Arseny wants to pay in such a way that the total dissatisfaction of the cashier for n days would be as small as possible. Help him to find out how he needs to pay in each of the n days!
Note that Arseny always has enough money to pay, because he has an infinite amount of notes. Arseny can use notes and coins he received in change during any of the following days.
Input
The first line contains two integers n and m (1 β€ n β€ 105, 0 β€ m β€ 109) β the amount of days Arseny planned his actions for and the amount of coins he currently has.
The second line contains a sequence of integers c1, c2, ..., cn (1 β€ ci β€ 105) β the amounts of money in rubles which Arseny is going to spend for each of the following days.
The third line contains a sequence of integers w1, w2, ..., wn (1 β€ wi β€ 105) β the cashier's dissatisfaction coefficients for each of the following days.
Output
In the first line print one integer β minimum possible total dissatisfaction of the cashier.
Then print n lines, the i-th of then should contain two numbers β the amount of notes and the amount of coins which Arseny should use to pay in the canteen on the i-th day.
Of course, the total amount of money Arseny gives to the casher in any of the days should be no less than the amount of money he has planned to spend. It also shouldn't exceed 106 rubles: Arseny never carries large sums of money with him.
If there are multiple answers, print any of them.
Examples
Input
5 42
117 71 150 243 200
1 1 1 1 1
Output
79
1 17
1 0
2 0
2 43
2 0
Input
3 0
100 50 50
1 3 2
Output
150
1 0
1 0
0 50
Input
5 42
117 71 150 243 200
5 4 3 2 1
Output
230
1 17
1 0
1 50
3 0
2 0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
multiset<pair<long long, long long> > q;
multiset<pair<long long, long long> >::iterator iter;
const long long max_n = 100050;
long long n, m, c[max_n], w[max_n], ans;
bool nu[max_n];
int main() {
ios_base::sync_with_stdio(false);
cin >> n >> m;
for (int i = 0; i < n; i++) cin >> c[i];
for (int i = 0; i < n; i++) {
cin >> w[i];
if (m >= c[i] % 100) {
m -= c[i] % 100;
if (c[i] % 100 != 0) {
q.insert(make_pair((100 - c[i] % 100) * w[i], i));
nu[i] = true;
}
} else {
iter = q.begin();
if (iter != q.end() && (100 - c[i] % 100) * w[i] > iter->first) {
m += 100;
ans += iter->first;
nu[iter->second] = false;
q.erase(iter);
m -= c[i] % 100;
q.insert(make_pair((100 - c[i] % 100) * w[i], i));
nu[i] = true;
} else {
m += 100 - c[i] % 100;
ans += (100 - c[i] % 100) * w[i];
}
}
}
cout << ans << '\n';
for (int i = 0; i < n; i++)
if (nu[i])
cout << c[i] / 100 << " " << c[i] % 100 << endl;
else
cout << c[i] / 100 + (c[i] % 100 > 0) << " " << 0 << endl;
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Ori and Sein have overcome many difficult challenges. They finally lit the Shrouded Lantern and found Gumon Seal, the key to the Forlorn Ruins. When they tried to open the door to the ruins... nothing happened.
Ori was very surprised, but Sein gave the explanation quickly: clever Gumon decided to make an additional defence for the door.
There are n lamps with Spirit Tree's light. Sein knows the time of turning on and off for the i-th lamp β l_i and r_i respectively. To open the door you have to choose k lamps in such a way that there will be a moment of time when they all will be turned on.
While Sein decides which of the k lamps to pick, Ori is interested: how many ways there are to pick such k lamps that the door will open? It may happen that Sein may be wrong and there are no such k lamps. The answer might be large, so print it modulo 998 244 353.
Input
First line contains two integers n and k (1 β€ n β€ 3 β
10^5, 1 β€ k β€ n) β total number of lamps and the number of lamps that must be turned on simultaneously.
Next n lines contain two integers l_i ans r_i (1 β€ l_i β€ r_i β€ 10^9) β period of time when i-th lamp is turned on.
Output
Print one integer β the answer to the task modulo 998 244 353.
Examples
Input
7 3
1 7
3 8
4 5
6 7
1 3
5 10
8 9
Output
9
Input
3 1
1 1
2 2
3 3
Output
3
Input
3 2
1 1
2 2
3 3
Output
0
Input
3 3
1 3
2 3
3 3
Output
1
Input
5 2
1 3
2 4
3 5
4 6
5 7
Output
7
Note
In first test case there are nine sets of k lamps: (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 3, 6), (1, 4, 6), (2, 3, 6), (2, 4, 6), (2, 6, 7).
In second test case k=1, so the answer is 3.
In third test case there are no such pairs of lamps.
In forth test case all lamps are turned on in a time 3, so the answer is 1.
In fifth test case there are seven sets of k lamps: (1, 2), (1, 3), (2, 3), (2, 4), (3, 4), (3, 5), (4, 5).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int fac[300005];
bool comp(pair<long long int, long long int> p1,
pair<long long int, long long int> p2) {
if (p1.first < p2.first) return 1;
if (p1.first == p2.first && p1.second < p2.second) return 1;
return 0;
}
void calc() {
fac[0] = 1;
for (long long int i = 1; i <= 300005; i++)
fac[i] = (fac[i - 1] % 998244353 * i % 998244353) % 998244353;
}
long long int power(long long int x, long long int y, long long int p) {
long long int res = 1;
x = x % p;
while (y > 0) {
if (y & 1) res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
long long int modInverse(long long int n, long long int p) {
return power(n, p - 2, p);
}
long long int nCrModPFermat(long long int n, long long int r, long long int p) {
if (r == 0) return 1;
return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) %
p;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cout.precision(15);
long long int t;
t = 1;
calc();
while (t--) {
long long int n, k;
cin >> n >> k;
vector<pair<long long int, long long int>> v(n);
long long int res = 0;
for (long long int i = 0; i < n; i++) cin >> v[i].first >> v[i].second;
if (k == 1) {
cout << n << "\n";
continue;
}
sort(v.begin(), v.end(), comp);
multiset<long long int> m;
for (long long int i = 0; i < n; i++) {
while (m.size() && *m.begin() < v[i].first) m.erase(m.begin());
long long int p = m.size();
if (p >= k - 1)
res = (res + nCrModPFermat(p, k - 1, 998244353)) % 998244353;
m.insert(v[i].second);
}
cout << res << "\n";
}
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Write a program which reads a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and swap specified elements by a list of the following operation:
* swapRange($b, e, t$): For each integer $k$ ($0 \leq k < (e - b)$, swap element $(b + k)$ and element $(t + k)$.
Constraints
* $1 \leq n \leq 1,000$
* $-1,000,000,000 \leq a_i \leq 1,000,000,000$
* $1 \leq q \leq 1,000$
* $0 \leq b_i < e_i \leq n$
* $0 \leq t_i < t_i + (e_i - b_i) \leq n$
* Given swap ranges do not overlap each other
Input
The input is given in the following format.
$n$
$a_0 \; a_1 \; ...,\; a_{n-1}$
$q$
$b_1 \; e_1 \; t_1$
$b_2 \; e_2 \; t_2$
:
$b_{q} \; e_{q} \; t_{q}$
In the first line, $n$ (the number of elements in $A$) is given. In the second line, $a_i$ (each element in $A$) are given. In the third line, the number of queries $q$ is given and each query is given by three integers $b_i \; e_i \; t_i$ in the following $q$ lines.
Output
Print all elements of $A$ in a line after performing the given operations. Put a single space character between adjacency elements and a newline at the end of the last element.
Example
Input
11
1 2 3 4 5 6 7 8 9 10 11
1
1 4 7
Output
1 8 9 10 5 6 7 2 3 4 11
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
unsigned int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
int q;
cin >> q;
while (q--) {
int b, e, t;
cin >> b >> e >> t;
swap_ranges(a.begin() + b, a.begin() + e, a.begin() + t);
}
for (int i = 0; i < a.size(); ++i) {
cout << (i ? " " : "") << a[i];
}
cout << endl;
return 0;
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.