text
stringlengths 424
69.5k
|
---|
### Prompt
Please provide a CPP coded solution to the problem described below:
The ancient Berlanders believed that the longer the name, the more important its bearer is. Thus, Berland kings were famous for their long names. But long names are somewhat inconvenient, so the Berlanders started to abbreviate the names of their kings. They called every king by the first letters of its name. Thus, the king, whose name was Victorious Vasily Pupkin, was always called by the berlanders VVP.
In Berland over its long history many dynasties of kings replaced each other, but they were all united by common traditions. Thus, according to one Berland traditions, to maintain stability in the country, the first name of the heir should be the same as the last name his predecessor (hence, the first letter of the abbreviated name of the heir coincides with the last letter of the abbreviated name of the predecessor). Berlanders appreciate stability, so this tradition has never been broken. Also Berlanders like perfection, so another tradition requires that the first name of the first king in the dynasty coincides with the last name of the last king in this dynasty (hence, the first letter of the abbreviated name of the first king coincides with the last letter of the abbreviated name of the last king). This tradition, of course, has also been always observed.
The name of a dynasty is formed by very simple rules: we take all the short names of the kings in the order in which they ruled, and write them in one line. Thus, a dynasty of kings "ab" and "ba" is called "abba", and the dynasty, which had only the king "abca", is called "abca".
Vasya, a historian, has recently found a list of abbreviated names of all Berland kings and their relatives. Help Vasya to find the maximally long name of the dynasty that could have existed in Berland.
Note that in his list all the names are ordered by the time, that is, if name A is earlier in the list than B, then if A and B were kings, then king A ruled before king B.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of names in Vasya's list. Next n lines contain n abbreviated names, one per line. An abbreviated name is a non-empty sequence of lowercase Latin letters. Its length does not exceed 10 characters.
Output
Print a single number β length of the sought dynasty's name in letters.
If Vasya's list is wrong and no dynasty can be found there, print a single number 0.
Examples
Input
3
abc
ca
cba
Output
6
Input
4
vvp
vvp
dam
vvp
Output
0
Input
3
ab
c
def
Output
1
Note
In the first sample two dynasties can exist: the one called "abcca" (with the first and second kings) and the one called "abccba" (with the first and third kings).
In the second sample there aren't acceptable dynasties.
The only dynasty in the third sample consists of one king, his name is "c".
### Response
```cpp
#include <bits/stdc++.h>
const int G = 'z' - 'a' + 1;
int g[G][G];
char name[16];
int n;
int main() {
memset(g, 0, sizeof(g));
scanf(" %d", &n);
for (int i = 0; i < n; ++i) {
scanf(" %s", name);
int len = strlen(name);
int a = name[0] - 'a', b = name[len - 1] - 'a';
for (int j = 0; j < 'z' - 'a' + 1; ++j)
if (g[j][a] && g[j][b] < g[j][a] + len) g[j][b] = g[j][a] + len;
g[a][b] = std::max(g[a][b], len);
}
int ans = 0;
for (int i = 0; i < 'z' - 'a' + 1; ++i) ans = std::max(ans, g[i][i]);
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Arthur has bought a beautiful big table into his new flat. When he came home, Arthur noticed that the new table is unstable.
In total the table Arthur bought has n legs, the length of the i-th leg is li.
Arthur decided to make the table stable and remove some legs. For each of them Arthur determined number di β the amount of energy that he spends to remove the i-th leg.
A table with k legs is assumed to be stable if there are more than half legs of the maximum length. For example, to make a table with 5 legs stable, you need to make sure it has at least three (out of these five) legs of the maximum length. Also, a table with one leg is always stable and a table with two legs is stable if and only if they have the same lengths.
Your task is to help Arthur and count the minimum number of energy units Arthur should spend on making the table stable.
Input
The first line of the input contains integer n (1 β€ n β€ 105) β the initial number of legs in the table Arthur bought.
The second line of the input contains a sequence of n integers li (1 β€ li β€ 105), where li is equal to the length of the i-th leg of the table.
The third line of the input contains a sequence of n integers di (1 β€ di β€ 200), where di is the number of energy units that Arthur spends on removing the i-th leg off the table.
Output
Print a single integer β the minimum number of energy units that Arthur needs to spend in order to make the table stable.
Examples
Input
2
1 5
3 2
Output
2
Input
3
2 4 4
1 1 1
Output
0
Input
6
2 2 1 1 3 3
4 3 5 5 2 1
Output
8
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int M = 100005;
multiset<int> st;
multiset<int>::iterator it;
int n, x[M], y[M], len[M], sum[M];
pair<int, int> in[M];
int main() {
cin >> n;
for (int i = 1; i <= n; i++) scanf("%d", &in[i].first);
for (int i = 1; i <= n; i++) scanf("%d", &in[i].second);
sort(in + 1, in + n + 1);
for (int i = 1; i <= n; i++) {
x[i] = in[i].first, y[i] = in[i].second;
sum[i] += (sum[i - 1] + in[i].second);
}
for (int i = n; i > 0; i--) {
if (x[i] == x[i + 1])
len[i] = len[i + 1] + 1;
else
len[i] = 1;
}
int ans = 1 << 30;
for (int i = 1; i <= n; i++) {
if (x[i] != x[i - 1]) {
int lim = len[i] - 1;
int tmp = sum[n] - sum[i + len[i] - 1] + sum[i - 1];
for (it = st.begin(); lim && it != st.end(); it++, lim--) {
tmp += (*it);
}
ans = min(ans, tmp);
}
st.insert(-y[i]);
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
In Omkar's last class of math, he learned about the least common multiple, or LCM. LCM(a, b) is the smallest positive integer x which is divisible by both a and b.
Omkar, having a laudably curious mind, immediately thought of a problem involving the LCM operation: given an integer n, find positive integers a and b such that a + b = n and LCM(a, b) is the minimum value possible.
Can you help Omkar solve his ludicrously challenging math problem?
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.
Each test case consists of a single integer n (2 β€ n β€ 10^{9}).
Output
For each test case, output two positive integers a and b, such that a + b = n and LCM(a, b) is the minimum possible.
Example
Input
3
4
6
9
Output
2 2
3 3
3 6
Note
For the first test case, the numbers we can choose are 1, 3 or 2, 2. LCM(1, 3) = 3 and LCM(2, 2) = 2, so we output 2 \ 2.
For the second test case, the numbers we can choose are 1, 5, 2, 4, or 3, 3. LCM(1, 5) = 5, LCM(2, 4) = 4, and LCM(3, 3) = 3, so we output 3 \ 3.
For the third test case, LCM(3, 6) = 6. It can be shown that there are no other pairs of numbers which sum to 9 that have a lower LCM.
### Response
```cpp
#include <bits/stdc++.h>
int t, n, r1, r2, vec[10000], size = 0;
char prime[int(1e5)];
void sang() {
prime[0] = prime[1] = 1;
for (int i = 2; i < 1e5; i += 1) {
if (!prime[i]) {
vec[size++] = i;
for (int j = i + i; j < 1e5; j += i) {
prime[j] = 1;
}
}
}
}
int main() {
scanf("%i", &t);
sang();
while (t--) {
scanf("%i", &n);
r1 = 1;
r2 = n - 1;
for (int i = 0; i < size && vec[i] * vec[i] <= n; i += 1) {
if (n % vec[i] == 0) {
r1 = n / vec[i];
r2 = n - r1;
break;
}
}
printf("%i %i\n", r1, r2);
}
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself, decides he wants to shuffle the guests around because he thinks this will create a vacancy (a room without a guest).
For any integer k and positive integer n, let kmod n denote the remainder when k is divided by n. More formally, r=kmod n is the smallest non-negative integer such that k-r is divisible by n. It always holds that 0β€ kmod nβ€ n-1. For example, 100mod 12=4 and (-1337)mod 3=1.
Then the shuffling works as follows. There is an array of n integers a_0,a_1,β¦,a_{n-1}. Then for each integer k, the guest in room k is moved to room number k+a_{kmod n}.
After this shuffling process, determine if there is still exactly one guest assigned to each room. That is, there are no vacancies or rooms with multiple guests.
Input
Each test consists of multiple test cases. The first line contains a single integer t (1β€ tβ€ 10^4) β the number of test cases. Next 2t lines contain descriptions of test cases.
The first line of each test case contains a single integer n (1β€ nβ€ 2β
10^5) β the length of the array.
The second line of each test case contains n integers a_0,a_1,β¦,a_{n-1} (-10^9β€ a_iβ€ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2β
10^5.
Output
For each test case, output a single line containing "YES" if there is exactly one guest assigned to each room after the shuffling process, or "NO" otherwise. You can print each letter in any case (upper or lower).
Example
Input
6
1
14
2
1 -1
4
5 5 5 1
3
3 2 1
2
0 1
5
-239 -2 -100 -3 -11
Output
YES
YES
YES
NO
NO
YES
Note
In the first test case, every guest is shifted by 14 rooms, so the assignment is still unique.
In the second test case, even guests move to the right by 1 room, and odd guests move to the left by 1 room. We can show that the assignment is still unique.
In the third test case, every fourth guest moves to the right by 1 room, and the other guests move to the right by 5 rooms. We can show that the assignment is still unique.
In the fourth test case, guests 0 and 1 are both assigned to room 3.
In the fifth test case, guests 1 and 2 are both assigned to room 2.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using llu = unsigned long long;
int mod(int a, int b) {
int ret = a % b;
if (ret < 0) return ret + b;
return ret;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
vector<int> g(n);
for (int k = 0; k < n; k++) {
cin >> a[k];
int r = mod(k + a[k], n);
g[k]--;
g[r]++;
}
bool good = true;
for (int i : g) {
if (i != 0) {
good = false;
break;
}
}
if (good)
cout << "YES\n";
else
cout << "NO\n";
}
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
The Hedgehog recently remembered one of his favorite childhood activities, β solving puzzles, and got into it with new vigor. He would sit day in, day out with his friend buried into thousands of tiny pieces of the picture, looking for the required items one by one.
Soon the Hedgehog came up with a brilliant idea: instead of buying ready-made puzzles, one can take his own large piece of paper with some picture and cut it into many small rectangular pieces, then mix them and solve the resulting puzzle, trying to piece together the picture. The resulting task is even more challenging than the classic puzzle: now all the fragments have the same rectangular shape, and one can assemble the puzzle only relying on the picture drawn on the pieces.
All puzzle pieces turn out to be of the same size X Γ Y, because the picture is cut first by horizontal cuts with the pitch of X, then with vertical cuts with the pitch of Y. If we denote the initial size of the picture as A Γ B, then A must be divisible by X and B must be divisible by Y (X and Y are integer numbers).
However, not every such cutting of the picture will result in a good puzzle. The Hedgehog finds a puzzle good if no two pieces in it are the same (It is allowed to rotate the pieces when comparing them, but it is forbidden to turn them over).
Your task is to count for a given picture the number of good puzzles that you can make from it, and also to find the puzzle with the minimal piece size.
Input
The first line contains two numbers A and B which are the sizes of the picture. They are positive integers not exceeding 20.
Then follow A lines containing B symbols each, describing the actual picture. The lines only contain uppercase English letters.
Output
In the first line print the number of possible good puzzles (in other words, the number of pairs (X, Y) such that the puzzle with the corresponding element sizes will be good). This number should always be positive, because the whole picture is a good puzzle itself.
In the second line print two numbers β the sizes X and Y of the smallest possible element among all good puzzles. The comparison is made firstly by the area XY of one element and secondly β by the length X.
Examples
Input
2 4
ABDC
ABDC
Output
3
2 1
Input
2 6
ABCCBA
ABCCBA
Output
1
2 6
Note
The picture in the first sample test has the following good puzzles: (2, 1), (2, 2), (2, 4).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <class T>
inline int __builtin_popcount(T n) {
return (n == 0) ? 0 : (1 + __builtin_popcount(n & (n - 1)));
}
struct Ans {
int x, y;
bool operator<(const Ans& a) const {
if (x * y == a.x * a.y) {
return x < a.x;
}
return x * y < a.x * a.y;
}
Ans(int xx, int yy) {
x = xx;
y = yy;
}
};
bool isOk(vector<vector<string> > vvs) {
int N = vvs.size();
for (int i = 0; i < (int)(N); i++) {
vector<string> vs = vvs[i];
int H = vs.size();
int W = vs[0].size();
vector<string> s0(H, ""), s1(H, ""), s2(W, ""), s3(W, "");
for (int h = 0; h < (int)(H); h++) {
string t0 = "", t1 = "";
for (int w = 0; w < (int)(W); w++) {
t0 += vs[h][w];
t1 += vs[H - 1 - h][W - 1 - w];
}
s0[h] = t0;
s1[h] = t1;
}
for (int w = 0; w < (int)(W); w++) {
string t2 = "", t3 = "";
for (int h = 0; h < (int)(H); h++) {
t2 += vs[H - 1 - h][w];
t3 += vs[h][W - 1 - w];
}
s2[w] = t2;
s3[w] = t3;
}
for (int j = 0; j < (int)(N); j++) {
if (i == j) continue;
vector<string> vj = vvs[j];
if (H == vj.size() && W == vj[0].size()) {
bool isSame = true;
for (int h = 0; h < (int)(H); h++)
for (int w = 0; w < (int)(W); w++) {
if (vj[h][w] != s0[h][w]) {
isSame = false;
h = H;
break;
}
}
if (isSame) return false;
isSame = true;
for (int h = 0; h < (int)(H); h++)
for (int w = 0; w < (int)(W); w++) {
if (vj[h][w] != s1[h][w]) {
isSame = false;
h = H;
break;
}
}
if (isSame) return false;
}
if (H == vj[0].size() && W == vj.size()) {
bool isSame = true;
for (int h = 0; h < (int)(H); h++)
for (int w = 0; w < (int)(W); w++) {
if (vj[w][h] != s2[w][h]) {
isSame = false;
h = H;
break;
}
}
if (isSame) return false;
isSame = true;
for (int h = 0; h < (int)(H); h++)
for (int w = 0; w < (int)(W); w++) {
if (vj[w][h] != s3[w][h]) {
isSame = false;
h = H;
break;
}
}
if (isSame) return false;
}
}
}
return true;
}
int main() {
int A, B;
cin >> A >> B;
int resNum = 0;
Ans res = Ans(100, 100);
vector<string> pic(A, "");
for (int i = 0; i < (int)(A); i++) cin >> pic[i];
for (int a = A; a > 0; a--)
if (A % a == 0) {
for (int b = B; b > 0; b--)
if (B % b == 0) {
bool isGood = true;
vector<vector<string> > tmp;
tmp.clear();
for (int y = 0; y < A; y += a) {
for (int x = 0; x < B; x += b) {
vector<string> piece;
for (int yy = y; yy < y + a; yy++) {
piece.push_back(pic[yy].substr(x, b));
}
tmp.push_back(piece);
}
}
if (isOk(tmp)) {
resNum++;
res = min(res, Ans(a, b));
}
}
}
cout << resNum << endl;
cout << res.x << " " << res.y << endl;
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
A chessboard n Γ m in size is given. During the zero minute we repaint all the black squares to the 0 color. During the i-th minute we repaint to the i color the initially black squares that have exactly four corner-adjacent squares painted i - 1 (all such squares are repainted simultaneously). This process continues ad infinitum. You have to figure out how many squares we repainted exactly x times.
The upper left square of the board has to be assumed to be always black. Two squares are called corner-adjacent, if they have exactly one common point.
Input
The first line contains integers n and m (1 β€ n, m β€ 5000). The second line contains integer x (1 β€ x β€ 109).
Output
Print how many squares will be painted exactly x times.
Examples
Input
3 3
1
Output
4
Input
3 3
2
Output
1
Input
1 1
1
Output
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m, x;
cin >> n >> m >> x;
int con = 1;
while (x != con && n > 2 && m > 2) {
n -= 2;
m -= 2;
con++;
}
if (x != con) {
cout << 0 << endl;
} else {
if (m > 1 && n > 1) {
int r = m + n + m + n - 4;
cout << r / 2 << endl;
} else {
if (m == 1) {
cout << (n + 1) / 2 << endl;
} else {
cout << (m + 1) / 2 << endl;
}
}
}
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
The Berland capital is shaken with three bold crimes committed by the Pihsters, a notorious criminal gang.
The Berland capital's map is represented by an n Γ m rectangular table. Each cell of the table on the map represents some districts of the capital.
The capital's main detective Polycarpus took a map and marked there the districts where the first three robberies had been committed as asterisks. Deduction tells Polycarpus that the fourth robbery will be committed in such district, that all four robbed districts will form the vertices of some rectangle, parallel to the sides of the map.
Polycarpus is good at deduction but he's hopeless at math. So he asked you to find the district where the fourth robbery will be committed.
Input
The first line contains two space-separated integers n and m (2 β€ n, m β€ 100) β the number of rows and columns in the table, correspondingly.
Each of the next n lines contains m characters β the description of the capital's map. Each character can either be a "." (dot), or an "*" (asterisk). A character equals "*" if the corresponding district has been robbed. Otherwise, it equals ".".
It is guaranteed that the map has exactly three characters "*" and we can always find the fourth district that meets the problem requirements.
Output
Print two integers β the number of the row and the number of the column of the city district that is the fourth one to be robbed. The rows are numbered starting from one from top to bottom and the columns are numbered starting from one from left to right.
Examples
Input
3 2
.*
..
**
Output
1 1
Input
3 3
*.*
*..
...
Output
2 3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int x, y;
cin >> x >> y;
vector<pair<int, int>> v;
string s[200];
for (int i = 0; i < x; i++) {
cin >> s[i];
}
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
if (s[i][j] == '*') {
v.push_back(make_pair(i, j));
}
}
}
int y1, y2, x1, x2;
y1 = v[0].first;
if (v[0].first == v[1].first) {
y2 = v[2].first;
} else {
y2 = v[1].first;
}
x1 = v[0].second;
x2 = v[1].second == v[0].second ? v[2].second : v[1].second;
int y3 = (y1 + y2) * 2 - (v[0].first + v[1].first + v[2].first);
int x3 = (x1 + x2) * 2 - (v[0].second + v[1].second + v[2].second);
cout << y3 + 1 << " " << x3 + 1;
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Only T milliseconds left before the start of well-known online programming contest Codehorses Round 2017.
Polycarp needs to download B++ compiler to take part in the contest. The size of the file is f bytes.
Polycarp's internet tariff allows to download data at the rate of one byte per t0 milliseconds. This tariff is already prepaid, and its use does not incur any expense for Polycarp. In addition, the Internet service provider offers two additional packages:
* download a1 bytes at the rate of one byte per t1 milliseconds, paying p1 burles for the package;
* download a2 bytes at the rate of one byte per t2 milliseconds, paying p2 burles for the package.
Polycarp can buy any package many times. When buying a package, its price (p1 or p2) is prepaid before usage. Once a package is bought it replaces the regular tariff until package data limit is completely used. After a package is consumed Polycarp can immediately buy a new package or switch to the regular tariff without loosing any time. While a package is in use Polycarp can't buy another package or switch back to the regular internet tariff.
Find the minimum amount of money Polycarp has to spend to download an f bytes file no more than in T milliseconds.
Note that because of technical reasons Polycarp can download only integer number of bytes using regular tariff and both packages. I.e. in each of three downloading modes the number of downloaded bytes will be integer. It means that Polycarp can't download a byte partially using the regular tariff or/and both packages.
Input
The first line contains three integer numbers f, T and t0 (1 β€ f, T, t0 β€ 107) β size of the file to download (in bytes), maximal time to download the file (in milliseconds) and number of milliseconds to download one byte using the regular internet tariff.
The second line contains a description of the first additional package. The line contains three integer numbers a1, t1 and p1 (1 β€ a1, t1, p1 β€ 107), where a1 is maximal sizes of downloaded data (in bytes), t1 is time to download one byte (in milliseconds), p1 is price of the package (in burles).
The third line contains a description of the second additional package. The line contains three integer numbers a2, t2 and p2 (1 β€ a2, t2, p2 β€ 107), where a2 is maximal sizes of downloaded data (in bytes), t2 is time to download one byte (in milliseconds), p2 is price of the package (in burles).
Polycarp can buy any package many times. Once package is bought it replaces the regular tariff until package data limit is completely used. While a package is in use Polycarp can't buy another package or switch back to the regular internet tariff.
Output
Print the minimum amount of money that Polycarp needs to pay to download B++ compiler no more than in T milliseconds. If there is no solution, print the only integer -1.
Examples
Input
120 964 20
26 8 8
13 10 4
Output
40
Input
10 200 20
1 1 1
2 2 3
Output
0
Input
8 81 11
4 10 16
3 10 12
Output
28
Input
8 79 11
4 10 16
3 10 12
Output
-1
Note
In the first example Polycarp has to buy the first additional package 5 times and do not buy the second additional package. He downloads 120 bytes (of total 26Β·5 = 130 bytes) in 120Β·8 = 960 milliseconds (960 β€ 964). He spends 8Β·5 = 40 burles on it.
In the second example Polycarp has enough time to download 10 bytes. It takes 10Β·20 = 200 milliseconds which equals to upper constraint on download time.
In the third example Polycarp has to buy one first additional package and one second additional package.
In the fourth example Polycarp has no way to download the file on time.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long INF = (long long)1e18;
long long f, T, t0;
long long a1, t1, p1, a2, t2, p2;
int main() {
cin >> f >> T >> t0;
cin >> a1 >> t1 >> p1;
cin >> a2 >> t2 >> p2;
long long res = INF;
for (int swapped = 0; swapped < 2; swapped++) {
if (swapped) {
swap(a1, a2);
swap(t1, t2);
swap(p1, p2);
}
for (long long c1 = 0; c1 * a1 <= f + a1; c1++) {
long long rem_f = max(0LL, f - c1 * a1);
if (t1 * min(a1 * c1, f) + min(t2, t0) * rem_f > T) continue;
if (t2 >= t0) {
res = min(res, c1 * p1);
} else {
res = min(res, c1 * p1 + (rem_f + a2 - 1) / a2 * p2);
long long over_t = max(0LL, rem_f * t0 + t1 * (f - rem_f) - T);
long long mn_c2 = (over_t + a2 * (t0 - t2) - 1) / ((t0 - t2) * a2);
if (mn_c2 * a2 <= rem_f) {
res = min(res, c1 * p1 + mn_c2 * p2);
}
}
}
}
cout << (res == INF ? -1 : res) << '\n';
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Sereja adores trees. Today he came up with a revolutionary new type of binary root trees.
His new tree consists of n levels, each vertex is indexed by two integers: the number of the level and the number of the vertex on the current level. The tree root is at level 1, its index is (1, 1). Here is a pseudo code of tree construction.
//the global data are integer arrays cnt[], left[][], right[][]
cnt[1] = 1;
fill arrays left[][], right[][] with values -1;
for(level = 1; level < n; level = level + 1){
cnt[level + 1] = 0;
for(position = 1; position <= cnt[level]; position = position + 1){
if(the value of position is a power of two){ // that is, 1, 2, 4, 8...
left[level][position] = cnt[level + 1] + 1;
right[level][position] = cnt[level + 1] + 2;
cnt[level + 1] = cnt[level + 1] + 2;
}else{
right[level][position] = cnt[level + 1] + 1;
cnt[level + 1] = cnt[level + 1] + 1;
}
}
}
After the pseudo code is run, cell cnt[level] contains the number of vertices on level level. Cell left[level][position] contains the number of the vertex on the level level + 1, which is the left child of the vertex with index (level, position), or it contains -1, if the vertex doesn't have a left child. Similarly, cell right[level][position] is responsible for the right child. You can see how the tree with n = 4 looks like in the notes.
Serja loves to make things complicated, so he first made a tree and then added an empty set A(level, position) for each vertex. Then Sereja executes m operations. Each operation is of one of the two following types:
* The format of the operation is "1 t l r x". For all vertices level, position (level = t; l β€ position β€ r) add value x to set A(level, position).
* The format of the operation is "2 t v". For vertex level, position (level = t, position = v), find the union of all sets of vertices that are in the subtree of vertex (level, position). Print the size of the union of these sets.
Help Sereja execute the operations. In this problem a set contains only distinct values like std::set in C++.
Input
The first line contains integers n and m (1 β€ n, m β€ 7000).
Next m lines contain the descriptions of the operations. The operation of the first type is given by five integers: 1 t l r x (1 β€ t β€ n; 1 β€ l β€ r β€ cnt[t]; 1 β€ x β€ 106). The operation of the second type is given by three integers: 2 t v (1 β€ t β€ n; 1 β€ v β€ cnt[t]).
Output
For each operation of the second type, print the answer on a single line.
Examples
Input
4 5
1 4 4 7 1
1 3 1 2 2
2 1 1
2 4 1
2 3 3
Output
2
0
1
Note
You can find the definitions that are used while working with root trees by this link: http://en.wikipedia.org/wiki/Tree_(graph_theory)
You can see an example of a constructed tree at n = 4 below.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct _ {
_() { ios_base::sync_with_stdio(0); }
} _;
template <class T>
void PV(T a, T b) {
while (a != b) cout << *a++, cout << (a != b ? " " : "\n");
}
template <class T>
inline bool chmin(T &a, T b) {
return a > b ? a = b, 1 : 0;
}
template <class T>
inline bool chmax(T &a, T b) {
return a < b ? a = b, 1 : 0;
}
template <class T>
string tostring(T first, int len = 0) {
stringstream ss;
ss << first;
string r = ss.str();
if (r.length() < len) r = string(len - r.length(), '0') + r;
return r;
}
template <class T>
void convert(string first, T &r) {
stringstream ss(first);
ss >> r;
}
template <class A, class B>
ostream &operator<<(ostream &o, pair<A, B> t) {
o << "(" << t.first << ", " << t.second << ")";
return o;
}
const int inf = 0x3f3f3f3f;
const int mod = int(1e9) + 7;
const int N = 7001;
int n, m;
vector<pair<pair<int, int>, int> > level[N];
int c[1000010];
void init() {
c[1] = 1;
for (int i = 2; i < 1000010; i++) {
if ((i - 1) & (i - 2))
c[i] = c[i - 1] + 1;
else
c[i] = c[i - 1] + 2;
}
}
int main() {
cin >> n >> m;
init();
while (m--) {
int op;
cin >> op;
if (op == 1) {
int lev, l, r, first;
cin >> lev >> l >> r >> first;
level[lev].push_back(make_pair(make_pair(l, r), first));
} else {
int lev, pos;
cin >> lev >> pos;
vector<int> v;
int l = pos, r = pos;
for (int j = lev; j <= n; j++) {
for (auto i : level[j]) {
int left = i.first.first;
int right = i.first.second;
if (left > r || right < l) continue;
v.push_back(i.second);
}
l = c[l];
r = c[r + 1] - 1;
}
sort((v).begin(), (v).end()),
v.resize(unique((v).begin(), (v).end()) - v.begin());
cout << v.size() << endl;
}
}
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.
Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.
Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.
Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
Input
The first line contains a single integer n (1 β€ n β€ 105), the number of piles.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 103, a1 + a2 + ... + an β€ 106), where ai is the number of worms in the i-th pile.
The third line contains single integer m (1 β€ m β€ 105), the number of juicy worms said by Marmot.
The fourth line contains m integers q1, q2, ..., qm (1 β€ qi β€ a1 + a2 + ... + an), the labels of the juicy worms.
Output
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
Examples
Input
5
2 7 3 4 9
3
1 25 11
Output
1
5
3
Note
For the sample input:
* The worms with labels from [1, 2] are in the first pile.
* The worms with labels from [3, 9] are in the second pile.
* The worms with labels from [10, 12] are in the third pile.
* The worms with labels from [13, 16] are in the fourth pile.
* The worms with labels from [17, 25] are in the fifth pile.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, arr[1000009], j = 1, m;
memset(arr, 0, sizeof arr);
cin >> n;
for (int i = 1; i <= n; i++) {
int a;
cin >> a;
for (int k = 0; k < a; k++) {
arr[j++] = i;
}
}
cin >> m;
for (int i = 0; i < m; i++) {
int a;
cin >> a;
cout << arr[a] << endl;
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Paul is at the orchestra. The string section is arranged in an r Γ c rectangular grid and is filled with violinists with the exception of n violists. Paul really likes violas, so he would like to take a picture including at least k of them. Paul can take a picture of any axis-parallel rectangle in the orchestra. Count the number of possible pictures that Paul can take.
Two pictures are considered to be different if the coordinates of corresponding rectangles are different.
Input
The first line of input contains four space-separated integers r, c, n, k (1 β€ r, c, n β€ 10, 1 β€ k β€ n) β the number of rows and columns of the string section, the total number of violas, and the minimum number of violas Paul would like in his photograph, respectively.
The next n lines each contain two integers xi and yi (1 β€ xi β€ r, 1 β€ yi β€ c): the position of the i-th viola. It is guaranteed that no location appears more than once in the input.
Output
Print a single integer β the number of photographs Paul can take which include at least k violas.
Examples
Input
2 2 1 1
1 2
Output
4
Input
3 2 3 3
1 1
3 1
2 2
Output
1
Input
3 2 3 2
1 1
3 1
2 2
Output
4
Note
We will use '*' to denote violinists and '#' to denote violists.
In the first sample, the orchestra looks as follows
*#
**
Paul can take a photograph of just the viola, the 1 Γ 2 column containing the viola, the 2 Γ 1 row containing the viola, or the entire string section, for 4 pictures total.
In the second sample, the orchestra looks as follows
#*
*#
#*
Paul must take a photograph of the entire section.
In the third sample, the orchestra looks the same as in the second sample.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[11][11];
int main() {
int r, c, n, K;
cin >> r >> c >> n >> K;
for (int i = 0; i < n; i++) {
int x, y;
;
cin >> x >> y;
a[x - 1][y - 1] = 1;
}
int cnt = 0;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
int cur = 0;
for (int k = i; k < r; k++) {
for (int l = j; l < c; l++) {
int cur = 0;
for (int m = i; m <= k; m++) {
for (int p = j; p <= l; p++) {
if (a[m][p] == 1) {
cur++;
}
}
}
if (cur >= K) {
cnt++;
}
}
}
}
}
cout << cnt << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS:
You are given two integers d, m, find the number of arrays a, satisfying the following constraints:
* The length of a is n, n β₯ 1
* 1 β€ a_1 < a_2 < ... < a_n β€ d
* Define an array b of length n as follows: b_1 = a_1, β i > 1, b_i = b_{i - 1} β a_i, where β is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold.
Since the number of possible arrays may be too large, you need to find the answer modulo m.
Input
The first line contains an integer t (1 β€ t β€ 100) denoting the number of test cases in the input.
Each of the next t lines contains two integers d, m (1 β€ d, m β€ 10^9).
Note that m is not necessary the prime!
Output
For each test case, print the number of arrays a, satisfying all given constrains, modulo m.
Example
Input
10
1 1000000000
2 999999999
3 99999998
4 9999997
5 999996
6 99995
7 9994
8 993
9 92
10 1
Output
1
3
5
11
17
23
29
59
89
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void file(string s) {
freopen((s + ".in").c_str(), "r", stdin);
freopen((s + ".out").c_str(), "w", stdout);
}
template <typename Tp>
void read(Tp &x) {
long long fh = 1;
char c = getchar();
x = 0;
while (c > '9' || c < '0') {
if (c == '-') {
fh = -1;
}
c = getchar();
}
while (c >= '0' && c <= '9') {
x = (x << 1) + (x << 3) + (c & 15);
c = getchar();
}
x *= fh;
}
long long n, m;
long long ans[50], sm = 0;
map<long long, long long> LG;
signed main() {
for (long long i = 0; i <= 31; i++) LG[1ll << i] = i;
long long T;
read(T);
while (T--) {
sm = 0;
memset(ans, 0, sizeof(ans));
read(n);
read(m);
if (n == 1) {
printf("%I64d\n", 1 % m);
continue;
}
long long N;
for (N = 1; (N << 1) <= n; N <<= 1)
;
ans[LG[N]] = 1;
ans[LG[N] - 1] = n - N + 2;
for (long long i = LG[N] - 2; i >= 0; i--) {
ans[i] = ans[i + 1] * ((1ll << (i + 1)) + 1) % m;
}
for (long long i = 0; i <= LG[N] - 1; i++) {
sm = (sm + ans[i] * (1ll << (i)) % m) % m;
}
sm = (sm + n - N + 1) % m;
printf("%I64d\n", sm);
}
fclose(stdin);
fclose(stdout);
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Polycarp is practicing his problem solving skill. He has a list of n problems with difficulties a_1, a_2, ..., a_n, respectively. His plan is to practice for exactly k days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cannot skip any problem from his list. He has to solve all n problems in exactly k days.
Thus, each day Polycarp solves a contiguous sequence of (consecutive) problems from the start of the list. He can't skip problems or solve them multiple times. As a result, in k days he will solve all the n problems.
The profit of the j-th day of Polycarp's practice is the maximum among all the difficulties of problems Polycarp solves during the j-th day (i.e. if he solves problems with indices from l to r during a day, then the profit of the day is max_{l β€ i β€ r}a_i). The total profit of his practice is the sum of the profits over all k days of his practice.
You want to help Polycarp to get the maximum possible total profit over all valid ways to solve problems. Your task is to distribute all n problems between k days satisfying the conditions above in such a way, that the total profit is maximum.
For example, if n = 8, k = 3 and a = [5, 4, 2, 6, 5, 1, 9, 2], one of the possible distributions with maximum total profit is: [5, 4, 2], [6, 5], [1, 9, 2]. Here the total profit equals 5 + 6 + 9 = 20.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of problems and the number of days, respectively.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2000) β difficulties of problems in Polycarp's list, in the order they are placed in the list (i.e. in the order Polycarp will solve them).
Output
In the first line of the output print the maximum possible total profit.
In the second line print exactly k positive integers t_1, t_2, ..., t_k (t_1 + t_2 + ... + t_k must equal n), where t_j means the number of problems Polycarp will solve during the j-th day in order to achieve the maximum possible total profit of his practice.
If there are many possible answers, you may print any of them.
Examples
Input
8 3
5 4 2 6 5 1 9 2
Output
20
3 2 3
Input
5 1
1 1 1 1 1
Output
1
5
Input
4 2
1 2000 2000 2
Output
4000
2 2
Note
The first example is described in the problem statement.
In the second example there is only one possible distribution.
In the third example the best answer is to distribute problems in the following way: [1, 2000], [2000, 2]. The total profit of this distribution is 2000 + 2000 = 4000.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2005;
struct node {
int num, x;
} a[maxn];
int n, k;
int b[maxn];
bool compare(node a, node b) { return a.x > b.x; }
int main() {
scanf("%d %d", &n, &k);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i].x);
a[i].num = i;
}
int ans = 0;
sort(a + 1, a + n + 1, compare);
for (int i = 1; i <= k; i++) {
b[i] = a[i].num;
ans += a[i].x;
}
sort(b + 1, b + k + 1);
printf("%d\n", ans);
if (k != 1) printf("%d ", b[1]);
for (int i = 2; i < k; i++) printf("%d ", b[i] - b[i - 1]);
if (k != 1)
printf("%d", n - b[k - 1]);
else
printf("%d", n);
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Given is a string S. Let T be the concatenation of K copies of S. We can repeatedly perform the following operation: choose a character in T and replace it with a different character. Find the minimum number of operations required to satisfy the following condition: any two adjacent characters in T are different.
Constraints
* 1 \leq |S| \leq 100
* S consists of lowercase English letters.
* 1 \leq K \leq 10^9
* K is an integer.
Input
Input is given from Standard Input in the following format:
S
K
Output
Print the minimum number of operations required.
Examples
Input
issii
2
Output
4
Input
qq
81
Output
81
Input
cooooooooonteeeeeeeeeest
999993333
Output
8999939997
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define INF 1LL<<62
#define inf 1000000007
int main() {
string s;
cin>>s;
ll k;
cin>>k;
ll m1,m2;
m1=m2=0;
string t='A'+s;
string u=s[s.size()-1]+s;
for(ll i=1;i<=t.size();i++){
if(t[i]==t[i-1]){
t[i]='A';
m1++;
}
}
for(ll i=1;i<=u.size();i++){
if(u[i]==u[i-1]){
u[i]='A';
m2++;
}
}
if(t[1]!=t[t.size()-1]){
cout<<k*m1;
}
else{
if(u[1]!=u[u.size()-1]){
cout << m1+(k-1)*m2;
}
else{
cout << k/2*(m1+m2)+k%2*m1;
}
}
// your code goes here
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state).
You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A).
You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007.
Input
The first line of input will contain two integers n, m (3 β€ n β€ 100 000, 0 β€ m β€ 100 000).
The next m lines will contain the description of the known relationships. The i-th line will contain three integers ai, bi, ci. If ci is 1, then ai and bi are in love, otherwise, they hate each other (1 β€ ai, bi β€ n, ai β bi, <image>).
Each pair of people will be described no more than once.
Output
Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007.
Examples
Input
3 0
Output
4
Input
4 4
1 2 1
2 3 1
3 4 0
4 1 0
Output
1
Input
4 4
1 2 1
2 3 1
3 4 0
4 1 1
Output
0
Note
In the first sample, the four ways are to:
* Make everyone love each other
* Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this).
In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int inf = 1e9;
const int MOD = 1e9 + 7;
const int N = 1e5 + 10;
int n, m, x, y, type, h[N];
vector<pair<int, int> > v[N];
queue<int> q;
int main() {
cin >> n >> m;
for (auto i = 1; i <= m; i++) {
scanf("%d%d%d", &x, &y, &type);
v[x].push_back(pair<int, int>(type ^ 1, y));
v[y].push_back(pair<int, int>(type ^ 1, x));
}
int ans = 1;
memset(h, -1, sizeof(h));
for (auto i = 1; i <= n; i++)
if (h[i] == -1) {
h[i] = 0;
q.push(i);
while (!q.empty()) {
int x = q.front();
q.pop();
for (auto j : v[x]) {
int y = j.second, ns = h[x] ^ j.first;
if (h[y] == -1) {
h[y] = ns;
q.push(y);
} else if (h[y] != ns) {
printf("0");
return 0;
}
}
}
if (i != 1) ans = ans * 2 % MOD;
}
cout << ans;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Miki is a high school student. She has a part time job, so she cannot take enough sleep on weekdays. She wants to take good sleep on holidays, but she doesn't know the best length of sleeping time for her. She is now trying to figure that out with the following algorithm:
1. Begin with the numbers K, R and L.
2. She tries to sleep for H=(R+L)/2 hours.
3. If she feels the time is longer than or equal to the optimal length, then update L with H. Otherwise, update R with H.
4. After repeating step 2 and 3 for K nights, she decides her optimal sleeping time to be T' = (R+L)/2.
If her feeling is always correct, the steps described above should give her a very accurate optimal sleeping time. But unfortunately, she makes mistake in step 3 with the probability P.
Assume you know the optimal sleeping time T for Miki. You have to calculate the probability PP that the absolute difference of T' and T is smaller or equal to E. It is guaranteed that the answer remains unaffected by the change of E in 10^{-10}.
Input
The input follows the format shown below
K R L
P
E
T
Where the integers 0 \leq K \leq 30, 0 \leq R \leq L \leq 12 are the parameters for the algorithm described above. The decimal numbers on the following three lines of the input gives the parameters for the estimation. You can assume 0 \leq P \leq 1, 0 \leq E \leq 12, 0 \leq T \leq 12.
Output
Output PP in one line. The output should not contain an error greater than 10^{-5}.
Examples
Input
3 0 2
0.10000000000
0.50000000000
1.00000000000
Output
0.900000
Input
3 0 2
0.10000000000
0.37499999977
1.00000000000
Output
0.810000
Input
3 0 2
0.10000000000
0.00000100000
0.37500000000
Output
0.729000
Input
3 0 2
0.20000000000
0.00000100000
0.37500000000
Output
0.512000
### Response
```cpp
#include<iostream>
#include<sstream>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
#include<complex>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cassert>
#define rep(i,n) for(int i=0;i<(int)n;i++)
#define all(c) (c).begin(),(c).end()
#define mp make_pair
#define pb push_back
#define each(i,c) for(__typeof((c).begin()) i=(c).begin();i!=(c).end();i++)
#define dbg(x) cerr<<__LINE__<<": "<<#x<<" = "<<(x)<<endl
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pi;
const int inf = (int)1e9;
const double INF = 1e12, EPS = 1e-9;
double k, l, r, p, e, t;
double rec(int k, double l, double r){
if(l >= t - e && r <= t + e) return 1.0;
if(r < t - e || l > t + e) return 0.0;
if(k == 0) return abs(t - (l + r) / 2) <= e ? 1.0 : 0.0;
double m = (l + r) / 2, res = 0;
if(m < t){
res += rec(k - 1, m, r) * (1 - p);
res += rec(k - 1, l, m) * p;
}
else{
res += rec(k - 1, l, m) * (1 - p);
res += rec(k - 1, m, r) * p;
}
return res;
}
int main(){
cin >> k >> l >> r;
cin >> p >> e >> t;
double ans = rec(k, l, r);
printf("%.9f\n", ans);
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Michael has just bought a new electric car for moving across city. Michael does not like to overwork, so each day he drives to only one of two his jobs.
Michael's day starts from charging his electric car for getting to the work and back. He spends 1000 burles on charge if he goes to the first job, and 2000 burles if he goes to the second job.
On a charging station he uses there is a loyalty program that involves bonus cards. Bonus card may have some non-negative amount of bonus burles. Each time customer is going to buy something for the price of x burles, he is allowed to pay an amount of y (0 β€ y β€ x) burles that does not exceed the bonus card balance with bonus burles. In this case he pays x - y burles with cash, and the balance on the bonus card is decreased by y bonus burles.
If customer pays whole price with cash (i.e., y = 0) then 10% of price is returned back to the bonus card. This means that bonus card balance increases by <image> bonus burles. Initially the bonus card balance is equal to 0 bonus burles.
Michael has planned next n days and he knows how much does the charge cost on each of those days. Help Michael determine the minimum amount of burles in cash he has to spend with optimal use of bonus card. Assume that Michael is able to cover any part of the price with cash in any day. It is not necessary to spend all bonus burles at the end of the given period.
Input
The first line of input contains a single integer n (1 β€ n β€ 300 000), the number of days Michael has planned.
Next line contains n integers a1, a2, ..., an (ai = 1000 or ai = 2000) with ai denoting the charging cost at the day i.
Output
Output the minimum amount of burles Michael has to spend.
Examples
Input
3
1000 2000 1000
Output
3700
Input
6
2000 2000 2000 2000 2000 1000
Output
10000
Note
In the first sample case the most optimal way for Michael is to pay for the first two days spending 3000 burles and get 300 bonus burles as return. After that he is able to pay only 700 burles for the third days, covering the rest of the price with bonus burles.
In the second sample case the most optimal way for Michael is to pay the whole price for the first five days, getting 1000 bonus burles as return and being able to use them on the last day without paying anything in cash.
### Response
```cpp
#include <bits/stdc++.h>
const int N = 3e5 + 10;
using namespace std;
int n, A[N];
int dp[2][35];
int main() {
memset(dp, 0x3f, sizeof(dp));
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &A[i]);
A[i] /= 100;
}
int s = 0, t = 1;
dp[0][0] = 0;
for (int i = 1; i <= n; ++i) {
int a = A[i] / 10;
for (int j = 0; j <= 31; ++j)
if (dp[s][j] < dp[0][32]) {
if (j + a <= 31) dp[t][j + a] = min(dp[t][j + a], dp[s][j] + A[i]);
int b = min(j, A[i]);
if (b) dp[t][j - b] = min(dp[t][j - b], dp[s][j] + A[i] - b);
dp[s][j] = dp[0][32];
}
swap(s, t);
}
int ans = dp[0][32];
for (int i = 0; i < 20; ++i) ans = min(ans, dp[s][i]);
printf("%d00\n", ans);
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
A and B are preparing themselves for programming contests.
The University where A and B study is a set of rooms connected by corridors. Overall, the University has n rooms connected by n - 1 corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from 1 to n.
Every day Π and B write contests in some rooms of their university, and after each contest they gather together in the same room and discuss problems. A and B want the distance from the rooms where problems are discussed to the rooms where contests are written to be equal. The distance between two rooms is the number of edges on the shortest path between them.
As they write contests in new rooms every day, they asked you to help them find the number of possible rooms to discuss problems for each of the following m days.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of rooms in the University.
The next n - 1 lines describe the corridors. The i-th of these lines (1 β€ i β€ n - 1) contains two integers ai and bi (1 β€ ai, bi β€ n), showing that the i-th corridor connects rooms ai and bi.
The next line contains integer m (1 β€ m β€ 105) β the number of queries.
Next m lines describe the queries. The j-th of these lines (1 β€ j β€ m) contains two integers xj and yj (1 β€ xj, yj β€ n) that means that on the j-th day A will write the contest in the room xj, B will write in the room yj.
Output
In the i-th (1 β€ i β€ m) line print the number of rooms that are equidistant from the rooms where A and B write contest on the i-th day.
Examples
Input
4
1 2
1 3
2 4
1
2 3
Output
1
Input
4
1 2
2 3
2 4
2
1 2
1 3
Output
0
2
Note
in the first sample there is only one room at the same distance from rooms number 2 and 3 β room number 1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n;
int T;
int pa[N];
int tin[N];
int tout[N];
int kp[N][20];
int d[N];
int sz[N];
vector<int> g[N];
void dfs(int x) {
tin[x] = T++;
sz[x] = 1;
for (int i = 0; i < g[x].size(); ++i) {
int y = g[x][i];
if (y != pa[x]) {
d[y] = d[x] + 1;
pa[y] = x;
dfs(y);
sz[x] += sz[y];
}
}
tout[x] = T++;
}
bool anc(int x, int y) { return tin[x] <= tin[y] && tout[x] >= tout[y]; }
int lca(int x, int y) {
if (anc(x, y)) {
return x;
}
for (int i = 19; i >= 0; --i) {
if (!anc(kp[x][i], y)) {
x = kp[x][i];
}
}
return pa[x];
}
int get_kth(int x, int k) {
for (int i = 19; i >= 0; --i) {
if (k >= (1 << i)) {
k -= (1 << i);
x = kp[x][i];
}
}
return x;
}
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
g[i].clear();
}
for (int i = 0; i < n - 1; ++i) {
int x, y;
scanf("%d %d", &x, &y);
--x;
--y;
g[x].push_back(y);
g[y].push_back(x);
}
T = 0;
d[0] = 0;
pa[0] = 0;
dfs(0);
for (int i = 0; i < n; ++i) {
kp[i][0] = pa[i];
}
for (int j = 1; j < 20; ++j) {
for (int i = 0; i < n; ++i) {
kp[i][j] = kp[kp[i][j - 1]][j - 1];
}
}
int qq;
scanf("%d", &qq);
while (qq--) {
int x, y;
scanf("%d %d", &x, &y);
--x;
--y;
if (x == y) {
printf("%d\n", n);
} else {
int z = lca(x, y);
int dist = d[x] + d[y] - 2 * d[z];
int ans = 0;
if (dist % 2 == 0) {
int middle = dist / 2;
if (d[x] > d[y]) {
ans += sz[get_kth(x, middle)];
ans -= sz[get_kth(x, middle - 1)];
} else if (d[y] > d[x]) {
ans += sz[get_kth(y, middle)];
ans -= sz[get_kth(y, middle - 1)];
} else {
ans += n;
ans -= sz[get_kth(x, middle - 1)];
ans -= sz[get_kth(y, middle - 1)];
}
}
printf("%d\n", ans);
}
}
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!
In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage.
One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.
But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).
The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.
Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
Input
The first line contains an integer n (1 β€ n β€ 105).
The next line contains n integers a1, a2, ..., an (0 β€ ai β€ 1012) β Mr. Bitkoch's sausage.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single integer β the maximum pleasure BitHaval and BitAryo can get from the dinner.
Examples
Input
2
1 2
Output
3
Input
3
1 2 3
Output
3
Input
2
1000 1000
Output
1000
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct Trie {
Trie *nx[2];
int cnt;
Trie() {
nx[0] = nx[1] = nullptr;
cnt = 0;
}
};
Trie *root;
void ins(long long x) {
Trie *now = root;
for (int bit = 45; bit >= 0; --bit) {
int p = (x >> bit) & 1LL;
if (now->nx[p] == nullptr) now->nx[p] = new Trie();
now = now->nx[p];
now->cnt++;
}
}
long long query(long long x) {
Trie *now = root;
long long ret = 0LL;
for (int bit = 45; bit >= 0; --bit) {
int p = (x >> bit) & 1LL;
p ^= 1;
if (now->nx[p] != nullptr && now->nx[p]->cnt > 0) {
ret += 1LL << bit;
now = now->nx[p];
} else {
now = now->nx[p ^ 1];
}
if (now == nullptr || now->cnt == 0) break;
}
return ret;
}
const int MXSZ = 1e5;
int n;
long long a[MXSZ + 5];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
root = new Trie();
cin >> n;
long long curr = 0LL;
for (int i = 1; i <= n; i++) {
cin >> a[i];
curr ^= a[i];
ins(curr);
}
long long mx = 0LL;
mx = max(mx, query(0));
curr = 0LL;
for (int i = n; i >= 1; --i) {
curr ^= a[i];
mx = max(mx, query(curr));
}
cout << mx << '\n';
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Famous Brazil city Rio de Janeiro holds a tennis tournament and Ostap Bender doesn't want to miss this event. There will be n players participating, and the tournament will follow knockout rules from the very first game. That means, that if someone loses a game he leaves the tournament immediately.
Organizers are still arranging tournament grid (i.e. the order games will happen and who is going to play with whom) but they have already fixed one rule: two players can play against each other only if the number of games one of them has already played differs by no more than one from the number of games the other one has already played. Of course, both players had to win all their games in order to continue participating in the tournament.
Tournament hasn't started yet so the audience is a bit bored. Ostap decided to find out what is the maximum number of games the winner of the tournament can take part in (assuming the rule above is used). However, it is unlikely he can deal with this problem without your help.
Input
The only line of the input contains a single integer n (2 β€ n β€ 1018) β the number of players to participate in the tournament.
Output
Print the maximum number of games in which the winner of the tournament can take part.
Examples
Input
2
Output
1
Input
3
Output
2
Input
4
Output
2
Input
10
Output
4
Note
In all samples we consider that player number 1 is the winner.
In the first sample, there would be only one game so the answer is 1.
In the second sample, player 1 can consequently beat players 2 and 3.
In the third sample, player 1 can't play with each other player as after he plays with players 2 and 3 he can't play against player 4, as he has 0 games played, while player 1 already played 2. Thus, the answer is 2 and to achieve we make pairs (1, 2) and (3, 4) and then clash the winners.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 101001;
long long dp[N];
int main(int argc, const char* argv[]) {
long long n;
cin >> n;
dp[0] = 1;
dp[1] = 2;
int k = 2;
while (1) {
dp[k] = dp[k - 1] + dp[k - 2];
if (dp[k] > n) {
cout << k - 1 << endl;
break;
}
++k;
}
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Given a string consisting of only numbers from 0 to 9, consider the operation of creating a new string from that string according to the following rules. Read the given string one character at a time from the left end. Go, if the same number a continues r, write the number r and the number a in this order without separating them with a space. Read to the right end of the given character string, and what is on the way to the end of the last writing Even if there are times of writing, all of them are counted as one operation. For the second and subsequent operations, the same operation is performed with the character string written out by the previous operation as the given character string. For example, "122244" If the character string "" is given, the character string obtained by one operation is "113224" and "44444444444" (11) because one 1, three 2, two 4s are given in order from the left end. In the case of 4), the obtained character string is β114β.
Create a program that outputs a string obtained by performing the above operation n times on a given string of 100 characters or less, where n β€ 20.
The input data consists of two lines, the first line contains the number of operations n, and the second line contains the first character string.
Input example
---
Five
11
Output example
13112221
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the character string that has been operated the specified number of times is output on one line.
Example
Input
5
11
5
11
0
Output
13112221
13112221
### Response
```cpp
#include<iostream>
#include<algorithm>
#include<string>
#define F 100000
using namespace std;
int c[F],d[F],n,ctop,dtop;
void news(int cnt,int r){
int y=F;
bool k=false;
while(true){
if(k){
d[dtop]=(cnt/y)%10;
dtop++;
}
else if(y<=cnt){
d[dtop]=(cnt/y)%10;
dtop++;
k=true;
}
if(y==1)break;
y/=10;
}
d[dtop]=c[r],dtop++;
return;
}
int main(){
string s;
while(true){
cin>>n;
if(!n)break;
cin>>s;
ctop=s.size();
for(int i=0;i<ctop;i++)c[i]=s[i]-'0';
for(int u=0;u<n;u++){
dtop=0;
int cnt=1;
for(int i=1;i<ctop;i++){
if(c[i]!=c[i-1]){news(cnt,i-1);cnt=0;}
cnt++;
}
news(cnt,ctop-1);
ctop=dtop;
for(int i=0;i<dtop;i++)c[i]=d[i];
}
for(int i=0;i<ctop;i++)cout<<c[i];
cout<<endl;
}
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.
For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.
What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.
Input
The first line contains three integers m, t, r (1 β€ m, t, r β€ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit.
The next line contains m space-separated numbers wi (1 β€ i β€ m, 1 β€ wi β€ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.
Output
If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that.
If that is impossible, print - 1.
Examples
Input
1 8 3
10
Output
3
Input
2 10 1
5 8
Output
1
Input
1 1 3
10
Output
-1
Note
Anya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.
It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.
In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.
In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.
In the third sample test the answer is - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int C = 1000;
int a[3000], f[3000], z[3000];
int main() {
ios_base::sync_with_stdio(0);
int m, t, r;
cin >> m >> t >> r;
int w = 5000;
int ans = 0;
for (int i = 0; i < m; i++) {
int x;
cin >> x;
x += C;
w = min(w, x);
f[x] = 1;
}
if (r > t) {
cout << -1 << endl;
return 0;
}
int j = 1;
w--;
for (int i = t + w; i > w; i--) {
a[i] = j;
z[i - t] = 1;
if (j < r) j++;
}
ans = r;
for (int i = w + 2; i <= 1300; i++) {
if (f[i] == 1 && a[i] < r) {
int j = i - 1;
while (a[i] < r && i - j <= t) {
if (z[j] != 1) {
for (int I = j + 1; I <= j + t; I++) a[I]++;
z[j] = 1;
ans++;
}
j--;
}
if (a[i] < r) {
cout << -1 << endl;
return 0;
}
}
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Two people play the following string game. Initially the players have got some string s. The players move in turns, the player who cannot make a move loses.
Before the game began, the string is written on a piece of paper, one letter per cell.
<image> An example of the initial situation at s = "abacaba"
A player's move is the sequence of actions:
1. The player chooses one of the available pieces of paper with some string written on it. Let's denote it is t. Note that initially, only one piece of paper is available.
2. The player chooses in the string t = t1t2... t|t| character in position i (1 β€ i β€ |t|) such that for some positive integer l (0 < i - l; i + l β€ |t|) the following equations hold: ti - 1 = ti + 1, ti - 2 = ti + 2, ..., ti - l = ti + l.
3. Player cuts the cell with the chosen character. As a result of the operation, he gets three new pieces of paper, the first one will contain string t1t2... ti - 1, the second one will contain a string consisting of a single character ti, the third one contains string ti + 1ti + 2... t|t|.
<image> An example of making action (i = 4) with string s = Β«abacabaΒ»
Your task is to determine the winner provided that both players play optimally well. If the first player wins, find the position of character that is optimal to cut in his first move. If there are multiple positions, print the minimal possible one.
Input
The first line contains string s (1 β€ |s| β€ 5000). It is guaranteed that string s only contains lowercase English letters.
Output
If the second player wins, print in the single line "Second" (without the quotes). Otherwise, print in the first line "First" (without the quotes), and in the second line print the minimal possible winning move β integer i (1 β€ i β€ |s|).
Examples
Input
abacaba
Output
First
2
Input
abcde
Output
Second
Note
In the first sample the first player has multiple winning moves. But the minimum one is to cut the character in position 2.
In the second sample the first player has no available moves.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
char s[6005];
int n;
int sp[6005];
vector<pair<int, int> > fst;
void init(void) {
scanf("%s", s + 1);
n = strlen(s + 1);
memset(sp, -1, sizeof sp);
}
bool ok(const int &l, const int &r, const int &m) {
if (m >= r || m <= l) return (false);
return (s[m - 1] == s[m + 1]);
}
int sprague(const int &l) {
if (l <= 0) return 0;
if (sp[l] >= 0) return (sp[l]);
set<int> s;
s.clear();
int i;
for (i = 1; i <= l; i = i + 1) s.insert(sprague(i - 2) ^ sprague(l - i - 1));
for (sp[l] = 0; s.find(sp[l]) != s.end(); sp[l]++)
;
return (sp[l]);
}
void process(void) {
int res = 0;
int i, j;
j = 1;
for (i = 1; i <= n + 1; i = i + 1) {
if (ok(1, n, i)) {
if (!ok(1, n, i - 1)) j = i;
} else {
if (ok(1, n, i - 1)) fst.push_back(pair<int, int>(j, i - j));
}
}
for (i = 0; i < fst.size(); i = i + 1) res = res ^ sprague(fst[i].second);
if (res == 0) {
printf("Second");
return;
}
printf("First\n");
for (i = 0; i < fst.size(); i = i + 1) {
res = 0;
for (j = 0; j < i; j = j + 1) res = res ^ sprague(fst[j].second);
for (j = i + 1; j < fst.size(); j = j + 1)
res = res ^ sprague(fst[j].second);
for (j = 1; j <= fst[i].second; j = j + 1)
if ((res ^ sprague(j - 2) ^ sprague(fst[i].second - j - 1)) == 0) {
printf("%d", fst[i].first + j - 1);
return;
}
}
}
int main(void) {
init();
process();
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Momiji has got a rooted tree, consisting of n nodes. The tree nodes are numbered by integers from 1 to n. The root has number 1. Momiji decided to play a game on this tree.
The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by v) and removes all the subtree nodes with the root in node v from the tree. Node v gets deleted as well. The game finishes when the tree has no nodes left. In other words, the game finishes after the step that chooses the node number 1.
Each time Momiji chooses a new node uniformly among all the remaining nodes. Your task is to find the expectation of the number of steps in the described game.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of nodes in the tree. The next n - 1 lines contain the tree edges. The i-th line contains integers ai, bi (1 β€ ai, bi β€ n; ai β bi) β the numbers of the nodes that are connected by the i-th edge.
It is guaranteed that the given graph is a tree.
Output
Print a single real number β the expectation of the number of steps in the described game.
The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
Examples
Input
2
1 2
Output
1.50000000000000000000
Input
3
1 2
1 3
Output
2.00000000000000000000
Note
In the first sample, there are two cases. One is directly remove the root and another is remove the root after one step. Thus the expected steps are:
1 Γ (1 / 2) + 2 Γ (1 / 2) = 1.5
In the second sample, things get more complex. There are two cases that reduce to the first sample, and one case cleaned at once. Thus the expected steps are:
1 Γ (1 / 3) + (1 + 1.5) Γ (2 / 3) = (1 / 3) + (5 / 3) = 2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<vector<int> > g;
double res;
void dfs(int u, int p, int l) {
int i, v, k;
res += 1. / l;
k = g[u].size();
for (i = 0; i < k; i++) {
v = g[u][i];
if (v != p) dfs(v, u, l + 1);
}
}
int main() {
int i, j, k;
int n;
int u, v;
scanf("%d", &n);
g.assign(n + 10, vector<int>());
for (i = 0; i < (n - 1); i++) {
scanf("%d%d", &u, &v);
u--;
v--;
g[u].push_back(v);
g[v].push_back(u);
}
dfs(0, -1, 1);
printf("%.15lf\n", res);
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
You have n problems. You have estimated the difficulty of the i-th one as integer ci. Now you want to prepare a problemset for a contest, using some of the problems you've made.
A problemset for the contest must consist of at least two problems. You think that the total difficulty of the problems of the contest must be at least l and at most r. Also, you think that the difference between difficulties of the easiest and the hardest of the chosen problems must be at least x.
Find the number of ways to choose a problemset for the contest.
Input
The first line contains four integers n, l, r, x (1 β€ n β€ 15, 1 β€ l β€ r β€ 109, 1 β€ x β€ 106) β the number of problems you have, the minimum and maximum value of total difficulty of the problemset and the minimum difference in difficulty between the hardest problem in the pack and the easiest one, respectively.
The second line contains n integers c1, c2, ..., cn (1 β€ ci β€ 106) β the difficulty of each problem.
Output
Print the number of ways to choose a suitable problemset for the contest.
Examples
Input
3 5 6 1
1 2 3
Output
2
Input
4 40 50 10
10 20 30 25
Output
2
Input
5 25 35 10
10 10 20 10 20
Output
6
Note
In the first example two sets are suitable, one consisting of the second and third problem, another one consisting of all three problems.
In the second example, two sets of problems are suitable β the set of problems with difficulties 10 and 30 as well as the set of problems with difficulties 20 and 30.
In the third example any set consisting of one problem of difficulty 10 and one problem of difficulty 20 is suitable.
### Response
```cpp
#include <bits/stdc++.h>
int n, l, r, x, a[20], ans = 0, state = 0;
void func(int k, int d, int e, int h, int t) {
if (k == n) {
if (h - e >= x && d >= l && d <= r && t > 1) {
ans++;
}
return;
}
if (state == 0) {
state = 1;
func(k + 1, d + a[k], a[k], a[k], t + 1);
state = 0;
func(k + 1, d, e, h, t);
} else {
if (a[k] < e) {
func(k + 1, d + a[k], a[k], h, t + 1);
func(k + 1, d, e, h, t);
} else if (a[k] > h) {
func(k + 1, d + a[k], e, a[k], t + 1);
func(k + 1, d, e, h, t);
} else {
func(k + 1, d + a[k], e, h, t + 1);
func(k + 1, d, e, h, t);
}
}
return;
}
int main() {
int i;
scanf("%d %d %d %d", &n, &l, &r, &x);
for (i = 0; i < n; i++) scanf("%d", &a[i]);
func(0, 0, 0, 0, 0);
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
There is a long-established secondhand bookstore called JOI secondhand bookstore in your town, and you often use the JOI secondhand bookstore. Each book has a standard price, and you can buy it at that price if you go to the JOI secondhand bookstore.
At the JOI secondhand bookstore, books are classified into 10 genres such as novels, manga, and magazines. Genres are numbered from 1 to 10. The JOI secondhand bookstore has a service that if you buy books of the same genre in bulk, they will buy them at a high price. Specifically, when books of the same genre are purchased together in T books, the purchase price per book of that genre is T -1 yen higher than the standard price. For example, if books of the same genre with standard prices of 100 yen, 120 yen, and 150 yen are sold together at the JOI secondhand bookstore, the purchase prices will be 102 yen, 122 yen, and 152 yen, respectively.
By the way, you have to move in a hurry due to personal reasons. You have N books, but it is difficult to bring all the books to your new home, so I decided to sell K of the N books to the JOI secondhand bookstore.
input
Read the following input from standard input.
* The integers N and K are written on the first line, separated by blanks, indicating that the number of books you have is N, of which K books will be sold to JOI secondhand bookstores.
* The following N lines contain information about your book. On the first line of i + (1 β€ i β€ N), the integers Ci and Gi are written separated by blanks, indicating that the base price of the i-th book is Ci and the genre number is Gi. ..
output
Output an integer representing the maximum value of the total purchase price to the standard output on one line.
Example
Input
7 4
14 1
13 2
12 3
14 2
8 2
16 3
11 2
Output
60
### Response
```cpp
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cmath>
#include <functional>
using namespace std;
int n, k;
vector<int> v[10];
int dp[10][2000];
int ans;
int main(){
scanf("%d %d", &n, &k);
for(int i=0; i<n; i++){
int s, t;
scanf("%d %d", &s, &t);
v[t-1].push_back(s);
}
for(int i=0; i<10; i++) sort(v[i].begin(), v[i].end(), greater<int>());
/*
for(int i=0; i<10; i++){
for(int j=0; j<v[i].size(); j++){
printf("%d\t", v[i][j]);
}
printf("\n");
}
*/
for(int i=0; i<10; i++) for(int j=1; j<v[i].size(); j++)
v[i][j] += v[i][j-1];
for(int i=0; i<10; i++) for(int j=1; j<v[i].size(); j++)
v[i][j] += j * (j + 1);
/*
for(int i=0; i<10; i++){
for(int j=0; j<v[i].size(); j++){
printf("%d\t", v[i][j]);
}
printf("\n");
}
*/
dp[0][0] = v[0][0];
for(int i=1; i<v[0].size(); i++) dp[0][i] = v[0][i];
for(int i=1; i<10; i++)
if(0 < v[i].size()) dp[i][0] = max(dp[i-1][0], v[i][0]);
for(int i=1; i<10; i++){
for(int j=0; j<k; j++){
dp[i][j] = dp[i-1][j];
for(int l=0; l<v[i].size(); l++){
if(j-l >= 0) dp[i][j] = max(dp[i][j], dp[i-1][j-l-1]+v[i][l]);
}
}
}
/*
for(int i=0; i<10; i++){
for(int j=0; j<k; j++){
printf("%d\t", dp[i][j]);
}
printf("\n");
}
*/
for(int i=0; i<10; i++) ans = max(ans, dp[i][k-1]);
printf("%d\n", ans);
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive.
The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.
Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.
Input
The first line of the input contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 10 000, n β₯ 2m) β the number of participants of the qualifying contest and the number of regions in Berland.
Next n lines contain the description of the participants of the qualifying contest in the following format: Surname (a string of length from 1 to 10 characters and consisting of large and small English letters), region number (integer from 1 to m) and the number of points scored by the participant (integer from 0 to 800, inclusive).
It is guaranteed that all surnames of all the participants are distinct and at least two people participated from each of the m regions. The surnames that only differ in letter cases, should be considered distinct.
Output
Print m lines. On the i-th line print the team of the i-th region β the surnames of the two team members in an arbitrary order, or a single character "?" (without the quotes) if you need to spend further qualifying contests in the region.
Examples
Input
5 2
Ivanov 1 763
Andreev 2 800
Petrov 1 595
Sidorov 1 790
Semenov 2 503
Output
Sidorov Ivanov
Andreev Semenov
Input
5 2
Ivanov 1 800
Andreev 2 763
Petrov 1 800
Sidorov 1 800
Semenov 2 503
Output
?
Andreev Semenov
Note
In the first sample region teams are uniquely determined.
In the second sample the team from region 2 is uniquely determined and the team from region 1 can have three teams: "Petrov"-"Sidorov", "Ivanov"-"Sidorov", "Ivanov" -"Petrov", so it is impossible to determine a team uniquely.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<vector<pair<int, string> > > v;
string s;
int p, pts;
bool cmp(pair<int, string> &a, pair<int, string> &b) {
return a.first > b.first;
}
int main() {
int n, m;
cin >> n >> m;
v.assign(m, vector<pair<int, string> >());
for (int i = 0; i < n; ++i) {
cin >> s >> p >> pts;
v[p - 1].push_back(make_pair(pts, s));
}
for (int i = 0; i < m; ++i) {
if (v[i].size()) sort(v[i].begin(), v[i].end(), cmp);
}
for (int i = 0; i < m; ++i) {
if (v[i].size() >= 3 && (v[i][1].first == v[i][2].first))
cout << "?\n";
else
cout << v[i][0].second << ' ' << v[i][1].second << '\n';
}
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
You are given a grid with n rows and m columns, where each cell has a non-negative integer written on it. We say the grid is good if for each cell the following condition holds: if it has a number k > 0 written on it, then exactly k of its neighboring cells have a number greater than 0 written on them. Note that if the number in the cell is 0, there is no such restriction on neighboring cells.
You are allowed to take any number in the grid and increase it by 1. You may apply this operation as many times as you want, to any numbers you want. Perform some operations (possibly zero) to make the grid good, or say that it is impossible. If there are multiple possible answers, you may find any of them.
Two cells are considered to be neighboring if they have a common edge.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 5000) β the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers n and m (2 β€ n, m β€ 300) β the number of rows and columns, respectively.
The following n lines contain m integers each, the j-th element in the i-th line a_{i, j} is the number written in the j-th cell of the i-th row (0 β€ a_{i, j} β€ 10^9).
It is guaranteed that the sum of n β
m over all test cases does not exceed 10^5.
Output
If it is impossible to obtain a good grid, print a single line containing "NO".
Otherwise, print a single line containing "YES", followed by n lines each containing m integers, which describe the final state of the grid. This final grid should be obtainable from the initial one by applying some operations (possibly zero).
If there are multiple possible answers, you may print any of them.
Example
Input
5
3 4
0 0 0 0
0 1 0 0
0 0 0 0
2 2
3 0
0 0
2 2
0 0
0 0
2 3
0 0 0
0 4 0
4 4
0 0 0 0
0 2 0 1
0 0 0 0
0 0 0 0
Output
YES
0 0 0 0
0 1 1 0
0 0 0 0
NO
YES
0 0
0 0
NO
YES
0 1 0 0
1 4 2 1
0 2 0 0
1 3 1 0
Note
In the first test case, we can obtain the resulting grid by increasing the number in row 2, column 3 once. Both of the cells that contain 1 have exactly one neighbor that is greater than zero, so the grid is good. Many other solutions exist, such as the grid
$$$0\;1\;0\;0 0\;2\;1\;0 0\;0\;0\;0$$$
All of them are accepted as valid answers.
In the second test case, it is impossible to make the grid good.
In the third test case, notice that no cell has a number greater than zero on it, so the grid is automatically good.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 323, bs = 500;
const long long inf = 1e9;
int n, m;
long long a[N][N];
void solve() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
int nr = 0;
if (i + 1 <= n) nr += 1;
if (i - 1 >= 1) nr += 1;
if (j + 1 <= m) nr += 1;
if (j - 1 >= 1) nr += 1;
if (nr < a[i][j]) {
cout << "NO\n";
return;
}
a[i][j] = nr;
}
}
cout << "YES\n";
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cout << a[i][j] << " ";
}
cout << "\n";
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T;
cin >> T;
while (T--) {
solve();
}
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
There are N rabbits on a number line. The rabbits are conveniently numbered 1 through N. The coordinate of the initial position of rabbit i is x_i.
The rabbits will now take exercise on the number line, by performing sets described below. A set consists of M jumps. The j-th jump of a set is performed by rabbit a_j (2β€a_jβ€N-1). For this jump, either rabbit a_j-1 or rabbit a_j+1 is chosen with equal probability (let the chosen rabbit be rabbit x), then rabbit a_j will jump to the symmetric point of its current position with respect to rabbit x.
The rabbits will perform K sets in succession. For each rabbit, find the expected value of the coordinate of its eventual position after K sets are performed.
Constraints
* 3β€Nβ€10^5
* x_i is an integer.
* |x_i|β€10^9
* 1β€Mβ€10^5
* 2β€a_jβ€N-1
* 1β€Kβ€10^{18}
Input
The input is given from Standard Input in the following format:
N
x_1 x_2 ... x_N
M K
a_1 a_2 ... a_M
Output
Print N lines. The i-th line should contain the expected value of the coordinate of the eventual position of rabbit i after K sets are performed. The output is considered correct if the absolute or relative error is at most 10^{-9}.
Examples
Input
3
-1 0 2
1 1
2
Output
-1.0
1.0
2.0
Input
3
1 -1 1
2 2
2 2
Output
1.0
-1.0
1.0
Input
5
0 1 3 6 10
3 10
2 3 4
Output
0.0
3.0
7.0
8.0
10.0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int x[100005],a[100005],d[100005],inv[100005],p[100005],tmp[100005],ans[100005],fd[100005];
int main()
{
int n,m;
long long k;
scanf("%d",&n);
for (int i=1;i<=n;i++)
{
scanf("%d",&x[i]);
d[i]=x[i]-x[i-1];
inv[i]=i;
ans[i]=i;
}
scanf("%d%lld",&m,&k);
for (int i=0;i<m;i++)
{
scanf("%d",&a[i]);
swap(inv[a[i]],inv[a[i]+1]);
}
for (int i=1;i<=n;i++)
p[inv[i]]=i;
while (k)
{
if (k%2)
{
for (int i=1;i<=n;i++)
ans[i]=p[ans[i]];
}
for (int i=1;i<=n;i++)
tmp[i]=p[p[i]];
for (int i=1;i<=n;i++)
p[i]=tmp[i];
k/=2;
}
for (int i=1;i<=n;i++)
fd[ans[i]]=d[i];
long long sum=0;
for (int i=1;i<=n;i++)
{
sum+=fd[i];
printf("%lld\n",sum);
}
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Piegirl found the red button. You have one last chance to change the inevitable end.
The circuit under the button consists of n nodes, numbered from 0 to n - 1. In order to deactivate the button, the n nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node i, the next node to be disarmed must be either node (2Β·i) modulo n or node (2Β·i) + 1 modulo n. The last node to be disarmed must be node 0. Node 0 must be disarmed twice, but all other nodes must be disarmed exactly once.
Your task is to find any such order and print it. If there is no such order, print -1.
Input
Input consists of a single integer n (2 β€ n β€ 105).
Output
Print an order in which you can to disarm all nodes. If it is impossible, print -1 instead. If there are multiple orders, print any one of them.
Examples
Input
2
Output
0 1 0
Input
3
Output
-1
Input
4
Output
0 1 3 2 0
Input
16
Output
0 1 2 4 9 3 6 13 10 5 11 7 15 14 12 8 0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int d4[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
template <class T>
void lmax(T& a, const T& b) {
if (a < b) a = b;
}
template <class T>
void lmin(T& a, const T& b) {
if (a > b) a = b;
}
template <class T>
void usort(vector<T>& a) {
sort((a).begin(), (a).end());
a.erase(unique((a).begin(), (a).end()));
}
template <class T>
void operator+=(vector<T>& v, const T& x) {
v.push_back(x);
}
int f[100000];
int root(int x) {
int r = f[x];
while (r != f[r]) r = f[r];
while (x != f[x]) {
int t = f[x];
f[x] = r;
x = t;
}
return r;
}
int main() {
int n;
cin >> n;
if (n & 1) {
cout << -1;
return 0;
}
vector<int> next(n);
for (int i = 0; i < (n); ++i) {
f[i] = i;
}
for (int i = 0; i < (n / 2); ++i) {
int j = i + n / 2;
int p = i * 2 % n;
int q = (i * 2 + 1) % n;
next[i] = p;
next[j] = q;
if (i != p) f[i] = root(p);
if (j != q) f[j] = root(q);
}
for (int i = 0; i < (n / 2); ++i) {
int j = i + n / 2;
if (root(i) != root(j)) {
int p = i * 2 % n;
int q = (i * 2 + 1) % n;
next[i] = q;
next[j] = p;
f[root(i)] = root(j);
}
}
int cur = 0;
while (cur != n / 2) {
cout << cur << ' ';
cur = next[cur];
}
cout << n / 2 << ' ' << 0;
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100000;
int n;
int p[MAX];
vector<int> children[MAX];
int counts[MAX];
double res[MAX];
void dfs1(int v) {
int curr = 1;
for (int i = 0; i < children[v].size(); ++i) {
int u = children[v][i];
dfs1(u);
curr += counts[u];
}
counts[v] = curr;
}
void dfs2(int v) {
int curr = 0;
for (int i = 0; i < children[v].size(); ++i) {
int u = children[v][i];
curr += counts[u];
}
for (int i = 0; i < children[v].size(); ++i) {
int u = children[v][i];
res[u] = res[v] + 1 + (double)(curr - counts[u]) / 2.0;
}
for (int i = 0; i < children[v].size(); ++i) {
int u = children[v][i];
dfs2(u);
}
}
int main(int argc, char* argv[]) {
cin >> n;
p[0] = 0;
for (int i = 1; i < n; ++i) {
int curr;
cin >> curr;
--curr;
p[i] = curr;
children[curr].push_back(i);
}
dfs1(0);
res[0] = 1;
dfs2(0);
for (int i = 0; i < n; ++i) {
cout << res[i] << " ";
}
cout << endl;
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.
Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.
Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
Input
The first line contains two integers n (1 β€ n β€ 100 000) and m (1 β€ m β€ 109) β the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys.
The next line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ 109) β the types of toys that Tanya already has.
Output
In the first line print a single integer k β the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m.
In the second line print k distinct space-separated integers t1, t2, ..., tk (1 β€ ti β€ 109) β the types of toys that Tanya should choose.
If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
Examples
Input
3 7
1 3 4
Output
2
2 5
Input
4 14
4 6 12 8
Output
4
7 2 3 1
Note
In the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
map<int, bool> arr;
vector<int> vc;
int main() {
int i, j, k, tc, r, n, m;
scanf("%d %d", &n, &m);
for (i = 1; i <= n; i++) {
scanf("%d", &tc);
arr[tc] = true;
}
i = 1;
while (m >= i) {
if (!arr[i]) {
vc.push_back(i);
m -= i;
}
i++;
}
int temp = vc.size();
printf("%d\n", temp);
for (i = 0; i < temp; i++) printf("%d ", vc[i]);
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least a minutes to feel refreshed.
Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in b minutes.
Every time Polycarp wakes up, he decides if he wants to sleep for some more time or not. If he's slept for less than a minutes in total, then he sets his alarm to go off in c minutes after it is reset and spends d minutes to fall asleep again. Otherwise, he gets out of his bed and proceeds with the day.
If the alarm goes off while Polycarp is falling asleep, then he resets his alarm to go off in another c minutes and tries to fall asleep for d minutes again.
You just want to find out when will Polycarp get out of his bed or report that it will never happen.
Please check out the notes for some explanations of the example.
Input
The first line contains one integer t (1 β€ t β€ 1000) β the number of testcases.
The only line of each testcase contains four integers a, b, c, d (1 β€ a, b, c, d β€ 10^9) β the time Polycarp has to sleep for to feel refreshed, the time before the first alarm goes off, the time before every succeeding alarm goes off and the time Polycarp spends to fall asleep.
Output
For each test case print one integer. If Polycarp never gets out of his bed then print -1. Otherwise, print the time it takes for Polycarp to get out of his bed.
Example
Input
7
10 3 6 4
11 3 6 4
5 9 4 10
6 5 2 3
1 1 1 1
3947465 47342 338129 123123
234123843 13 361451236 361451000
Output
27
27
9
-1
1
6471793
358578060125049
Note
In the first testcase Polycarp wakes up after 3 minutes. He only rested for 3 minutes out of 10 minutes he needed. So after that he sets his alarm to go off in 6 minutes and spends 4 minutes falling asleep. Thus, he rests for 2 more minutes, totaling in 3+2=5 minutes of sleep. Then he repeats the procedure three more times and ends up with 11 minutes of sleep. Finally, he gets out of his bed. He spent 3 minutes before the first alarm and then reset his alarm four times. The answer is 3+4 β
6 = 27.
The second example is almost like the first one but Polycarp needs 11 minutes of sleep instead of 10. However, that changes nothing because he gets 11 minutes with these alarm parameters anyway.
In the third testcase Polycarp wakes up rested enough after the first alarm. Thus, the answer is b=9.
In the fourth testcase Polycarp wakes up after 5 minutes. Unfortunately, he keeps resetting his alarm infinitely being unable to rest for even a single minute :(
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
long long a, b, c, d, total;
cin >> a >> b >> c >> d;
if (b >= a)
cout << b << "\n";
else {
long long f = c - d;
if (f <= 0)
cout << -1 << "\n";
else {
total = ((a - b) + f - 1) / f;
total = (total * c) + b;
cout << total << "\n";
}
}
}
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers.
A common divisor for two positive numbers is a number which both numbers are divisible by.
But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low β€ d β€ high. It is possible that there is no common divisor in the given range.
You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query.
Input
The first line contains two integers a and b, the two integers as described above (1 β€ a, b β€ 109). The second line contains one integer n, the number of queries (1 β€ n β€ 104). Then n lines follow, each line contains one query consisting of two integers, low and high (1 β€ low β€ high β€ 109).
Output
Print n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query.
Examples
Input
9 27
3
1 5
10 11
9 11
Output
3
-1
9
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a, b, q, i, j;
scanf("%d %d", &a, &b);
set<int> s1, s2;
for (i = 1; i * i <= a; i++) {
if (a % i == 0) {
s1.insert(i);
s1.insert(a / i);
}
}
for (i = 1; i * i <= b; i++) {
if (b % i == 0) {
int bil1 = i, bil2 = b / i;
if (s1.count(bil1)) {
s2.insert(bil1);
}
if (s1.count(bil2)) {
s2.insert(bil2);
}
}
}
set<int>::iterator it;
int arr[100000];
int cnt = 0;
for (it = s2.begin(); it != s2.end(); it++) {
arr[cnt] = *it;
cnt++;
}
scanf("%d", &q);
while (q--) {
int depan, belakang;
scanf("%d %d", &depan, &belakang);
int idx = lower_bound(arr, arr + cnt, belakang) - arr;
if (idx == cnt) {
idx--;
}
if (arr[idx] > belakang) {
idx--;
}
if (idx < 0) {
printf("-1\n");
} else {
if (arr[idx] < depan) {
printf("-1\n");
} else {
printf("%d\n", arr[idx]);
}
}
}
return 0;
};
``` |
### Prompt
Please formulate a cpp solution to the following problem:
There is a string s of length 3 or greater. No two neighboring characters in s are equal.
Takahashi and Aoki will play a game against each other. The two players alternately performs the following operation, Takahashi going first:
* Remove one of the characters in s, excluding both ends. However, a character cannot be removed if removal of the character would result in two neighboring equal characters in s.
The player who becomes unable to perform the operation, loses the game. Determine which player will win when the two play optimally.
Constraints
* 3 β€ |s| β€ 10^5
* s consists of lowercase English letters.
* No two neighboring characters in s are equal.
Input
The input is given from Standard Input in the following format:
s
Output
If Takahashi will win, print `First`. If Aoki will win, print `Second`.
Examples
Input
aba
Output
Second
Input
abc
Output
First
Input
abcab
Output
First
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;
int main(){
string s;
cin>>s;
cout<<(s.size()%2==(s[0]==s[s.size()-1])?"Second":"First");
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Write a program to simulate rolling a dice, which can be constructed by the following net.
<image>
<image>
As shown in the figures, each face is identified by a different label from 1 to 6.
Write a program which reads integers assigned to each face identified by the label and a sequence of commands to roll the dice, and prints the integer on the top face. At the initial state, the dice is located as shown in the above figures.
Constraints
* $0 \leq $ the integer assigned to a face $ \leq 100$
* $0 \leq $ the length of the command $\leq 100$
Input
In the first line, six integers assigned to faces are given in ascending order of their corresponding labels.
In the second line, a string which represents a sequence of commands, is given. The command is one of 'E', 'N', 'S' and 'W' representing four directions shown in the above figures.
Output
Print the integer which appears on the top face after the simulation.
Examples
Input
1 2 4 8 16 32
SE
Output
8
Input
1 2 4 8 16 32
EESWN
Output
32
### Response
```cpp
#include<iostream>
using namespace std;
struct Dice{
int s[6];
void roll(char c){
int b;
if(c=='E'){
b=s[0];
s[0]=s[3];
s[3]=s[5];
s[5]=s[2];
s[2]=b;
}
if(c=='W'){
b=s[0];
s[0]=s[2];
s[2]=s[5];
s[5]=s[3];
s[3]=b;
}
if(c=='N'){
b=s[0];
s[0]=s[1];
s[1]=s[5];
s[5]=s[4];
s[4]=b;
}
if(c=='S'){
b=s[0];
s[0]=s[4];
s[4]=s[5];
s[5]=s[1];
s[1]=b;
}
}
int top() {
return s[0];
}
};
int main(){
Dice d;
for(int i=0;i<6;i++) cin >> d.s[i];
string s;cin >> s;
for(int i=0;i<s.size();i++) d.roll(s[i]);
cout << d.top() << endl;
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Problem statement
N first-year students of the Faculty of Information Science and Technology of R University take the final exam of the lecture called Programming Exercise 1. The test is a perfect score of m. In other words, the score that one student can get is an integer between 0 and m.
Since the teacher in charge is nasty, I am concerned about the score distribution that maximizes the difference between the average value and the median value. Output one such way of scoring.
Note: The average value is the sum of the points divided by n, and the median is the (n + 1) / second (1 β indexed) from the front if n is an odd number when the points are arranged in ascending order. If it is an even number, it is the score obtained by adding the n / 2nd and n / 2 + 1th scores from the front and dividing by 2.
input
n \ m
Constraint
* An integer
* 1 β€ n β€ 100
* 1 β€ m β€ 100
output
Output the n-point column of the answer on a single line separated by spaces, and finally output a line break. If there are multiple types, any one can be output.
sample
Sample input 1
3 100
Sample output 1
0 0 100
100 \ 100 \ 0 etc. are also correct answers.
Sample input 2
1 100
Sample output 2
50
Example
Input
3 100
Output
0 0 100
### Response
```cpp
#include <bits/stdc++.h>
#define ALL(a) (a).begin(), (a).end()
#define llong long long
using namespace std;
signed main(){
int n,m;
cin >> n >> m;
int mid = (n&1) ? (n+1)/2 : n/2+1;
vector<int> a;
for(int i = 0; i < mid; i++){
a.push_back(0);
}
for(int i = 0; i < n-mid; i++){
a.push_back(m);
}
for(size_t i = 0; i < a.size(); i++){
cout << a[i];
if(i != a.size() -1)cout << " ";
}
cout << endl;
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
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 β€ 2 β
10^5) β the number of queries. Then q queries follow.
The first line of the query contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β 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 2 β
10^5 (β n β€ 2 β
10^5).
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() {
long long int q;
cin >> q;
while (q--) {
long long int n, k;
cin >> n >> k;
string s;
cin >> s;
string s1 = "RGB", s2 = "GBR", s3 = "BRG";
long long int x1 = 0, x2 = 0, x3 = 0;
long long int jj = 0;
for (long long int i = 0; i < k; i++) {
if (s[i] != s1[i % 3]) {
x1++;
}
if (s[i] != s2[i % 3]) {
x2++;
}
if (s[i] != s3[i % 3]) {
x3++;
}
}
long long int mn = min(x1, min(x2, x3));
jj = 0;
for (long long int i = 1; i <= s.length() - k; i++) {
if (s[i - 1] != s1[(i - 1) % 3]) {
if (x1 > 0) x1--;
}
if (s[i + k - 1] != s1[(i + k - 1) % 3]) x1++;
if (s[i - 1] != s2[(i - 1) % 3]) {
if (x2 > 0) x2--;
}
if (s[i + k - 1] != s2[(i + k - 1) % 3]) x2++;
if (s[i - 1] != s3[(i - 1) % 3]) {
if (x3 > 0) x3--;
}
if (s[(i + k - 1)] != s3[(i + k - 1) % 3]) x3++;
mn = min(mn, min(x1, min(x2, x3)));
}
cout << mn << endl;
}
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Let's call a string "s-palindrome" if it is symmetric about the middle of the string. For example, the string "oHo" is "s-palindrome", but the string "aa" is not. The string "aa" is not "s-palindrome", because the second half of it is not a mirror reflection of the first half.
<image> English alphabet
You are given a string s. Check if the string is "s-palindrome".
Input
The only line contains the string s (1 β€ |s| β€ 1000) which consists of only English letters.
Output
Print "TAK" if the string s is "s-palindrome" and "NIE" otherwise.
Examples
Input
oXoxoXo
Output
TAK
Input
bod
Output
TAK
Input
ER
Output
NIE
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long double epsilon = 1e-9;
const long long MOD = 1e9 + 7;
bool comp(long long a, long long b) { return (a > b); }
long long binpow(long long a, long long b) {
long long res = 1;
while (b > 0) {
if (b & 1) res *= a;
a = a * a;
b >>= 1;
}
return res;
}
bool isSPalin(string s) {
long long i = 0, j = s.length() - 1;
bool flag = 1;
while (i <= j) {
if (s[i] == 'b') {
if (s[j] != 'd') {
flag = 0;
break;
}
} else if (s[i] == 'd') {
if (s[j] != 'b') {
flag = 0;
break;
}
} else if (s[i] == 'p') {
if (s[j] != 'q') {
flag = 0;
break;
}
} else if (s[i] == 'q') {
if (s[j] != 'p') {
flag = 0;
break;
}
} else if (s[i] == 'A' || s[i] == 'H' || s[i] == 'I' || s[i] == 'M' ||
s[i] == 'O' || s[i] == 'T' || s[i] == 'U' || s[i] == 'V' ||
s[i] == 'W' || s[i] == 'X' || s[i] == 'Y' || s[i] == 'o' ||
s[i] == 'v' || s[i] == 'w' || s[i] == 'x') {
if (s[j] != s[i]) {
flag = 0;
break;
}
} else {
flag = 0;
break;
}
i++;
j--;
}
return flag;
}
void runcase() {
string s;
cin >> s;
if (isSPalin(s))
cout << "TAK\n";
else
cout << "NIE\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.precision(10);
long long tests = 1;
while (tests--) {
runcase();
}
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
You have array a1, a2, ..., an. Segment [l, r] (1 β€ l β€ r β€ n) is good if ai = ai - 1 + ai - 2, for all i (l + 2 β€ i β€ r).
Let's define len([l, r]) = r - l + 1, len([l, r]) is the length of the segment [l, r]. Segment [l1, r1], is longer than segment [l2, r2], if len([l1, r1]) > len([l2, r2]).
Your task is to find a good segment of the maximum length in array a. Note that a segment of length 1 or 2 is always good.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of elements in the array. The second line contains integers: a1, a2, ..., an (0 β€ ai β€ 109).
Output
Print the length of the longest good segment in array a.
Examples
Input
10
1 2 3 5 8 13 21 34 55 89
Output
10
Input
5
1 1 1 1 1
Output
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long a[100005];
int n;
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%I64d", &a[i]);
int ans = 0, sum = 2;
if (n >= 2)
ans = 2;
else if (n >= 1)
ans = 1;
for (int i = 2; i < n; i++) {
if (a[i] == a[i - 1] + a[i - 2])
sum++;
else
sum = 2;
ans = max(ans, sum);
}
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
D: Indecision-Indecision-
problem
Ebi-chan has been addicted to gal games lately, and her goal now is to capture two heroines at the same time.
Ebi-chan can use several events to increase her liking from the heroine, but only one heroine can be selected for each event. However, Ebi-chan does not forget to follow the heroine that she did not choose, so the liking from the other heroine can be increased to some extent. However, not all events can be done because events are expensive.
By the way, indecisive Ebi-chan is wondering which heroine to perform each event with (or neither). Ebi-chan thinks that it is meaningless if only one heroine has a high liking, but the other has a low liking, so the ideal choice is to maximize the liking from the heroine who does not have a high liking.
At this time, find the maximum value of the liking from the heroine who does not have the high liking. In other words, as a result of selecting the event and the target heroine, find the maximum value that can be considered as min \\ {A, B \\} when the favorability from the two heroines is A and B, respectively. Here, the total cost of the event you decide to do must not exceed your budget. Also, the initial value of favorability from each heroine is 0.
Input format
N C
a_1 b_1 c_1
...
a_N b_N c_N
The first line gives the number of candidate events N and the budget C, separated by blanks.
Line 1 + i (1 \ leq i \ leq N) contains the increment of favorability a_i of the heroine doing it, the increment of favorability b_i of the other heroine, and the cost c_i for the i-th event. Given with a space delimiter.
Constraint
* 1 \ leq N \ leq 100
* 1 \ leq C \ leq 100
* 1 \ leq b_i <a_i \ leq 100
* 1 \ leq c_i \ leq 100
Output format
Under the ideal selection in the question sentence, output the maximum value of the liking from the heroine who does not have the high liking in one line.
Input example 1
3 4
3 2 2
2 1 1
2 1 1
Output example 1
Five
It's best to have the first two events with one heroine and the last event with the other heroine.
Input example 2
3 3
3 2 2
2 1 1
2 1 1
Output example 2
Four
Example
Input
3 4
3 2 2
2 1 1
2 1 1
Output
5
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int dp[2][101][10001],a[100],b[100],c[100];
int main(){
int n,d;
cin>>n>>d;
for(int i=0;i<n;i++)
cin>>a[i]>>b[i]>>c[i];
for(int i=0;i<=100;i++)
for(int j=0;j<=10000;j++)
dp[0][i][j]=dp[1][i][j]=-1e9;
dp[0][0][0]=0;
for(int i=0;i<n;i++){
for(int j=0;j<=d;j++)
for(int k=0;k<=10000;k++){
if(j+c[i]<=d&&k+a[i]<=10000)
dp[(i+1)%2][j+c[i]][k+a[i]]=
max(dp[(i+1)%2][j+c[i]][k+a[i]],dp[i%2][j][k]+b[i]);
if(j+c[i]<=d&&k+b[i]<=10000)
dp[(i+1)%2][j+c[i]][k+b[i]]=
max(dp[(i+1)%2][j+c[i]][k+b[i]],dp[i%2][j][k]+a[i]);
dp[(i+1)%2][j][k]=max(dp[(i+1)%2][j][k],dp[i%2][j][k]);
}
for(int j=0;j<=100;j++)
for(int k=0;k<=10000;k++)dp[i%2][j][k]=-1e9;
}
int ans=0;
for(int i=0;i<=d;i++)
for(int j=0;j<=10000;j++){
ans=max(ans,min(j,dp[n%2][i][j]));
}
cout<<ans<<endl;
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
You are fed up with your messy room, so you decided to clean it up.
Your room is a bracket sequence s=s_{1}s_{2}... s_{n} of length n. Each character of this string is either an opening bracket '(' or a closing bracket ')'.
In one operation you can choose any consecutive substring of s and reverse it. In other words, you can choose any substring s[l ... r]=s_l, s_{l+1}, ..., s_r and change the order of elements in it into s_r, s_{r-1}, ..., s_{l}.
For example, if you will decide to reverse substring s[2 ... 4] of string s="((()))" it will be equal to s="()(())".
A regular (aka balanced) bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.
A prefix of a string s is a substring that starts at position 1. For example, for s="(())()" there are 6 prefixes: "(", "((", "(()", "(())", "(())(" and "(())()".
In your opinion, a neat and clean room s is a bracket sequence that:
* the whole string s is a regular bracket sequence;
* and there are exactly k prefixes of this sequence which are regular (including whole s itself).
For example, if k = 2, then "(())()" is a neat and clean room.
You want to use at most n operations to make your room neat and clean. Operations are applied one after another sequentially.
It is guaranteed that the answer exists. Note that you do not need to minimize the number of operations: find any way to achieve the desired configuration in n or less operations.
Input
The first line contains integer number t (1 β€ t β€ 100) β the number of test cases in the input. Then t test cases follow.
The first line of a test case contains two integers n and k (1 β€ k β€ n/2, 2 β€ n β€ 2000, n is even) β length of s and required number of regular prefixes.
The second line of a test case contains s of length n β the given bracket sequence. It contains only '(' and ')'.
It is guaranteed that there are exactly n/2 characters '(' and exactly n/2 characters ')' in the given string.
The sum of all values n over all the test cases in the input doesn't exceed 2000.
Output
For each test case print an answer.
In the first line print integer m (0 β€ m β€ n) β the number of operations. You do not need to minimize m, any value is suitable.
In the following m lines print description of the operations, each line should contain two integers l,r (1 β€ l β€ r β€ n), representing single reverse operation of s[l ... r]=s_{l}s_{l+1}... s_{r}. Operations are applied one after another sequentially.
The final s after all operations should be a regular, also it should be exactly k prefixes (including s) which are regular.
It is guaranteed that the answer exists. If there are several possible answers you can print any.
Example
Input
4
8 2
()(())()
10 3
))()()()((
2 1
()
2 1
)(
Output
4
3 4
1 1
5 8
2 2
3
4 10
1 4
6 7
0
1
1 2
Note
In the first example, the final sequence is "()(()())", where two prefixes are regular, "()" and "()(()())". Note, that all the operations except "5 8" in the example output are useless (they do not change s).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long int inf = 1e18;
const long long int mod = 1e9 + 7;
inline long long int add(long long int x, long long int y) {
x += y;
if (x >= mod) x -= mod;
return x;
}
inline long long int sub(long long int x, long long int y) {
x -= y;
if (x < 0) x += mod;
return x;
}
inline long long int mul(long long int x, long long int y) {
return ((x % mod) * (y % mod)) % mod;
}
inline long long int gcd(long long int x, long long int y) {
return x == 0 ? y : gcd(y % x, x);
}
inline long long int power(long long int a, long long int b) {
long long int x = 1;
while (b) {
if (b & 1) x = mul(x, a);
a = mul(a, a);
b >>= 1;
}
return x;
}
inline long long int inv(long long int a) { return power(a, mod - 2); }
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
string s, t = "";
cin >> s;
for (int i = 0; i < k - 1; i++) t += "()";
for (int i = 0; i < n / 2 + 1 - k; i++) t += "(";
for (int i = 0; i < n / 2 + 1 - k; i++) t += ")";
vector<pair<int, int> > moves;
for (int i = 0; i < n; i++) {
if (s[i] != t[i]) {
for (int j = i + 1; j < n; j++) {
if (s[j] == t[i]) {
moves.push_back({i + 1, j + 1});
reverse(s.begin() + i, s.begin() + j + 1);
break;
}
}
}
}
cout << (int)moves.size() << "\n";
for (auto x : moves) cout << x.first << " " << x.second << "\n";
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Joisino has a bar of length N, which has M marks on it. The distance from the left end of the bar to the i-th mark is X_i.
She will place several squares on this bar. Here, the following conditions must be met:
* Only squares with integral length sides can be placed.
* Each square must be placed so that its bottom side touches the bar.
* The bar must be completely covered by squares. That is, no square may stick out of the bar, and no part of the bar may be left uncovered.
* The boundary line of two squares may not be directly above a mark.
<image>
Examples of arrangements that satisfy/violate the conditions
The beauty of an arrangement of squares is defined as the product of the areas of all the squares placed. Joisino is interested in the sum of the beauty over all possible arrangements that satisfy the conditions. Write a program to find it. Since it can be extremely large, print the sum modulo 10^9+7.
Constraints
* All input values are integers.
* 1 \leq N \leq 10^9
* 0 \leq M \leq 10^5
* 1 \leq X_1 < X_2 < ... < X_{M-1} < X_M \leq N-1
Input
Input is given from Standard Input in the following format:
N M
X_1 X_2 ... X_{M-1} X_M
Output
Print the sum of the beauty over all possible arrangements that satisfy the conditions, modulo 10^9+7.
Examples
Input
3 1
2
Output
13
Input
5 2
2 3
Output
66
Input
10 9
1 2 3 4 5 6 7 8 9
Output
100
Input
1000000000 0
Output
693316425
### Response
```cpp
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<iostream>
const long long mod=1000000007;
using namespace std;
long long pos[100003];
long long n,m;
struct node{
long long x[3][3];
inline void operator *=(const node &a){
long long c[3][3];
c[0][0]=c[0][1]=c[0][2]=0;
c[1][0]=c[1][1]=c[1][2]=0;
c[2][0]=c[2][1]=c[2][2]=0;
for(int i=0;i<=2;i++){
for(int j=0;j<=2;j++){
for(int k=0;k<=2;k++){
c[i][j]=(c[i][j]+x[i][k]*a.x[k][j]%mod)%mod;
}
}
}
for(int i=0;i<=2;i++){
for(int j=0;j<=2;j++){
x[i][j]=c[i][j];
}
}
}
}e,a,e1,e2;
inline void fsp(node &x,node y,long long t){
node y1=y;
for(;t;t>>=1){
if(t&1){
x*=y1;
}
y1*=y1;
}
}
long long A[3],B[3];
int main(){
cin>>n>>m;
for(int i=1;i<=m;i++){
cin>>pos[i];
}
e.x[0][0]=e.x[1][1]=e.x[2][2]=e.x[1][2]=e.x[0][2]=1;
e.x[0][1]=2;
e2.x[0][0]=e2.x[1][1]=e2.x[2][2]=e2.x[2][0]=1;
e1=e;
e1*=e2;
m++;
pos[m]=n;
B[0]=1;
for(int l=1;l<=m;l++){
int s=pos[l]-pos[l-1]-1;
a.x[0][0]=1,a.x[0][1]=0,a.x[0][2]=0;
a.x[1][0]=0,a.x[1][1]=1,a.x[1][2]=0;
a.x[2][0]=0,a.x[2][1]=0,a.x[2][2]=1;
fsp(a,e1,s);
a*=e;
for(int i=0;i<=2;i++){
A[i]=0;
for(int j=0;j<=2;j++){
A[i]=(A[i]+B[j]*a.x[j][i]%mod)%mod;
}
}
for(int i=0;i<=2;i++){
B[i]=A[i];
}
}
cout<<B[2]<<endl;
return 0;
}
/*
in:
10 9
1 2 3 4 5 6 7 8 9
out:
100
*/
//f[i][0]=f[i-1][0];
//f[i][1]=f[i-1][0]+f[i-1][1];
//f[i][2]=2*f[i-1][1]+f[i-1][2]+f[i-1][0]; i-1ε°iζ ιζΏ
//f[i][0]=f[i-1][2];
//f[i][1]=f[i-1][2];
//f[i][2]=f[i-1][2]; i-1ε°iζιζΏ
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Let N be a positive odd number.
There are N coins, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), when Coin i is tossed, it comes up heads with probability p_i and tails with probability 1 - p_i.
Taro has tossed all the N coins. Find the probability of having more heads than tails.
Constraints
* N is an odd number.
* 1 \leq N \leq 2999
* p_i is a real number and has two decimal places.
* 0 < p_i < 1
Input
Input is given from Standard Input in the following format:
N
p_1 p_2 \ldots p_N
Output
Print the probability of having more heads than tails. The output is considered correct when the absolute error is not greater than 10^{-9}.
Examples
Input
3
0.30 0.60 0.80
Output
0.612
Input
1
0.50
Output
0.5
Input
5
0.42 0.01 0.42 0.99 0.42
Output
0.3821815872
### Response
```cpp
// I - Coins
#include <bits/stdc++.h>
using namespace std;
using dl = double;
dl dp[2999+2];
int main(){
int N; scanf("%d",&N);
int C = (N+1)/2;
dp[1] = 1.;
for(int lv=1; lv<=N; lv++){
dl p; scanf("%lf",&p);
dl q = 1.-p;
int e = max(1, lv-C+2);
for(int i=lv+1; i>=e; i--) dp[i] = q*dp[i] + p*dp[i-1];
}
dl a = 0; for(int i=N+1; i>C; i--) a += dp[i];
printf("%.10g\n",a);
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
There are N towns in the State of Atcoder, connected by M bidirectional roads.
The i-th road connects Town A_i and B_i and has a length of C_i.
Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in this order).
She will fly to the first town she visits, and fly back from the last town she visits, but for the rest of the trip she will have to travel by road.
If she visits the towns in the order that minimizes the distance traveled by road, what will that distance be?
Constraints
* 2β€Nβ€200
* 1β€Mβ€NΓ(N-1)/2
* 2β€Rβ€min(8,N) (min(8,N) is the smaller of 8 and N.)
* r_iβ r_j (iβ j)
* 1β€A_i,B_iβ€N, A_iβ B_i
* (A_i,B_i)β (A_j,B_j),(A_i,B_i)β (B_j,A_j) (iβ j)
* 1β€C_iβ€100000
* Every town can be reached from every town by road.
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M R
r_1 ... r_R
A_1 B_1 C_1
:
A_M B_M C_M
Output
Print the distance traveled by road if Joisino visits the towns in the order that minimizes it.
Examples
Input
3 3 3
1 2 3
1 2 1
2 3 1
3 1 4
Output
2
Input
3 3 2
1 3
2 3 2
1 3 6
1 2 2
Output
4
Input
4 6 3
2 3 4
1 2 4
2 3 3
4 3 1
1 4 1
4 2 2
3 1 6
Output
3
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
ll n, m, r; cin >> n >> m >> r;
ll dp[n][n];
for(ll i = 0; i < n; ++i)
for(ll j = 0; j < n; ++j)dp[i][j] = (i == j ? 0 : 1145141919);
vector<ll> rr;
for(ll i = 0; i < r; ++i){
ll a; cin >> a;
rr.push_back(--a);
}
sort(rr.begin(), rr.end());
for(ll i = 0; i < m; ++i){
ll a, b; cin >> a >> b;
cin >> dp[--a][--b];
dp[b][a] = dp[a][b];
}
for(ll i = 0; i < n; ++i)
for(ll j = 0; j < n; ++j)
for(ll k = 0; k < n; ++k) dp[j][k] = min(dp[j][k], dp[j][i] + dp[i][k]);
ll ans = 1145141919;
do{
ll dist = 0;
for(ll i = 0; i < rr.size() - 1; ++i) dist += dp[rr[i]][rr[i + 1]];
ans = min(dist, ans);
}while(next_permutation(rr.begin(), rr.end()));
cout << ans << endl;
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Snuke has N strings. The i-th string is s_i.
Let us concatenate these strings into one string after arranging them in some order. Find the maximum possible number of occurrences of `AB` in the resulting string.
Constraints
* 1 \leq N \leq 10^{4}
* 2 \leq |s_i| \leq 10
* s_i consists of uppercase English letters.
Input
Input is given from Standard Input in the following format:
N
s_1
\vdots
s_N
Output
Print the answer.
Examples
Input
3
ABCA
XBAZ
BAD
Output
2
Input
9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA
Output
4
Input
7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA
Output
4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
int ans = 0;
int ba = 0;
int b = 0;
int a = 0;
for (int i = 0; i < n; i++)
{
string s;
cin >> s;
for (int j = 0; j < s.size()-1; j++)
{
if(s[j]=='A'&&s[j+1]=='B') ans++;
}
if(s[0]=='B'&&s[s.size()-1]=='A') ba++;
else if (s[0]=='B') b++;
else if (s[s.size()-1]=='A') a++;
}
if(ba==0){
ans+=min(a,b);
}
else{
if(a+b>0){
ans+=ba+min(a,b);
}
else{
ans+=ba-1;
}
}
cout << ans << endl;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Alice, Bob and Charlie are playing Card Game for Three, as below:
* At first, each of the three players has a deck consisting of some number of cards. Alice's deck has N cards, Bob's deck has M cards, and Charlie's deck has K cards. Each card has a letter `a`, `b` or `c` written on it. The orders of the cards in the decks cannot be rearranged.
* The players take turns. Alice goes first.
* If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says `a`, Alice takes the next turn.)
* If the current player's deck is empty, the game ends and the current player wins the game.
There are 3^{N+M+K} possible patters of the three player's initial decks. Among these patterns, how many will lead to Alice's victory?
Since the answer can be large, print the count modulo 1\,000\,000\,007 (=10^9+7).
Constraints
* 1 \leq N \leq 3Γ10^5
* 1 \leq M \leq 3Γ10^5
* 1 \leq K \leq 3Γ10^5
Input
The input is given from Standard Input in the following format:
N M K
Output
Print the answer modulo 1\,000\,000\,007 (=10^9+7).
Examples
Input
1 1 1
Output
17
Input
4 2 2
Output
1227
Input
1000 1000 1000
Output
261790852
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define re register
#define gc getchar
#define pc putchar
#define cs const
cs ll mod=1000000007;
ll fac[1000001]={1,1},inv[1000001]={1,1},ifac[1000001]={1,1};
inline
ll C(int n,int m){
return fac[n]*ifac[m]%mod*ifac[n-m]%mod;
}
int n,m,k,maxn;
signed main(){
for(int re i=2;i<=1000000;++i)
fac[i]=fac[i-1]*i%mod,
inv[i]=(mod-mod/i)*inv[mod%i]%mod,
ifac[i]=ifac[i-1]*inv[i]%mod;
scanf("%d%d%d",&n,&m,&k);
--n;
maxn=max(n,m+k);
ll sum=1,ans=1;
for(int re i=1;i<=m+k;++i){
sum=(sum*2+mod)%mod;
if(i>m)sum=(sum+mod-C(i-1,m))%mod;
if(i>k)sum=(sum+mod-C(i-1,k))%mod;
ans=ans*3%mod;
ans=(ans+C(n+i,i)*sum%mod)%mod;
}
cout<<(ans%mod+mod)%mod;
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art.
The main exhibit is a construction of n matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from 1 to n. A matryoshka with a smaller number can be nested in a matryoshka with a higher number, two matryoshkas can not be directly nested in the same doll, but there may be chain nestings, for example, 1 β 2 β 4 β 5.
In one second, you can perform one of the two following operations:
* Having a matryoshka a that isn't nested in any other matryoshka and a matryoshka b, such that b doesn't contain any other matryoshka and is not nested in any other matryoshka, you may put a in b;
* Having a matryoshka a directly contained in matryoshka b, such that b is not nested in any other matryoshka, you may get a out of b.
According to the modern aesthetic norms the matryoshka dolls on display were assembled in a specific configuration, i.e. as several separate chains of nested matryoshkas, but the criminal, following the mysterious plan, took out all the dolls and assembled them into a single large chain (1 β 2 β ... β n). In order to continue the investigation Andrewid needs to know in what minimum time it is possible to perform this action.
Input
The first line contains integers n (1 β€ n β€ 105) and k (1 β€ k β€ 105) β the number of matryoshkas and matryoshka chains in the initial configuration.
The next k lines contain the descriptions of the chains: the i-th line first contains number mi (1 β€ mi β€ n), and then mi numbers ai1, ai2, ..., aimi β the numbers of matryoshkas in the chain (matryoshka ai1 is nested into matryoshka ai2, that is nested into matryoshka ai3, and so on till the matryoshka aimi that isn't nested into any other matryoshka).
It is guaranteed that m1 + m2 + ... + mk = n, the numbers of matryoshkas in all the chains are distinct, in each chain the numbers of matryoshkas follow in the ascending order.
Output
In the single line print the minimum number of seconds needed to assemble one large chain from the initial configuration.
Examples
Input
3 2
2 1 2
1 3
Output
1
Input
7 3
3 1 3 7
2 2 5
2 4 6
Output
10
Note
In the first sample test there are two chains: 1 β 2 and 3. In one second you can nest the first chain into the second one and get 1 β 2 β 3.
In the second sample test you need to disassemble all the three chains into individual matryoshkas in 2 + 1 + 1 = 4 seconds and then assemble one big chain in 6 seconds.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
while (cin >> n >> k) {
vector<int> pieces(k);
for (int i = 0; i < k; ++i) {
int m;
cin >> m;
vector<int> doll(m);
for (int j = 0; j < m; ++j) {
cin >> doll[j];
}
if (doll[0] == 1) {
int j = 0;
while (j < m and doll[j] == j + 1) ++j;
pieces[i] = m - j + 1;
} else {
pieces[i] = m;
}
}
int res = 0;
for (int i = 0; i < k; ++i) {
res += pieces[i] * 2 - 1;
}
res -= 1;
cout << res << endl;
}
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix a with n lines and m columns. Let number a[i][j] represents the calories burned by performing workout at the cell of gym in the i-th line and the j-th column.
Iahub starts with workout located at line 1 and column 1. He needs to finish with workout a[n][m]. After finishing workout a[i][j], he can go to workout a[i + 1][j] or a[i][j + 1]. Similarly, Iahubina starts with workout a[n][1] and she needs to finish with workout a[1][m]. After finishing workout from cell a[i][j], she goes to either a[i][j + 1] or a[i - 1][j].
There is one additional condition for their training. They have to meet in exactly one cell of gym. At that cell, none of them will work out. They will talk about fast exponentiation (pretty odd small talk) and then both of them will move to the next workout.
If a workout was done by either Iahub or Iahubina, it counts as total gain. Please plan a workout for Iahub and Iahubina such as total gain to be as big as possible. Note, that Iahub and Iahubina can perform workouts with different speed, so the number of cells that they use to reach meet cell may differs.
Input
The first line of the input contains two integers n and m (3 β€ n, m β€ 1000). Each of the next n lines contains m integers: j-th number from i-th line denotes element a[i][j] (0 β€ a[i][j] β€ 105).
Output
The output contains a single number β the maximum total gain possible.
Examples
Input
3 3
100 100 100
100 1 100
100 100 100
Output
800
Note
Iahub will choose exercises a[1][1] β a[1][2] β a[2][2] β a[3][2] β a[3][3]. Iahubina will choose exercises a[3][1] β a[2][1] β a[2][2] β a[2][3] β a[1][3].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long N = 1e3 + 5;
long long n, m;
long long a[N][N];
long long dp1[N][N];
long long dp2[N][N];
long long dp3[N][N];
long long dp4[N][N];
void solve() {
cin >> n >> m;
for (long long i = 1; i <= n; i++) {
for (long long j = 1; j <= m; j++) {
cin >> a[i][j];
}
}
for (long long i = 1; i <= n; i++) {
for (long long j = 1; j <= m; j++) {
dp1[i][j] = a[i][j] + max(dp1[i - 1][j], dp1[i][j - 1]);
}
}
for (long long i = n; i >= 1; i--) {
for (long long j = m; j >= 1; j--) {
dp2[i][j] = a[i][j] + max(dp2[i + 1][j], dp2[i][j + 1]);
}
}
for (long long i = n; i >= 1; i--) {
for (long long j = 1; j <= m; j++) {
dp3[i][j] = a[i][j] + max(dp3[i + 1][j], dp3[i][j - 1]);
}
}
for (long long i = 1; i <= n; i++) {
for (long long j = m; j >= 1; j--) {
dp4[i][j] = a[i][j] + max(dp4[i - 1][j], dp4[i][j + 1]);
}
}
long long ans = 0;
for (long long i = 2; i < n; i++) {
for (long long j = 2; j < m; j++) {
ans = max(ans,
dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j]);
ans = max(ans,
dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1]);
}
}
cout << ans;
}
int32_t main() {
long long tst = 1;
while (tst--) solve();
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
There is a string S consisting of digits `1`, `2`, ..., `9`. Lunlun, the Dachshund, will take out three consecutive digits from S, treat them as a single integer X and bring it to her master. (She cannot rearrange the digits.)
The master's favorite number is 753. The closer to this number, the better. What is the minimum possible (absolute) difference between X and 753?
Constraints
* S is a string of length between 4 and 10 (inclusive).
* Each character in S is `1`, `2`, ..., or `9`.
Input
Input is given from Standard Input in the following format:
S
Output
Print the minimum possible difference between X and 753.
Examples
Input
1234567876
Output
34
Input
35753
Output
0
Input
1111111111
Output
642
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
long ans=1000;
cin >> s;
for(int i=0;i<s.size()-2;i++) {
long x=(s[i]-'0')*100+(s[i+1]-'0')*10+(s[i+2]-'0');
ans=min(ans,max(x-753,753-x));
}
cout << ans << endl;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Every day, N passengers arrive at Takahashi Airport. The i-th passenger arrives at time T_i.
Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers. Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport. Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane. For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).
When setting the departure times for buses under this condition, find the minimum required number of buses. Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.
Constraints
* 2 \leq N \leq 100000
* 1 \leq C \leq 10^9
* 1 \leq K \leq 10^9
* 1 \leq T_i \leq 10^9
* C, K and T_i are integers.
Input
The input is given from Standard Input in the following format:
N C K
T_1
T_2
:
T_N
Output
Print the minimum required number of buses.
Examples
Input
5 3 5
1
2
3
6
12
Output
3
Input
6 3 3
7
6
2
8
10
6
Output
3
### Response
```cpp
#include <iostream>
#include <algorithm>
using namespace std;
const int nmax=100005;
int t[nmax];
int n,c,k,lst,ans,i;
int main()
{
cin>>n>>c>>k;
for(i=1;i<=n;i++)
{
cin>>t[i];
}
sort(t+1,t+n+1);
lst=1;ans=1;
for(i=2;i<=n;i++)
{
if(t[i]-t[lst]>k||i-lst+1>c)
{
lst=i;
ans+=1;
}
}
cout<<ans;
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
After the Search Ultimate program that searched for strings in a text failed, Igor K. got to think: "Why on Earth does my program work so slowly?" As he double-checked his code, he said: "My code contains no errors, yet I know how we will improve Search Ultimate!" and took a large book from the shelves. The book read "Azembler. Principally New Approach".
Having carefully thumbed through the book, Igor K. realised that, as it turns out, you can multiply the numbers dozens of times faster. "Search Ultimate will be faster than it has ever been!" β the fellow shouted happily and set to work.
Let us now clarify what Igor's idea was. The thing is that the code that was generated by a compiler was far from perfect. Standard multiplying does work slower than with the trick the book mentioned.
The Azembler language operates with 26 registers (eax, ebx, ..., ezx) and two commands:
* [x] β returns the value located in the address x. For example, [eax] returns the value that was located in the address, equal to the value in the register eax.
* lea x, y β assigns to the register x, indicated as the first operand, the second operand's address. Thus, for example, the "lea ebx, [eax]" command will write in the ebx register the content of the eax register: first the [eax] operation will be fulfilled, the result of it will be some value that lies in the address written in eax. But we do not need the value β the next operation will be lea, that will take the [eax] address, i.e., the value in the eax register, and will write it in ebx.
On the first thought the second operation seems meaningless, but as it turns out, it is acceptable to write the operation as
lea ecx, [eax + ebx],
lea ecx, [k*eax]
or even
lea ecx, [ebx + k*eax],
where k = 1, 2, 4 or 8.
As a result, the register ecx will be equal to the numbers eax + ebx, k*eax and ebx + k*eax correspondingly. However, such operation is fulfilled many times, dozens of times faster that the usual multiplying of numbers. And using several such operations, one can very quickly multiply some number by some other one. Of course, instead of eax, ebx and ecx you are allowed to use any registers.
For example, let the eax register contain some number that we should multiply by 41. It takes us 2 lines:
lea ebx, [eax + 4*eax] // now ebx = 5*eax
lea eax, [eax + 8*ebx] // now eax = eax + 8*ebx = 41*eax
Igor K. got interested in the following question: what is the minimum number of lea operations needed to multiply by the given number n and how to do it? Your task is to help him.
Consider that at the initial moment of time eax contains a number that Igor K. was about to multiply by n, and the registers from ebx to ezx contain number 0. At the final moment of time the result can be located in any register.
Input
The input data contain the only integer n (1 β€ n β€ 255), which Igor K. is about to multiply.
Output
On the first line print number p, which represents the minimum number of lea operations, needed to do that. Then print the program consisting of p commands, performing the operations. It is guaranteed that such program exists for any n from 1 to 255.
Use precisely the following format of commands (here k is equal to 1, 2, 4 or 8, and x, y and z are any, even coinciding registers):
lea x, [y]
lea x, [y + z]
lea x, [k*y]
lea x, [y + k*z]
Please note that extra spaces at the end of a command are unacceptable.
Examples
Input
41
Output
2
lea ebx, [eax + 4*eax]
lea ecx, [eax + 8*ebx]
Input
2
Output
1
lea ebx, [eax + eax]
Input
4
Output
1
lea ebx, [4*eax]
### Response
```cpp
#include <bits/stdc++.h>
int a[32];
int p[32][3];
int r[32][3];
int ans;
int n;
void dfs(int t) {
int i, j;
if (a[t] == n) {
if (t < ans) {
ans = t;
for (i = 0; i <= ans; i++)
for (j = 0; j < 3; j++) r[i][j] = p[i][j];
}
return;
}
if (t >= ans) return;
for (i = t; i >= 0; i--)
for (j = 1; j <= 8; j *= 2) {
if (a[i] + a[t] * j <= n) {
a[t + 1] = a[i] + a[t] * j;
p[t + 1][0] = i, p[t + 1][1] = t, p[t + 1][2] = j;
dfs(t + 1);
}
if (j != 1 && a[i] * j + a[t] <= n) {
a[t + 1] = a[t] + a[i] * j;
p[t + 1][0] = t, p[t + 1][1] = i, p[t + 1][2] = j;
dfs(t + 1);
}
}
for (j = 2; j <= 8 && a[t] * j <= n; j *= 2) {
a[t + 1] = a[t] * j;
p[t + 1][0] = -1, p[t + 1][1] = t, p[t + 1][2] = j;
dfs(t + 1);
}
}
int main() {
int i;
scanf("%d", &n);
for (ans = i = 0; i < 8; i++)
if (n & (1 << i)) ans++;
for (i = 1; i <= n; i *= 8) ans++;
a[0] = 1;
dfs(0);
printf("%d\n", ans);
for (i = 1; i <= ans; i++) {
if (r[i][0] == -1) {
printf("lea e%cx, [%d*e%cx]\n", 'a' + i, r[i][2], 'a' + r[i][1]);
} else if (r[i][2] == 1) {
printf("lea e%cx, [e%cx + e%cx]\n", 'a' + i, 'a' + r[i][0],
'a' + r[i][1]);
} else {
printf("lea e%cx, [e%cx + %d*e%cx]\n", 'a' + i, 'a' + r[i][0], r[i][2],
'a' + r[i][1]);
}
}
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.
You are asked to choose some integer k (k > 0) and find a sequence a of length k such that:
* 1 β€ a_1 < a_2 < ... < a_k β€ |s|;
* a_{i-1} + 1 < a_i for all i from 2 to k.
The characters at positions a_1, a_2, ..., a_k are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence a should not be adjacent.
Let the resulting string be s'. s' is called sorted if for all i from 2 to |s'| s'_{i-1} β€ s'_i.
Does there exist such a sequence a that the resulting string s' is sorted?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string s (2 β€ |s| β€ 100). Each character is either '0' or '1'.
Output
For each testcase print "YES" if there exists a sequence a such that removing the characters at positions a_1, a_2, ..., a_k and concatenating the parts without changing the order produces a sorted string.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
10101011011
0000
11111
110
1100
Output
YES
YES
YES
YES
NO
Note
In the first testcase you can choose a sequence a=[1,3,6,9]. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.
In the second and the third testcases the sequences are already sorted.
In the fourth testcase you can choose a sequence a=[3]. s'= "11", which is sorted.
In the fifth testcase there is no way to choose a sequence a such that s' is sorted.
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
string arr;
int t;
vector<int>p;
int main()
{
cin >> t;
while (t--)
{
cin >> arr;
bool sy1 = 1, sy2 = 1;
for (int i = 1; i < arr.length(); i++) {
if (sy2==0&&arr[i] == '0' && arr[i - 1] == '0') {
sy1 = 0;
}
if (arr[i] == '1' && arr[i - 1] == '1')
sy2 = 0;
}
if (sy1==0&&sy2==0)cout << "NO" << endl;
else cout << "YES" << endl;
}
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
The process of mammoth's genome decoding in Berland comes to its end!
One of the few remaining tasks is to restore unrecognized nucleotides in a found chain s. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, s is a string consisting of letters 'A', 'C', 'G', 'T' and characters '?'.
It is known that the number of nucleotides of each of the four types in the decoded genome of mammoth in Berland should be equal.
Your task is to decode the genome and replace each unrecognized nucleotide with one of the four types so that the number of nucleotides of each of the four types becomes equal.
Input
The first line contains the integer n (4 β€ n β€ 255) β the length of the genome.
The second line contains the string s of length n β the coded genome. It consists of characters 'A', 'C', 'G', 'T' and '?'.
Output
If it is possible to decode the genome, print it. If there are multiple answer, print any of them. If it is not possible, print three equals signs in a row: "===" (without quotes).
Examples
Input
8
AG?C??CT
Output
AGACGTCT
Input
4
AGCT
Output
AGCT
Input
6
????G?
Output
===
Input
4
AA??
Output
===
Note
In the first example you can replace the first question mark with the letter 'A', the second question mark with the letter 'G', the third question mark with the letter 'T', then each nucleotide in the genome would be presented twice.
In the second example the genome is already decoded correctly and each nucleotide is exactly once in it.
In the third and the fourth examples it is impossible to decode the genom.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1000000007;
const long long N = 1e9 + 5;
const long long Hash = 31;
const double pi = 3.141592653;
const double E = 2.718281828;
void solve() {
int n;
string s;
cin >> n >> s;
if (n % 4) {
cout << "===";
return;
}
int num[5] = {0};
for (int i = 0; i < n; i++) {
if (s[i] == 'A')
num[0]++;
else if (s[i] == 'C')
num[1]++;
else if (s[i] == 'G')
num[2]++;
else if (s[i] == 'T')
num[3]++;
else
num[4]++;
}
for (int i = 0; i < 4; i++) {
num[i] = (n / 4) - num[i];
if (num[i] < 0) {
cout << "===";
return;
}
}
int tag = 0;
for (int i = 0; i < n; i++) {
if (s[i] == '?') {
while (num[tag] == 0) tag++;
num[tag]--;
if (tag == 0)
cout << 'A';
else if (tag == 1)
cout << 'C';
else if (tag == 2)
cout << 'G';
else
cout << 'T';
} else
cout << s[i];
}
}
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t = 1;
while (t--) solve();
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Peter has a sequence of integers a1, a2, ..., an. Peter wants all numbers in the sequence to equal h. He can perform the operation of "adding one on the segment [l, r]": add one to all elements of the sequence with indices from l to r (inclusive). At that, Peter never chooses any element as the beginning of the segment twice. Similarly, Peter never chooses any element as the end of the segment twice. In other words, for any two segments [l1, r1] and [l2, r2], where Peter added one, the following inequalities hold: l1 β l2 and r1 β r2.
How many distinct ways are there to make all numbers in the sequence equal h? Print this number of ways modulo 1000000007 (109 + 7). Two ways are considered distinct if one of them has a segment that isn't in the other way.
Input
The first line contains two integers n, h (1 β€ n, h β€ 2000). The next line contains n integers a1, a2, ..., an (0 β€ ai β€ 2000).
Output
Print a single integer β the answer to the problem modulo 1000000007 (109 + 7).
Examples
Input
3 2
1 1 1
Output
4
Input
5 1
1 1 1 1 1
Output
1
Input
4 3
3 2 1 1
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long N = 2e5 + 6;
const long long M = 1e9 + 7;
long long dp[2005][2005];
long long A[N];
long long n, h;
long long alpha(long long i, long long op) {
if (i == 1) {
if (op == 0)
return (A[i] == h || A[i] + 1 == h ? 1 : 0);
else if (op == 1)
return (A[i] + 1 == h ? 1 : 0);
return 0;
}
long long &abstergo = dp[i][op];
if (abstergo != -1) return abstergo % M;
long long ans = 0;
if (A[i] + op == h) {
if (op > 0) ans += alpha(i - 1, op - 1), ans %= M;
ans += alpha(i - 1, op), ans %= M;
} else if (A[i] + op + 1 == h) {
ans += alpha(i - 1, op + 1) * (op + 1), ans %= M;
ans += alpha(i - 1, op), ans %= M;
if (op > 0) ans += alpha(i - 1, op) * op, ans %= M;
}
return abstergo = ans % M;
}
void solve() {
cin >> n >> h;
for (long long i = 1; i < n + 1; i++) cin >> A[i];
memset(dp, -1, sizeof(dp));
cout << alpha(n, 0);
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long t = 1;
while (t--) solve();
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
This winter is so... well, you've got the idea :-) The Nvodsk road system can be represented as n junctions connected with n - 1 bidirectional roads so that there is a path between any two junctions. The organizers of some event want to choose a place to accommodate the participants (junction v), and the place to set up the contests (junction u). Besides, at the one hand, they want the participants to walk about the city and see the neighbourhood (that's why the distance between v and u should be no less than l). On the other hand, they don't want the participants to freeze (so the distance between v and u should be no more than r). Besides, for every street we know its beauty β some integer from 0 to 109. Your task is to choose the path that fits in the length limits and has the largest average beauty. We shall define the average beauty as a median of sequence of the beauties of all roads along the path.
We can put it more formally like that: let there be a path with the length k. Let ai be a non-decreasing sequence that contains exactly k elements. Each number occurs there exactly the number of times a road with such beauty occurs along on path. We will represent the path median as number aβk / 2β, assuming that indexation starting from zero is used. βxβ β is number Ρ
, rounded down to the nearest integer.
For example, if a = {0, 5, 12}, then the median equals to 5, and if a = {0, 5, 7, 12}, then the median is number 7.
It is guaranteed that there will be at least one path with the suitable quantity of roads.
Input
The first line contains three integers n, l, r (1 β€ l β€ r < n β€ 105).
Next n - 1 lines contain descriptions of roads of the Nvodsk, each line contains three integers ai, bi, ci (1 β€ ai, bi β€ n, 0 β€ ci β€ 109, ai β bi) β junctions ai and bi are connected with a street whose beauty equals ci.
Output
Print two integers β numbers of the junctions, where to accommodate the participants and set up the contests, correspondingly. If there are multiple optimal variants, print any of them.
Examples
Input
6 3 4
1 2 1
2 3 1
3 4 1
4 5 1
5 6 1
Output
4 1
Input
6 3 4
1 2 1
2 3 1
3 4 1
4 5 2
5 6 2
Output
6 3
Input
5 1 4
1 2 1
1 3 4
3 4 7
3 5 2
Output
4 3
Input
8 3 6
1 2 9
2 3 7
3 4 7
4 5 8
5 8 2
3 6 3
2 7 4
Output
5 1
Note
In the first sample all roads have the same beauty. That means that all paths of the positive length have the same median. Thus, any path with length from 3 to 4, inclusive will be valid for us.
In the second sample the city looks like that: 1 - 2 - 3 - 4 - 5 - 6. Two last roads are more valuable and we should choose any path that contains both of them and has the suitable length. It is either the path between 2 and 6 or the path between 3 and 6.
### Response
```cpp
#include <bits/stdc++.h>
const int maxn = 100005;
using namespace std;
int SEGLEN;
pair<int, int> mx[4 * maxn];
int mxself[maxn];
void make() {
fill(mx, mx + 4 * SEGLEN, make_pair(-maxn, 0));
fill(mxself, mxself + SEGLEN, -maxn);
}
pair<int, int> get(int l, int r, int s = 0, int e = SEGLEN, int x = 1) {
if (l <= s && e <= r) return mx[x];
int mid = (s + e) / 2;
if (l < mid && r > mid)
return max(get(l, r, s, mid, 2 * x), get(l, r, mid, e, 2 * x + 1));
if (l < mid) return get(l, r, s, mid, 2 * x);
if (r > mid) return get(l, r, mid, e, 2 * x + 1);
}
void insert(int p, int val, int who, int s = 0, int e = SEGLEN, int x = 1) {
if (e - s == 1) {
if (val > mx[x].first) {
mx[x] = {val, who};
mxself[s] = val;
}
return;
}
int mid = (s + e) / 2;
if (p < mid)
insert(p, val, who, s, mid, 2 * x);
else
insert(p, val, who, mid, e, 2 * x + 1);
mx[x] = max(mx[2 * x], mx[2 * x + 1]);
}
vector<pair<int, int> > v[maxn];
int sz[maxn], d[maxn], s[maxn], a[maxn];
bool mark[maxn];
int n, l, r, len = 0;
vector<int> wei;
int dfs(int cur, int p = -1) {
sz[cur] = 1;
for (auto e : v[cur]) {
int u = e.first;
if (u != p && !mark[u]) sz[cur] += dfs(u, cur);
}
return sz[cur];
}
void make_list(int cur, int k, int p = -1) {
a[len++] = cur;
for (auto e : v[cur]) {
int u = e.first, w = e.second;
if (u != p && !mark[u]) {
d[u] = d[cur] + 1;
s[u] = s[cur] + (w >= k ? 1 : -1);
make_list(u, k, cur);
}
}
}
void solve(int cur, int k, int &x, int &y) {
dfs(cur);
bool found = true;
int root = cur, p = -1;
while (found) {
found = false;
for (auto e : v[cur]) {
int u = e.first;
if (u != p && !mark[u] && sz[u] >= sz[root] / 2) {
p = cur;
cur = u;
found = true;
break;
}
}
}
mark[cur] = true;
SEGLEN = sz[root];
make();
insert(0, 0, cur);
for (auto e : v[cur]) {
int u = e.first, w = e.second;
if (mark[u]) continue;
d[u] = 1;
s[u] = (w >= k ? 1 : -1);
len = 0;
make_list(u, k);
for (int i = 0; i < len; i++) {
int l2 = max(0, l - d[a[i]]), r2 = min(SEGLEN, r - d[a[i]] + 1);
if (r2 <= l2) continue;
auto p = get(l2, r2);
if (s[a[i]] + p.first >= 0) {
x = a[i], y = p.second;
break;
}
}
if (x != -1) break;
for (int i = 0; i < len; i++)
if (mxself[d[a[i]]] < s[a[i]]) insert(d[a[i]], s[a[i]], a[i]);
}
for (auto e : v[cur])
if (!mark[e.first]) {
if (x != -1) return;
solve(e.first, k, x, y);
}
}
int main() {
scanf("%d%d%d", &n, &l, &r);
for (int i = 0; i < n - 1; i++) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
a--;
b--;
v[a].push_back({b, c});
v[b].push_back({a, c});
wei.push_back(c);
}
sort(wei.begin(), wei.end());
wei.resize(unique(wei.begin(), wei.end()) - wei.begin());
int s = 0, e = wei.size();
int x, y;
solve(0, wei[0], x, y);
while (e - s > 1) {
fill(mark, mark + n, false);
int mid = (s + e) / 2, x_ = -1, y_ = -1;
solve(0, wei[mid], x_, y_);
if (x_ != -1)
s = mid, x = x_, y = y_;
else
e = mid;
}
printf("%d %d\n", x + 1, y + 1);
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft k torches. One torch can be crafted using one stick and one coal.
Hopefully, you've met a very handsome wandering trader who has two trade offers:
* exchange 1 stick for x sticks (you lose 1 stick and gain x sticks).
* exchange y sticks for 1 coal (you lose y sticks and gain 1 coal).
During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.
Your task is to find the minimum number of trades you need to craft at least k torches. The answer always exists under the given constraints.
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 three integers x, y and k (2 β€ x β€ 10^9; 1 β€ y, k β€ 10^9) β the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively.
Output
For each test case, print the answer: the minimum number of trades you need to craft at least k torches. The answer always exists under the given constraints.
Example
Input
5
2 1 5
42 13 24
12 11 12
1000000000 1000000000 1000000000
2 1000000000 1000000000
Output
14
33
25
2000000003
1000000001999999999
### Response
```cpp
#include <bits/stdc++.h>
int main() {
int i, t;
scanf("%d", &t);
for (i = 0; i < t; i++) {
long long x, y, k;
scanf("%lld%lld%lld", &x, &y, &k);
long long cs = y * k;
long long s = cs + k;
long long ans = k;
ans = ans + (s - 1) / (x - 1);
if ((ans - k) * (x - 1) < (s - 1)) ans = ans + 1;
printf("%lld\n", ans);
}
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Fox Ciel has n boxes in her room. They have the same size and weight, but they might have different strength. The i-th box can hold at most xi boxes on its top (we'll call xi the strength of the box).
Since all the boxes have the same size, Ciel cannot put more than one box directly on the top of some box. For example, imagine Ciel has three boxes: the first has strength 2, the second has strength 1 and the third has strength 1. She cannot put the second and the third box simultaneously directly on the top of the first one. But she can put the second box directly on the top of the first one, and then the third box directly on the top of the second one. We will call such a construction of boxes a pile.
<image>
Fox Ciel wants to construct piles from all the boxes. Each pile will contain some boxes from top to bottom, and there cannot be more than xi boxes on the top of i-th box. What is the minimal number of piles she needs to construct?
Input
The first line contains an integer n (1 β€ n β€ 100). The next line contains n integers x1, x2, ..., xn (0 β€ xi β€ 100).
Output
Output a single integer β the minimal possible number of piles.
Examples
Input
3
0 0 10
Output
2
Input
5
0 1 2 3 4
Output
1
Input
4
0 0 0 0
Output
4
Input
9
0 1 0 2 0 1 1 2 10
Output
3
Note
In example 1, one optimal way is to build 2 piles: the first pile contains boxes 1 and 3 (from top to bottom), the second pile contains only box 2.
<image>
In example 2, we can build only 1 pile that contains boxes 1, 2, 3, 4, 5 (from top to bottom).
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool comp(int x, int y) { return x > y; }
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
;
int tt = 1;
int m = INT_MIN, n, k;
string st;
while (tt--) {
cin >> n;
int arr[n], mx[101] = {0}, count[101] = {0};
for (long long i = 0; i < n; i++) {
cin >> arr[i];
mx[arr[i]] += 1;
}
sort(arr, arr + n);
int i = 0;
while (n > 0) {
int k = 1;
while (mx[arr[i]] > 0) {
if (arr[i] < count[k]) ++k;
++count[k];
n--;
--mx[arr[i]];
if (k > m) m = k;
}
++i;
}
cout << m << endl;
}
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
You have an array a_1, a_2, ..., a_n.
Let's call some subarray a_l, a_{l + 1}, ... , a_r of this array a subpermutation if it contains all integers from 1 to r-l+1 exactly once. For example, array a = [2, 2, 1, 3, 2, 3, 1] contains 6 subarrays which are subpermutations: [a_2 ... a_3], [a_2 ... a_4], [a_3 ... a_3], [a_3 ... a_5], [a_5 ... a_7], [a_7 ... a_7].
You are asked to calculate the number of subpermutations.
Input
The first line contains one integer n (1 β€ n β€ 3 β
10^5).
The second line contains n integers a_1, a_2, ... , a_n (1 β€ a_i β€ n).
This array can contain the same integers.
Output
Print the number of subpermutations of the array a.
Examples
Input
8
2 4 1 3 4 2 1 2
Output
7
Input
5
1 1 2 1 2
Output
6
Note
There are 7 subpermutations in the first test case. Their segments of indices are [1, 4], [3, 3], [3, 6], [4, 7], [6, 7], [7, 7] and [7, 8].
In the second test case 6 subpermutations exist: [1, 1], [2, 2], [2, 3], [3, 4], [4, 4] and [4, 5].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 3e5 + 10;
const int maxl = 20;
int a[maxn], LOG[maxn], RMQ[maxl][maxn], LMQ[maxl][maxn], nex[maxn], dpn[maxn],
pre[maxn], dpp[maxn], last[maxn];
long long answer = 0;
void find(int L, int R) {
if (L >= R) return;
int len = LOG[R - L];
int fi = RMQ[len][L], se = LMQ[len][R - 1];
if (a[fi] < a[se]) fi = se;
if (fi - L < R - fi) {
int now = min(dpn[fi], R);
if (now - fi == a[fi]) {
answer++;
}
for (int i = fi - 1; i >= max(L, fi - a[fi] + 1) and now > fi; i--) {
now = min(now, nex[i]);
if (now > fi and now - i == a[fi]) {
answer++;
}
}
} else {
int now = max(L - 1, dpp[fi]);
if (fi - now == a[fi]) {
answer++;
}
for (int i = fi + 1; i < min(R, fi + a[fi]) and now < fi; i++) {
now = max(now, pre[i]);
if (fi > now and i - now == a[fi]) {
answer++;
}
}
}
find(L, fi);
find(fi + 1, R);
}
int main() {
ios_base::sync_with_stdio(false);
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i];
for (int len = 1; len <= n; len++) LOG[len] = log2(len);
for (int i = 0; i < n; i++) {
RMQ[0][i] = i;
LMQ[0][i] = i;
}
for (int i = 0; i < 18; i++) {
for (int j = 0; j + (1 << i) < n; j++) {
int fi = RMQ[i][j], se = RMQ[i][(1 << i) + j];
if (a[fi] >= a[se])
RMQ[i + 1][j] = fi;
else
RMQ[i + 1][j] = se;
}
for (int j = (1 << i); j < n; j++) {
int fi = LMQ[i][j], se = LMQ[i][j - (1 << i)];
if (a[fi] > a[se])
LMQ[i + 1][j] = fi;
else
LMQ[i + 1][j] = se;
}
}
memset(last, -1, sizeof last);
for (int i = n - 1; i >= 0; i--) {
nex[i] = (last[a[i]] == -1 ? n : last[a[i]]);
dpn[i] = (i == n - 1 ? n : min(nex[i], dpn[i + 1]));
last[a[i]] = i;
}
memset(last, -1, sizeof last);
for (int i = 0; i < n; i++) {
pre[i] = last[a[i]];
dpp[i] = (i == 0 ? -1 : max(pre[i], dpp[i - 1]));
last[a[i]] = i;
}
find(0, n);
cout << answer << endl;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Since next season are coming, you'd like to form a team from two or three participants. There are n candidates, the i-th candidate has rank a_i. But you have weird requirements for your teammates: if you have rank v and have chosen the i-th and j-th candidate, then GCD(v, a_i) = X and LCM(v, a_j) = Y must be met.
You are very experienced, so you can change your rank to any non-negative integer but X and Y are tied with your birthdate, so they are fixed.
Now you want to know, how many are there pairs (i, j) such that there exists an integer v meeting the following constraints: GCD(v, a_i) = X and LCM(v, a_j) = Y. It's possible that i = j and you form a team of two.
GCD is the greatest common divisor of two number, LCM β the least common multiple.
Input
First line contains three integers n, X and Y (1 β€ n β€ 2 β
10^5, 1 β€ X β€ Y β€ 10^{18}) β the number of candidates and corresponding constants.
Second line contains n space separated integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{18}) β ranks of candidates.
Output
Print the only integer β the number of pairs (i, j) such that there exists an integer v meeting the following constraints: GCD(v, a_i) = X and LCM(v, a_j) = Y. It's possible that i = j.
Examples
Input
12 2 2
1 2 3 4 5 6 7 8 9 10 11 12
Output
12
Input
12 1 6
1 3 5 7 9 11 12 10 8 6 4 2
Output
30
Note
In the first example next pairs are valid: a_j = 1 and a_i = [2, 4, 6, 8, 10, 12] or a_j = 2 and a_i = [2, 4, 6, 8, 10, 12]. The v in both cases can be equal to 2.
In the second example next pairs are valid:
* a_j = 1 and a_i = [1, 5, 7, 11];
* a_j = 2 and a_i = [1, 5, 7, 11, 10, 8, 4, 2];
* a_j = 3 and a_i = [1, 3, 5, 7, 9, 11];
* a_j = 6 and a_i = [1, 3, 5, 7, 9, 11, 12, 10, 8, 6, 4, 2].
### Response
```cpp
#include <bits/stdc++.h>
inline long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; }
inline void sub(long long &a, long long b) {
a -= b;
if (a < 0) a += 1000000009;
}
inline void add(long long &a, long long b) {
a += b;
if (a >= 1000000009) a -= 1000000009;
}
template <typename T>
inline T const &MAX(T const &a, T const &b) {
return a > b ? a : b;
}
template <typename T>
inline T const &MIN(T const &a, T const &b) {
return a < b ? a : b;
}
inline long long qp(long long a, long long b) {
long long ans = 1;
while (b) {
if (b & 1) ans = ans * a % 1000000009;
a = a * a % 1000000009, b >>= 1;
}
return ans;
}
inline long long qp(long long a, long long b, long long c) {
long long ans = 1;
while (b) {
if (b & 1) ans = ans * a % c;
a = a * a % c, b >>= 1;
}
return ans;
}
inline long long qm(long long a, long long b, long long c) {
long long ans = 0;
while (b) {
if (b & 1) ans = (ans + a) % c;
a = (a + a) % c;
b >>= 1;
}
return ans % c;
}
inline long long qpow(long long a, long long b, long long c) {
long long ans = 1;
while (b) {
if (b & 1) ans = qm(ans, a, c) % c;
a = qm(a, a, c) % c;
b >>= 1;
}
return ans;
}
using namespace std;
const unsigned long long ba = 233;
const double eps = 1e-10;
const long long INF = 0x3f3f3f3f3f3f3f3f;
const int N = 200000 + 10, maxn = 100000 + 10, inf = 0x3f3f3f3f;
int cnt;
long long f[110];
bool check(long long a, long long n, long long x, long long sum) {
long long judge = qpow(a, x, n);
if (judge == n - 1 || judge == 1) return 1;
while (sum--) {
judge = qm(judge, judge, n);
if (judge == n - 1) return 1;
}
return 0;
}
bool miller(long long n) {
if (n < 2) return 0;
if (n == 2) return 1;
if ((n & 1) == 0) return 0;
long long x = n - 1, sum = 0;
while (x % 2 == 0) x >>= 1, sum++;
for (long long i = 1; i <= 20; i++) {
long long a = rand() % (n - 1) + 1;
if (!check(a, n, x, sum)) return 0;
}
return 1;
}
long long pollard(long long n, long long c) {
long long x, y, d, i = 1, k = 2;
x = rand() % n;
y = x;
while (1) {
i++;
x = (qm(x, x, n) + c) % n;
d = gcd(y - x, n);
if (d < 0) d = -d;
if (d > 1 && d < n) return d;
if (y == x) return n;
if (i == k) y = x, k <<= 1;
}
}
void Find(long long n) {
if (n == 1) return;
if (miller(n)) {
f[cnt++] = n;
return;
}
long long p = n;
while (p >= n) p = pollard(p, rand() % (n - 1) + 1);
Find(n / p);
Find(p);
}
long long a[N], b[N], c[N];
int cal(long long x, long long y) {
int ans = 0;
while (x % y == 0) ans++, x /= y;
return ans;
}
void fwt_and(long long *a, int n, int dft) {
for (int i = 1; i < n; i <<= 1)
for (int j = 0; j < n; j += i << 1)
for (int k = j; k < j + i; k++) {
if (dft == 1)
a[k] = a[k] + a[i + k];
else
a[k] = a[k] - a[i + k];
}
}
int main() {
int n;
long long x, y;
scanf("%d%lld%lld", &n, &x, &y);
if (y % x) return 0 * puts("0");
Find(y);
sort(f, f + cnt);
cnt = unique(f, f + cnt) - f;
for (int i = 1; i <= n; i++) {
scanf("%lld", &a[i]);
int p1 = 0, p2 = 0;
for (int j = 0; j < cnt; j++)
if (cal(x, f[j]) != cal(y, f[j])) {
p1 += (1 << j) * (cal(a[i], f[j]) > cal(x, f[j]));
p2 += (1 << j) * (cal(a[i], f[j]) < cal(y, f[j]));
}
if (a[i] % x == 0) b[p1]++;
if (y % a[i] == 0) c[p2]++;
}
fwt_and(b, (1 << cnt), 1);
fwt_and(c, (1 << cnt), 1);
for (int i = 0; i < (1 << cnt); i++) b[i] = b[i] * c[i];
fwt_and(b, (1 << cnt), -1);
printf("%lld\n", b[0]);
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
The Smart Beaver from ABBYY has a long history of cooperating with the "Institute of Cytology and Genetics". Recently, the Institute staff challenged the Beaver with a new problem. The problem is as follows.
There is a collection of n proteins (not necessarily distinct). Each protein is a string consisting of lowercase Latin letters. The problem that the scientists offered to the Beaver is to select a subcollection of size k from the initial collection of proteins so that the representativity of the selected subset of proteins is maximum possible.
The Smart Beaver from ABBYY did some research and came to the conclusion that the representativity of a collection of proteins can be evaluated by a single number, which is simply calculated. Let's suppose we have a collection {a1, ..., ak} consisting of k strings describing proteins. The representativity of this collection is the following value:
<image>
where f(x, y) is the length of the longest common prefix of strings x and y; for example, f("abc", "abd") = 2, and f("ab", "bcd") = 0.
Thus, the representativity of collection of proteins {"abc", "abd", "abe"} equals 6, and the representativity of collection {"aaa", "ba", "ba"} equals 2.
Having discovered that, the Smart Beaver from ABBYY asked the Cup contestants to write a program that selects, from the given collection of proteins, a subcollection of size k which has the largest possible value of representativity. Help him to solve this problem!
Input
The first input line contains two integers n and k (1 β€ k β€ n), separated by a single space. The following n lines contain the descriptions of proteins, one per line. Each protein is a non-empty string of no more than 500 characters consisting of only lowercase Latin letters (a...z). Some of the strings may be equal.
The input limitations for getting 20 points are:
* 1 β€ n β€ 20
The input limitations for getting 50 points are:
* 1 β€ n β€ 100
The input limitations for getting 100 points are:
* 1 β€ n β€ 2000
Output
Print a single number denoting the largest possible value of representativity that a subcollection of size k of the given collection of proteins can have.
Examples
Input
3 2
aba
bzd
abq
Output
2
Input
4 3
eee
rrr
ttt
qqq
Output
0
Input
4 3
aaa
abba
abbc
abbd
Output
9
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0, y = 0;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') y = 1;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
return y ? -x : x;
}
template <typename T>
inline T read() {
T x = 0;
int y = 0;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') y = 1;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
return y ? -x : x;
}
int en[1000005], son[1000005][26], siz[1000005], deep[1000005], s[1000005],
f[4005][2005], h[1000005], c[1000005], num, k, cnt = 1, all;
char a[505];
struct edge {
int pre, to;
} e[1000005];
inline void add(int from, int to) {
e[++num] = (edge){h[from], to}, h[from] = num;
}
void insert() {
int len = strlen(a + 1), node = 1;
for (register int i = 1; i <= len; ++i) {
if (!son[node][a[i] - 'a']) son[node][a[i] - 'a'] = ++cnt, ++siz[node];
node = son[node][a[i] - 'a'];
}
++en[node];
}
void dfs(int node = 1, int dep = 0, int last = 0) {
if (node == 1 || siz[node] > 1 || en[node]) {
deep[++all] = dep, add(last, all), last = all, s[all] = en[node];
}
for (register int i = 0; i < 26; ++i)
if (son[node][i]) dfs(son[node][i], dep + 1, last);
}
void dp(int node = 1, int fa = 0) {
f[node][0] = 0;
for (register int i = h[node], x; i; i = e[i].pre) {
dp(x = e[i].to, node), s[node] += s[x];
for (register int j = min(s[node], k); j; --j)
for (register int k = min(s[x], j); k; --k)
f[node][j] = max(f[node][j], f[x][k] + f[node][j - k]);
}
for (register int i = 1; i <= s[node]; ++i)
f[node][i] += c[i] * (deep[node] - deep[fa]);
}
signed main() {
int n = read();
k = read();
for (register int i = 1; i <= n; ++i) scanf("%s", a + 1), insert();
for (register int i = 1; i <= k; ++i) c[i] = i * (i - 1) >> 1;
dfs(), dp();
printf("%d\n", f[1][k]);
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
In the Isle of Guernsey there are n different types of coins. For each i (1 β€ i β€ n), coin of type i is worth ai cents. It is possible that ai = aj for some i and j (i β j).
Bessie has some set of these coins totaling t cents. She tells Jessie q pairs of integers. For each i (1 β€ i β€ q), the pair bi, ci tells Jessie that Bessie has a strictly greater number of coins of type bi than coins of type ci. It is known that all bi are distinct and all ci are distinct.
Help Jessie find the number of possible combinations of coins Bessie could have. Two combinations are considered different if there is some i (1 β€ i β€ n), such that the number of coins Bessie has of type i is different in the two combinations. Since the answer can be very large, output it modulo 1000000007 (109 + 7).
If there are no possible combinations of coins totaling t cents that satisfy Bessie's conditions, output 0.
Input
The first line contains three space-separated integers, n, q and t (1 β€ n β€ 300; 0 β€ q β€ n; 1 β€ t β€ 105). The second line contains n space separated integers, a1, a2, ..., an (1 β€ ai β€ 105). The next q lines each contain two distinct space-separated integers, bi and ci (1 β€ bi, ci β€ n; bi β ci).
It's guaranteed that all bi are distinct and all ci are distinct.
Output
A single integer, the number of valid coin combinations that Bessie could have, modulo 1000000007 (109 + 7).
Examples
Input
4 2 17
3 1 2 5
4 2
3 4
Output
3
Input
3 2 6
3 1 1
1 2
2 3
Output
0
Input
3 2 10
1 2 3
1 2
2 1
Output
0
Note
For the first sample, the following 3 combinations give a total of 17 cents and satisfy the given conditions: {0 of type 1, 1 of type 2, 3 of type 3, 2 of type 4}, {0, 0, 6, 1}, {2, 0, 3, 1}.
No other combinations exist. Note that even though 4 occurs in both bi and ci, the problem conditions are still satisfied because all bi are distinct and all ci are distinct.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
const int MAXN = 305;
const int MAXT = 100005;
int a[MAXN], e[MAXN], d[MAXN];
int dp[MAXT];
long long t, cnt;
void dfs(int u, int acc) {
if (t < 0) {
return;
}
++cnt;
a[u] += acc;
if (e[u] != 0) {
dfs(e[u], a[u]);
t -= a[u];
if (t < 0) {
return;
}
}
}
int main() {
int n, q;
int u, v;
scanf("%d%d%d", &n, &q, &t);
for (int i = 1; i <= n; ++i) {
scanf("%d", a + i);
}
while (q--) {
scanf("%d%d", &u, &v);
e[u] = v;
d[v] = 1;
}
for (int i = 1; i <= n && t >= 0; ++i) {
if (d[i] == 0) {
dfs(i, 0);
}
}
if (t < 0 || cnt < n) {
printf("0\n");
return 0;
}
dp[0] = 1;
for (int i = 1; i <= n; ++i) {
for (int j = a[i]; j <= t; ++j) {
dp[j] = (dp[j] + dp[j - a[i]]) % MOD;
}
}
printf("%d\n", dp[t]);
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Given is an integer S. Find how many sequences there are whose terms are all integers greater than or equal to 3, and whose sum is equal to S. The answer can be very large, so output it modulo 10^9 + 7.
Constraints
* 1 \leq S \leq 2000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
S
Output
Print the answer.
Examples
Input
7
Output
3
Input
2
Output
0
Input
1729
Output
294867501
### Response
```cpp
#include <iostream>
using namespace std;
const long long mod = 1000000007;
int main() {
int S, A[2000];
cin >> S;
A[0] = A[1] = A[2] = 0;
A[3] = 1;
for (int i = 4; i <= S; i++) {
A[i] = (A[i - 1] + A[i - 3]) % mod;
}
cout << A[S] << endl;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
A and B are preparing themselves for programming contests.
The University where A and B study is a set of rooms connected by corridors. Overall, the University has n rooms connected by n - 1 corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from 1 to n.
Every day Π and B write contests in some rooms of their university, and after each contest they gather together in the same room and discuss problems. A and B want the distance from the rooms where problems are discussed to the rooms where contests are written to be equal. The distance between two rooms is the number of edges on the shortest path between them.
As they write contests in new rooms every day, they asked you to help them find the number of possible rooms to discuss problems for each of the following m days.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of rooms in the University.
The next n - 1 lines describe the corridors. The i-th of these lines (1 β€ i β€ n - 1) contains two integers ai and bi (1 β€ ai, bi β€ n), showing that the i-th corridor connects rooms ai and bi.
The next line contains integer m (1 β€ m β€ 105) β the number of queries.
Next m lines describe the queries. The j-th of these lines (1 β€ j β€ m) contains two integers xj and yj (1 β€ xj, yj β€ n) that means that on the j-th day A will write the contest in the room xj, B will write in the room yj.
Output
In the i-th (1 β€ i β€ m) line print the number of rooms that are equidistant from the rooms where A and B write contest on the i-th day.
Examples
Input
4
1 2
1 3
2 4
1
2 3
Output
1
Input
4
1 2
2 3
2 4
2
1 2
1 3
Output
0
2
Note
in the first sample there is only one room at the same distance from rooms number 2 and 3 β room number 1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
int add(int x, int y, int CMOD = MOD) { return (0LL + x + y) % CMOD; }
int mult(int x, int y, int CMOD = MOD) { return (1LL * x * y) % CMOD; }
long long fast_expo(long long x, long long y, long long CMOD = MOD) {
if (x == 0) return 0;
if (y == 0) return 1;
long long ans = fast_expo(x, y / 2, CMOD);
ans = mult(ans, ans, CMOD);
if (y & 1) ans = mult(ans, x, CMOD);
return ans;
}
const int TAM = 1e5 + 100;
const int L = 19;
int n;
vector<int> G[TAM];
int sub[TAM];
int in[TAM];
int out[TAM];
int timer = 0;
int h[TAM];
int up[TAM][L];
void dfs(int u, int pd, int alt) {
in[u] = timer++;
sub[u] = 1, h[u] = alt;
up[u][0] = pd;
for (int i = 1; i < L; i++) up[u][i] = up[up[u][i - 1]][i - 1];
for (int v : G[u]) {
if (v != pd) {
dfs(v, u, alt + 1);
sub[u] += sub[v];
}
}
out[u] = timer++;
}
bool isAncestor(int u, int v) { return (in[u] <= in[v] and out[v] <= out[u]); }
int lca(int u, int v) {
if (isAncestor(u, v)) return u;
if (isAncestor(v, u)) return v;
for (int i = L - 1; i >= 0; i--) {
if (!isAncestor(up[u][i], v)) u = up[u][i];
}
return up[u][0];
}
int subir(int u, int t) {
for (int i = L - 1; i >= 0; i--) {
if (t - (1 << i) >= 0) {
u = up[u][i];
t -= (1 << i);
}
}
return u;
}
int main() {
ios_base ::sync_with_stdio(false);
cin.tie(NULL);
cin >> n;
for (int i = 0; i < n - 1; i++) {
int u, v;
cin >> u >> v;
u--;
v--;
G[u].emplace_back(v);
G[v].emplace_back(u);
}
dfs(0, 0, 0);
int q;
cin >> q;
for (int i = 0; i < q; i++) {
int u, v;
cin >> u >> v;
u--;
v--;
if (h[u] < h[v]) swap(u, v);
int l = lca(u, v);
int dis = h[u] + h[v] - 2 * h[l];
if (dis % 2 != 0) {
cout << "0\n";
continue;
}
if (u == v) {
cout << n << "\n";
continue;
}
if (h[v] == h[u]) {
u = subir(u, h[u] - h[l] - 1);
v = subir(v, h[v] - h[l] - 1);
cout << n - sub[u] - sub[v] << endl;
} else {
u = subir(u, dis / 2 - 1);
int ans = -sub[u];
u = up[u][0];
ans += sub[u];
cout << ans << endl;
}
}
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins.
Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.
Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.
Input
The first line contains integer n (1 β€ n β€ 1000) β the number of cards on the table. The second line contains space-separated numbers on the cards from left to right. The numbers on the cards are distinct integers from 1 to 1000.
Output
On a single line, print two integers. The first number is the number of Sereja's points at the end of the game, the second number is the number of Dima's points at the end of the game.
Examples
Input
4
4 1 2 10
Output
12 5
Input
7
1 2 3 4 5 6 7
Output
16 12
Note
In the first sample Sereja will take cards with numbers 10 and 2, so Sereja's sum is 12. Dima will take cards with numbers 4 and 1, so Dima's sum is 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int cards, sereja = 0, dima = 0;
bool turn = true;
cin >> cards;
int card[cards];
int left = 0, right = cards - 1;
for (int i = 0; i < cards; i++) cin >> card[i];
while (left <= right) {
if (card[left] > card[right]) {
if (turn)
sereja += card[left];
else
dima += card[left];
left++;
} else {
if (turn)
sereja += card[right];
else
dima += card[right];
right--;
}
if (turn)
turn = false;
else
turn = true;
}
cout << sereja << "\t" << dima << endl;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.
The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 β€ i β€ n - 1.
To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li β€ x β€ ri, li + 1 β€ y β€ ri + 1 and y - x = a.
The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.
Input
The first line contains integers n (2 β€ n β€ 2Β·105) and m (1 β€ m β€ 2Β·105) β the number of islands and bridges.
Next n lines each contain two integers li and ri (1 β€ li β€ ri β€ 1018) β the coordinates of the island endpoints.
The last line contains m integer numbers a1, a2, ..., am (1 β€ ai β€ 1018) β the lengths of the bridges that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.
Examples
Input
4 4
1 4
7 8
9 10
12 14
4 5 3 8
Output
Yes
2 3 1
Input
2 2
11 14
17 18
2 9
Output
No
Input
2 1
1 1
1000000000000000000 1000000000000000000
999999999999999999
Output
Yes
1
Note
In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.
In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 19;
const long long inf = 1e18 + 10;
int n, m, vis[N];
long long l, r;
struct node {
long long l, r;
int id;
bool operator<(const node &a) const { return l < a.l; }
};
vector<int> ans(N);
vector<pair<long long, long long> > dis;
vector<node> lr;
set<pair<long long, long long> > d_i;
int main() {
cin >> n >> m;
long long tl, tr;
cin >> tl >> tr;
for (int i = 0; i < n - 1; i++) {
cin >> l >> r;
lr.push_back({l - tr, r - tl, i});
tl = l;
tr = r;
}
for (int i = 1; i <= m; i++) {
cin >> l;
dis.push_back({l, i});
}
sort(lr.begin(), lr.end());
sort(dis.begin(), dis.end());
for (int j = m - 1, i = n - 2; i >= 0; i--) {
while (j >= 0 && dis[j].first >= lr[i].l) d_i.insert(dis[j]), j--;
auto it = d_i.upper_bound({lr[i].r + 1, 0});
if (it == d_i.begin()) {
cout << "No" << endl;
return 0;
}
it--;
ans[lr[i].id] = it->second;
d_i.erase(it);
}
cout << "Yes" << endl;
for (int i = 0; i <= n - 2; i++) cout << ans[i] << (i == n - 2 ? '\n' : ' ');
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
In the country of Never, there are n cities and a well-developed road system. There is exactly one bidirectional road between every pair of cities, thus, there are as many as <image> roads! No two roads intersect, and no road passes through intermediate cities. The art of building tunnels and bridges has been mastered by Neverians.
An independent committee has evaluated each road of Never with a positive integer called the perishability of the road. The lower the road's perishability is, the more pleasant it is to drive through this road.
It's the year of transport in Never. It has been decided to build a museum of transport in one of the cities, and to set a single signpost directing to some city (not necessarily the one with the museum) in each of the other cities. The signposts must satisfy the following important condition: if any Neverian living in a city without the museum starts travelling from that city following the directions of the signposts, then this person will eventually arrive in the city with the museum.
Neverians are incredibly positive-minded. If a Neverian travels by a route consisting of several roads, he considers the perishability of the route to be equal to the smallest perishability of all the roads in this route.
The government of Never has not yet decided where to build the museum, so they consider all n possible options. The most important is the sum of perishabilities of the routes to the museum city from all the other cities of Never, if the travelers strictly follow the directions of the signposts. The government of Never cares about their citizens, so they want to set the signposts in a way which minimizes this sum. Help them determine the minimum possible sum for all n possible options of the city where the museum can be built.
Input
The first line contains a single integer n (2 β€ n β€ 2000) β the number of cities in Never.
The following n - 1 lines contain the description of the road network. The i-th of these lines contains n - i integers. The j-th integer in the i-th line denotes the perishability of the road between cities i and i + j.
All road perishabilities are between 1 and 109, inclusive.
Output
For each city in order from 1 to n, output the minimum possible sum of perishabilities of the routes to this city from all the other cities of Never if the signposts are set in a way which minimizes this sum.
Examples
Input
3
1 2
3
Output
2
2
3
Input
6
2 9 9 6 6
7 1 9 10
9 2 5
4 10
8
Output
6
5
7
5
7
11
Note
The first example is explained by the picture below. From left to right, there is the initial road network and the optimal directions of the signposts in case the museum is built in city 1, 2 and 3, respectively. The museum city is represented by a blue circle, the directions of the signposts are represented by green arrows.
For instance, if the museum is built in city 3, then the signpost in city 1 must be directed to city 3, while the signpost in city 2 must be directed to city 1. Then the route from city 1 to city 3 will have perishability 2, while the route from city 2 to city 3 will have perishability 1. The sum of perishabilities of these routes is 3.
<image>
### Response
```cpp
#include <bits/stdc++.h>
template <class T>
T Min(const T &a, const T &b) {
return a < b ? a : b;
}
template <class T>
T Max(const T &a, const T &b) {
return a > b ? a : b;
}
template <class T>
bool Chkmin(T &a, const T &b) {
return a > b ? a = b, 1 : 0;
}
template <class T>
bool Chkmax(T &a, const T &b) {
return a < b ? a = b, 1 : 0;
}
class fast_input {
private:
static const int SIZE = 1 << 15 | 1;
char buf[SIZE], *front, *back;
void Next(char &c) {
if (front == back) back = (front = buf) + fread(buf, 1, SIZE, stdin);
c = front == back ? (char)EOF : *front++;
}
public:
template <class T>
void operator()(T &x) {
char c, f = 1;
for (Next(c); !isdigit(c); Next(c))
if (c == '-') f = -1;
for (x = 0; isdigit(c); Next(c)) x = x * 10 + c - '0';
x *= f;
}
void operator()(char &c, char l = 'a', char r = 'z') {
for (Next(c); c > r || c < l; Next(c))
;
}
} input;
struct edge {
int u, v, w;
explicit edge(int u = 0, int v = 0, int w = 0) : u(u), v(v), w(w) {}
bool operator<(const edge &o) const { return w < o.w; }
};
const int SN = 2000 + 47;
const int SE = SN * SN;
const long long INF = 0x3f3f3f3f3f3f3f3fLL;
edge e[SE];
int n, cnt;
long long ans[SN];
int main() {
int x, y, z;
input(n);
for (int i = (1), i_end = (n); i < i_end; ++i)
for (int j = (i + 1), j_end = (n); j <= j_end; ++j)
input(x), e[++cnt] = edge(i, j, x);
std::sort(e + 1, e + cnt + 1);
memset(ans, 0x3f, sizeof ans);
for (int i = (1), i_end = (cnt); i <= i_end; ++i) {
x = e[i].w;
Chkmin(ans[e[i].u], ans[e[i].v] + x - e[1].w);
Chkmin(ans[e[i].v], ans[e[i].u] + x - e[1].w);
Chkmin(ans[e[i].u], 2 * x + 1LL * (n - 3) * e[1].w);
Chkmin(ans[e[i].v], 2 * x + 1LL * (n - 3) * e[1].w);
}
for (int i = (1), i_end = (n); i <= i_end; ++i)
printf(
"%I64d"
"\n",
ans[i]);
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
In a flower bed, there are N flowers, numbered 1,2,......,N. Initially, the heights of all flowers are 0. You are given a sequence h=\\{h_1,h_2,h_3,......\\} as input. You would like to change the height of Flower k to h_k for all k (1 \leq k \leq N), by repeating the following "watering" operation:
* Specify integers l and r. Increase the height of Flower x by 1 for all x such that l \leq x \leq r.
Find the minimum number of watering operations required to satisfy the condition.
Constraints
* 1 \leq N \leq 100
* 0 \leq h_i \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
h_1 h_2 h_3 ...... h_N
Output
Print the minimum number of watering operations required to satisfy the condition.
Examples
Input
4
1 2 2 1
Output
2
Input
5
3 1 2 3 1
Output
5
Input
8
4 23 75 0 23 96 50 100
Output
221
### Response
```cpp
// C - Grand Garden
#include <bits/stdc++.h>
using namespace std;
using vi = vector<int>;
#define rp(i,n) for(int i=0;i<(n);i++)
int main(){
int N; cin>>N;
vi H(N);
rp(i,N)cin>>H[i];
int V = 0;
rp(i,N) V+=H[i];
int E = 0;
rp(i,N-1) E += min(H[i], H[i+1]);
cout<< V-E <<endl;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').
Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.
Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.
It is guaranteed that the answer exists.
Input
The first line of the input contains one integer n (3 β€ n β€ 3 β
10^5, n is divisible by 3) β the number of characters in s.
The second line contains the string s consisting of exactly n characters '0', '1' and '2'.
Output
Print one string β the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.
Because n is divisible by 3 it is obvious that the answer exists. And it is obvious that there is only one possible answer.
Examples
Input
3
121
Output
021
Input
6
000000
Output
001122
Input
6
211200
Output
211200
Input
6
120110
Output
120120
### Response
```cpp
#include <bits/stdc++.h>
const double PI =
3.141592653589793238462643383279502884197169399375105820974944;
using namespace std;
const int MOD = 1e9 + 7;
double gcd(double a, double b) { return a < 0.01 ? b : gcd(fmod(b, a), a); }
template <typename T>
T mymax(T a, T b) {
return (a > b) ? a : b;
}
template <typename T>
T mymax(T a, T b, T c) {
return mymax(a, mymax(b, c));
}
template <typename T>
T mymin(T a, T b) {
return (a < b) ? a : b;
}
template <typename T>
T mymin(T a, T b, T c) {
return mymin(a, mymin(b, c));
}
template <typename T>
T power(T x, T y) {
T res = 1;
x = x % MOD;
while (y > 0) {
if (y & 1) res = (res * x) % MOD;
y = y >> 1;
x = (x * x) % MOD;
}
return res;
}
template <typename T>
void swap(T *x, T *y) {
T temp;
temp = *y;
*y = *x;
*x = temp;
}
template <typename T>
T mod(T a) {
if (a > 0)
return a;
else
return -a;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
int n;
cin >> n;
string s;
cin >> s;
int f[3] = {0};
for (auto l : s) {
f[l - '0']++;
}
int req = n / 3;
for (int i = 0; i <= s.size() - 1; i++) {
int h = s[i] - '0';
if (f[h] > req) {
for (int j = 0; j <= 2; j++) {
if (f[j] < req && j < h) {
f[h]--;
f[j]++;
s[i] = (char)(j + '0');
break;
}
}
}
}
for (int i = s.size() - 1; i >= 0; i--) {
int h = s[i] - '0';
if (f[h] > req) {
for (int j = 2; j >= 0; j--) {
if (f[j] < req && j > h) {
f[h]--;
f[j]++;
s[i] = (char)(j + '0');
break;
}
}
}
}
cout << s << endl;
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most βn/2β vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of queries.
Then t queries follow.
The first line of each query contains two integers n and m (2 β€ n β€ 2 β
10^5, n - 1 β€ m β€ min(2 β
10^5, (n(n-1))/(2))) β the number of vertices and the number of edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 β€ v_i, u_i β€ n, u_i β v_i), which are the indices of vertices connected by the edge.
There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i β u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that β m β€ 2 β
10^5 over all queries.
Output
For each query print two lines.
In the first line print k (1 β€ βn/2β) β the number of chosen vertices.
In the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
Example
Input
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
Output
2
1 3
3
4 3 6
Note
In the first query any vertex or any pair of vertices will suffice.
<image>
Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> g;
vector<int> e;
vector<int> o;
vector<bool> visited;
void bfs() {
queue<int> q;
q.push(1);
bool flag = true;
while (!q.empty()) {
flag = !flag;
int si = q.size();
while (si--) {
int u = q.front();
q.pop();
if (flag)
e.push_back(u);
else
o.push_back(u);
visited[u] = true;
for (auto it : g[u]) {
if (visited[it] == false) {
visited[it] = true;
q.push(it);
}
}
}
}
}
int main() {
int t;
cin >> t;
while (t--) {
o.clear();
e.clear();
int n, m;
cin >> n >> m;
visited.clear();
g = vector<vector<int>>(n + 1);
for (int i = 0; i <= n; i++) visited.push_back(false);
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
bfs();
if (o.size() < e.size()) {
cout << o.size() << "\n";
for (int i = 0; i < o.size(); i++) cout << o[i] << " ";
cout << "\n";
} else {
cout << e.size() << "\n";
for (int i = 0; i < e.size(); i++) cout << e[i] << " ";
cout << "\n";
}
}
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Karnaugh is a poor farmer who has a very small field. He wants to reclaim wasteland in the kingdom to get a new field. But the king who loves regular shape made a rule that a settler can only get a rectangular land as his field. Thus, Karnaugh should get the largest rectangular land suitable for reclamation.
The map of the wasteland is represented with a 5 x 5 grid as shown in the following figures, where '1' represents a place suitable for reclamation and '0' represents a sandy place. Your task is to find the largest rectangle consisting only of 1's in the map, and to report the size of the rectangle. The size of a rectangle is defined by the number of 1's in it. Note that there may be two or more largest rectangles of the same size.
<image>
Figure 1. The size of the largest rectangles is 4.
There are two largest rectangles (shaded).
<image>
Figure 2. The size of the largest rectangle is 3.
There is one largest rectangle (shaded).
Input
The input consists of maps preceded by an integer m indicating the number of input maps.
m
map1
map2
map3
...
mapm
Two maps are separated by an empty line.
Each mapk is in the following format:
p p p p p
p p p p p
p p p p p
p p p p p
p p p p p
Each p is a character either '1' or '0'. Two p's in the same line are separated by a space character. Here, the character '1' shows a place suitable for reclamation and '0' shows a sandy place. Each map contains at least one '1'.
Output
The size of the largest rectangle(s) for each input map should be shown each in a separate line.
Example
Input
3
1 1 0 1 0
0 1 1 1 1
1 0 1 0 1
0 1 1 1 0
0 1 1 0 0
0 1 0 1 1
0 1 0 1 0
0 0 1 0 0
0 0 1 1 0
1 0 1 0 0
1 1 1 1 0
0 1 1 1 0
0 1 1 0 1
0 1 1 1 0
0 0 0 0 1
Output
4
3
8
### Response
```cpp
#include<bits/stdc++.h>
#define r(i,n) for(int i=0;i<n;i++)
using namespace std;
int main(){
int n;
char c;
cin>>n;
r(o,n){
int a[5][5],sum=0;
r(i,5)r(j,5)cin>>a[i][j];
r(i,5)r(j,5)if(j&&a[i][j])a[i][j]+=a[i][j-1];
r(i,5)r(j,5){
if(a[i][j]){
int p=a[i][j],x=1;
sum=max(sum,p);
for(int k=i+1;k<5;k++){
if(!a[k][j])break;
p=min(p,a[k][j]);
x++;
sum=max(sum,x*p);
}
sum=max(sum,x*p);
}
}
cout<<sum<<endl;
}
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
There are n products in the shop. The price of the i-th product is a_i. The owner of the shop wants to equalize the prices of all products. However, he wants to change prices smoothly.
In fact, the owner of the shop can change the price of some product i in such a way that the difference between the old price of this product a_i and the new price b_i is at most k. In other words, the condition |a_i - b_i| β€ k should be satisfied (|x| is the absolute value of x).
He can change the price for each product not more than once. Note that he can leave the old prices for some products. The new price b_i of each product i should be positive (i.e. b_i > 0 should be satisfied for all i from 1 to n).
Your task is to find out the maximum possible equal price B of all productts with the restriction that for all products the condiion |a_i - B| β€ k should be satisfied (where a_i is the old price of the product and B is the same new price of all products) or report that it is impossible to find such price B.
Note that the chosen price B should be integer.
You should answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 100) β the number of queries. Each query is presented by two lines.
The first line of the query contains two integers n and k (1 β€ n β€ 100, 1 β€ k β€ 10^8) β the number of products and the value k. The second line of the query contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^8), where a_i is the price of the i-th product.
Output
Print q integers, where the i-th integer is the answer B on the i-th query.
If it is impossible to equalize prices of all given products with restriction that for all products the condition |a_i - B| β€ k should be satisfied (where a_i is the old price of the product and B is the new equal price of all products), print -1. Otherwise print the maximum possible equal price of all products.
Example
Input
4
5 1
1 1 2 3 1
4 2
6 4 8 5
2 2
1 6
3 5
5 2 5
Output
2
6
-1
7
Note
In the first example query you can choose the price B=2. It is easy to see that the difference between each old price and each new price B=2 is no more than 1.
In the second example query you can choose the price B=6 and then all the differences between old and new price B=6 will be no more than 2.
In the third example query you cannot choose any suitable price B. For any value B at least one condition out of two will be violated: |1-B| β€ 2, |6-B| β€ 2.
In the fourth example query all values B between 1 and 7 are valid. But the maximum is 7, so it's the answer.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base ::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int test;
cin >> test;
while (test--) {
long int n, k;
cin >> n >> k;
long int small = INT_MAX;
long int big = INT_MIN;
for (int i = 0; i < n; i++) {
long int number;
cin >> number;
big = max(big, number);
small = min(small, number);
}
if (abs(big - small) > 2 * k)
cout << -1 << endl;
else
cout << small + k << endl;
}
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
You have matrix a of size n Γ n. Let's number the rows of the matrix from 1 to n from top to bottom, let's number the columns from 1 to n from left to right. Let's use aij to represent the element on the intersection of the i-th row and the j-th column.
Matrix a meets the following two conditions:
* for any numbers i, j (1 β€ i, j β€ n) the following inequality holds: aij β₯ 0;
* <image>.
Matrix b is strictly positive, if for any numbers i, j (1 β€ i, j β€ n) the inequality bij > 0 holds. You task is to determine if there is such integer k β₯ 1, that matrix ak is strictly positive.
Input
The first line contains integer n (2 β€ n β€ 2000) β the number of rows and columns in matrix a.
The next n lines contain the description of the rows of matrix a. The i-th line contains n non-negative integers ai1, ai2, ..., ain (0 β€ aij β€ 50). It is guaranteed that <image>.
Output
If there is a positive integer k β₯ 1, such that matrix ak is strictly positive, print "YES" (without the quotes). Otherwise, print "NO" (without the quotes).
Examples
Input
2
1 0
0 1
Output
NO
Input
5
4 5 6 1 2
1 2 3 4 5
6 4 1 2 4
1 1 1 1 1
4 4 4 4 4
Output
YES
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct edge {
int to, next;
} e[2002 * 2002];
int head[2002], cnte;
void add(int u, int v) {
e[++cnte].to = v;
e[cnte].next = head[u];
head[u] = cnte;
}
int n, low[2002], dfn[2002], cntdfn, stk[2002], top, cntcyc;
bool incyc[2002];
void tarjan(int u) {
low[u] = dfn[u] = ++cntdfn;
stk[++top] = u;
for (int i = head[u]; i; i = e[i].next) {
int v = e[i].to;
if (!dfn[v]) {
tarjan(v);
low[u] = min(low[u], low[v]);
} else if (!incyc[v]) {
low[u] = min(low[u], dfn[v]);
}
}
if (dfn[u] == low[u]) {
cntcyc++;
int x;
do {
x = stk[top];
top--;
incyc[x] = 1;
} while (x != u);
}
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) {
int x;
scanf("%d", &x);
if (x) add(i, j);
}
for (int i = 1; i <= n; i++) {
if (!dfn[i]) tarjan(i);
}
puts(cntcyc == 1 ? "YES" : "NO");
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
You are given an angle ang.
The Jury asks You to find such regular n-gon (regular polygon with n vertices) that it has three vertices a, b and c (they can be non-consecutive) with \angle{abc} = ang or report that there is no such n-gon.
<image>
If there are several answers, print the minimal one. It is guarantied that if answer exists then it doesn't exceed 998244353.
Input
The first line contains single integer T (1 β€ T β€ 180) β the number of queries.
Each of the next T lines contains one integer ang (1 β€ ang < 180) β the angle measured in degrees.
Output
For each query print single integer n (3 β€ n β€ 998244353) β minimal possible number of vertices in the regular n-gon or -1 if there is no such n.
Example
Input
4
54
50
2
178
Output
10
18
90
180
Note
The answer for the first query is on the picture above.
The answer for the second query is reached on a regular 18-gon. For example, \angle{v_2 v_1 v_6} = 50^{\circ}.
The example angle for the third query is \angle{v_{11} v_{10} v_{12}} = 2^{\circ}.
In the fourth query, minimal possible n is 180 (not 90).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1000000007;
const long double EPS = 1e-10;
const int dyx[4][2] = {{0, 1}, {-1, 0}, {0, -1}, {1, 0}};
const int MAX_N = 400;
int ans[181];
void init() {
fill(ans, ans + 181, -1);
for (int i = 3; i <= MAX_N; ++i) {
double min_deg = 180.0 / i;
for (int deg = 1; deg <= 180; ++deg) {
if (ans[deg] != -1) continue;
if (deg - floor(deg / min_deg + EPS) * min_deg < EPS &&
deg <= min_deg * double(i - 2))
ans[deg] = i;
}
}
}
int main() {
init();
int t, deg;
cin >> t;
while (t--) {
cin >> deg;
cout << ans[deg] << "\n";
}
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
One day, Snuke was given a permutation of length N, a_1, a_2, ..., a_N, from his friend.
Find the following:
<image>
Constraints
* 1 β¦ N β¦ 200,000
* (a_1, a_2, ..., a_N) is a permutation of (1, 2, ..., N).
Input
The input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the answer.
Note that the answer may not fit into a 32-bit integer.
Examples
Input
3
2 1 3
Output
9
Input
4
1 3 2 4
Output
19
Input
8
5 4 8 1 2 6 7 3
Output
85
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
ll N; cin >> N;
vector<pair<ll,ll>> a(N);
for(ll i = 0; i < N; i++){ cin >> a[i].first; a[i].second = i+1;}
sort(a.begin(),a.end());
set<ll> se;
se.insert(0); se.insert(N+1);
ll ans = 0;
for(ll i = 0; i < N; i++){
ll r = a[i].second;
se.insert(r);
auto itr = se.lower_bound(r);
auto itr1 = itr; auto itr2 = itr;
itr1--; itr2++;
ll res = (r-*itr1)*(*itr2-r);
ans += res*a[i].first;
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path.
You are given l and r. For all integers from l to r, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times.
Solve the problem to show that it's not a NP problem.
Input
The first line contains two integers l and r (2 β€ l β€ r β€ 109).
Output
Print single integer, the integer that appears maximum number of times in the divisors.
If there are multiple answers, print any of them.
Examples
Input
19 29
Output
2
Input
3 6
Output
3
Note
Definition of a divisor: <https://www.mathsisfun.com/definitions/divisor-of-an-integer-.html>
The first example: from 19 to 29 these numbers are divisible by 2: {20, 22, 24, 26, 28}.
The second example: from 3 to 6 these numbers are divisible by 3: {3, 6}.
### Response
```cpp
#include <bits/stdc++.h>
int main() {
long long int a, b;
scanf("%lld %lld", &a, &b);
if (a == b)
printf("%lld", a);
else
printf("2");
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s = "ac?b?c" then we can obtain the following strings: ["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"].
Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 10^{9} + 7.
A subsequence of the string t is such a sequence that can be derived from the string t after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" β a subsequence consisting of letters at positions (2, 5, 6) and a subsequence consisting of letters at positions (3, 5, 6).
Input
The first line of the input contains one integer n (3 β€ n β€ 200 000) β the length of s.
The second line of the input contains the string s of length n consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".
Output
Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 10^{9} + 7.
Examples
Input
6
ac?b?c
Output
24
Input
7
???????
Output
2835
Input
9
cccbbbaaa
Output
0
Input
5
a???c
Output
46
Note
In the first example, we can obtain 9 strings:
* "acabac" β there are 2 subsequences "abc",
* "acabbc" β there are 4 subsequences "abc",
* "acabcc" β there are 4 subsequences "abc",
* "acbbac" β there are 2 subsequences "abc",
* "acbbbc" β there are 3 subsequences "abc",
* "acbbcc" β there are 4 subsequences "abc",
* "accbac" β there is 1 subsequence "abc",
* "accbbc" β there are 2 subsequences "abc",
* "accbcc" β there are 2 subsequences "abc".
So, there are 2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long mod = 1e9 + 7;
long long n;
cin >> n;
string s;
cin >> s;
long long a = 0, ab = 0, abc = 0, val = 1;
for (int i = 0; i < s.length(); i++) {
if (s[i] == 'a') {
a += val;
a %= mod;
}
if (s[i] == 'b') {
ab += a;
ab %= mod;
}
if (s[i] == 'c') {
abc += ab;
abc %= mod;
}
if (s[i] == '?') {
abc = 3 * abc + ab;
abc %= mod;
ab = 3 * ab + a;
ab %= mod;
a = 3 * a + val;
a %= mod;
val *= 3;
val %= mod;
}
}
cout << abc << "\n";
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Taro is planning a long trip by train during the summer vacation. However, in order for Taro, who is a high school student, to travel as far as possible during the summer vacation, which has only one month, he cannot make a good plan unless he finds the cheapest and the fastest way. Let's create a program to help Taro's plan so that he can enjoy a wonderful trip.
<image>
Create a program that outputs the minimum amount or the shortest time in response to inquiries by inputting track information and the number of stations.
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 m
a1 b1 cost1 time1
a2 b2 cost2 time2
::
an bn costn timen
k
p1 q1 r1
p2 q2 r2
::
pk qk rk
The first line gives the number of track information n (1 β€ n β€ 3000) and the number of stations m (1 β€ m β€ 100).
The following n lines give information on the i-th line. As information on each line, the numbers ai, bi (1 β€ ai, bi β€ m) of the two stations connecting the lines, the toll costi (1 β€ costi β€ 1000), and the travel time timei (1 β€ timei β€ 1000) are given. I will. However, each station shall be numbered in order from 1 to m. If ai and bi are connected by railroad tracks, both ai to bi and bi to ai can be moved at the same rate and time.
The following line is given the number of queries k (1 β€ k β€ 200). The next k line is given the i-th query. For each query, the departure station pi, the arrival station qi, and the type of value to output ri (0 or 1) are given. Inquiries must have a route.
The number of datasets does not exceed 50.
Output
Outputs the minimum amount or minimum time on one line for each data set. When ri is 0, the minimum amount is output, and when ri is 1, the minimum time is output.
Example
Input
6 5
1 2 200 10
1 4 400 15
1 3 250 25
2 4 100 10
4 5 150 20
3 5 300 20
2
1 5 0
1 5 1
0 0
Output
450
35
### Response
```cpp
#include <cstdio>
#include <algorithm>
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define lengthof(x) (sizeof(x) / sizeof(*(x)))
#define INF 1 << 20
#define MAX_M 101
using namespace std;
int main(){
int n, m, a, b, c, t, p, q, r, s;
int C[MAX_M][MAX_M], T[MAX_M][MAX_M];
while(true){
scanf("%d %d", &n, &m);
if((n | m) == 0){
break;
}
fill((int*) C, (int*)(C + lengthof(C)), INF);
fill((int*) T, (int*)(T + lengthof(T)), INF);
REP(i,n){
scanf("%d %d %d %d", &a, &b, &c, &t);
C[a][b] = C[b][a] = c;
T[a][b] = T[b][a] = t;
}
REP(k,m+1){
REP(i,m+1){
REP(j,m+1){
C[i][j] = min(C[i][j], C[i][k] + C[k][j]);
T[i][j] = min(T[i][j], T[i][k] + T[k][j]);
}
}
}
scanf("%d", &s);
REP(i,s){
scanf("%d %d %d", &p, &q, &r);
if(r == 0){
printf("%d\n", C[p][q]);
}
else{
printf("%d\n", T[p][q]);
}
}
}
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
The Smart Beaver from ABBYY has once again surprised us! He has developed a new calculating device, which he called the "Beaver's Calculator 1.0". It is very peculiar and it is planned to be used in a variety of scientific problems.
To test it, the Smart Beaver invited n scientists, numbered from 1 to n. The i-th scientist brought ki calculating problems for the device developed by the Smart Beaver from ABBYY. The problems of the i-th scientist are numbered from 1 to ki, and they must be calculated sequentially in the described order, since calculating each problem heavily depends on the results of calculating of the previous ones.
Each problem of each of the n scientists is described by one integer ai, j, where i (1 β€ i β€ n) is the number of the scientist, j (1 β€ j β€ ki) is the number of the problem, and ai, j is the number of resource units the calculating device needs to solve this problem.
The calculating device that is developed by the Smart Beaver is pretty unusual. It solves problems sequentially, one after another. After some problem is solved and before the next one is considered, the calculating device allocates or frees resources.
The most expensive operation for the calculating device is freeing resources, which works much slower than allocating them. It is therefore desirable that each next problem for the calculating device requires no less resources than the previous one.
You are given the information about the problems the scientists offered for the testing. You need to arrange these problems in such an order that the number of adjacent "bad" pairs of problems in this list is minimum possible. We will call two consecutive problems in this list a "bad pair" if the problem that is performed first requires more resources than the one that goes after it. Do not forget that the problems of the same scientist must be solved in a fixed order.
Input
The first line contains integer n β the number of scientists. To lessen the size of the input, each of the next n lines contains five integers ki, ai, 1, xi, yi, mi (0 β€ ai, 1 < mi β€ 109, 1 β€ xi, yi β€ 109) β the number of problems of the i-th scientist, the resources the first problem requires and three parameters that generate the subsequent values of ai, j. For all j from 2 to ki, inclusive, you should calculate value ai, j by formula ai, j = (ai, j - 1 * xi + yi) mod mi, where a mod b is the operation of taking the remainder of division of number a by number b.
To get the full points for the first group of tests it is sufficient to solve the problem with n = 2, 1 β€ ki β€ 2000.
To get the full points for the second group of tests it is sufficient to solve the problem with n = 2, 1 β€ ki β€ 200000.
To get the full points for the third group of tests it is sufficient to solve the problem with 1 β€ n β€ 5000, 1 β€ ki β€ 5000.
Output
On the first line print a single number β the number of "bad" pairs in the optimal order.
If the total number of problems does not exceed 200000, also print <image> lines β the optimal order of the problems. On each of these lines print two integers separated by a single space β the required number of resources for the problem and the number of the scientist who offered this problem, respectively. The scientists are numbered from 1 to n in the order of input.
Examples
Input
2
2 1 1 1 10
2 3 1 1 10
Output
0
1 1
2 1
3 2
4 2
Input
2
3 10 2 3 1000
3 100 1 999 1000
Output
2
10 1
23 1
49 1
100 2
99 2
98 2
Note
In the first sample n = 2, k1 = 2, a1, 1 = 1, a1, 2 = 2, k2 = 2, a2, 1 = 3, a2, 2 = 4. We've got two scientists, each of them has two calculating problems. The problems of the first scientist require 1 and 2 resource units, the problems of the second one require 3 and 4 resource units. Let's list all possible variants of the calculating order (each problem is characterized only by the number of resource units it requires): (1, 2, 3, 4), (1, 3, 2, 4), (3, 1, 2, 4), (1, 3, 4, 2), (3, 4, 1, 2), (3, 1, 4, 2).
Sequence of problems (1, 3, 2, 4) has one "bad" pair (3 and 2), (3, 1, 4, 2) has two "bad" pairs (3 and 1, 4 and 2), and (1, 2, 3, 4) has no "bad" pairs.
### Response
```cpp
#include <bits/stdc++.h>
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
const int inf = 0x3f3f3f3f;
inline long long read() {
register long long x = 0, f = 1;
register char c = getchar();
for (; !isdigit(c); c = getchar())
if (c == '-') f = -1;
for (; isdigit(c); c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
return x * f;
}
void write(long long x) {
if (x < 0) x = -x, putchar('-');
if (x >= 10) write(x / 10);
putchar(x % 10 + '0');
}
void writeln(long long x) {
write(x);
puts("");
}
const int maxn = 2e5;
pair<pair<int, int>, int> a[maxn];
int K, c, x, y, m, n, cnt, t, mx;
int main() {
n = read();
for (register int i = (1); i <= int(n); ++i) {
int K = read(), c = read(), x = read(), y = read(), m = read();
t = 0;
for (register int j = (1); j <= int(K); ++j) {
if (cnt <= maxn) a[++cnt] = make_pair(make_pair(t, c), i);
if (j < K && c > (1ll * c * x + y) % m) t++;
c = (1ll * c * x + y) % m;
}
mx = max(mx, t);
}
sort(a + 1, a + 1 + cnt);
writeln(mx);
if (cnt <= maxn)
for (register int i = (1); i <= int(cnt); ++i)
printf("%d %d\n", a[i].first.second, a[i].second);
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
You found a mysterious function f. The function takes two strings s1 and s2. These strings must consist only of lowercase English letters, and must be the same length.
The output of the function f is another string of the same length. The i-th character of the output is equal to the minimum of the i-th character of s1 and the i-th character of s2.
For example, f("ab", "ba") = "aa", and f("nzwzl", "zizez") = "niwel".
You found two strings x and y of the same length and consisting of only lowercase English letters. Find any string z such that f(x, z) = y, or print -1 if no such string z exists.
Input
The first line of input contains the string x.
The second line of input contains the string y.
Both x and y consist only of lowercase English letters, x and y have same length and this length is between 1 and 100.
Output
If there is no string z such that f(x, z) = y, print -1.
Otherwise, print a string z such that f(x, z) = y. If there are multiple possible answers, print any of them. The string z should be the same length as x and y and consist only of lowercase English letters.
Examples
Input
ab
aa
Output
ba
Input
nzwzl
niwel
Output
xiyez
Input
ab
ba
Output
-1
Note
The first case is from the statement.
Another solution for the second case is "zizez"
There is no solution for the third case. That is, there is no z such that f("ab", z) = "ba".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n, m, a, b, x, ans, num[20], mii = 100000000;
string s, s1, s2;
int main() {
cin >> s >> s1;
for (int i = 0; i < s.size(); i++) {
if (s[i] < s1[i]) return cout << -1, 0;
}
cout << s1;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
The king's birthday dinner was attended by k guests. The dinner was quite a success: every person has eaten several dishes (though the number of dishes was the same for every person) and every dish was served alongside with a new set of kitchen utensils.
All types of utensils in the kingdom are numbered from 1 to 100. It is known that every set of utensils is the same and consist of different types of utensils, although every particular type may appear in the set at most once. For example, a valid set of utensils can be composed of one fork, one spoon and one knife.
After the dinner was over and the guests were dismissed, the king wondered what minimum possible number of utensils could be stolen. Unfortunately, the king has forgotten how many dishes have been served for every guest but he knows the list of all the utensils left after the dinner. Your task is to find the minimum possible number of stolen utensils.
Input
The first line contains two integer numbers n and k (1 β€ n β€ 100, 1 β€ k β€ 100) β the number of kitchen utensils remaining after the dinner and the number of guests correspondingly.
The next line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 100) β the types of the utensils remaining. Equal values stand for identical utensils while different values stand for different utensils.
Output
Output a single value β the minimum number of utensils that could be stolen by the guests.
Examples
Input
5 2
1 2 2 1 3
Output
1
Input
10 3
1 3 3 1 3 5 5 5 5 100
Output
14
Note
In the first example it is clear that at least one utensil of type 3 has been stolen, since there are two guests and only one such utensil. But it is also possible that every person received only one dish and there were only six utensils in total, when every person got a set (1, 2, 3) of utensils. Therefore, the answer is 1.
One can show that in the second example at least 2 dishes should have been served for every guest, so the number of utensils should be at least 24: every set contains 4 utensils and every one of the 3 guests gets two such sets. Therefore, at least 14 objects have been stolen. Please note that utensils of some types (for example, of types 2 and 4 in this example) may be not present in the set served for dishes.
### Response
```cpp
#include <bits/stdc++.h>
int main() {
int n, k, i, A[101], h = 0, S = 0, max = 0, bluda = 0;
scanf("%d%d", &n, &k);
for (i = 0; i < 100; i++) {
A[i] = 0;
}
for (i = 0; i < n; i++) {
scanf("%d", &h);
A[h - 1]++;
}
for (i = 0; i < 100; i++) {
if (A[i] > max) max = A[i];
}
if (max % k != 0) {
bluda = max / k + 1;
} else {
bluda = max / k;
}
for (i = 0; i < 100; i++) {
if (A[i] != 0) {
A[i] = bluda * k - A[i];
S = S + A[i];
}
}
printf("%d\n", S);
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes.
Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the i-th safe from the left is called safe i. There are n banknotes left in all the safes in total. The i-th banknote is in safe xi. Oleg is now at safe a. There are two security guards, one of which guards the safe b such that b < a, i.e. the first guard is to the left of Oleg. The other guard guards the safe c so that c > a, i.e. he is to the right of Oleg.
The two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather.
Input
The first line of input contains three space-separated integers, a, b and c (1 β€ b < a < c β€ 109), denoting the positions of Oleg, the first security guard and the second security guard, respectively.
The next line of input contains a single integer n (1 β€ n β€ 105), denoting the number of banknotes.
The next line of input contains n space-separated integers x1, x2, ..., xn (1 β€ xi β€ 109), denoting that the i-th banknote is located in the xi-th safe. Note that xi are not guaranteed to be distinct.
Output
Output a single integer: the maximum number of banknotes Oleg can take.
Examples
Input
5 3 7
8
4 7 5 5 3 6 2 8
Output
4
Input
6 5 7
5
1 5 7 92 3
Output
0
Note
In the first example Oleg can take the banknotes in positions 4, 5, 6 (note that there are 2 banknotes at position 5). Oleg can't take the banknotes in safes 7 and 8 because he can't run into the second security guard. Similarly, Oleg cannot take the banknotes at positions 3 and 2 because he can't run into the first security guard. Thus, he can take a maximum of 4 banknotes.
For the second sample, Oleg can't take any banknotes without bumping into any of the security guards.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
int a, b, c;
cin >> a >> b >> c;
int n;
cin >> n;
int ans = 0;
while (n--) {
int x;
cin >> x;
if (x > b and x < c) ans++;
}
cout << ans << "\n";
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Okabe and Super Hacker Daru are stacking and removing boxes. There are n boxes numbered from 1 to n. Initially there are no boxes on the stack.
Okabe, being a control freak, gives Daru 2n commands: n of which are to add a box to the top of the stack, and n of which are to remove a box from the top of the stack and throw it in the trash. Okabe wants Daru to throw away the boxes in the order from 1 to n. Of course, this means that it might be impossible for Daru to perform some of Okabe's remove commands, because the required box is not on the top of the stack.
That's why Daru can decide to wait until Okabe looks away and then reorder the boxes in the stack in any way he wants. He can do it at any point of time between Okabe's commands, but he can't add or remove boxes while he does it.
Tell Daru the minimum number of times he needs to reorder the boxes so that he can successfully complete all of Okabe's commands. It is guaranteed that every box is added before it is required to be removed.
Input
The first line of input contains the integer n (1 β€ n β€ 3Β·105) β the number of boxes.
Each of the next 2n lines of input starts with a string "add" or "remove". If the line starts with the "add", an integer x (1 β€ x β€ n) follows, indicating that Daru should add the box with number x to the top of the stack.
It is guaranteed that exactly n lines contain "add" operations, all the boxes added are distinct, and n lines contain "remove" operations. It is also guaranteed that a box is always added before it is required to be removed.
Output
Print the minimum number of times Daru needs to reorder the boxes to successfully complete all of Okabe's commands.
Examples
Input
3
add 1
remove
add 2
add 3
remove
remove
Output
1
Input
7
add 3
add 2
add 1
remove
add 4
remove
remove
remove
add 6
add 7
add 5
remove
remove
remove
Output
2
Note
In the first sample, Daru should reorder the boxes after adding box 3 to the stack.
In the second sample, Daru should reorder the boxes after adding box 4 and box 7 to the stack.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
stack<int> s;
void reorder() {}
int main(void) {
int n;
cin >> n;
int count = 0;
int i = 1;
while (n) {
string temp = "";
int x;
cin >> temp;
if (temp.compare("add") == 0) {
cin >> x;
s.push(x);
} else if (temp.compare("remove") == 0) {
if (!s.empty() && (s.top() != i)) {
while (!s.empty()) s.pop();
count++;
} else {
if (!s.empty()) s.pop();
}
i++;
n--;
}
}
cout << count;
return 0;
}
``` |
### Prompt
Generate a cpp solution 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>
using namespace std;
void fast() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
const long long N = 2002;
long long dr[4] = {0, 0, 1, -1};
long long dc[4] = {1, -1, 0, 0};
long long ddr[8] = {0, 0, 1, -1, 1, -1, 1, -1};
long long ddc[8] = {1, -1, 0, 0, 1, -1, -1, 1};
long long ddr1[8] = {1, 1, -1, -1, 2, 2, -2, -2};
long long ddc1[8] = {2, -2, 2, -2, 1, -1, 1, -1};
int32_t main() {
fast();
long long n, x, x1 = 0, x2 = 1023;
long long y1 = 0, y2 = 0, y3 = 0;
y1 = x2;
char ch;
cin >> n;
while (n--) {
cin >> ch >> x;
if (ch == '&') {
x1 &= x;
x2 &= x;
} else if (ch == '^') {
x1 ^= x;
x2 ^= x;
} else {
x1 |= x;
x2 |= x;
}
}
for (long long i = 0; i < 10; i++) {
bool f1, f2;
long long t1 = (1 << i);
f1 = (x1 & t1);
f2 = (x2 & t1);
if (f1 == 1 && f2 == 0)
y3 |= t1;
else if (f1 == 1 && f2 == 1)
y2 |= t1;
else if (f1 == 0 && f2 == 0)
y1 ^= t1;
}
cout << "3\n& " << y1 << "\n| " << y2 << "\n^ " << y3;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
Input
The first line contains two integers n and k (1 β€ n β€ 105, 1 β€ k β€ 109) β the number of share prices, and the amount of rubles some price decreases each second.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) β the initial prices.
Output
Print the only line containing the minimum number of seconds needed for prices to become equal, of Β«-1Β» if it is impossible.
Examples
Input
3 3
12 9 15
Output
3
Input
2 2
10 9
Output
-1
Input
4 1
1 1000000000 1000000000 1000000000
Output
2999999997
Note
Consider the first example.
Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.
There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.
In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.
In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3fffffff;
const int SINF = 0x7fffffff;
const long long LINF = 0x3fffffffffffffff;
const long long SLINF = 0x7fffffffffffffff;
const int MAXN = 100007;
int n, k;
int a[MAXN];
void init();
void input();
void work();
int main() {
init();
input();
work();
}
void init() { ios::sync_with_stdio(false); }
void input() {
scanf("%d%d", &n, &k);
for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
}
void work() {
int mini = INF;
for (int i = 1; i <= n; ++i) mini = (((mini) < (a[i])) ? (mini) : (a[i]));
long long ans = 0;
for (int i = 1; i <= n; ++i) {
if ((a[i] - mini) % k == 0)
ans += (a[i] - mini) / k;
else {
printf("-1\n");
return;
}
}
printf("%I64d\n", ans);
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
char s[1000005];
char *s1, *s2;
long long su1, su2;
int main() {
int l1, l2;
while (scanf("%s", s) != EOF) {
s1 = strtok(s, "^");
s2 = strtok(NULL, "^");
l1 = strlen(s1);
l2 = strlen(s2);
su1 = 0;
su2 = 0;
for (int i = 0; i < l1; i++) {
if (isdigit(s1[i])) {
su1 = su1 + (s1[i] - '0') * (l1 - i);
}
}
for (int i = 0; i < l2; i++) {
if (isdigit(s2[i])) {
su2 = su2 + (s2[i] - '0') * (i + 1);
}
}
if (su1 < su2) printf("right\n");
if (su1 == su2) printf("balance\n");
if (su1 > su2) printf("left\n");
}
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Let's call beauty of an array b_1, b_2, β¦, b_n (n > 1) β min_{1 β€ i < j β€ n} |b_i - b_j|.
You're given an array a_1, a_2, β¦ a_n and a number k. Calculate the sum of beauty over all subsequences of the array of length exactly k. As this number can be very large, output it modulo 998244353.
A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements.
Input
The first line contains integers n, k (2 β€ k β€ n β€ 1000).
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^5).
Output
Output one integer β the sum of beauty over all subsequences of the array of length exactly k. As this number can be very large, output it modulo 998244353.
Examples
Input
4 3
1 7 3 5
Output
8
Input
5 5
1 10 100 1000 10000
Output
9
Note
In the first example, there are 4 subsequences of length 3 β [1, 7, 3], [1, 3, 5], [7, 3, 5], [1, 7, 5], each of which has beauty 2, so answer is 8.
In the second example, there is only one subsequence of length 5 β the whole array, which has the beauty equal to |10-1| = 9.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long mod = 998244353;
const int N = 1e3 + 5;
long long pwr(long long x, long long y);
int a[N], n, k;
int dp[N][N];
int solve(int x) {
for (int i = 0; i < n + 1; i++) {
for (int j = 0; j < k + 1; j++) dp[i][j] = 0;
}
dp[0][0] = 1;
int pos = 0;
for (int i = 1; i < n + 1; i++) {
while ((a[i] - a[pos + 1]) >= x) ++pos;
for (int j = 0; j < k + 1; j++) {
dp[i][j] = dp[i - 1][j] % mod;
}
for (int j = 1; j < k + 1; j++) {
dp[i][j] = (dp[i][j] + dp[pos][j - 1]) % mod;
}
}
return dp[n][k];
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> k;
for (int i = 1; i < n + 1; i++) {
cin >> a[i];
}
sort(a + 1, a + n + 1);
int ans = 0;
for (int i = 1; i < 1e5 / (k - 1) + 1; i++) {
ans = (ans + solve(i)) % mod;
}
cout << ans << endl;
return 0;
}
long long pwr(long long x, long long y) {
long long ans = 1;
x = x % mod;
while (y > 0) {
if (y & 1) ans = (x * (ans % mod)) % mod;
x = (x * x) % mod;
y = y / 2;
}
return ans % mod;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
The official capital and the cultural capital of Berland are connected by a single road running through n regions. Each region has a unique climate, so the i-th (1 β€ i β€ n) region has a stable temperature of ti degrees in summer.
This summer a group of m schoolchildren wants to get from the official capital to the cultural capital to visit museums and sights. The trip organizers transport the children between the cities in buses, but sometimes it is very hot. Specifically, if the bus is driving through the i-th region and has k schoolchildren, then the temperature inside the bus is ti + k degrees.
Of course, nobody likes it when the bus is hot. So, when the bus drives through the i-th region, if it has more than Ti degrees inside, each of the schoolchild in the bus demands compensation for the uncomfortable conditions. The compensation is as large as xi rubles and it is charged in each region where the temperature in the bus exceeds the limit.
To save money, the organizers of the trip may arbitrarily add or remove extra buses in the beginning of the trip, and between regions (of course, they need at least one bus to pass any region). The organizers can also arbitrarily sort the children into buses, however, each of buses in the i-th region will cost the organizers costi rubles. Please note that sorting children into buses takes no money.
Your task is to find the minimum number of rubles, which the organizers will have to spend to transport all schoolchildren.
Input
The first input line contains two integers n and m (1 β€ n β€ 105; 1 β€ m β€ 106) β the number of regions on the way and the number of schoolchildren in the group, correspondingly. Next n lines contain four integers each: the i-th line contains ti, Ti, xi and costi (1 β€ ti, Ti, xi, costi β€ 106). The numbers in the lines are separated by single spaces.
Output
Print the only integer β the minimum number of roubles the organizers will have to spend to transport all schoolchildren.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
2 10
30 35 1 100
20 35 10 10
Output
120
Input
3 100
10 30 1000 1
5 10 1000 3
10 40 1000 100000
Output
200065
Note
In the first sample the organizers will use only one bus to travel through the first region. However, the temperature in the bus will equal 30 + 10 = 40 degrees and each of 10 schoolchildren will ask for compensation. Only one bus will transport the group through the second region too, but the temperature inside won't exceed the limit. Overall, the organizers will spend 100 + 10 + 10 = 120 rubles.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
long long ans = 0;
for (int i = (0); i < (n); ++i) {
long long t, T, x, cost;
cin >> t >> T >> x >> cost;
if (t >= T) {
ans += cost + m * x;
continue;
}
long long aux1 = cost;
if (m > (T - t)) aux1 += m * x;
long long aux2 = (long long)ceil((double)(m - (T - t)) / (T - t)) + 1;
aux2 *= cost;
ans += min(aux1, aux2);
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Joe has been hurt on the Internet. Now he is storming around the house, destroying everything in his path.
Joe's house has n floors, each floor is a segment of m cells. Each cell either contains nothing (it is an empty cell), or has a brick or a concrete wall (always something one of three). It is believed that each floor is surrounded by a concrete wall on the left and on the right.
Now Joe is on the n-th floor and in the first cell, counting from left to right. At each moment of time, Joe has the direction of his gaze, to the right or to the left (always one direction of the two). Initially, Joe looks to the right.
Joe moves by a particular algorithm. Every second he makes one of the following actions:
* If the cell directly under Joe is empty, then Joe falls down. That is, he moves to this cell, the gaze direction is preserved.
* Otherwise consider the next cell in the current direction of the gaze.
* If the cell is empty, then Joe moves into it, the gaze direction is preserved.
* If this cell has bricks, then Joe breaks them with his forehead (the cell becomes empty), and changes the direction of his gaze to the opposite.
* If this cell has a concrete wall, then Joe just changes the direction of his gaze to the opposite (concrete can withstand any number of forehead hits).
Joe calms down as soon as he reaches any cell of the first floor.
The figure below shows an example Joe's movements around the house.
<image>
Determine how many seconds Joe will need to calm down.
Input
The first line contains two integers n and m (2 β€ n β€ 100, 1 β€ m β€ 104).
Next n lines contain the description of Joe's house. The i-th of these lines contains the description of the (n - i + 1)-th floor of the house β a line that consists of m characters: "." means an empty cell, "+" means bricks and "#" means a concrete wall.
It is guaranteed that the first cell of the n-th floor is empty.
Output
Print a single number β the number of seconds Joe needs to reach the first floor; or else, print word "Never" (without the quotes), if it can never happen.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
3 5
..+.#
#+..+
+.#+.
Output
14
Input
4 10
...+.##+.+
+#++..+++#
++.#++++..
.+##.++#.+
Output
42
Input
2 2
..
++
Output
Never
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10;
int cnt[100 + 2][N + 2];
string s[100 + 2];
set<int> on[100 + 2], of[100 + 2];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> s[i];
s[i] = "#" + s[i] + "#";
for (int j = 1; j <= m; j++) {
if (s[i][j] == '.')
of[i].insert(j);
else
on[i].insert(j);
}
on[i].insert(0);
on[i].insert(m + 1);
of[i].insert(-1);
of[i].insert(m + 2);
}
long long ans = 0;
int a = 1, b = 1, d = 1;
while (true) {
if (clock() > CLOCKS_PER_SEC * 0.8) cout << "Never\n", exit(0);
if (a == n) break;
if (d) {
int cr = *on[a].lower_bound(b);
int nx = *of[a + 1].lower_bound(b);
if (nx < cr) {
ans += nx - b + 1;
a++;
b = nx;
} else {
ans += cr - b;
b = cr - 1;
d ^= 1;
if (s[a][cr] == '+') {
on[a].erase(cr);
s[a][cr] = '.';
of[a].insert(cr);
}
}
} else {
auto it1 = on[a].upper_bound(b);
auto it2 = of[a + 1].upper_bound(b);
it1--, it2--;
int cr = *it1, nx = *it2;
if (nx > cr) {
ans += b - nx + 1;
a++;
b = nx;
} else {
ans += b - cr;
b = cr + 1;
d ^= 1;
if (s[a][cr] == '+') {
on[a].erase(cr);
s[a][cr] = '.';
of[a].insert(cr);
}
}
}
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
There is a cube which consists of n Γ n Γ n small cubes. Small cubes have marks on their surfaces. An example where n = 4 is shown in the following figure.
<image>
Then, as shown in the figure above (right), make a hole that penetrates horizontally or vertically from the marked surface to the opposite surface.
Your job is to create a program that reads the positions marked n and counts the number of small cubes with no holes.
Input
The input consists of several datasets. Each dataset is given in the following format:
n h
c1 a1 b1
c2 a2 b2
..
..
..
ch ah bh
h is an integer indicating the number of marks. The h lines that follow enter the positions of the h marks. The coordinate axes shown in the figure below will be used to specify the position of the mark. (x, y, z) = (1, 1, 1) is the lower left cube, and (x, y, z) = (n, n, n) is the upper right cube.
<image>
ci is a string indicating the plane marked with the i-th. ci is one of "xy", "xz", and "yz", indicating that the i-th mark is on the xy, xz, and yz planes, respectively.
ai and bi indicate the coordinates on the plane indicated by ci. For the xy, xz, and yz planes, ai and bi indicate the plane coordinates (x, y), (x, z), and (y, z), respectively. For example, in the above figure, the values ββof ci, ai, and bi of marks A, B, and C are "xy 4 4", "xz 1 2", and "yz 2 3", respectively.
When both n and h are 0, it indicates the end of input.
You can assume that n β€ 500 and h β€ 200.
Output
For each dataset, print the number of non-perforated cubes on one line.
Example
Input
4 3
xy 4 4
xz 1 2
yz 2 3
4 5
xy 1 1
xy 3 3
xz 3 3
yz 2 1
yz 3 3
0 0
Output
52
46
### Response
```cpp
#include<iostream>
#include<set>
using namespace std;
struct Point{int x,y,z;};
bool operator<(Point a,Point b)
{
return a.x!=b.x?(a.x<b.x):(a.y!=b.y?a.y<b.y:a.z<b.z);
}
int main()
{
int n,h,a,b;
string c;
int i;
while(cin>>n>>h,n|h){
set<Point>hole;
while(h-->0){
cin>>c>>a>>b;
if(c=="xy"){
for(i=n;i>=1;i--){
Point p={a,b,i};
hole.insert(p);
}
}else if(c=="xz"){
for(i=n;i>=1;i--){
Point p={a,i,b};
hole.insert(p);
}
}else{
for(i=n;i>=1;i--){
Point p={i,a,b};
hole.insert(p);
}
}
}
cout<<n*n*n-hole.size()<<endl;
}
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
You are given a function f written in some basic language. The function accepts an integer value, which is immediately written into some variable x. x is an integer variable and can be assigned values from 0 to 2^{32}-1. The function contains three types of commands:
* for n β for loop;
* end β every command between "for n" and corresponding "end" is executed n times;
* add β adds 1 to x.
After the execution of these commands, value of x is returned.
Every "for n" is matched with "end", thus the function is guaranteed to be valid. "for n" can be immediately followed by "end"."add" command can be outside of any for loops.
Notice that "add" commands might overflow the value of x! It means that the value of x becomes greater than 2^{32}-1 after some "add" command.
Now you run f(0) and wonder if the resulting value of x is correct or some overflow made it incorrect.
If overflow happened then output "OVERFLOW!!!", otherwise print the resulting value of x.
Input
The first line contains a single integer l (1 β€ l β€ 10^5) β the number of lines in the function.
Each of the next l lines contains a single command of one of three types:
* for n (1 β€ n β€ 100) β for loop;
* end β every command between "for n" and corresponding "end" is executed n times;
* add β adds 1 to x.
Output
If overflow happened during execution of f(0), then output "OVERFLOW!!!", otherwise print the resulting value of x.
Examples
Input
9
add
for 43
end
for 10
for 15
add
end
add
end
Output
161
Input
2
for 62
end
Output
0
Input
11
for 100
for 100
for 100
for 100
for 100
add
end
end
end
end
end
Output
OVERFLOW!!!
Note
In the first example the first "add" is executed 1 time, the second "add" is executed 150 times and the last "add" is executed 10 times. Note that "for n" can be immediately followed by "end" and that "add" can be outside of any for loops.
In the second example there are no commands "add", thus the returning value is 0.
In the third example "add" command is executed too many times, which causes x to go over 2^{32}-1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long MAX = 4294967295;
int main() {
int l;
string in;
long long val = 0;
cin >> l;
long long x = 0;
stack<long long> fors;
for (int i = 0; i < l; i++) {
cin >> in;
if (in == "for") {
cin >> val;
long long curr = val;
if (!fors.empty()) {
if (fors.top() == -1) {
curr = -1;
} else {
curr *= fors.top();
}
}
if (curr > MAX) {
curr = -1;
}
fors.push(curr);
}
if (in == "end") {
fors.pop();
}
if (in == "add") {
if (fors.empty()) {
x++;
} else {
if (fors.top() == -1) {
cout << "OVERFLOW!!!";
return 0;
}
x += fors.top();
}
if (x > MAX) {
cout << "OVERFLOW!!!";
return 0;
}
}
}
cout << x;
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
How to make a cake you'll never eat.
Ingredients.
* 2 carrots
* 0 calories
* 100 g chocolate spread
* 1 pack of flour
* 1 egg
Method.
1. Put calories into the mixing bowl.
2. Take carrots from refrigerator.
3. Chop carrots.
4. Take chocolate spread from refrigerator.
5. Put chocolate spread into the mixing bowl.
6. Combine pack of flour into the mixing bowl.
7. Fold chocolate spread into the mixing bowl.
8. Add chocolate spread into the mixing bowl.
9. Put pack of flour into the mixing bowl.
10. Add egg into the mixing bowl.
11. Fold pack of flour into the mixing bowl.
12. Chop carrots until choped.
13. Pour contents of the mixing bowl into the baking dish.
Serves 1.
Input
The only line of input contains a sequence of integers a0, a1, ... (1 β€ a0 β€ 100, 0 β€ ai β€ 1000 for i β₯ 1).
Output
Output a single integer.
Examples
Input
4 1 2 3 4
Output
30
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long int n;
long long int res = 0;
cin >> n;
for (long long int i = 0; i < ((long long int)(n)); ++i) {
long long int a;
cin >> a;
res += a * (i + 1);
}
cout << res << endl;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Life is not easy for the perfectly common variable named Vasya. Wherever it goes, it is either assigned a value, or simply ignored, or is being used!
Vasya's life goes in states of a program. In each state, Vasya can either be used (for example, to calculate the value of another variable), or be assigned a value, or ignored. Between some states are directed (oriented) transitions.
A path is a sequence of states v1, v2, ..., vx, where for any 1 β€ i < x exists a transition from vi to vi + 1.
Vasya's value in state v is interesting to the world, if exists path p1, p2, ..., pk such, that pi = v for some i (1 β€ i β€ k), in state p1 Vasya gets assigned a value, in state pk Vasya is used and there is no state pi (except for p1) where Vasya gets assigned a value.
Help Vasya, find the states in which Vasya's value is interesting to the world.
Input
The first line contains two space-separated integers n and m (1 β€ n, m β€ 105) β the numbers of states and transitions, correspondingly.
The second line contains space-separated n integers f1, f2, ..., fn (0 β€ fi β€ 2), fi described actions performed upon Vasya in state i: 0 represents ignoring, 1 β assigning a value, 2 β using.
Next m lines contain space-separated pairs of integers ai, bi (1 β€ ai, bi β€ n, ai β bi), each pair represents the transition from the state number ai to the state number bi. Between two states can be any number of transitions.
Output
Print n integers r1, r2, ..., rn, separated by spaces or new lines. Number ri should equal 1, if Vasya's value in state i is interesting to the world and otherwise, it should equal 0. The states are numbered from 1 to n in the order, in which they are described in the input.
Examples
Input
4 3
1 0 0 2
1 2
2 3
3 4
Output
1
1
1
1
Input
3 1
1 0 2
1 3
Output
1
0
1
Input
3 1
2 0 1
1 3
Output
0
0
0
Note
In the first sample the program states can be used to make the only path in which the value of Vasya interests the world, 1 <image> 2 <image> 3 <image> 4; it includes all the states, so in all of them Vasya's value is interesting to the world.
The second sample the only path in which Vasya's value is interesting to the world is , β 1 <image> 3; state 2 is not included there.
In the third sample we cannot make from the states any path in which the value of Vasya would be interesting to the world, so the value of Vasya is never interesting to the world.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const double pi = 3.141592653589793;
const int INF = 2000000000;
const int mod = 1000000007;
const int N = 100000000;
const int base = 10;
vector<int> read(string s) {
vector<int> a;
for (int i = (int)s.length(); i > 0; i -= 1)
if (i < 1)
a.push_back(atoi(s.substr(0, i).c_str()));
else
a.push_back(atoi(s.substr(i - 1, 1).c_str()));
return a;
}
vector<int> add(vector<int> a, vector<int> b) {
int carry = 0;
for (size_t i = 0; i < max(a.size(), b.size()) || carry; ++i) {
if (i == a.size()) a.push_back(0);
a[i] += carry + (i < b.size() ? b[i] : 0);
carry = a[i] >= base;
if (carry) a[i] -= base;
}
return a;
}
vector<int> mul(vector<int> a, int b) {
int carry = 0;
for (size_t i = 0; i < a.size() || carry; ++i) {
if (i == a.size()) a.push_back(0);
long long cur = carry + a[i] * 1ll * b;
a[i] = int(cur % base);
carry = int(cur / base);
}
while (a.size() > 1 && a.back() == 0) a.pop_back();
return a;
}
vector<int> c;
vector<int> a[100005], b[100005];
vector<bool> f;
vector<bool> f1;
int main() {
vector<int> queue;
int n, x, y, m;
cin >> n >> m;
for (int(i) = (0); (i) < (n); (i)++) {
cin >> x;
c.push_back(x);
}
for (int(i) = (0); (i) < (m); (i)++) {
cin >> x >> y;
x--;
y--;
a[x].push_back(y);
b[y].push_back(x);
}
for (int(i) = (0); (i) < (c.size()); (i)++)
if (c[i] == 1) {
queue.push_back(i);
f.push_back(true);
} else {
f.push_back(false);
}
for (int(i) = (0); (i) < (queue.size()); (i)++) {
for (int(j) = (0); (j) < (a[queue[i]].size()); (j)++) {
if (f[a[queue[i]][j]]) continue;
queue.push_back(a[queue[i]][j]);
f[a[queue[i]][j]] = true;
}
}
queue.clear();
for (int(i) = (0); (i) < (c.size()); (i)++)
if (c[i] == 2) {
queue.push_back(i);
f1.push_back(true);
} else {
f1.push_back(false);
}
for (int(i) = (0); (i) < (queue.size()); (i)++) {
for (int(j) = (0); (j) < (b[queue[i]].size()); (j)++) {
if (f1[b[queue[i]][j]]) continue;
f1[b[queue[i]][j]] = true;
if (c[b[queue[i]][j]] == 1) continue;
queue.push_back(b[queue[i]][j]);
}
}
for (int(i) = (0); (i) < (n); (i)++)
if (f[i] && f1[i]) {
cout << 1 << endl;
} else {
cout << 0 << endl;
}
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Vladimir wants to modernize partitions in his office. To make the office more comfortable he decided to remove a partition and plant several bamboos in a row. He thinks it would be nice if there are n bamboos in a row, and the i-th from the left is ai meters high.
Vladimir has just planted n bamboos in a row, each of which has height 0 meters right now, but they grow 1 meter each day. In order to make the partition nice Vladimir can cut each bamboo once at any height (no greater that the height of the bamboo), and then the bamboo will stop growing.
Vladimir wants to check the bamboos each d days (i.e. d days after he planted, then after 2d days and so on), and cut the bamboos that reached the required height. Vladimir wants the total length of bamboo parts he will cut off to be no greater than k meters.
What is the maximum value d he can choose so that he can achieve what he wants without cutting off more than k meters of bamboo?
Input
The first line contains two integers n and k (1 β€ n β€ 100, 1 β€ k β€ 1011) β the number of bamboos and the maximum total length of cut parts, in meters.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) β the required heights of bamboos, in meters.
Output
Print a single integer β the maximum value of d such that Vladimir can reach his goal.
Examples
Input
3 4
1 3 5
Output
3
Input
3 40
10 30 50
Output
32
Note
In the first example Vladimir can check bamboos each 3 days. Then he will cut the first and the second bamboos after 3 days, and the third bamboo after 6 days. The total length of cut parts is 2 + 0 + 1 = 3 meters.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct query {
long long l, r, x;
};
int n, a[109];
long long m;
int main() {
cin >> n >> m;
vector<query> v;
vector<long long> cp = {1LL << 60};
for (int i = 0; i < n; i++) {
cin >> a[i];
int pr = sqrt(a[i]);
for (int j = 1; j < pr; j++) {
v.push_back(query{j, j + 1, (a[i] + j - 1) / j});
cp.push_back(j);
}
cp.push_back(pr);
int r = (a[i] + pr - 1) / pr, ptr = pr;
for (int j = r; j > 1; j--) {
v.push_back(query{ptr, (a[i] + j - 2) / (j - 1), j});
ptr = v.back().r;
cp.push_back(ptr);
}
v.push_back(query{ptr, 1LL << 60, 1});
}
sort(cp.begin(), cp.end());
cp.erase(unique(cp.begin(), cp.end()), cp.end());
vector<long long> sum(cp.size());
for (query i : v) {
int pl = lower_bound(cp.begin(), cp.end(), i.l) - cp.begin();
int pr = lower_bound(cp.begin(), cp.end(), i.r) - cp.begin();
sum[pl] += i.x;
sum[pr] -= i.x;
}
for (int i = 1; i < cp.size(); i++) sum[i] += sum[i - 1];
long long ret = 0;
for (int i = 0; i < cp.size() - 1; i++) {
long long r = min(cp[i + 1] - 1, (m + sum[0]) / sum[i]);
if (cp[i] <= r) ret = max(ret, r);
}
cout << ret << endl;
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
Recently, Vladimir got bad mark in algebra again. To avoid such unpleasant events in future he decided to train his arithmetic skills. He wrote four integer numbers a, b, c, d on the blackboard. During each of the next three minutes he took two numbers from the blackboard (not necessarily adjacent) and replaced them with their sum or their product. In the end he got one number. Unfortunately, due to the awful memory he forgot that number, but he remembers four original numbers, sequence of the operations and his surprise because of the very small result. Help Vladimir remember the forgotten number: find the smallest number that can be obtained from the original numbers by the given sequence of operations.
Input
First line contains four integers separated by space: 0 β€ a, b, c, d β€ 1000 β the original numbers. Second line contains three signs ('+' or '*' each) separated by space β the sequence of the operations in the order of performing. ('+' stands for addition, '*' β multiplication)
Output
Output one integer number β the minimal result which can be obtained.
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
1 1 1 1
+ + *
Output
3
Input
2 2 2 2
* * +
Output
8
Input
1 2 3 4
* + +
Output
9
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long a[5], ans = 0x7f7f7f7f7f7f7f7f;
char p[4];
inline void dfs(const int &left) {
if (left == 1) {
register long long s;
for (register int i = 1; i <= 4; i++)
if (a[i] != -1) {
s = a[i];
break;
}
ans = (ans < s ? ans : s);
return;
}
for (register int i = 1; i <= 4; i++)
for (register int j = i + 1; j <= 4; j++) {
register int k = 4 - left + 1;
if (a[i] == -1 || a[j] == -1 || p[k] == '-') continue;
register long long x = a[i], y = a[j];
register char t = p[k];
p[k] = '-';
a[j] = -1;
if (t == '+')
a[i] = x + y;
else
a[i] = x * y;
dfs(left - 1);
a[i] = x;
a[j] = y;
p[k] = t;
}
}
int main() {
for (register int i = 1; i <= 4; i++) cin >> a[i];
for (register int i = 1; i <= 3; i++) cin >> p[i];
dfs(4);
cout << ans;
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling the cubes downwards. When Chris switches the gravity, it begins to pull all the cubes to the right side of the box. The figure shows the initial and final configurations of the cubes in the box: the cubes that have changed their position are highlighted with orange.
<image>
Given the initial configuration of the toy cubes in the box, find the amounts of cubes in each of the n columns after the gravity switch!
Input
The first line of input contains an integer n (1 β€ n β€ 100), the number of the columns in the box. The next line contains n space-separated integer numbers. The i-th number ai (1 β€ ai β€ 100) denotes the number of cubes in the i-th column.
Output
Output n integer numbers separated by spaces, where the i-th number is the amount of cubes in the i-th column after the gravity switch.
Examples
Input
4
3 2 1 2
Output
1 2 2 3
Input
3
2 3 8
Output
2 3 8
Note
The first example case is shown on the figure. The top cube of the first column falls to the top of the last column; the top cube of the second column falls to the top of the third column; the middle cube of the first column falls to the top of the second column.
In the second example case the gravity switch does not change the heights of the columns.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
vector<long long int> v;
long long int n, m, a;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a;
v.push_back(a);
}
sort(v.begin(), v.end());
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Someone give a strange birthday present to Ivan. It is hedgehog β connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog.
Let us define k-multihedgehog as follows:
* 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1.
* For all k β₯ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift.
Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog.
Input
First line of input contains 2 integers n, k (1 β€ n β€ 10^{5}, 1 β€ k β€ 10^{9}) β number of vertices and hedgehog parameter.
Next n-1 lines contains two integers u v (1 β€ u, v β€ n; u β v) β indices of vertices connected by edge.
It is guaranteed that given graph is a tree.
Output
Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise.
Examples
Input
14 2
1 4
2 4
3 4
4 13
10 5
11 5
12 5
14 5
5 13
6 7
8 6
13 6
9 6
Output
Yes
Input
3 1
1 3
2 3
Output
No
Note
2-multihedgehog from the first example looks like this:
<image>
Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13].
Tree from second example is not a hedgehog because degree of center should be at least 3.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int n, k, l;
vector<vector<long long int> > adj;
vector<bool> visited;
long long int d[100006] = {INT_MAX};
long long int MOD = 1000000007;
long long int level[100006];
long long int dis2[100006];
long long int degree[100006] = {0};
long long int distance(long long int x) {
long long int last = x;
for (long long int j = 1; j <= n; j++) d[j] = INT_MAX;
queue<long long int> q;
q.push(x);
d[x] = 0;
long long int node = x;
while (!q.empty()) {
node = q.front();
q.pop();
for (auto it : adj[node]) {
if (d[it] > (d[node] + 1)) {
d[it] = d[node] + 1;
q.push(it);
}
}
}
return node;
}
void get_farthest2(int node) {
int i;
for (i = 0; i <= 100001; i++) {
dis2[i] = MOD;
}
dis2[node] = 0;
queue<int> q;
q.push(node);
while (!q.empty()) {
int x = q.front();
q.pop();
for (auto it : adj[x]) {
if (dis2[it] > (dis2[x] + 1)) {
dis2[it] = dis2[x] + 1;
q.push(it);
}
}
}
}
int main() {
for (long long int i = 0; i <= 100001; i++) {
level[i] = MOD;
degree[i] = 0;
}
long long int i, a, b;
cin >> n >> k;
if (n == 1) {
cout << "No" << endl;
return 0;
}
adj.resize(n + 1);
long long int center = 0;
for (i = 1; i < n; i++) {
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
degree[a]++;
degree[b]++;
}
long long int x = distance(1);
long long int y = distance(x);
get_farthest2(y);
long long int ans = 1;
if ((d[y] % 2 == 1) || k > n || (dis2[x] % 2 == 1)) {
cout << "No" << endl;
return 0;
}
for (i = 1; i <= n; i++)
if ((d[i] == dis2[i]) && (adj[i].size() >= 3) && (d[i] == (d[y] / 2))) {
center = i;
break;
}
if (center == 0) {
cout << "No" << endl;
return 0;
}
queue<int> qu;
long long int centre = center;
qu.push(centre);
level[centre] = 1;
while (!qu.empty()) {
int xx = qu.front();
qu.pop();
if (xx == centre && degree[xx] < 3) {
cout << "No";
return 0;
} else if ((degree[xx] < 4) && (level[xx] <= k) && (xx != centre)) {
cout << "No";
return 0;
} else if (level[xx] > k && degree[xx] != 1) {
cout << "No";
return 0;
}
for (auto it : adj[xx]) {
if (level[it] > level[xx] + 1) {
level[it] = level[xx] + 1;
qu.push(it);
}
}
}
cout << "Yes" << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
The fundamental prerequisite for justice is not to be correct, but to be strong. That's why justice is always the victor.
The Cinderswarm Bee. Koyomi knows it.
The bees, according to their nature, live in a tree. To be more specific, a complete binary tree with n nodes numbered from 1 to n. The node numbered 1 is the root, and the parent of the i-th (2 β€ i β€ n) node is <image>. Note that, however, all edges in the tree are undirected.
Koyomi adds m extra undirected edges to the tree, creating more complication to trick the bees. And you're here to count the number of simple paths in the resulting graph, modulo 109 + 7. A simple path is an alternating sequence of adjacent nodes and undirected edges, which begins and ends with nodes and does not contain any node more than once. Do note that a single node is also considered a valid simple path under this definition. Please refer to the examples and notes below for instances.
Input
The first line of input contains two space-separated integers n and m (1 β€ n β€ 109, 0 β€ m β€ 4) β the number of nodes in the tree and the number of extra edges respectively.
The following m lines each contains two space-separated integers u and v (1 β€ u, v β€ n, u β v) β describing an undirected extra edge whose endpoints are u and v.
Note that there may be multiple edges between nodes in the resulting graph.
Output
Output one integer β the number of simple paths in the resulting graph, modulo 109 + 7.
Examples
Input
3 0
Output
9
Input
3 1
2 3
Output
15
Input
2 4
1 2
2 1
1 2
2 1
Output
12
Note
In the first example, the paths are: (1); (2); (3); (1, 2); (2, 1); (1, 3); (3, 1); (2, 1, 3); (3, 1, 2). (For the sake of clarity, the edges between nodes are omitted since there are no multiple edges in this case.)
In the second example, the paths are: (1); (1, 2); (1, 2, 3); (1, 3); (1, 3, 2); and similarly for paths starting with 2 and 3. (5 Γ 3 = 15 paths in total.)
In the third example, the paths are: (1); (2); any undirected edge connecting the two nodes travelled in either direction. (2 + 5 Γ 2 = 12 paths in total.)
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
const int mod = 1e9 + 7;
int add(int x, int y) {
x += y;
if (x >= mod) x -= mod;
return x;
}
int mul(int x, int y) {
long long z = 1LL * x * y;
return z - z / mod * mod;
}
vector<pair<int, int> > g[555];
unordered_map<int, int> q;
int d[555], w[555], p[555][555], tot, ans;
bool vis[555];
int get_id(int x) {
if (q.find(x) == q.end()) {
d[tot] = x;
q[x] = tot++;
}
return q[x];
}
void add_edge(int x) {
if (x == 1) return;
int u = get_id(x), v = get_id(x >> 1);
p[u][v] = p[v][u] = 1;
add_edge(x >> 1);
}
int fcount(int x, int n) {
int res = 0;
if (q.find(x) == q.end()) {
for (int i = 0; 1; i++) {
if (((x + 1) << i) - 1 >= n) {
if ((x << i) <= n) res += n - (x << i) + 1;
break;
} else
res += 1 << i;
}
} else {
res++;
if ((x << 1) <= n && q.find(x << 1) == q.end()) res += fcount(x << 1, n);
if ((x << 1 | 1) <= n && q.find(x << 1 | 1) == q.end())
res += fcount(x << 1 | 1, n);
}
return res;
}
int dfs(int u) {
if (vis[u]) return 0;
vis[u] = 1;
int res = w[u];
for (auto v : g[u]) res = add(res, mul(v.second, dfs(v.first)));
vis[u] = 0;
return res;
}
int main() {
int n, m, i, j, u[5], v[5];
scanf("%d%d", &n, &m);
if (!m) {
printf("%d\n", mul(n, n));
return 0;
}
for (i = 0; i < m; i++) {
scanf("%d%d", &u[i], &v[i]);
add_edge(u[i]);
add_edge(v[i]);
}
for (i = 0; i < m; i++) {
p[q[u[i]]][q[v[i]]]++;
p[q[v[i]]][q[u[i]]]++;
}
for (i = 0; i < tot; i++) {
for (j = 0; j < tot; j++) {
if (p[i][j]) g[i].push_back(pair<int, int>(j, p[i][j]));
}
}
for (i = 0; i < tot; i++) w[i] = fcount(d[i], n);
for (i = 0; i < tot; i++) ans = add(ans, mul(w[i], dfs(i)));
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Snuke loves permutations. He is making a permutation of length N.
Since he hates the integer K, his permutation will satisfy the following:
* Let the permutation be a_1, a_2, ..., a_N. For each i = 1,2,...,N, |a_i - i| \neq K.
Among the N! permutations of length N, how many satisfies this condition?
Since the answer may be extremely large, find the answer modulo 924844033(prime).
Constraints
* 2 β¦ N β¦ 2000
* 1 β¦ K β¦ N-1
Input
The input is given from Standard Input in the following format:
N K
Output
Print the answer modulo 924844033.
Examples
Input
3 1
Output
2
Input
4 1
Output
5
Input
4 2
Output
9
Input
4 3
Output
14
Input
425 48
Output
756765083
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int Maxn = 2005, p = 924844033;
int n, k, ct, arr[Maxn];
long long ans, f[Maxn][Maxn][2][2], fac[Maxn];
int main()
{
scanf("%d%d", &n, &k);
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
for (int i = 1; i <= k; i++)
for (int j = i; j <= n; j += k)
arr[++ct] = j;
arr[0] = -0x3f3f3f3f;
f[0][0][0][0] = 1;
for (int i = 1; i <= n; i++)
{
f[i][0][0][0] = 1;
for (int j = 1; j <= i; j++)
{
f[i][j][0][0] = (f[i - 1][j][0][0] + f[i - 1][j][1][0] + f[i - 1][j - 1][0][0] * (arr[i] - arr[i - 1] == k)) % p;
f[i][j][0][1] = (arr[i + 1] - arr[i] == k) * (f[i - 1][j - 1][0][0] + f[i - 1][j - 1][1][0]) % p;
f[i][j][1][0] = (f[i - 1][j][0][1] + f[i - 1][j][1][1] + (arr[i] - arr[i - 1] == k) * f[i - 1][j - 1][0][1]) % p;
f[i][j][1][1] = (arr[i + 1] - arr[i] == k) * (f[i - 1][j - 1][0][1] + f[i - 1][j - 1][1][1]) % p;
}
}
for (int i = 0; i <= n; i++)
(ans += (i & 1 ? p - 1 : 1) * fac[n - i] % p * (f[n][i][0][0] + f[n][i][1][0])) %= p;
printf("%lld", ans);
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
PolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses.
You're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, if both play optimally?
Input
The first input line contains two integers n and m (1 β€ n, m β€ 103) β number of words PolandBall and EnemyBall know, respectively.
Then n strings follow, one per line β words familiar to PolandBall.
Then m strings follow, one per line β words familiar to EnemyBall.
Note that one Ball cannot know a word more than once (strings are unique), but some words can be known by both players.
Each word is non-empty and consists of no more than 500 lowercase English alphabet letters.
Output
In a single line of print the answer β "YES" if PolandBall wins and "NO" otherwise. Both Balls play optimally.
Examples
Input
5 1
polandball
is
a
cool
character
nope
Output
YES
Input
2 2
kremowka
wadowicka
kremowka
wiedenska
Output
YES
Input
1 2
a
a
b
Output
NO
Note
In the first example PolandBall knows much more words and wins effortlessly.
In the second example if PolandBall says kremowka first, then EnemyBall cannot use that word anymore. EnemyBall can only say wiedenska. PolandBall says wadowicka and wins.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool sortbysec(const pair<long int, long int> &a,
const pair<long int, long int> &b) {
return (a.second < b.second);
}
int main() {
long int n, m, i;
cin >> n >> m;
set<string> s;
string s1;
for (i = 0; i < n + m; i++) {
cin >> s1;
s.insert(s1);
}
i = n + m - s.size();
if (i % 2 == 0) {
n = n - i;
m = m - i;
if (n > m) {
cout << "YES";
} else {
cout << "NO";
}
} else {
n = n - i;
m = m - i;
m--;
if (n > m) {
cout << "YES";
} else {
cout << "NO";
}
}
return 0;
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.