text
stringlengths 424
69.5k
|
---|
### Prompt
Your task is to create a CPP solution to the following problem:
Dreamoon has a string s and a pattern string p. He first removes exactly x characters from s obtaining string s' as a result. Then he calculates <image> that is defined as the maximal number of non-overlapping substrings equal to p that can be found in s'. He wants to make this number as big as possible.
More formally, let's define <image> as maximum value of <image> over all s' that can be obtained by removing exactly x characters from s. Dreamoon wants to know <image> for all x from 0 to |s| where |s| denotes the length of string s.
Input
The first line of the input contains the string s (1 β€ |s| β€ 2 000).
The second line of the input contains the string p (1 β€ |p| β€ 500).
Both strings will only consist of lower case English letters.
Output
Print |s| + 1 space-separated integers in a single line representing the <image> for all x from 0 to |s|.
Examples
Input
aaaaa
aa
Output
2 2 1 1 0 0
Input
axbaxxb
ab
Output
0 1 1 2 1 1 0 0
Note
For the first sample, the corresponding optimal values of s' after removal 0 through |s| = 5 characters from s are {"aaaaa", "aaaa", "aaa", "aa", "a", ""}.
For the second sample, possible corresponding optimal values of s' are {"axbaxxb", "abaxxb", "axbab", "abab", "aba", "ab", "a", ""}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
char str[2010], pattern[2010];
int dp[2010][2010];
int main(void) {
scanf("%s", str);
scanf("%s", pattern);
int len1 = (int)strlen(str);
int len2 = (int)strlen(pattern);
for (int i = 1; i <= len1; ++i) {
int k = len2, j = i;
while (k > 0 && j > 0) {
if (pattern[k - 1] == str[j - 1]) k--;
j--;
}
if (k == 0) {
int del = i - j - len2;
for (int f = del; f <= i - len2; ++f)
dp[i][f] = max(dp[i][f], dp[j][f - del] + 1);
}
for (int f = 0; f < i; ++f) dp[i][f] = max(dp[i][f], dp[i - 1][f]);
}
for (int i = 0; i <= len1; ++i) printf("%d ", dp[len1][i]);
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
There are n points on a plane. The i-th point has coordinates (x_i, y_i). You have two horizontal platforms, both of length k. Each platform can be placed anywhere on a plane but it should be placed horizontally (on the same y-coordinate) and have integer borders. If the left border of the platform is (x, y) then the right border is (x + k, y) and all points between borders (including borders) belong to the platform.
Note that platforms can share common points (overlap) and it is not necessary to place both platforms on the same y-coordinate.
When you place both platforms on a plane, all points start falling down decreasing their y-coordinate. If a point collides with some platform at some moment, the point stops and is saved. Points which never collide with any platform are lost.
Your task is to find the maximum number of points you can save if you place both platforms optimally.
You have to answer t independent test cases.
For better understanding, please read the Note section below to see a picture for the first test case.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 10^9) β the number of points and the length of each platform, respectively. The second line of the test case contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ 10^9), where x_i is x-coordinate of the i-th point. The third line of the input contains n integers y_1, y_2, ..., y_n (1 β€ y_i β€ 10^9), where y_i is y-coordinate of the i-th point. All points are distinct (there is no pair 1 β€ i < j β€ n such that x_i = x_j and y_i = y_j).
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer: the maximum number of points you can save if you place both platforms optimally.
Example
Input
4
7 1
1 5 2 3 1 5 4
1 3 6 7 2 5 4
1 1
1000000000
1000000000
5 10
10 7 5 15 8
20 199 192 219 1904
10 10
15 19 8 17 20 10 9 2 10 19
12 13 6 17 1 14 7 9 19 3
Output
6
1
5
10
Note
The picture corresponding to the first test case of the example:
<image>
Blue dots represent the points, red segments represent the platforms. One of the possible ways is to place the first platform between points (1, -1) and (2, -1) and the second one between points (4, 3) and (5, 3). Vectors represent how the points will fall down. As you can see, the only point we can't save is the point (3, 7) so it falls down infinitely and will be lost. It can be proven that we can't achieve better answer here. Also note that the point (5, 3) doesn't fall at all because it is already on the platform.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int t, n, k;
int x[200005];
int y[200005];
int count1[200005];
int max1[200005];
int main() {
cin >> t;
for (int i = 0; i < t; i++) {
cin >> n >> k;
for (int j = 1; j <= n; j++) {
cin >> x[j];
}
for (int j = 1; j <= n; j++) {
cin >> y[i];
}
sort(x + 1, x + n + 1);
for (int j = 1; j <= n; j++) {
count1[j] = upper_bound(x + 1, x + n + 1, x[j] + k) - (x + j);
}
for (int j = 1; j <= n; j++) {
max1[j] = max(max1[j - 1], count1[j]);
}
int max2 = 0;
for (int j = 1; j <= n; j++) {
int temp = upper_bound(x + 1, x + n + 1, x[j] - k - 1) - (x + 1);
max2 = max(max2, max1[temp] + count1[j]);
}
cout << max2 << endl;
}
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Today Pari and Arya are playing a game called Remainders.
Pari chooses two positive integer x and k, and tells Arya k but not x. Arya have to find the value <image>. There are n ancient numbers c1, c2, ..., cn and Pari has to tell Arya <image> if Arya wants. Given k and the ancient values, tell us if Arya has a winning strategy independent of value of x or not. Formally, is it true that Arya can understand the value <image> for any positive integer x?
Note, that <image> means the remainder of x after dividing it by y.
Input
The first line of the input contains two integers n and k (1 β€ n, k β€ 1 000 000) β the number of ancient integers and value k that is chosen by Pari.
The second line contains n integers c1, c2, ..., cn (1 β€ ci β€ 1 000 000).
Output
Print "Yes" (without quotes) if Arya has a winning strategy independent of value of x, or "No" (without quotes) otherwise.
Examples
Input
4 5
2 3 5 12
Output
Yes
Input
2 7
2 3
Output
No
Note
In the first sample, Arya can understand <image> because 5 is one of the ancient numbers.
In the second sample, Arya can't be sure what <image> is. For example 1 and 7 have the same remainders after dividing by 2 and 3, but they differ in remainders after dividing by 7.
### 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);
}
int main() {
long long int n, k;
scanf("%lld %lld\n", &n, &k);
long long int value = 1;
long long int curr;
for (long long int i = 0; i < n; i++) {
scanf("%lld", &curr);
value = gcd(k, value * curr / gcd(value, curr));
}
if (value == k) {
printf("Yes\n");
} else {
printf("No\n");
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold:
1. The product of all numbers in the first set is less than zero ( < 0).
2. The product of all numbers in the second set is greater than zero ( > 0).
3. The product of all numbers in the third set is equal to zero.
4. Each number from the initial array must occur in exactly one set.
Help Vitaly. Divide the given array.
Input
The first line of the input contains integer n (3 β€ n β€ 100). The second line contains n space-separated distinct integers a1, a2, ..., an (|ai| β€ 103) β the array elements.
Output
In the first line print integer n1 (n1 > 0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set.
In the next line print integer n2 (n2 > 0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set.
In the next line print integer n3 (n3 > 0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set.
The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them.
Examples
Input
3
-1 2 0
Output
1 -1
1 2
1 0
Input
4
-1 -2 -3 0
Output
1 -1
2 -3 -2
1 0
### Response
```cpp
#include <bits/stdc++.h>
int n, i, z = 0, x = 0, c = 0, a, s[10001], t[10001], r[10001];
int main() {
scanf("%d", &n);
for (i = 1; i <= n; i++) {
scanf("%d", &a);
if (a > 0) {
z++;
s[z] = a;
} else if (a == 0) {
x++;
t[x] = a;
} else {
c++;
r[c] = a;
}
}
if (c % 2 == 0) {
x++;
t[x] = r[c];
c--;
}
if (z == 0) {
z = 2;
s[1] = r[c];
s[2] = r[c - 1];
c = c - 2;
}
printf("%d ", c);
for (i = 1; i <= c; i++) printf("%d ", r[i]);
printf("\n");
printf("%d ", z);
for (i = 1; i <= z; i++) printf("%d ", s[i]);
printf("\n");
printf("%d ", x);
for (i = 1; i <= x; i++) printf("%d ", t[i]);
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apartment has three windows, a five-room β five windows, and a seven-room β seven windows.
Monocarp went around the building and counted n windows. Now he is wondering, how many apartments of each type the building may have.
Unfortunately, Monocarp only recently has learned to count, so he is asking you to help him to calculate the possible quantities of three-room, five-room, and seven-room apartments in the building that has n windows. If there are multiple answers, you can print any of them.
Here are some examples:
* if Monocarp has counted 30 windows, there could have been 2 three-room apartments, 2 five-room apartments and 2 seven-room apartments, since 2 β
3 + 2 β
5 + 2 β
7 = 30;
* if Monocarp has counted 67 windows, there could have been 7 three-room apartments, 5 five-room apartments and 3 seven-room apartments, since 7 β
3 + 5 β
5 + 3 β
7 = 67;
* if Monocarp has counted 4 windows, he should have mistaken since no building with the aforementioned layout can have 4 windows.
Input
Th first line contains one integer t (1 β€ t β€ 1000) β the number of test cases.
The only line of each test case contains one integer n (1 β€ n β€ 1000) β the number of windows in the building.
Output
For each test case, if a building with the new layout and the given number of windows just can't exist, print -1.
Otherwise, print three non-negative integers β the possible number of three-room, five-room, and seven-room apartments. If there are multiple answers, print any of them.
Example
Input
4
30
67
4
14
Output
2 2 2
7 5 3
-1
0 0 2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void count(int n) {
for (int a = 0; a * 3 <= n; a++) {
for (int b = 0; a * 3 + b * 5 <= n; b++) {
for (int c = 0; a * 3 + b * 5 + c * 7 <= n; c++) {
if (a * 3 + b * 5 + c * 7 == n) {
cout << a << ' ' << b << ' ' << c << endl;
return;
}
}
}
}
cout << -1 << endl;
}
int main() {
int t, n;
cin >> t;
for (int i = 0; i < t; i++) {
cin >> n;
count(n);
}
}
``` |
### Prompt
Generate a CPP solution to the following problem:
A schoolboy Petya studies square equations. The equations that are included in the school curriculum, usually look simple:
x2 + 2bx + c = 0 where b, c are natural numbers.
Petya noticed that some equations have two real roots, some of them have only one root and some equations don't have real roots at all. Moreover it turned out that several different square equations can have a common root.
Petya is interested in how many different real roots have all the equations of the type described above for all the possible pairs of numbers b and c such that 1 β€ b β€ n, 1 β€ c β€ m. Help Petya find that number.
Input
The single line contains two integers n and m. (1 β€ n, m β€ 5000000).
Output
Print a single number which is the number of real roots of the described set of equations.
Examples
Input
3 3
Output
12
Input
1 2
Output
1
Note
In the second test from the statement the following equations are analysed:
b = 1, c = 1: x2 + 2x + 1 = 0; The root is x = - 1
b = 1, c = 2: x2 + 2x + 2 = 0; No roots
Overall there's one root
In the second test the following equations are analysed:
b = 1, c = 1: x2 + 2x + 1 = 0; The root is x = - 1
b = 1, c = 2: x2 + 2x + 2 = 0; No roots
b = 1, c = 3: x2 + 2x + 3 = 0; No roots
b = 2, c = 1: x2 + 4x + 1 = 0; The roots are <image>
b = 2, c = 2: x2 + 4x + 2 = 0; The roots are <image>
b = 2, c = 3: x2 + 4x + 3 = 0; The roots are x1 = - 3, x2 = - 1
b = 3, c = 1: x2 + 6x + 1 = 0; The roots are <image>
b = 3, c = 2: x2 + 6x + 2 = 0; The roots are <image>
b = 3, c = 3: x2 + 6x + 3 = 0; The roots are <image> Overall there are 13 roots and as the root - 1 is repeated twice, that means there are 12 different roots.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int mark[5000000 * 4], n, m;
long long num(long long x) {
long long g = (int)sqrt(x * 1.0);
while (((g) * (g)) <= x) g++;
while (((g) * (g)) > x) g--;
return g;
}
int main() {
scanf("%d%d", &n, &m);
long long ans = 0;
for (int b = 1; b <= n; b++) {
long long max_c = min((long long)m, (((long long)b) * ((long long)b)));
ans += max_c * 2;
long long x = (((long long)b) * ((long long)b)) - max_c,
y = (((long long)b) * ((long long)b)) - 1;
long long l = num(x), r = num(y);
if (((l) * (l)) < x) l++;
ans -= (r - l + 1) * 2;
mark[-b - r + n * 3]++;
mark[-b - l + 1 + n * 3]--;
mark[-b + l + n * 3]++;
mark[-b + r + 1 + n * 3]--;
}
for (int i = 0, k = 0; i < n * 4; i++) {
k += mark[i];
if (k) ans++;
}
printf("%I64d\n", ans);
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Last year Bob earned by selling memory sticks. During each of n days of his work one of the two following events took place:
* A customer came to Bob and asked to sell him a 2x MB memory stick. If Bob had such a stick, he sold it and got 2x berllars.
* Bob won some programming competition and got a 2x MB memory stick as a prize. Bob could choose whether to present this memory stick to one of his friends, or keep it.
Bob never kept more than one memory stick, as he feared to mix up their capacities, and deceive a customer unintentionally. It is also known that for each memory stick capacity there was at most one customer, who wanted to buy that memory stick. Now, knowing all the customers' demands and all the prizes won at programming competitions during the last n days, Bob wants to know, how much money he could have earned, if he had acted optimally.
Input
The first input line contains number n (1 β€ n β€ 5000) β amount of Bob's working days. The following n lines contain the description of the days. Line sell x stands for a day when a customer came to Bob to buy a 2x MB memory stick (0 β€ x β€ 2000). It's guaranteed that for each x there is not more than one line sell x. Line win x stands for a day when Bob won a 2x MB memory stick (0 β€ x β€ 2000).
Output
Output the maximum possible earnings for Bob in berllars, that he would have had if he had known all the events beforehand. Don't forget, please, that Bob can't keep more than one memory stick at a time.
Examples
Input
7
win 10
win 5
win 3
sell 5
sell 3
win 10
sell 10
Output
1056
Input
3
win 5
sell 6
sell 4
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef int bignum_t[10000 + 1];
int read(bignum_t a, istream& is = cin) {
char buf[10000 * 4 + 1], ch;
int i, j;
memset((void*)a, 0, sizeof(bignum_t));
if (!(is >> buf)) return 0;
for (a[0] = strlen(buf), i = a[0] / 2 - 1; i >= 0; i--)
ch = buf[i], buf[i] = buf[a[0] - 1 - i], buf[a[0] - 1 - i] = ch;
for (a[0] = (a[0] + 4 - 1) / 4, j = strlen(buf); j < a[0] * 4; buf[j++] = '0')
;
for (i = 1; i <= a[0]; i++)
for (a[i] = 0, j = 0; j < 4; j++)
a[i] = a[i] * 10 + buf[i * 4 - 1 - j] - '0';
for (; !a[a[0]] && a[0] > 1; a[0]--)
;
return 1;
}
void write(const bignum_t a, ostream& os = cout) {
int i, j;
for (os << a[i = a[0]], i--; i; i--)
for (j = 10000 / 10; j; j /= 10) os << a[i] / j % 10;
}
int comp(const bignum_t a, const bignum_t b) {
int i;
if (a[0] != b[0]) return a[0] - b[0];
for (i = a[0]; i; i--)
if (a[i] != b[i]) return a[i] - b[i];
return 0;
}
int comp(const bignum_t a, const int b) {
int c[12] = {1};
for (c[1] = b; c[c[0]] >= 10000;
c[c[0] + 1] = c[c[0]] / 10000, c[c[0]] %= 10000, c[0]++)
;
return comp(a, c);
}
int comp(const bignum_t a, const int c, const int d, const bignum_t b) {
int i, t = 0, O = -10000 * 2;
if (b[0] - a[0] < d && c) return 1;
for (i = b[0]; i > d; i--) {
t = t * 10000 + a[i - d] * c - b[i];
if (t > 0) return 1;
if (t < O) return 0;
}
for (i = d; i; i--) {
t = t * 10000 - b[i];
if (t > 0) return 1;
if (t < O) return 0;
}
return t > 0;
}
void add(bignum_t a, const bignum_t b) {
int i;
for (i = 1; i <= b[0]; i++)
if ((a[i] += b[i]) >= 10000) a[i] -= 10000, a[i + 1]++;
if (b[0] >= a[0])
a[0] = b[0];
else
for (; a[i] >= 10000 && i < a[0]; a[i] -= 10000, i++, a[i]++)
;
a[0] += (a[a[0] + 1] > 0);
}
void add(bignum_t a, const int b) {
int i = 1;
for (a[1] += b; a[i] >= 10000 && i < a[0];
a[i + 1] += a[i] / 10000, a[i] %= 10000, i++)
;
for (; a[a[0]] >= 10000;
a[a[0] + 1] = a[a[0]] / 10000, a[a[0]] %= 10000, a[0]++)
;
}
void sub(bignum_t a, const bignum_t b) {
int i;
for (i = 1; i <= b[0]; i++)
if ((a[i] -= b[i]) < 0) a[i + 1]--, a[i] += 10000;
for (; a[i] < 0; a[i] += 10000, i++, a[i]--)
;
for (; !a[a[0]] && a[0] > 1; a[0]--)
;
}
void sub(bignum_t a, const int b) {
int i = 1;
for (a[1] -= b; a[i] < 0; a[i + 1] += (a[i] - 10000 + 1) / 10000,
a[i] -= (a[i] - 10000 + 1) / 10000 * 10000, i++)
;
for (; !a[a[0]] && a[0] > 1; a[0]--)
;
}
void sub(bignum_t a, const bignum_t b, const int c, const int d) {
int i, O = b[0] + d;
for (i = 1 + d; i <= O; i++)
if ((a[i] -= b[i - d] * c) < 0)
a[i + 1] += (a[i] - 10000 + 1) / 10000,
a[i] -= (a[i] - 10000 + 1) / 10000 * 10000;
for (; a[i] < 0; a[i + 1] += (a[i] - 10000 + 1) / 10000,
a[i] -= (a[i] - 10000 + 1) / 10000 * 10000, i++)
;
for (; !a[a[0]] && a[0] > 1; a[0]--)
;
}
void mul(bignum_t c, const bignum_t a, const bignum_t b) {
int i, j;
memset((void*)c, 0, sizeof(bignum_t));
for (c[0] = a[0] + b[0] - 1, i = 1; i <= a[0]; i++)
for (j = 1; j <= b[0]; j++)
if ((c[i + j - 1] += a[i] * b[j]) >= 10000)
c[i + j] += c[i + j - 1] / 10000, c[i + j - 1] %= 10000;
for (c[0] += (c[c[0] + 1] > 0); !c[c[0]] && c[0] > 1; c[0]--)
;
}
void mul(bignum_t a, const int b) {
int i;
for (a[1] *= b, i = 2; i <= a[0]; i++) {
a[i] *= b;
if (a[i - 1] >= 10000) a[i] += a[i - 1] / 10000, a[i - 1] %= 10000;
}
for (; a[a[0]] >= 10000;
a[a[0] + 1] = a[a[0]] / 10000, a[a[0]] %= 10000, a[0]++)
;
for (; !a[a[0]] && a[0] > 1; a[0]--)
;
}
void mul(bignum_t b, const bignum_t a, const int c, const int d) {
int i;
memset((void*)b, 0, sizeof(bignum_t));
for (b[0] = a[0] + d, i = d + 1; i <= b[0]; i++)
if ((b[i] += a[i - d] * c) >= 10000)
b[i + 1] += b[i] / 10000, b[i] %= 10000;
for (; b[b[0] + 1]; b[0]++, b[b[0] + 1] = b[b[0]] / 10000, b[b[0]] %= 10000)
;
for (; !b[b[0]] && b[0] > 1; b[0]--)
;
}
void div(bignum_t c, bignum_t a, const bignum_t b) {
int h, l, m, i;
memset((void*)c, 0, sizeof(bignum_t));
c[0] = (b[0] < a[0] + 1) ? (a[0] - b[0] + 2) : 1;
for (i = c[0]; i; sub(a, b, c[i] = m, i - 1), i--)
for (h = 10000 - 1, l = 0, m = (h + l + 1) >> 1; h > l;
m = (h + l + 1) >> 1)
if (comp(b, m, i - 1, a))
h = m - 1;
else
l = m;
for (; !c[c[0]] && c[0] > 1; c[0]--)
;
c[0] = c[0] > 1 ? c[0] : 1;
}
void div(bignum_t a, const int b, int& c) {
int i;
for (c = 0, i = a[0]; i; c = c * 10000 + a[i], a[i] = c / b, c %= b, i--)
;
for (; !a[a[0]] && a[0] > 1; a[0]--)
;
}
void sqrt(bignum_t b, bignum_t a) {
int h, l, m, i;
memset((void*)b, 0, sizeof(bignum_t));
for (i = b[0] = (a[0] + 1) >> 1; i; sub(a, b, m, i - 1), b[i] += m, i--)
for (h = 10000 - 1, l = 0, b[i] = m = (h + l + 1) >> 1; h > l;
b[i] = m = (h + l + 1) >> 1)
if (comp(b, m, i - 1, a))
h = m - 1;
else
l = m;
for (; !b[b[0]] && b[0] > 1; b[0]--)
;
for (i = 1; i <= b[0]; b[i++] >>= 1)
;
}
int length(const bignum_t a) {
int t, ret;
for (ret = (a[0] - 1) * 4, t = a[a[0]]; t; t /= 10, ret++)
;
return ret > 0 ? ret : 1;
}
int digit(const bignum_t a, const int b) {
int i, ret;
for (ret = a[(b - 1) / 4 + 1], i = (b - 1) % 4; i; ret /= 10, i--)
;
return ret % 10;
}
int zeronum(const bignum_t a) {
int ret, t;
for (ret = 0; !a[ret + 1]; ret++)
;
for (t = a[ret + 1], ret *= 4; !(t % 10); t /= 10, ret++)
;
return ret;
}
void comp(int* a, const int l, const int h, const int d) {
int i, j, t;
for (i = l; i <= h; i++)
for (t = i, j = 2; t > 1; j++)
while (!(t % j)) a[j] += d, t /= j;
}
void convert(int* a, const int h, bignum_t b) {
int i, j, t = 1;
memset(b, 0, sizeof(bignum_t));
for (b[0] = b[1] = 1, i = 2; i <= h; i++)
if (a[i])
for (j = a[i]; j; t *= i, j--)
if (t * i > 10000) mul(b, t), t = 1;
mul(b, t);
}
void combination(bignum_t a, int m, int n) {
int* t = new int[m + 1];
memset((void*)t, 0, sizeof(int) * (m + 1));
comp(t, n + 1, m, 1);
comp(t, 2, m - n, -1);
convert(t, m, a);
delete[] t;
}
void permutation(bignum_t a, int m, int n) {
int i, t = 1;
memset(a, 0, sizeof(bignum_t));
a[0] = a[1] = 1;
for (i = m - n + 1; i <= m; t *= i++)
if (t * i > 10000) mul(a, t), t = 1;
mul(a, t);
}
int read(bignum_t a, int& sgn, istream& is = cin) {
char str[10000 * 4 + 2], ch, *buf;
int i, j;
memset((void*)a, 0, sizeof(bignum_t));
if (!(is >> str)) return 0;
buf = str, sgn = 1;
if (*buf == '-') sgn = -1, buf++;
for (a[0] = strlen(buf), i = a[0] / 2 - 1; i >= 0; i--)
ch = buf[i], buf[i] = buf[a[0] - 1 - i], buf[a[0] - 1 - i] = ch;
for (a[0] = (a[0] + 4 - 1) / 4, j = strlen(buf); j < a[0] * 4; buf[j++] = '0')
;
for (i = 1; i <= a[0]; i++)
for (a[i] = 0, j = 0; j < 4; j++)
a[i] = a[i] * 10 + buf[i * 4 - 1 - j] - '0';
for (; !a[a[0]] && a[0] > 1; a[0]--)
;
if (a[0] == 1 && !a[1]) sgn = 0;
return 1;
}
struct bignum {
bignum_t num;
int sgn;
public:
inline bignum() {
memset(num, 0, sizeof(bignum_t));
num[0] = 1;
sgn = 0;
}
inline int operator!() { return num[0] == 1 && !num[1]; }
inline bignum& operator=(const bignum& a) {
memcpy(num, a.num, sizeof(bignum_t));
sgn = a.sgn;
return *this;
}
inline bignum& operator=(const int a) {
memset(num, 0, sizeof(bignum_t));
num[0] = 1;
sgn = ((a) > 0 ? 1 : ((a) < 0 ? -1 : 0));
add(num, sgn * a);
return *this;
};
inline bignum& operator+=(const bignum& a) {
if (sgn == a.sgn)
add(num, a.num);
else if (sgn && a.sgn) {
int ret = comp(num, a.num);
if (ret > 0)
sub(num, a.num);
else if (ret < 0) {
bignum_t t;
memcpy(t, num, sizeof(bignum_t));
memcpy(num, a.num, sizeof(bignum_t));
sub(num, t);
sgn = a.sgn;
} else
memset(num, 0, sizeof(bignum_t)), num[0] = 1, sgn = 0;
} else if (!sgn)
memcpy(num, a.num, sizeof(bignum_t)), sgn = a.sgn;
return *this;
}
inline bignum& operator+=(const int a) {
if (sgn * a > 0)
add(num, ((a) > 0 ? (a) : -(a)));
else if (sgn && a) {
int ret = comp(num, ((a) > 0 ? (a) : -(a)));
if (ret > 0)
sub(num, ((a) > 0 ? (a) : -(a)));
else if (ret < 0) {
bignum_t t;
memcpy(t, num, sizeof(bignum_t));
memset(num, 0, sizeof(bignum_t));
num[0] = 1;
add(num, ((a) > 0 ? (a) : -(a)));
sgn = -sgn;
sub(num, t);
} else
memset(num, 0, sizeof(bignum_t)), num[0] = 1, sgn = 0;
} else if (!sgn)
sgn = ((a) > 0 ? 1 : ((a) < 0 ? -1 : 0)),
add(num, ((a) > 0 ? (a) : -(a)));
return *this;
}
inline bignum operator+(const bignum& a) {
bignum ret;
memcpy(ret.num, num, sizeof(bignum_t));
ret.sgn = sgn;
ret += a;
return ret;
}
inline bignum operator+(const int a) {
bignum ret;
memcpy(ret.num, num, sizeof(bignum_t));
ret.sgn = sgn;
ret += a;
return ret;
}
inline bignum& operator-=(const bignum& a) {
if (sgn * a.sgn < 0)
add(num, a.num);
else if (sgn && a.sgn) {
int ret = comp(num, a.num);
if (ret > 0)
sub(num, a.num);
else if (ret < 0) {
bignum_t t;
memcpy(t, num, sizeof(bignum_t));
memcpy(num, a.num, sizeof(bignum_t));
sub(num, t);
sgn = -sgn;
} else
memset(num, 0, sizeof(bignum_t)), num[0] = 1, sgn = 0;
} else if (!sgn)
add(num, a.num), sgn = -a.sgn;
return *this;
}
inline bignum& operator-=(const int a) {
if (sgn * a < 0)
add(num, ((a) > 0 ? (a) : -(a)));
else if (sgn && a) {
int ret = comp(num, ((a) > 0 ? (a) : -(a)));
if (ret > 0)
sub(num, ((a) > 0 ? (a) : -(a)));
else if (ret < 0) {
bignum_t t;
memcpy(t, num, sizeof(bignum_t));
memset(num, 0, sizeof(bignum_t));
num[0] = 1;
add(num, ((a) > 0 ? (a) : -(a)));
sub(num, t);
sgn = -sgn;
} else
memset(num, 0, sizeof(bignum_t)), num[0] = 1, sgn = 0;
} else if (!sgn)
sgn = -((a) > 0 ? 1 : ((a) < 0 ? -1 : 0)),
add(num, ((a) > 0 ? (a) : -(a)));
return *this;
}
inline bignum operator-(const bignum& a) {
bignum ret;
memcpy(ret.num, num, sizeof(bignum_t));
ret.sgn = sgn;
ret -= a;
return ret;
}
inline bignum operator-(const int a) {
bignum ret;
memcpy(ret.num, num, sizeof(bignum_t));
ret.sgn = sgn;
ret -= a;
return ret;
}
inline bignum& operator*=(const bignum& a) {
bignum_t t;
mul(t, num, a.num);
memcpy(num, t, sizeof(bignum_t));
sgn *= a.sgn;
return *this;
}
inline bignum& operator*=(const int a) {
mul(num, ((a) > 0 ? (a) : -(a)));
sgn *= ((a) > 0 ? 1 : ((a) < 0 ? -1 : 0));
return *this;
}
inline bignum operator*(const bignum& a) {
bignum ret;
mul(ret.num, num, a.num);
ret.sgn = sgn * a.sgn;
return ret;
}
inline bignum operator*(const int a) {
bignum ret;
memcpy(ret.num, num, sizeof(bignum_t));
mul(ret.num, ((a) > 0 ? (a) : -(a)));
ret.sgn = sgn * ((a) > 0 ? 1 : ((a) < 0 ? -1 : 0));
return ret;
}
inline bignum& operator/=(const bignum& a) {
bignum_t t;
div(t, num, a.num);
memcpy(num, t, sizeof(bignum_t));
sgn = (num[0] == 1 && !num[1]) ? 0 : sgn * a.sgn;
return *this;
}
inline bignum& operator/=(const int a) {
int t;
div(num, ((a) > 0 ? (a) : -(a)), t);
sgn =
(num[0] == 1 && !num[1]) ? 0 : sgn * ((a) > 0 ? 1 : ((a) < 0 ? -1 : 0));
return *this;
}
inline bignum operator/(const bignum& a) {
bignum ret;
bignum_t t;
memcpy(t, num, sizeof(bignum_t));
div(ret.num, t, a.num);
ret.sgn = (ret.num[0] == 1 && !ret.num[1]) ? 0 : sgn * a.sgn;
return ret;
}
inline bignum operator/(const int a) {
bignum ret;
int t;
memcpy(ret.num, num, sizeof(bignum_t));
div(ret.num, ((a) > 0 ? (a) : -(a)), t);
ret.sgn = (ret.num[0] == 1 && !ret.num[1])
? 0
: sgn * ((a) > 0 ? 1 : ((a) < 0 ? -1 : 0));
return ret;
}
inline bignum& operator%=(const bignum& a) {
bignum_t t;
div(t, num, a.num);
if (num[0] == 1 && !num[1]) sgn = 0;
return *this;
}
inline int operator%=(const int a) {
int t;
div(num, ((a) > 0 ? (a) : -(a)), t);
memset(num, 0, sizeof(bignum_t));
num[0] = 1;
add(num, t);
return t;
}
inline bignum operator%(const bignum& a) {
bignum ret;
bignum_t t;
memcpy(ret.num, num, sizeof(bignum_t));
div(t, ret.num, a.num);
ret.sgn = (ret.num[0] == 1 && !ret.num[1]) ? 0 : sgn;
return ret;
}
inline int operator%(const int a) {
bignum ret;
int t;
memcpy(ret.num, num, sizeof(bignum_t));
div(ret.num, ((a) > 0 ? (a) : -(a)), t);
memset(ret.num, 0, sizeof(bignum_t));
ret.num[0] = 1;
add(ret.num, t);
return t;
}
inline bignum& operator++() {
*this += 1;
return *this;
}
inline bignum& operator--() {
*this -= 1;
return *this;
};
inline int operator>(const bignum& a) {
return sgn > 0
? (a.sgn > 0 ? comp(num, a.num) > 0 : 1)
: (sgn < 0 ? (a.sgn < 0 ? comp(num, a.num) < 0 : 0) : a.sgn < 0);
}
inline int operator>(const int a) {
return sgn > 0 ? (a > 0 ? comp(num, a) > 0 : 1)
: (sgn < 0 ? (a < 0 ? comp(num, -a) < 0 : 0) : a < 0);
}
inline int operator>=(const bignum& a) {
return sgn > 0 ? (a.sgn > 0 ? comp(num, a.num) >= 0 : 1)
: (sgn < 0 ? (a.sgn < 0 ? comp(num, a.num) <= 0 : 0)
: a.sgn <= 0);
}
inline int operator>=(const int a) {
return sgn > 0 ? (a > 0 ? comp(num, a) >= 0 : 1)
: (sgn < 0 ? (a < 0 ? comp(num, -a) <= 0 : 0) : a <= 0);
}
inline int operator<(const bignum& a) {
return sgn < 0
? (a.sgn < 0 ? comp(num, a.num) > 0 : 1)
: (sgn > 0 ? (a.sgn > 0 ? comp(num, a.num) < 0 : 0) : a.sgn > 0);
}
inline int operator<(const int a) {
return sgn < 0 ? (a < 0 ? comp(num, -a) > 0 : 1)
: (sgn > 0 ? (a > 0 ? comp(num, a) < 0 : 0) : a > 0);
}
inline int operator<=(const bignum& a) {
return sgn < 0 ? (a.sgn < 0 ? comp(num, a.num) >= 0 : 1)
: (sgn > 0 ? (a.sgn > 0 ? comp(num, a.num) <= 0 : 0)
: a.sgn >= 0);
}
inline int operator<=(const int a) {
return sgn < 0 ? (a < 0 ? comp(num, -a) >= 0 : 1)
: (sgn > 0 ? (a > 0 ? comp(num, a) <= 0 : 0) : a >= 0);
}
inline int operator==(const bignum& a) {
return (sgn == a.sgn) ? !comp(num, a.num) : 0;
}
inline int operator==(const int a) {
return (sgn * a >= 0) ? !comp(num, ((a) > 0 ? (a) : -(a))) : 0;
}
inline int operator!=(const bignum& a) {
return (sgn == a.sgn) ? comp(num, a.num) : 1;
}
inline int operator!=(const int a) {
return (sgn * a >= 0) ? comp(num, ((a) > 0 ? (a) : -(a))) : 1;
}
inline int operator[](const int a) { return digit(num, a); }
friend inline istream& operator>>(istream& is, bignum& a) {
read(a.num, a.sgn, is);
return is;
}
friend inline ostream& operator<<(ostream& os, const bignum& a) {
if (a.sgn < 0) os << '-';
write(a.num, os);
return os;
}
friend inline bignum sqrt(const bignum& a) {
bignum ret;
bignum_t t;
memcpy(t, a.num, sizeof(bignum_t));
sqrt(ret.num, t);
ret.sgn = ret.num[0] != 1 || ret.num[1];
return ret;
}
friend inline bignum sqrt(const bignum& a, bignum& b) {
bignum ret;
memcpy(b.num, a.num, sizeof(bignum_t));
sqrt(ret.num, b.num);
ret.sgn = ret.num[0] != 1 || ret.num[1];
b.sgn = b.num[0] != 1 || ret.num[1];
return ret;
}
inline int length() { return ::length(num); }
inline int zeronum() { return ::zeronum(num); }
inline bignum C(const int m, const int n) {
combination(num, m, n);
sgn = 1;
return *this;
}
inline bignum P(const int m, const int n) {
permutation(num, m, n);
sgn = 1;
return *this;
}
};
int a[5002], b[5002], ans[5002], n;
int sum[5002 << 2], setv[5002 << 2];
void Up(int rt, int ls, int rs) { sum[rt] = sum[ls] + sum[rs]; }
void Down(int rt, int ls, int rs, int m) {
if (~setv[rt]) {
sum[ls] = m - (m >> 1), sum[rs] = m >> 1;
setv[ls] = setv[rs] = 1;
setv[rt] = -1;
}
}
void build(int l, int r, int rt) {
sum[rt] = 0;
setv[rt] = -1;
if (l == r) return;
int mid = (l + r) >> 1;
build(l, mid, rt << 1);
build(mid + 1, r, rt << 1 | 1);
}
void update(int L, int R, int l, int r, int rt) {
if (L == l && R == r) {
setv[rt] = 1;
sum[rt] = r - l + 1;
return;
}
int mid = (l + r) >> 1;
Down(rt, rt << 1, rt << 1 | 1, r - l + 1);
if (L > mid)
update(L, R, mid + 1, r, rt << 1 | 1);
else if (R <= mid)
update(L, R, l, mid, rt << 1);
else {
update(L, mid, l, mid, rt << 1);
update(mid + 1, R, mid + 1, r, rt << 1 | 1);
}
Up(rt, rt << 1, rt << 1 | 1);
}
int query(int L, int R, int l, int r, int rt) {
if (L == l && R == r) return sum[rt];
int mid = (l + r) >> 1;
Down(rt, rt << 1, rt << 1 | 1, r - l + 1);
if (L > mid)
return query(L, R, mid + 1, r, rt << 1 | 1);
else if (R <= mid)
return query(L, R, l, mid, rt << 1);
else
return query(L, mid, l, mid, rt << 1) +
query(mid + 1, R, mid + 1, r, rt << 1 | 1);
}
void solve() {
char s[10];
int u;
memset(a, -1, sizeof(a));
memset(b, -1, sizeof(b));
memset(ans, 0, sizeof(ans));
build(1, n, 1);
for (int i = 1; i <= n; ++i) {
scanf("%s%d", s, &u);
if (*s == 'w') {
if (~b[u])
continue;
else
a[u] = i;
} else
b[u] = i;
}
for (int i = 2000; i >= 0; --i) {
if (~a[i] && ~b[i] && a[i] < b[i]) {
if (0 == query(a[i], b[i], 1, n, 1)) {
update(a[i], b[i], 1, n, 1);
ans[i] = true;
}
}
}
bignum x;
for (int i = 2000; i >= 0; --i) {
x = x * 2;
if (ans[i]) x = x + 1;
}
cout << x << endl;
}
int main() {
while (1 == scanf("%d", &n)) {
solve();
}
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.
There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.
There are n cars in the rental service, i-th of them is characterized with two integers ci and vi β the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.
Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.
Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
Input
The first line contains four positive integers n, k, s and t (1 β€ n β€ 2Β·105, 1 β€ k β€ 2Β·105, 2 β€ s β€ 109, 1 β€ t β€ 2Β·109) β the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts.
Each of the next n lines contains two positive integers ci and vi (1 β€ ci, vi β€ 109) β the price of the i-th car and its fuel tank capacity.
The next line contains k distinct integers g1, g2, ..., gk (1 β€ gi β€ s - 1) β the positions of the gas stations on the road in arbitrary order.
Output
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
Examples
Input
3 1 8 10
10 8
5 7
11 9
3
Output
10
Input
2 2 10 18
10 4
20 6
5 3
Output
20
Note
In the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, k, s, t;
int g[200005], c[200005], v[200005], l[200005];
int suml[200005];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> n >> k >> s >> t;
for (int i = 1; i <= n; i++) {
cin >> c[i] >> v[i];
}
for (int i = 1; i <= k; i++) {
cin >> g[i];
}
k++;
sort(g + 1, g + k);
g[k] = s;
for (int i = 1; i <= k; i++) {
l[i] = g[i] - g[i - 1];
}
sort(l + 1, l + k + 1);
for (int i = 1; i <= k; i++) {
suml[i] = suml[i - 1] + l[i];
}
int mc = 1999999999;
for (int i = 1; i <= n; i++) {
int c = ::c[i];
int v = ::v[i];
if (v < l[k]) {
continue;
}
int split = upper_bound(l + 1, l + k + 1, v / 2) - l;
int t_fast = suml[split - 1];
long long t_eco =
3ll * (suml[k] - suml[split - 1]) - v * 1ll * (k - split + 1);
if (t_fast + t_eco <= t) {
mc = min(mc, c);
}
}
if (mc == 1999999999) {
mc = -1;
}
cout << mc;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
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;
template <typename T, typename U>
inline void smin(T &a, U b) {
if (a > b) a = b;
}
template <typename T, typename U>
inline void smax(T &a, U b) {
if (a < b) a = b;
}
template <class T>
inline void gn(T &first) {
char c, sg = 0;
while (c = getchar(), (c > '9' || c < '0') && c != '-')
;
for ((c == '-' ? sg = 1, c = getchar() : 0), first = 0; c >= '0' && c <= '9';
c = getchar())
first = (first << 1) + (first << 3) + c - '0';
if (sg) first = -first;
}
template <class T, class T1>
inline void gn(T &first, T1 &second) {
gn(first);
gn(second);
}
template <class T, class T1, class T2>
inline void gn(T &first, T1 &second, T2 &z) {
gn(first);
gn(second);
gn(z);
}
template <class T>
inline void print(T first) {
if (first < 0) {
putchar('-');
return print(-first);
}
if (first < 10) {
putchar('0' + first);
return;
}
print(first / 10);
putchar(first % 10 + '0');
}
template <class T>
inline void printsp(T first) {
print(first);
putchar(' ');
}
template <class T>
inline void println(T first) {
print(first);
putchar('\n');
}
int power(int a, int b, int m, int ans = 1) {
for (; b; b >>= 1, a = 1LL * a * a % m)
if (b & 1) ans = 1LL * ans * a % m;
return ans;
}
char str[2000100];
int pos[2000100], cnt[2000100];
int p[2000100], q[2000100];
int main() {
int n, k;
cin >> n >> k;
scanf("%s", str + 1);
int len = strlen(str + 1);
for (int i = 1; i <= len; i++)
p[i] = (p[i - 1] * 29LL + str[i] - 'a' + 1) % 1000000007;
long long pp = 1;
for (int i = len; i; i--) {
int l = len - i + 1;
q[l] = (q[l - 1] + pp * (str[i] - 'a' + 1)) % 1000000007;
pp = pp * 29 % 1000000007;
}
for (int i = 0; i < k; i++) gn(pos[i]), cnt[pos[i]]++, cnt[pos[i] + len]--;
for (int i = 0; i < k - 1; i++) {
int l = pos[i] + len - pos[i + 1];
if (l <= 0) continue;
if (p[l] != q[l]) {
puts("0");
return 0;
}
}
int nn = 0;
for (int i = 1; i <= n; i++) {
cnt[i] += cnt[i - 1];
if (cnt[i] == 0) nn++;
}
printf("%d\n", power(26, nn, 1000000007));
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Takahashi has N days of summer vacation.
His teacher gave him M summer assignments. It will take A_i days for him to do the i-th assignment.
He cannot do multiple assignments on the same day, or hang out on a day he does an assignment.
What is the maximum number of days Takahashi can hang out during the vacation if he finishes all the assignments during this vacation?
If Takahashi cannot finish all the assignments during the vacation, print `-1` instead.
Constraints
* 1 \leq N \leq 10^6
* 1 \leq M \leq 10^4
* 1 \leq A_i \leq 10^4
Input
Input is given from Standard Input in the following format:
N M
A_1 ... A_M
Output
Print the maximum number of days Takahashi can hang out during the vacation, or `-1`.
Examples
Input
41 2
5 6
Output
30
Input
10 2
5 6
Output
-1
Input
11 2
5 6
Output
0
Input
314 15
9 26 5 35 8 9 79 3 23 8 46 2 6 43 3
Output
9
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
long N;
int M, l, sum=0;
cin >> N >> M;
for(int i=0;i<M;i++){
cin >> l;
sum += l;
}
cout << ((N>=sum)?N-sum:-1) << endl;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
You are given a n Γ m field consisting only of periods ('.') and asterisks ('*'). Your task is to count all right triangles with two sides parallel to the square sides, whose vertices are in the centers of '*'-cells. A right triangle is a triangle in which one angle is a right angle (that is, a 90 degree angle).
Input
The first line contains two positive integer numbers n and m (1 β€ n, m β€ 1000). The following n lines consist of m characters each, describing the field. Only '.' and '*' are allowed.
Output
Output a single number β total number of square triangles in the field. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
2 2
**
*.
Output
1
Input
3 4
*..*
.**.
*.**
Output
9
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <class T>
T abs(T x) {
return x > 0 ? x : (-x);
}
template <class T>
T sqr(T x) {
return x * x;
}
const int maxn = 1010;
int n, m;
char a[maxn][maxn];
long long h[maxn];
long long v[maxn];
int main() {
cin >> n >> m;
for (int i = 0; i < n; ++i) scanf("%s", a[i]);
for (int i = 0; i < n; ++i) {
h[i] = 0;
for (int j = 0; j < m; ++j)
if (a[i][j] == '*') ++h[i];
}
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
if (a[i][j] == '*') v[j] += h[i] - 1;
long long res = 0;
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j) {
if (a[i][j] != '*') continue;
res += v[j] - h[i] + 1;
}
cout << res << "\n";
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
The Little Elephant loves to play with color cards.
He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered).
Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β colors of both sides. The first number in a line is the color of the front of the card, the second one β of the back. The color of the front of the card may coincide with the color of the back of the card.
The numbers in the lines are separated by single spaces.
Output
On a single line print a single integer β the sought minimum number of moves. If it is impossible to make the set funny, print -1.
Examples
Input
3
4 7
4 7
7 4
Output
0
Input
5
4 7
7 4
2 11
9 7
1 1
Output
2
Note
In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0.
In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int dir[] = {0, 1, 0, -1, 1, 0, -1, 0};
void solve() {
int n;
cin >> n;
map<int, int> cnt1, cnt2;
for (int i = 0; i < n; i++) {
int num1, num2;
cin >> num1 >> num2;
cnt1[num1]++;
cnt2[num1]++;
if (num1 != num2) cnt2[num2]++;
}
int mn = -1;
for (auto x : cnt2) {
int need = max(0, (n / 2) + (n % 2) - cnt1[x.first]);
if (cnt2[x.first] >= need + cnt1[x.first]) {
if (mn == -1) mn = need;
mn = min(mn, need);
}
}
cout << mn << endl;
}
int main() {
ios_base::sync_with_stdio(0);
int t = 1;
for (int cn = 1; cn <= t; cn++) {
solve();
}
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
There are N children, numbered 1, 2, ..., N.
Snuke has decided to distribute x sweets among them. He needs to give out all the x sweets, but some of the children may get zero sweets.
For each i (1 \leq i \leq N), Child i will be happy if he/she gets exactly a_i sweets. Snuke is trying to maximize the number of happy children by optimally distributing the sweets. Find the maximum possible number of happy children.
Constraints
* All values in input are integers.
* 2 \leq N \leq 100
* 1 \leq x \leq 10^9
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N
Output
Print the maximum possible number of happy children.
Examples
Input
3 70
20 30 10
Output
2
Input
3 10
20 30 10
Output
1
Input
4 1111
1 10 100 1000
Output
4
Input
2 10
20 20
Output
0
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,x;cin>>n>>x;
int a[n];for(int i=0;i<n;i++){cin>>a[i];}
int cnt=0;
sort(a,a+n);
for(int i=0;i<n-1;i++){if(a[i]>x)break;else{x-=a[i];cnt++;}}
cout<<(x-a[n-1]?cnt:cnt+1)<<endl;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.
The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.
A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of 7 because its subribbon a appears 7 times, and the ribbon abcdabc has the beauty of 2 because its subribbon abc appears twice.
The rules are simple. The game will have n turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after n turns wins the treasure.
Could you find out who is going to be the winner if they all play optimally?
Input
The first line contains an integer n (0 β€ n β€ 10^{9}) β the number of turns.
Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than 10^{5} uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors.
Output
Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw".
Examples
Input
3
Kuroo
Shiro
Katie
Output
Kuro
Input
7
treasurehunt
threefriends
hiCodeforces
Output
Shiro
Input
1
abcabc
cbabac
ababca
Output
Katie
Input
15
foPaErcvJ
mZaxowpbt
mkuOlaHRE
Output
Draw
Note
In the first example, after 3 turns, Kuro can change his ribbon into ooooo, which has the beauty of 5, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most 4, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.
In the fourth example, since the length of each of the string is 9 and the number of turn is 15, everyone can change their ribbons in some way to reach the maximal beauty of 9 by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100005;
int solve(string st, int n) {
map<char, int> mp;
for (int i = 0; i < st.size(); i++) {
mp[st[i]]++;
}
int m = 0;
for (int i = 0; i < st.size(); i++) m = max(m, mp[st[i]]);
int needchange = st.size() - m;
if (n == 1) {
if (needchange == 0)
return st.size() - 1;
else
return m + 1;
}
if (n > needchange) {
return st.size();
}
return m + n;
}
int main() {
int n;
scanf("%d", &n);
string s1, s2, s3;
cin >> s1 >> s2 >> s3;
int m1 = solve(s1, n);
int m2 = solve(s2, n);
int m3 = solve(s3, n);
if (m1 > m2 && m1 > m3)
cout << "Kuro" << endl;
else if (m2 > m1 && m2 > m3)
cout << "Shiro" << endl;
else if (m3 > m1 && m3 > m2)
cout << "Katie" << endl;
else
cout << "Draw" << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
A prime number n (11, 19, 23, etc.) that divides by 4 and has 3 has an interesting property. The results of calculating the remainder of the square of a natural number (1, 2, ..., n -1) of 1 or more and less than n divided by n are the same, so they are different from each other. The number is (n -1) / 2.
The set of numbers thus obtained has special properties. From the resulting set of numbers, choose two different a and b and calculate the difference. If the difference is negative, add n to the difference. If the result is greater than (n -1) / 2, subtract the difference from n.
For example, when n = 11, the difference between 1 and 9 is 1 β 9 = β8 β β8 + n = β8 + 11 = 3. The difference between 9 and 1 is also 9 β1 = 8 β n β 8 = 11 β 8 = 3, which is the same value 3. This difference can be easily understood by writing 0, 1, Β·Β·Β·, n -1 on the circumference and considering the shorter arc between the two numbers. (See the figure below)
<image>
The "difference" in the numbers thus obtained is either 1, 2, ..., (n -1) / 2, and appears the same number of times.
[Example] When n = 11, it will be as follows.
1. Calculate the remainder of the square of the numbers from 1 to n-1 divided by n.
12 = 1 β 1
22 = 4 β 4
32 = 9 β 9
42 = 16 β 5
52 = 25 β 3
62 = 36 β 3
72 = 49 β 5
82 = 64 β 9
92 = 81 β 4
102 = 100 β 1
2. Calculation of "difference" between a and b
1. Calculate the difference between different numbers for 1, 3, 4, 5, 9 obtained in 1.
2. If the calculation result is negative, add n = 11.
3. In addition, if the result of the calculation is greater than (n-1) / 2 = 5, subtract from n = 11.
3. Find the number of appearances
Count the number of occurrences of the calculation results 1, 2, 3, 4, and 5, respectively.
From these calculation results, we can see that 1, 2, 3, 4, and 5 appear four times. This property is peculiar to a prime number that is 3 when divided by 4, and this is not the case with a prime number that is 1 when divided by 4. To confirm this, a program that takes an odd number n of 10000 or less as an input, executes the calculation as shown in the example (finds the frequency of the difference of the square that is too much divided by n), and outputs the number of occurrences. Please create.
Input
Given multiple datasets. One integer n (n β€ 10000) is given on one row for each dataset. The input ends with a line containing one 0.
Output
For each data set, output the frequency of occurrence in the following format.
Number of occurrences (integer) of (a, b) where the difference between the squares of the remainder is 1
The number of occurrences (integer) of (a, b) where the difference between the squares of the remainder is 2
::
::
The number of occurrences (integer) of (a, b) where the difference between the squares of the remainder is (n-1) / 2
Example
Input
11
15
0
Output
4
4
4
4
4
2
2
4
2
4
4
2
### Response
```cpp
#include <iostream>
#include <cstring>
using namespace std;
bool flg[10002];
int cnt[10002];
int main(){
int n;
while(cin >> n, n){
memset(flg, 0, sizeof(flg));
memset(cnt, 0, sizeof(cnt));
for(int i = 1; i < n; i++){
flg[(i * i) % n] = true;
}
for(int i = 0; i < n; i++){
if(!flg[i]) continue;
for(int j = i + 1; j < n; j++){
if(!flg[j]) continue;
int cal = j - i;
if(cal > (n - 1) / 2) cal = n - cal;
cnt[cal]++;
cal = i - j + n;
if(cal > (n - 1) / 2) cal = n - cal;
cnt[cal]++;
}
}
for(int i = 1; i <= (n - 1) / 2; i++){
cout << cnt[i] << endl;
}
}
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
After years of hard work scientists invented an absolutely new e-reader display. The new display has a larger resolution, consumes less energy and its production is cheaper. And besides, one can bend it. The only inconvenience is highly unusual management. For that very reason the developers decided to leave the e-readers' software to programmers.
The display is represented by n Γ n square of pixels, each of which can be either black or white. The display rows are numbered with integers from 1 to n upside down, the columns are numbered with integers from 1 to n from the left to the right. The display can perform commands like "x, y". When a traditional display fulfills such command, it simply inverts a color of (x, y), where x is the row number and y is the column number. But in our new display every pixel that belongs to at least one of the segments (x, x) - (x, y) and (y, y) - (x, y) (both ends of both segments are included) inverts a color.
For example, if initially a display 5 Γ 5 in size is absolutely white, then the sequence of commands (1, 4), (3, 5), (5, 1), (3, 3) leads to the following changes:
<image>
You are an e-reader software programmer and you should calculate minimal number of commands needed to display the picture. You can regard all display pixels as initially white.
Input
The first line contains number n (1 β€ n β€ 2000).
Next n lines contain n characters each: the description of the picture that needs to be shown. "0" represents the white color and "1" represents the black color.
Output
Print one integer z β the least number of commands needed to display the picture.
Examples
Input
5
01110
10010
10001
10011
11110
Output
4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n;
bool A[2010][2010];
bool B[2010][2010];
int C1[2010], C2[2010];
int C11[2010], C22[2010];
int D[2010];
int S, S1;
void load() {
cin >> n;
string T;
for (int i = 1; i <= n; ++i) {
cin >> T;
for (size_t j = 0; j < T.size(); ++j)
if (T[j] == '1') A[i][j + 1] = 1;
}
}
void algo1() {
for (int i = 1; i <= n; ++i)
for (int j = n; j > i; j--)
if ((C1[j] + C2[i]) % 2 != A[i][j]) {
C1[j]++, C2[i]++, S1++, D[i]++, D[j]++;
}
for (int i = n; i >= 1; i--)
for (int j = 1; j < i; ++j)
if ((C11[j] + C22[i]) % 2 != A[i][j]) {
C11[j]++, C22[i]++, S1++, D[i]++, D[j]++;
}
for (int i = 1; i <= n; ++i)
if (D[i] % 2 != A[i][i]) D[i]++, S1++;
}
void write() { cout << S1 << endl; }
int main() {
load();
algo1();
write();
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
You are given a connected undirected graph without cycles (that is, a tree) of n vertices, moreover, there is a non-negative integer written on every edge.
Consider all pairs of vertices (v, u) (that is, there are exactly n^2 such pairs) and for each pair calculate the bitwise exclusive or (xor) of all integers on edges of the simple path between v and u. If the path consists of one vertex only, then xor of all integers on edges of this path is equal to 0.
Suppose we sorted the resulting n^2 values in non-decreasing order. You need to find the k-th of them.
The definition of xor is as follows.
Given two integers x and y, consider their binary representations (possibly with leading zeros): x_k ... x_2 x_1 x_0 and y_k ... y_2 y_1 y_0 (where k is any number so that all bits of x and y can be represented). Here, x_i is the i-th bit of the number x and y_i is the i-th bit of the number y. Let r = x β y be the result of the xor operation of x and y. Then r is defined as r_k ... r_2 r_1 r_0 where:
$$$ r_i = \left\{ \begin{aligned} 1, ~ if ~ x_i β y_i \\\ 0, ~ if ~ x_i = y_i \end{aligned} \right. $$$
Input
The first line contains two integers n and k (2 β€ n β€ 10^6, 1 β€ k β€ n^2) β the number of vertices in the tree and the number of path in the list with non-decreasing order.
Each of the following n - 1 lines contains two integers p_i and w_i (1 β€ p_i β€ i, 0 β€ w_i < 2^{62}) β the ancestor of vertex i + 1 and the weight of the corresponding edge.
Output
Print one integer: k-th smallest xor of a path in the tree.
Examples
Input
2 1
1 3
Output
0
Input
3 6
1 2
1 3
Output
2
Note
The tree in the second sample test looks like this:
<image>
For such a tree in total 9 paths exist:
1. 1 β 1 of value 0
2. 2 β 2 of value 0
3. 3 β 3 of value 0
4. 2 β 3 (goes through 1) of value 1 = 2 β 3
5. 3 β 2 (goes through 1) of value 1 = 2 β 3
6. 1 β 2 of value 2
7. 2 β 1 of value 2
8. 1 β 3 of value 3
9. 3 β 1 of value 3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline long long read() {
long long x = 0, f = 1;
char c = getchar();
while (!isdigit(c)) {
if (c == '-') f = -1;
c = getchar();
}
while (isdigit(c)) {
x = (x << 1) + (x << 3) + c - 48;
c = getchar();
}
return x * f;
}
const int N = 1e6 + 7;
long long val[N];
int A[N], B[N], siz[N], ch[N][2];
int main() {
long long n = read(), k = read();
A[1] = B[1] = 1;
for (int i = 2; i <= n; i++) {
long long fa = read(), w = read();
val[i] = val[fa] ^ w;
A[i] = B[i] = 1;
}
long long ans = 0;
for (int i = 61; i >= 0; i--) {
long long cnt = 0, sum = 0;
for (int j = 1; j <= n; j++) ch[j][0] = ch[j][1] = siz[j] = 0;
for (int j = 1; j <= n; j++) {
int &p = ch[A[j]][(val[j] >> i) & 1];
if (!p) p = ++cnt;
siz[A[j] = p]++;
}
for (int j = 1; j <= n; j++) {
sum += siz[ch[B[j]][val[j] >> i & 1]];
}
int op = 0;
if (sum < k) k -= sum, op = 1, ans |= 1ll << i;
for (int j = 1; j <= n; j++) {
B[j] = ch[B[j]][((val[j] >> i) & 1) ^ op];
}
}
printf("%lld\n", ans);
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
The only difference between easy and hard versions is the size of the input.
You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'.
You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be a string of length k that is a substring of s, and is also a substring of the infinite string "RGBRGBRGB ...".
A string a is a substring of string b if there exists a positive integer i such that a_1 = b_i, a_2 = b_{i + 1}, a_3 = b_{i + 2}, ..., a_{|a|} = b_{i + |a| - 1}. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 2000) β the number of queries. Then q queries follow.
The first line of the query contains two integers n and k (1 β€ k β€ n β€ 2000) β the length of the string s and the length of the substring.
The second line of the query contains a string s consisting of n characters 'R', 'G' and 'B'.
It is guaranteed that the sum of n over all queries does not exceed 2000 (β n β€ 2000).
Output
For each query print one integer β the minimum number of characters you need to change in the initial string s so that after changing there will be a substring of length k in s that is also a substring of the infinite string "RGBRGBRGB ...".
Example
Input
3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR
Output
1
0
3
Note
In the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".
In the second example, the substring is "BRG".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
string b = "RGB";
while (b.length() < 2000) {
b += b;
}
long long t;
cin >> t;
while (t--) {
unordered_map<string, long long> mp;
long long n, k;
cin >> n >> k;
string s;
cin >> s;
long long ans = 1000000, m = 0;
while (true) {
string tmp = "";
bool flag = false;
for (long long i = 0; i <= n - k; i++) {
long long l = m;
long long new_ans = 0;
for (long long j = i; j < i + k; j++) {
if (!flag) {
tmp += b[l];
}
if (b[l] != s[j]) new_ans++;
l++;
}
if (mp[tmp] == 1) break;
flag = true;
ans = min(ans, new_ans);
}
if (mp[tmp] == 1) {
break;
}
mp[tmp] = 1;
m++;
}
cout << ans << endl;
}
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
You are given two strings s and t consisting of lowercase Latin letters. Also you have a string z which is initially empty. You want string z to be equal to string t. You can perform the following operation to achieve this: append any subsequence of s at the end of string z. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z = ac, s = abcde, you may turn z into following strings in one operation:
1. z = acace (if we choose subsequence ace);
2. z = acbcd (if we choose subsequence bcd);
3. z = acbce (if we choose subsequence bce).
Note that after this operation string s doesn't change.
Calculate the minimum number of such operations to turn string z into string t.
Input
The first line contains the integer T (1 β€ T β€ 100) β the number of test cases.
The first line of each testcase contains one string s (1 β€ |s| β€ 10^5) consisting of lowercase Latin letters.
The second line of each testcase contains one string t (1 β€ |t| β€ 10^5) consisting of lowercase Latin letters.
It is guaranteed that the total length of all strings s and t in the input does not exceed 2 β
10^5.
Output
For each testcase, print one integer β the minimum number of operations to turn string z into string t. If it's impossible print -1.
Example
Input
3
aabce
ace
abacaba
aax
ty
yyt
Output
1
-1
3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
map<int, int> mp, x[1000005];
int main() {
int t1;
cin >> t1;
while (t1--) {
string s, t;
cin >> s >> t;
mp.clear();
for (int i = 0; i < s.size(); i++) mp[s[i]]++;
bool q = true;
for (int i = 0; i < t.size(); i++) {
if (mp[t[i]] == 0) {
q = false;
break;
}
}
if (q == false) {
cout << -1 << endl;
continue;
}
for (int j = 100005; j >= 1; j--) x[j].clear();
for (int i = s.size() - 1; i >= 0; i--) {
for (int j = 1; j <= 26; j++) x[i + 1][j] = x[i + 2][j];
x[i + 1][s[i] - 'a' + 1] = i + 1;
}
int in = 0, ans = 0;
while (in < t.size()) {
ans++;
int ind = 0;
while (true) {
if (x[ind + 1][t[in] - 'a' + 1] == 0) break;
ind = x[ind + 1][t[in] - 'a' + 1];
in++;
if (in >= t.size()) break;
}
if (in >= t.size()) break;
}
cout << ans << endl;
}
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
<image>
To monitor cryptocurrency exchange rates trader William invented a wonderful device consisting of n lights arranged in a row. The device functions in the following way:
Initially, all lights on William's device are turned off. At the beginning of a new iteration the device randomly, with a uniform distribution, picks a light that is turned off and turns it on, telling William which cryptocurrency he should invest in. After this iteration if any k consecutive lights contain more than one turned on light, then the device finishes working.
William doesn't like uncertainty, so he wants you to calculate the expected value of the number of lights that are turned on in the device after it finishes working.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 10). Description of the test cases follows.
The only line for each test case contains two integers n and k (2 β€ k β€ n β€ 10^5), which are the total number of lights and the length of subsegment of lights that are being checked, respectively.
Output
For each test case print the answer, modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not β‘ 0 \pmod{M}. Output the integer equal to p β
q^{-1} mod M. In other words, output such an integer x that 0 β€ x < M and x β
q β‘ p \pmod{M}.
Example
Input
3
3 2
15 2
40 15
Output
333333338
141946947
329622137
Note
Explanation of the first sample test case:
Let's write out all possible sequences of light toggles, which will make the device complete its operation:
1. (1, 2) β 2 lights are turned on
2. (1, 3, 2) β 3 lights are turned on
3. (2, 1) β 2 lights are turned on
4. (2, 3) β 2 lights are turned on
5. (3, 2) β 2 lights are turned on
6. (3, 1, 2) β 3 lights are turned on
Then the final expected value will be equal to 2/6 + 3/6 + 2/6 + 2/6 + 2/6 + 3/6 = 14/6 = 7/3.
Then the required output will be 333333338, since 333333338 β
3 β‘ 7 \pmod{10^9+7}.
### Response
```cpp
#include<bits/stdc++.h>
#define int long long
#define ld long double
#define fi first
#define se second
#define vll vector<int>
#define pii pair<int,int>
#define pb push_back
#define sz(v) (int)(v).size()
#define inf (int)(1e18)
#define md (int)(1e9+7)
#define all(v) (v).begin(),(v).end()
#define rep(i,a,b) for(int i=a;i<b;++i)
using namespace std;
const int M = 2e5 + 10;
int ex(int a,int b=md-2){
int ans=1;
while(b) {
if(b&1) ans=(ans*a)%md;
a=(a*a)%md,b/=2;
}
return ans;
}
inline int add(int a,int b){
a+=b;
if(a>=md) a-=md;
return a;
}
inline int sub(int a,int b){
a-=b;
if(a<0) a+=md;
return a;
}
inline int mul(int a,int b){
return (a*b)%md;
}
int f[M],iv[M];
int C(int n,int r){
if(n<r) return 0;
return mul(f[n],mul(iv[r],iv[n-r]));
}
void init(){
f[0]=1;
for(int i=1;i<M;++i) {
f[i]=mul(i,f[i-1]);
}
iv[M-1]=ex(f[M-1]);
for(int i=M-2;i>=0;--i) {
iv[i]=mul(i+1,iv[i+1]);
}
}
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
init();
int tc;
cin>>tc;
while(tc--) {
int n,k;
cin>>n>>k;
int ans=0;
for(int i=1;(i-1)*(k-1)<=n;++i) {
ans=add(ans,mul(C(n-(i-1)*(k-1),i),mul(f[i],f[n-i])));
}
ans=mul(ans,iv[n]);
ans=add(ans,1);
cout<<ans<<"\n";
}
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Shaass has n books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the i-th book is ti and its pages' width is equal to wi. The thickness of each book is either 1 or 2. All books have the same page heights.
<image>
Shaass puts the books on the bookshelf in the following way. First he selects some of the books and put them vertically. Then he puts the rest of the books horizontally above the vertical books. The sum of the widths of the horizontal books must be no more than the total thickness of the vertical books. A sample arrangement of the books is depicted in the figure.
<image>
Help Shaass to find the minimum total thickness of the vertical books that we can achieve.
Input
The first line of the input contains an integer n, (1 β€ n β€ 100). Each of the next n lines contains two integers ti and wi denoting the thickness and width of the i-th book correspondingly, (1 β€ ti β€ 2, 1 β€ wi β€ 100).
Output
On the only line of the output print the minimum total thickness of the vertical books that we can achieve.
Examples
Input
5
1 12
1 3
2 15
2 5
2 1
Output
5
Input
3
1 10
2 1
2 4
Output
3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, f[101], v[101], w[101];
int v1, ans;
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> v[i] >> w[i];
v1 += v[i];
}
for (int i = 0; i <= v1; i++) f[i] = 1e9;
f[0] = 0;
for (int i = 1; i <= n; i++) {
for (int j = v1; j >= v[i]; j--) {
f[j] = min(f[j], f[j - v[i]] + w[i]);
}
}
for (int i = v1; i >= 0; i--) {
if (v1 - i >= f[i]) {
ans = v1 - i;
break;
}
}
cout << ans;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Ivan has an array consisting of n elements. Each of the elements is an integer from 1 to n.
Recently Ivan learned about permutations and their lexicographical order. Now he wants to change (replace) minimum number of elements in his array in such a way that his array becomes a permutation (i.e. each of the integers from 1 to n was encountered in his array exactly once). If there are multiple ways to do it he wants to find the lexicographically minimal permutation among them.
Thus minimizing the number of changes has the first priority, lexicographical minimizing has the second priority.
In order to determine which of the two permutations is lexicographically smaller, we compare their first elements. If they are equal β compare the second, and so on. If we have two permutations x and y, then x is lexicographically smaller if xi < yi, where i is the first index in which the permutations x and y differ.
Determine the array Ivan will obtain after performing all the changes.
Input
The first line contains an single integer n (2 β€ n β€ 200 000) β the number of elements in Ivan's array.
The second line contains a sequence of integers a1, a2, ..., an (1 β€ ai β€ n) β the description of Ivan's array.
Output
In the first line print q β the minimum number of elements that need to be changed in Ivan's array in order to make his array a permutation. In the second line, print the lexicographically minimal permutation which can be obtained from array with q changes.
Examples
Input
4
3 2 2 3
Output
2
1 2 4 3
Input
6
4 5 6 3 2 1
Output
0
4 5 6 3 2 1
Input
10
6 8 4 6 7 1 6 3 4 5
Output
3
2 8 4 6 7 1 9 3 10 5
Note
In the first example Ivan needs to replace number three in position 1 with number one, and number two in position 3 with number four. Then he will get a permutation [1, 2, 4, 3] with only two changed numbers β this permutation is lexicographically minimal among all suitable.
In the second example Ivan does not need to change anything because his array already is a permutation.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int M = 2e5 + 7;
int n, arr[M], d[M], b = 1, t = 0;
bool used[M];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &arr[i]);
d[arr[i]]++;
}
for (int i = 1; i <= n; i++) {
if (d[arr[i]] > 1) {
while (n >= b && d[b]) b++;
if (arr[i] > b || used[arr[i]]) {
t++;
d[arr[i]]--;
d[b]++;
arr[i] = b;
} else
used[arr[i]] = 1;
}
}
printf("%d\n", t);
for (int i = 1; i <= n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
You are given two strings s and t, each of length n and consisting of lowercase Latin alphabets. You want to make s equal to t.
You can perform the following operation on s any number of times to achieve it β
* Choose any substring of s and rotate it clockwise once, that is, if the selected substring is s[l,l+1...r], then it becomes s[r,l,l + 1 ... r - 1]. All the remaining characters of s stay in their position.
For example, on rotating the substring [2,4] , string "abcde" becomes "adbce".
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Find the minimum number of operations required to convert s to t, or determine that it's impossible.
Input
The first line of the input contains a single integer t (1β€ t β€ 2000) β the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1β€ n β€ 2000) β the length of the strings.
The second and the third lines contain strings s and t respectively.
The sum of n over all the test cases does not exceed 2000.
Output
For each test case, output the minimum number of operations to convert s to t. If it is not possible to convert s to t, output -1 instead.
Example
Input
6
1
a
a
2
ab
ba
3
abc
cab
3
abc
cba
4
abab
baba
4
abcc
aabc
Output
0
1
1
2
1
-1
Note
For the 1-st test case, since s and t are equal, you don't need to apply any operation.
For the 2-nd test case, you only need to apply one operation on the entire string ab to convert it to ba.
For the 3-rd test case, you only need to apply one operation on the entire string abc to convert it to cab.
For the 4-th test case, you need to apply the operation twice: first on the entire string abc to convert it to cab and then on the substring of length 2 beginning at the second character to convert it to cba.
For the 5-th test case, you only need to apply one operation on the entire string abab to convert it to baba.
For the 6-th test case, it is not possible to convert string s to t.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int w;
int dp[2005][2005];
string s, t;
int quick_s[2005][30], quick_ts[2005][30];
int solve(int i, int j) {
if (i == 0)
return 0;
else {
int cur;
if (dp[i - 1][j] == INF)
cur = solve(i - 1, j) + 1;
else
cur = dp[i - 1][j] + 1;
if (s.at(i) == t.at(j)) {
if (dp[i - 1][j - 1] == INF)
dp[i][j] = solve(i - 1, j - 1);
else
dp[i][j] = dp[i - 1][j - 1];
return dp[i][j];
} else if (j >= i) {
int prob = t.at(j) - 'a';
if (quick_ts[j][prob] > quick_s[i][prob]) {
if (dp[i][j - 1] == INF)
dp[i][j] = solve(i, j - 1);
else
dp[i][j] = dp[i][j - 1];
} else {
if (dp[i - 1][j] == INF)
dp[i][j] = solve(i - 1, j) + 1;
else
dp[i][j] = dp[i - 1][j] + 1;
}
dp[i][j] = min(cur, dp[i][j]);
return dp[i][j];
} else {
return 0;
}
}
}
int main() {
cin >> w;
while (w--) {
int n, i, j;
cin >> n >> s >> t;
for (i = 0; i <= n; i++) {
dp[0][i] = 0;
}
for (i = 0; i < 30; i++) {
quick_s[0][i] = 0;
quick_ts[0][i] = 0;
}
quick_s[0][s.at(0) - 'a'] = 1;
quick_ts[0][t.at(0) - 'a'] = 1;
for (i = 1; i < n; i++) {
for (j = 0; j < 30; j++) {
if (j == s.at(i) - 'a')
quick_s[i][j] = quick_s[i - 1][j] + 1;
else
quick_s[i][j] = quick_s[i - 1][j];
if (j == t.at(i) - 'a')
quick_ts[i][j] = quick_ts[i - 1][j] + 1;
else
quick_ts[i][j] = quick_ts[i - 1][j];
}
}
bool pass = true;
for (i = 0; i < 30; i++) {
if (quick_s[n - 1][i] != quick_ts[n - 1][i]) {
pass = false;
}
}
for (i = 1; i < n; i++) {
for (j = i; j < n; j++) {
dp[i][j] = INF;
}
}
if (pass)
cout << solve(n - 1, n - 1) << "\n";
else
cout << -1 << "\n";
}
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
As Famil Doorβs birthday is coming, some of his friends (like Gabi) decided to buy a present for him. His friends are going to buy a string consisted of round brackets since Famil Door loves string of brackets of length n more than any other strings!
The sequence of round brackets is called valid if and only if:
1. the total number of opening brackets is equal to the total number of closing brackets;
2. for any prefix of the sequence, the number of opening brackets is greater or equal than the number of closing brackets.
Gabi bought a string s of length m (m β€ n) and want to complete it to obtain a valid sequence of brackets of length n. He is going to pick some strings p and q consisting of round brackets and merge them in a string p + s + q, that is add the string p at the beginning of the string s and string q at the end of the string s.
Now he wonders, how many pairs of strings p and q exists, such that the string p + s + q is a valid sequence of round brackets. As this number may be pretty large, he wants to calculate it modulo 109 + 7.
Input
First line contains n and m (1 β€ m β€ n β€ 100 000, n - m β€ 2000) β the desired length of the string and the length of the string bought by Gabi, respectively.
The second line contains string s of length m consisting of characters '(' and ')' only.
Output
Print the number of pairs of string p and q such that p + s + q is a valid sequence of round brackets modulo 109 + 7.
Examples
Input
4 1
(
Output
4
Input
4 4
(())
Output
1
Input
4 3
(((
Output
0
Note
In the first sample there are four different valid pairs:
1. p = "(", q = "))"
2. p = "()", q = ")"
3. p = "", q = "())"
4. p = "", q = ")()"
In the second sample the only way to obtain a desired string is choose empty p and q.
In the third sample there is no way to get a valid sequence of brackets.
### Response
```cpp
#include <bits/stdc++.h>
const int maxm = 100000;
const int maxd = 2000;
const int mod = 1000000007;
int n, m;
char s[maxm + 3];
long long d[maxd + 3][maxd + 3], ans;
void init() {
scanf("%d%d%*c%s", &n, &m, s + 1);
d[0][0] = 1;
for (int i = 1; i <= n - m; i++)
for (int j = 0; j <= i; j++) {
if (j > 0) (d[i][j] = d[i][j] + d[i - 1][j - 1]) % mod;
d[i][j] = (d[i][j] + d[i - 1][j + 1]) % mod;
}
}
void solve() {
if (n % 2) {
printf("0\n");
return;
}
int del = 0, mindel = 0;
for (int i = 1; i <= m; i++) {
if (s[i] == '(')
del++;
else
del--;
if (del < mindel) mindel = del;
}
for (int i = 0; i <= n - m; i++)
for (int j = 0; j <= i; j++) {
if (j + mindel < 0 || j + del > n - m - i) continue;
ans = (ans + d[i][j] * d[n - m - i][j + del] % mod) % mod;
}
printf("%I64d\n", ans);
}
int main() {
init();
solve();
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages.
There is a very powerful system of pointers on &K* β you can add an asterisk to the right of the existing type X β that will result in new type X * . That is called pointer-definition operation. Also, there is the operation that does the opposite β to any type of X, which is a pointer, you can add an ampersand β that will result in a type &X, to which refers X. That is called a dereference operation.
The &K* language has only two basic data types β void and errtype. Also, the language has operators typedef and typeof.
* The operator "typedef A B" defines a new data type B, which is equivalent to A. A can have asterisks and ampersands, and B cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**.
* The operator "typeof A" returns type of A, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**.
An attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype* = &errtype = errtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype.
Using typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change.
Let us also note that the dereference operation has the lower priority that the pointer operation, in other words &T * is always equal to T.
Note, that the operators are executed consecutively one by one. If we have two operators "typedef &void a" and "typedef a* b", then at first a becomes errtype, and after that b becomes errtype* = errtype, but not &void* = void (see sample 2).
Vasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators.
Input
The first line contains an integer n (1 β€ n β€ 100) β the number of operators. Then follow n lines with operators. Each operator is of one of two types: either "typedef A B", or "typeof A". In the first case the B type differs from void and errtype types, and besides, doesn't have any asterisks and ampersands.
All the data type names are non-empty lines of no more than 20 lowercase Latin letters. The number of asterisks and ampersands separately in one type in any operator does not exceed 10, however if we bring some types to void with several asterisks, their number may exceed 10.
Output
For every typeof operator print on the single line the answer to that operator β the type that the given operator returned.
Examples
Input
5
typedef void* ptv
typeof ptv
typedef &&ptv node
typeof node
typeof &ptv
Output
void*
errtype
void
Input
17
typedef void* b
typedef b* c
typeof b
typeof c
typedef &b b
typeof b
typeof c
typedef &&b* c
typeof c
typedef &b* c
typeof c
typedef &void b
typeof b
typedef b******* c
typeof c
typedef &&b* c
typeof c
Output
void*
void**
void
void**
errtype
void
errtype
errtype
errtype
Note
Let's look at the second sample.
After the first two queries typedef the b type is equivalent to void*, and Ρ β to void**.
The next query typedef redefines b β it is now equal to &b = &void* = void. At that, the Ρ type doesn't change.
After that the Ρ type is defined as &&b* = &&void* = &void = errtype. It doesn't influence the b type, that's why the next typedef defines c as &void* = void.
Then the b type is again redefined as &void = errtype.
Please note that the c type in the next query is defined exactly as errtype******* = errtype, and not &void******* = void******. The same happens in the last typedef.
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
clock_t clk = clock();
long long int i, j;
void solve(void);
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
;
int t = 1;
while (t--) solve();
return 0;
}
map<string, string> m;
void solve() {
long long int n;
cin >> n;
for (i = 0; i <= n - 1; ++i) {
string s;
cin >> s;
if (s == "typedef") {
string a, b;
cin >> a >> b;
int st = 0, en = (int)a.size() - 1;
while (a[st] == '&' && st < (int)a.size()) ++st;
while (a[en] == '*' && en >= 0) --en;
string temp;
for (j = st; j <= en; ++j) temp += a[j];
if (temp == "void") {
if (st <= (int)a.size() - 1 - en) {
for (j = 1; j <= (int)a.size() - 1 - en - st; ++j) temp += '*';
a = temp;
} else
a = "errtype";
m[b] = a;
continue;
} else if (temp == "errtype") {
a = temp;
m[b] = a;
continue;
}
if (m.find(temp) == m.end())
a = "errtype";
else {
string t = m[temp];
if (t == "errtype")
a = t;
else {
int stn = 0, enn = (int)t.size() - 1;
while (t[stn] == '&' && stn < (int)t.size()) ++stn;
while (t[enn] == '*' && enn >= 0) --enn;
if (st + stn <= (int)a.size() - 1 + (int)t.size() - 1 - enn - en) {
long long int val =
(int)a.size() + (int)t.size() - 2 - enn - en - st - stn;
t = "void";
for (j = 1; j <= val; ++j) t += '*';
} else
t = "errtype";
a = t;
}
m[b] = a;
}
} else {
string a;
cin >> a;
if (a == "void" || a == "errtype") {
cout << a << '\n';
continue;
}
long long int st = 0, en = (int)a.size() - 1;
while (a[st] == '&' && st < (int)a.size()) ++st;
while (a[en] == '*' && en >= 0) --en;
string t;
for (j = st; j <= en; ++j) t += a[j];
if (m.find(t) == m.end())
cout << "errtype\n";
else {
string temp = m[t];
if (temp == "errtype") {
cout << "errtype\n";
continue;
}
long long int stn = 0, enn = (int)temp.size() - 1;
while (temp[stn] == '&' && stn < (int)temp.size()) ++stn;
while (temp[enn] == '*' && enn >= 0) --enn;
if (st + stn <= (int)a.size() - 1 - en + (int)temp.size() - 1 - enn) {
long long int val =
(int)a.size() + (int)temp.size() - 2 - en - enn - st - stn;
temp = "void";
for (j = 1; j <= val; ++j) temp += '*';
} else
temp = "errtype";
cout << temp << '\n';
}
}
}
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
"This problem is rubbish! There is not statement, and there are only 5 test cases. The problemsetter took liberties with this problem!" β people complained in the comments to one round on Codeforces. And even more... No, wait, the checker for the problem was alright, that's a mercy.
Input
The only line of the input contains an integer between 1 and 5, inclusive. All tests for this problem are different. The contents of the test case doesn't need to be equal to its index.
Output
The only line of the output contains an integer between 1 and 3, inclusive.
Examples
Note
This problem has no samples, since there so few test cases.
### Response
```cpp
#include <bits/stdc++.h>
int main() {
int n;
const char r[] = "023121";
std::scanf("%d", &n);
std::printf("%c\n", r[n]);
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Taro Aizu's company has a boss who hates being indivisible. When Taro goes out to eat with his boss, he pays by splitting the bill, but when the payment amount is not divisible by the number of participants, his boss always pays for it.
One day, Taro became the secretary of the dinner party. Mr. Taro, who has little money, wondered if he could invite his boss to get a treat. I have to place an order with a restaurant, but I don't know how many people will participate yet, so it seems that I want to place an order so that any number of people can participate. At the same time as Mr. Taro, you who are also planning to attend the dinner party decided to cooperate with Mr. Taro to calculate the amount that is less than the budget amount and is not divisible by any number of people.
Create a program that inputs the type of dish, the price of each dish, and the budget amount, and outputs the total amount (excluding 1 and the total amount) that is not divisible by any number that is less than or equal to the budget amount. You can order multiple dishes of each type, but you do not have to order all types of dishes. However, if there is no such total amount, output NA.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
n x
v1
v2
::
vn
On the first line, the type of dish n (1 β€ n β€ 30) and the budget amount x (1 β€ x β€ 1000000) are given, separated by blanks. The next n lines are given the integer vi (1 β€ vi β€ 1000000), which represents the amount of the i-type dish.
The number of datasets does not exceed 100.
Output
For each input dataset, print the total amount or NA closest to the budget amount on one line.
Example
Input
4 15000
305
260
129
500
3 400
10
20
30
3 200909
5
9
12
0 0
Output
14983
NA
200909
### Response
```cpp
// 2012/11/19 Tazoe
#include <iostream>
using namespace std;
int main()
{
bool is_prime[1000001];
is_prime[0] = is_prime[1] = false;
for(int i=2; i<=1000000; i++){
is_prime[i] = true;
}
for(int i=2; i*i<=1000000; i++){
if(is_prime[i]){
for(int j=i*i; j<=1000000; j+=i){
is_prime[j] = false;
}
}
}
while(true){
int n, x;
cin >> n >> x;
if(n==0&&x==0)
break;
int K[30];
for(int i=0; i<n; i++){
cin >> K[i];
}
bool dp[1000001];
dp[0] = true;
for(int i=1; i<=x; i++){
dp[i] = false;
}
for(int i=0; i<n; i++){
for(int j=K[i]; j<=x; j++){
if(!dp[j]&&dp[j-K[i]]){
dp[j] = true;
}
}
}
int ans = -1;
for(int i=x; i>=2; i--){
if(dp[i]&&is_prime[i]){
ans = i;
break;
}
}
if(ans!=-1){
cout << ans << endl;
}
else{
cout << "NA" << endl;
}
}
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door:
The cleaning of all evil will awaken the door!
Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells.
The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once.
You would like to purify all n Γ n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell.
Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way.
Input
The first line will contain a single integer n (1 β€ n β€ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise.
Output
If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell.
Examples
Input
3
.E.
E.E
.E.
Output
1 1
2 2
3 3
Input
3
EEE
E..
E.E
Output
-1
Input
5
EE.EE
E.EE.
E...E
.EE.E
EE.EE
Output
3 3
1 3
2 2
4 4
5 3
Note
The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously.
<image>
In the second example, it is impossible to purify the cell located at row 1 and column 1.
For the third example:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 105;
int n;
int G[MAXN][MAXN];
char s[MAXN][MAXN];
int ans[MAXN][2], cnt;
void solve() {
cnt = 0;
for (int i = 1; i <= n; ++i) {
scanf("%s", s[i] + 1);
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
if (s[i][j] == '.') {
ans[cnt][0] = i;
ans[cnt][1] = j;
++cnt;
break;
}
}
}
if (cnt < n) {
cnt = 0;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
if (s[j][i] == '.') {
ans[cnt][0] = j;
ans[cnt][1] = i;
++cnt;
break;
}
}
}
}
if (cnt < n)
printf("-1\n");
else {
for (int i = 0; i < n; ++i) {
printf("%d %d\n", ans[i][0], ans[i][1]);
}
}
}
int main() {
while (~scanf("%d", &n)) solve();
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
While doing some spring cleaning, Daniel found an old calculator that he loves so much. However, it seems like it is broken. When he tries to compute 1 + 3 using the calculator, he gets 2 instead of 4. But when he tries computing 1 + 4, he gets the correct answer, 5. Puzzled by this mystery, he opened up his calculator and found the answer to the riddle: the full adders became half adders!
So, when he tries to compute the sum a + b using the calculator, he instead gets the xorsum a β b (read the definition by the link: <https://en.wikipedia.org/wiki/Exclusive_or>).
As he saw earlier, the calculator sometimes gives the correct answer. And so, he wonders, given integers l and r, how many pairs of integers (a, b) satisfy the following conditions: $$$a + b = a β b l β€ a β€ r l β€ b β€ r$$$
However, Daniel the Barman is going to the bar and will return in two hours. He tells you to solve the problem before he returns, or else you will have to enjoy being blocked.
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of testcases.
Then, t lines follow, each containing two space-separated integers l and r (0 β€ l β€ r β€ 10^9).
Output
Print t integers, the i-th integer should be the answer to the i-th testcase.
Example
Input
3
1 4
323 323
1 1000000
Output
8
0
3439863766
Note
a β b denotes the bitwise XOR of a and b.
For the first testcase, the pairs are: (1, 2), (1, 4), (2, 1), (2, 4), (3, 4), (4, 1), (4, 2), and (4, 3).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long dp[50][2][2], a[50], b[50];
inline long long dfs(long long pos, long long l1, long long l2) {
if (pos == -1) return 1;
if (dp[pos][l1][l2] != -1) return dp[pos][l1][l2];
long long up1 = l1 ? a[pos] : 1;
long long up2 = l2 ? b[pos] : 1;
long long res = 0;
for (long long i = 0; i <= up1; i++)
for (long long j = 0; j <= up2; j++)
if (!(i & j)) res += dfs(pos - 1, l1 && i == up1, l2 && j == up2);
dp[pos][l1][l2] = res;
return res;
}
inline long long solve(long long l, long long r) {
if (l == -1 || r == -1) return 0;
long long pos1 = 0, pos2 = 0;
memset(dp, -1, sizeof(dp));
while (l || r) {
a[pos1++] = (l & 1), b[pos2++] = (r & 1);
l >>= 1, r >>= 1;
}
return dfs(max(pos1, pos2) - 1, 1, 1);
}
signed main() {
long long T;
cin >> T;
while (T--) {
long long l, r;
cin >> l >> r;
cout << solve(r, r) - solve(l - 1, r) - solve(r, l - 1) +
solve(l - 1, l - 1)
<< endl;
}
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
The bear decided to store some raspberry for the winter. He cunningly found out the price for a barrel of honey in kilos of raspberry for each of the following n days. According to the bear's data, on the i-th (1 β€ i β€ n) day, the price for one barrel of honey is going to is xi kilos of raspberry.
Unfortunately, the bear has neither a honey barrel, nor the raspberry. At the same time, the bear's got a friend who is ready to lend him a barrel of honey for exactly one day for c kilograms of raspberry. That's why the bear came up with a smart plan. He wants to choose some day d (1 β€ d < n), lent a barrel of honey and immediately (on day d) sell it according to a daily exchange rate. The next day (d + 1) the bear wants to buy a new barrel of honey according to a daily exchange rate (as he's got some raspberry left from selling the previous barrel) and immediately (on day d + 1) give his friend the borrowed barrel of honey as well as c kilograms of raspberry for renting the barrel.
The bear wants to execute his plan at most once and then hibernate. What maximum number of kilograms of raspberry can he earn? Note that if at some point of the plan the bear runs out of the raspberry, then he won't execute such a plan.
Input
The first line contains two space-separated integers, n and c (2 β€ n β€ 100, 0 β€ c β€ 100), β the number of days and the number of kilos of raspberry that the bear should give for borrowing the barrel.
The second line contains n space-separated integers x1, x2, ..., xn (0 β€ xi β€ 100), the price of a honey barrel on day i.
Output
Print a single integer β the answer to the problem.
Examples
Input
5 1
5 10 7 3 20
Output
3
Input
6 2
100 1 10 40 10 40
Output
97
Input
3 0
1 2 3
Output
0
Note
In the first sample the bear will lend a honey barrel at day 3 and then sell it for 7. Then the bear will buy a barrel for 3 and return it to the friend. So, the profit is (7 - 3 - 1) = 3.
In the second sample bear will lend a honey barrel at day 1 and then sell it for 100. Then the bear buy the barrel for 1 at the day 2. So, the profit is (100 - 1 - 2) = 97.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, c;
scanf("%d%d", &n, &c);
int a[n], b[n - 1];
scanf("%d", &a[0]);
for (int i = 1; i < n; i++) {
scanf("%d", &a[i]);
b[i - 1] = a[i - 1] - a[i] - c;
}
int max = 0;
for (int i = 0; i < n - 1; i++) {
if (b[i] > max) max = b[i];
}
printf("%d\n", max);
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.
In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned.
Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023.
Input
The first line contains an integer n (1 β€ n β€ 5Β·105) β the number of lines.
Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 β€ xi β€ 1023.
Output
Output an integer k (0 β€ k β€ 5) β the length of your program.
Next k lines must contain commands in the same format as in the input.
Examples
Input
3
| 3
^ 2
| 1
Output
2
| 3
^ 2
Input
3
& 1
& 3
& 5
Output
1
& 1
Input
3
^ 1
^ 2
^ 3
Output
0
Note
You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>.
Second sample:
Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs.
### Response
```cpp
#include <bits/stdc++.h>
const int N = 500 * 1000, of_bits = 10;
int n, where_set[of_bits], consts[N], one, two, three;
char str[20], op[N], one_xor[of_bits], val[of_bits];
int main() {
std::scanf("%d", &n);
for (int i = 0; i < of_bits; i++) val[i] = -1;
for (int i = 0; i < n; i++) {
std::scanf("%s%d", str, &consts[i]);
op[i] = str[0];
}
for (int i = n - 1; i >= 0; i--) {
if (op[i] == '&') {
for (int j = 0; j < of_bits; j++)
if (val[j] == -1 && !((1 << j) & consts[i])) val[j] = one_xor[j];
} else if (op[i] == '|') {
for (int j = 0; j < of_bits; j++)
if (val[j] == -1 && ((1 << j) & consts[i]))
val[j] = (one_xor[j] + 1) % 2;
} else {
for (int j = 0; j < of_bits; j++)
if (val[j] == -1 && ((1 << j) & consts[i]))
one_xor[j] = (one_xor[j] + 1) % 2;
}
}
for (int j = 0; j < of_bits; j++)
if (val[j] == 1) one |= (1 << j);
for (int j = 0; j < of_bits; j++)
if (val[j] != 0) two |= (1 << j);
for (int j = 0; j < of_bits; j++)
if (val[j] == -1 && one_xor[j]) three |= (1 << j);
std::printf("3\n");
std::printf("| %d\n", one);
std::printf("& %d\n", two);
std::printf("^ %d\n", three);
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Little Chris is participating in a graph cutting contest. He's a pro. The time has come to test his skills to the fullest.
Chris is given a simple undirected connected graph with n vertices (numbered from 1 to n) and m edges. The problem is to cut it into edge-distinct paths of length 2. Formally, Chris has to partition all edges of the graph into pairs in such a way that the edges in a single pair are adjacent and each edge must be contained in exactly one pair.
For example, the figure shows a way Chris can cut a graph. The first sample test contains the description of this graph.
<image>
You are given a chance to compete with Chris. Find a way to cut the given graph or determine that it is impossible!
Input
The first line of input contains two space-separated integers n and m (1 β€ n, m β€ 105), the number of vertices and the number of edges in the graph. The next m lines contain the description of the graph's edges. The i-th line contains two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), the numbers of the vertices connected by the i-th edge. It is guaranteed that the given graph is simple (without self-loops and multi-edges) and connected.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
If it is possible to cut the given graph into edge-distinct paths of length 2, output <image> lines. In the i-th line print three space-separated integers xi, yi and zi, the description of the i-th path. The graph should contain this path, i.e., the graph should contain edges (xi, yi) and (yi, zi). Each edge should appear in exactly one path of length 2. If there are multiple solutions, output any of them.
If it is impossible to cut the given graph, print "No solution" (without quotes).
Examples
Input
8 12
1 2
2 3
3 4
4 1
1 3
2 4
3 5
3 6
5 6
6 7
6 8
7 8
Output
1 2 4
1 3 2
1 4 3
5 3 6
5 6 8
6 7 8
Input
3 3
1 2
2 3
3 1
Output
No solution
Input
3 2
1 2
2 3
Output
1 2 3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100005;
const double eps = 1e-11;
const int oo = 1e9 + 7;
const long long mod = 1e9 + 7;
vector<int> g[MAX], mark[MAX], ver1[MAX];
int n, m;
int dfs(int node) {
vector<int> adj, aux;
for (int i = 0; i < g[node].size(); ++i) {
if (mark[node][i] == 1) {
mark[node][i] = 0;
mark[g[node][i]][ver1[node][i]] = 0;
adj.push_back(g[node][i]);
}
}
int v;
for (int i = 0; i < adj.size(); ++i) {
v = dfs(adj[i]);
if (v == 0) {
aux.push_back(adj[i]);
} else {
printf("%d %d %d\n", v, adj[i], node);
}
}
while (aux.size() >= 2) {
int x, y;
x = aux.back();
aux.pop_back();
y = aux.back();
aux.pop_back();
printf("%d %d %d\n", x, node, y);
}
if (aux.size() == 0)
return 0;
else
return aux[0];
}
int main() {
scanf("%d%d", &n, &m);
int a, b;
if (m % 2 != 0) {
printf("No solution\n");
return 0;
}
while (m--) {
scanf("%d%d", &a, &b);
g[a].push_back(b);
g[b].push_back(a);
mark[a].push_back(1);
mark[b].push_back(1);
ver1[a].push_back(g[b].size() - 1);
ver1[b].push_back(g[a].size() - 1);
}
dfs(1);
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Tanechka is shopping in the toy shop. There are exactly n toys in the shop for sale, the cost of the i-th toy is i burles. She wants to choose two toys in such a way that their total cost is k burles. How many ways to do that does she have?
Each toy appears in the shop exactly once. Pairs (a, b) and (b, a) are considered equal. Pairs (a, b), where a=b, are not allowed.
Input
The first line of the input contains two integers n, k (1 β€ n, k β€ 10^{14}) β the number of toys and the expected total cost of the pair of toys.
Output
Print the number of ways to choose the pair of toys satisfying the condition above. Print 0, if Tanechka can choose no pair of toys in such a way that their total cost is k burles.
Examples
Input
8 5
Output
2
Input
8 15
Output
1
Input
7 20
Output
0
Input
1000000000000 1000000000001
Output
500000000000
Note
In the first example Tanechka can choose the pair of toys (1, 4) or the pair of toys (2, 3).
In the second example Tanechka can choose only the pair of toys (7, 8).
In the third example choosing any pair of toys will lead to the total cost less than 20. So the answer is 0.
In the fourth example she can choose the following pairs: (1, 1000000000000), (2, 999999999999), (3, 999999999998), ..., (500000000000, 500000000001). The number of such pairs is exactly 500000000000.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n, k;
int main() {
cin >> n >> k;
long long now = min(n, k - 1);
long long tmp = k - now;
if (tmp <= 0) {
cout << 0;
return 0;
}
cout << max((now - tmp + 1) / 2, (long long)0);
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.
Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):
* In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.
Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)
Constraints
* 2 \leq N \leq 5000
* 1 \leq K \leq 10^9
* 1 \leq P_i \leq N
* P_i \neq i
* P_1, P_2, \cdots, P_N are all different.
* -10^9 \leq C_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N
Output
Print the maximum possible score at the end of the game.
Examples
Input
5 2
2 4 5 1 3
3 4 -10 -8 8
Output
8
Input
2 3
2 1
10 -7
Output
13
Input
3 3
3 1 2
-1000 -2000 -3000
Output
-1000
Input
10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719
Output
29507023469
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
vector<int>pes,color,ces,sz;
vector<ll>points;
void dfs(int u, int z){
color[u]=z;
sz[color[u]]++;
points[color[u]]+=ces[u];
int v = pes[u];
if(color[v]==-1)dfs(v,z);
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;ll k;
cin>>n>>k;
pes=ces=sz=vector<int>(n+1);
color.resize(n+1,-1);
points.resize(n+1);
for(int i=1;i<=n;i++){
cin>>pes[i];
}
for(int i=1;i<=n;i++){
cin>>ces[i];
}
int z = 0;
for(int i=1;i<=n;i++){
if(color[i]==-1){
dfs(i,++z);
}
}
ll ans=-1e10;
for(int i =1;i<=n;i++){
int u=i;
u=pes[u];
ll tmp=0;
for(int len=1;len<=sz[color[i]];len++){
if(len>k)break;
u=pes[u];
tmp+=ces[u];
ans=max(ans,tmp);
ll foo=(k-len)/sz[color[i]];
ans=max(ans,tmp+foo*points[color[i]]);
}
}
cout<<ans;
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.
More formally, for each invited person the following conditions should be fulfilled:
* all his friends should also be invited to the party;
* the party shouldn't have any people he dislikes;
* all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2, a3, ..., ap - 1 such that all pairs of people ai and ai + 1 (1 β€ i < p) are friends.
Help the Beaver find the maximum number of acquaintances he can invite.
Input
The first line of input contains an integer n β the number of the Beaver's acquaintances.
The second line contains an integer k <image> β the number of pairs of friends. Next k lines contain space-separated pairs of integers ui, vi <image> β indices of people who form the i-th pair of friends.
The next line contains an integer m <image> β the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described.
Each pair of people is mentioned in the input at most once <image>. In particular, two persons cannot be friends and dislike each other at the same time.
The input limitations for getting 30 points are:
* 2 β€ n β€ 14
The input limitations for getting 100 points are:
* 2 β€ n β€ 2000
Output
Output a single number β the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0.
Examples
Input
9
8
1 2
1 3
2 3
4 5
6 7
7 8
8 9
9 6
2
1 6
7 9
Output
3
Note
Let's have a look at the example.
<image>
Two groups of people can be invited: {1, 2, 3} and {4, 5}, thus the answer will be the size of the largest of these groups. Group {6, 7, 8, 9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1, 2, 3, 4, 5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bitset<2005> used, b;
vector<int> like[2005], dislike[2005];
int n;
int solve(int idx) {
b.reset();
queue<int> q;
q.push(idx);
b.set(idx);
used.set(idx);
int ans = 1;
bool flag = false;
while (!q.empty()) {
int curr = q.front();
q.pop();
for (int i = 0; i < like[curr].size(); i++) {
int u = like[curr][i];
if (b.test(u)) continue;
for (int j = 0; !flag && j < dislike[u].size(); j++) {
int v = dislike[u][j];
if (b.test(v)) flag = true;
}
q.push(u);
b.set(u);
used.set(u);
ans++;
}
}
if (flag) return 0;
return ans;
}
int solve() {
int ans = 0;
used.reset();
for (int i = 1; i <= n; i++) {
if (used.test(i)) continue;
ans = max(ans, solve(i));
}
return ans;
}
int main() {
int k, m, u, v;
scanf("%d", &n);
scanf("%d", &k);
for (int i = 0; i < k; i++) {
scanf("%d%d", &u, &v);
like[u].push_back(v);
like[v].push_back(u);
}
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf("%d%d", &u, &v);
dislike[u].push_back(v);
dislike[v].push_back(u);
}
printf("%d\n", solve());
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
The problem describes the properties of a command line. The description somehow resembles the one you usually see in real operating systems. However, there are differences in the behavior. Please make sure you've read the statement attentively and use it as a formal document.
In the Pindows operating system a strings are the lexemes of the command line β the first of them is understood as the name of the program to run and the following lexemes are its arguments. For example, as we execute the command " run.exe one, two . ", we give four lexemes to the Pindows command line: "run.exe", "one,", "two", ".". More formally, if we run a command that can be represented as string s (that has no quotes), then the command line lexemes are maximal by inclusion substrings of string s that contain no spaces.
To send a string with spaces or an empty string as a command line lexeme, we can use double quotes. The block of characters that should be considered as one lexeme goes inside the quotes. Embedded quotes are prohibited β that is, for each occurrence of character """ we should be able to say clearly that the quotes are opening or closing. For example, as we run the command ""run.exe o" "" " ne, " two . " " ", we give six lexemes to the Pindows command line: "run.exe o", "" (an empty string), " ne, ", "two", ".", " " (a single space).
It is guaranteed that each lexeme of the command line is either surrounded by spaces on both sides or touches the corresponding command border. One of its consequences is: the opening brackets are either the first character of the string or there is a space to the left of them.
You have a string that consists of uppercase and lowercase English letters, digits, characters ".,?!"" and spaces. It is guaranteed that this string is a correct OS Pindows command line string. Print all lexemes of this command line string. Consider the character """ to be used only in order to denote a single block of characters into one command line lexeme. In particular, the consequence is that the given string has got an even number of such characters.
Input
The single line contains a non-empty string s. String s consists of at most 105 characters. Each character is either an uppercase or a lowercase English letter, or a digit, or one of the ".,?!"" signs, or a space.
It is guaranteed that the given string is some correct command line string of the OS Pindows. It is guaranteed that the given command line string contains at least one lexeme.
Output
In the first line print the first lexeme, in the second line print the second one and so on. To make the output clearer, print the "<" (less) character to the left of your lexemes and the ">" (more) character to the right. Print the lexemes in the order in which they occur in the command.
Please, follow the given output format strictly. For more clarifications on the output format see the test samples.
Examples
Input
"RUn.exe O" "" " 2ne, " two! . " "
Output
<RUn.exe O>
<>
< 2ne, >
<two!>
<.>
< >
Input
firstarg second ""
Output
<firstarg>
<second>
<>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
const int inf = 10000000;
char s[100005];
void print(string t) { cout << "<" << t << ">" << endl; }
int main() {
int n;
gets(s);
n = strlen(s);
s[n++] = ' ';
string t;
int comm = 0;
for (int i = 0; i < (n); i++) {
if (comm == 0 && s[i] == ' ') continue;
if (comm == 0 && s[i] == '"') {
comm = 1;
continue;
}
if (comm == 0) comm = 2;
if (comm == 1) {
if (s[i] == '"') {
print(t);
t = "";
comm = 0;
} else
t += s[i];
} else {
if (s[i] == ' ') {
print(t);
t = "";
comm = 0;
} else
t += s[i];
}
}
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point (0, 0) and Varda's home is located in point (a, b). In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position (x, y) he can go to positions (x + 1, y), (x - 1, y), (x, y + 1) or (x, y - 1).
Unfortunately, Drazil doesn't have sense of direction. So he randomly chooses the direction he will go to in each step. He may accidentally return back to his house during his travel. Drazil may even not notice that he has arrived to (a, b) and continue travelling.
Luckily, Drazil arrived to the position (a, b) successfully. Drazil said to Varda: "It took me exactly s steps to travel from my house to yours". But Varda is confused about his words, she is not sure that it is possible to get from (0, 0) to (a, b) in exactly s steps. Can you find out if it is possible for Varda?
Input
You are given three integers a, b, and s ( - 109 β€ a, b β€ 109, 1 β€ s β€ 2Β·109) in a single line.
Output
If you think Drazil made a mistake and it is impossible to take exactly s steps and get from his home to Varda's home, print "No" (without quotes).
Otherwise, print "Yes".
Examples
Input
5 5 11
Output
No
Input
10 15 25
Output
Yes
Input
0 5 1
Output
No
Input
0 0 2
Output
Yes
Note
In fourth sample case one possible route is: <image>.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long a, b, s;
cin >> a >> b >> s;
a = abs(a);
b = abs(b);
if (a + b > s)
cout << "NO";
else if (a + b == s)
cout << "YES";
else if ((a + b) % 2 == s % 2)
cout << "YES";
else
cout << "NO";
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
There are n problems prepared for the next Codeforces round. They are arranged in ascending order by their difficulty, and no two problems have the same difficulty. Moreover, there are m pairs of similar problems. Authors want to split problems between two division according to the following rules:
* Problemset of each division should be non-empty.
* Each problem should be used in exactly one division (yes, it is unusual requirement).
* Each problem used in division 1 should be harder than any problem used in division 2.
* If two problems are similar, they should be used in different divisions.
Your goal is count the number of ways to split problem between two divisions and satisfy all the rules. Two ways to split problems are considered to be different if there is at least one problem that belongs to division 1 in one of them and to division 2 in the other.
Note, that the relation of similarity is not transitive. That is, if problem i is similar to problem j and problem j is similar to problem k, it doesn't follow that i is similar to k.
Input
The first line of the input contains two integers n and m (2 β€ n β€ 100 000, 0 β€ m β€ 100 000) β the number of problems prepared for the round and the number of pairs of similar problems, respectively.
Each of the following m lines contains a pair of similar problems ui and vi (1 β€ ui, vi β€ n, ui β vi). It's guaranteed, that no pair of problems meets twice in the input.
Output
Print one integer β the number of ways to split problems in two divisions.
Examples
Input
5 2
1 4
5 2
Output
2
Input
3 3
1 2
2 3
1 3
Output
0
Input
3 2
3 1
3 2
Output
1
Note
In the first sample, problems 1 and 2 should be used in division 2, while problems 4 and 5 in division 1. Problem 3 may be used either in division 1 or in division 2.
In the second sample, all pairs of problems are similar and there is no way to split problem between two divisions without breaking any rules.
Third sample reminds you that the similarity relation is not transitive. Problem 3 is similar to both 1 and 2, but 1 is not similar to 2, so they may be used together.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
int a, b, low = 1, hight = n;
while (m--) {
cin >> a >> b;
if (a < b) swap(a, b);
low = max(low, b);
hight = min(hight, a);
}
cout << max(0, hight - low) << "\n";
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Let's call an array good if there is an element in the array that equals to the sum of all other elements. For example, the array a=[1, 3, 3, 7] is good because there is the element a_4=7 which equals to the sum 1 + 3 + 3.
You are given an array a consisting of n integers. Your task is to print all indices j of this array such that after removing the j-th element from the array it will be good (let's call such indices nice).
For example, if a=[8, 3, 5, 2], the nice indices are 1 and 4:
* if you remove a_1, the array will look like [3, 5, 2] and it is good;
* if you remove a_4, the array will look like [8, 3, 5] and it is good.
You have to consider all removals independently, i. e. remove the element, check if the resulting array is good, and return the element into the array.
Input
The first line of the input contains one integer n (2 β€ n β€ 2 β
10^5) β the number of elements in the array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^6) β elements of the array a.
Output
In the first line print one integer k β the number of indices j of the array a such that after removing the j-th element from the array it will be good (i.e. print the number of the nice indices).
In the second line print k distinct integers j_1, j_2, ..., j_k in any order β nice indices of the array a.
If there are no such indices in the array a, just print 0 in the first line and leave the second line empty or do not print it at all.
Examples
Input
5
2 5 1 2 2
Output
3
4 1 5
Input
4
8 3 5 2
Output
2
1 4
Input
5
2 1 2 4 3
Output
0
Note
In the first example you can remove any element with the value 2 so the array will look like [5, 1, 2, 2]. The sum of this array is 10 and there is an element equals to the sum of remaining elements (5 = 1 + 2 + 2).
In the second example you can remove 8 so the array will look like [3, 5, 2]. The sum of this array is 10 and there is an element equals to the sum of remaining elements (5 = 3 + 2). You can also remove 2 so the array will look like [8, 3, 5]. The sum of this array is 16 and there is an element equals to the sum of remaining elements (8 = 3 + 5).
In the third example you cannot make the given array good by removing exactly one element.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n;
int arr[2 * 100010], cnt[1000010] = {0};
long long sum = 0;
vector<int> ans;
int main() {
cin.tie(0), ios_base::sync_with_stdio(0);
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> arr[i];
sum += arr[i];
++cnt[arr[i]];
}
for (int i = 0; i < n; ++i) {
sum -= arr[i];
--cnt[arr[i]];
if (sum % 2 == 0 && sum / 2 <= 1000000 && cnt[sum / 2]) {
ans.push_back(i);
}
++cnt[arr[i]];
sum += arr[i];
}
cout << ans.size() << "\n";
for (int i = 0; i < ans.size(); ++i) {
if (i) cout << " ";
cout << ans[i] + 1;
}
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Paw the Spider is making a web. Web-making is a real art, Paw has been learning to do it his whole life. Let's consider the structure of the web.
<image>
There are n main threads going from the center of the web. All main threads are located in one plane and divide it into n equal infinite sectors. The sectors are indexed from 1 to n in the clockwise direction. Sectors i and i + 1 are adjacent for every i, 1 β€ i < n. In addition, sectors 1 and n are also adjacent.
Some sectors have bridge threads. Each bridge connects the two main threads that make up this sector. The points at which the bridge is attached to the main threads will be called attachment points. Both attachment points of a bridge are at the same distance from the center of the web. At each attachment point exactly one bridge is attached. The bridges are adjacent if they are in the same sector, and there are no other bridges between them.
A cell of the web is a trapezoid, which is located in one of the sectors and is bounded by two main threads and two adjacent bridges. You can see that the sides of the cell may have the attachment points of bridges from adjacent sectors. If the number of attachment points on one side of the cell is not equal to the number of attachment points on the other side, it creates an imbalance of pulling forces on this cell and this may eventually destroy the entire web. We'll call such a cell unstable. The perfect web does not contain unstable cells.
Unstable cells are marked red in the figure. Stable cells are marked green.
Paw the Spider isn't a skillful webmaker yet, he is only learning to make perfect webs. Help Paw to determine the number of unstable cells in the web he has just spun.
Input
The first line contains integer n (3 β€ n β€ 1000) β the number of main threads.
The i-th of following n lines describe the bridges located in the i-th sector: first it contains integer ki (1 β€ ki β€ 105) equal to the number of bridges in the given sector. Then follow ki different integers pij (1 β€ pij β€ 105; 1 β€ j β€ ki). Number pij equals the distance from the attachment points of the j-th bridge of the i-th sector to the center of the web.
It is guaranteed that any two bridges between adjacent sectors are attached at a different distance from the center of the web. It is guaranteed that the total number of the bridges doesn't exceed 105.
Output
Print a single integer β the number of unstable cells in Paw the Spider's web.
Examples
Input
7
3 1 6 7
4 3 5 2 9
2 8 1
4 3 7 6 4
3 2 5 9
3 6 3 8
3 4 2 9
Output
6
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v[1001];
int n, k, r;
while (scanf("%d", &n) != EOF) {
for (int i = 1; i <= n; i++) {
v[i].clear();
scanf("%d", &k);
while (k--) {
scanf("%d", &r);
v[i].push_back(r);
}
sort(v[i].begin(), v[i].end());
}
int ans = 0;
for (int i = 1; i <= n; i++) {
int pre = i - 1;
pre = pre == 0 ? n : pre;
int next = i + 1;
next = next == n + 1 ? 1 : next;
for (int j = 1; j < v[i].size(); j++) {
int x = upper_bound(v[pre].begin(), v[pre].end(), v[i][j]) -
upper_bound(v[pre].begin(), v[pre].end(), v[i][j - 1]);
int y = upper_bound(v[next].begin(), v[next].end(), v[i][j]) -
upper_bound(v[next].begin(), v[next].end(), v[i][j - 1]);
if (x != y) ans++;
}
}
printf("%d\n", ans);
}
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one.
Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one.
Input
The first line contains two space-separated integers n and k (2 β€ n β€ 104, 2 β€ k β€ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits.
Output
On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one.
Examples
Input
6 5
898196
Output
4
888188
Input
3 2
533
Output
0
533
Input
10 6
0001112223
Output
3
0000002223
Note
In the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188".
The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 β€ i β€ n), that xi < yi, and for any j (1 β€ j < i) xj = yj. The strings compared in this problem will always have the length n.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int A[11];
string tmpa;
int f(int dig, int i, int k) {
if (k == 0) return (0);
int newk = k;
if (dig + i <= 9) {
newk = max(0, newk - A[dig + i]);
for (int ii = 0, kk = 0; ii < tmpa.length(), kk < k - newk; ii++)
if (tmpa[ii] == dig + i + '0') {
tmpa[ii] = dig + '0';
kk++;
}
}
int buf = newk;
if (dig - i >= 0) {
newk = max(0, newk - A[dig - i]);
for (int ii = tmpa.length() - 1, kk = 0; ii >= 0, kk < buf - newk; ii--)
if (tmpa[ii] == dig - i + '0') {
tmpa[ii] = dig + '0';
kk++;
}
}
int res = (k - newk) * i;
return (res + f(dig, i + 1, newk));
}
int main() {
int n, k;
cin >> n >> k;
string s;
cin >> s;
for (int i = 0; i < s.length(); i++) {
A[s[i] - '0']++;
}
int res = INT_MAX;
string ans;
for (int i = 0; i < 10; i++) {
tmpa = s;
int tmp = f(i, 1, max(0, k - A[i]));
if (res == tmp) {
ans = min(ans, tmpa);
continue;
}
if (res > tmp) {
res = tmp;
ans = tmpa;
}
}
cout << res << endl;
cout << ans;
exit:
return (0);
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Chris the Rabbit found the traces of an ancient Martian civilization. The brave astronomer managed to see through a small telescope an architecture masterpiece β "A Road to the Sun". The building stands on cubical stones of the same size. The foundation divides the entire "road" into cells, into which the cubical stones are fit tightly. Thus, to any cell of the foundation a coordinate can be assigned. To become the leader of the tribe, a Martian should build a Road to the Sun, that is to build from those cubical stones on a given foundation a stairway. The stairway should be described by the number of stones in the initial coordinate and the coordinates of the stairway's beginning and end. Each following cell in the coordinate's increasing order should contain one cubical stone more than the previous one. At that if the cell has already got stones, they do not count in this building process, the stairways were simply built on them. In other words, let us assume that a stairway is built with the initial coordinate of l, the final coordinate of r and the number of stones in the initial coordinate x. That means that x stones will be added in the cell l, x + 1 stones will be added in the cell l + 1, ..., x + r - l stones will be added in the cell r.
Chris managed to find an ancient manuscript, containing the descriptions of all the stairways. Now he wants to compare the data to be sure that he has really found "A Road to the Sun". For that he chose some road cells and counted the total number of cubical stones that has been accumulated throughout the Martian history and then asked you to count using the manuscript to what the sum should ideally total.
Input
The first line contains three space-separated integers: n, m, k (1 β€ n, m β€ 105, 1 β€ k β€ min(n, 100)) which is the number of cells, the number of "Roads to the Sun" and the number of cells in the query correspondingly. Each of the following m roads contain three space-separated integers: ai, bi, ci (1 β€ ai β€ bi β€ n, 1 β€ ci β€ 1000) which are the stairway's description, its beginning, end and the initial cell's height. Then follow a line, containing k different space-separated integers bi. All these numbers ranging from 1 to n are cells, the number of stones in which interests Chris.
Output
You have to print a single number on a single line which is the sum of stones in all the cells Chris is interested in.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
Examples
Input
5 2 1
1 5 1
2 4 1
3
Output
5
Input
3 2 1
1 3 1
1 3 1
2
Output
4
Input
3 2 1
1 3 1
1 3 1
3
Output
6
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int dxx[] = {-1, -1, -1, 0, 0, 1, 1, 1};
int dyy[] = {-1, 0, 1, -1, 1, -1, 0, 1};
int dx[] = {-1, 0, 0, 1};
int dy[] = {0, -1, 1, 0};
int cas = 1;
int main() {
int n, q, m;
scanf("%d %d %d", &n, &m, &q);
;
vector<pair<int, int> > vc;
vector<int> qr;
int val[100005];
for (int i = 0; i < m; i++) {
int x, y, z;
scanf("%d %d %d", &x, &y, &z);
;
vc.push_back(make_pair(x, y));
val[i] = z;
}
for (int i = 1; i <= q; i++) {
int x;
scanf("%d", &x);
qr.push_back(x);
}
long long sum = 0;
for (int i = 0; i < vc.size(); i++) {
int x = vc[i].first;
int y = vc[i].second;
for (int j = 0; j < qr.size(); j++) {
if (qr[j] >= x && qr[j] <= y) {
sum += val[i] + (qr[j] - x);
}
}
}
printf("%lld\n", sum);
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied:
* a12 + a22 + ... + an2 β₯ x
* a1 + a2 + ... + an β€ y
Input
The first line contains three space-separated integers n, x and y (1 β€ n β€ 105, 1 β€ x β€ 1012, 1 β€ y β€ 106).
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is recommended to use cin, cout streams or the %I64d specificator.
Output
Print n positive integers that satisfy the conditions, one integer per line. If such numbers do not exist, print a single number "-1". If there are several solutions, print any of them.
Examples
Input
5 15 15
Output
4
4
1
1
2
Input
2 3 2
Output
-1
Input
1 99 11
Output
11
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n, x, y, t, r;
while (~scanf("%I64d%I64d%I64d", &n, &x, &y)) {
t = y - n + 1;
if (t * t + n - 1 < x || t <= 0) {
puts("-1");
continue;
} else {
printf("%I64d\n", t);
n--;
while (n--) {
puts("1");
}
}
}
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
At University A, there were many mistakes in entering IDs.
Therefore, University A decided to issue a new ID to prevent typos.
There is a way to check if the new ID is correct to prevent typos.
γ» Calculate the sum of all digits.
γ» However, the number of even-numbered digits is doubled, with the rightmost digit as the first digit.
-When the number becomes 10 or more by doubling, the number obtained by adding the 1st digit and the 10th digit is used as the digit number.
γ» If the sum is divisible by 10, the ID is correct, otherwise it is incorrect.
As an example, check the ID 53579.
Since the sum of all digits is calculated,
5 + 3 + 5 + 7 + 9
However, since the number of even-numbered digits is doubled,
5 + 6 + 5 + 14 + 9
When the number becomes 10 or more by doubling, the number obtained by adding the ones digit and the tens digit is the digit number.
5 + 6 + 5 + (1 + 4) + 9
From the above, the total sum is 30. Since 30 is divisible by 10, 53579 is the correct ID.
Mr. B is a college student at University A and was issued a new ID, but he forgot some digits of the ID.
However, I succeeded in narrowing down some candidates as to what kind of numbers will be included in the forgotten part.
Your job is to find out how many correct combinations of B's ββIDs are available.
Input
The input is given in the following format.
n
ID
m
a0 a1 ... am-1
n is the number of digits in the ID.
Each digit of the ID contains a number from 0 to 9 or the letter'*' to indicate that it is a forgotten digit.
m is the number of candidate numbers in the'*'.
ai is a candidate for numbers in'*'.
Input meets the following constraints
1 β€ n β€ 100,000
1 β€ m β€ 10
0 β€ ai β€ 9
Number of 1 β€'*' β€ 7
Output
Output the answer value on one line
Examples
Input
5
5*57*
2
3 9
Output
1
Input
15
2***9*2*6*1199*
9
0 1 2 3 4 6 7 8 9
Output
478297
### Response
```cpp
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int n, m, *id, *a, result = 0, known = 0;
vector<int> undefined;
bool isCollectID(void) {
int sum = 0;
for (int i = 0; i < undefined.size(); i++) {
int j = undefined[i];
if ((n + j) % 2)
sum += id[j];
else
sum += id[j] * 2 >= 10 ? id[j] * 2 - 9 : id[j] * 2;
}
return (known + sum) % 10 == 0;
}
void searchCadidate(int i) {
if (i == undefined.size()) {
if (isCollectID())
result++;
} else {
/*
for (int j = 0; j < n; j++)
if (id[j] > 0)
cout << id[j];
else
cout << '*';
cout << endl;
*/
for (int j = 0; j < m; j++) {
id[undefined[i]] = a[j];
searchCadidate(i + 1);
}
}
}
int main(int argc, char *argv[]) {
string s;
cin >> n;
cin >> s;
cin >> m;
a = new int[m];
for (int i = 0; i < m; i++)
cin >> a[i];
id = new int[n];
for (int i = 0; i < n; i++)
if (s[i] == '*') {
id[i] = -1;// test
undefined.push_back(i);
} else {
id[i] = s[i] - '0';
if ((n + i) % 2)
known += s[i] - '0';
else
known += id[i] * 2 >= 10 ? id[i] * 2 - 9 : id[i] * 2;
}
searchCadidate(0);
cout << result << endl;
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
To become the king of Codeforces, Kuroni has to solve the following problem.
He is given n numbers a_1, a_2, ..., a_n. Help Kuroni to calculate β_{1β€ i<jβ€ n} |a_i - a_j|. As result can be very big, output it modulo m.
If you are not familiar with short notation, β_{1β€ i<jβ€ n} |a_i - a_j| is equal to |a_1 - a_2|β
|a_1 - a_3|β
... β
|a_1 - a_n|β
|a_2 - a_3|β
|a_2 - a_4|β
... β
|a_2 - a_n| β
... β
|a_{n-1} - a_n|. In other words, this is the product of |a_i - a_j| for all 1β€ i < j β€ n.
Input
The first line contains two integers n, m (2β€ n β€ 2β
10^5, 1β€ m β€ 1000) β number of numbers and modulo.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 10^9).
Output
Output the single number β β_{1β€ i<jβ€ n} |a_i - a_j| mod m.
Examples
Input
2 10
8 5
Output
3
Input
3 12
1 4 5
Output
0
Input
3 7
1 4 9
Output
1
Note
In the first sample, |8 - 5| = 3 β‘ 3 mod 10.
In the second sample, |1 - 4|β
|1 - 5|β
|4 - 5| = 3β
4 β
1 = 12 β‘ 0 mod 12.
In the third sample, |1 - 4|β
|1 - 9|β
|4 - 9| = 3 β
8 β
5 = 120 β‘ 1 mod 7.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n, m, i, j, k, a, b, c = 1, p = 1;
map<long long, long long> mp;
vector<long long> v;
scanf("%lld %lld", &n, &m);
for (i = 0; i < n; i++) {
scanf("%lld", &a);
b = a % m;
if (mp[b] == 1) c = 0;
v.push_back(a);
mp[b] = 1;
}
if (c == 0)
printf("0\n");
else {
k = v.size();
for (i = 0; i < k - 1; i++) {
for (j = i + 1; j < k; j++) {
p = (p * abs(v[i] - v[j])) % m;
}
}
printf("%lld\n", p);
}
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number.
For example, let's consider string "zbcdzefdzc". The lists of positions of equal letters are:
* b: 2
* c: 3, 10
* d: 4, 8
* e: 6
* f: 7
* z: 1, 5, 9
* Lists of positions of letters a, g, h, ..., y are empty.
This string is lucky as all differences are lucky numbers. For letters z: 5 - 1 = 4, 9 - 5 = 4, for letters c: 10 - 3 = 7, for letters d: 8 - 4 = 4.
Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky.
Find the lexicographically minimal lucky string whose length equals n.
Input
The single line contains a positive integer n (1 β€ n β€ 105) β the length of the sought string.
Output
Print on the single line the lexicographically minimal lucky string whose length equals n.
Examples
Input
5
Output
abcda
Input
3
Output
abc
Note
The lexical comparison of strings is performed by the < operator in modern programming languages. String a is lexicographically less than string b if exists such i (1 β€ i β€ n), that ai < bi, and for any j (1 β€ j < i) aj = bj.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int OO = (int)1e6;
const double EPS = (1e-11);
int dcmp(double x, double y) { return fabs(x - y) <= EPS ? 0 : x < y ? -1 : 1; }
int main() {
int n;
cin >> n;
for (int i = 0; i < (int)(n); ++i) {
cout << (char)('a' + (i % 4));
}
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Recently Polycarpus has learned the "bitwise AND" operation (which is also called "AND") of non-negative integers. Now he wants to demonstrate the school IT teacher his superb manipulation with the learned operation.
For that Polycarpus came to school a little earlier and wrote on the board a sequence of non-negative integers a1, a2, ..., an. He also wrote a square matrix b of size n Γ n. The element of matrix b that sits in the i-th row in the j-th column (we'll denote it as bij) equals:
* the "bitwise AND" of numbers ai and aj (that is, bij = ai & aj), if i β j;
* -1, if i = j.
Having written out matrix b, Polycarpus got very happy and wiped a off the blackboard. But the thing is, the teacher will want this sequence to check whether Polycarpus' calculations were correct. Polycarus urgently needs to restore the removed sequence of integers, or else he won't prove that he can count correctly.
Help Polycarpus, given matrix b, restore the sequence of numbers a1, a2, ..., an, that he has removed from the board. Polycarpus doesn't like large numbers, so any number in the restored sequence mustn't exceed 109.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the size of square matrix b. Next n lines contain matrix b. The i-th of these lines contains n space-separated integers: the j-th number represents the element of matrix bij. It is guaranteed, that for all i (1 β€ i β€ n) the following condition fulfills: bii = -1. It is guaranteed that for all i, j (1 β€ i, j β€ n; i β j) the following condition fulfills: 0 β€ bij β€ 109, bij = bji.
Output
Print n non-negative integers a1, a2, ..., an (0 β€ ai β€ 109) β the sequence that Polycarpus wiped off the board. Separate the numbers by whitespaces.
It is guaranteed that there is sequence a that satisfies the problem conditions. If there are multiple such sequences, you are allowed to print any of them.
Examples
Input
1
-1
Output
0
Input
3
-1 18 0
18 -1 0
0 0 -1
Output
18 18 0
Input
4
-1 128 128 128
128 -1 148 160
128 148 -1 128
128 160 128 -1
Output
128 180 148 160
Note
If you do not know what is the "bitwise AND" operation please read: http://en.wikipedia.org/wiki/Bitwise_operation.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long b[200][200], cnt, c[200][200], ans[200], n, po, a[200][200][70], m;
int main() {
cin >> n;
for (long long i = 1; i <= n; i++) {
for (long long j = 1; j <= n; j++) {
cin >> b[i][j];
if (i != j) {
cnt = 0;
long long cur = b[i][j];
while (cur != 0) {
a[i][j][cnt++] = cur % 2;
cur /= 2;
}
}
}
}
for (long long i = 1; i <= n; i++) {
for (long long j = 1; j <= n; j++) {
if (i != j) {
for (long long k = 0; k <= 50; k++) {
if (a[i][j][k] == 1) {
c[i][k] = 1;
c[j][k] = 1;
}
}
}
}
}
for (long long i = 1; i <= n; i++) {
po = 1;
for (long long j = 0; j <= 50; j++) {
ans[i] += c[i][j] * po;
po *= 2;
}
cout << ans[i] << ' ';
}
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
The Berland Kingdom is a set of n cities connected with each other with n - 1 railways. Each road connects exactly two different cities. The capital is located in city 1. For each city there is a way to get from there to the capital by rail.
In the i-th city there is a soldier division number i, each division is characterized by a number of ai. It represents the priority, the smaller the number, the higher the priority of this division. All values of ai are different.
One day the Berland King Berl Great declared a general mobilization, and for that, each division should arrive in the capital. Every day from every city except the capital a train departs. So there are exactly n - 1 departing trains each day. Each train moves toward the capital and finishes movement on the opposite endpoint of the railway on the next day. It has some finite capacity of cj, expressed in the maximum number of divisions, which this train can transport in one go. Each train moves in the direction of reducing the distance to the capital. So each train passes exactly one railway moving from a city to the neighboring (where it stops) toward the capital.
In the first place among the divisions that are in the city, division with the smallest number of ai get on the train, then with the next smallest and so on, until either the train is full or all the divisions are be loaded. So it is possible for a division to stay in a city for a several days.
The duration of train's progress from one city to another is always equal to 1 day. All divisions start moving at the same time and end up in the capital, from where they don't go anywhere else any more. Each division moves along a simple path from its city to the capital, regardless of how much time this journey will take.
Your goal is to find for each division, in how many days it will arrive to the capital of Berland. The countdown begins from day 0.
Input
The first line contains the single integer n (1 β€ n β€ 5000). It is the number of cities in Berland. The second line contains n space-separated integers a1, a2, ..., an, where ai represents the priority of the division, located in the city number i. All numbers a1, a2, ..., an are different (1 β€ ai β€ 109). Then n - 1 lines contain the descriptions of the railway roads. Each description consists of three integers vj, uj, cj, where vj, uj are number of cities connected by the j-th rail, and cj stands for the maximum capacity of a train riding on this road (1 β€ vj, uj β€ n, vj β uj, 1 β€ cj β€ n).
Output
Print sequence t1, t2, ..., tn, where ti stands for the number of days it takes for the division of city i to arrive to the capital. Separate numbers with spaces.
Examples
Input
4
40 10 30 20
1 2 1
2 3 1
4 2 1
Output
0 1 3 2
Input
5
5 4 3 2 1
1 2 1
2 3 1
2 4 1
4 5 1
Output
0 1 4 2 3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MM = 5e3 + 5, MOD = 1e9 + 7;
int N, p[MM], ans[MM], d;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>>
pq[MM];
vector<pair<int, int>> adj[MM];
void dfs(int u, int pa, int cap) {
int cnt = 0;
while (!pq[u].empty() && cnt++ < cap) {
pq[pa].push(pq[u].top());
if (pa == 0) ans[pq[u].top().second] = d;
pq[u].pop();
}
for (pair<int, int> e : adj[u]) {
int v = e.first, c = e.second;
if (v == pa) continue;
dfs(v, u, c);
}
}
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
cin >> N;
for (int i = 1; i <= N; i++) cin >> p[i], pq[i].push({p[i], i});
for (int i = 1, u, v, w; i < N; i++) {
cin >> u >> v >> w;
adj[u].push_back({v, w});
adj[v].push_back({u, w});
}
while (pq[0].size() != N) dfs(1, 0, 1e9), d++;
for (int i = 1; i <= N; i++) cout << ans[i] << (i == N ? "\n" : " ");
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill:
* the graph contains exactly 2n + p edges;
* the graph doesn't contain self-loops and multiple edges;
* for any integer k (1 β€ k β€ n), any subgraph consisting of k vertices contains at most 2k + p edges.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
Your task is to find a p-interesting graph consisting of n vertices.
Input
The first line contains a single integer t (1 β€ t β€ 5) β the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 β€ n β€ 24; p β₯ 0; <image>) β the number of vertices in the graph and the interest value for the appropriate test.
It is guaranteed that the required graph exists.
Output
For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 β€ ai, bi β€ n; ai β bi) β two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n.
Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.
Examples
Input
1
6 0
Output
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
### Response
```cpp
#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
const int inf = 1e9 + 7;
const long long linf = 1e18;
const double pi = acos(-1.0);
int main() {
ios::sync_with_stdio(false);
int t;
cin >> t;
for (int total = 0; total < t; total++) {
int n, p;
cin >> n >> p;
for (int temp = 0; temp < 2 * n + p;) {
for (int i = 1; i <= n; i++) {
if (temp == 2 * n + p) break;
for (int j = i + 1; j <= n; j++) {
temp++;
cout << i << ' ' << j << endl;
if (temp == 2 * n + p) break;
}
}
}
}
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
You are given two integers a and b.
In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k β [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.
Your task is to find the minimum number of moves required to obtain b from a.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
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 required to obtain b from a.
Example
Input
6
5 5
13 42
18 4
1337 420
123456789 1000000000
100500 9000
Output
0
3
2
92
87654322
9150
Note
In the first test case of the example, you don't need to do anything.
In the second test case of the example, the following sequence of moves can be applied: 13 β 23 β 32 β 42 (add 10, add 9, add 10).
In the third test case of the example, the following sequence of moves can be applied: 18 β 10 β 4 (subtract 8, subtract 6).
### 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;
cin >> t;
while (t--) {
long long int a, b;
cin >> a >> b;
if (a == b) cout << "0" << endl;
if (b > a && (b - a) % 2 == 1) cout << "1" << endl;
if (b > a && (b - a) % 2 == 0) cout << "2" << endl;
if (a > b && (a - b) % 2 == 0) cout << "1" << endl;
if (a > b && (a - b) % 2 == 1) cout << "2" << endl;
}
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
You are given an undirected graph with N vertices and M edges. Here, N-1β€Mβ€N holds and the graph is connected. There are no self-loops or multiple edges in this graph.
The vertices are numbered 1 through N, and the edges are numbered 1 through M. Edge i connects vertices a_i and b_i.
The color of each vertex can be either white or black. Initially, all the vertices are white. Snuke is trying to turn all the vertices black by performing the following operation some number of times:
* Select a pair of adjacent vertices with the same color, and invert the colors of those vertices. That is, if the vertices are both white, then turn them black, and vice versa.
Determine if it is possible to turn all the vertices black. If the answer is positive, find the minimum number of times the operation needs to be performed in order to achieve the objective.
Constraints
* 2β€Nβ€10^5
* N-1β€Mβ€N
* 1β€a_i,b_iβ€N
* There are no self-loops or multiple edges in the given graph.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1
a_2 b_2
:
a_M b_M
Output
If it is possible to turn all the vertices black, print the minimum number of times the operation needs to be performed in order to achieve the objective. Otherwise, print `-1` instead.
Examples
Input
6 5
1 2
1 3
1 4
2 5
2 6
Output
5
Input
3 2
1 2
2 3
Output
-1
Input
4 4
1 2
2 3
3 4
4 1
Output
2
Input
6 6
1 2
2 3
3 1
1 4
1 5
1 6
Output
7
### Response
```cpp
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const int N=100010;
int n,m,cnt=1,G[N],c[N],ic[N],dfn[N],dpt[N];
struct edge{
int t,nx;
}E[N<<2];
inline void addedge(int x,int y){
E[++cnt].t=y; E[cnt].nx=G[x]; G[x]=cnt;
E[++cnt].t=x; E[cnt].nx=G[y]; G[y]=cnt;
}
int prty,u,v;
void dfs(int x,int cc){
c[x]=cc;
for(int i=G[x];i;i=E[i].nx){
if(!c[E[i].t]) dfs(E[i].t,3-cc);
if(c[E[i].t]==c[x]) prty=1,u=x,v=E[i].t;
}
}
int ans,a[N];
int dfs1(int x,int f){
int ret=a[x];
for(int i=G[x];i;i=E[i].nx)
if(E[i].t!=f && c[E[i].t]!=c[x]) ret+=dfs1(E[i].t,x);
ans+=abs(ret);
return ret;
}
int k[N],Q[N],t,ct;
int dfs2(int x,int f){
int ret=a[x];
for(int i=G[x];i;i=E[i].nx)
if(E[i].t!=f && i!=ct && (i^1)!=ct){
ret+=dfs2(E[i].t,x);
k[x]+=k[E[i].t];
}
if(k[x]){
if(k[x]<0) Q[++t]=-ret;
else Q[++t]=ret;
}
else ans+=abs(ret);
return ret;
}
int vis[N];
void dfs3(int x,int f){
vis[x]=1;
for(int i=G[x];i;i=E[i].nx){
if(E[i].t==f) continue;
if(!vis[E[i].t]) dfs3(E[i].t,x);
else u=x,v=E[i].t,ct=i;
}
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1,x,y;i<=m;i++)
scanf("%d%d",&x,&y),addedge(x,y);
dfs(1,1); int num=0;
for(int i=1;i<=n;i++)
if(c[i]==2) num++,a[i]=1; else num--,a[i]=-1;
if(n-1==m){
if(num) puts("-1");
else{
dfs1(1,0); printf("%d\n",ans);
}
}
else{
if(prty){
if(num&1) puts("-1");
else{
a[u]-=num/2; a[v]-=num/2;
dfs1(1,0); printf("%d\n",ans+abs(num/2));
}
}
else{
if(num) puts("-1");
else{
dfs3(1,0);
k[u]=1; k[v]=-1;
dfs2(1,0); Q[++t]=0;
sort(Q+1,Q+1+t);
int cur=Q[t/2];
for(int i=1;i<=t;i++) ans+=abs(cur-Q[i]);
printf("%d\n",ans);
}
}
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
You are given an array a_1, a_2, β¦, a_n of integers. This array is non-increasing.
Let's consider a line with n shops. The shops are numbered with integers from 1 to n from left to right. The cost of a meal in the i-th shop is equal to a_i.
You should process q queries of two types:
* 1 x y: for each shop 1 β€ i β€ x set a_{i} = max(a_{i}, y).
* 2 x y: let's consider a hungry man with y money. He visits the shops from x-th shop to n-th and if he can buy a meal in the current shop he buys one item of it. Find how many meals he will purchase. The man can buy a meal in the shop i if he has at least a_i money, and after it his money decreases by a_i.
Input
The first line contains two integers n, q (1 β€ n, q β€ 2 β
10^5).
The second line contains n integers a_{1},a_{2}, β¦, a_{n} (1 β€ a_{i} β€ 10^9) β the costs of the meals. It is guaranteed, that a_1 β₯ a_2 β₯ β¦ β₯ a_n.
Each of the next q lines contains three integers t, x, y (1 β€ t β€ 2, 1β€ x β€ n, 1 β€ y β€ 10^9), each describing the next query.
It is guaranteed that there exists at least one query of type 2.
Output
For each query of type 2 output the answer on the new line.
Example
Input
10 6
10 10 10 6 6 5 5 5 3 1
2 3 50
2 4 10
1 3 10
2 2 36
1 4 7
2 2 17
Output
8
3
6
2
Note
In the first query a hungry man will buy meals in all shops from 3 to 10.
In the second query a hungry man will buy meals in shops 4, 9, and 10.
After the third query the array a_1, a_2, β¦, a_n of costs won't change and will be \{10, 10, 10, 6, 6, 5, 5, 5, 3, 1\}.
In the fourth query a hungry man will buy meals in shops 2, 3, 4, 5, 9, and 10.
After the fifth query the array a of costs will be \{10, 10, 10, 7, 6, 5, 5, 5, 3, 1\}.
In the sixth query a hungry man will buy meals in shops 2 and 4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n, q, a[200005];
struct nod {
long long mi, mx, s, lazy;
} tr[200005 << 2];
void pushup(long long now, long long l, long long r) {
tr[now].mx = max(tr[(now << 1)].mx, tr[((now << 1) | 1)].mx);
tr[now].mi = min(tr[(now << 1)].mi, tr[((now << 1) | 1)].mi);
tr[now].s = tr[(now << 1)].s + tr[((now << 1) | 1)].s;
}
void mdf(long long now, long long l, long long r, long long v) {
tr[now].mx = tr[now].mi = v;
tr[now].s = (r - l + 1) * v;
tr[now].lazy = v;
}
void pushdown(long long now, long long l, long long r) {
if (l == r) return;
long long mid = (l + r) >> 1;
if (tr[now].lazy) {
tr[(now << 1)].mx = tr[((now << 1) | 1)].mx = tr[(now << 1)].mi =
tr[((now << 1) | 1)].mi = tr[now].lazy;
tr[(now << 1)].s = (mid - l + 1) * tr[now].lazy;
tr[((now << 1) | 1)].s = (r - mid) * tr[now].lazy;
tr[(now << 1)].lazy = tr[((now << 1) | 1)].lazy = tr[now].lazy;
tr[now].lazy = 0;
}
pushup(now, l, r);
}
void ins(long long now, long long l, long long r, long long x, long long y,
long long v) {
if (tr[now].lazy) pushdown(now, l, r);
if (x <= l && r <= y) {
mdf(now, l, r, v);
return;
}
long long mid = (l + r) >> 1;
if (x <= mid) ins((now << 1), l, mid, x, y, v);
if (y > mid) ins(((now << 1) | 1), mid + 1, r, x, y, v);
pushup(now, l, r);
}
long long query(long long now, long long l, long long r, long long k) {
if (tr[1].mi > k) return n + 1;
if (tr[now].lazy) pushdown(now, l, r);
if (l == r) return l;
long long mid = (l + r) >> 1;
if (tr[(now << 1)].mi <= k) return query((now << 1), l, mid, k);
return query(((now << 1) | 1), mid + 1, r, k);
}
long long flag, sum, cnt;
long long solve(long long now, long long l, long long r, long long x) {
if (tr[now].lazy) pushdown(now, l, r);
if (!flag && l == r && x == l) flag = 1;
if (l == r) {
if (flag == 1 && sum >= tr[now].s) {
sum -= tr[now].s;
cnt++;
return 1;
}
return 0;
}
long long mid = (l + r) >> 1;
if (flag == 0) {
if (x <= mid) {
long long adc = solve((now << 1), l, mid, x);
if (adc == 1) adc = solve(((now << 1) | 1), mid + 1, r, x);
return adc;
} else
return solve(((now << 1) | 1), mid + 1, r, x);
} else {
if (sum >= tr[now].s) {
sum -= tr[now].s, cnt += r - l + 1;
return 1;
} else {
long long adc = solve((now << 1), l, mid, x);
if (adc == 1) adc = solve(((now << 1) | 1), mid + 1, r, x);
return adc;
}
}
}
signed main() {
ios::sync_with_stdio(0);
cin >> n >> q;
for (long long i = 1, x; i <= n; i++) cin >> a[i], ins(1, 1, n, i, i, a[i]);
for (long long i = 1, op, x, y; i <= q; i++) {
cin >> op >> x >> y;
if (op == 1) {
long long pos = query(1, 1, n, y);
if (pos > y)
continue;
else
ins(1, 1, n, pos, x, y);
} else {
sum = y, cnt = 0;
while (sum >= tr[1].mi) {
flag = 0;
long long pos = query(1, 1, n, sum);
if (pos < x) pos = x;
long long adc = solve(1, 1, n, pos);
if (adc == 1) break;
}
cout << cnt << endl;
}
}
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Find the number of k-divisible numbers on the segment [a, b]. In other words you need to find the number of such integer values x that a β€ x β€ b and x is divisible by k.
Input
The only line contains three space-separated integers k, a and b (1 β€ k β€ 1018; - 1018 β€ a β€ b β€ 1018).
Output
Print the required number.
Examples
Input
1 1 10
Output
10
Input
2 -4 4
Output
5
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long N = 2e5 + 30, Mod = 1e9 + 7;
const long long SQ = 330;
int main() {
ios::sync_with_stdio(0), cin.tie(0);
long long k, a, b;
cin >> k >> a >> b;
long long ans = 0;
if (0 >= a && 0 <= b) ans++;
if (a == 0) return cout << ans + b / k, 0;
if (b == 0) return cout << ans + abs(a) / k, 0;
if (a < 0 && b > 0) return cout << ans + abs(a) / k + abs(b) / k, 0;
a = abs(a), b = abs(b);
if (a > b) swap(a, b);
cout << ans + b / k - (a - 1) / k;
return (0);
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Winters are just damn freezing cold in Nvodsk! That's why a group of n friends prefers to take a taxi, order a pizza and call girls. The phone numbers in the city consist of three pairs of digits (for example, 12-34-56). Each friend has a phonebook of size si (that's the number of phone numbers). We know that taxi numbers consist of six identical digits (for example, 22-22-22), the numbers of pizza deliveries should necessarily be decreasing sequences of six different digits (for example, 98-73-21), all other numbers are the girls' numbers.
You are given your friends' phone books. Calculate which friend is best to go to when you are interested in each of those things (who has maximal number of phone numbers of each type).
If the phone book of one person contains some number two times, you should count it twice. That is, each number should be taken into consideration the number of times it occurs in the phone book.
Input
The first line contains an integer n (1 β€ n β€ 100) β the number of friends.
Then follow n data blocks that describe each friend's phone books. Each block is presented in the following form: first goes the line that contains integer si and string namei (0 β€ si β€ 100) β the number of phone numbers in the phone book of the i-th friend and the name of the i-th friend. The name is a non-empty sequence of uppercase and lowercase Latin letters, containing no more than 20 characters. Next si lines contain numbers as "XX-XX-XX", where X is arbitrary digits from 0 to 9.
Output
In the first line print the phrase "If you want to call a taxi, you should call: ". Then print names of all friends whose phone books contain maximal number of taxi phone numbers.
In the second line print the phrase "If you want to order a pizza, you should call: ". Then print names of all friends who have maximal number of pizza phone numbers.
In the third line print the phrase "If you want to go to a cafe with a wonderful girl, you should call: ". Then print names of all friends who have maximal number of girls' phone numbers.
Print the names in the order in which they are given in the input data. Separate two consecutive names with a comma and a space. Each line should end with exactly one point. For clarifications concerning the output form, see sample tests. It is necessary that you follow the output form strictly. Extra spaces are not allowed.
Examples
Input
4
2 Fedorov
22-22-22
98-76-54
3 Melnikov
75-19-09
23-45-67
99-99-98
7 Rogulenko
22-22-22
11-11-11
33-33-33
44-44-44
55-55-55
66-66-66
95-43-21
3 Kaluzhin
11-11-11
99-99-99
98-65-32
Output
If you want to call a taxi, you should call: Rogulenko.
If you want to order a pizza, you should call: Fedorov, Rogulenko, Kaluzhin.
If you want to go to a cafe with a wonderful girl, you should call: Melnikov.
Input
3
5 Gleb
66-66-66
55-55-55
01-01-01
65-43-21
12-34-56
3 Serega
55-55-55
87-65-43
65-55-21
5 Melnik
12-42-12
87-73-01
36-04-12
88-12-22
82-11-43
Output
If you want to call a taxi, you should call: Gleb.
If you want to order a pizza, you should call: Gleb, Serega.
If you want to go to a cafe with a wonderful girl, you should call: Melnik.
Input
3
3 Kulczynski
22-22-22
65-43-21
98-12-00
4 Pachocki
11-11-11
11-11-11
11-11-11
98-76-54
0 Smietanka
Output
If you want to call a taxi, you should call: Pachocki.
If you want to order a pizza, you should call: Kulczynski, Pachocki.
If you want to go to a cafe with a wonderful girl, you should call: Kulczynski.
Note
In the first sample you are given four friends. Fedorov's phone book contains one taxi number and one pizza delivery number, Melnikov's phone book only has 3 numbers of girls, Rogulenko's one has 6 taxi numbers and one pizza delivery number, Kaluzhin's one contains 2 taxi numbers and one pizza delivery number.
Thus, if you need to order a taxi, you should obviously call Rogulenko, if you need to order a pizza you should call anybody of the following: Rogulenko, Fedorov, Kaluzhin (each of them has one number). Melnikov has maximal number of phone numbers of girls.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<int> T, P, G;
pair<string, vector<int> > p[100];
string s;
int main() {
int n, x, cc = 0;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x >> p[i].first;
for (int k = 0; k < 3; k++) p[i].second.push_back(0);
for (int j = 0; j < x; j++) {
cin >> s;
if (s[0] == s[1] && s[0] == s[3] && s[0] == s[4] && s[0] == s[6] &&
s[0] == s[7])
p[i].second[0]++;
else if (s[0] > s[1] && s[1] > s[3] && s[3] > s[4] && s[4] > s[6] &&
s[6] > s[7])
p[i].second[1]++;
else
p[i].second[2]++;
}
T.push_back(p[i].second[0]);
P.push_back(p[i].second[1]);
G.push_back(p[i].second[2]);
}
sort(T.rbegin(), T.rend());
sort(P.rbegin(), P.rend());
sort(G.rbegin(), G.rend());
cout << "If you want to call a taxi, you should call: ";
for (int i = 0; i < n; i++) {
if (p[i].second[0] == T[0]) {
if (cc == 1) cout << ", ";
cout << p[i].first;
cc = 1;
}
}
cout << "." << endl;
cout << "If you want to order a pizza, you should call: ";
cc = 0;
for (int i = 0; i < n; i++) {
if (p[i].second[1] == P[0]) {
if (cc == 1) cout << ", ";
cout << p[i].first;
cc = 1;
}
}
cout << "." << endl;
cout
<< "If you want to go to a cafe with a wonderful girl, you should call: ";
cc = 0;
for (int i = 0; i < n; i++) {
if (p[i].second[2] == G[0]) {
if (cc == 1) cout << ", ";
cout << p[i].first;
cc = 1;
}
}
cout << "." << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
While playing yet another strategy game, Mans has recruited n [Swedish heroes](https://www.youtube.com/watch?v=5sGOwFVUU0I), whose powers which can be represented as an array a.
Unfortunately, not all of those mighty heroes were created as capable as he wanted, so that he decided to do something about it. In order to accomplish his goal, he can pick two consecutive heroes, with powers a_i and a_{i+1}, remove them and insert a hero with power -(a_i+a_{i+1}) back in the same position.
For example if the array contains the elements [5, 6, 7, 8], he can pick 6 and 7 and get [5, -(6+7), 8] = [5, -13, 8].
After he will perform this operation n-1 times, Mans will end up having only one hero. He wants his power to be as big as possible. What's the largest possible power he can achieve?
Input
The first line contains a single integer n (1 β€ n β€ 200000).
The second line contains n integers a_1, a_2, β¦, a_n (-10^9 β€ a_i β€ 10^9) β powers of the heroes.
Output
Print the largest possible power he can achieve after n-1 operations.
Examples
Input
4
5 6 7 8
Output
26
Input
5
4 -5 9 -2 1
Output
15
Note
Suitable list of operations for the first sample:
[5, 6, 7, 8] β [-11, 7, 8] β [-11, -15] β [26]
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
constexpr long long mod = 998244353;
const long long INF = mod * mod;
const double eps = 1e-12;
const double pi = acosl(-1.0);
long long mod_pow(long long x, long long n, long long m = mod) {
if (n < 0) {
long long res = mod_pow(x, -n, m);
return mod_pow(res, m - 2, m);
}
if (abs(x) >= m) x %= m;
if (x < 0) x += m;
long long res = 1;
while (n) {
if (n & 1) res = res * x % m;
x = x * x % m;
n >>= 1;
}
return res;
}
struct modint {
long long n;
modint() : n(0) { ; }
modint(long long m) : n(m) {
if (n >= mod)
n %= mod;
else if (n < 0)
n = (n % mod + mod) % mod;
}
operator int() { return n; }
};
bool operator==(modint a, modint b) { return a.n == b.n; }
modint operator+=(modint& a, modint b) {
a.n += b.n;
if (a.n >= mod) a.n -= mod;
return a;
}
modint operator-=(modint& a, modint b) {
a.n -= b.n;
if (a.n < 0) a.n += mod;
return a;
}
modint operator*=(modint& a, modint b) {
a.n = ((long long)a.n * b.n) % mod;
return a;
}
modint operator+(modint a, modint b) { return a += b; }
modint operator-(modint a, modint b) { return a -= b; }
modint operator*(modint a, modint b) { return a *= b; }
modint operator^(modint a, long long n) {
if (n == 0) return modint(1);
modint res = (a * a) ^ (n / 2);
if (n % 2) res = res * a;
return res;
}
long long inv(long long a, long long p) {
return (a == 1 ? 1 : (1 - p * inv(p % a, a)) / a + p);
}
modint operator/(modint a, modint b) { return a * modint(inv(b, mod)); }
modint operator/=(modint& a, modint b) {
a = a / b;
return a;
}
const int max_n = 1 << 2;
modint fact[max_n], factinv[max_n];
void init_f() {
fact[0] = modint(1);
for (int i = 0; i < max_n - 1; i++) {
fact[i + 1] = fact[i] * modint(i + 1);
}
factinv[max_n - 1] = modint(1) / fact[max_n - 1];
for (int i = max_n - 2; i >= 0; i--) {
factinv[i] = factinv[i + 1] * modint(i + 1);
}
}
modint comb(int a, int b) {
if (a < 0 || b < 0 || a < b) return 0;
return fact[a] * factinv[b] * factinv[a - b];
}
modint combP(int a, int b) {
if (a < 0 || b < 0 || a < b) return 0;
return fact[a] * factinv[a - b];
}
vector<string> s[11];
void expr() {
s[1] = {"1"};
for (int i = 2; i <= 10; i++) {
for (int j = 1; j < i; j++) {
for (string t : s[j])
for (string u : s[i - j]) {
string ad = t + u;
for (int k = 0; k < ad.size(); k++) ad[k] = '0' + '1' - ad[k];
s[i].push_back(ad);
}
}
sort((s[i]).begin(), (s[i]).end());
s[i].erase(unique((s[i]).begin(), (s[i]).end()), s[i].end());
}
for (int i = 1; i <= 8; i++) {
cout << i << " start "
<< "\n";
for (string t : s[i]) cout << t << "\n";
}
}
void solve() {
int n;
cin >> n;
vector<long long> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
if (n == 1) {
cout << a[0] << "\n";
return;
}
if (n % 2 == 0) {
sort((a).begin(), (a).end());
vector<long long> ra(n + 1);
for (int i = 0; i < n; i++) ra[i + 1] = ra[i] + a[i];
int c = (n / 2) % 3;
c = (c + 2) % 3;
long long ans = -INF;
for (int x = c; x <= n; x += 3) {
long long sum = ra[n] - ra[n - x] - (ra[n - x]);
ans = max(ans, sum);
}
cout << ans << "\n";
} else {
vector<pair<long long, long long> > v(n);
for (int i = 0; i < n; i++) v[i] = {a[i], i};
sort((v).begin(), (v).end());
vector<long long> ra(n + 1);
for (int i = 0; i < n; i++) {
ra[i + 1] = ra[i] + v[i].first;
}
int c = (n + 1) / 2;
c %= 3;
long long ans = -INF;
for (int x = c; x <= n; x += 3) {
if (x == (n + 1) / 2) {
bool valid = false;
for (int j = 0; j < x; j++) {
if (v[n - 1 - j].second % 2) valid = true;
}
if (valid) {
long long sum = ra[n] - ra[n - x] - (ra[n - x]);
ans = max(ans, sum);
} else {
long long sum = ra[n] - ra[n - x] - (ra[n - x]);
sum -= 2 * v[n / 2].first;
sum += 2 * v[n / 2 - 1].first;
ans = max(ans, sum);
}
} else {
long long sum = ra[n] - ra[n - x] - (ra[n - x]);
ans = max(ans, sum);
}
}
cout << ans << "\n";
}
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
solve();
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
You are given n segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.
The intersection of a sequence of segments is such a maximal set of points (not necesserily having integer coordinates) that each point lies within every segment from the sequence. If the resulting set isn't empty, then it always forms some continuous segment. The length of the intersection is the length of the resulting segment or 0 in case the intersection is an empty set.
For example, the intersection of segments [1;5] and [3;10] is [3;5] (length 2), the intersection of segments [1;5] and [5;7] is [5;5] (length 0) and the intersection of segments [1;5] and [6;6] is an empty set (length 0).
Your task is to remove exactly one segment from the given sequence in such a way that the intersection of the remaining (n - 1) segments has the maximal possible length.
Input
The first line contains a single integer n (2 β€ n β€ 3 β
10^5) β the number of segments in the sequence.
Each of the next n lines contains two integers l_i and r_i (0 β€ l_i β€ r_i β€ 10^9) β the description of the i-th segment.
Output
Print a single integer β the maximal possible length of the intersection of (n - 1) remaining segments after you remove exactly one segment from the sequence.
Examples
Input
4
1 3
2 6
0 4
3 3
Output
1
Input
5
2 6
1 3
0 4
1 20
0 4
Output
2
Input
3
4 5
1 2
9 20
Output
0
Input
2
3 10
1 5
Output
7
Note
In the first example you should remove the segment [3;3], the intersection will become [2;3] (length 1). Removing any other segment will result in the intersection [3;3] (length 0).
In the second example you should remove the segment [1;3] or segment [2;6], the intersection will become [2;4] (length 2) or [1;3] (length 2), respectively. Removing any other segment will result in the intersection [2;3] (length 1).
In the third example the intersection will become an empty set no matter the segment you remove.
In the fourth example you will get the intersection [3;10] (length 7) if you remove the segment [1;5] or the intersection [1;5] (length 4) if you remove the segment [3;10].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxN = 3e5 + 10;
int pf[maxN][2], sf[maxN][2];
int l[maxN], r[maxN];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> l[i] >> r[i];
if (i == 0)
pf[i + 1][0] = l[i], pf[i + 1][1] = r[i];
else {
pf[i + 1][0] = max(pf[i][0], l[i]);
pf[i + 1][1] = min(pf[i][1], r[i]);
}
}
for (int i = n - 1; i >= 0; i--) {
if (i == n - 1)
sf[i][0] = l[i], sf[i][1] = r[i];
else {
sf[i][0] = max(sf[i + 1][0], l[i]);
sf[i][1] = min(sf[i + 1][1], r[i]);
}
}
int ans = 0;
for (int i = 0; i < n; i++) {
int maxL = -1;
if (i) maxL = max(maxL, pf[i][0]);
if (i + 1 < n) maxL = max(maxL, sf[i + 1][0]);
int minR = 1e9 + 10;
if (i + 1 < n) minR = min(minR, sf[i + 1][1]);
if (i) minR = min(minR, pf[i][1]);
ans = max(ans, minR - maxL);
}
cout << ans << endl;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
There are n Christmas trees on an infinite number line. The i-th tree grows at the position x_i. All x_i are guaranteed to be distinct.
Each integer point can be either occupied by the Christmas tree, by the human or not occupied at all. Non-integer points cannot be occupied by anything.
There are m people who want to celebrate Christmas. Let y_1, y_2, ..., y_m be the positions of people (note that all values x_1, x_2, ..., x_n, y_1, y_2, ..., y_m should be distinct and all y_j should be integer). You want to find such an arrangement of people that the value β_{j=1}^{m}min_{i=1}^{n}|x_i - y_j| is the minimum possible (in other words, the sum of distances to the nearest Christmas tree for all people should be minimized).
In other words, let d_j be the distance from the j-th human to the nearest Christmas tree (d_j = min_{i=1}^{n} |y_j - x_i|). Then you need to choose such positions y_1, y_2, ..., y_m that β_{j=1}^{m} d_j is the minimum possible.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 2 β
10^5) β the number of Christmas trees and the number of people.
The second line of the input contains n integers x_1, x_2, ..., x_n (-10^9 β€ x_i β€ 10^9), where x_i is the position of the i-th Christmas tree. It is guaranteed that all x_i are distinct.
Output
In the first line print one integer res β the minimum possible value of β_{j=1}^{m}min_{i=1}^{n}|x_i - y_j| (in other words, the sum of distances to the nearest Christmas tree for all people).
In the second line print m integers y_1, y_2, ..., y_m (-2 β
10^9 β€ y_j β€ 2 β
10^9), where y_j is the position of the j-th human. All y_j should be distinct and all values x_1, x_2, ..., x_n, y_1, y_2, ..., y_m should be distinct.
If there are multiple answers, print any of them.
Examples
Input
2 6
1 5
Output
8
-1 2 6 4 0 3
Input
3 5
0 3 1
Output
7
5 -2 4 -1 2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n, m;
long long sum = 0;
long long k = 0;
queue<pair<long long, long long>> bfs;
map<int, bool> map;
cin >> n >> m;
for (int i = 0; i < n; i++) {
long long a;
cin >> a;
bfs.push({a, 0});
map[a] = true;
}
vector<long long> ans;
while (true) {
if (k == m) break;
if (map.find(bfs.front().first - 1) == map.end()) {
ans.push_back(bfs.front().first - 1);
bfs.push({bfs.front().first - 1, bfs.front().second + 1});
map[bfs.front().first - 1] = true;
sum += bfs.front().second + 1;
k++;
}
if (k == m) break;
if (map.find(bfs.front().first + 1) == map.end()) {
ans.push_back(bfs.front().first + 1);
bfs.push({bfs.front().first + 1, bfs.front().second + 1});
map[bfs.front().first + 1] = true;
sum += bfs.front().second + 1;
k++;
}
bfs.pop();
if (k == m) break;
}
cout << sum << "\n";
for (int i = 0; i < m; i++) {
cout << ans[i] << " ";
}
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Let's introduce the designation <image>, where x is a string, n is a positive integer and operation " + " is the string concatenation operation. For example, [abc, 2] = abcabc.
We'll say that string s can be obtained from string t, if we can remove some characters from string t and obtain string s. For example, strings ab and aΡba can be obtained from string xacbac, and strings bx and aaa cannot be obtained from it.
Sereja has two strings, w = [a, b] and q = [c, d]. He wants to find such maximum integer p (p > 0), that [q, p] can be obtained from string w.
Input
The first line contains two integers b, d (1 β€ b, d β€ 107). The second line contains string a. The third line contains string c. The given strings are not empty and consist of lowercase English letters. Their lengths do not exceed 100.
Output
In a single line print an integer β the largest number p. If the required value of p doesn't exist, print 0.
Examples
Input
10 3
abab
bab
Output
3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int dp[100];
int main() {
int b, d, n, m, i, j, t;
string a, c;
cin >> b >> d >> a >> c;
n = a.size();
m = c.size();
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
if (a[j] == c[(i + dp[i]) % m]) dp[i]++;
t = 0;
for (i = 0; i < b; i++) t += dp[t % m];
cout << t / d / m << endl;
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
There are n incoming messages for Vasya. The i-th message is going to be received after ti minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. After reading the message, Vasya's bank account receives the current cost of this message. Initially, Vasya's bank account is at 0.
Also, each minute Vasya's bank account receives CΒ·k, where k is the amount of received but unread messages.
Vasya's messages are very important to him, and because of that he wants to have all messages read after T minutes.
Determine the maximum amount of money Vasya's bank account can hold after T minutes.
Input
The first line contains five integers n, A, B, C and T (1 β€ n, A, B, C, T β€ 1000).
The second string contains n integers ti (1 β€ ti β€ T).
Output
Output one integer β the answer to the problem.
Examples
Input
4 5 5 3 5
1 5 5 4
Output
20
Input
5 3 1 1 3
2 2 2 1 1
Output
15
Input
5 5 3 4 5
1 2 3 4 5
Output
35
Note
In the first sample the messages must be read immediately after receiving, Vasya receives A points for each message, nΒ·A = 20 in total.
In the second sample the messages can be read at any integer moment.
In the third sample messages must be read at the moment T. This way Vasya has 1, 2, 3, 4 and 0 unread messages at the corresponding minutes, he gets 40 points for them. When reading messages, he receives (5 - 4Β·3) + (5 - 3Β·3) + (5 - 2Β·3) + (5 - 1Β·3) + 5 = - 5 points. This is 35 in total.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, A, B, C, T, a[100000];
int mon = 0;
cin >> n >> A >> B >> C >> T;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
if (C <= B) {
mon = n * A;
} else {
for (int i = 0; i < n; i++) {
if (a[i] <= T) mon = mon + (T - a[i]) * C + A - (T - a[i]) * B;
}
}
cout << mon;
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
You are given a string S consisting of lowercase English letters. Determine whether all the characters in S are different.
Constraints
* 2 β€ |S| β€ 26, where |S| denotes the length of S.
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
If all the characters in S are different, print `yes` (case-sensitive); otherwise, print `no`.
Examples
Input
uncopyrightable
Output
yes
Input
different
Output
no
Input
no
Output
yes
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
string s;
int hsh[35];
int main()
{
cin >> s;
for(int i=0;i<s.size();i++)
{
++hsh[s[i]-'a'];
}
for(int i=0;i<26;i++)
{
if(hsh[i]>1)
{
printf("no");
return 0;
}
}
printf("yes");
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
Input
The single line of the input contains two positive integers a and b (1 β€ a, b β€ 100) β the number of red and blue socks that Vasya's got.
Output
Print two space-separated integers β the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.
Examples
Input
3 1
Output
1 1
Input
2 3
Output
2 0
Input
7 3
Output
3 2
Note
In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
int x, coun;
x = abs(a - b) / 2;
if (a > b)
cout << b << " " << x;
else
cout << a << " " << x;
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
You successfully found poor Arkady near the exit of the station you've perfectly predicted. You sent him home on a taxi and suddenly came up with a question.
There are n crossroads in your city and several bidirectional roads connecting some of them. A taxi ride is a path from some crossroads to another one without passing the same crossroads twice. You have a collection of rides made by one driver and now you wonder if this driver can be a robot or they are definitely a human.
You think that the driver can be a robot if for every two crossroads a and b the driver always chooses the same path whenever he drives from a to b. Note that a and b here do not have to be the endpoints of a ride and that the path from b to a can be different. On the contrary, if the driver ever has driven two different paths from a to b, they are definitely a human.
Given the system of roads and the description of all rides available to you, determine if the driver can be a robot or not.
Input
Each test contains one or more test cases. The first line contains a single integer t (1 β€ t β€ 3 β
10^5) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 3 β
10^5) β the number of crossroads in the city.
The next line contains a single integer q (1 β€ q β€ 3 β
10^5) β the number of rides available to you.
Each of the following q lines starts with a single integer k (2 β€ k β€ n) β the number of crossroads visited by the driver on this ride. It is followed by k integers c_1, c_2, ..., c_k (1 β€ c_i β€ n) β the crossroads in the order the driver visited them. It is guaranteed that all crossroads in one ride are distinct.
It is guaranteed that the sum of values k among all rides of all test cases does not exceed 3 β
10^5.
It is guaranteed that the sum of values n and the sum of values q doesn't exceed 3 β
10^5 among all test cases.
Output
Output a single line for each test case.
If the driver can be a robot, output "Robot" in a single line. Otherwise, output "Human".
You can print each letter in any case (upper or lower).
Examples
Input
1
5
2
4 1 2 3 5
3 1 4 3
Output
Human
Input
1
4
4
3 1 2 3
3 2 3 4
3 3 4 1
3 4 1 2
Output
Robot
Note
In the first example it is clear that the driver used two different ways to get from crossroads 1 to crossroads 3. It must be a human.
In the second example the driver always drives the cycle 1 β 2 β 3 β 4 β 1 until he reaches destination.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int S = 500;
vector<int> v[300001];
vector<pair<int, int> > V[300001];
int T, n, q, k, x, po[300001], p[300001];
void solve() {
scanf("%d%d", &n, &q);
for (int i = 1; i <= q; i++) {
scanf("%d", &k);
v[i].clear();
for (int j = 0; j < k; j++) scanf("%d", &x), v[i].push_back(x);
}
for (int i = 1; i <= q; i++)
if (v[i].size() >= S) {
int k = v[i].size();
for (int j = 0; j < k; j++) po[v[i][j]] = j + 1;
for (int j = 1, siz, l; j <= q; j++)
if (i != j) {
int mi = (po[v[j][0]] ? po[v[j][0]] : (1e9));
for (l = 1, siz = v[j].size(); l < siz; l++)
if (po[v[j][l]]) {
if (mi < po[v[j][l]] && !po[v[j][l - 1]] ||
po[v[j][l - 1]] && po[v[j][l - 1]] < po[v[j][l]] - 1) {
for (int j = 0; j < k; j++) po[v[i][j]] = 0;
puts("Human");
return;
}
mi = (mi > po[v[j][l]] ? po[v[j][l]] : mi);
}
}
for (int j = 0; j < k; j++) po[v[i][j]] = 0;
}
for (int i = 1; i <= n; i++) V[i].clear();
for (int i = 1, siz, j; i <= q; i++)
if (v[i].size() < S)
for (j = 0, siz = v[i].size(); j < siz; j++)
V[v[i][j]].push_back(make_pair(i, j));
for (int i = 1, siz, j; i <= n; i++) {
for (j = 0, siz = V[i].size(); j < siz; j++) {
int p1 = V[i][j].first, p2 = V[i][j].second, s = v[p1].size();
for (int k = p2 + 1, K; k < s; k++) {
K = v[p1][k];
if (!po[K])
po[K] = p1, p[K] = k;
else if (v[po[K]][p[K] - 1] != v[p1][k - 1]) {
for (j = 0, siz = V[i].size(); j < siz; j++) {
int p1 = V[i][j].first, p2 = V[i][j].second, s = v[p1].size();
for (int k = p2 + 1; k < s; k++) po[v[p1][k]] = 0;
}
puts("Human");
return;
}
}
}
for (j = 0, siz = V[i].size(); j < siz; j++) {
int p1 = V[i][j].first, p2 = V[i][j].second, s = v[p1].size();
for (int k = p2 + 1; k < s; k++) po[v[p1][k]] = 0;
}
}
puts("Robot");
}
int main() {
scanf("%d", &T);
memset(po, 0, sizeof(po));
while (T--) solve();
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Leonid works for a small and promising start-up that works on decoding the human genome. His duties include solving complex problems of finding certain patterns in long strings consisting of letters 'A', 'T', 'G' and 'C'.
Let's consider the following scenario. There is a fragment of a human DNA chain, recorded as a string S. To analyze the fragment, you need to find all occurrences of string T in a string S. However, the matter is complicated by the fact that the original chain fragment could contain minor mutations, which, however, complicate the task of finding a fragment. Leonid proposed the following approach to solve this problem.
Let's write down integer k β₯ 0 β the error threshold. We will say that string T occurs in string S on position i (1 β€ i β€ |S| - |T| + 1), if after putting string T along with this position, each character of string T corresponds to the some character of the same value in string S at the distance of at most k. More formally, for any j (1 β€ j β€ |T|) there must exist such p (1 β€ p β€ |S|), that |(i + j - 1) - p| β€ k and S[p] = T[j].
For example, corresponding to the given definition, string "ACAT" occurs in string "AGCAATTCAT" in positions 2, 3 and 6.
<image>
Note that at k = 0 the given definition transforms to a simple definition of the occurrence of a string in a string.
Help Leonid by calculating in how many positions the given string T occurs in the given string S with the given error threshold.
Input
The first line contains three integers |S|, |T|, k (1 β€ |T| β€ |S| β€ 200 000, 0 β€ k β€ 200 000) β the lengths of strings S and T and the error threshold.
The second line contains string S.
The third line contains string T.
Both strings consist only of uppercase letters 'A', 'T', 'G' and 'C'.
Output
Print a single number β the number of occurrences of T in S with the error threshold k by the given definition.
Examples
Input
10 4 1
AGCAATTCAT
ACAT
Output
3
Note
If you happen to know about the structure of the human genome a little more than the author of the problem, and you are not impressed with Leonid's original approach, do not take everything described above seriously.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 9;
const int MOD = 1e9 + 7;
int mod = 999998639;
inline long long qpow(long long b, long long e, long long m = MOD) {
long long a = 1;
for (; e; e >>= 1, b = b * b % m)
if (e & 1) a = a * b % m;
return a;
}
long long exgcd(long long a, long long b, long long &x, long long &y) {
if (b == 0) {
x = 1, y = 0;
return a;
}
long long d = exgcd(b, a % b, x, y);
long long z = x;
x = y, y = z - y * (a / b);
return d;
}
int rev[maxn];
struct Complex {
double x, y;
Complex(double _x = 0.0, double _y = 0.0) {
x = _x;
y = _y;
}
Complex operator-(const Complex &b) const {
return Complex(x - b.x, y - b.y);
}
Complex operator+(const Complex &b) const {
return Complex(x + b.x, y + b.y);
}
Complex operator*(const Complex &b) const {
return Complex(x * b.x - y * b.y, x * b.y + y * b.x);
}
};
void change(Complex y[], int len) {
for (int i = 0; i < len; ++i) {
rev[i] = rev[i >> 1] >> 1;
if (i & 1) {
rev[i] |= len >> 1;
}
}
for (int i = 0; i < len; ++i) {
if (i < rev[i]) {
swap(y[i], y[rev[i]]);
}
}
return;
}
void fft(Complex y[], int len, int on) {
change(y, len);
for (int h = 2; h <= len; h <<= 1) {
Complex wn(cos(2 * acos(-1) / h), sin(on * 2 * acos(-1) / h));
for (int j = 0; j < len; j += h) {
Complex w(1, 0);
for (int k = j; k < j + h / 2; k++) {
Complex u = y[k];
Complex t = w * y[k + h / 2];
y[k] = u + t;
y[k + h / 2] = u - t;
w = w * wn;
}
}
}
if (on == -1) {
for (int i = 0; i < len; i++) {
y[i].x /= len;
}
}
}
Complex A[maxn], B[maxn];
char s[maxn], t[maxn];
int a[maxn], b[maxn], ans[maxn];
map<char, vector<int> > mp;
int n, m, k;
void solve(char c, int len) {
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
for (int i = 0; i < n; i++) {
int l = -0x3f3f3f3f, r = 0x3f3f3f3f;
auto it = lower_bound(mp[c].begin(), mp[c].end(), i);
if (it != mp[c].end()) r = *it;
if (it != mp[c].begin()) l = *(--it);
if (abs(i - l) <= k || abs(i - r) <= k) a[i] = 1;
}
for (int i = 0; i < m; i++) {
if (t[i] == c) b[i] = 1;
}
for (int i = 0; i <= len; i++) {
A[i] = Complex(a[i], 0);
B[i] = Complex(b[i], 0);
}
fft(A, len, 1), fft(B, len, 1);
for (int i = 0; i <= len; i++) {
A[i] = A[i] * B[i];
}
fft(A, len, -1);
for (int i = 0; i <= len; i++) {
ans[i] += int(A[i].x + 0.5);
}
}
int main() {
while (scanf("%d%d%d", &n, &m, &k) != EOF) {
scanf("%s%s", s, t);
reverse(s, s + n);
for (int i = 0; i < n; i++) {
mp[s[i]].push_back(i);
}
int len = 1;
while (len < 2 * n) len <<= 1;
solve('A', len), solve('T', len), solve('G', len), solve('C', len);
int res = 0;
for (int i = 0; i < n; i++) {
if (ans[i] == m) res++;
}
printf("%d\n", res);
}
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
Input
The first line of input contains integer n denoting the number of psychos, (1 β€ n β€ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive β ids of the psychos in the line from left to right.
Output
Print the number of steps, so that the line remains the same afterward.
Examples
Input
10
10 9 7 8 6 5 3 4 2 1
Output
2
Input
6
1 2 3 4 5 6
Output
0
Note
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] β [10 8 4] β [10]. So, there are two steps.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
const int maxm = 1e6 + 5;
const int inf = 0x3f3f3f3f;
long long mod = 998244353;
const double eps = 1e-9;
const double pi = acos(-1);
const double e = 2.718281828;
int n, m, w, k;
int ans[maxn];
int sta[maxn];
int a[maxn];
int main() {
int _;
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
int as = 0;
int l = 0;
for (int i = n - 1; i >= 0; i--) {
sta[l++] = a[i];
while (l > 1 && sta[l - 1] > sta[l - 2]) {
if (ans[sta[l - 2]] > ans[sta[l - 1]])
ans[sta[l - 1]] = ans[sta[l - 2]];
else
ans[sta[l - 1]]++;
sta[l - 2] = sta[l - 1];
l--;
}
as = max(as, ans[sta[l - 1]]);
}
cout << as << endl;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
On one quiet day all of sudden Mister B decided to draw angle a on his field. Aliens have already visited his field and left many different geometric figures on it. One of the figures is regular convex n-gon (regular convex polygon with n sides).
That's why Mister B decided to use this polygon. Now Mister B must find three distinct vertices v1, v2, v3 such that the angle <image> (where v2 is the vertex of the angle, and v1 and v3 lie on its sides) is as close as possible to a. In other words, the value <image> should be minimum possible.
If there are many optimal solutions, Mister B should be satisfied with any of them.
Input
First and only line contains two space-separated integers n and a (3 β€ n β€ 105, 1 β€ a β€ 180) β the number of vertices in the polygon and the needed angle, in degrees.
Output
Print three space-separated integers: the vertices v1, v2, v3, which form <image>. If there are multiple optimal solutions, print any of them. The vertices are numbered from 1 to n in clockwise order.
Examples
Input
3 15
Output
1 2 3
Input
4 67
Output
2 1 3
Input
4 68
Output
4 1 2
Note
In first sample test vertices of regular triangle can create only angle of 60 degrees, that's why every possible angle is correct.
Vertices of square can create 45 or 90 degrees angles only. That's why in second sample test the angle of 45 degrees was chosen, since |45 - 67| < |90 - 67|. Other correct answers are: "3 1 2", "3 2 4", "4 2 3", "4 3 1", "1 3 4", "1 4 2", "2 4 1", "4 1 3", "3 1 4", "3 4 2", "2 4 3", "2 3 1", "1 3 2", "1 2 4", "4 2 1".
In third sample test, on the contrary, the angle of 90 degrees was chosen, since |90 - 68| < |45 - 68|. Other correct answers are: "2 1 4", "3 2 1", "1 2 3", "4 3 2", "2 3 4", "1 4 3", "3 4 1".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename T, typename T1>
ostream &operator<<(ostream &out, pair<T, T1> obj) {
out << "(" << obj.first << "," << obj.second << ")";
return out;
}
template <typename T, typename T1>
ostream &operator<<(ostream &out, map<T, T1> cont) {
typename map<T, T1>::const_iterator itr = cont.begin();
typename map<T, T1>::const_iterator ends = cont.end();
for (; itr != ends; ++itr) out << *itr << " ";
out << endl;
return out;
}
template <typename T>
ostream &operator<<(ostream &out, set<T> cont) {
typename set<T>::const_iterator itr = cont.begin();
typename set<T>::const_iterator ends = cont.end();
for (; itr != ends; ++itr) out << *itr << " ";
out << endl;
return out;
}
template <typename T>
ostream &operator<<(ostream &out, multiset<T> cont) {
typename multiset<T>::const_iterator itr = cont.begin();
typename multiset<T>::const_iterator ends = cont.end();
for (; itr != ends; ++itr) out << *itr << " ";
out << endl;
return out;
}
template <typename T,
template <typename ELEM, typename ALLOC = allocator<ELEM>> class CONT>
ostream &operator<<(ostream &out, CONT<T> cont) {
typename CONT<T>::const_iterator itr = cont.begin();
typename CONT<T>::const_iterator ends = cont.end();
for (; itr != ends; ++itr) out << *itr << " ";
out << endl;
return out;
}
template <typename T, unsigned int N, typename CTy, typename CTr>
typename enable_if<!is_same<T, char>::value, basic_ostream<CTy, CTr> &>::type
operator<<(basic_ostream<CTy, CTr> &out, const T (&arr)[N]) {
for (auto i = 0; i < N; ++i) out << arr[i] << " ";
out << endl;
return out;
}
template <typename T>
T gcd(T a, T b) {
T min_v = min(a, b);
T max_v = max(a, b);
while (min_v) {
T temp = max_v % min_v;
max_v = min_v;
min_v = temp;
}
return max_v;
}
template <typename T>
T lcm(T a, T b) {
return (a * b) / gcd(a, b);
}
template <typename T>
T fast_exp_pow(T base, T exp, T mod) {
T res = 1;
while (exp) {
if (exp & 1) {
res *= base;
res %= mod;
}
exp >>= 1;
base *= base;
base %= mod;
}
return res % mod;
}
int N, A;
int main() {
scanf("%d%d", &N, &A);
double angle = (N - 2.0) * 180.0 / N;
double angle_1 = angle / (N - 2.0);
int div = min(N - 3, (int)(A / angle_1));
double val_1 = fabs(div * angle_1 - A);
double val_2 = fabs((div + 1) * angle_1 - A);
if (div && val_1 < val_2) {
printf("1 2 %d\n", N - div + 1);
} else {
printf("1 2 %d\n", N - div);
}
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
The prison of your city has n prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer c of the prisoners to a prison located in another city.
For this reason, he made the n prisoners to stand in a line, with a number written on their chests. The number is the severity of the crime he/she has committed. The greater the number, the more severe his/her crime was.
Then, the mayor told you to choose the c prisoners, who will be transferred to the other prison. He also imposed two conditions. They are,
* The chosen c prisoners has to form a contiguous segment of prisoners.
* Any of the chosen prisoner's crime level should not be greater then t. Because, that will make the prisoner a severe criminal and the mayor doesn't want to take the risk of his running away during the transfer.
Find the number of ways you can choose the c prisoners.
Input
The first line of input will contain three space separated integers n (1 β€ n β€ 2Β·105), t (0 β€ t β€ 109) and c (1 β€ c β€ n). The next line will contain n space separated integers, the ith integer is the severity ith prisoner's crime. The value of crime severities will be non-negative and will not exceed 109.
Output
Print a single integer β the number of ways you can choose the c prisoners.
Examples
Input
4 3 3
2 3 1 1
Output
2
Input
1 1 1
2
Output
0
Input
11 4 2
2 2 0 7 3 2 2 4 9 1 4
Output
6
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[200005];
int main() {
int n, t, c, i, j = 0, tmp = 0, f = 0;
cin >> n >> t >> c;
for (i = 0; i < n; i++) {
cin >> a[i];
if (a[i] > t) {
j = 0;
} else {
if (j >= c - 1) {
tmp++;
}
j++;
}
}
cout << tmp;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Dreamoon likes coloring cells very much.
There is a row of n cells. Initially, all cells are empty (don't contain any color). Cells are numbered from 1 to n.
You are given an integer m and m integers l_1, l_2, β¦, l_m (1 β€ l_i β€ n)
Dreamoon will perform m operations.
In i-th operation, Dreamoon will choose a number p_i from range [1, n-l_i+1] (inclusive) and will paint all cells from p_i to p_i+l_i-1 (inclusive) in i-th color. Note that cells may be colored more one than once, in this case, cell will have the color from the latest operation.
Dreamoon hopes that after these m operations, all colors will appear at least once and all cells will be colored. Please help Dreamoon to choose p_i in each operation to satisfy all constraints.
Input
The first line contains two integers n,m (1 β€ m β€ n β€ 100 000).
The second line contains m integers l_1, l_2, β¦, l_m (1 β€ l_i β€ n).
Output
If it's impossible to perform m operations to satisfy all constraints, print "'-1" (without quotes).
Otherwise, print m integers p_1, p_2, β¦, p_m (1 β€ p_i β€ n - l_i + 1), after these m operations, all colors should appear at least once and all cells should be colored.
If there are several possible solutions, you can print any.
Examples
Input
5 3
3 2 2
Output
2 4 1
Input
10 1
1
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline long long read() {
register long long x = 0;
register bool f = 0;
register char c = getchar();
while (c < '0' || c > '9') {
if (c == '-') f = 1;
c = getchar();
}
while (c >= '0' && c <= '9') {
x = (x << 3) + (x << 1) + c - 48;
c = getchar();
}
return f ? -x : x;
}
char cr[200];
long long tt;
inline void print(register long long x, register char k = '\n') {
if (!x) putchar('0');
if (x < 0) putchar('-'), x = -x;
while (x) cr[++tt] = x % 10 + '0', x /= 10;
while (tt) putchar(cr[tt--]);
putchar(k);
}
const long long maxn = 114514;
long long a[maxn], s[maxn], n, m, p[maxn], sum;
signed main() {
n = read();
m = read();
for (long long i = 1; i <= m; i++) {
a[i] = read();
p[i] = i;
if (p[i] + a[i] - 1 > n) {
print(-1);
return 0;
}
sum += a[i];
}
if (sum < n) {
print(-1);
return 0;
}
sum = 0;
for (long long i = m; i; i--) {
sum += a[i];
p[i] = n - sum + 1;
if (p[i] < i) p[i] = i;
}
for (long long i = 1; i <= m; i++) {
print(p[i], ' ');
}
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
For a dynamic list $L$ of integers, perform a sequence of the following operations. $L$ has a special element called END at the end of the list and an element of $L$ is indicated by a cursor.
* insert($x$): Insert $x$ before the element indicated by the cursor. After this operation, the cursor points the inserted element.
* move($d$): Move the cursor to the end by $d$, if $d$ is positive. Move the cursor to the front by $d$, if $d$ is negative.
* erase(): Delete the element indicated by the cursor. After this operation, the cursor points the element next to the deleted element. In case there is no such element, the cursor should point END.
In the initial state, $L$ is empty and the cursor points END.
Constraints
* $1 \leq q \leq 500,000$
* The cursor indicates an element of $L$ or END during the operations
* Erase operation will not given when the cursor points END
* $-1,000,000,000 \leq x \leq 1,000,000,000$
* Moving distance of the cursor ($\sum{|d|}$) does not exceed 1,000,000
* $L$ is not empty after performing all operations
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $x$
or
1 $d$
or
2
where the first digits 0, 1 and 2 represent insert, move and erase operations respectively.
Output
Print all elements of the list in order after performing given operations. Print an element in a line.
Example
Input
5
0 1
0 2
0 3
1 1
2
Output
3
1
### Response
```cpp
#include "stdio.h"
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <list>
#include <iterator>
using namespace std;
enum {INS, MOVE, DEL};
class Puzzle
{
public:
int N;
//vector<long> list;
list<int> data;
void input()
{
cin >> N;
}
void play()
{
int q;
long d;
//int cs = 0;
list<int>::iterator itr = data.begin();
for (int qi = 0; qi < N; qi++) {
cin >> q;
switch (q) {
case INS:
cin >> d;
itr = data.insert(itr,d);
break;
case MOVE:
cin >> d;
advance(itr, d);
//itr = itr + 5;
break;
case DEL:
itr = data.erase(itr);
break;
}
}
for (auto d : data) {
printf("%d\n", d);
}
}
};
int main()
{
Puzzle puz;
puz.input();
puz.play();
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Luba thinks about watering her garden. The garden can be represented as a segment of length k. Luba has got n buckets, the i-th bucket allows her to water some continuous subsegment of garden of length exactly ai each hour. Luba can't water any parts of the garden that were already watered, also she can't water the ground outside the garden.
Luba has to choose one of the buckets in order to water the garden as fast as possible (as mentioned above, each hour she will water some continuous subsegment of length ai if she chooses the i-th bucket). Help her to determine the minimum number of hours she has to spend watering the garden. It is guaranteed that Luba can always choose a bucket so it is possible water the garden.
See the examples for better understanding.
Input
The first line of input contains two integer numbers n and k (1 β€ n, k β€ 100) β the number of buckets and the length of the garden, respectively.
The second line of input contains n integer numbers ai (1 β€ ai β€ 100) β the length of the segment that can be watered by the i-th bucket in one hour.
It is guaranteed that there is at least one bucket such that it is possible to water the garden in integer number of hours using only this bucket.
Output
Print one integer number β the minimum number of hours required to water the garden.
Examples
Input
3 6
2 3 5
Output
2
Input
6 7
1 2 3 4 5 6
Output
7
Note
In the first test the best option is to choose the bucket that allows to water the segment of length 3. We can't choose the bucket that allows to water the segment of length 5 because then we can't water the whole garden.
In the second test we can choose only the bucket that allows us to water the segment of length 1.
### Response
```cpp
#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:10000000")
using namespace std;
const double PI = acos(-1.0);
const int INF = 1e9;
const int MOD = INF + 7;
const long long BIGINF = 1e16;
int n, k, elem, mini = 1e9;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> k;
for (int i = 0; i < n; i++) {
cin >> elem;
if (k % elem == 0) mini = min(k / elem, mini);
}
cout << mini << '\n';
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
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 n, a, b;
int main(int argc, char const *argv[]) {
scanf("%d %d %d", &n, &a, &b);
int ans = (a - 1 + b) % n + 1;
printf("%d\n", ans < 1 ? ans + n : ans);
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
The Fair Nut found a string s. The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences p_1, p_2, β¦, p_k, such that:
1. For each i (1 β€ i β€ k), s_{p_i} = 'a'.
2. For each i (1 β€ i < k), there is such j that p_i < j < p_{i + 1} and s_j = 'b'.
The Nut is upset because he doesn't know how to find the number. Help him.
This number should be calculated modulo 10^9 + 7.
Input
The first line contains the string s (1 β€ |s| β€ 10^5) consisting of lowercase Latin letters.
Output
In a single line print the answer to the problem β the number of such sequences p_1, p_2, β¦, p_k modulo 10^9 + 7.
Examples
Input
abbaa
Output
5
Input
baaaa
Output
4
Input
agaa
Output
3
Note
In the first example, there are 5 possible sequences. [1], [4], [5], [1, 4], [1, 5].
In the second example, there are 4 possible sequences. [2], [3], [4], [5].
In the third example, there are 3 possible sequences. [1], [3], [4].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;
const ll N = 1e5 + 5;
ll mat[N];
vector<int> v;
int n;
ll nikal(int pos) {
if (pos == n) return 1;
if (mat[pos] != -1) return mat[pos];
return mat[pos] = (nikal(pos + 1) * v[pos] + nikal(pos + 1)) % mod;
}
void solve() {
string s;
memset(mat, -1, sizeof(mat));
cin >> s;
string t;
for (int i = 0; i < s.size(); i++) {
if (s[i] == 'a' || s[i] == 'b') t.push_back(s[i]);
;
}
s = t;
int c = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == 'a')
c++;
else if (s[i] == 'b') {
if (c) v.push_back(c);
c = 0;
}
}
if (c) v.push_back(c);
n = v.size();
cout << nikal(0) - 1;
}
int main() {
int t = 1;
while (t--) {
solve();
}
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
This is the easy version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved.
You are given an array [a_1, a_2, ..., a_n].
Your goal is to find the length of the longest subarray of this array such that the most frequent value in it is not unique. In other words, you are looking for a subarray such that if the most frequent value occurs f times in this subarray, then at least 2 different values should occur exactly f times.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
The first line contains a single integer n (1 β€ n β€ 200 000) β the length of the array.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ min(n, 100)) β elements of the array.
Output
You should output exactly one integer β the length of the longest subarray of the array whose most frequent value is not unique. If there is no such subarray, output 0.
Examples
Input
7
1 1 2 2 3 3 3
Output
6
Input
10
1 1 1 5 4 1 3 1 2 2
Output
7
Input
1
1
Output
0
Note
In the first sample, the subarray [1, 1, 2, 2, 3, 3] is good, but [1, 1, 2, 2, 3, 3, 3] isn't: in the latter there are 3 occurrences of number 3, and no other element appears 3 times.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <class T>
ostream &operator<<(ostream &os, const vector<T> &v) {
os << "[";
for (int i = 0; i < (((int)(v).size())); ++i) {
if (i) os << ", ";
os << v[i];
}
return os << "]";
}
template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
return os << "(" << p.first << " " << p.second << ")";
}
template <class T>
bool chmax(T &a, const T &b) {
if (a < b) {
a = b;
return true;
}
return false;
}
template <class T>
bool chmin(T &a, const T &b) {
if (b < a) {
a = b;
return true;
}
return false;
}
using ll = long long;
using ull = unsigned long long;
using ld = long double;
using P = pair<int, int>;
using vi = vector<int>;
using vll = vector<ll>;
using vvi = vector<vi>;
using vvll = vector<vll>;
const ll MOD = 1e9 + 7;
const int INF = INT_MAX / 2;
const ll LINF = LLONG_MAX / 2;
const ld eps = 1e-9;
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
cout << fixed << setprecision(10);
int n;
cin >> n;
vi a(n);
map<int, int> mp;
set<int> st;
for (int i = 0; i < (n); ++i) {
cin >> a[i];
mp[a[i]]++;
st.insert(a[i]);
}
int ma = 0, argma = 0;
for (auto [val, cnt] : mp) {
bool upd = chmax(ma, cnt);
if (upd) argma = val;
}
int ans = 0;
for (auto &val : st) {
if (val == argma) continue;
vvi v(2 * n + 5);
int now = 0;
v[n].push_back(-1);
for (int i = 0; i < (n); ++i) {
if (a[i] == argma) {
now++;
} else if (a[i] == val) {
now--;
}
v[now + n].push_back(i);
}
for (int i = 0; i < (2 * n + 5); ++i) {
int mi = INF, ma = -INF;
for (int j = 0; j < (((int)(v[i]).size())); ++j) {
chmin(mi, v[i][j]);
chmax(ma, v[i][j]);
}
if (mi != INF && ma != -INF && mi != ma) {
chmax(ans, ma - mi);
}
}
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
You are given n points on a plane. All points are different.
Find the number of different groups of three points (A, B, C) such that point B is the middle of segment AC.
The groups of three points are considered unordered, that is, if point B is the middle of segment AC, then groups (A, B, C) and (C, B, A) are considered the same.
Input
The first line contains a single integer n (3 β€ n β€ 3000) β the number of points.
Next n lines contain the points. The i-th line contains coordinates of the i-th point: two space-separated integers xi, yi ( - 1000 β€ xi, yi β€ 1000).
It is guaranteed that all given points are different.
Output
Print the single number β the answer to the problem.
Examples
Input
3
1 1
2 2
3 3
Output
1
Input
3
0 0
-1 0
0 1
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int cot[4010][4010];
int main() {
int x[3010], y[3010];
int n, i, j;
while (cin >> n) {
memset(cot, 0, sizeof(cot));
for (i = 0; i < n; i++) {
cin >> x[i] >> y[i];
x[i] += 1000;
y[i] += 1000;
}
int ans = 0;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
cot[x[i] + x[j]][y[i] + y[j]]++;
}
}
for (i = 0; i < n; i++) {
ans += cot[x[i] * 2][y[i] * 2];
}
cout << ans << endl;
}
}
``` |
### Prompt
Generate a CPP solution to the following problem:
At University A, there were many mistakes in entering IDs.
Therefore, University A decided to issue a new ID to prevent typos.
There is a way to check if the new ID is correct to prevent typos.
γ» Calculate the sum of all digits.
γ» However, the number of even-numbered digits is doubled, with the rightmost digit as the first digit.
-When the number becomes 10 or more by doubling, the number obtained by adding the 1st digit and the 10th digit is used as the digit number.
γ» If the sum is divisible by 10, the ID is correct, otherwise it is incorrect.
As an example, check the ID 53579.
Since the sum of all digits is calculated,
5 + 3 + 5 + 7 + 9
However, since the number of even-numbered digits is doubled,
5 + 6 + 5 + 14 + 9
When the number becomes 10 or more by doubling, the number obtained by adding the ones digit and the tens digit is the digit number.
5 + 6 + 5 + (1 + 4) + 9
From the above, the total sum is 30. Since 30 is divisible by 10, 53579 is the correct ID.
Mr. B is a college student at University A and was issued a new ID, but he forgot some digits of the ID.
However, I succeeded in narrowing down some candidates as to what kind of numbers will be included in the forgotten part.
Your job is to find out how many correct combinations of B's ββIDs are available.
Input
The input is given in the following format.
n
ID
m
a0 a1 ... am-1
n is the number of digits in the ID.
Each digit of the ID contains a number from 0 to 9 or the letter'*' to indicate that it is a forgotten digit.
m is the number of candidate numbers in the'*'.
ai is a candidate for numbers in'*'.
Input meets the following constraints
1 β€ n β€ 100,000
1 β€ m β€ 10
0 β€ ai β€ 9
Number of 1 β€'*' β€ 7
Output
Output the answer value on one line
Examples
Input
5
5*57*
2
3 9
Output
1
Input
15
2***9*2*6*1199*
9
0 1 2 3 4 6 7 8 9
Output
478297
### Response
```cpp
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int m, n, a[10], a_2[10], ID[100001];
int dp[100001][10];
int table[] = { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9};
int rec( int now, int sum ){
if(now == n + 1) return sum % 10 == 0;
if(~dp[now][sum % 10]) return dp[now][sum % 10];
int ret = 0;
if(~ID[now]){
ret += rec( now + 1, sum + ID[now]);
}else{
if(now & 1)
for(int i = 0 ; i < m ; i++ ){
ret += rec( now + 1, sum + a[i]);
}
else
for(int i = 0 ; i < m ; i++ ){
ret += rec( now + 1, sum + a_2[i]);
}
}
return dp[now][sum % 10] = ret;
}
int main(){
fill_n( *dp, 100001 * 10, -1);
cin >> n;
for(int i = n ; i ; i-- ){
char c;
cin >> c;
if(c == '*') ID[i] = -1;
else ID[i] = i % 2 ? c - '0' : table[c - '0'];
}
cin >> m;
for(int i = 0 ; i < m ; i++ ){
cin >> a[i];
a_2[i] = table[a[i]];
}
cout << rec( 1, 0) << endl;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Takahashi and Aoki are playing a stone-taking game. Initially, there are N piles of stones, and the i-th pile contains A_i stones and has an associated integer K_i.
Starting from Takahashi, Takahashi and Aoki take alternate turns to perform the following operation:
* Choose a pile. If the i-th pile is selected and there are X stones left in the pile, remove some number of stones between 1 and floor(X/K_i) (inclusive) from the pile.
The player who first becomes unable to perform the operation loses the game. Assuming that both players play optimally, determine the winner of the game. Here, floor(x) represents the largest integer not greater than x.
Constraints
* 1 \leq N \leq 200
* 1 \leq A_i,K_i \leq 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 K_1
:
A_N K_N
Output
If Takahashi will win, print `Takahashi`; if Aoki will win, print `Aoki`.
Examples
Input
2
5 2
3 3
Output
Aoki
Input
3
3 2
4 3
5 1
Output
Takahashi
Input
3
28 3
16 4
19 2
Output
Aoki
Input
4
3141 59
26535 897
93 23
8462 64
Output
Takahashi
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, r = 0;
cin >> n;
for (int i = 0; i < n; i++) {
int a, k;
cin >> a >> k;
for (;;) {
int b = a % k % (a / k + 1);
if (!b) break;
a += b - a / k - a % k - 1;
}
r ^= a / k;
}
cout << (r ? "Takahashi" : "Aoki") << endl;
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.
Limak will repeat the following operation till everything is destroyed.
Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.
Limak is ready to start. You task is to count how many operations will it take him to destroy all towers.
Input
The first line contains single integer n (1 β€ n β€ 105).
The second line contains n space-separated integers h1, h2, ..., hn (1 β€ hi β€ 109) β sizes of towers.
Output
Print the number of operations needed to destroy all towers.
Examples
Input
6
2 1 4 6 2 2
Output
3
Input
7
3 3 3 1 3 3 3
Output
2
Note
The picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color.
<image> After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100000 + 5;
int n;
int l[maxn], r[maxn], h[maxn];
int main() {
while (cin >> n) {
for (int i = 1; i <= n; i++) {
scanf("%d", &h[i]);
}
h[0] = l[0] = h[n + 1] = r[n + 1] = 0;
for (int i = 1; i <= n; i++) {
l[i] = min(l[i - 1] + 1, h[i]);
}
for (int i = n; i >= 1; i--) {
r[i] = min(r[i + 1] + 1, h[i]);
}
int ans = 0;
for (int i = 1; i <= n; i++) {
ans = max(ans, min(r[i], l[i]));
}
cout << ans << endl;
}
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Given the number n, find the smallest positive integer which has exactly n divisors. It is guaranteed that for the given n the answer will not exceed 1018.
Input
The first line of the input contains integer n (1 β€ n β€ 1000).
Output
Output the smallest positive integer with exactly n divisors.
Examples
Input
4
Output
6
Input
6
Output
12
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int prime[16] = {2, 3, 5, 7, 11, 13, 17, 19,
23, 29, 31, 37, 41, 43, 47, 53};
const int lmlog[16] = {59, 37, 25, 21, 17, 16, 14, 14,
13, 12, 12, 11, 11, 11, 10, 10};
const int maxN = 1000;
const unsigned long long oo = 1000000000000000001;
int n;
unsigned long long ppow[16][60];
unsigned long long f[maxN + 1][17];
int main() {
cin >> n;
int i, j, k;
for (i = 0; i < 16; ++i) {
ppow[i][0] = 1;
for (j = 1; j <= lmlog[i]; ++j) ppow[i][j] = ppow[i][j - 1] * prime[i];
}
for (i = 1; i <= n; ++i) f[i][0] = oo;
for (i = 0; i <= 16; ++i) f[1][i] = 1;
for (j = 1; j <= 16; ++j)
for (i = 2; i <= n; ++i) {
f[i][j] = f[i][j - 1];
for (k = 1; k < lmlog[j - 1]; ++k)
if (i % (k + 1) == 0 && f[i / (k + 1)][j - 1] < oo &&
f[i / (k + 1)][j - 1] < oo / ppow[j - 1][k])
f[i][j] = min(f[i][j], f[i / (k + 1)][j - 1] * ppow[j - 1][k]);
}
cout << f[n][16];
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse!
There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful.
Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.
Input
The first line of the input contains the number of countries n (1 β€ n β€ 100 000). The second line contains n non-negative integers ai without leading zeroes β the number of tanks of the i-th country.
It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000.
Output
Print a single number without leading zeroes β the product of the number of tanks presented by each country.
Examples
Input
3
5 10 1
Output
50
Input
4
1 1 10 11
Output
110
Input
5
0 3 1 100 1
Output
0
Note
In sample 1 numbers 10 and 1 are beautiful, number 5 is not not.
In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful.
In sample 3 number 3 is not beautiful, all others are beautiful.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, y, s = 0, j = 0, k = 0;
vector<int> T;
cin >> n;
string m;
string mot = "";
while (j < n) {
cin >> m;
if (m == "0") {
cout << 0;
return 0;
}
for (int i = 0; i < m.size(); i++) {
if (m[i] == '0') s++;
}
if ((s == m.size() - 1) && (m[0] == '1')) {
k += s;
} else {
mot = m;
}
s = 0;
j++;
}
if (mot != "") {
cout << mot;
} else
cout << 1;
for (int i = 1; i <= k; i++) {
cout << '0';
}
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
You are visiting a large electronics store to buy a refrigerator and a microwave.
The store sells A kinds of refrigerators and B kinds of microwaves. The i-th refrigerator ( 1 \le i \le A ) is sold at a_i yen (the currency of Japan), and the j-th microwave ( 1 \le j \le B ) is sold at b_j yen.
You have M discount tickets. With the i-th ticket ( 1 \le i \le M ), you can get a discount of c_i yen from the total price when buying the x_i-th refrigerator and the y_i-th microwave together. Only one ticket can be used at a time.
You are planning to buy one refrigerator and one microwave. Find the minimum amount of money required.
Constraints
* All values in input are integers.
* 1 \le A \le 10^5
* 1 \le B \le 10^5
* 1 \le M \le 10^5
* 1 \le a_i , b_i , c_i \le 10^5
* 1 \le x_i \le A
* 1 \le y_i \le B
* c_i \le a_{x_i} + b_{y_i}
Input
Input is given from Standard Input in the following format:
A B M
a_1 a_2 ... a_A
b_1 b_2 ... b_B
x_1 y_1 c_1
\vdots
x_M y_M c_M
Output
Print the answer.
Examples
Input
2 3 1
3 3
3 3 3
1 2 1
Output
5
Input
1 1 2
10
10
1 1 5
1 1 10
Output
10
Input
2 2 1
3 5
3 5
2 2 2
Output
6
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int A, B, M;
cin >> A >> B >> M;
vector<int> a(A), b(B);
for (auto &x : a) cin >> x;
for (auto &x : b) cin >> x;
int ans = 1e9;
for (int i = 0, x, y, c; cin >> x >> y >> c; i++)
ans = min(ans, a.at(--x) + b.at(--y) - c);
sort(a.begin(), a.end());
sort(b.begin(), b.end());
cout << min(ans, a.at(0) + b.at(0)) << "\n";
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice!
Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to play a simple game. All n people who came to the barbecue sat in a circle (thus each person received a unique index bi from 0 to n - 1). The person number 0 started the game (this time it was Vasya). All turns in the game were numbered by integers starting from 1. If the j-th turn was made by the person with index bi, then this person acted like that:
1. he pointed at the person with index (bi + 1) mod n either with an elbow or with a nod (x mod y is the remainder after dividing x by y);
2. if j β₯ 4 and the players who had turns number j - 1, j - 2, j - 3, made during their turns the same moves as player bi on the current turn, then he had drunk a glass of juice;
3. the turn went to person number (bi + 1) mod n.
The person who was pointed on the last turn did not make any actions.
The problem was, Vasya's drunk too much juice and can't remember the goal of the game. However, Vasya's got the recorded sequence of all the participants' actions (including himself). Now Vasya wants to find out the maximum amount of juice he could drink if he played optimally well (the other players' actions do not change). Help him.
You can assume that in any scenario, there is enough juice for everybody.
Input
The first line contains a single integer n (4 β€ n β€ 2000) β the number of participants in the game. The second line describes the actual game: the i-th character of this line equals 'a', if the participant who moved i-th pointed at the next person with his elbow, and 'b', if the participant pointed with a nod. The game continued for at least 1 and at most 2000 turns.
Output
Print a single integer β the number of glasses of juice Vasya could have drunk if he had played optimally well.
Examples
Input
4
abbba
Output
1
Input
4
abbab
Output
0
Note
In both samples Vasya has got two turns β 1 and 5. In the first sample, Vasya could have drunk a glass of juice during the fifth turn if he had pointed at the next person with a nod. In this case, the sequence of moves would look like "abbbb". In the second sample Vasya wouldn't drink a single glass of juice as the moves performed during turns 3 and 4 are different.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int i, j, k, n, m, x, y, z, l, now, sum;
char ch[3000], c;
int main() {
scanf("%d", &n);
scanf("%s", &ch);
l = strlen(ch);
now = 0;
sum = 0;
for (i = 0; i < l; i++) {
if (now == 0) {
if (i >= 3) {
c = ch[i - 1];
if ((ch[i - 2] == c) && (ch[i - 3] == c)) sum++;
ch[i] = c;
}
}
now++;
now = now % n;
}
printf("%d", sum);
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Dima and Anya love playing different games. Now Dima has imagined a new game that he wants to play with Anya.
Dima writes n pairs of integers on a piece of paper (li, ri) (1 β€ li < ri β€ p). Then players take turns. On his turn the player can do the following actions:
1. choose the number of the pair i (1 β€ i β€ n), such that ri - li > 2;
2. replace pair number i by pair <image> or by pair <image>. Notation βxβ means rounding down to the closest integer.
The player who can't make a move loses.
Of course, Dima wants Anya, who will move first, to win. That's why Dima should write out such n pairs of integers (li, ri) (1 β€ li < ri β€ p), that if both players play optimally well, the first one wins. Count the number of ways in which Dima can do it. Print the remainder after dividing the answer by number 1000000007 (109 + 7).
Two ways are considered distinct, if the ordered sequences of the written pairs are distinct.
Input
The first line contains two integers n, p (1 β€ n β€ 1000, 1 β€ p β€ 109). The numbers are separated by a single space.
Output
In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7).
Examples
Input
2 2
Output
0
Input
4 4
Output
520
Input
100 1000
Output
269568947
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int gi() {
int w = 0;
bool q = 1;
char c = getchar();
while ((c < '0' || c > '9') && c != '-') c = getchar();
if (c == '-') q = 0, c = getchar();
while (c >= '0' && c <= '9') w = w * 10 + c - '0', c = getchar();
return q ? w : -w;
}
const int N = 1e5;
const int lim = 1e9;
int L[N], R[N], sg[N];
inline void init() {
int m = 1, a = 1, b = 1;
L[1] = 1, R[1] = 2;
while (R[m] < lim) {
while (R[a] * 3 + 2 <= R[m]) a++;
while (R[b] / 2 * 3 + (R[b] & 1) <= R[m]) b++;
L[m + 1] = R[m] + 1;
R[++m] = min(R[a] * 3 + 2, R[b] / 2 * 3 + (R[b] & 1));
if (!sg[a] || !sg[b]) sg[m] = 1 + (sg[a] == 1 || sg[b] == 1);
if (sg[m] == sg[m - 1]) R[m - 1] = R[m], m--;
}
L[m + 1] = 1 << 30;
}
int main() {
init();
const int mod = 1e9 + 7;
int n = gi(), p = gi(), i, t, s[3] = {}, f[4] = {}, g[4] = {};
for (i = 1; L[i] < p; i++) {
t = min(R[i], p - 1);
s[sg[i]] = (s[sg[i]] + 1LL * (t - L[i] + 1) * (p - L[i] + p - t) / 2) % mod;
}
for (i = 0; i < 3; i++)
if (s[i] < 0) s[i] += mod;
f[0] = 1;
while (n--) {
for (i = 0; i < 4; i++) g[i] = f[i], f[i] = 0;
for (i = 0; i < 4; i++)
for (t = 0; t < 3; t++) f[i ^ t] = (f[i ^ t] + 1LL * g[i] * s[t]) % mod;
}
printf("%d\n", ((f[1] + f[2]) % mod + f[3]) % mod);
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.
But wait, something is still known, because that day a record was achieved β M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him.
Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that:
* the number of different users online did not exceed M at any moment,
* at some second the number of distinct users online reached value M,
* the total number of users (the number of distinct identifiers) was as much as possible.
Help Polycarpus cope with the test.
Input
The first line contains three integers n, M and T (1 β€ n, M β€ 20 000, 1 β€ T β€ 86400) β the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59).
Output
In the first line print number R β the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes).
Examples
Input
4 2 10
17:05:53
17:05:58
17:06:01
22:39:47
Output
3
1
2
2
3
Input
1 2 86400
00:00:00
Output
No solution
Note
Consider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 β from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 β from 22:39:47 to 22:39:56.
In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.)
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename T1, typename T2>
ostream& operator<<(ostream& os, const pair<T1, T2>& p) {
os << "(" << p.first << ", " << p.second << ")";
return os;
}
template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
os << "{";
for (int i = 0; i < v.size(); i++)
os << v[i] << (i + 1 < v.size() ? ", " : "");
os << "}";
return os;
}
class range {
struct Iterator {
int val, inc;
int operator*() { return val; }
bool operator!=(Iterator& rhs) { return val < rhs.val; }
void operator++() { val += inc; }
};
Iterator i, n;
public:
range(int e) : i({0, 1}), n({e, 1}) {}
range(int b, int e) : i({b, 1}), n({e, 1}) {}
range(int b, int e, int inc) : i({b, inc}), n({e, inc}) {}
Iterator& begin() { return i; }
Iterator& end() { return n; }
};
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
inline bool valid(int x, int w) { return 0 <= x && x < w; }
void iostream_init() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.setf(ios::fixed);
cout.precision(12);
}
int time(string s) {
for (char& c : s)
if (c == ':') c = ' ';
stringstream ss(s);
int h, m, c;
ss >> h >> m >> c;
return 60 * 60 * h + 60 * m + c;
}
int main() {
iostream_init();
int N, M, T;
while (cin >> N >> M >> T) {
vector<int> t(N);
for (int i = 0; i < (int)(N); ++i) {
string s;
cin >> s;
t[i] = time(s);
}
vector<int> b, e;
{
int last = 0;
for (int i = 0; i < (int)(N); ++i) {
bool update = false;
while (last < N && t[last] < t[i] + T) {
update = true;
last++;
}
if (update) {
b.push_back(i);
e.push_back(last);
}
}
}
int L = b.size();
bool exist = false;
for (int i = 0; i < (int)(L); ++i)
if (e[i] - b[i] >= M) exist = true;
if (!exist) {
cout << "No solution" << endl;
continue;
}
vector<int> ans(N);
int last = 0;
int start = 0;
vector<int> cnt(L);
for (int i = 0; i < N; i++) {
bool add_ok = true;
while (start < L && e[start] <= i) start++;
for (int j = start; j < L; j++) {
if (i < b[j]) break;
if (cnt[j] == M) add_ok = false;
}
if (add_ok) {
ans[i] = ++last;
for (int j = start; j < L; j++) {
if (i < b[j]) break;
cnt[j]++;
}
} else {
ans[i] = last;
for (int j = start; j < L; j++) {
if (i < b[j]) break;
if (b[j] == i) cnt[j]++;
}
}
}
cout << last << endl;
for (int i = 0; i < (int)(N); ++i) cout << ans[i] << endl;
}
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
You are given several queries. In the i-th query you are given a single positive integer ni. You are to represent ni as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings.
An integer greater than 1 is composite, if it is not prime, i.e. if it has positive divisors not equal to 1 and the integer itself.
Input
The first line contains single integer q (1 β€ q β€ 105) β the number of queries.
q lines follow. The (i + 1)-th line contains single integer ni (1 β€ ni β€ 109) β the i-th query.
Output
For each query print the maximum possible number of summands in a valid splitting to composite summands, or -1, if there are no such splittings.
Examples
Input
1
12
Output
3
Input
2
6
8
Output
1
2
Input
3
1
2
3
Output
-1
-1
-1
Note
12 = 4 + 4 + 4 = 4 + 8 = 6 + 6 = 12, but the first splitting has the maximum possible number of summands.
8 = 4 + 4, 6 can't be split into several composite summands.
1, 2, 3 are less than any composite number, so they do not have valid splittings.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long maxn = 1e5 + 1, msiz = 2, mod = 1e9 + 7, inf = 1e18;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int q;
cin >> q;
for (int i = 1; i <= q; i++) {
int x;
cin >> x;
if (x < 3)
cout << -1;
else if (x % 2 == 0)
cout << x / 4;
else if (x % 4 == 1) {
if (x == 5)
cout << -1;
else
cout << x / 4 - 1;
} else {
if (x < 12)
cout << -1;
else
cout << x / 4 - 1;
}
cout << endl;
}
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Anton likes to play chess, and so does his friend Danik.
Once they have played n games in a row. For each game it's known who was the winner β Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of games played.
The second line contains a string s, consisting of n uppercase English letters 'A' and 'D' β the outcome of each of the games. The i-th character of the string is equal to 'A' if the Anton won the i-th game and 'D' if Danik won the i-th game.
Output
If Anton won more games than Danik, print "Anton" (without quotes) in the only line of the output.
If Danik won more games than Anton, print "Danik" (without quotes) in the only line of the output.
If Anton and Danik won the same number of games, print "Friendship" (without quotes).
Examples
Input
6
ADAAAA
Output
Anton
Input
7
DDDAADA
Output
Danik
Input
6
DADADA
Output
Friendship
Note
In the first sample, Anton won 6 games, while Danik β only 1. Hence, the answer is "Anton".
In the second sample, Anton won 3 games and Danik won 4 games, so the answer is "Danik".
In the third sample, both Anton and Danik won 3 games and the answer is "Friendship".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int game, a = 0, d = 0;
cin >> game;
string x;
cin >> x;
for (int i = 0; i < x.size(); i++) {
x[i] == 'D' ? d++ : a++;
}
if (a > d)
cout << "Anton";
else if (d > a)
cout << "Danik";
else
cout << "Friendship";
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
The GCD table G of size n Γ n for an array of positive integers a of length n is defined by formula
<image>
Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as <image>. For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows:
<image>
Given all the numbers of the GCD table G, restore array a.
Input
The first line contains number n (1 β€ n β€ 500) β the length of array a. The second line contains n2 space-separated numbers β the elements of the GCD table of G for array a.
All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
Output
In the single line print n positive integers β the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
Examples
Input
4
2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2
Output
4 3 6 2
Input
1
42
Output
42
Input
2
1 1 1 1
Output
1 1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int val[1000111];
map<int, int> f;
vector<int> luu;
int gcd(int x, int y) {
while (y > 0) {
x %= y;
swap(x, y);
}
return x;
}
int main() {
int n;
scanf("%d", &n);
for (int i = (1), _b = (n * n); i <= _b; ++i) {
scanf("%d", &val[i]);
f[val[i]]++;
}
sort(val + 1, val + n * n + 1);
int m = 0;
for (int i = (n * n), _b = (1); i >= _b; --i) {
if (f[val[i]] > 0) {
f[val[i]]--;
for (int j = 0, _b = (luu.size()); j < _b; ++j)
f[gcd(val[i], luu[j])] -= 2;
luu.push_back(val[i]);
}
}
for (int i = 0, _b = (luu.size()); i < _b; ++i) printf("%d ", luu[i]);
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Consider the following process. You have a binary string (a string where each character is either 0 or 1) w of length n and an integer x. You build a new binary string s consisting of n characters. The i-th character of s is chosen as follows:
* if the character w_{i-x} exists and is equal to 1, then s_i is 1 (formally, if i > x and w_{i-x} = 1, then s_i = 1);
* if the character w_{i+x} exists and is equal to 1, then s_i is 1 (formally, if i + x β€ n and w_{i+x} = 1, then s_i = 1);
* if both of the aforementioned conditions are false, then s_i is 0.
You are given the integer x and the resulting string s. Reconstruct the original string w.
Input
The first line contains one integer t (1 β€ t β€ 1000) β the number of test cases.
Each test case consists of two lines. The first line contains the resulting string s (2 β€ |s| β€ 10^5, each character of s is either 0 or 1). The second line contains one integer x (1 β€ x β€ |s| - 1).
The total length of all strings s in the input does not exceed 10^5.
Output
For each test case, print the answer on a separate line as follows:
* if no string w can produce the string s at the end of the process, print -1;
* otherwise, print the binary string w consisting of |s| characters. If there are multiple answers, print any of them.
Example
Input
3
101110
2
01
1
110
1
Output
111011
10
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const double PI = 3.141592653589793238463;
const long long int MOD = 1000000007;
list<long long> ls;
vector<long long> v, v1, v2, vv;
set<long long> s;
map<long long, long long> mp;
stack<char> st;
stack<long long> sti;
inline long long fp(long long bs, long long pw) {
long long res = 1;
while (pw > 0) {
if (pw % 2 == 1) {
res = (res * bs) % MOD;
}
bs = (bs * bs) % MOD;
pw = pw / 2;
}
return res;
}
long long pp(long long bs, unsigned long long pw) {
long long ans = 1;
while (pw > 0) {
if (pw & 1) ans = ans * bs;
pw = pw >> 1;
bs = bs * bs;
}
return ans;
}
bool ff22(const pair<long long, long long> &a,
const pair<long long, long long> &b) {
return (a.second < b.second);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long t, n, m, k, h, p, i, j, a, b, c, x, V, ind, sz,
ans = 0, ans2, mx, sum = 0, ct = 0, ti, q, temp, t2, mn, ptr, ct1, ct2,
cc, ln, diff;
double kh = 4;
bool fl;
string s, sub, sorted, anss;
cin >> t;
while (t--) {
ct = 0;
cin >> s;
n = s.length();
sub = "";
for (i = 0; i < n; i++) sub.push_back('1');
cin >> x;
for (i = 0; i < n; i++) {
long long ms = i - x;
long long pl = i + x;
if (s[i] == '0') {
if (ms >= 0) {
sub[ms] = '0';
}
if (pl < n) {
sub[pl] = '0';
}
}
}
for (i = 0; i < n; i++) {
long long ms = i - x;
long long pl = i + x;
if (s[i] == '1') {
if ((ms >= 0 && sub[ms] == '1') || (pl < n && sub[pl] == '1'))
continue;
else {
ct++;
break;
}
} else {
if ((ms >= 0 && sub[ms] == '1') || (pl < n && sub[pl] == '1')) {
ct++;
break;
}
}
}
if (ct > 0)
cout << -1 << endl;
else
cout << sub << endl;
}
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a) to the end of a. For example, <image>.
* Remove the first character of a. For example, <image>. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Input
The first line contains the string a and the second line contains the string b (1 β€ |a|, |b| β€ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
Output
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
Examples
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
Note
In the first sample, the steps are as follows: 01011 β 1011 β 011 β 0110
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
string a, b;
int ans[2];
void dfs(string s, int pos) {
cout << s << " " << pos << endl;
if (s == "0") {
ans[pos] |= 1;
return;
}
if (s == "1") {
ans[pos] |= 2;
return;
}
dfs(s.substr(1), pos);
int ct = count(s.begin(), s.end(), '1');
if (ct % 2 == 0) dfs(s.substr(0, s.length() - 1), pos);
}
int main() {
cin >> a >> b;
int ac = count(a.begin(), a.end(), '1');
int bc = count(b.begin(), b.end(), '1');
if (ac % 2) {
ac++;
}
if (ac >= bc)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular (shortly, RBS) if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are RBS and ")(" and "(()" are not.
We can see that each opening bracket in RBS is paired with some closing bracket, and, using this fact, we can define nesting depth of the RBS as maximum number of bracket pairs, such that the 2-nd pair lies inside the 1-st one, the 3-rd one β inside the 2-nd one and so on. For example, nesting depth of "" is 0, "()()()" is 1 and "()((())())" is 3.
Now, you are given RBS s of even length n. You should color each bracket of s into one of two colors: red or blue. Bracket sequence r, consisting only of red brackets, should be RBS, and bracket sequence, consisting only of blue brackets b, should be RBS. Any of them can be empty. You are not allowed to reorder characters in s, r or b. No brackets can be left uncolored.
Among all possible variants you should choose one that minimizes maximum of r's and b's nesting depth. If there are multiple solutions you can print any of them.
Input
The first line contains an even integer n (2 β€ n β€ 2 β
10^5) β the length of RBS s.
The second line contains regular bracket sequence s (|s| = n, s_i β \{"(", ")"\}).
Output
Print single string t of length n consisting of "0"-s and "1"-s. If t_i is equal to 0 then character s_i belongs to RBS r, otherwise s_i belongs to b.
Examples
Input
2
()
Output
11
Input
4
(())
Output
0101
Input
10
((()())())
Output
0110001111
Note
In the first example one of optimal solutions is s = "\color{blue}{()}". r is empty and b = "()". The answer is max(0, 1) = 1.
In the second example it's optimal to make s = "\color{red}{(}\color{blue}{(}\color{red}{)}\color{blue}{)}". r = b = "()" and the answer is 1.
In the third example we can make s = "\color{red}{(}\color{blue}{((}\color{red}{)()}\color{blue}{)())}". r = "()()" and b = "(()())" and the answer is 2.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int t, n, m, i, j;
string str;
cin >> n;
cin >> str;
stack<int> s;
int arr[n];
j = 0;
for (i = 0; i < n; i++) {
if (str[i] == '(') {
if (s.empty()) {
s.push(i);
arr[i] = 0;
} else {
arr[i] = (arr[s.top()] + 1) % 2;
s.push(i);
}
} else {
arr[i] = arr[s.top()];
s.pop();
}
}
for (i = 0; i < n; i++) cout << arr[i];
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Three planets X, Y and Z within the Alpha planetary system are inhabited with an advanced civilization. The spaceports of these planets are connected by interplanetary space shuttles. The flight scheduler should decide between 1, 2 and 3 return flights for every existing space shuttle connection. Since the residents of Alpha are strong opponents of the symmetry, there is a strict rule that any two of the spaceports connected by a shuttle must have a different number of flights.
For every pair of connected spaceports, your goal is to propose a number 1, 2 or 3 for each shuttle flight, so that for every two connected spaceports the overall number of flights differs.
You may assume that:
1) Every planet has at least one spaceport
2) There exist only shuttle flights between spaceports of different planets
3) For every two spaceports there is a series of shuttle flights enabling traveling between them
4) Spaceports are not connected by more than one shuttle
Input
The first row of the input is the integer number N (3 β€ N β€ 100 000), representing overall number of spaceports. The second row is the integer number M (2 β€ M β€ 100 000) representing number of shuttle flight connections.
Third row contains N characters from the set \\{X, Y, Z\}. Letter on I^{th} position indicates on which planet is situated spaceport I. For example, "XYYXZZ" indicates that the spaceports 0 and 3 are located at planet X, spaceports 1 and 2 are located at Y, and spaceports 4 and 5 are at Z.
Starting from the fourth row, every row contains two integer numbers separated by a whitespace. These numbers are natural numbers smaller than N and indicate the numbers of the spaceports that are connected. For example, "12\ 15" indicates that there is a shuttle flight between spaceports 12 and 15.
Output
The same representation of shuttle flights in separate rows as in the input, but also containing a third number from the set \{1, 2, 3\} standing for the number of shuttle flights between these spaceports.
Example
Input
10
15
XXXXYYYZZZ
0 4
0 5
0 6
4 1
4 8
1 7
1 9
7 2
7 5
5 3
6 2
6 9
8 2
8 3
9 3
Output
0 4 2
0 5 2
0 6 2
4 1 1
4 8 1
1 7 2
1 9 3
7 2 2
7 5 1
5 3 1
6 2 1
6 9 1
8 2 3
8 3 1
9 3 1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int N = 100100;
int n, m;
int ed[N][3];
vector<int> g[N];
char t[N];
int h[N];
int par[N];
int col[N];
bool used[N];
void printAns() {
for (int i = 0; i < m; i++) {
int x = ed[i][2];
x %= 3;
while (x <= 0) x += 3;
printf("%d %d %d\n", ed[i][0], ed[i][1], x);
}
exit(0);
}
int getOther(int id, int v) { return ed[id][0] ^ ed[id][1] ^ v; }
void dfsSolve(int v) {
for (int id : g[v]) {
int u = getOther(id, v);
if (used[u]) continue;
used[u] = true;
dfsSolve(u);
ed[id][2] = col[u];
col[u] -= ed[id][2];
col[v] -= ed[id][2];
if (col[v] < 0) col[v] += 3;
}
}
void solveOdd(int id) {
int v = ed[id][0], u = ed[id][1];
if (h[v] < h[u]) swap(v, u);
vector<pair<int, int> > cyc;
while (v != u) {
cyc.push_back(make_pair(v, par[v]));
v = getOther(par[v], v);
}
cyc.push_back(make_pair(u, id));
int sz = (int)cyc.size();
for (int i = 0; i < sz; i++) {
42;
}
for (int i = 0; i < n; i++) col[i] = (int)(t[i] - 'X');
for (int i = 0; i < sz; i++) used[cyc[i].first] = true;
for (int i = 0; i < sz; i++) dfsSolve(cyc[i].first);
int sum = 0;
for (int i = 0; i < sz; i++) sum += col[cyc[i].first];
if (sum & 1) sum += 3;
sum /= 2;
for (int i = 2; i < sz; i += 2) sum -= col[cyc[i].first];
sum %= 3;
if (sum < 0) sum += 3;
ed[cyc[0].second][2] = sum;
for (int i = 1; i < sz; i++) {
int x = col[cyc[i].first] - ed[cyc[i - 1].second][2];
if (x < 0) x += 3;
ed[cyc[i].second][2] = x;
}
printAns();
}
void solveEven(int id) {
int v = ed[id][0], u = ed[id][1];
if (h[v] < h[u]) swap(v, u);
vector<pair<int, int> > cyc;
while (v != u) {
cyc.push_back(make_pair(v, par[v]));
v = getOther(par[v], v);
}
cyc.push_back(make_pair(u, id));
int sz = (int)cyc.size();
for (int i = 0; i < n; i++) col[i] = h[i] & 1;
if (col[cyc[0].first] == 1) rotate(cyc.begin(), cyc.begin() + 1, cyc.end());
for (int i = 0; i < sz; i++) used[cyc[i].first] = true;
for (int i = 0; i < sz; i++) dfsSolve(cyc[i].first);
int bal = 0;
for (int i = 0; i < sz; i++) {
int x = col[cyc[i].first];
if (i % 2 == 0)
bal += x;
else
bal -= x;
}
bal %= 3;
if (bal < 0) bal += 3;
if (bal == 1) {
int v = cyc[0].first;
col[v]--;
if (col[v] < 0) col[v] += 3;
} else if (bal == 2) {
for (int i = 0; i < 3; i += 2) {
int v = cyc[i].first;
col[v]--;
if (col[v] < 0) col[v] += 3;
}
}
for (int i = 1; i < sz; i++) {
int x = col[cyc[i].first] - ed[cyc[i - 1].second][2];
if (x < 0) x += 3;
ed[cyc[i].second][2] = x;
}
printAns();
}
void dfs1(int v) {
for (int id : g[v]) {
int u = getOther(id, v);
if (h[u] == -1) {
h[u] = h[v] + 1;
par[u] = id;
dfs1(u);
} else if (h[v] % 2 == h[u] % 2) {
solveOdd(id);
}
}
}
int main() {
scanf("%d%d", &n, &m);
scanf("%s", t);
for (int i = 0; i < m; i++) {
for (int j = 0; j < 2; j++) {
scanf("%d", &ed[i][j]);
g[ed[i][j]].push_back(i);
}
}
for (int i = 0; i < n; i++) h[i] = -1;
for (int i = 0; i < n; i++) {
if ((int)g[i].size() == 1) {
for (int j = 0; j < n; j++) col[j] = (int)(t[j] - 'X');
dfsSolve(i);
printAns();
}
}
h[0] = 0;
dfs1(0);
for (int v = 0; v < n; v++) {
for (int id : g[v]) {
if (par[v] == id) continue;
int u = getOther(id, v);
if (h[u] < h[v]) solveEven(id);
}
}
throw;
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
The finalists of the "Russian Code Cup" competition in 2214 will be the participants who win in one of the elimination rounds.
The elimination rounds are divided into main and additional. Each of the main elimination rounds consists of c problems, the winners of the round are the first n people in the rating list. Each of the additional elimination rounds consists of d problems. The winner of the additional round is one person. Besides, k winners of the past finals are invited to the finals without elimination.
As a result of all elimination rounds at least nΒ·m people should go to the finals. You need to organize elimination rounds in such a way, that at least nΒ·m people go to the finals, and the total amount of used problems in all rounds is as small as possible.
Input
The first line contains two integers c and d (1 β€ c, d β€ 100) β the number of problems in the main and additional rounds, correspondingly. The second line contains two integers n and m (1 β€ n, m β€ 100). Finally, the third line contains an integer k (1 β€ k β€ 100) β the number of the pre-chosen winners.
Output
In the first line, print a single integer β the minimum number of problems the jury needs to prepare.
Examples
Input
1 10
7 2
1
Output
2
Input
2 2
2 1
2
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5, inf = 0x3f3f3f3f, mod = 1000000007;
void read() {}
template <typename T, typename... T2>
inline void read(T &x, T2 &...oth) {
x = 0;
int ch = getchar(), f = 0;
while (ch < '0' || ch > '9') {
if (ch == '-') f = 1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = (x << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
if (f) x = -x;
read(oth...);
}
int dp[maxn];
int main() {
std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int c, d, n, m, k;
cin >> c >> d >> n >> m >> k;
for (int i = 1; i < n; i++) dp[i] = min(c, i * d);
for (int i = n; i <= n * m - k; i++)
dp[i] = min(dp[i - n] + c, dp[i - 1] + d);
cout << dp[n * m - k] << endl;
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Spongebob is already tired trying to reason his weird actions and calculations, so he simply asked you to find all pairs of n and m, such that there are exactly x distinct squares in the table consisting of n rows and m columns. For example, in a 3 Γ 5 table there are 15 squares with side one, 8 squares with side two and 3 squares with side three. The total number of distinct squares in a 3 Γ 5 table is 15 + 8 + 3 = 26.
Input
The first line of the input contains a single integer x (1 β€ x β€ 1018) β the number of squares inside the tables Spongebob is interested in.
Output
First print a single integer k β the number of tables with exactly x distinct squares inside.
Then print k pairs of integers describing the tables. Print the pairs in the order of increasing n, and in case of equality β in the order of increasing m.
Examples
Input
26
Output
6
1 26
2 9
3 5
5 3
9 2
26 1
Input
2
Output
2
1 2
2 1
Input
8
Output
4
1 8
2 3
3 2
8 1
Note
In a 1 Γ 2 table there are 2 1 Γ 1 squares. So, 2 distinct squares in total.
<image>
In a 2 Γ 3 table there are 6 1 Γ 1 squares and 2 2 Γ 2 squares. That is equal to 8 squares in total.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int dx[] = {0, 0, +1, -1};
int dy[] = {+1, -1, 0, 0};
int dxx[] = {+1, 0, -1, 0, +1, +1, -1, -1};
int dyy[] = {0, +1, 0, -1, +1, -1, +1, -1};
inline bool EQ(double a, double b) { return fabs(a - b) < 1e-9; }
vector<pair<long long, long long> > ans;
int main() {
long long x, i, sz = 0, l, y;
scanf("%lld", &x);
l = min(x, 10000000LL);
for (i = 1; i <= l; i++) {
y = x * 6LL;
if (y % i) continue;
y /= i;
if (y % (i + 1)) continue;
y /= (i + 1);
y += (i - 1);
if (y % 3) continue;
y /= 3;
if (y < i) continue;
ans.push_back(make_pair(i, y));
if (i == y)
sz++;
else
sz += 2;
}
printf("%lld\n", sz);
for (i = 0; i < ans.size(); i++)
printf("%lld %lld\n", ans[i].first, ans[i].second);
for (i = ans.size() - 1; ~i; i--)
if (ans[i].first != ans[i].second)
printf("%lld %lld\n", ans[i].second, ans[i].first);
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.
The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.
Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.
If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
Input
The first line of input contains n β a positive integer number without leading zeroes (1 β€ n < 10100000).
Output
Print one number β any beautiful number obtained by erasing as few as possible digits. If there is no answer, print - 1.
Examples
Input
1033
Output
33
Input
10
Output
0
Input
11
Output
-1
Note
In the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline long long ma(long long a, long long b) { return ((a - b > 0) ? a : b); }
inline long long mi(long long a, long long b) { return ((a - b > 0) ? b : a); }
long long dp[200005], ar[200005];
vector<long long> v;
inline long long solve(long long id, long long cnt, string &s, string &s2) {
vector<long long> v;
string s1;
for (long long(i) = (s.size() - 1); (i) >= (0); (i)--) {
if (v.size() >= cnt) break;
if ((s[i] - '0') % 3 == id) v.push_back(i);
}
for (long long(i) = (0); (i) < (s.size()); (i)++) {
long long flag = 0;
for (long long(j) = (0); (j) < (v.size()); (j)++) {
if (i == v[j]) flag = 1;
}
if (flag == 0) s1 += s[i];
}
long long flag = 0;
id = -1;
for (long long(i) = (0); (i) < (s1.size()); (i)++) {
if ((s1[i] - '0') != 0) {
id = i;
flag = 1;
break;
}
}
if (v.size() != 0 && v.size() == cnt) {
if (flag == 0) s1.size() != 0 ? s2 += '0' : s2;
if (flag == 1)
for (long long(i) = (id); (i) < (s1.size()); (i)++) s2 += s1[i];
}
return s2.size();
}
int main() {
string s, s1, s2, s3;
cin >> s;
for (long long(i) = (0); (i) < (s.size()); (i)++) dp[(s[i] - '0') % 3]++;
long long a = dp[1] % 3, b = dp[2] % 3;
long long id, cnt;
if (a == 0) {
if (b == 0) cout << s << endl;
if (b == 1) {
long long ta1 = solve(2, 1, s, s1), ta2 = solve(1, 2, s, s2);
(ta1 > ta2) ? s3 = s1 : s3 = s2;
(s3.size() != 0) ? cout << s3 << "\n" : cout << -1 << "\n";
}
if (b == 2) {
long long ta1 = solve(2, 2, s, s1), ta2 = solve(1, 1, s, s2);
(ta1 > ta2) ? s3 = s1 : s3 = s2;
(s3.size() != 0) ? cout << s3 << "\n" : cout << -1 << "\n";
}
}
if (a == 1) {
if (b == 1) cout << s << endl;
if (b == 0) {
long long ta1 = solve(1, 1, s, s1), ta2 = solve(2, 2, s, s2);
(ta1 > ta2) ? s3 = s1 : s3 = s2;
(s3.size() != 0) ? cout << s3 << "\n" : cout << -1 << "\n";
}
if (b == 2) {
long long ta1 = solve(2, 1, s, s1), ta2 = solve(1, 2, s, s2);
(ta1 > ta2) ? s3 = s1 : s3 = s2;
(s3.size() != 0) ? cout << s3 << "\n" : cout << -1 << "\n";
}
}
if (a == 2) {
if (b == 0) {
long long ta1 = solve(1, 2, s, s1), ta2 = solve(2, 1, s, s2);
(ta1 > ta2) ? s3 = s1 : s3 = s2;
(s3.size() != 0) ? cout << s3 << "\n" : cout << -1 << "\n";
}
if (b == 1) {
long long ta1 = solve(1, 1, s, s1), ta2 = solve(2, 2, s, s2);
(ta1 > ta2) ? s3 = s1 : s3 = s2;
(s3.size() != 0) ? cout << s3 << "\n" : cout << -1 << "\n";
}
if (b == 2) cout << s << endl;
}
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.
Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti:
* If Petya has visited this room before, he writes down the minute he was in this room last time;
* Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i.
Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0.
At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook?
Input
The first line contains a single integer n (1 β€ n β€ 2Β·105) β then number of notes in Petya's logbook.
The second line contains n non-negative integers t1, t2, ..., tn (0 β€ ti < i) β notes in the logbook.
Output
In the only line print a single integer β the minimum possible number of rooms in Paris catacombs.
Examples
Input
2
0 0
Output
2
Input
5
0 1 0 1 3
Output
3
Note
In the first sample, sequence of rooms Petya visited could be, for example 1 β 1 β 2, 1 β 2 β 1 or 1 β 2 β 3. The minimum possible number of rooms is 2.
In the second sample, the sequence could be 1 β 2 β 3 β 1 β 2 β 1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long inf = 1e18;
const long long mod = 1e9 + 7;
const long long N = 2e5 + 5;
long long a[N], s[N] = {0}, pos[N] = {0};
long long n, cnt = 1;
vector<long long> ans;
int main() {
ios_base::sync_with_stdio(false);
cin >> n;
for (long long i = 0; i < (n); ++i) cin >> a[i + 1];
for (int i = n; i > 0; i--) s[a[i]]++;
pos[0] = 1;
for (int i = 1; i <= n; i++) {
s[a[i]]--;
if (pos[a[i]]) {
if (s[a[i]] == 0) {
ans.push_back(pos[a[i]]);
pos[i] = pos[a[i]];
pos[a[i]] = 0;
continue;
}
}
cnt++;
ans.push_back(cnt);
pos[i] = cnt;
}
cout << cnt << endl;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 β€ N β€ 10^4) - number of airports/factories, and M (1 β€ M β€ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 β€ u,v β€ N), d (1 β€ d β€ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long inf = 0x3f3f3f3f3f3f3f3f;
class BPGraph {
public:
long long n;
long long m;
vector<long long> *adj;
long long *pair_left;
long long *pair_right;
long long *dis;
BPGraph(long long n, long long m) {
this->n = n;
this->m = m;
adj = new vector<long long>[n + 1];
}
void add_Edge(long long u, long long v) { adj[u].push_back(v); }
bool bfs() {
queue<long long> q;
dis[0] = inf;
for (long long i = 1; i <= n; i++) {
if (pair_left[i] == 0) {
dis[i] = 0;
q.push(i);
} else {
dis[i] = inf;
}
}
while (!q.empty()) {
long long u = q.front();
q.pop();
if (dis[u] < dis[0]) {
for (long long v : adj[u]) {
long long pair = pair_right[v];
if (dis[pair] == inf) {
dis[pair] = dis[u] + 1;
q.push(pair);
}
}
}
}
return (dis[0] < inf);
}
bool dfs(long long u) {
if (!u) return true;
for (long long v : adj[u]) {
long long pair = pair_right[v];
if (dis[pair] == dis[u] + 1) {
if (dfs(pair)) {
pair_left[u] = v;
pair_right[v] = u;
return true;
}
}
}
return false;
}
long long hopcroft_karp() {
pair_left = new long long[n + 1];
pair_right = new long long[m + 1];
dis = new long long[n + 1];
for (long long i = 0; i <= n; i++) {
pair_left[i] = 0;
}
for (long long i = 0; i <= m; i++) {
pair_right[i] = 0;
}
long long ans = 0;
while (bfs()) {
for (long long u = 1; u <= n; u++) {
if (!pair_left[u] && dfs(u)) {
ans++;
}
}
}
return ans;
}
};
int32_t main() {
long long n, m;
cin >> n >> m;
vector<pair<long long, pair<long long, long long>>> edge;
for (long long i = 0; i < m; i++) {
long long a, b;
cin >> a >> b;
long long t;
cin >> t;
edge.push_back({t, {a, b}});
}
sort(edge.begin(), edge.end());
long long low = 0, high = inf, ans = inf;
while (low <= high) {
long long mid = low + (high - low) / 2;
BPGraph g(n, n);
for (long long i = 0; i < m; i++) {
if (edge[i].first > mid) break;
g.add_Edge(edge[i].second.first, edge[i].second.second);
}
if (g.hopcroft_karp() == n) {
ans = min(ans, mid);
high = mid - 1;
} else {
low = mid + 1;
}
}
if (ans < inf)
cout << ans << endl;
else
cout << -1 << endl;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
George woke up and saw the current time s on the digital clock. Besides, George knows that he has slept for time t.
Help George! Write a program that will, given time s and t, determine the time p when George went to bed. Note that George could have gone to bed yesterday relatively to the current time (see the second test sample).
Input
The first line contains current time s as a string in the format "hh:mm". The second line contains time t in the format "hh:mm" β the duration of George's sleep. It is guaranteed that the input contains the correct time in the 24-hour format, that is, 00 β€ hh β€ 23, 00 β€ mm β€ 59.
Output
In the single line print time p β the time George went to bed in the format similar to the format of the time in the input.
Examples
Input
05:50
05:44
Output
00:06
Input
00:00
01:00
Output
23:00
Input
00:01
00:00
Output
00:01
Note
In the first sample George went to bed at "00:06". Note that you should print the time only in the format "00:06". That's why answers "0:06", "00:6" and others will be considered incorrect.
In the second sample, George went to bed yesterday.
In the third sample, George didn't do to bed at all.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int h1, h2, m1, m2, h3, m3;
char c;
cin >> h1 >> c >> m1;
cin >> h2 >> c >> m2;
if (m1 - m2 < 0) {
h1--;
m3 = 60 - (m2 - m1);
} else
m3 = m1 - m2;
if (h1 - h2 < 0)
h3 = 24 - (h2 - h1);
else
h3 = h1 - h2;
if (h3 / 10 == 0)
cout << 0 << h3;
else
cout << h3;
cout << ":";
if (m3 / 10 == 0)
cout << 0 << m3;
else
cout << m3;
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular a mm Γ b mm sheet of paper (a > b). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting the excess part.
<image>
After making a paper ship from the square piece, Vasya looked on the remaining (a - b) mm Γ b mm strip of paper. He got the idea to use this strip of paper in the same way to make an origami, and then use the remainder (if it exists) and so on. At the moment when he is left with a square piece of paper, he will make the last ship from it and stop.
Can you determine how many ships Vasya will make during the lesson?
Input
The first line of the input contains two integers a, b (1 β€ b < a β€ 1012) β the sizes of the original sheet of paper.
Output
Print a single integer β the number of ships that Vasya will make.
Examples
Input
2 1
Output
2
Input
10 7
Output
6
Input
1000000000000 1
Output
1000000000000
Note
Pictures to the first and second sample test.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long a, b;
cin >> a >> b;
long long count = 0;
while (a != 0 && b != 0) {
if (a == b) {
a = 0;
b = 0;
++count;
break;
}
if (a > b) {
count += a / b;
a = a % b;
} else if (a < b) {
count += b / a;
b = b % a;
}
}
cout << count;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Berland β is a huge country with diverse geography. One of the most famous natural attractions of Berland is the "Median mountain range". This mountain range is n mountain peaks, located on one straight line and numbered in order of 1 to n. The height of the i-th mountain top is a_i.
"Median mountain range" is famous for the so called alignment of mountain peaks happening to it every day. At the moment of alignment simultaneously for each mountain from 2 to n - 1 its height becomes equal to the median height among it and two neighboring mountains. Formally, if before the alignment the heights were equal b_i, then after the alignment new heights a_i are as follows: a_1 = b_1, a_n = b_n and for all i from 2 to n - 1 a_i = median(b_{i-1}, b_i, b_{i+1}). The median of three integers is the second largest number among them. For example, median(5,1,2) = 2, and median(4,2,4) = 4.
Recently, Berland scientists have proved that whatever are the current heights of the mountains, the alignment process will stabilize sooner or later, i.e. at some point the altitude of the mountains won't changing after the alignment any more. The government of Berland wants to understand how soon it will happen, i.e. to find the value of c β how many alignments will occur, which will change the height of at least one mountain. Also, the government of Berland needs to determine the heights of the mountains after c alignments, that is, find out what heights of the mountains stay forever. Help scientists solve this important problem!
Input
The first line contains integers n (1 β€ n β€ 500 000) β the number of mountains.
The second line contains integers a_1, a_2, a_3, β¦, a_n (1 β€ a_i β€ 10^9) β current heights of the mountains.
Output
In the first line print c β the number of alignments, which change the height of at least one mountain.
In the second line print n integers β the final heights of the mountains after c alignments.
Examples
Input
5
1 2 1 2 1
Output
2
1 1 1 1 1
Input
6
1 3 2 5 4 6
Output
1
1 2 3 4 5 6
Input
6
1 1 2 2 1 1
Output
0
1 1 2 2 1 1
Note
In the first example, the heights of the mountains at index 1 and 5 never change. Since the median of 1, 2, 1 is 1, the second and the fourth mountains will have height 1 after the first alignment, and since the median of 2, 1, 2 is 2, the third mountain will have height 2 after the first alignment. This way, after one alignment the heights are 1, 1, 2, 1, 1. After the second alignment the heights change into 1, 1, 1, 1, 1 and never change from now on, so there are only 2 alignments changing the mountain heights.
In the third examples the alignment doesn't change any mountain height, so the number of alignments changing any height is 0.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 7;
const int INF = 1e9 + 7;
int n;
int a[N], g[N], h[N];
struct pir {
int x, v;
} p[N];
bool cmp(pir x, pir y) { return x.v < y.v; }
bool t[N];
struct dat {
int vl, vr, vm, gg, l;
};
dat mer(dat a, dat b) {
dat c = (dat){0, 0, 0, 0, a.l + b.l};
if (a.gg) {
if (b.gg) return (dat){a.l + b.l, a.l + b.l, a.l + b.l, 1, a.l + b.l};
c.vl = a.l + b.vl;
c.vr = b.vr;
c.vm = max(b.vm, c.vl);
c.gg = 0;
return c;
}
if (b.gg) {
c.vr = a.vr + b.l;
c.vl = a.vl;
c.vm = max(a.vm, c.vr);
c.gg = 0;
return c;
}
c.gg = 0;
c.vl = a.vl;
c.vr = b.vr;
c.vm = max(max(a.vm, b.vm), a.vr + b.vl);
return c;
}
struct Tree {
int l, r, mx, mi;
dat q;
} tr[N * 4];
void upd(int p) {
tr[p].q = mer(tr[p * 2].q, tr[p * 2 + 1].q);
tr[p].mx = max(tr[p * 2].mx, tr[p * 2 + 1].mx);
tr[p].mi = min(tr[p * 2].mi, tr[p * 2 + 1].mi);
}
void build(int l, int r, int p) {
tr[p] = (Tree){l, r, r, l, (dat){0, 0, 0, 0, r - l + 1}};
if (l == r) return;
int mid = (l + r) >> 1;
build(l, mid, p * 2);
build(mid + 1, r, p * 2 + 1);
}
void ins(int x, int p) {
int l = tr[p].l, r = tr[p].r;
if (l == r) {
if (tr[p].mx) {
tr[p].q = (dat){1, 1, 1, 1, 1};
tr[p].mx = 0;
tr[p].mi = INF;
} else {
tr[p].q = (dat){0, 0, 0, 0, 1};
tr[p].mx = tr[p].mi = x;
}
return;
}
int mid = (l + r) >> 1;
ins(x, p * 2 + (x > mid));
upd(p);
}
int ch1(int p, int L) {
if (L <= tr[p].l) return tr[p].mi;
int mid = (tr[p].l + tr[p].r) >> 1;
if (L <= mid) return min(ch1(p * 2, L), tr[p * 2 + 1].mi);
return ch1(p * 2 + 1, L);
}
int ch2(int p, int R) {
if (R >= tr[p].r) return tr[p].mx;
int mid = (tr[p].l + tr[p].r) >> 1;
if (R > mid) return max(ch2(p * 2 + 1, R), tr[p * 2].mx);
return ch2(p * 2, R);
}
bool ck(int x) {
if (x <= 1 || x >= n) return 0;
return (t[x - 1] ^ t[x]) & (t[x] ^ t[x + 1]);
}
set<int> S;
void calc(int l, int r, int k) {
int cnt = 0;
for (set<int>::iterator ss = S.lower_bound(l); ss != S.end(); ss++) {
if ((*ss) > r) break;
g[(*ss)] = k;
h[++cnt] = (*ss);
}
for (int i = 1; i <= cnt; i++) S.erase(h[i]);
}
void modify(int x, int nw) {
if (!ck(x)) {
int pl = ch2(1, x - 1), pr = ch1(1, x + 1);
calc((x + pl + 1) / 2, x, nw);
calc(x, (x + pr) / 2, nw);
} else {
int pl = ch2(1, x - 1), pr = ch1(1, x + 1);
if (t[pl]) calc(pl, (pl + pr) / 2, nw);
if (t[pr]) calc((pl + pr + 1) / 2, pr, nw);
}
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
for (int i = 1; i <= n; i++) p[i] = (pir){i, a[i]};
for (int i = 1; i <= n; i++) S.insert(i);
sort(p + 1, p + n + 1, cmp);
memset(t, 0, sizeof(t));
build(1, n, 1);
int ans = 0;
p[n + 1].v = -INF;
for (int i = 1; i <= n; i++) {
int e0 = ck(p[i].x - 1), e1 = ck(p[i].x), e2 = ck(p[i].x + 1);
t[p[i].x] ^= 1;
if (ck(p[i].x - 1) != e0) ins(p[i].x - 1, 1);
if (ck(p[i].x) != e1) ins(p[i].x, 1);
if (ck(p[i].x + 1) != e2) ins(p[i].x + 1, 1);
if (ck(p[i].x - 1) != e0) modify(p[i].x - 1, p[i].v);
if (ck(p[i].x) != e1) modify(p[i].x, p[i].v);
if (ck(p[i].x + 1) != e2) modify(p[i].x + 1, p[i].v);
if (ck(p[i].x) == e1) {
g[p[i].x] = a[p[i].x];
S.erase(p[i].x);
}
if (p[i + 1].v != p[i].v) ans = max(ans, tr[1].q.vm);
}
printf("%d\n", (ans + 1) / 2);
g[1] = a[1];
g[n] = a[n];
for (int i = 1; i <= n; i++) printf("%d ", g[i]);
puts("");
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Polycarp has just launched his new startup idea. The niche is pretty free and the key vector of development sounds really promising, so he easily found himself some investors ready to sponsor the company. However, he is yet to name the startup!
Actually, Polycarp has already came up with the name but some improvement to it will never hurt. So now he wants to swap letters at some positions in it to obtain the better name. It isn't necessary for letters to be adjacent.
In addition, each of the investors has chosen some index in the name and selected a set of letters that can go there. Indices chosen by different investors are pairwise distinct. If some indices aren't chosen by any investor then any letter can go there.
Finally, Polycarp is sure that the smallest lexicographically name is the best. (Like why do you think Google decided to become Alphabet?)
More formally, you are given a string consisting of lowercase Latin letters from "a" to "f". You can swap letters at any positions arbitrary number of times (zero swaps is also possible).
What is the smallest lexicographically name you can obtain such that the letter at every position is among the allowed letters?
If Polycarp can't produce any valid name then print "Impossible".
Input
The first line is the string s (1 β€ |s| β€ 10^5) β the name Polycarp has came up with. The string consists only of lowercase Latin letters from "a" to "f".
The second line contains a single integer m (0 β€ m β€ |s|) β the number of investors.
The i-th of the next m lines contain an integer number pos_i and a non-empty string of allowed characters for pos_i (1 β€ pos_i β€ |s|). Each string contains pairwise distinct letters from "a" to "f". pos_1, pos_2, ..., pos_m are pairwise distinct. If any position of the string doesn't appear in the investors demands then any letter can go in this position.
Output
If Polycarp can't produce any valid name then print "Impossible".
Otherwise print the smallest lexicographically name Polycarp can obtain by swapping letters in string s such that the letter at every position is among the allowed ones.
Examples
Input
bedefead
5
2 e
1 dc
5 b
7 ef
6 ef
Output
deadbeef
Input
abacaba
0
Output
aaaabbc
Input
fc
2
1 cfab
2 f
Output
cf
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int cntmask[1 << 6];
int cnt[6];
int dp[1 << 6];
int allow[100010];
string s;
string ans;
int main(int argc, char const *argv[]) {
ios_base ::sync_with_stdio(false);
cin.tie(0);
cin >> s;
int n = s.size();
for (int i = 0; i < n; i++) {
allow[i] = (1 << 6) - 1;
}
int emp;
cin >> emp;
for (int i = 0; i < emp; i++) {
int x;
string t;
cin >> x >> t;
--x;
int m = 0;
for (int j = 0; j < t.size(); j++) {
m |= 1 << (t[j] - 'a');
}
allow[x] = m;
}
for (int i = 0; i < n; i++) {
cntmask[allow[i]] += 1;
cnt[s[i] - 'a'] += 1;
}
memset(dp, 0, sizeof dp);
for (int i = 0; i < (1 << 6); i++) {
dp[i] = cntmask[i];
}
for (int i = 0; i < 6; i++) {
for (int j = 0; j < (1 << 6); j++) {
if ((j >> i) & 1) {
dp[j] += dp[j ^ (1 << i)];
}
}
}
bool good = true;
for (int j = 0; j < (1 << 6); j++) {
int sum = 0;
for (int k = 0; k < 6; k++) {
if ((j >> k) & 1) {
sum += cnt[k];
}
}
int right = n - dp[((1 << 6) - 1) ^ j];
if (sum > right) {
good = false;
break;
}
}
if (!good) {
cout << "Impossible" << endl;
exit(0);
}
ans = s;
for (int x = 0; x < n; x++) {
cntmask[allow[x]] -= 1;
memset(dp, 0, sizeof dp);
for (int i = 0; i < (1 << 6); i++) {
dp[i] = cntmask[i];
}
for (int i = 0; i < 6; i++) {
for (int j = 0; j < (1 << 6); j++) {
if ((j >> i) & 1) {
dp[j] += dp[j ^ (1 << i)];
}
}
}
for (int i = 0; i < 6; i++) {
if ((allow[x] >> i) & 1) {
cnt[i] -= 1;
bool good = (cnt[i] >= 0);
for (int j = 0; j < (1 << 6); j++) {
int sum = 0;
for (int k = 0; k < 6; k++) {
if ((j >> k) & 1) {
sum += cnt[k];
}
}
int right = (n - x - 1) - dp[((1 << 6) - 1) ^ j];
if (sum > right) {
good = false;
break;
}
}
if (good) {
ans[x] = i + 'a';
break;
}
cnt[i] += 1;
}
}
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
In the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side.
One example of a grid path is (0, 0) β (0, 1) β (0, 2) β (1, 2) β (1, 1) β (0, 1) β ( - 1, 1). Note that squares in this sequence might be repeated, i.e. path has self intersections.
Movement within a grid path is restricted to adjacent squares within the sequence. That is, from the i-th square, one can only move to the (i - 1)-th or (i + 1)-th squares of this path. Note that there is only a single valid move from the first and last squares of a grid path. Also note, that even if there is some j-th square of the path that coincides with the i-th square, only moves to (i - 1)-th and (i + 1)-th squares are available. For example, from the second square in the above sequence, one can only move to either the first or third squares.
To ensure that movement is not ambiguous, the two grid paths will not have an alternating sequence of three squares. For example, a contiguous subsequence (0, 0) β (0, 1) β (0, 0) cannot occur in a valid grid path.
One marble is placed on the first square of each grid path. Genos wants to get both marbles to the last square of each grid path. However, there is a catch. Whenever he moves one marble, the other marble will copy its movement if possible. For instance, if one marble moves east, then the other marble will try and move east as well. By try, we mean if moving east is a valid move, then the marble will move east.
Moving north increases the second coordinate by 1, while moving south decreases it by 1. Similarly, moving east increases first coordinate by 1, while moving west decreases it.
Given these two valid grid paths, Genos wants to know if it is possible to move both marbles to the ends of their respective paths. That is, if it is possible to move the marbles such that both marbles rest on the last square of their respective paths.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1 000 000) β the length of the paths.
The second line of the input contains a string consisting of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') β the first grid path. The characters can be thought of as the sequence of moves needed to traverse the grid path. For example, the example path in the problem statement can be expressed by the string "NNESWW".
The third line of the input contains a string of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') β the second grid path.
Output
Print "YES" (without quotes) if it is possible for both marbles to be at the end position at the same time. Print "NO" (without quotes) otherwise. In both cases, the answer is case-insensitive.
Examples
Input
7
NNESWW
SWSWSW
Output
YES
Input
3
NN
SS
Output
NO
Note
In the first sample, the first grid path is the one described in the statement. Moreover, the following sequence of moves will get both marbles to the end: NNESWWSWSW.
In the second sample, no sequence of moves can get both marbles to the end.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1001000, P1 = 1000000007, P2 = 1000000009;
int i, j, k, n, m, t1, t2, o1, o2;
int tm1[N], tm2[N];
char s1[N], s2[N];
char get(char x) {
if (x == 'W') return 'E';
if (x == 'E') return 'W';
if (x == 'S') return 'N';
if (x == 'N') return 'S';
}
int main() {
scanf("%d", &n);
n--;
scanf("%s", s1 + 1);
scanf("%s", s2 + 1);
tm1[0] = tm2[0] = 1;
for (i = 1; i <= n; i++)
tm1[i] = 31ll * tm1[i - 1] % P1, tm2[i] = 31ll * tm2[i - 1] % P2;
for (i = n; i; i--) {
s2[i] = get(s2[i]);
t1 = (31ll * t1 + s1[i]) % P1;
t2 = (1ll * s2[i] * tm1[n - i] + t2) % P1;
o1 = (31ll * o1 + s1[i]) % P2;
o2 = (1ll * s2[i] * tm2[n - i] + o2) % P2;
if (t1 == t2 && o1 == o2) return puts("NO"), 0;
}
puts("YES");
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Santa Claus has n tangerines, and the i-th of them consists of exactly ai slices. Santa Claus came to a school which has k pupils. Santa decided to treat them with tangerines.
However, there can be too few tangerines to present at least one tangerine to each pupil. So Santa decided to divide tangerines into parts so that no one will be offended. In order to do this, he can divide a tangerine or any existing part into two smaller equal parts. If the number of slices in the part he wants to split is odd, then one of the resulting parts will have one slice more than the other. It's forbidden to divide a part consisting of only one slice.
Santa Claus wants to present to everyone either a whole tangerine or exactly one part of it (that also means that everyone must get a positive number of slices). One or several tangerines or their parts may stay with Santa.
Let bi be the number of slices the i-th pupil has in the end. Let Santa's joy be the minimum among all bi's.
Your task is to find the maximum possible joy Santa can have after he treats everyone with tangerines (or their parts).
Input
The first line contains two positive integers n and k (1 β€ n β€ 106, 1 β€ k β€ 2Β·109) denoting the number of tangerines and the number of pupils, respectively.
The second line consists of n positive integers a1, a2, ..., an (1 β€ ai β€ 107), where ai stands for the number of slices the i-th tangerine consists of.
Output
If there's no way to present a tangerine or a part of tangerine to everyone, print -1. Otherwise, print the maximum possible joy that Santa can have.
Examples
Input
3 2
5 9 3
Output
5
Input
2 4
12 14
Output
6
Input
2 3
1 1
Output
-1
Note
In the first example Santa should divide the second tangerine into two parts with 5 and 4 slices. After that he can present the part with 5 slices to the first pupil and the whole first tangerine (with 5 slices, too) to the second pupil.
In the second example Santa should divide both tangerines, so that he'll be able to present two parts with 6 slices and two parts with 7 slices.
In the third example Santa Claus can't present 2 slices to 3 pupils in such a way that everyone will have anything.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using LL = long long;
int n, k, a[1000000 + 10];
bool ok(int x) {
LL sum = 0;
for (int i = 0; i < int(n); ++i) {
if (x > a[i]) break;
LL t = 0;
for (LL j = 1; a[i] / j + 1 >= x; j += j) {
LL r = a[i] % j;
LL tmp = a[i] / j >= x ? j : r;
t = max(t, tmp);
if (a[i] / j == 0) break;
}
if (sum + (n - i) * t < k) break;
sum += t;
if (sum >= k) break;
}
return sum >= k;
}
int main() {
scanf("%d%d", &n, &k);
for (int i = 0; i < int(n); ++i) scanf("%d", &a[i]);
sort(a, a + n, greater<int>());
int l = 1, r = 1e7 + 1, ans = -1;
while (l <= r) {
int m = (l + r) >> 1;
if (ok(m)) {
ans = m;
l = m + 1;
} else
r = m - 1;
}
printf("%d\n", ans);
return 0;
}
``` |
Subsets and Splits