text
stringlengths
424
69.5k
### Prompt Generate a Cpp solution to the following problem: You are given an integer k and a tree T with n nodes (n is even). Let dist(u, v) be the number of edges on the shortest path from node u to node v in T. Let us define a undirected weighted complete graph G = (V, E) as following: * V = \\{x ∣ 1 ≀ x ≀ n \} i.e. the set of integers from 1 to n * E = \{(u, v, w) ∣ 1 ≀ u, v ≀ n, u β‰  v, w = dist(u, v) \} i.e. there is an edge between every pair of distinct nodes, the weight being the distance between their respective nodes in T Your task is simple, find a perfect matching in G with total edge weight k (1 ≀ k ≀ n^2). Input The first line of input contains two integers n, k (2 ≀ n ≀ 100 000, n is even, 1 ≀ k ≀ n^2): number of nodes and the total edge weight of the perfect matching you need to find. The i-th of the following n - 1 lines contains two integers v_i, u_i (1 ≀ v_i, u_i ≀ n) denoting an edge between v_i and u_i in T. It is guaranteed that the given graph is a tree. Output If there are no matchings that satisfy the above condition, output "NO" (without quotes) on a single line. Otherwise, you should output "YES" (without quotes) on the first line of output. You should then output n/2 lines, the i-th line containing p_i, q_i (1 ≀ p_i, q_i ≀ n): the i-th pair of the matching. Examples Input 4 2 1 2 2 3 3 4 Output YES 2 1 3 4 Input 4 4 1 2 2 3 3 4 Output YES 3 1 2 4 Note A tree is a connected acyclic undirected graph. A matching is set of pairwise non-adjacent edges, none of which are loops; that is, no two edges share a common vertex. A perfect matching is a matching which matches all vertices of the graph; that is, every vertex of the graph is incident to exactly one edge of the matching. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long mod = 1000000007; const unsigned gen_seed = std::chrono::system_clock::now().time_since_epoch().count(); std::mt19937_64 gen(gen_seed); std::vector<std::vector<int> > g; int n, l; std::vector<int> tin, tout; int timer; vector<vector<int> > up; std::vector<int> lev; void dfs(int v, int p, int curl) { lev[v] = curl; tin[v] = ++timer; up[v][0] = p; for (int i = 1; i <= l; ++i) up[v][i] = up[up[v][i - 1]][i - 1]; for (size_t i = 0; i < g[v].size(); ++i) { int to = g[v][i]; if (to != p) dfs(to, v, curl + 1); } tout[v] = ++timer; } std::vector<int> maj; std::vector<int> st; int go(int v, int p) { st[v] = 1; for (auto u : g[v]) { if (u == p) continue; st[v] += go(u, v); } for (auto u : g[v]) { if (st[u] * 2 >= n) maj[v] = u; } return st[v]; } bool upper(int a, int b) { return tin[a] <= tin[b] && tout[a] >= tout[b]; } int lca(int a, int b) { if (upper(a, b)) return a; if (upper(b, a)) return b; for (int i = l; i >= 0; --i) if (!upper(up[a][i], b)) a = up[a][i]; return up[a][0]; } int dist(int a, int b) { int c = lca(a, b); return lev[a] + lev[b] - 2 * lev[c]; } std::vector<int> getpath(int a, int b) { int c = lca(a, b); std::vector<int> ret; std::vector<int> rev; while (a != c) { ret.push_back(a); a = up[a][0]; } while (b != c) { rev.push_back(b); b = up[b][0]; } reverse((rev).begin(), (rev).end()); ret.push_back(c); for (auto x : rev) ret.push_back(x); return ret; } long long todist(std::vector<int>& x) { long long ret = 0; for (int i = 0; i < n; i++) if (x[i] > i) ret += dist(x[i], i); return ret; } std::vector<std::pair<int, int> > prmin; int greed(int v, int p) { std::vector<int> stray; for (auto u : g[v]) { if (u == p) continue; int ret = greed(u, v); if (ret != -1) stray.push_back(ret); } stray.push_back(v); while (stray.size() >= 2) { int p = stray.size(); prmin.push_back(make_pair(stray[p - 1], stray[p - 2])); stray.pop_back(); stray.pop_back(); } int ret = -1; if (stray.size() == 1) ret = stray[0]; return ret; } std::vector<int> tomin; int main() { long long k; scanf("%d %lld", &n, &k); l = 1; while ((1 << l) <= n) ++l; tin.resize(n), tout.resize(n), up.resize(n); for (int i = 0; i < n; ++i) up[i].resize(l + 1); lev.resize(n); st = std::vector<int>(n, 0); g.resize(n); for (int i = 0; i < n - 1; i++) { int u, v; scanf("%d %d", &u, &v); u--; v--; g[u].push_back(v); g[v].push_back(u); } if (n == 2) { if (k != 1) cout << "NO\n"; else { cout << "YES\n"; cout << "1 2\n"; } exit(0); } for (int i = 0; i < n; i++) maj.push_back(i); go(0, 0); int root = 0; while (maj[root] != root) root = maj[root]; dfs(root, root, 0); long long mx = 0; for (int i = 0; i < n; i++) mx += lev[i]; std::vector<std::pair<int, int> > ord; for (int i = 0; i < n; i++) ord.push_back(make_pair(tin[i], i)); sort((ord).begin(), (ord).end()); std::vector<std::pair<int, int> > prmax; for (int i = 0; i < n / 2; i++) prmax.push_back(make_pair(ord[i].second, ord[i + n / 2].second)); greed(root, root); long long mn = 0; for (int i = 0; i < n / 2; i++) { mn += dist(prmin[i].first, prmin[i].second); } std::vector<int> tomax(n); tomin.resize(n); for (int i = 0; i < n / 2; i++) { tomin[prmin[i].first] = prmin[i].second; tomin[prmin[i].second] = prmin[i].first; tomax[prmax[i].first] = prmax[i].second; tomax[prmax[i].second] = prmax[i].first; } if (k % 2 != mn % 2 || k < mn || k > mx) { cout << "NO\n"; exit(0); } int eq = 0; while (1) { if (eq == n) break; if (tomin[eq] == tomax[eq]) { eq++; continue; } int cp = tomin[tomax[eq]]; int neq = tomin[eq]; int xeq = tomax[eq]; if (mn == k) break; swap(tomin[cp], tomin[eq]); swap(tomin[xeq], tomin[neq]); long long md = mn - dist(eq, neq) - dist(xeq, cp) + dist(eq, xeq) + dist(cp, neq); if (md == k) break; else if (md < k) { eq++; mn = md; continue; } else { swap(tomin[cp], tomin[eq]); swap(tomin[xeq], tomin[neq]); std::vector<int> path = getpath(eq, cp); for (auto x : path) { if (x == tomin[eq]) { eq = tomin[eq]; path = getpath(eq, cp); break; } } int q = path.size(); for (int i = 0; i < q - 1; i++) { int a = path[i]; int b = path[i + 1]; int ca = tomin[a]; int cb = tomin[b]; swap(tomin[a], tomin[b]); swap(tomin[ca], tomin[cb]); if (ca != b) mn += dist(a, cb) + dist(b, ca) - dist(a, ca) - dist(b, cb); if (mn == k) { printf("YES\n"); for (int i = 0; i < n; i++) { if (tomin[i] > i) printf("%d %d\n", i + 1, tomin[i] + 1); } exit(0); } } for (int i = q - 3; i >= 0; i--) { int a = path[i]; int b = path[i + 1]; int ca = tomin[a]; int cb = tomin[b]; swap(tomin[a], tomin[b]); swap(tomin[ca], tomin[cb]); if (ca != b) mn += dist(a, cb) + dist(b, ca) - dist(a, ca) - dist(b, cb); if (mn == k) { printf("YES\n"); for (int i = 0; i < n; i++) { if (tomin[i] > i) printf("%d %d\n", i + 1, tomin[i] + 1); } exit(0); } } printf("NO\n"); exit(0); } } printf("YES\n"); for (int i = 0; i < n; i++) { if (tomin[i] > i) printf("%d %d\n", i + 1, tomin[i] + 1); } } ```
### Prompt Create a solution in CPP for the following problem: Draw a rectangle which has a height of H cm and a width of W cm. Draw a 1-cm square by single '#'. Constraints * 1 ≀ H ≀ 300 * 1 ≀ W ≀ 300 Input The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space. The input ends with two 0 (when both H and W are zero). Output For each dataset, print the rectangle made of H Γ— W '#'. Print a blank line after each dataset. Example Input 3 4 5 6 2 2 0 0 Output #### #### #### ###### ###### ###### ###### ###### ## ## ### Response ```cpp #include<bits/stdc++.h> using namespace std; int main(){ int h,w; while(1){ cin >>h>>w; if(h==0&&w==0){ break; } else{ for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ cout <<"#"; } cout <<endl; } cout <<endl; } } } ```
### Prompt In cpp, your task is to solve the following problem: You might have remembered Theatre square from the [problem 1A](https://codeforces.com/problemset/problem/1/A). Now it's finally getting repaved. The square still has a rectangular shape of n Γ— m meters. However, the picture is about to get more complicated now. Let a_{i,j} be the j-th square in the i-th row of the pavement. You are given the picture of the squares: * if a_{i,j} = "*", then the j-th square in the i-th row should be black; * if a_{i,j} = ".", then the j-th square in the i-th row should be white. The black squares are paved already. You have to pave the white squares. There are two options for pavement tiles: * 1 Γ— 1 tiles β€” each tile costs x burles and covers exactly 1 square; * 1 Γ— 2 tiles β€” each tile costs y burles and covers exactly 2 adjacent squares of the same row. Note that you are not allowed to rotate these tiles or cut them into 1 Γ— 1 tiles. You should cover all the white squares, no two tiles should overlap and no black squares should be covered by tiles. What is the smallest total price of the tiles needed to cover all the white squares? Input The first line contains a single integer t (1 ≀ t ≀ 500) β€” the number of testcases. Then the description of t testcases follow. The first line of each testcase contains four integers n, m, x and y (1 ≀ n ≀ 100; 1 ≀ m ≀ 1000; 1 ≀ x, y ≀ 1000) β€” the size of the Theatre square, the price of the 1 Γ— 1 tile and the price of the 1 Γ— 2 tile. Each of the next n lines contains m characters. The j-th character in the i-th line is a_{i,j}. If a_{i,j} = "*", then the j-th square in the i-th row should be black, and if a_{i,j} = ".", then the j-th square in the i-th row should be white. It's guaranteed that the sum of n Γ— m over all testcases doesn't exceed 10^5. Output For each testcase print a single integer β€” the smallest total price of the tiles needed to cover all the white squares in burles. Example Input 4 1 1 10 1 . 1 2 10 1 .. 2 1 10 1 . . 3 3 3 7 ..* *.. .*. Output 10 1 20 18 Note In the first testcase you are required to use a single 1 Γ— 1 tile, even though 1 Γ— 2 tile is cheaper. So the total price is 10 burles. In the second testcase you can either use two 1 Γ— 1 tiles and spend 20 burles or use a single 1 Γ— 2 tile and spend 1 burle. The second option is cheaper, thus the answer is 1. The third testcase shows that you can't rotate 1 Γ— 2 tiles. You still have to use two 1 Γ— 1 tiles for the total price of 20. In the fourth testcase the cheapest way is to use 1 Γ— 1 tiles everywhere. The total cost is 6 β‹… 3 = 18. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long power(long long a, long long b) { if (b == 0) return 1; if (b == 1) return a; else { long long t = power(a, b / 2); if (b % 2 == 0) return ((t % 1000000007) * (t % 1000000007)) % 1000000007; else return ((((t % 1000000007) * (t % 1000000007)) % 1000000007) * ((a % 1000000007) % 1000000007)) % 1000000007; } } void solve() { long long n, m, x, y, c = 0, co = 0, ans, i, j; cin >> n >> m >> x >> y; char s[n + 1][m + 1]; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { cin >> s[i][j]; } } for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { if (j == m - 1) { if (s[i][j] == '.') c += x; } else { if (s[i][j] == '.' && s[i][j + 1] == '.') { c += y; j++; } else if (s[i][j] == '.' && s[i][j + 1] != '.') c += x; } } } for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { if (s[i][j] == '.') co++; } } co = co * x; ans = min(c, co); cout << ans << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long t = 1; cin >> t; while (t--) { solve(); } return 0; } ```
### Prompt Construct a cpp code solution to the problem outlined: One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one! Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture. In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses. The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n. Input The only line contains n (1 ≀ n ≀ 25) β€” the required sum of points. Output Print the numbers of ways to get the second card in the required way if the first card is the queen of spades. Examples Input 12 Output 4 Input 20 Output 15 Input 10 Output 0 Note In the first sample only four two's of different suits can earn the required sum of points. In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use. In the third sample there is no card, that would add a zero to the current ten points. ### Response ```cpp #include <bits/stdc++.h> using namespace std; void solve() { long long n; cin >> n; n -= 10; if (n <= 0) { cout << 0; } else { if (n == 10) cout << 15; else if (n <= 11) cout << 4; else cout << 0; } } int main() { ios::sync_with_stdio(0); cin.tie(0); cout << fixed << setprecision(9); solve(); return 0; } ```
### Prompt Generate a Cpp solution to the following problem: There are N children, numbered 1, 2, ..., N. Snuke has decided to distribute x sweets among them. He needs to give out all the x sweets, but some of the children may get zero sweets. For each i (1 \leq i \leq N), Child i will be happy if he/she gets exactly a_i sweets. Snuke is trying to maximize the number of happy children by optimally distributing the sweets. Find the maximum possible number of happy children. Constraints * All values in input are integers. * 2 \leq N \leq 100 * 1 \leq x \leq 10^9 * 1 \leq a_i \leq 10^9 Input Input is given from Standard Input in the following format: N x a_1 a_2 ... a_N Output Print the maximum possible number of happy children. Examples Input 3 70 20 30 10 Output 2 Input 3 10 20 30 10 Output 1 Input 4 1111 1 10 100 1000 Output 4 Input 2 10 20 20 Output 0 ### Response ```cpp #include<bits/stdc++.h> using namespace std; int main(){ long long n,x,cnt=0; long long a[109]; cin>>n>>x; for(int i=0;i<n;i++){ cin>>a[i]; } sort(a,a+n); for(int i=0;i<n;i++){ x-=a[i]; if(x>=0)cnt++; } if(x>0)cnt--; cout<<cnt<<endl; return(0); } ```
### Prompt Develop a solution in Cpp to the problem described below: One day a highly important task was commissioned to Vasya β€” writing a program in a night. The program consists of n lines of code. Vasya is already exhausted, so he works like that: first he writes v lines of code, drinks a cup of tea, then he writes as much as <image> lines, drinks another cup of tea, then he writes <image> lines and so on: <image>, <image>, <image>, ... The expression <image> is regarded as the integral part from dividing number a by number b. The moment the current value <image> equals 0, Vasya immediately falls asleep and he wakes up only in the morning, when the program should already be finished. Vasya is wondering, what minimum allowable value v can take to let him write not less than n lines of code before he falls asleep. Input The input consists of two integers n and k, separated by spaces β€” the size of the program in lines and the productivity reduction coefficient, 1 ≀ n ≀ 109, 2 ≀ k ≀ 10. Output Print the only integer β€” the minimum value of v that lets Vasya write the program in one night. Examples Input 7 2 Output 4 Input 59 9 Output 54 Note In the first sample the answer is v = 4. Vasya writes the code in the following portions: first 4 lines, then 2, then 1, and then Vasya falls asleep. Thus, he manages to write 4 + 2 + 1 = 7 lines in a night and complete the task. In the second sample the answer is v = 54. Vasya writes the code in the following portions: 54, 6. The total sum is 54 + 6 = 60, that's even more than n = 59. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { long long int i, j, a, k, b, c, n, t, m, p, q, d, e, f, y, g, z, h, r, l, x, o; long double aa, bb, ee, dd, ff, kk, gg; vector<long long int> v, s, vv; map<long long int, vector<long long int> > me; map<long long int, long long int> sa, ta, pa, ma; priority_queue<long long int, vector<long long int>, greater<long long int> > aq, tq, pq; string st, et, ft, pt, ct; deque<long long int> de, pe, ne; ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> k; l = 1; r = n * 2; while (l < r) { c = (l + r) / 2; a = c; d = 0; while (c) { d = d + c; c = c / k; } if (d < n) l = a + 1; else r = a; } cout << l << endl; } ```
### Prompt Develop a solution in CPP to the problem described below: Borya has recently found a big electronic display. The computer that manages the display stores some integer number. The number has n decimal digits, the display shows the encoded version of the number, where each digit is shown using some lowercase letter of the English alphabet. There is a legend near the display, that describes how the number is encoded. For each digit position i and each digit j the character c is known, that encodes this digit at this position. Different digits can have the same code characters. Each second the number is increased by 1. And one second after a moment when the number reaches the value that is represented as n 9-s in decimal notation, the loud beep sounds. Andrew knows the number that is stored in the computer. Now he wants to know how many seconds must pass until Borya can definitely tell what was the original number encoded by the display. Assume that Borya can precisely measure time, and that the encoded number will first be increased exactly one second after Borya started watching at the display. Input Input data contains multiple test cases. The first line of input contains t (1 ≀ t ≀ 100) β€” the number of test cases. Each test case is described as follows. The first line of the description contains n (1 ≀ n ≀ 18) β€” the number of digits in the number. The second line contains n decimal digits without spaces (but possibly with leading zeroes) β€” the number initially stored in the display computer. The following n lines contain 10 characters each. The j-th character of the i-th of these lines is the code character for a digit j - 1 in position i, most significant digit positions are described first. Output For each test case print an integer: the number of seconds until Borya definitely knows what was the initial number stored on the display of the computer. Do not print leading zeroes. Example Input 3 2 42 abcdefghij jihgfedcba 2 42 aaaaaaaaaa aaaaaaaaaa 1 2 abcdabcdff Output 0 58 2 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 25; const int g[2] = {23, 37}; char s[maxn][maxn]; long long pw[maxn]; int n; int cas; bool equal(long long a, long long b) { for (int i = 0; i < n; i++, a /= 10, b /= 10) if (s[i][a % 10] != s[i][b % 10]) return 0; return 1; } long long calc(int bit, long long a, long long b) { if (a > b) swap(a, b); long long ans = pw[n] - b; if (!equal(a, b)) return 0; for (int i = bit; i < n; i++) { long long cur = b / (pw[i]) * pw[i]; long long jump = pw[i]; for (int j = 1; j < 10; j++) { cur += jump; long long step = cur - b; if (step >= ans) break; long long ano = a + step; if (!equal(ano, cur)) { ans = min(ans, step); break; } } } return ans; } void work() { ++cas; static char st[maxn]; scanf("%d", &n); scanf("%s", st); reverse(st, st + n); long long v = 0, up = 1; pw[0] = 1; for (int i = 1; i <= n; i++) pw[i] = pw[i - 1] * 10; for (int i = 0; i < n; i++) v = v + (st[i] - 48) * pw[i]; long long ans = 0; for (int i = n - 1; i >= 0; i--) scanf("%s", s[i]); for (int i = 0; i < n; i++) for (int j = 0; j < 10; j++) if (j != st[i] - 48) ans = max(ans, calc(i, v, v - (st[i] - 48) * pw[i] + j * pw[i])); printf("%lld\n", ans); } int main() { int t; scanf("%d", &t); for (; t; t--) work(); return 0; } ```
### Prompt Construct a Cpp code solution to the problem outlined: A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily 7 days! In detail, she can choose any integer k which satisfies 1 ≀ k ≀ r, and set k days as the number of days in a week. Alice is going to paint some n consecutive days on this calendar. On this calendar, dates are written from the left cell to the right cell in a week. If a date reaches the last day of a week, the next day's cell is the leftmost cell in the next (under) row. She wants to make all of the painted cells to be connected by side. It means, that for any two painted cells there should exist at least one sequence of painted cells, started in one of these cells, and ended in another, such that any two consecutive cells in this sequence are connected by side. Alice is considering the shape of the painted cells. Two shapes are the same if there exists a way to make them exactly overlapped using only parallel moves, parallel to the calendar's sides. For example, in the picture, a week has 4 days and Alice paints 5 consecutive days. [1] and [2] are different shapes, but [1] and [3] are equal shapes. <image> Alice wants to know how many possible shapes exists if she set how many days a week has and choose consecutive n days and paints them in calendar started in one of the days of the week. As was said before, she considers only shapes, there all cells are connected by side. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Next t lines contain descriptions of test cases. For each test case, the only line contains two integers n, r (1 ≀ n ≀ 10^9, 1 ≀ r ≀ 10^9). Output For each test case, print a single integer β€” the answer to the problem. Please note, that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language. Example Input 5 3 4 3 2 3 1 13 7 1010000 9999999 Output 4 3 1 28 510049495001 Note In the first test case, Alice can set 1,2,3 or 4 days as the number of days in a week. There are 6 possible paintings shown in the picture, but there are only 4 different shapes. So, the answer is 4. Notice that the last example in the picture is an invalid painting because all cells are not connected by sides. <image> In the last test case, be careful with the overflow issue, described in the output format. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long N = 2e6 + 10; const long long INF = 1e9 + 10; const long long MOD = 1e9 + 7; void solve() { long long n, r; cin >> n >> r; if (n > r) cout << r * (r + 1) / 2 << '\n'; else cout << n * (n - 1) / 2 + 1 << '\n'; } signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long t = 1; cin >> t; while (t--) solve(); return 0; } ```
### Prompt Develop a solution in Cpp to the problem described below: We will buy a product for N yen (the currency of Japan) at a shop. If we use only 1000-yen bills to pay the price, how much change will we receive? Assume we use the minimum number of bills required. Constraints * 1 \leq N \leq 10000 * N is an integer. Input Input is given from Standard Input in the following format: N Output Print the amount of change as an integer. Examples Input 1900 Output 100 Input 3000 Output 0 ### Response ```cpp #include <iostream> using namespace std; int main() { int N; cin >> N; cout << (10000 - N) % 1000; } ```
### Prompt Please formulate a cpp solution to the following problem: Given are N integers A_1,\ldots,A_N. We will choose exactly K of these elements. Find the maximum possible product of the chosen elements. Then, print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive). Constraints * 1 \leq K \leq N \leq 2\times 10^5 * |A_i| \leq 10^9 Input Input is given from Standard Input in the following format: N K A_1 \ldots A_N Output Print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive). Examples Input 4 2 1 2 -3 -4 Output 12 Input 4 3 -1 -2 -3 -4 Output 1000000001 Input 2 1 -1 1000000000 Output 1000000000 Input 10 10 1000000000 100000000 10000000 1000000 100000 10000 1000 100 10 1 Output 999983200 ### Response ```cpp #include <bits/stdc++.h> using namespace std; typedef long long ll; const ll mod=1e9+7; ll A[300001]; int main() { ll n,k; cin>>n>>k; for(int i=0; i<n; i++) cin>>A[i]; sort(A,A+n); ll ans=1,sign=0; int l=0,r=n-1; if(k%2) { ans=A[r]; r--; --k; if(ans<0) sign=1; } while(k) { ll x=A[l]*A[l+1],y=A[r]*A[r-1]; if(sign) { if(x<y) { ans=x%mod*ans%mod; l+=2; } else { ans=y%mod*ans%mod; r-=2; } } else { if(x>y) { ans=x%mod*ans%mod; l+=2; } else { ans=y%mod*ans%mod; r-=2; } } k-=2; } cout<<(ans+mod)%mod<<endl; return 0; } ```
### Prompt Generate a CPP solution to the following problem: Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card. Vasya is watching a recorded football match now and makes notes of all the fouls that he would give a card for. Help Vasya determine all the moments in time when players would be given red cards if Vasya were the judge. For each player, Vasya wants to know only the first moment of time when he would receive a red card from Vasya. Input The first line contains the name of the team playing at home. The second line contains the name of the team playing away. Both lines are not empty. The lengths of both lines do not exceed 20. Each line contains only of large English letters. The names of the teams are distinct. Next follows number n (1 ≀ n ≀ 90) β€” the number of fouls. Each of the following n lines contains information about a foul in the following form: * first goes number t (1 ≀ t ≀ 90) β€” the minute when the foul occurs; * then goes letter "h" or letter "a" β€” if the letter is "h", then the card was given to a home team player, otherwise the card was given to an away team player; * then goes the player's number m (1 ≀ m ≀ 99); * then goes letter "y" or letter "r" β€” if the letter is "y", that means that the yellow card was given, otherwise the red card was given. The players from different teams can have the same number. The players within one team have distinct numbers. The fouls go chronologically, no two fouls happened at the same minute. Output For each event when a player received his first red card in a chronological order print a string containing the following information: * The name of the team to which the player belongs; * the player's number in his team; * the minute when he received the card. If no player received a card, then you do not need to print anything. It is possible case that the program will not print anything to the output (if there were no red cards). Examples Input MC CSKA 9 28 a 3 y 62 h 25 y 66 h 42 y 70 h 25 y 77 a 4 y 79 a 25 y 82 h 42 r 89 h 16 y 90 a 13 r Output MC 25 70 MC 42 82 CSKA 13 90 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main(int argc, char *argv[]) { string s[2]; cin >> s[0] >> s[1]; int t; cin >> t; int a[2][100] = {0}; while (t--) { int min; string wh; int num; string get; cin >> min >> wh >> num >> get; int p = wh == "a" ? 1 : 0; if (get == "y") { a[p][num]++; if (a[p][num] == 2) { cout << s[p] << " " << num << " " << min << endl; } } else { if (a[p][num] < 2) { a[p][num] = 2; cout << s[p] << " " << num << " " << min << endl; } } } return 0; } ```
### Prompt Create a solution in CPP for the following problem: There are n seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from 1 to n from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat i (1 ≀ i ≀ n) will decide to go for boiled water at minute t_i. Tank with a boiled water is located to the left of the 1-st seat. In case too many passengers will go for boiled water simultaneously, they will form a queue, since there can be only one passenger using the tank at each particular moment of time. Each passenger uses the tank for exactly p minutes. We assume that the time it takes passengers to go from their seat to the tank is negligibly small. Nobody likes to stand in a queue. So when the passenger occupying the i-th seat wants to go for a boiled water, he will first take a look on all seats from 1 to i - 1. In case at least one of those seats is empty, he assumes that those people are standing in a queue right now, so he would be better seating for the time being. However, at the very first moment he observes that all seats with numbers smaller than i are busy, he will go to the tank. There is an unspoken rule, that in case at some moment several people can go to the tank, than only the leftmost of them (that is, seating on the seat with smallest number) will go to the tank, while all others will wait for the next moment. Your goal is to find for each passenger, when he will receive the boiled water for his noodles. Input The first line contains integers n and p (1 ≀ n ≀ 100 000, 1 ≀ p ≀ 10^9) β€” the number of people and the amount of time one person uses the tank. The second line contains n integers t_1, t_2, ..., t_n (0 ≀ t_i ≀ 10^9) β€” the moments when the corresponding passenger will go for the boiled water. Output Print n integers, where i-th of them is the time moment the passenger on i-th seat will receive his boiled water. Example Input 5 314 0 310 942 628 0 Output 314 628 1256 942 1570 Note Consider the example. At the 0-th minute there were two passengers willing to go for a water, passenger 1 and 5, so the first passenger has gone first, and returned at the 314-th minute. At this moment the passenger 2 was already willing to go for the water, so the passenger 2 has gone next, and so on. In the end, 5-th passenger was last to receive the boiled water. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 100000 + 10; int n, p, pos, t[maxn], vis[maxn]; long long tim, ans[maxn]; queue<int> pre; priority_queue<int, vector<int>, greater<int> > pp; priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > q; inline void Update(int x, int d) { for (; x <= n; x = x + (x & -x)) vis[x] = vis[x] + d; } inline int Query(int x) { for (int res = 0;; res = res + vis[x], x = x - (x & -x)) if (x == 0) return res; } int main(int argc, char const *argv[]) { scanf("%d%d", &n, &p); for (int i = 1; i <= n; ++i) scanf("%d", t + i), q.push(make_pair(t[i], i)); tim = q.top().first, pos = 0; while (!q.empty() || !pre.empty() || !pp.empty()) { while (!q.empty() && tim > q.top().first) { if (!pp.empty() && pp.top() < q.top().second && Query(pp.top()) == 0) pre.push(pp.top()), Update(pp.top(), 1), pp.pop(); if (Query(q.top().second) == 0) pre.push(q.top().second), Update(q.top().second, 1), q.pop(); else pp.push(q.top().second), q.pop(); } if (pos) Update(pos, -1); while (!q.empty() && tim == q.top().first) { if (!pp.empty() && pp.top() < q.top().second && Query(pp.top()) == 0) pre.push(pp.top()), Update(pp.top(), 1), pp.pop(); if (Query(q.top().second) == 0) pre.push(q.top().second), Update(q.top().second, 1), q.pop(); else pp.push(q.top().second), q.pop(); } if (!pp.empty() && Query(pp.top()) == 0) pre.push(pp.top()), Update(pp.top(), 1), pp.pop(); if (pre.empty()) tim = q.top().first, pos = 0; else tim = tim + p, ans[pos = pre.front()] = tim, pre.pop(); } for (int i = 1; i <= n; ++i) printf("%I64d ", ans[i]); return 0; } ```
### Prompt Your task is to create a cpp solution to the following problem: Polycarp loves ciphers. He has invented his own cipher called Right-Left. Right-Left cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{n} Polycarp uses the following algorithm: * he writes down s_1, * he appends the current word with s_2 (i.e. writes down s_2 to the right of the current result), * he prepends the current word with s_3 (i.e. writes down s_3 to the left of the current result), * he appends the current word with s_4 (i.e. writes down s_4 to the right of the current result), * he prepends the current word with s_5 (i.e. writes down s_5 to the left of the current result), * and so on for each position until the end of s. For example, if s="techno" the process is: "t" β†’ "te" β†’ "cte" β†’ "cteh" β†’ "ncteh" β†’ "ncteho". So the encrypted s="techno" is "ncteho". Given string t β€” the result of encryption of some string s. Your task is to decrypt it, i.e. find the string s. Input The only line of the input contains t β€” the result of encryption of some string s. It contains only lowercase Latin letters. The length of t is between 1 and 50, inclusive. Output Print such string s that after encryption it equals t. Examples Input ncteho Output techno Input erfdcoeocs Output codeforces Input z Output z ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { string t; cin >> t; int l = (t.length() + 1) / 2; int r = l + 1; l--; r--; bool f = true; while (l >= 0 || r < t.length()) { if (f) cout << t[l--]; else cout << t[r++]; f = !f; } char I; cin >> I; return 0; } ```
### Prompt Your challenge is to write a CPP solution to the following problem: You are given a string t consisting of n lowercase Latin letters and an integer number k. Let's define a substring of some string s with indices from l to r as s[l ... r]. Your task is to construct such string s of minimum possible length that there are exactly k positions i such that s[i ... i + n - 1] = t. In other words, your task is to construct such string s of minimum possible length that there are exactly k substrings of s equal to t. It is guaranteed that the answer is always unique. Input The first line of the input contains two integers n and k (1 ≀ n, k ≀ 50) β€” the length of the string t and the number of substrings. The second line of the input contains the string t consisting of exactly n lowercase Latin letters. Output Print such string s of minimum possible length that there are exactly k substrings of s equal to t. It is guaranteed that the answer is always unique. Examples Input 3 4 aba Output ababababa Input 3 2 cat Output catcat ### Response ```cpp #include <bits/stdc++.h> using namespace std; string s; int f() { int len = s.size(); for (int i = 1; i < len; ++i) { if (s.substr(i) == s.substr(0, len - i)) return len - i; } return 0; } int main() { int n, k; scanf("%d %d", &n, &k); cin >> s; int len = f(); cout << s; for (int i = 1; i < k; ++i) cout << s.substr(len); cout << "\n"; return 0; } ```
### Prompt Your task is to create a CPP solution to the following problem: You want to perform the combo on your opponent in one popular fighting game. The combo is the string s consisting of n lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in s. I.e. if s="abca" then you have to press 'a', then 'b', 'c' and 'a' again. You know that you will spend m wrong tries to perform the combo and during the i-th try you will make a mistake right after p_i-th button (1 ≀ p_i < n) (i.e. you will press first p_i buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1-th try you press all buttons right and finally perform the combo. I.e. if s="abca", m=2 and p = [1, 3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'. Your task is to calculate for each button (letter) the number of times you'll press it. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains two integers n and m (2 ≀ n ≀ 2 β‹… 10^5, 1 ≀ m ≀ 2 β‹… 10^5) β€” the length of s and the number of tries correspondingly. The second line of each test case contains the string s consisting of n lowercase Latin letters. The third line of each test case contains m integers p_1, p_2, ..., p_m (1 ≀ p_i < n) β€” the number of characters pressed right during the i-th try. It is guaranteed that the sum of n and the sum of m both does not exceed 2 β‹… 10^5 (βˆ‘ n ≀ 2 β‹… 10^5, βˆ‘ m ≀ 2 β‹… 10^5). It is guaranteed that the answer for each letter does not exceed 2 β‹… 10^9. Output For each test case, print the answer β€” 26 integers: the number of times you press the button 'a', the number of times you press the button 'b', ..., the number of times you press the button 'z'. Example Input 3 4 2 abca 1 3 10 5 codeforces 2 8 3 2 9 26 10 qwertyuioplkjhgfdsazxcvbnm 20 10 1 2 3 5 10 5 9 4 Output 4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0 2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2 Note The first test case is described in the problem statement. Wrong tries are "a", "abc" and the final try is "abca". The number of times you press 'a' is 4, 'b' is 2 and 'c' is 2. In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 9, 'd' is 4, 'e' is 5, 'f' is 3, 'o' is 9, 'r' is 3 and 's' is 1. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int b[200005]; int main() { int t; cin >> t; while (t--) { int m, n; cin >> n >> m; string s; cin >> s; long long a[30] = {0}; memset(b, 0, sizeof(b)); for (int i = 0; i < m; i++) cin >> b[i]; sort(b, b + m); int x = 0; for (int i = 0; i < n; i++) { while (i + 1 > b[x] && b[x] != 0) x++; a[s[i] - 'a'] += m + 1 - x; } for (int i = 0; i < 26; i++) cout << a[i] << ' '; cout << endl; } return 0; } ```
### Prompt Please create a solution in cpp to the following problem: Akari has n kinds of flowers, one of each kind. She is going to choose one or more of these flowers to make a bouquet. However, she hates two numbers a and b, so the number of flowers in the bouquet cannot be a or b. How many different bouquets are there that Akari can make? Find the count modulo (10^9 + 7). Here, two bouquets are considered different when there is a flower that is used in one of the bouquets but not in the other bouquet. Constraints * All values in input are integers. * 2 \leq n \leq 10^9 * 1 \leq a < b \leq \textrm{min}(n, 2 \times 10^5) Input Input is given from Standard Input in the following format: n a b Output Print the number of bouquets that Akari can make, modulo (10^9 + 7). (If there are no such bouquets, print `0`.) Examples Input 4 1 3 Output 7 Input 1000000000 141421 173205 Output 34076506 ### Response ```cpp #include <bits/stdc++.h> #define N 100005 #define ll long long using namespace std; ifstream in("in.txt"); const ll M=1000000007; ll fortza(ll x, ll i){ if(i==1){ return x; } ll t=fortza(x,i/2); t=(t*t)%M; if(i&1){ t=(t*x)%M; } return t; } int main(){ ll n, a, b, x=1, t; cin>>n>>a>>b; for(ll i=1; i<=a; ++i){ x=x*((n-i+1)*fortza(i, M-2)%M)%M; } t=(fortza(2, n)-1-x+M)%M; for(ll i=a+1; i<=b; ++i){ x=x*((n-i+1)*fortza(i, M-2)%M)%M; } cout<<(t-x+M)%M; return 0; } ```
### Prompt Develop a solution in cpp to the problem described below: This problem is interactive. You should guess hidden number x which is between 1 and M = 10004205361450474, inclusive. You could use up to 5 queries. In each query, you can output an increasing sequence of k ≀ x integers, each between 1 and M, inclusive, and you will obtain one of the following as an answer: * either the hidden number belongs to your query sequence, in this case you immediately win; * or you will be given where the hidden number is located with respect to your query sequence, that is, either it is less than all numbers from the sequence, greater than all numbers from the sequence, or you will be given such an i that the hidden number x is between the i-th and the (i+1)-st numbers of your sequence. See the interaction section for clarity. Be aware that the interactor is adaptive, i.e. the hidden number can depend on queries the solution makes. However, it is guaranteed that for any solution the interactor works non-distinguishable from the situation when the hidden number is fixed beforehand. Hacks are allowed only with fixed hidden number. A hack is represented by a single integer between 1 and M. In all pretests the hidden number is fixed as well. Interaction You can make up to 5 queries. To make a query print a number k (1 ≀ k ≀ 10^4) and then an increasing sequence t_0 < t_1 < … < t_{k-1} of k numbers, each between 1 and M, inclusive. If k > x, you lose. You get one integer as a response. * If it is -2, it means you made an invalid query or you lost. Exit immediately after receiving -2 and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream. * If it is -1, you guessed the number and should terminate too. * Otherwise you get a number i between 0 and k, inclusive, denoting where the hidden number is, with respect to the printed numbers. If i = 0, then x < t_0. If i = k, then t_{k-1} < x. Otherwise t_{i-1} < x < t_i. After printing a query do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. Example Input Β  2 0 -1 Output 2 2 3 2 20 30 3 5 7 9 Note In the first example the number 5 is hidden. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long LIM = 10004205361450474; const int K = 10000; long long cnt = 0; pair<long long, long long> query(vector<long long> V) { cnt++; assert(cnt <= 5); assert(V[0] >= (long long)V.size() - 2); assert(V.size() <= K + 2); printf("%d ", (int)V.size() - 2); for (int i = (1); i < ((int)V.size() - 1); i++) printf("%lld ", V[i]); printf("\n"); fflush(stdout); int ind; scanf("%d", &ind); if (ind == -1) exit(0); if (ind == 0) return pair<long long, long long>(V[0], V[1] - 1); if (ind == (int)V.size() - 2) return pair<long long, long long>(V[V.size() - 2] + 1, V.back()); return pair<long long, long long>(V[ind] + 1, V[ind + 1] - 1); } long long what_next[6][K + 1]; long long kolko_vel[6]; long long get_what(int step, long long val) { assert(step < 5); if (val < K) return what_next[step][val] - 1; if (val >= LIM) return LIM; return val + kolko_vel[step] - 1; } void calc() { kolko_vel[1] = K; for (int i = (2); i < (6); i++) kolko_vel[i] = (K + 1) * kolko_vel[i - 1] + K; for (int i = (1); i < (K + 1); i++) what_next[1][i] = 2 * i; for (int step = (2); step < (6); step++) { for (int i = (1); i < (K + 1); i++) { int kolko = min(i, K); long long nxt = get_what(step - 1, i) + 1; for (int j = (0); j < (kolko); j++) nxt = get_what(step - 1, nxt + 1) + 1; what_next[step][i] = nxt; } } } long long find_prev(int steps, long long val) { long long lo = 1, hi = val; for (; lo < hi;) { long long mid = (lo + hi) / 2; if (get_what(steps, mid) >= val) hi = mid; else lo = mid + 1; } return lo; } void go(long long lo, long long hi, int steps) { if (steps == 1) { assert(lo + min((long long)K, lo) - 1 >= hi); vector<long long> T = {lo}; for (long long i = lo; i <= hi; i++) T.push_back(i); T.push_back(hi); query(T); assert(0); } vector<long long> T; for (long long tmp = hi; (long long)T.size() < min((long long)K, lo);) { long long nov = max(1ll, find_prev(steps - 1, tmp) - 1); T.push_back(nov); tmp = nov - 1; } reverse(T.begin(), T.end()); T.insert(T.begin(), lo); T.push_back(hi); pair<long long, long long> dalje = query(T); go(dalje.first, dalje.second, steps - 1); } int main() { calc(); go(1, LIM, 5); return 0; } ```
### Prompt In CPP, your task is to solve the following problem: The supercomputer system L in the PCK Research Institute performs a variety of calculations upon request from external institutes, companies, universities and other entities. To use the L system, you have to reserve operation time by specifying the start and end time. No two reservation periods are allowed to overlap each other. Write a program to report if a new reservation overlaps with any of the existing reservations. Note that the coincidence of start and end times is not considered to constitute an overlap. All the temporal data is given as the elapsed time from the moment at which the L system starts operation. Input The input is given in the following format. a b N s_1 f_1 s_2 f_2 : s_N f_N The first line provides new reservation information, i.e., the start time a and end time b (0 ≀ a < b ≀ 1000) in integers. The second line specifies the number of existing reservations N (0 ≀ N ≀ 100). Subsequent N lines provide temporal information for the i-th reservation: start time s_i and end time f_i (0 ≀ s_i < f_i ≀ 1000) in integers. No two existing reservations overlap. Output Output "1" if the new reservation temporally overlaps with any of the existing ones, or "0" otherwise. Examples Input 5 7 3 1 4 4 5 7 10 Output 0 Input 3 7 3 7 10 1 4 4 5 Output 1 ### Response ```cpp #include<stdio.h> int main(void) { int a,b,n,s[100],f[100],i,j,flg; scanf("%d %d",&a,&b); scanf("%d",&n); flg=0; for(i=0;i<n;i++) scanf("%d %d",&s[i],&f[i]); for(i=0;i<n;i++){ if(a>s[i]&&a<f[i]) flg=1; if(b>s[i]&&b<f[i]) flg=1; if(a<s[i]&&b>f[i]) flg=1; if(a==s[i]&&b==f[i]) flg=1; } if(flg==0) printf("0\n"); else printf("1\n"); return 0; } ```
### Prompt Please formulate a CPP solution to the following problem: To get on the Shinkansen, you need two tickets, a "ticket" and a "limited express ticket". These are separate tickets because some of the routes may not use the Shinkansen, but for routes that use only the Shinkansen, one ticket can be used as both a ticket and a limited express ticket. It may also be issued. Automatic ticket gates must read these tickets and open the gate only when the correct ticket is inserted. Create a program that determines whether one "ticket" and one "limited express ticket" or both, or one "boarding / limited express ticket" has been inserted, and determines whether the door of the automatic ticket gate is open or closed. please do it. input The input is given in the following format. b1 b2 b3 The input consists of one line and contains three integers separated by one space. b1 indicates the state in which the "ticket" is inserted, b2 indicates the state in which the "limited express ticket" is inserted, and b3 indicates the state in which the "boarding / limited express ticket" is inserted. The turned-in state is represented by 0 or 1, where 0 indicates a non-charged state, and 1 indicates a loaded state. However, the combination of expected input states is limited to the following cases. Input | Input state | Door operation for input --- | --- | --- 1 0 0 | Insert only "ticket" | Close 0 1 0 | Only "Limited Express Ticket" is introduced | Close 1 1 0 | Introducing "tickets" and "express tickets" | Open 0 0 1 | Introducing "Boarding / Limited Express Tickets" | Open 0 0 0 | No input | Close output Outputs Open or Close, which indicates the opening and closing of the automatic ticket gate, on one line. Example Input 0 0 1 Output Open ### Response ```cpp #include <iostream> using namespace std; int main(void){ int a,b,c; cin >> a >> b >> c; if(a == 1 && b == 1 && c == 0){ cout << "Open" << endl; } else if(a == 0 && b == 0 && c == 1){ cout << "Open" << endl; } else { cout << "Close" << endl; } } ```
### Prompt Create a solution in CPP for the following problem: You are given two strings s and t consisting of lowercase Latin letters. The length of t is 2 (i.e. this string consists only of two characters). In one move, you can choose any character of s and replace it with any lowercase Latin letter. More formally, you choose some i and replace s_i (the character at the position i) with some character from 'a' to 'z'. You want to do no more than k replacements in such a way that maximizes the number of occurrences of t in s as a subsequence. Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. Input The first line of the input contains two integers n and k (2 ≀ n ≀ 200; 0 ≀ k ≀ n) β€” the length of s and the maximum number of moves you can make. The second line of the input contains the string s consisting of n lowercase Latin letters. The third line of the input contains the string t consisting of two lowercase Latin letters. Output Print one integer β€” the maximum possible number of occurrences of t in s as a subsequence if you replace no more than k characters in s optimally. Examples Input 4 2 bbaa ab Output 3 Input 7 3 asddsaf sd Output 10 Input 15 6 qwertyhgfdsazxc qa Output 16 Input 7 2 abacaba aa Output 15 Note In the first example, you can obtain the string "abab" replacing s_1 with 'a' and s_4 with 'b'. Then the answer is 3. In the second example, you can obtain the string "ssddsdd" and get the answer 10. In the fourth example, you can obtain the string "aaacaaa" and get the answer 15. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int INF = 1e9; int main() { int n, k; string s, t; cin >> n >> k >> s >> t; vector<vector<vector<int>>> dp( n + 1, vector<vector<int>>(n + 1, vector<int>(n + 1, -INF))); dp[0][0][0] = 0; for (int i = 0; i < n; ++i) { for (int ck = 0; ck <= k; ++ck) { for (int cnt0 = 0; cnt0 <= n; ++cnt0) { if (dp[i][ck][cnt0] == -INF) continue; int e0 = s[i] == t[0]; int e1 = s[i] == t[1]; int e01 = t[0] == t[1]; dp[i + 1][ck][cnt0 + e0] = max(dp[i + 1][ck][cnt0 + e0], dp[i][ck][cnt0] + (e1 ? cnt0 : 0)); if (ck < k) { dp[i + 1][ck + 1][cnt0 + 1] = max(dp[i + 1][ck + 1][cnt0 + 1], dp[i][ck][cnt0] + (e01 ? cnt0 : 0)); dp[i + 1][ck + 1][cnt0 + e01] = max(dp[i + 1][ck + 1][cnt0 + e01], dp[i][ck][cnt0] + cnt0); } } } } int ans = 0; for (int ck = 0; ck <= k; ++ck) { for (int cnt0 = 0; cnt0 <= n; ++cnt0) { ans = max(ans, dp[n][ck][cnt0]); } } cout << ans << endl; return 0; } ```
### Prompt Create a solution in cpp for the following problem: There are a number of ways to shuffle a deck of cards. Hanafuda shuffling for Japanese card game 'Hanafuda' is one such example. The following is how to perform Hanafuda shuffling. There is a deck of n cards. Starting from the p-th card from the top of the deck, c cards are pulled out and put on the top of the deck, as shown in Figure 1. This operation, called a cutting operation, is repeated. Write a program that simulates Hanafuda shuffling and answers which card will be finally placed on the top of the deck. <image> --- Figure 1: Cutting operation Input The input consists of multiple data sets. Each data set starts with a line containing two positive integers n (1 <= n <= 50) and r (1 <= r <= 50); n and r are the number of cards in the deck and the number of cutting operations, respectively. There are r more lines in the data set, each of which represents a cutting operation. These cutting operations are performed in the listed order. Each line contains two positive integers p and c (p + c <= n + 1). Starting from the p-th card from the top of the deck, c cards should be pulled out and put on the top. The end of the input is indicated by a line which contains two zeros. Each input line contains exactly two integers separated by a space character. There are no other characters in the line. Output For each data set in the input, your program should write the number of the top card after the shuffle. Assume that at the beginning the cards are numbered from 1 to n, from the bottom to the top. Each number should be written in a separate line without any superfluous characters such as leading or following spaces. Example Input 5 2 3 1 3 1 10 3 1 10 10 1 8 3 0 0 Output 4 4 ### Response ```cpp #include<stdio.h> int main(void) { int i,j; int n,r; int p,c; int h[50],tmp[50]; while(1){ scanf("%d %d",&n,&r); if(!n && !r){break;} for(i=0;i<n;i++)h[i] = n-i; for(i=0;i<r;i++){ scanf("%d %d",&p,&c); p--; for(j=0;j<c;j++)tmp[j] = h[j+p]; for(j=p-1;j>=0;j--)h[j+c] = h[j]; for(j=0;j<c;j++)h[j] = tmp[j]; } printf("%d\n",h[0]); } return 0; } ```
### Prompt Develop a solution in CPP to the problem described below: The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row. Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same. The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task. Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added). Input The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house. Output Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one. Examples Input 5 1 2 3 1 2 Output 3 2 0 2 0 Input 4 3 2 1 4 Output 2 3 4 0 ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long n, i, a[100005], r[100005], m; int main() { cin >> n; for (i = 1; i <= n; i++) { cin >> a[i]; } r[n] = 0; for (i = n - 1; i >= 1; i--) { m = max(m, a[i + 1]); r[i] = m; } for (i = 1; i <= n; i++) { if (r[i] >= a[i]) { cout << r[i] - a[i] + 1 << " "; } else { cout << "0 "; } } return 0; } ```
### Prompt In cpp, your task is to solve the following problem: Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number! The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband. The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once. The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence a_{i_1}, a_{i_2}, …, a_{i_k} where 1≀ i_1 < i_2 < … < i_k≀ n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < … < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > … > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences. For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3. Note, the lengths of LIS and LDS can be different. So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS. Input The only line contains one integer n (1 ≀ n ≀ 10^5) β€” the length of permutation that you need to build. Output Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any. Examples Input 4 Output 3 4 1 2 Input 2 Output 2 1 Note In the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid. In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int count = n; int L = sqrt(n); int block = n / L; vector<int> ar(n, 0); int i; for (i = 0; i < block; i++) { for (int j = L - 1; j >= 0; j--) { ar[L * i + j] = count; count--; } } if (count > 0) { for (i = n - 1; i > 0 && count > 0; i--) { ar[i] = count; count--; } } for (i = 0; i < n; i++) cout << ar[i] << " "; cout << "\n"; return 0; } ```
### Prompt In CPP, your task is to solve the following problem: For a given prime integer p and integers Ξ±, A calculate the number of pairs of integers (n, k), such that 0 ≀ k ≀ n ≀ A and <image> is divisible by pΞ±. As the answer can be rather large, print the remainder of the answer moduly 109 + 7. Let us remind you that <image> is the number of ways k objects can be chosen from the set of n objects. Input The first line contains two integers, p and Ξ± (1 ≀ p, Ξ± ≀ 109, p is prime). The second line contains the decimal record of integer A (0 ≀ A < 101000) without leading zeroes. Output In the single line print the answer to the problem. Examples Input 2 2 7 Output 3 Input 3 1 9 Output 17 Input 3 3 9 Output 0 Input 2 4 5000 Output 8576851 Note In the first sample three binominal coefficients divisible by 4 are <image>, <image> and <image>. ### Response ```cpp #include <bits/stdc++.h> using namespace std; char buf[1 << 23 | 1], *p1 = buf, *p2 = buf; int (*GC)() = getchar; inline int gc() { return (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 23, stdin), p1 == p2) ? EOF : *p1++); } template <typename T> void read(T &x) { x = 0; bool f = 0; char ch = GC(); while (!isdigit(ch)) { if (ch == '-') f = 1; ch = GC(); } while (isdigit(ch)) x = x * 10 + (ch ^ 48), ch = GC(); if (f) x = -x; } void fileopen() {} int const P = 1e9 + 7; void update(int &x, long long y) { x = (x + y) % P; } int f[3330][3330][2][2]; long long A[3330]; int main() { fileopen(); int p, k; read(p), read(k); if (k > 3325) { puts("0"); return 0; } char ch = gc(); while (!isdigit(ch)) ch = gc(); while (isdigit(ch)) { for (int i = 0; i <= 3325; i++) A[i] *= 10; A[0] += ch - '0'; for (int i = 0; i <= 3325; i++) if (A[i] >= p) A[i + 1] += A[i] / p, A[i] %= p; ch = gc(); } f[3325][0][0][0] = 1; for (int i = 3325; i >= 1; i--) for (int j = 0; j <= 3325 - i; j++) { update(f[i - 1][j][0][0], 1ll * (A[i - 1] + 1) * f[i][j][0][0]); update(f[i - 1][j][1][0], 1ll * (A[i - 1] + 1) * A[i - 1] / 2 % P * f[i][j][0][0]); update(f[i - 1][j + 1][0][1], 1ll * A[i - 1] * f[i][j][0][0]); update(f[i - 1][j + 1][1][1], 1ll * (A[i - 1] - 1) * A[i - 1] / 2 % P * f[i][j][0][0]); update(f[i - 1][j][0][0], 1ll * (p - A[i - 1] - 1) * f[i][j][0][1]); update(f[i - 1][j][1][0], 1ll * A[i - 1] * (2 * p - A[i - 1] - 1) / 2 % P * f[i][j][0][1]); update(f[i - 1][j + 1][0][1], 1ll * (p - A[i - 1]) * f[i][j][0][1]); update(f[i - 1][j + 1][1][1], 1ll * A[i - 1] * (2 * p + 1 - A[i - 1]) / 2 % P * f[i][j][0][1]); update(f[i - 1][j][1][0], 1ll * p * (p + 1) / 2 % P * f[i][j][1][0]); update(f[i - 1][j + 1][1][1], 1ll * p * (p - 1) / 2 % P * f[i][j][1][0]); update(f[i - 1][j][1][0], 1ll * p * (p - 1) / 2 % P * f[i][j][1][1]); update(f[i - 1][j + 1][1][1], 1ll * p * (p + 1) / 2 % P * f[i][j][1][1]); } long long res = 0; for (int i = k; i <= 3325; i++) res = (res + f[0][i][0][0] + f[0][i][1][0]) % P; printf("%lld", res); return 0; } ```
### Prompt In CPP, your task is to solve the following problem: Egor is a famous Russian singer, rapper, actor and blogger, and finally he decided to give a concert in the sunny Republic of Dagestan. There are n cities in the republic, some of them are connected by m directed roads without any additional conditions. In other words, road system of Dagestan represents an arbitrary directed graph. Egor will arrive to the city 1, travel to the city n by roads along some path, give a concert and fly away. As any famous artist, Egor has lots of haters and too annoying fans, so he can travel only by safe roads. There are two types of the roads in Dagestan, black and white: black roads are safe at night only, and white roads β€” in the morning. Before the trip Egor's manager's going to make a schedule: for each city he'll specify it's color, black or white, and then if during the trip they visit some city, the only time they can leave it is determined by the city's color: night, if it's black, and morning, if it's white. After creating the schedule Egor chooses an available path from 1 to n, and for security reasons it has to be the shortest possible. Egor's manager likes Dagestan very much and wants to stay here as long as possible, so he asks you to make such schedule that there would be no path from 1 to n or the shortest path's length would be greatest possible. A path is one city or a sequence of roads such that for every road (excluding the first one) the city this road goes from is equal to the city previous road goes into. Egor can move only along paths consisting of safe roads only. The path length is equal to the number of roads in it. The shortest path in a graph is a path with smallest length. Input The first line contains two integers n, m (1 ≀ n ≀ 500000, 0 ≀ m ≀ 500000) β€” the number of cities and the number of roads. The i-th of next m lines contains three integers β€” u_i, v_i and t_i (1 ≀ u_i, v_i ≀ n, t_i ∈ \{0, 1\}) β€” numbers of cities connected by road and its type, respectively (0 β€” night road, 1 β€” morning road). Output In the first line output the length of the desired path (or -1, if it's possible to choose such schedule that there's no path from 1 to n). In the second line output the desired schedule β€” a string of n digits, where i-th digit is 0, if the i-th city is a night one, and 1 if it's a morning one. If there are multiple answers, print any. Examples Input 3 4 1 2 0 1 3 1 2 3 0 2 3 1 Output 2 011 Input 4 8 1 1 0 1 3 0 1 3 1 3 2 0 2 1 0 3 4 1 2 4 0 2 4 1 Output 3 1101 Input 5 10 1 2 0 1 3 1 1 4 0 2 3 0 2 3 1 2 5 0 3 4 0 3 4 1 4 2 1 4 5 0 Output -1 11111 Note For the first sample, if we paint city 1 white, the shortest path is 1 β†’ 3. Otherwise, it's 1 β†’ 2 β†’ 3 regardless of other cities' colors. For the second sample, we should paint city 3 black, and there are both black and white roads going from 2 to 4. Note that there can be a road connecting a city with itself. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n; const int N = 5e5 + 5; vector<pair<int, int>> adj[N]; int bad[N], C[N], vis[N], d[N], m; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> m; for (int i = 1; i <= m; i++) { int a, b, w; cin >> a >> b >> w; if (a == b) continue; adj[b].push_back({a, w}); } for (int i = 1; i < n; i++) C[i] = -1, d[i] = 100000000; d[n] = 0; priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq; pq.push({0, n}); C[n] = 0; while (!pq.empty()) { auto i1 = pq.top(); pq.pop(); int v = i1.second; int val = i1.first; if (vis[v]) continue; vis[v] = 1; if (v == 1) { cout << val << '\n'; for (int i = 1; i <= n; i++) if (C[i] == -1) cout << 0; else cout << C[i]; return 0; } for (auto i1 : adj[v]) { int i = i1.first; int x = i1.second; if (vis[i]) continue; if (d[i] > d[v] + 1) { if (C[i] == -1) { C[i] = (!x); continue; } else if (C[i] == x) { if (d[i] > val + 1) { d[i] = val + 1; pq.push({val + 1, i}); } } } } } cout << "-1\n"; for (int i = 1; i <= n; i++) if (C[i] != -1) cout << C[i]; else cout << 1; return 0; } ```
### Prompt Please formulate a CPP solution to the following problem: problem You decide to invite your friends of the school and your friends of a friend to the Christmas party. The number of students in your school is n, and each student is assigned a number from 1 to n. Your number is 1. You have a list of who and who are your friends. Based on this list, create a program that asks for the number of students you will invite to your Christmas party. input The input consists of multiple datasets. Each dataset is given in the following format. The first line of the dataset contains the number of students in the school n (2 ≀ n ≀ 500), and the second line contains the length of the list m (1 ≀ m ≀ 10000). The input consists of 2 + m lines in total. Line 2 + i (1 ≀ i ≀ m) contains two integers ai and bi (1 ≀ ai <bi ≀ n) separated by blanks, and the students with numbers ai and bi are friends. Represents that. From the 3rd line to the 2 + m line, the lines representing the same friendship do not appear twice. When both n and m are 0, it indicates the end of input. The number of data sets does not exceed 5. output For each dataset, print the number of students you invite to the Christmas party on one line. Examples Input 6 5 1 2 1 3 3 4 2 3 4 5 6 5 2 3 3 4 4 5 5 6 2 5 0 0 Output 3 0 Input None Output None ### Response ```cpp #include<iostream> using namespace std; int main() { int n, m; while (cin >> n >> m, n, m) { pair<int, int>p[10010]; bool b1[510], b2[510]; for (int i = 1; i <= n; i++) { b1[i] = false; b2[i] = false; } for (int i = 0; i < m; i++)cin >> p[i].first >> p[i].second; for (int i = 0; i < m; i++) { if (p[i].first == 1)b1[p[i].second] = true; if (p[i].second == 1)b1[p[i].first] = true; } for (int i = 0; i < m; i++) { if (b1[p[i].first])b2[p[i].second] = true; if (b1[p[i].second])b2[p[i].first] = true; } int cnt = 0; for (int i = 2; i <= n; i++)if (b1[i] || b2[i])cnt++; cout << cnt << endl; } } ```
### Prompt Your task is to create a Cpp solution to the following problem: Joisino is planning to record N TV programs with recorders. The TV can receive C channels numbered 1 through C. The i-th program that she wants to record will be broadcast from time s_i to time t_i (including time s_i but not t_i) on Channel c_i. Here, there will never be more than one program that are broadcast on the same channel at the same time. When the recorder is recording a channel from time S to time T (including time S but not T), it cannot record other channels from time S-0.5 to time T (including time S-0.5 but not T). Find the minimum number of recorders required to record the channels so that all the N programs are completely recorded. Constraints * 1≀N≀10^5 * 1≀C≀30 * 1≀s_i<t_i≀10^5 * 1≀c_i≀C * If c_i=c_j and iβ‰ j, either t_i≀s_j or s_iβ‰₯t_j. * All input values are integers. Input Input is given from Standard Input in the following format: N C s_1 t_1 c_1 : s_N t_N c_N Output When the minimum required number of recorders is x, print the value of x. Examples Input 3 2 1 7 2 7 8 1 8 12 1 Output 2 Input 3 4 1 3 2 3 4 4 1 4 3 Output 3 Input 9 4 56 60 4 33 37 2 89 90 3 32 43 1 67 68 3 49 51 3 31 32 3 70 71 1 11 12 3 Output 2 ### Response ```cpp #include <iostream> #include <cstdio> #define C 35 #define N 100005 using namespace std; int n, c, cnt, mx; bool v[C][N]; int main() { int i, j, t1, t2, t3; cin >> n >> c; while (n--) { scanf("%d %d %d", &t1, &t2, &t3); for (i = t1; i <= t2; i++) v[t3][i] = 1; } for (i = 1; i < N; i++) { for (j = 1, cnt = 0; j <= c; j++) cnt += v[j][i]; mx = max(mx, cnt); } cout << mx << endl; return 0; } ```
### Prompt Develop a solution in cpp to the problem described below: In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum. For example, for n = 4 the sum is equal to - 1 - 2 + 3 - 4 = - 4, because 1, 2 and 4 are 20, 21 and 22 respectively. Calculate the answer for t values of n. Input The first line of the input contains a single integer t (1 ≀ t ≀ 100) β€” the number of values of n to be processed. Each of next t lines contains a single integer n (1 ≀ n ≀ 109). Output Print the requested sum for each of t integers n given in the input. Examples Input 2 4 1000000000 Output -4 499999998352516354 Note The answer for the first sample is explained in the statement. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; long long n; for (int i = 0; i < t; i++) { cin >> n; long long ans = ((1 + n) * n) / 2; unsigned long long sum2 = 0; unsigned long long power = 1; while (power <= n) { sum2 += power; power *= 2; } ans = ans - (sum2 * 2); cout << ans << endl; } return 0; } ```
### Prompt Your task is to create a CPP solution to the following problem: Masha has n types of tiles of size 2 Γ— 2. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type. Masha decides to construct the square of size m Γ— m consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of this square has to be covered with exactly one tile cell, and also sides of tiles should be parallel to the sides of the square. All placed tiles cannot intersect with each other. Also, each tile should lie inside the square. See the picture in Notes section for better understanding. Symmetric with respect to the main diagonal matrix is such a square s that for each pair (i, j) the condition s[i][j] = s[j][i] holds. I.e. it is true that the element written in the i-row and j-th column equals to the element written in the j-th row and i-th column. Your task is to determine if Masha can construct a square of size m Γ— m which is a symmetric matrix and consists of tiles she has. Masha can use any number of tiles of each type she has to construct the square. Note that she can not rotate tiles, she can only place them in the orientation they have in the input. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 100) β€” the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and m (1 ≀ n ≀ 100, 1 ≀ m ≀ 100) β€” the number of types of tiles and the size of the square Masha wants to construct. The next 2n lines of the test case contain descriptions of tiles types. Types of tiles are written one after another, each type is written on two lines. The first line of the description contains two positive (greater than zero) integers not exceeding 100 β€” the number written in the top left corner of the tile and the number written in the top right corner of the tile of the current type. The second line of the description contains two positive (greater than zero) integers not exceeding 100 β€” the number written in the bottom left corner of the tile and the number written in the bottom right corner of the tile of the current type. It is forbidden to rotate tiles, it is only allowed to place them in the orientation they have in the input. Output For each test case print the answer: "YES" (without quotes) if Masha can construct the square of size m Γ— m which is a symmetric matrix. Otherwise, print "NO" (withtout quotes). Example Input 6 3 4 1 2 5 6 5 7 7 4 8 9 9 8 2 5 1 1 1 1 2 2 2 2 1 100 10 10 10 10 1 2 4 5 8 4 2 2 1 1 1 1 1 2 3 4 1 2 1 1 1 1 Output YES NO YES NO YES YES Note The first test case of the input has three types of tiles, they are shown on the picture below. <image> Masha can construct, for example, the following square of size 4 Γ— 4 which is a symmetric matrix: <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { long long t; cin >> t; while (t--) { long long n, m; cin >> n >> m; int ar[2 * n][2]; for (int i = 0; i < 2 * n; i++) { cin >> ar[i][0]; cin >> ar[i][1]; } int tile = 0; for (int i = 0; i < 2 * n; i += 2) { if (ar[i][1] == ar[i + 1][0]) { tile++; } } if (tile >= 1 && m % 2 == 0) cout << "YES" << endl; else cout << "NO" << endl; } return 0; } ```
### Prompt Please provide a Cpp coded solution to the problem described below: Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers). The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: * Each boy plays for exactly one team (x + y = n). * The sizes of teams differ in no more than one (|x - y| ≀ 1). * The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: <image> Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists. Input The first line contains the only integer n (2 ≀ n ≀ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≀ ai ≀ 104), the i-th number represents the i-th boy's playing skills. Output On the first line print an integer x β€” the number of boys playing for the first team. On the second line print x integers β€” the individual numbers of boys playing for the first team. On the third line print an integer y β€” the number of boys playing for the second team, on the fourth line print y integers β€” the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≀ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order. Examples Input 3 1 2 1 Output 2 1 2 1 3 Input 5 2 3 3 1 1 Output 3 4 1 3 2 5 2 Note Let's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≀ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≀ 2) is fulfilled. ### Response ```cpp #include <bits/stdc++.h> using namespace std; void solve() { long long n; cin >> n; vector<long long> a(n, 0); for (int i = 0, _n = (n); i < _n; i++) cin >> a[i]; vector<pair<long long, long long> > b(n); for (int i = 0, _n = (n); i < _n; i++) b[i] = {a[i], i}; sort((b).begin(), (b).end()); sort((a).begin(), (a).end()); long long l = 0, r = 1; vector<long long> pre(n, 0); for (int i = 0, _n = (n); i < _n; i++) { pre[i] = a[i]; if (i) pre[i] += pre[i - 1]; } long long sum = pre.back(); long double maxi = (sum - a.back()) / 2.0; long double mini = sum / 2.0; vector<long long> ans1, ans2; long long cnt = n / 2; for (int i = (cnt - 1), _b = (n - 1); i <= _b; i++) { long long sumInRange = pre[i]; if (i - cnt >= 0) sumInRange -= pre[i - cnt]; if (sumInRange <= mini && sumInRange >= maxi) { for (int j = 0, _n = (n); j < _n; j++) { if (j <= i - cnt || j > i) { ans2.push_back(b[j].second); } else { ans1.push_back(b[j].second); } } break; } } cout << ans1.size() << '\n'; for (int i = 0, _n = (ans1.size()); i < _n; i++) { cout << ans1[i] + 1 << ' '; } cout << '\n'; cout << ans2.size() << '\n'; for (int i = 0, _n = (ans2.size()); i < _n; i++) { cout << ans2[i] + 1 << ' '; } cout << '\n'; return; } int main(int argc, char** argv) { ios_base::sync_with_stdio(false); cin.tie(NULL); long long t = 1; while (t--) { solve(); } return 0; } ```
### Prompt Your challenge is to write a cpp solution to the following problem: Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process. There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems. You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day. Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days. Input The first line of input contains three integers n, m and k (1 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ k ≀ 106). The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≀ di ≀ 106, 0 ≀ fi ≀ n, 0 ≀ ti ≀ n, 1 ≀ ci ≀ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost. Output Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities. If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes). Examples Input 2 6 5 1 1 0 5000 3 2 0 5500 2 2 0 6000 15 0 2 9000 9 0 1 7000 8 0 2 6500 Output 24500 Input 2 4 5 1 2 0 5000 2 1 0 4500 2 1 0 3000 8 0 1 6000 Output -1 Note The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more. In the second sample it is impossible to send jury member from city 2 back home from Metropolis. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long int INF = 1e11; struct souvik { int d, f, t, c; } q[100003]; long long int ans[1000005], f[1000005], e[1000005]; bool comp(souvik q, souvik w) { return q.d < w.d; } int main() { int n, m, i, j, k; long long int res = 0; scanf("%d %d %d", &n, &m, &k); for (i = 0; i < m; i++) scanf("%d %d %d %d", &q[i].d, &q[i].f, &q[i].t, &q[i].c); sort(q, q + m, comp); for (i = 1; i <= n; i++) ans[i] = INF, res += ans[i]; j = 0; for (i = 0; i <= 1000000; i++) { while (j < m && q[j].d == i) { if (q[j].t == 0) { if (ans[q[j].f] > q[j].c) { res += q[j].c - ans[q[j].f]; ans[q[j].f] = q[j].c; } } j++; } f[i] = res; } res = 0; for (i = 1; i <= n; i++) ans[i] = INF, res += ans[i]; j = m - 1; for (i = 1000000; i >= 0; i--) { while (j >= 0 && q[j].d == i) { if (q[j].f == 0) { if (ans[q[j].t] > q[j].c) { res += q[j].c - ans[q[j].t]; ans[q[j].t] = q[j].c; } } j--; } e[i] = res; } res = INF + 5LL; for (i = 1; i + k <= 1000000; i++) res = min(res, f[i - 1] + e[i + k]); if (res > INF) printf("-1\n"); else printf("%lld\n", res); return 0; } ```
### Prompt Develop a solution in cpp to the problem described below: You are given an integer n. You should find a list of pairs (x_1, y_1), (x_2, y_2), ..., (x_q, y_q) (1 ≀ x_i, y_i ≀ n) satisfying the following condition. Let's consider some function f: N Γ— N β†’ N (we define N as the set of positive integers). In other words, f is a function that returns a positive integer for a pair of positive integers. Let's make an array a_1, a_2, …, a_n, where a_i = i initially. You will perform q operations, in i-th of them you will: 1. assign t = f(a_{x_i}, a_{y_i}) (t is a temporary variable, it is used only for the next two assignments); 2. assign a_{x_i} = t; 3. assign a_{y_i} = t. In other words, you need to simultaneously change a_{x_i} and a_{y_i} to f(a_{x_i}, a_{y_i}). Note that during this process f(p, q) is always the same for a fixed pair of p and q. In the end, there should be at most two different numbers in the array a. It should be true for any function f. Find any possible list of pairs. The number of pairs should not exceed 5 β‹… 10^5. Input The single line contains a single integer n (1 ≀ n ≀ 15 000). Output In the first line print q (0 ≀ q ≀ 5 β‹… 10^5) β€” the number of pairs. In each of the next q lines print two integers. In the i-th line print x_i, y_i (1 ≀ x_i, y_i ≀ n). The condition described in the statement should be satisfied. If there exists multiple answers you can print any of them. Examples Input 3 Output 1 1 2 Input 4 Output 2 1 2 3 4 Note In the first example, after performing the only operation the array a will be [f(a_1, a_2), f(a_1, a_2), a_3]. It will always have at most two different numbers. In the second example, after performing two operations the array a will be [f(a_1, a_2), f(a_1, a_2), f(a_3, a_4), f(a_3, a_4)]. It will always have at most two different numbers. ### Response ```cpp #include <bits/stdc++.h> using namespace std; vector<pair<int, int>> ans; void solve(int l, int r) { if (l >= r) return; int mid = (l + r) / 2; int x = (r - l) / 2 + ((r - l) % 2); for (int i = l; i < l + x; i++) { ans.emplace_back(i, i + x); } solve(l, mid); solve(mid + 1, r); } int main() { int n; cin >> n; int m = 0; while (1 << (m + 1) < n) { m++; } solve(1, 1 << m); solve(n - ((1 << m) - 1), n); cout << ans.size() << '\n'; for (auto it : ans) { cout << it.first << " " << it.second; cout << '\n'; } } ```
### Prompt Construct a CPP code solution to the problem outlined: You've got table a, consisting of n rows, numbered from 1 to n. The i-th line of table a contains ci cells, at that for all i (1 < i ≀ n) holds ci ≀ ci - 1. Let's denote s as the total number of cells of table a, that is, <image>. We know that each cell of the table contains a single integer from 1 to s, at that all written integers are distinct. Let's assume that the cells of the i-th row of table a are numbered from 1 to ci, then let's denote the number written in the j-th cell of the i-th row as ai, j. Your task is to perform several swap operations to rearrange the numbers in the table so as to fulfill the following conditions: 1. for all i, j (1 < i ≀ n; 1 ≀ j ≀ ci) holds ai, j > ai - 1, j; 2. for all i, j (1 ≀ i ≀ n; 1 < j ≀ ci) holds ai, j > ai, j - 1. In one swap operation you are allowed to choose two different cells of the table and swap the recorded there numbers, that is the number that was recorded in the first of the selected cells before the swap, is written in the second cell after it. Similarly, the number that was recorded in the second of the selected cells, is written in the first cell after the swap. Rearrange the numbers in the required manner. Note that you are allowed to perform any number of operations, but not more than s. You do not have to minimize the number of operations. Input The first line contains a single integer n (1 ≀ n ≀ 50) that shows the number of rows in the table. The second line contains n space-separated integers ci (1 ≀ ci ≀ 50; ci ≀ ci - 1) β€” the numbers of cells on the corresponding rows. Next n lines contain table Π°. The i-th of them contains ci space-separated integers: the j-th integer in this line represents ai, j. It is guaranteed that all the given numbers ai, j are positive and do not exceed s. It is guaranteed that all ai, j are distinct. Output In the first line print a single integer m (0 ≀ m ≀ s), representing the number of performed swaps. In the next m lines print the description of these swap operations. In the i-th line print four space-separated integers xi, yi, pi, qi (1 ≀ xi, pi ≀ n; 1 ≀ yi ≀ cxi; 1 ≀ qi ≀ cpi). The printed numbers denote swapping the contents of cells axi, yi and api, qi. Note that a swap operation can change the contents of distinct table cells. Print the swaps in the order, in which they should be executed. Examples Input 3 3 2 1 4 3 5 6 1 2 Output 2 1 1 2 2 2 1 3 1 Input 1 4 4 3 2 1 Output 2 1 1 1 4 1 2 1 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int c[n]; for (int i = 0; i < n; i++) cin >> c[i]; vector<vector<int> > a(n); for (int i = 0; i < n; i++) { for (int j = 0; j < c[i]; j++) { int x; cin >> x; a[i].push_back(x); } } vector<pair<pair<int, int>, pair<int, int> > > ans; int cur = 1; for (int i = 0; i < n; i++) { for (int j = 0; j < c[i]; j++, cur++) { if (a[i][j] == cur) continue; for (int k = i; k < n; k++) { for (int l = 0; l < c[k]; l++) { if (a[k][l] == cur) { ans.push_back( make_pair(make_pair(i + 1, j + 1), make_pair(k + 1, l + 1))); int temp = a[i][j]; a[i][j] = a[k][l]; a[k][l] = temp; break; } } } } } cout << ans.size() << endl; for (int i = 0; i < ans.size(); i++) { cout << ans[i].first.first << " " << ans[i].first.second << " " << ans[i].second.first << " " << ans[i].second.second << endl; } } ```
### Prompt Please create a solution in cpp to the following problem: Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after the decimal point (also, he can ask to round to the nearest integer). There are t seconds left till the end of the break, so Efim has to act fast. Help him find what is the maximum grade he can get in no more than t seconds. Note, that he can choose to not use all t seconds. Moreover, he can even choose to not round the grade at all. In this problem, classic rounding rules are used: while rounding number to the n-th digit one has to take a look at the digit n + 1. If it is less than 5 than the n-th digit remain unchanged while all subsequent digits are replaced with 0. Otherwise, if the n + 1 digit is greater or equal to 5, the digit at the position n is increased by 1 (this might also change some other digits, if this one was equal to 9) and all subsequent digits are replaced with 0. At the end, all trailing zeroes are thrown away. For example, if the number 1.14 is rounded to the first decimal place, the result is 1.1, while if we round 1.5 to the nearest integer, the result is 2. Rounding number 1.299996121 in the fifth decimal place will result in number 1.3. Input The first line of the input contains two integers n and t (1 ≀ n ≀ 200 000, 1 ≀ t ≀ 109) β€” the length of Efim's grade and the number of seconds till the end of the break respectively. The second line contains the grade itself. It's guaranteed that the grade is a positive number, containing at least one digit after the decimal points, and it's representation doesn't finish with 0. Output Print the maximum grade that Efim can get in t seconds. Do not print trailing zeroes. Examples Input 6 1 10.245 Output 10.25 Input 6 2 10.245 Output 10.3 Input 3 100 9.2 Output 9.2 Note In the first two samples Efim initially has grade 10.245. During the first second Efim can obtain grade 10.25, and then 10.3 during the next second. Note, that the answer 10.30 will be considered incorrect. In the third sample the optimal strategy is to not perform any rounding at all. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long fp(long long x, long long exp) { if (exp == 00) return 1; if (exp % 2 == 0) return fp((x * x), exp / 2); return (((fp((x * x), exp / 2))) * x); } bool IspowerofTwo(int x) { return (x & (x - 1)) == 0; } int main() { int ind = -1, ans, j, t; string s; cin >> ans >> t; cin >> s; for (int i = 0; i < s.size() && ind == -1; i++) if (s[i] == '.') ind = i + 1; for (int i = ind; i < s.size(); i++) if (s[i] > '4') { j = i; break; } for (int i = j; i >= ind && t; i--) if (s[i] > '9') if (i - 1 >= ind) { s[i - 1]++; ans = i; } else { s[ind - 2]++; ans = ind; } else if (s[i] > '4') if (i - 1 >= ind) { t--; s[i - 1]++; ans = i; } else { t--; s[ind - 2]++; ans = ind; } j = ind - 2; while (j > -1 && s[j] > '9') { s[j] = '0'; if (j > 0) s[j - 1]++; else s = '1' + s, ans++; j--; } for (int i = ans - 1; i > -1 && s[i] == '0'; i--) ans--; for (int i = 0; i < ans; i++) { if (s[i] == '.' && i == ans - 1) break; cout << s[i]; } return 0; } ```
### Prompt Your task is to create a cpp solution to the following problem: "Eat a beaver, save a tree!" β€” That will be the motto of ecologists' urgent meeting in Beaverley Hills. And the whole point is that the population of beavers on the Earth has reached incredible sizes! Each day their number increases in several times and they don't even realize how much their unhealthy obsession with trees harms the nature and the humankind. The amount of oxygen in the atmosphere has dropped to 17 per cent and, as the best minds of the world think, that is not the end. In the middle of the 50-s of the previous century a group of soviet scientists succeed in foreseeing the situation with beavers and worked out a secret technology to clean territory. The technology bears a mysterious title "Beavermuncher-0xFF". Now the fate of the planet lies on the fragile shoulders of a small group of people who has dedicated their lives to science. The prototype is ready, you now need to urgently carry out its experiments in practice. You are given a tree, completely occupied by beavers. A tree is a connected undirected graph without cycles. The tree consists of n vertices, the i-th vertex contains ki beavers. "Beavermuncher-0xFF" works by the following principle: being at some vertex u, it can go to the vertex v, if they are connected by an edge, and eat exactly one beaver located at the vertex v. It is impossible to move to the vertex v if there are no beavers left in v. "Beavermuncher-0xFF" cannot just stand at some vertex and eat beavers in it. "Beavermuncher-0xFF" must move without stops. Why does the "Beavermuncher-0xFF" works like this? Because the developers have not provided place for the battery in it and eating beavers is necessary for converting their mass into pure energy. It is guaranteed that the beavers will be shocked by what is happening, which is why they will not be able to move from a vertex of the tree to another one. As for the "Beavermuncher-0xFF", it can move along each edge in both directions while conditions described above are fulfilled. The root of the tree is located at the vertex s. This means that the "Beavermuncher-0xFF" begins its mission at the vertex s and it must return there at the end of experiment, because no one is going to take it down from a high place. Determine the maximum number of beavers "Beavermuncher-0xFF" can eat and return to the starting vertex. Input The first line contains integer n β€” the number of vertices in the tree (1 ≀ n ≀ 105). The second line contains n integers ki (1 ≀ ki ≀ 105) β€” amounts of beavers on corresponding vertices. Following n - 1 lines describe the tree. Each line contains two integers separated by space. These integers represent two vertices connected by an edge. Vertices are numbered from 1 to n. The last line contains integer s β€” the number of the starting vertex (1 ≀ s ≀ n). Output Print the maximum number of beavers munched by the "Beavermuncher-0xFF". Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d). Examples Input 5 1 3 1 3 2 2 5 3 4 4 5 1 5 4 Output 6 Input 3 2 1 1 3 2 1 2 3 Output 2 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int T; int N; struct node { int x, next; }; struct node edge[200000 + 5]; int head[100000 + 5], edgenum; void AddEdge(int x, int y) { edge[edgenum].x = y; edge[edgenum].next = head[x]; head[x] = edgenum++; } int g[100000 + 5]; long long dp[100000 + 5], Left[100000 + 5], fa[100000 + 5]; int start; vector<long long> temp; void dfs(int x) { dp[x] = 0; Left[x] = g[x] - 1; long long cnt = 0; for (int i = head[x]; i != -1; i = edge[i].next) { int tx = edge[i].x; if (fa[x] == tx) continue; fa[tx] = x; cnt++; dfs(tx); } temp.clear(); for (int i = head[x]; i != -1; i = edge[i].next) { int tx = edge[i].x; if (fa[x] == tx) continue; temp.push_back(dp[tx]); cnt += Left[tx]; } sort(temp.begin(), temp.end()); reverse(temp.begin(), temp.end()); for (int i = 0; i < (int)(temp).size() && temp[i] > 0 && Left[x] > 0; i++) { dp[x] += temp[i] + 2; Left[x]--; cnt--; } dp[x] += min(Left[x], cnt) * 2; Left[x] -= min(Left[x], cnt); } int main() { memset(head, -1, sizeof(head)); scanf("%d", &N); for (int i = 1; i <= N; i++) scanf("%d", &g[i]); for (int i = 0, x, y; i + 1 < N; i++) { scanf("%d %d", &x, &y); AddEdge(x, y); AddEdge(y, x); } scanf("%d", &start); g[start]++; dfs(start); cout << dp[start] << endl; return 0; } ```
### Prompt Generate a Cpp solution to the following problem: You are given four integers: H, W, h and w (1 ≀ h ≀ H, 1 ≀ w ≀ W). Determine whether there exists a matrix such that all of the following conditions are held, and construct one such matrix if the answer is positive: * The matrix has H rows and W columns. * Each element of the matrix is an integer between -10^9 and 10^9 (inclusive). * The sum of all the elements of the matrix is positive. * The sum of all the elements within every subrectangle with h rows and w columns in the matrix is negative. Constraints * 1 ≀ h ≀ H ≀ 500 * 1 ≀ w ≀ W ≀ 500 Input Input is given from Standard Input in the following format: H W h w Output If there does not exist a matrix that satisfies all of the conditions, print `No`. Otherwise, print `Yes` in the first line, and print a matrix in the subsequent lines in the following format: a_{11} ... a_{1W} : a_{H1} ... a_{HW} Here, a_{ij} represents the (i,\ j) element of the matrix. Examples Input 3 3 2 2 Output Yes 1 1 1 1 -4 1 1 1 1 Input 2 4 1 2 Output No Input 3 4 2 3 Output Yes 2 -5 8 7 3 -5 -4 -5 2 1 -1 7 ### Response ```cpp #include <cmath> #include <cstring> #include <cstdio> #include <algorithm> #define ll long long using namespace std; const int x=1000; int W,H,w,h,sum; int a[510][510]; int main(){ scanf("%d%d%d%d",&W,&H,&w,&h); for (int i=1;i<=W;++i) for (int j=1;j<=H;++j) a[i][j]=x; sum=W*H*x; for (int i=w;i<=W;i+=w) for (int j=h;j<=H;j+=h){ a[i][j]=-w*h*x+x-1; sum=sum-w*h*x-1; } if (sum<=0) puts("No"); else{ puts("Yes"); for (int i=1;i<=W;++i){ for (int j=1;j<=H;++j) printf("%d ",a[i][j]); puts(""); } } } ```
### Prompt Your challenge is to write a cpp solution to the following problem: Santa Claus is the first who came to the Christmas Olympiad, and he is going to be the first to take his place at a desk! In the classroom there are n lanes of m desks each, and there are two working places at each of the desks. The lanes are numbered from 1 to n from the left to the right, the desks in a lane are numbered from 1 to m starting from the blackboard. Note that the lanes go perpendicularly to the blackboard, not along it (see picture). The organizers numbered all the working places from 1 to 2nm. The places are numbered by lanes (i. e. all the places of the first lane go first, then all the places of the second lane, and so on), in a lane the places are numbered starting from the nearest to the blackboard (i. e. from the first desk in the lane), at each desk, the place on the left is numbered before the place on the right. <image> The picture illustrates the first and the second samples. Santa Clause knows that his place has number k. Help him to determine at which lane at which desk he should sit, and whether his place is on the left or on the right! Input The only line contains three integers n, m and k (1 ≀ n, m ≀ 10 000, 1 ≀ k ≀ 2nm) β€” the number of lanes, the number of desks in each lane and the number of Santa Claus' place. Output Print two integers: the number of lane r, the number of desk d, and a character s, which stands for the side of the desk Santa Claus. The character s should be "L", if Santa Clause should sit on the left, and "R" if his place is on the right. Examples Input 4 3 9 Output 2 2 L Input 4 3 24 Output 4 3 R Input 2 4 4 Output 1 2 R Note The first and the second samples are shown on the picture. The green place corresponds to Santa Claus' place in the first example, the blue place corresponds to Santa Claus' place in the second example. In the third sample there are two lanes with four desks in each, and Santa Claus has the fourth place. Thus, his place is in the first lane at the second desk on the right. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n, m, k; cin >> n >> m >> k; if (k % (m << 1)) cout << (((k / m) >> 1) + 1) << " " << ((k % (m << 1) + 1) >> 1) << " "; else cout << ((k / m) >> 1) << " " << m << " "; if (k % 2) cout << "L"; else cout << "R"; return 0; } ```
### Prompt Construct a Cpp code solution to the problem outlined: Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects can be any letter from the first 20 lowercase letters of English alphabet (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t). In one move Koa: 1. selects some subset of positions p_1, p_2, …, p_k (k β‰₯ 1; 1 ≀ p_i ≀ n; p_i β‰  p_j if i β‰  j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). 2. selects any letter y (from the first 20 lowercase letters in English alphabet). 3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≀ i ≀ k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A. Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her! Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 10) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains one integer n (1 ≀ n ≀ 10^5) β€” the length of strings A and B. The second line of each test case contains string A (|A|=n). The third line of each test case contains string B (|B|=n). Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal. Example Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 3 3 2 4 Note * In the 1-st test case Koa: 1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β†’ \color{blue}{bb}b). 2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β†’ b\color{blue}{cc}). * In the 2-nd test case Koa: 1. selects positions 1 and 4 and sets A_1 = A_4 = a (\color{red}{c}ab\color{red}{c} β†’ \color{blue}{a}ab\color{blue}{a}). 2. selects positions 2 and 4 and sets A_2 = A_4 = b (a\color{red}{a}b\color{red}{a} β†’ a\color{blue}{b}b\color{blue}{b}). 3. selects position 3 and sets A_3 = c (ab\color{red}{b}b β†’ ab\color{blue}{c}b). * In the 3-rd test case Koa: 1. selects position 1 and sets A_1 = t (\color{red}{a}bc β†’ \color{blue}{t}bc). 2. selects position 2 and sets A_2 = s (t\color{red}{b}c β†’ t\color{blue}{s}c). 3. selects position 3 and sets A_3 = r (ts\color{red}{c} β†’ ts\color{blue}{r}). ### Response ```cpp #include <bits/stdc++.h> using namespace std; int T, n, a[100005], b[100005], f[22], F[22], u[22], m, dp[2222222], cnt[2222222], C; void ope(int x) { dp[x] = 0; for (int i = 1; i <= 20; ++i) { if ((1 << i) & x) { int y = x ^ (1 << i); if (dp[y] == -1) ope(y); if (!(y & f[i])) dp[x] |= dp[y]; } } if (dp[x]) C = max(C, cnt[x]); } void dfs(int x) { u[x] = 1; m |= (1 << x); for (int i = 1; i <= 20; ++i) if (!u[i] && (F[x] & (1 << i))) dfs(i); } int main() { for (int i = 1; i < 2222000; ++i) { if (i & 1) cnt[i] = cnt[i >> 1] + 1; else cnt[i] = cnt[i >> 1]; } scanf("%d", &T); while (T--) { scanf("%d", &n); for (int i = 1; i <= n; ++i) { char c; scanf(" %c", &c); a[i] = c - 96; } for (int i = 1; i <= n; ++i) { char c; scanf(" %c", &c); b[i] = c - 96; } memset(f, 0, sizeof(f)); memset(F, 0, sizeof(F)); for (int i = 1; i <= n; ++i) if (a[i] != b[i]) f[a[i]] |= (1 << b[i]), F[b[i]] |= (1 << a[i]); for (int i = 1; i <= 20; ++i) F[i] |= f[i]; memset(u, 0, sizeof(u)); memset(dp, -1, sizeof(dp)); dp[0] = 1; int ans = 0; for (int i = 1; i <= 20; ++i) { if (!u[i]) { m = 0; C = 0; dfs(i); ope(m); ans += cnt[m] * 2 - 1 - C; } } printf("%d\n", ans); } return 0; } ```
### Prompt Your task is to create a CPP solution to the following problem: You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array. A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous. Input The first line contains single positive integer n (1 ≀ n ≀ 105) β€” the number of integers. The second line contains n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output Print the maximum length of an increasing subarray of the given array. Examples Input 5 1 7 2 11 15 Output 3 Input 6 100 100 100 100 100 100 Output 1 Input 3 1 2 3 Output 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int N; cin >> N; int last; int dp; int result = 0; for (int i = 0; i < N; i++) { int x; cin >> x; if (i == 0) { dp = 1; result = 1; } else { if (x > last) dp = dp + 1; else dp = 1; } last = x; result = max(result, dp); } cout << result << endl; return 0; } ```
### Prompt Generate a cpp solution to the following problem: Aoki loves numerical sequences and trees. One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree. Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1. Determine whether such a tree exists. Constraints * 2 ≦ N ≦ 100 * 1 ≦ a_i ≦ N-1 Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output If there exists a tree that satisfies the condition, print `Possible`. Otherwise, print `Impossible`. Examples Input 5 3 2 2 3 3 Output Possible Input 3 1 1 2 Output Impossible Input 10 1 2 2 2 2 2 2 2 2 2 Output Possible Input 10 1 1 2 2 2 2 2 2 2 2 Output Impossible Input 6 1 1 1 1 1 5 Output Impossible Input 5 4 3 2 3 4 Output Possible ### Response ```cpp #include <bits/stdc++.h> #define rep(i, n) for (int i = 0; i < (n); i++) using namespace std; int main(){ int n; cin >> n; int s = 0; vector<int> a(n,0); rep(i,n){ int x; cin >> x; a[x]++; s = max(s, x); } bool check = 1; rep(i,s+1){ if(i < (s+1)/2){ if(a[i] > 0) check = 0; } else if(i == (s+1)/2 && s%2){ if(a[i] != 2) check = 0; } else if(i == (s+1)/2){ if(a[i] != 1) check = 0; } else { if(a[i] < 2) check = 0; } } cout << (check ? "Possible" : "Impossible") << endl; return 0; } ```
### Prompt Generate a CPP solution to the following problem: [Γ†sir - CHAOS](https://soundcloud.com/kivawu/aesir-chaos) [Γ†sir - V.](https://soundcloud.com/kivawu/aesir-v) "Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect. The time right now...... 00:01:12...... It's time." The emotion samples are now sufficient. After almost 3 years, it's time for Ivy to awake her bonded sister, Vanessa. The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1, 2, 3, …). The node with a number x (x > 1), is directly connected with a node with number (x)/(f(x)), with f(x) being the lowest prime divisor of x. Vanessa's mind is divided into n fragments. Due to more than 500 years of coma, the fragments have been scattered: the i-th fragment is now located at the node with a number k_i! (a factorial of k_i). To maximize the chance of successful awakening, Ivy decides to place the samples in a node P, so that the total length of paths from each fragment to P is smallest possible. If there are multiple fragments located at the same node, the path from that node to P needs to be counted multiple times. In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node. But for a mere human like you, is this still possible? For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node P. Input The first line contains an integer n (1 ≀ n ≀ 10^6) β€” number of fragments of Vanessa's mind. The second line contains n integers: k_1, k_2, …, k_n (0 ≀ k_i ≀ 5000), denoting the nodes where fragments of Vanessa's mind are located: the i-th fragment is at the node with a number k_i!. Output Print a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node P). As a reminder, if there are multiple fragments at the same node, the distance from that node to P needs to be counted multiple times as well. Examples Input 3 2 1 4 Output 5 Input 4 3 1 4 4 Output 6 Input 4 3 1 4 1 Output 6 Input 5 3 1 4 1 5 Output 11 Note Considering the first 24 nodes of the system, the node network will look as follows (the nodes 1!, 2!, 3!, 4! are drawn bold): <image> For the first example, Ivy will place the emotion samples at the node 1. From here: * The distance from Vanessa's first fragment to the node 1 is 1. * The distance from Vanessa's second fragment to the node 1 is 0. * The distance from Vanessa's third fragment to the node 1 is 4. The total length is 5. For the second example, the assembly node will be 6. From here: * The distance from Vanessa's first fragment to the node 6 is 0. * The distance from Vanessa's second fragment to the node 6 is 2. * The distance from Vanessa's third fragment to the node 6 is 2. * The distance from Vanessa's fourth fragment to the node 6 is again 2. The total path length is 6. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long ans = LONG_LONG_MAX; int n, tot, num, top; int cnt[5005][700], l[5005], r[5005], sum[5005], presum[5005]; int vis[5005], pri[5005]; int st[5005]; void dfs(int nl, int nr, long long nowdis) { ans = min(ans, nowdis); for (int i = nl; i <= nr; i++) if (cnt[st[i]][r[st[i]]] == 0) r[st[i]]--; while (nl <= nr && r[st[nl]] <= 0) nl++; if (nl > nr) return; int pre = nl; for (int i = nl; i <= nr; i++) { if (r[st[i]] != r[st[pre]]) { long long nexdis = nowdis; int szson = presum[i - 1] - presum[pre - 1]; nexdis -= szson; nexdis += n - szson; for (int j = pre; j <= i - 1; j++) cnt[st[j]][r[st[j]]]--; dfs(pre, i - 1, nexdis); pre = i; } } long long nexdis = nowdis; int szson = presum[nr] - presum[pre - 1]; nexdis -= szson; nexdis += n - szson; for (int j = pre; j <= nr; j++) cnt[st[j]][r[st[j]]]--; dfs(pre, nr, nexdis); } int main() { for (int i = 2; i <= 5000; i++) { if (!vis[i]) pri[++tot] = i; for (int j = i + i; j <= 5000; j += i) vis[j] = 1; } int gg = 0; for (int i = 2; i <= 5000; i++) { for (int j = 1; j <= tot; j++) { if (pri[j] > i) break; r[i] = j; int temp = pri[j]; while (i >= temp) { cnt[i][j] += i / temp; gg += i / temp; temp *= pri[j]; } } } scanf("%d", &n); for (int i = 1; i <= n; i++) { int x; scanf("%d", &x); sum[x]++; } long long nowdis = 0; for (int i = 1; i <= 5000; i++) { if (sum[i]) { st[++top] = i; for (int j = 1; j <= r[i]; j++) { nowdis += 1ll * sum[i] * cnt[i][j]; } } } for (int i = 1; i <= top; i++) presum[i] = presum[i - 1] + sum[st[i]]; dfs(1, top, nowdis); printf("%lld\n", ans); } ```
### Prompt Please provide a Cpp coded solution to the problem described below: Greg has an array a = a1, a2, ..., an and m operations. Each operation looks as: li, ri, di, (1 ≀ li ≀ ri ≀ n). To apply operation i to the array means to increase all array elements with numbers li, li + 1, ..., ri by value di. Greg wrote down k queries on a piece of paper. Each query has the following form: xi, yi, (1 ≀ xi ≀ yi ≀ m). That means that one should apply operations with numbers xi, xi + 1, ..., yi to the array. Now Greg is wondering, what the array a will be after all the queries are executed. Help Greg. Input The first line contains integers n, m, k (1 ≀ n, m, k ≀ 105). The second line contains n integers: a1, a2, ..., an (0 ≀ ai ≀ 105) β€” the initial array. Next m lines contain operations, the operation number i is written as three integers: li, ri, di, (1 ≀ li ≀ ri ≀ n), (0 ≀ di ≀ 105). Next k lines contain the queries, the query number i is written as two integers: xi, yi, (1 ≀ xi ≀ yi ≀ m). The numbers in the lines are separated by single spaces. Output On a single line print n integers a1, a2, ..., an β€” the array after executing all the queries. Separate the printed numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 3 3 3 1 2 3 1 2 1 1 3 2 2 3 4 1 2 1 3 2 3 Output 9 18 17 Input 1 1 1 1 1 1 1 1 1 Output 2 Input 4 3 6 1 2 3 4 1 2 1 2 3 2 3 4 4 1 2 1 3 2 3 1 2 1 3 2 3 Output 5 18 31 20 ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct node { int first, second, d; }; void solve() { int n, m, k; cin >> n >> m >> k; vector<long long> v(n); for (int i = 0; i < n; i++) { cin >> v[i]; } vector<node> op(m); for (int i = 0; i < m; i++) { int first, second, d; cin >> first >> second >> d; first--, second--; op[i] = {first, second, d}; } vector<int> cnt(m + 1); for (int i = 0; i < k; i++) { int first, second; cin >> first >> second; first--, second--; cnt[first]++; cnt[second + 1]--; } vector<long long> dv(n + 1); for (int i = 0; i < m; i++) { cnt[i] += (i - 1 >= 0 ? cnt[i - 1] : 0); long long inc = (long long)op[i].d * cnt[i]; dv[op[i].first] += inc; dv[op[i].second + 1] -= inc; } for (int i = 0; i < n; i++) { dv[i] += (i - 1 >= 0 ? dv[i - 1] : 0); cout << v[i] + dv[i] << (i == n - 1 ? '\n' : ' '); } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); solve(); return 0; } ```
### Prompt Create a solution in CPP for the following problem: A subway scheme, classic for all Berland cities is represented by a set of n stations connected by n passages, each of which connects exactly two stations and does not pass through any others. Besides, in the classic scheme one can get from any station to any other one along the passages. The passages can be used to move in both directions. Between each pair of stations there is no more than one passage. Berland mathematicians have recently proved a theorem that states that any classic scheme has a ringroad. There can be only one ringroad. In other words, in any classic scheme one can find the only scheme consisting of stations (where any two neighbouring ones are linked by a passage) and this cycle doesn't contain any station more than once. This invention had a powerful social impact as now the stations could be compared according to their distance from the ringroad. For example, a citizen could say "I live in three passages from the ringroad" and another one could reply "you loser, I live in one passage from the ringroad". The Internet soon got filled with applications that promised to count the distance from the station to the ringroad (send a text message to a short number...). The Berland government decided to put an end to these disturbances and start to control the situation. You are requested to write a program that can determine the remoteness from the ringroad for each station by the city subway scheme. Input The first line contains an integer n (3 ≀ n ≀ 3000), n is the number of stations (and trains at the same time) in the subway scheme. Then n lines contain descriptions of the trains, one per line. Each line contains a pair of integers xi, yi (1 ≀ xi, yi ≀ n) and represents the presence of a passage from station xi to station yi. The stations are numbered from 1 to n in an arbitrary order. It is guaranteed that xi β‰  yi and that no pair of stations contain more than one passage. The passages can be used to travel both ways. It is guaranteed that the given description represents a classic subway scheme. Output Print n numbers. Separate the numbers by spaces, the i-th one should be equal to the distance of the i-th station from the ringroad. For the ringroad stations print number 0. Examples Input 4 1 3 4 3 4 2 1 2 Output 0 0 0 0 Input 6 1 2 3 4 6 4 2 3 1 3 3 5 Output 0 0 0 1 1 2 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const double eps = 1e-9; const int inf = (int)1e9; const int MAX_N = 3000 + 100; int n; vector<int> arr[MAX_N]; int tour[MAX_N]; int visit[MAX_N]; vector<int> grey; int dist[MAX_N]; vector<int> q; int dfs(int here, int par, int depth) { if (visit[here] != -1) { for (int i = 0; i < depth - visit[here]; i++) { tour[grey.back()] = 1; grey.pop_back(); } return 1; } visit[here] = depth; for (int i = 0; i < ((int)arr[here].size()); i++) { int next = arr[here][i]; if (next != par) { grey.push_back(next); int res = dfs(next, here, depth + 1); if (res == 1) return 1; grey.pop_back(); } } return 0; } void bfs() { for (int i = 1; i <= n; i++) { dist[i] = inf; if (tour[i]) { dist[i] = 0; q.push_back(i); } } for (int head = 0; head < ((int)q.size()); head++) { int here = q[head]; for (int i = 0; i < ((int)arr[here].size()); i++) { int next = arr[here][i]; if (dist[next] > dist[here] + 1) { dist[next] = dist[here] + 1; q.push_back(next); } } } } int main() { cin >> n; for (int i = 0; i < n; i++) { int x, y; cin >> x >> y; arr[x].push_back(y); arr[y].push_back(x); } memset(visit, -1, sizeof visit); dfs(1, -1, 0); bfs(); for (int i = 1; i <= n; i++) { if (i > 1) cout << " "; cout << dist[i]; } cout << endl; return 0; } ```
### Prompt Your challenge is to write a cpp solution to the following problem: In the good old days, the Internet was free from fears and terrorism. People did not have to worry about any cyber criminals or mad computer scientists. Today, however, you are facing atrocious crackers wherever you are, unless being disconnected. You have to protect yourselves against their attacks. Counting upon your excellent talent for software construction and strong sense of justice, you are invited to work as a cyber guardian. Your ultimate mission is to create a perfect firewall system that can completely shut out any intruders invading networks and protect children from harmful information exposed on the Net. However, it is extremely difficult and none have ever achieved it before. As the first step, instead, you are now requested to write a software simulator under much simpler assumptions. In general, a firewall system works at the entrance of a local network of an organization (e.g., a company or a university) and enforces its local administrative policy. It receives both inbound and outbound packets (note: data transmitted on the Net are divided into small segments called packets) and carefully inspects them one by one whether or not each of them is legal. The definition of the legality may vary from site to site or depend upon the local administrative policy of an organization. Your simulator should accept data representing not only received packets but also the local administrative policy. For simplicity in this problem we assume that each network packet consists of three fields: its source address, destination address, and message body. The source address specifies the computer or appliance that transmits the packet and the destination address specifies the computer or appliance to which the packet is transmitted. An address in your simulator is represented as eight digits such as 03214567 or 31415926, instead of using the standard notation of IP addresses such as 192.168.1.1. Administrative policy is described in filtering rules, each of which specifies some collection of source-destination address pairs and defines those packets with the specified address pairs either legal or illegal. Input The input consists of several data sets, each of which represents filtering rules and received packets in the following format: n m rule1 rule2 ... rulen packet1 packet2 ... packetm The first line consists of two non-negative integers n and m. If both n and m are zeros, this means the end of input. Otherwise, n lines, each representing a filtering rule, and m lines, each representing an arriving packet, follow in this order. You may assume that n and m are less than or equal to 1,024. Each rulei is in one of the following formats: permit source-pattern destination-pattern deny source-pattern destination-pattern A source-pattern or destination-pattern is a character string of length eight, where each character is either a digit ('0' to '9') or a wildcard character '?'. For instance, "1????5??" matches any address whose first and fifth digits are '1' and '5', respectively. In general, a wildcard character matches any single digit while a digit matches only itself. With the keywords "permit" and "deny", filtering rules specify legal and illegal packets, respectively. That is, if the source and destination addresses of a packed are matched with source-pattern and destination-pattern, respectively, it is permitted to pass the firewall or the request is denied according to the keyword. Note that a permit rule and a deny rule can contradict since they may share the same source and destination address pair. For the purpose of conflict resolution, we define a priority rule: rulei has a higher priority over rulej if and only if i > j. For completeness, we define the default rule: any packet is illegal unless being explicitly specified legal by some given rule. A packet is in the following format: source-address destination-address message-body Each of the first two is a character string of length eight that consists solely of digits. The last one is a character string consisting solely of alphanumeric characters ('a' to 'z', 'A' to 'Z', and '0' to '9'). Neither whitespaces nor special characters can occur in a message body. You may assume that it is not empty and that its length is at most 50. You may also assume that there is exactly one space character between any two adjacent fields in an input line representing a rule or a packet. Output For each data set, print the number of legal packets in the first line, followed by all legal packets in the same order as they occur in the data set. Each packet must be written exactly in one line. If the data set includes two packets consisting of the same source and destination addresses and the same message body, you should consider them different packets and so they must be written in different lines. Any extra whitespaces or extra empty lines must not be written. Example Input 2 5 permit 192168?? ?12??34? deny 19216899 012343?5 19216711 11233340 HiIamACracker 19216891 01234345 Hello 19216899 01234345 HiIamAlsoACracker 19216809 11200340 World 00000000 99999999 TheEndOfTheWorld 1 2 permit 12345678 23456789 19216891 01234345 Hello 12345678 23456789 Hello 0 0 Output 2 19216891 01234345 Hello 19216809 11200340 World 1 12345678 23456789 Hello ### Response ```cpp #include<iostream> #include<cstdio> #include<functional> #include<cstdlib> #include<stdexcept> #include<numeric> #include<cmath> #include<fstream> #include<memory> #include<algorithm> #include<cstring> #include<ctime> #include<deque> #include<sstream> #include<iomanip> #include<sstream> #include<vector> #include<queue> #include<stack> #include<string> #include<climits> #include<map> #include<set> #include<list> #include<cassert> #include<deque> #define REP(i,s,n) for(int i=s;i<n;i++) #define rep(i,n) REP(i,0,n) #define INF 1<<27 #define all(n) n.begin(),n.end() #define insert(a,b,c,d) PP(P(a,b),P(c,d)) #define F first #define iter(c) __typeof__((c).begin()) #define foreach(i,c) for(iter(c) i=(c).begin();i!=(c).end();++i) #define S second #define ppins(a,b,c,d) PP(P(a,b),P(c,d)) #define pb push_back #define pf push_front #define LIM 100000 using namespace std; typedef pair<int,int> P; typedef pair<P,P> PP; typedef long long ll; typedef unsigned long long ull; typedef pair<bool,bool> BI; bool judge(string s1,string s2) { rep(i,8) { if(s1[i] == '?')continue; if(s1[i] != s2[i]) return false; } for(int i=8;i<16;i++) { if(s1[i] == '?')continue; if(s1[i] != s2[i]) return false; } return true; } vector<char> rules; vector<string> sourceAnDdestination; int main() { while(true) { int n,m; cin >> n >> m; if(n+m == 0) break; char Message[1024][52]; rules.clear(),sourceAnDdestination.clear(); cin.ignore(); rep(i,n) { string line; string so,de,soandde; cin >> line >> so >> de; soandde = so+de; rules.pb(line[0]),sourceAnDdestination.pb(soandde); } BI legal[m]; rep(i,m) legal[i] = BI(false,false); rep(i,m) { string a,b,c; cin >> a >> b >> c; string aandb = a+b; sourceAnDdestination.pb(aandb); strcpy(Message[i],c.c_str()); } int cnt = 0; for(int i=n-1;i>=0;i--) { if(rules[i] == 'p') { rep(j,m) { if(legal[j].S) continue; if(judge(sourceAnDdestination[i],sourceAnDdestination[n+j])) { legal[j] = BI(true,true); cnt++; } } } else { rep(j,m) { if(legal[j].S) continue; if(judge(sourceAnDdestination[i],sourceAnDdestination[n+j])) { legal[j] = BI(false,true); } } } } cout << cnt << endl; rep(i,m) { if(legal[i].F) { cout << sourceAnDdestination[i+n].substr(0,8) << " " << sourceAnDdestination[i+n].substr(8,8) << " " << Message[i] << endl; } } } return 0; } ```
### Prompt Please create a solution in Cpp to the following problem: There is a tree with N vertices numbered 1 through N. The i-th edge connects Vertex x_i and y_i. Each vertex is painted white or black. The initial color of Vertex i is represented by a letter c_i. c_i = `W` represents the vertex is white; c_i = `B` represents the vertex is black. A cat will walk along this tree. More specifically, she performs one of the following in one second repeatedly: * Choose a vertex that is adjacent to the vertex where she is currently, and move to that vertex. Then, invert the color of the destination vertex. * Invert the color of the vertex where she is currently. The cat's objective is to paint all the vertices black. She may start and end performing actions at any vertex. At least how many seconds does it takes for the cat to achieve her objective? Constraints * 1 ≀ N ≀ 10^5 * 1 ≀ x_i,y_i ≀ N (1 ≀ i ≀ N-1) * The given graph is a tree. * c_i = `W` or c_i = `B`. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} c_1c_2..c_N Output Print the minimum number of seconds required to achieve the objective. Examples Input 5 1 2 2 3 2 4 4 5 WBBWW Output 5 Input 6 3 1 4 5 2 6 6 1 3 4 WWBWBB Output 7 Input 1 B Output 0 Input 20 2 19 5 13 6 4 15 6 12 19 13 19 3 11 8 3 3 20 16 13 7 14 3 17 7 8 10 20 11 9 8 18 8 2 10 1 6 13 WBWBWBBWWWBBWWBBBBBW Output 21 ### Response ```cpp #include <bits/stdc++.h> using namespace std; vector <int> e[200005]; int d[200005]; bool ban[200005],val[200005]; int dis[200005]; int dfs(int x,int fa) { dis[x]=dis[fa]+val[x]; int ans=x; for(int i=0;i<e[x].size();i++) if (e[x][i]!=fa&&!ban[e[x][i]]) { int u=e[x][i]; int t=dfs(u,x); if (dis[t]>dis[ans]) ans=t; } return ans; } char str[200005]; queue <int> q; int main() { int n; scanf("%d",&n); for(int i=1;i<n;i++) { int x,y; scanf("%d%d",&x,&y); e[x].push_back(y); e[y].push_back(x); d[x]++;d[y]++; } scanf("%s",str+1); bool ok=0; for(int i=1;i<=n;i++) { val[i]=(str[i]=='W'); ok|=val[i]; } if (!ok) { puts("0"); return 0; } for(int i=1;i<=n;i++) if (!val[i]&&d[i]<=1) q.push(i); while (!q.empty()) { int x=q.front();q.pop(); ban[x]=1; for(int i=0;i<e[x].size();i++) if (!ban[e[x][i]]) { int u=e[x][i]; d[u]--; if (!val[u]&&d[u]<=1) q.push(u); } } int rt=0,s=-2; for(int i=1;i<=n;i++) if (!ban[i]) { rt=i; for(int j=0;j<e[i].size();j++) if (!ban[e[i][j]]) val[e[i][j]]^=1; s+=2; } for(int i=1;i<=n;i++) if (!ban[i]) s+=val[i]; rt=dfs(rt,0); int x=dfs(rt,0); printf("%d\n",max(1,s-2*dis[x])); return 0; } ```
### Prompt Please provide a cpp coded solution to the problem described below: 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; template <typename T> void println(const T &t) { cout << t << '\n'; } template <typename T, typename... Args> void println(const T &t, const Args &...rest) { cout << t << ' '; println(rest...); } template <typename T> void print(const T &t) { cout << t << ' '; } template <typename T, typename... Args> void print(const T &t, const Args &...rest) { cout << t; print(rest...); } template <class T> void scan(T &t) { cin >> t; } template <class T, class... Args> void scan(T &a, Args &...rest) { cin >> a; scan(rest...); } using ll = long long; using vl = vector<ll>; using vi = vector<int>; using pii = pair<int, int>; using vb = vector<bool>; using vpii = vector<pii>; auto bet = [](const ll x, const ll y, const ll i) { return x <= i && i <= y; }; template <typename T> struct bit { vector<T> a; explicit bit(int n, int v = 0) { a.resize(n + 1); if (v != 0) { for (int i = 1; i <= n; ++i) a[i] = v; } } T sum(T x) { T res = 0; while (x) { res += a[x]; x -= x & -x; } return res; } T sum(int l, int r) { if (l > r) return 0; return sum(r) - sum(l - 1); } void add(int x, T v) { while (x < a.size()) { a[x] += v; x += x & -x; } } void clear() { fill(a.begin(), a.end(), 0); } }; vi get_prime(int n) { vi minp(n + 1), p; for (int i = 2; i <= n; i++) { if (!minp[i]) { minp[i] = i; p.push_back(i); } for (auto &x : p) { if (x <= minp[i] && x * i <= n) minp[x * i] = x; else break; } } return p; } const int mod = 998244353; void add_mod(ll &x, const ll &y) { x += y; if (x >= mod) x -= mod; } void sub_mod(ll &x, const ll &y) { x -= y; if (x < 0) x += mod; } template <typename T> using vv = vector<vector<T>>; template <typename T1, typename T2 = T1> using vp = vector<pair<T1, T2>>; using vec = vector<ll>; using mat = vector<vec>; mat get_I(int n) { mat res(n, vec(n)); for (int i = 0; i < n; i++) res[i][i] = 1; return res; } mat operator*(const mat &a, const mat &b) { mat c(a.size(), vec(b[0].size())); for (size_t i = 0; i < a.size(); i++) { for (size_t j = 0; j < a[0].size(); j++) { if (a[i][j]) { for (size_t k = 0; k < b[0].size(); k++) { add_mod(c[i][k], a[i][j] * b[j][k] % mod); } } } } return c; } vec operator*(const mat &a, const vec &b) { vec c(a.size()); for (size_t i = 0; i < a.size(); i++) { for (size_t j = 0; j < a[0].size(); j++) { add_mod(c[i], a[i][j] * b[j] % mod); } } return c; } mat pow(mat a, ll n) { mat res(a.size(), vec(a[0].size())); for (size_t i = 0; i < a.size(); i++) { res[i][i] = 1; } while (n) { if (n & 1) { res = res * a; } a = a * a; n >>= 1; } return res; } const int N = 100005; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, k; scan(n, k); vi d(n), lev(n); vi par(n); vv<int> g(n); for (int _ = 0, __ = (int)n - 1; _ < __; _++) { int u, v; scan(u, v); --u, --v; d[u]++, d[v]++; g[u].push_back(v), g[v].push_back(u); } int c3 = 0; for (int i = (0); i < (n); ++i) { if (d[i] == 2) { println("No"); return 0; } c3 += d[i] == 3; if (c3 == 2) { println("No"); return 0; } } queue<int> que; for (int i = (0); i < (n); ++i) if (d[i] == 1) { lev[i] = 1; for (auto &j : g[i]) { if (d[j] == 1) { ; { println("No"); return 0; }; } if (!lev[j]) { par[i] = j; lev[j] = lev[i] + 1; que.push(j); } } } while (que.size() > 1) { auto u = que.front(); que.pop(); bool flag = false; for (auto &v : g[u]) { if (lev[v]) { if (lev[v] == lev[u] + 1) { if (!flag) par[u] = v, flag = true; else { ; { println("No"); return 0; } } } else if (lev[v] != lev[u] - 1) { ; { println("No"); return 0; } } } else if (!flag) { flag = true; que.push(v); lev[v] = lev[u] + 1; par[v] = u; } else { ; { println("No"); return 0; } } } if (!flag) { ; { println("No"); return 0; } } }; if (que.size() != 1) { println("No"); return 0; }; int u = que.front(); ; if (lev[u] != k + 1 || c3 && d[u] != 3) { println("No"); return 0; } println("Yes"); return 0; } ```
### Prompt Construct a CPP code solution to the problem outlined: You are given a description of a depot. It is a rectangular checkered field of n Γ— m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall. Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the depot field. The next n lines contain m symbols "." and "*" each β€” the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall. Output If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line β€” the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them. Examples Input 3 4 .*.. .... .*.. Output YES 1 2 Input 3 3 ..* .*. *.. Output NO Input 6 5 ..*.. ..*.. ***** ..*.. ..*.. ..*.. Output YES 3 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int R[1005], C[1005]; int T[1005][1005]; vector<pair<int, int> > V; int main() { ios_base::sync_with_stdio(0); int n, m; cin >> n >> m; int cnt = 0; int cnt1 = 0, cnt2 = 0, cnt3 = 0, cnt4 = 0; int x = 0, y = 0; int x2, y2; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { char c; cin >> c; if (c == '*') { cnt++; V.push_back(make_pair(i + 1, j + 1)); T[i][j] = 1; R[i]++; C[j]++; x = i, y = j; } else T[i][j] = 0; } for (int i = 0; i < n; i++) { if (R[i] > 1) { for (int j = 0; j < m; j++) { if (R[i] + C[j] - T[i][j] == cnt) { cout << "YES\n" << i + 1 << " " << j + 1 << "\n"; return 0; } } cout << "NO\n"; return 0; } } for (int i = 0; i < m; i++) { if (C[i] > 1) { for (int j = 0; j < n; j++) { if (R[j] + C[i] - T[j][i] == cnt) { cout << "YES\n" << j + 1 << " " << i + 1 << "\n"; return 0; } } cout << "NO\n"; return 0; } } if (cnt > 2) { cout << "NO\n"; } else if (cnt == 2) { cout << "YES\n" << V[0].first << " " << V[1].second << "\n"; } else if (cnt == 1) { cout << "YES\n" << V[0].first << " " << V[0].second << "\n"; } else cout << "YES\n1 1\n"; return 0; } ```
### Prompt Develop a solution in CPP to the problem described below: Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it. That element can store information about the matrix of integers size n Γ— m. There are n + m inputs in that element, i.e. each row and each column can get the signal. When signal comes to the input corresponding to some row, this row cyclically shifts to the left, that is the first element of the row becomes last element, second element becomes first and so on. When signal comes to the input corresponding to some column, that column shifts cyclically to the top, that is first element of the column becomes last element, second element becomes first and so on. Rows are numbered with integers from 1 to n from top to bottom, while columns are numbered with integers from 1 to m from left to right. Artem wants to carefully study this element before using it. For that purpose he is going to set up an experiment consisting of q turns. On each turn he either sends the signal to some input or checks what number is stored at some position of the matrix. Artem has completed his experiment and has written down the results, but he has lost the chip! Help Artem find any initial matrix that will match the experiment results. It is guaranteed that experiment data is consistent, which means at least one valid matrix exists. Input The first line of the input contains three integers n, m and q (1 ≀ n, m ≀ 100, 1 ≀ q ≀ 10 000) β€” dimensions of the matrix and the number of turns in the experiment, respectively. Next q lines contain turns descriptions, one per line. Each description starts with an integer ti (1 ≀ ti ≀ 3) that defines the type of the operation. For the operation of first and second type integer ri (1 ≀ ri ≀ n) or ci (1 ≀ ci ≀ m) follows, while for the operations of the third type three integers ri, ci and xi (1 ≀ ri ≀ n, 1 ≀ ci ≀ m, - 109 ≀ xi ≀ 109) are given. Operation of the first type (ti = 1) means that signal comes to the input corresponding to row ri, that is it will shift cyclically. Operation of the second type (ti = 2) means that column ci will shift cyclically. Finally, operation of the third type means that at this moment of time cell located in the row ri and column ci stores value xi. Output Print the description of any valid initial matrix as n lines containing m integers each. All output integers should not exceed 109 by their absolute value. If there are multiple valid solutions, output any of them. Examples Input 2 2 6 2 1 2 2 3 1 1 1 3 2 2 2 3 1 2 8 3 2 1 8 Output 8 2 1 8 Input 3 3 2 1 2 3 2 2 5 Output 0 0 0 0 0 5 0 0 0 ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <class T> T gcd(T a, T b) { return b ? gcd(b, a % b) : a; } const double EPS = 1e-9; const double PI = acos(-1.); const int INF = 1e9; const int MAXN = 2e5 + 5, MAXC = 105; const long long MOD = 1e9 + 7; int vv[MAXC][MAXC]; int tt[MAXN], r[MAXN], c[MAXN], x[MAXN]; void solve() { int n, m, q; scanf("%d%d%d", &n, &m, &q); for (int i = (0); i < (int)(q); i++) { scanf("%d", &tt[i]); if (tt[i] == 1) { scanf("%d", &r[i]); } else if (tt[i] == 2) { scanf("%d", &c[i]); } else { scanf("%d%d%d", &r[i], &c[i], &x[i]); } } for (int k = q - 1; k >= 0; k--) { if (tt[k] == 3) { vv[r[k]][c[k]] = x[k]; } else if (tt[k] == 1) { for (int i = r[k]; i <= r[k]; i++) { for (int j = m + 1; j >= 2; j--) { vv[i][j] = vv[i][j - 1]; } vv[i][1] = vv[i][m + 1]; } } else if (tt[k] == 2) { for (int j = c[k]; j <= c[k]; j++) { for (int i = n + 1; i >= 2; i--) { vv[i][j] = vv[i - 1][j]; } vv[1][j] = vv[n + 1][j]; } } } for (int i = (1); i <= (int)(n); i++) { for (int j = (1); j <= (int)(m); j++) { printf("%d ", vv[i][j]); } putchar('\n'); } } int main() { int t = 1; while (t--) { solve(); } } ```
### Prompt Please formulate a CPP solution to the following problem: You are given n strings s1, s2, ..., sn consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation saisbi is saved into a new string sn + i (the operations are numbered starting from 1). After each operation you need to find the maximum positive integer k such that all possible strings consisting of 0 and 1 of length k (there are 2k such strings) are substrings of the new string. If there is no such k, print 0. Input The first line contains single integer n (1 ≀ n ≀ 100) β€” the number of strings. The next n lines contain strings s1, s2, ..., sn (1 ≀ |si| ≀ 100), one per line. The total length of strings is not greater than 100. The next line contains single integer m (1 ≀ m ≀ 100) β€” the number of operations. m lines follow, each of them contains two integers ai abd bi (1 ≀ ai, bi ≀ n + i - 1) β€” the number of strings that are concatenated to form sn + i. Output Print m lines, each should contain one integer β€” the answer to the question after the corresponding operation. Example Input 5 01 10 101 11111 0 3 1 2 6 5 4 4 Output 1 2 0 Note On the first operation, a new string "0110" is created. For k = 1 the two possible binary strings of length k are "0" and "1", they are substrings of the new string. For k = 2 and greater there exist strings of length k that do not appear in this string (for k = 2 such string is "00"). So the answer is 1. On the second operation the string "01100" is created. Now all strings of length k = 2 are present. On the third operation the string "1111111111" is created. There is no zero, so the answer is 0. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long mod = 1000000007; const unsigned gen_seed = std::chrono::system_clock::now().time_since_epoch().count(); std::mt19937_64 gen(gen_seed); std::vector<int> a[201][20]; string l[201]; string r[201]; const int INF = 1e9; void mer(std::vector<int>& a, std::vector<int>& b, std::vector<int>& c, std::vector<int>& to) { int pta = 0, ptb = 0, ptc = 0; a.push_back(INF); b.push_back(INF); c.push_back(INF); while (1) { if (a[pta] <= b[ptb] && a[pta] <= c[ptc]) { if (a[pta] == INF) break; to.push_back(a[pta]); if (b[ptb] == a[pta]) ptb++; if (c[ptc] == a[pta]) ptc++; pta++; } else if (b[ptb] <= a[pta] && b[ptb] <= c[ptc]) { to.push_back(b[ptb]); if (b[ptb] == a[pta]) pta++; if (c[ptc] == b[ptb]) ptc++; ptb++; } else { to.push_back(c[ptc]); if (c[ptc] == a[pta]) pta++; if (c[ptc] == b[ptb]) ptb++; ptc++; } } a.pop_back(); b.pop_back(); c.pop_back(); } int main() { int n; cin >> n; for (int i = 0; i < n; i++) { string s; cin >> s; l[i] = s; r[i] = s; for (int st = 0; st < s.size(); st++) for (int en = st; en < s.size(); en++) { if (en - st + 1 >= 20) continue; int cur = 0; for (int j = st; j < en + 1; j++) { cur = cur * 2 + (s[j] - '0'); } a[i][en - st + 1].push_back(cur); } for (int j = 0; j < 20; j++) { std::vector<int> fil = a[i][j]; sort((fil).begin(), (fil).end()); a[i][j].clear(); for (int k = 0; k < fil.size(); k++) if (k == 0 || fil[k] != fil[k - 1]) a[i][j].push_back(fil[k]); } } for (int i = 0; i < n; i++) { if (l[i].size() > 20) l[i] = l[i].substr(0, 20); if (r[i].size() > 20) r[i] = r[i].substr(r[i].size() - 20); } int m; cin >> m; for (int it = 0; it < m; it++) { int x, y; cin >> x >> y; x--; y--; l[n + it] = l[x]; if (l[n + it].size() < 20) l[n + it] += l[y]; if (l[n + it].size() > 20) l[n + it] = l[n + it].substr(0, 20); r[n + it] = r[y]; if (r[n + it].size() < 20) r[n + it] = r[x] + r[n + it]; if (r[n + it].size() > 20) r[n + it] = r[n + it].substr(r[n + it].size() - 20); int sl = r[x].size(); int sr = l[y].size(); for (int len = 1; len < 20; len++) { std::vector<int> addgr; for (int tl = 1; tl < len; tl++) { int tr = len - tl; if (tl > sl || tr > sr) continue; string p = r[x].substr(sl - tl) + l[y].substr(0, tr); int cur = 0; for (auto cx : p) cur = cur * 2 + (cx - '0'); addgr.push_back(cur); } sort((addgr).begin(), (addgr).end()); std::vector<int> add; for (int i = 0; i < addgr.size(); i++) if (i == 0 || addgr[i] != addgr[i - 1]) add.push_back(addgr[i]); mer(a[x][len], a[y][len], add, a[n + it][len]); } int k = 1; while (a[n + it][k].size() == (1 << k)) k++; printf("%d\n", k - 1); } } ```
### Prompt In CPP, your task is to solve the following problem: Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm! Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen. The string on the screen can be changed using the operation Β«shift xΒ». In order to apply this operation, explorers choose an integer x from 0 to n inclusive. After that, the current string p = Ξ±Ξ² changes to Ξ²RΞ±, where the length of Ξ² is x, and the length of Ξ± is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation Β«shift 4Β» the string Β«abcacbΒ» will be changed with string Β«bcacab Β», since Ξ± = ab, Ξ² = cacb, Ξ²R = bcac. Explorers are afraid that if they apply too many operations Β«shiftΒ», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations. Input The first line contains an integer n, the length of the strings s and t (1 ≀ n ≀ 2 000). After that, there are two strings s and t, consisting of n lowercase Latin letters each. Output If it is impossible to get string t from string s using no more than 6100 operations Β«shiftΒ», print a single number - 1. Otherwise, in the first line output the number of operations k (0 ≀ k ≀ 6100). In the next line output k numbers xi corresponding to the operations Β«shift xiΒ» (0 ≀ xi ≀ n) in the order in which they should be applied. Examples Input 6 abacbb babcba Output 4 6 3 2 3 Input 3 aba bba Output -1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, cnt[30]; char sir1[2010], sir2[2010]; vector<int> rez; void solve(int poz) { rez.push_back(poz); reverse(sir1 + 1, sir1 + (n - poz) + 1); reverse(sir1 + 1, sir1 + n + 1); } int main() { scanf("%d\n", &n); scanf("%s\n", sir1 + 1); scanf("%s", sir2 + 1); for (int i = 1; i <= n; i++) cnt[sir1[i] - 'a']++; for (int i = 1; i <= n; i++) cnt[sir2[i] - 'a']--; for (int i = 0; i < 26; i++) if (cnt[i] != 0) { printf("-1"); return 0; } for (int i = 1; i <= n; i++) { int poz = 1; for (; sir1[poz] != sir2[i]; poz++) ; solve(n - poz); solve(1); solve(n); } printf("%d\n", rez.size()); for (int i = 0; i < rez.size(); i++) printf("%d ", rez[i]); return 0; } ```
### Prompt In CPP, your task is to solve the following problem: Petya has n integers: 1, 2, 3, ..., n. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible. Help Petya to split the integers. Each of n integers should be exactly in one group. Input The first line contains a single integer n (2 ≀ n ≀ 60 000) β€” the number of integers Petya has. Output Print the smallest possible absolute difference in the first line. In the second line print the size of the first group, followed by the integers in that group. You can print these integers in arbitrary order. If there are multiple answers, print any of them. Examples Input 4 Output 0 2 1 4 Input 2 Output 1 1 1 Note In the first example you have to put integers 1 and 4 in the first group, and 2 and 3 in the second. This way the sum in each group is 5, and the absolute difference is 0. In the second example there are only two integers, and since both groups should be non-empty, you have to put one integer in the first group and one in the second. This way the absolute difference of sums of integers in each group is 1. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n; int main() { cin >> n; vector<int> hi; if (n % 2 == 0 && n % 4 == 2) { cout << 1 << "\n"; for (int i = 1; i <= n; i++) if (i % 4 == 1 || i % 4 == 0) hi.push_back(i); cout << hi.size() << " "; for (int i = 0; i < hi.size(); i++) cout << hi[i] << " "; } else if (n % 2 == 0 && n % 4 == 0) { cout << 0 << "\n"; for (int i = 1; i <= n; i++) if (i % 4 == 1 || i % 4 == 0) hi.push_back(i); cout << hi.size() << " "; for (int i = 0; i < hi.size(); i++) cout << hi[i] << " "; } else if (n % 2 == 1 && n % 4 == 1) { cout << 1 << "\n"; hi.push_back(3); for (int i = 4; i <= n; i++) if (i % 4 == 1 || i % 4 == 2) hi.push_back(i); cout << hi.size() << " "; for (int i = 0; i < hi.size(); i++) cout << hi[i] << " "; } else { cout << 0 << "\n"; hi.push_back(1); hi.push_back(2); for (int i = 4; i <= n; i++) if (i % 4 == 1 || i % 4 == 2) hi.push_back(i); cout << hi.size() << " "; for (int i = 0; i < hi.size(); i++) cout << hi[i] << " "; } return 0; } ```
### Prompt Please formulate a cpp solution to the following problem: You are developing a robot that processes strings. When the robot is given a string t consisting of lowercase English letters, it processes the string by following the procedure below: 1. Let i be the smallest index such that t_i = t_{i + 1}. If such an index does not exist, terminate the procedure. 2. If t_i is `z`, remove t_i and t_{i + 1} from t. Otherwise, let c be the next letter of t_i in the English alphabet, and replace t_i and t_{i + 1} together with c, reducing the length of t by 1. 3. Go back to step 1. For example, when the robot is given the string `axxxxza`, it will be processed as follows: `axxxxza` β†’ `ayxxza` β†’ `ayyza` β†’ `azza` β†’ `aa` β†’ `b`. You are given a string s consisting of lowercase English letters. Answer Q queries. The i-th query is as follows: * Assume that the robot is given a substring of s that runs from the l_i-th character and up to the r_i-th character (inclusive). Will the string be empty after processing? Constraints * 1 ≀ |s| ≀ 5 Γ— 10^5 * s consists of lowercase English letters. * 1 ≀ Q ≀ 10^5 * 1 ≀ l_i ≀ r_i ≀ |s| Input The input is given from Standard Input in the following format: s Q l_1 r_1 l_2 r_2 : l_Q r_Q Output Print Q lines. The i-th line should contain the answer to the i-th query: `Yes` or `No`. Examples Input axxxxza 2 1 7 2 6 Output No Yes Input aabcdefghijklmnopqrstuvwxyz 1 1 27 Output Yes Input yzyyyzyzyyyz 8 1 6 7 12 1 12 6 11 1 1 1 3 4 9 3 8 Output Yes Yes Yes Yes No No No No ### Response ```cpp #include <cstdio> #include <cstring> using namespace std; const int N = 5e5 + 500; const int ALP = 26; int n, dp[N][ALP + 1], q; int par[N][ALP]; char s[N]; int main(){ scanf("%s", s); n = strlen(s); for(int i = 0;i <= ALP;i++) dp[n][i] = n + 1, dp[n + 1][i] = n + 1; dp[n][ALP] = n; for(int i = 0;i < ALP;i++){ par[n][i] = n; par[n + 1][i] = n + 1; } for(int i = n - 1;i >= 0;i--){ int k = s[i] - 'a'; dp[i][k] = i + 1; for(int j = k + 1;j <= ALP;j++){ dp[i][j] = dp[dp[i][j - 1]][j - 1]; } for(int j = 0;j < k;j++){ dp[i][j] = dp[dp[i][ALP]][j]; } par[i][0] = dp[i][ALP]; for(int j = 1;j < ALP;j++) par[i][j] = par[par[i][j - 1]][j - 1]; } scanf("%d", &q); for(int i = 0;i < q;i++){ int l, r; scanf("%d%d", &l, &r); l--, r--; for(int k = ALP - 1;k >= 0;k--){ if(par[l][k] <= r + 1) l = par[l][k]; } printf((l == r + 1) ? "Yes\n" : "No\n"); } } ```
### Prompt Please provide a cpp coded solution to the problem described below: Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a]. By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT. The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon? Input The single line of the input contains two integers a, b (1 ≀ a, b ≀ 107). Output Print a single integer representing the answer modulo 1 000 000 007 (109 + 7). Examples Input 1 1 Output 0 Input 2 2 Output 8 Note For the first sample, there are no nice integers because <image> is always zero. For the second sample, the set of nice integers is {3, 5}. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long MOD = 1e9 + 7; long long a, b, SUMA, SUMB; int main() { cin >> a >> b; SUMA = ((b * (b - 1LL)) / 2LL) % MOD; SUMA = (SUMA * a) % MOD; SUMB = (b * (b - 1LL)) / 2LL % MOD; SUMB = (b * SUMB) % MOD; SUMB = (SUMB * (((a * (a + 1LL)) / 2LL) % MOD) % MOD); cout << (SUMA + SUMB) % MOD; return 0; } ```
### Prompt Your task is to create a CPP solution to the following problem: The mayor of Amida, the City of Miracle, is not elected like any other city. Once exhausted by long political struggles and catastrophes, the city has decided to leave the fate of all candidates to the lottery in order to choose all candidates fairly and to make those born under the lucky star the mayor. I did. It is a lottery later called Amidakuji. The election is held as follows. The same number of long vertical lines as the number of candidates will be drawn, and some horizontal lines will be drawn there. Horizontal lines are drawn so as to connect the middle of adjacent vertical lines. Below one of the vertical lines is written "Winning". Which vertical line is the winner is hidden from the candidates. Each candidate selects one vertical line. Once all candidates have been selected, each candidate follows the line from top to bottom. However, if a horizontal line is found during the movement, it moves to the vertical line on the opposite side to which the horizontal line is connected, and then traces downward. When you reach the bottom of the vertical line, the person who says "winning" will be elected and become the next mayor. This method worked. Under the lucky mayor, a peaceful era with few conflicts and disasters continued. However, in recent years, due to population growth, the limits of this method have become apparent. As the number of candidates increased, the Amidakuji became large-scale, and manual tabulation took a lot of time. Therefore, the city asked you, the programmer of the city hall, to computerize the Midakuji. Your job is to write a program that finds the structure of the Amidakuji and which vertical line you will eventually reach given the position of the selected vertical line. The figure below shows the contents of the input and output given as a sample. <image> Input The input consists of multiple datasets. One dataset is given as follows. > n m a > Horizontal line 1 > Horizontal line 2 > Horizontal line 3 > ... > Horizontal line m > n, m, and a are integers that satisfy 2 <= n <= 100, 0 <= m <= 1000, 1 <= a <= n, respectively. Represents a number. The horizontal line data is given as follows. > h p q h, p, and q are integers that satisfy 1 <= h <= 1000, 1 <= p <q <= n, respectively, h is the height of the horizontal line, and p and q are connected to the horizontal line 2 Represents the number of the vertical line of the book. No two or more different horizontal lines are attached to the same height of one vertical line. At the end of the input, there is a line consisting of only three zeros separated by blanks. Output Output one line for each dataset, the number of the vertical line at the bottom of the vertical line a when traced from the top. Sample Input 4 4 1 3 1 2 2 2 3 3 3 4 1 3 4 0 0 0 Output for the Sample Input Four Example Input 4 4 1 3 1 2 2 2 3 3 3 4 1 3 4 0 0 0 Output 4 ### Response ```cpp #include<iostream> #include<algorithm> using namespace std; class Line{ public: int h,p,q; friend istream& operator>>(istream &in,Line &a){ in>>a.h>>a.p>>a.q; return in; } }; bool cmp(Line a,Line b){ return b.h<a.h; } int main(){ int n,m,a; Line line[1000]; while(cin>>n>>m>>a,n|m|a){ for(int i=0;i<m;i++)cin>>line[i]; sort(line,line+m,cmp); for(int i=0;i<m;i++){ if(line[i].p==a)a=line[i].q; else if(line[i].q==a)a=line[i].p; } cout<<a<<endl; } } ```
### Prompt Develop a solution in cpp to the problem described below: There are n athletes in front of you. Athletes are numbered from 1 to n from left to right. You know the strength of each athlete β€” the athlete number i has the strength s_i. You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team. You want the strongest athlete from the first team to differ as little as possible from the weakest athlete from the second team. Formally, you want to split the athletes into two teams A and B so that the value |max(A) - min(B)| is as small as possible, where max(A) is the maximum strength of an athlete from team A, and min(B) is the minimum strength of an athlete from team B. For example, if n=5 and the strength of the athletes is s=[3, 1, 2, 6, 4], then one of the possible split into teams is: * first team: A = [1, 2, 4], * second team: B = [3, 6]. In this case, the value |max(A) - min(B)| will be equal to |4-3|=1. This example illustrates one of the ways of optimal split into two teams. Print the minimum value |max(A) - min(B)|. Input The first line contains an integer t (1 ≀ t ≀ 1000) β€” the number of test cases in the input. Then t test cases follow. Each test case consists of two lines. The first line contains positive integer n (2 ≀ n ≀ 50) β€” number of athletes. The second line contains n positive integers s_1, s_2, …, s_n (1 ≀ s_i ≀ 1000), where s_i β€” is the strength of the i-th athlete. Please note that s values may not be distinct. Output For each test case print one integer β€” the minimum value of |max(A) - min(B)| with the optimal split of all athletes into two teams. Each of the athletes must be a member of exactly one of the two teams. Example Input 5 5 3 1 2 6 4 6 2 1 3 2 4 3 4 7 9 3 1 2 1 1000 3 100 150 200 Output 1 0 2 999 50 Note The first test case was explained in the statement. In the second test case, one of the optimal splits is A=[2, 1], B=[3, 2, 4, 3], so the answer is |2-2|=0. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long MOD = 1000000007; const long long INF = 1e15; using Graph = vector<vector<long long>>; signed main() { long long T; cin >> T; for (long long t = 0; t < T; t++) { long long N; cin >> N; vector<long long> A(N); for (long long i = 0; i < N; i++) cin >> A[i]; sort(A.begin(), A.end()); long long ans = 1000000; for (long long i = 1; i < N; i++) { ans = min(ans, A[i] - A[i - 1]); } cout << ans << endl; } } ```
### Prompt Construct a CPP code solution to the problem outlined: Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position". Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. Input The first line contains two non-negative numbers n and m (0 ≀ n ≀ 3Β·105, 0 ≀ m ≀ 3Β·105) β€” the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6Β·105. Each line consists only of letters 'a', 'b', 'c'. Output For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). Examples Input 2 3 aaaaa acacaca aabaa ccacacc caaac Output YES NO NO ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long inf = 1e9; const long long mod = 1e9 + 7; const double eps = 1e-8; const long long MAX = 1e7 + 20; template <class T> T gcd(T a, T b) { return (b != 0 ? gcd<T>(b, a % b) : a); } template <class T> T lcm(T a, T b) { return (a / gcd<T>(a, b) * b); } long long BM(long long B, long long P, long long M) { long long R = 1; while (P > 0) { if (P & 1) { R = (R * B) % M; } P /= 2; B = (B * B) % M; } return (long long)R; } long long MI(long long x, long long m) { return BM(x, m - 2, m); } struct data { bool endmark; int next[5]; data() { endmark = false; memset(next, -1, sizeof(next)); } } trie[600005]; int tot = 0, sz; string s; void add(string s) { int cur = 0; for (int i = 0; i < s.size(); i++) { int ch = s[i] - 'a'; if (trie[cur].next[ch] == -1) { trie[++tot] = data(); trie[cur].next[ch] = tot; } cur = trie[cur].next[ch]; } trie[cur].endmark = true; } bool findmatch(int pos, int cur, bool change) { if (pos == sz) { return (change and trie[cur].endmark); } bool ret = false; int now = s[pos] - 'a'; if (change) { if (trie[cur].next[now] == -1) return false; return findmatch(pos + 1, trie[cur].next[now], change); } else { for (int i = 0; i < 3; i++) { if (trie[cur].next[i] == -1) continue; ret |= findmatch(pos + 1, trie[cur].next[i], (i == now) ? 0 : 1); } } return ret; } int main() { trie[0] = data(); int n, m; cin >> n >> m; for (int i = 0; i < n; i++) { cin >> s; add(s); } while (m--) { cin >> s; sz = s.size(); if (findmatch(0, 0, 0)) cout << "YES\n"; else cout << "NO\n"; } return 0; } ```
### Prompt Please formulate a cpp solution to the following problem: We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≀ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≀ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v. It is expected that one of the vertices will be invaded by aliens from outer space. Snuke wants to immediately identify that vertex when the invasion happens. To do so, he has decided to install an antenna on some vertices. First, he decides the number of antennas, K (1 ≀ K ≀ N). Then, he chooses K different vertices, x_0, x_1, ..., x_{K - 1}, on which he installs Antenna 0, 1, ..., K - 1, respectively. If Vertex v is invaded by aliens, Antenna k (0 ≀ k < K) will output the distance d(x_k, v). Based on these K outputs, Snuke will identify the vertex that is invaded. Thus, in order to identify the invaded vertex no matter which one is invaded, the following condition must hold: * For each vertex u (0 ≀ u < N), consider the vector (d(x_0, u), ..., d(x_{K - 1}, u)). These N vectors are distinct. Find the minumum value of K, the number of antennas, when the condition is satisfied. Constraints * 2 ≀ N ≀ 10^5 * 0 ≀ a_i, b_i < N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_0 b_0 a_1 b_1 : a_{N - 2} b_{N - 2} Output Print the minumum value of K, the number of antennas, when the condition is satisfied. Examples Input 5 0 1 0 2 0 3 3 4 Output 2 Input 2 0 1 Output 1 Input 10 2 8 6 0 4 1 7 6 2 3 8 6 6 9 2 4 5 8 Output 3 ### Response ```cpp #include<bits/stdc++.h> using namespace std; int n,doe,root; int pre[202020],son[202020],now[101010],du[101010]; int g[101010],size[101010]; bool br[101010]; void add(int x,int y) { ++x; ++y; ++doe; pre[doe]=now[x]; now[x]=doe; son[doe]=y; } void dfs(int x,int fa) { int p=now[x]; br[x]=1; if (du[x]==1) { g[x]=1; return; } int dog=0; while (p) { int y=son[p]; if (y!=fa) { dfs(y,x); g[x]+=g[y]; if (br[y]) dog=max(dog,g[y]); br[x]&=br[y]; } p=pre[p]; } if (du[x]>2) br[x]=0,g[x]-=dog; } int main() { scanf("%d",&n); int x,y; for (int i=1;i<n;++i) scanf("%d%d",&x,&y),add(x,y),add(y,x),++du[x+1],++du[y+1]; for (int i=1;i<=n;++i) if (du[i]>2) root=i; if (!root) { printf("1\n"); return 0; } int p=now[root]; int dog=0; // printf("%d\n",root); while (p) { y=son[p]; dfs(y,root); g[root]+=g[y]; if (br[y]) dog=max(dog,g[y]); p=pre[p]; } // for (int i=1;i<=n;++i) printf("%d ",g[i]); // printf("\n"); printf("%d\n",g[root]-dog); return 0; } ```
### Prompt Develop a solution in CPP to the problem described below: Pushok the dog has been chasing Imp for a few hours already. <image> Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner. While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of string "sh" as a subsequence in it, in other words, the number of such pairs (i, j), that i < j and <image> and <image>. The robot is off at the moment. Imp knows that it has a sequence of strings ti in its memory, and he can arbitrary change their order. When the robot is started, it generates the string t as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation. Help Imp to find the maximum noise he can achieve by changing the order of the strings. Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of strings in robot's memory. Next n lines contain the strings t1, t2, ..., tn, one per line. It is guaranteed that the strings are non-empty, contain only English letters 's' and 'h' and their total length does not exceed 105. Output Print a single integer β€” the maxumum possible noise Imp can achieve by changing the order of the strings. Examples Input 4 ssh hs s hhhs Output 18 Input 2 h s Output 1 Note The optimal concatenation in the first sample is ssshhshhhs. ### Response ```cpp #include <bits/stdc++.h> using namespace std; bool compare1(pair<long long int, int> p1, pair<long long int, long long int> p2) { if ((p1.first * p2.second) == (p2.first * p1.second)) { return (p1.first > p2.first); } return (p1.first * p2.second) > (p2.first * p1.second); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long int n; cin >> n; string str; vector<pair<long long int, long long int>> vec; long long int ctrs, ctrh; long long int sum = 0; for (long long int i = 0; i < n; i++) { cin >> str; ctrs = 0; ctrh = 0; for (long long int j = 0; j < str.size(); j++) { if (str[j] == 's') { ctrs++; } else { ctrh++; sum += ctrs; } } vec.push_back(make_pair(ctrs, ctrh)); } sort(vec.begin(), vec.end(), compare1); long long int s_sum = vec[0].first; for (int long long i = 1; i < n; i++) { sum = sum + s_sum * vec[i].second; s_sum += vec[i].first; } cout << sum << '\n'; return 0; } ```
### Prompt Your challenge is to write a CPP solution to the following problem: You are given an array a consisting of n integer numbers. You have to color this array in k colors in such a way that: * Each element of the array should be colored in some color; * For each i from 1 to k there should be at least one element colored in the i-th color in the array; * For each i from 1 to k all elements colored in the i-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers c_1, c_2, ... c_n, where 1 ≀ c_i ≀ k and c_i is the color of the i-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any. Input The first line of the input contains two integers n and k (1 ≀ k ≀ n ≀ 5000) β€” the length of the array a and the number of colors, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 5000) β€” elements of the array a. Output If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers c_1, c_2, ... c_n, where 1 ≀ c_i ≀ k and c_i is the color of the i-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any. Examples Input 4 2 1 2 2 3 Output YES 1 1 2 2 Input 5 2 3 2 1 2 3 Output YES 2 1 1 2 1 Input 5 2 2 1 1 2 1 Output NO Note In the first example the answer 2~ 1~ 2~ 1 is also acceptable. In the second example the answer 1~ 1~ 1~ 2~ 2 is also acceptable. There exist other acceptable answers for both examples. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, k; int main() { int n, k; while (cin >> n >> k) { vector<int> V[5005]; for (int i = 1; i <= n; i++) { int tmp; cin >> tmp; V[tmp].push_back(i); } int mx = 0; for (int i = 1; i <= 5000; i++) { mx = mx > V[i].size() ? mx : V[i].size(); } if (mx > k || n < k) { cout << "NO" << endl; continue; } else { queue<int> Q; int tmp = 1; while (Q.size() < n) { for (int i = 0; i < V[tmp].size(); i++) { Q.push(V[tmp][i]); } tmp++; } int ans[5005]; int f = 0; while (Q.empty() == 0) { int t = Q.front(); Q.pop(); ans[t] = ++f; if (f == k) f = 0; } for (int i = tmp; i <= 5000; i++) { for (int j = 0; j < V[i].size(); j++) { ans[V[i][j]] = j + 1; } } cout << "YES" << endl; for (int i = 1; i <= n; i++) { cout << ans[i] << " "; } cout << endl; } } } ```
### Prompt Your challenge is to write a Cpp solution to the following problem: Let's call an integer array a_1, a_2, ..., a_n good if a_i β‰  i for each i. Let F(a) be the number of pairs (i, j) (1 ≀ i < j ≀ n) such that a_i + a_j = i + j. Let's say that an array a_1, a_2, ..., a_n is excellent if: * a is good; * l ≀ a_i ≀ r for each i; * F(a) is the maximum possible among all good arrays of size n. Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first and only line of each test case contains three integers n, l, and r (2 ≀ n ≀ 2 β‹… 10^5; -10^9 ≀ l ≀ 1; n ≀ r ≀ 10^9). It's guaranteed that the sum of n doesn't exceed 2 β‹… 10^5. Output For each test case, print the number of excellent arrays modulo 10^9 + 7. Example Input 4 3 0 3 4 -3 5 42 -33 55 69 -42 146 Output 4 10 143922563 698570404 Note In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are: 1. [2, 1, 2]; 2. [0, 3, 2]; 3. [2, 3, 2]; 4. [3, 0, 1]. ### Response ```cpp #include <string.h> #include <stdio.h> #include <math.h> #include <map> #include <queue> #include <vector> #include <numeric> #include <iostream> #include <algorithm> using namespace std; typedef unsigned long long ll; typedef pair<int, int> pi; typedef vector<int> vi; #define mp make_pair #define pb push_back #define F first #define S second #define ab(x) (((x)<0)?-(x):(x)) #define MOD 1000000007 class nCrModular { public: ll mod; vector<ll> fac; nCrModular(int n, ll _mod) { mod = _mod; fac.resize(n + 1); fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = (fac[i - 1] * i) % mod; } ll pow(ll x, ll y) { ll r = 1; for (x = x % mod; y; y >>= 1, x = (x * x) % mod) if (y & 1) r = (r * x) % mod; return r; } ll inv(ll x) { return pow(x, mod - 2); } ll nCr(ll n, ll r) { if (n < r) return 0; if (r == 0) return 1; return ((fac[n] * inv(fac[r]) % mod) * inv(fac[n - r])) % mod; } } ncr(200000, MOD); void solve() { int n, s, e; cin >> n >> s >> e; int k = min(min(ab(s - 1), ab(e - 1)), min(ab(s - n), ab(e - n))); int L = 1, R = n, m1 = n / 2, m2 = (n + 1) / 2; ll r = 0; for (int i = 0; i <= m2 - m1; i++) { int need = m1 + i; r = (r + ncr.nCr(n, need) * k) % MOD; } for (k = k + 1;; k++) { if (!(s - L <= -k && k <= e - L)) L++; if (!(s - R <= -k && k <= e - R)) R--; if (R - L + 1 < 0) break; int plus = L - 1; int minus = n - R; if (plus > m2 || minus > m2) break; for (int i = 0; i <= m2 - m1; i++) { int need = m1 + i - plus; r = (r + ncr.nCr(R - L + 1, need)) % MOD; } } cout << r << endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int test_case; cin >> test_case; while (test_case--) solve(); } ```
### Prompt Generate a cpp solution to the following problem: You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n. For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10. Input The first line contains an integer t (1 ≀ t ≀ 1000) β€” the number of test cases in the input. Next, t test cases are given, one per line. Each test case is two positive integers n (2 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 10^9). Output For each test case print the k-th positive integer that is not divisible by n. Example Input 6 3 7 4 12 2 1000000000 7 97 1000000000 1000000000 2 1 Output 10 15 1999999999 113 1000000001 1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long f(long long x, long long n) { return x - (x / n); } long long solve(long long n, long long k) { long long L = 1; long long R = 1e10; while (L < R) { long long M = L + (R - L) / 2; if (f(M, n) < k) L = M + 1; else R = M; } return L; } int main() { long long k, n, t; cin >> t; while (t--) { cin >> n >> k; cout << solve(n, k) << "\n"; } return 0; } ```
### Prompt Your challenge is to write a cpp solution to the following problem: Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions: * After the cutting each ribbon piece should have length a, b or c. * After the cutting the number of ribbon pieces should be maximum. Help Polycarpus and find the number of ribbon pieces after the required cutting. Input The first line contains four space-separated integers n, a, b and c (1 ≀ n, a, b, c ≀ 4000) β€” the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide. Output Print a single number β€” the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists. Examples Input 5 5 3 2 Output 2 Input 7 5 5 2 Output 2 Note In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3. In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long M = 1e9 + 7; int main() { ios::sync_with_stdio(false); cin.tie(0); cerr.tie(0); int a, b, c, n, dp[4001]; cin >> n >> a >> b >> c; for (int i = 1; i <= n; i++) { dp[i] = 0; if (a == i || b == i || c == i) dp[i] = 1; for (int j = 1; j <= i / 2; j++) { if (dp[j] != 0 && dp[i - j] != 0) dp[i] = max(dp[i], (dp[j] + dp[i - j])); } } cout << dp[n]; return 0; } ```
### Prompt Create a solution in CPP for the following problem: Description THE BY DOLM @ STER is a training simulation game scheduled to be released on EXIDNA by 1rem on April 1, 2010. For the time being, it probably has nothing to do with an arcade game where the network connection service stopped earlier this month. This game is a game in which members of the unit (formation) to be produced are selected from the bidders, and through lessons and communication with the members, they (they) are raised to the top of the bidders, the top biddles. Each bidle has three parameters, vocal, dance, and looks, and the unit's ability score is the sum of all the parameters of the biddles that belong to the unit. The highest of the three stats of a unit is the rank of the unit. There is no limit to the number of people in a unit, and you can work as a unit with one, three, or 100 members. Of course, you can hire more than one of the same bidle, but hiring a bidle is expensive and must be taken into account. As a producer, you decided to write and calculate a program to make the best unit. Input The input consists of multiple test cases. The first line of each test case is given the number N of bid dollars and the available cost M. (1 <= N, M <= 300) The next 2 * N lines contain information about each bidle. The name of the bidle is on the first line of the bidle information. Biddle names consist of alphabets and spaces, with 30 characters or less. Also, there is no bidle with the same name. The second line is given the integers C, V, D, L. C is the cost of hiring one Biddle, V is the vocal, D is the dance, and L is the stat of the looks. (1 <= C, V, D, L <= 300) Input ends with EOF. Output Answer the maximum rank of units that can be made within the given cost. If you cannot make a unit, output 0. Example Input 3 10 Dobkeradops 7 5 23 10 PataPata 1 1 2 1 dop 5 3 11 14 2 300 Bydo System Alpha 7 11 4 7 Green Inferno 300 300 300 300 Output 29 462 ### Response ```cpp #include <iostream> #include <cstring> using namespace std; int n,m; int c[301],v[301],d[301],l[301]; int dp[301][301]; int solve(int idx,int rem,int *t){ if(idx == n) return 0; if(dp[idx][rem] != -1) return dp[idx][rem]; int res = 0; for(int i=0;i*c[idx]<=rem;i++){ res = max(res,i*t[idx]+solve(idx+1,rem-i*c[idx],t)); } return dp[idx][rem]=res; } int main(void){ while(cin>>n>>m){ for(int i=0;i<n;i++){ char ch = getchar(); while((ch=getchar()) != '\n'); cin>>c[i]>>v[i]>>d[i]>>l[i]; } int ans = 0; memset(dp,-1,sizeof(dp)); ans = max(ans,solve(0,m,v)); memset(dp,-1,sizeof(dp)); ans = max(ans,solve(0,m,d)); memset(dp,-1,sizeof(dp)); ans = max(ans,solve(0,m,l)); cout<<ans<<endl; } return 0; } ```
### Prompt Please create a solution in CPP to the following problem: Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences of days 0, 010, 01010 are zebras, while sequences 1, 0110, 0101 are not. Oleg tells you the story of days he lived in chronological order in form of string consisting of 0 and 1. Now you are interested if it is possible to divide Oleg's life history into several subsequences, each of which is a zebra, and the way it can be done. Each day must belong to exactly one of the subsequences. For each of the subsequences, days forming it must be ordered chronologically. Note that subsequence does not have to be a group of consecutive days. Input In the only line of input data there is a non-empty string s consisting of characters 0 and 1, which describes the history of Oleg's life. Its length (denoted as |s|) does not exceed 200 000 characters. Output If there is a way to divide history into zebra subsequences, in the first line of output you should print an integer k (1 ≀ k ≀ |s|), the resulting number of subsequences. In the i-th of following k lines first print the integer li (1 ≀ li ≀ |s|), which is the length of the i-th subsequence, and then li indices of days forming the subsequence. Indices must follow in ascending order. Days are numbered starting from 1. Each index from 1 to n must belong to exactly one subsequence. If there is no way to divide day history into zebra subsequences, print -1. Subsequences may be printed in any order. If there are several solutions, you may print any of them. You do not have to minimize nor maximize the value of k. Examples Input 0010100 Output 3 3 1 3 4 3 2 5 6 1 7 Input 111 Output -1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, tms, st[200005], st_[200005], lst[200005], t, tt, k, i; char S[200005]; bool vis[200005]; int main() { scanf("%s", S + 1); n = strlen(S + 1); for (i = 1; i <= n; i++) if (S[i] == '1') { if (!t) return puts("-1"), 0; lst[i] = st[--t]; st_[tt++] = i; } else { if (tt) lst[i] = st_[--tt]; st[t++] = i; } if (tt) return puts("-1"), 0; printf("%d\n", t); while (t--) { for (i = st[t], k = 0; i; k++, i = lst[i]) ; printf("%d", k); tt = 0; for (int i = st[t]; i; i = lst[i]) { st_[tt++] = i; } for (int i = tt - 1; i >= 0; i--) printf(" %d", st_[i]); puts(""); } } ```
### Prompt In CPP, your task is to solve the following problem: We get more and more news about DDoS-attacks of popular websites. Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds 100 β‹… t, where t β€” the number of seconds in this time segment. Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence r_1, r_2, ..., r_n, where r_i β€” the number of requests in the i-th second after boot. Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment [1, n]. Input The first line contains n (1 ≀ n ≀ 5000) β€” number of seconds since server has been booted. The second line contains sequence of integers r_1, r_2, ..., r_n (0 ≀ r_i ≀ 5000), r_i β€” number of requests in the i-th second. Output Print the only integer number β€” the length of the longest time period which is considered to be a DDoS-attack by Arseny. If it doesn't exist print 0. Examples Input 5 100 200 1 1 1 Output 3 Input 5 1 2 3 4 5 Output 0 Input 2 101 99 Output 1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; #pragma GCC optimize("O3") #pragma GCC target("sse4") const double PI = acos(-1.0); const long long INF = 1e9 + 47; const long long LINF = INF * INF; int a[1 << 20]; int p[1 << 20]; int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); int n; cin >> n; for (int i = (0); i < (n); ++i) cin >> a[i]; p[0] = a[0]; for (int i = (1); i < (n); ++i) p[i] = p[i - 1] + a[i]; int ans = 0; for (int l = (0); l < (n); ++l) for (int len = (1); len < (n - l + 1); ++len) { int tut = p[len + l - 1]; if (l) tut -= p[l - 1]; if (tut > 100 * len) ans = max(ans, len); } cout << ans << endl; cerr << "Time elapsed : " << clock() / (double)CLOCKS_PER_SEC << endl; return 0; } ```
### Prompt Develop a solution in cpp to the problem described below: Write a program which prints $n$-th fibonacci number for a given integer $n$. The $n$-th fibonacci number is defined by the following recursive formula: \begin{equation*} fib(n)= \left \\{ \begin{array}{ll} 1 & (n = 0) \\\ 1 & (n = 1) \\\ fib(n - 1) + fib(n - 2) & \\\ \end{array} \right. \end{equation*} Constraints * $0 \leq n \leq 44$ Input An integer $n$ is given. Example Input 3 Output 3 ### Response ```cpp #include<bits/stdc++.h> using namespace std; int main(){ int f[45],n; cin>>n; f[0]=1;f[1]=1; for(int i=2;i<45;i++){ f[i]=f[i-1]+f[i-2]; } cout<<f[n]<<endl; return 0; } ```
### Prompt Develop a solution in Cpp to the problem described below: You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges. The i-th (1≀i≀M) edge connects vertex a_i and vertex b_i with a distance of c_i. Here, a self-loop is an edge where a_i = b_i (1≀i≀M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≀i<j≀M). A connected graph is a graph where there is a path between every pair of different vertices. Find the number of the edges that are not contained in any shortest path between any pair of different vertices. Constraints * 2≀N≀100 * N-1≀M≀min(N(N-1)/2,1000) * 1≀a_i,b_i≀N * 1≀c_i≀1000 * c_i is an integer. * The given graph contains neither self-loops nor double edges. * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Output Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices. Examples Input 3 3 1 2 1 1 3 1 2 3 3 Output 1 Input 3 2 1 2 1 2 3 1 Output 0 ### Response ```cpp #include <bits/stdc++.h> using namespace std; typedef long long ll; ll e[1005][1005]; ll d[1005][1005]; ll n,m; ll a[1005],b[1005],c; ll ans; int main(void){ cin>>n>>m; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ d[i][j]=1000000000; } } for(int i=0;i<m;i++){ cin>>a[i]>>b[i]>>c; e[a[i]-1][b[i]-1]=c; e[b[i]-1][a[i]-1]=c; d[a[i]-1][b[i]-1]=c; d[b[i]-1][a[i]-1]=c; } for(int k=0;k<n;k++){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ d[i][j]=min(d[i][j],d[i][k]+d[k][j]); } } } for(int i=0;i<m;i++){ if(d[a[i]-1][b[i]-1]<e[a[i]-1][b[i]-1]){ ans++; } } cout<<ans<<endl; } ```
### Prompt Please formulate a cpp solution to the following problem: For a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that βˆ‘_{i=1}^{n}{βˆ‘_{j=i}^{n}{(a_j)/(j)}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for example, 5/2=2.5. Input The first line contains a single integer t β€” the number of test cases (1 ≀ t ≀ 100). The test cases follow, each in two lines. The first line of a test case contains two integers n and m (1 ≀ n ≀ 100, 0 ≀ m ≀ 10^6). The second line contains integers a_1, a_2, …, a_n (0 ≀ a_i ≀ 10^6) β€” the elements of the array. Output For each test case print "YES", if it is possible to reorder the elements of the array in such a way that the given formula gives the given value, and "NO" otherwise. Example Input 2 3 8 2 5 1 4 4 0 1 2 3 Output YES NO Note In the first test case one of the reorders could be [1, 2, 5]. The sum is equal to (1/1 + 2/2 + 5/3) + (2/2 + 5/3) + (5/3) = 8. The brackets denote the inner sum βˆ‘_{j=i}^{n}{(a_j)/(j)}, while the summation of brackets corresponds to the sum over i. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; template <class T> inline void read(T &res) { char c; T flag = 1; while ((c = getchar()) < '0' || c > '9') if (c == '-') flag = -1; res = c - '0'; while ((c = getchar()) >= '0' && c <= '9') res = res * 10 + c - '0'; res *= flag; } const int maxn = 2e5 + 7; int n, t, m; int main() { read(t); while (t--) { read(n); read(m); int sum = 0; for (int i = 1; i <= n; ++i) { int x; read(x); sum += x; } printf("%s\n", m == sum ? "YES" : "NO"); } return 0; } ```
### Prompt Please provide a Cpp coded solution to the problem described below: Recently Max has got himself into popular CCG "BrainStone". As "BrainStone" is a pretty intellectual game, Max has to solve numerous hard problems during the gameplay. Here is one of them: Max owns n creatures, i-th of them can be described with two numbers β€” its health hpi and its damage dmgi. Max also has two types of spells in stock: 1. Doubles health of the creature (hpi := hpiΒ·2); 2. Assigns value of health of the creature to its damage (dmgi := hpi). Spell of first type can be used no more than a times in total, of the second type β€” no more than b times in total. Spell can be used on a certain creature multiple times. Spells can be used in arbitrary order. It isn't necessary to use all the spells. Max is really busy preparing for his final exams, so he asks you to determine what is the maximal total damage of all creatures he can achieve if he uses spells in most optimal way. Input The first line contains three integers n, a, b (1 ≀ n ≀ 2Β·105, 0 ≀ a ≀ 20, 0 ≀ b ≀ 2Β·105) β€” the number of creatures, spells of the first type and spells of the second type, respectively. The i-th of the next n lines contain two number hpi and dmgi (1 ≀ hpi, dmgi ≀ 109) β€” description of the i-th creature. Output Print single integer β€” maximum total damage creatures can deal. Examples Input 2 1 1 10 15 6 1 Output 27 Input 3 0 3 10 8 7 11 5 2 Output 26 Note In the first example Max should use the spell of the first type on the second creature, then the spell of the second type on the same creature. Then total damage will be equal to 15 + 6Β·2 = 27. In the second example Max should use the spell of the second type on the first creature, then the spell of the second type on the third creature. Total damage will be equal to 10 + 11 + 5 = 26. ### Response ```cpp #include <bits/stdc++.h> const int N = 2e5 + 5; long long hp[N], dmg[N], c[N]; int a, b, n, p[N]; bool cmp(int x, int y) { return hp[x] - dmg[x] > hp[y] - dmg[y]; } int main() { scanf("%d%d%d", &n, &a, &b); long long ans = 0; for (int i = 1; i <= n; ++i) scanf("%lld%lld", hp + i, dmg + i), p[i] = i; long long now = 1LL << a; std::sort(p + 1, p + 1 + n, cmp); for (int i = 1; i <= n; i++) if (i <= b) ans += std::max(hp[p[i]], dmg[p[i]]); else ans += dmg[p[i]]; long long sum = ans; for (int i = 1; i <= n; i++) { long long res = sum; int j = p[i]; if (i <= b) { res -= std::max(hp[j], dmg[j]); res += std::max(hp[j] * now, dmg[j]); ans = std::max(ans, res); } else { res -= std::max(hp[p[b]], dmg[p[b]]) - dmg[p[b]] + dmg[j]; res += std::max(dmg[j], hp[j] * now); ans = std::max(ans, res); } } if (!b) ans = sum; printf("%lld\n", ans); return 0; } ```
### Prompt Your task is to create a CPP solution to the following problem: A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable. Constraints * 1 ≀ |V| ≀ 10,000 * 0 ≀ |E| ≀ 30,000 * 1 ≀ Q ≀ 100,000 Input A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v. |V| |E| s0 t0 s1 t1 : s|E|-1 t|E|-1 Q u0 v0 u1 v1 : uQ-1 vQ-1 |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target nodes of i-th edge (directed). ui and vi represent a pair of nodes given as the i-th query. Output For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise. Example Input 5 6 0 1 1 0 1 2 2 4 4 3 3 2 4 0 1 0 3 2 3 3 4 Output 1 0 1 1 ### Response ```cpp #include<iostream> #include<string> #include<algorithm> #include<vector> #include<iomanip> #include<math.h> #include<complex> #include<queue> #include<deque> #include<map> #include<set> #include<bitset> using namespace std; #define REP(i,m,n) for(int i=(int)m ; i < (int) n ; i++ ) #define rep(i,n) REP(i,0,n) typedef long long ll; typedef pair<int,int> pint; const int inf=1e9+7; const ll longinf=1LL<<60 ; const ll mod=1e9+7 ; int dx[4]={1,0,-1,0} , dy[4]={0,1,0,-1} ; int n,m,used[101010],cmp[101010]; vector<int> v[101010],rv[101010],vs; void dfs(int x){ used[x]=true; for(auto to:v[x])if(!used[to])dfs(to); vs.push_back(x); } void rdfs(int x,int k){ used[x]=true; cmp[x]=k; for(auto to:rv[x])if(!used[to])rdfs(to,k); } int scc(){ rep(i,n)if(!used[i])dfs(i); rep(i,n)used[i]=0; reverse(vs.begin(),vs.end()); int k=0; for(auto x:vs)if(!used[x])rdfs(x,k++); return k; } int main(){ cin>>n>>m; rep(i,m){ int s,t; cin>>s>>t; v[s].push_back(t); rv[t].push_back(s); } scc(); int q; cin>>q; rep(i,q){ int s,t; cin>>s>>t; cout<<(cmp[s]==cmp[t])<<endl; } return 0; } ```
### Prompt Your task is to create a cpp solution to the following problem: Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≀ i ≀ m). You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i β‰₯ 1 Ai = p(Ai - 1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k. Input The first line contains two integers n and k (2 ≀ n ≀ 200000, 1 ≀ k ≀ 1018). n is the size of array A0. The second line contains n integers A00, A01... A0n - 1 β€” the elements of A0 (0 ≀ A0i ≀ 109). At least two elements of A0 are positive. Output Print the minimum i such that Ai contains a number which is larger or equal than k. Examples Input 2 2 1 1 Output 1 Input 3 6 1 1 1 Output 2 Input 3 1 1 0 1 Output 0 ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <class T> using v2d = vector<vector<T> >; template <class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; } template <class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; } mt19937 rng(chrono::system_clock::now().time_since_epoch().count()); const int maxN = 2e5 + 10; const long long inf = 1e18; int n; long long k, a[maxN]; bool check(long long d) { long long c = 1, x = d - 1, y = 0, sum = 0; bool ovf = 0; for (int i = n; i; i--) { if (a[i] > 0 && (ovf || (long double)sum + (long double)c * a[i] > inf)) { return 1; } if (a[i] > 0) { sum += c * a[i]; } if (sum >= k) { return 1; } x++; y++; if ((long double)c * x / y > inf) { ovf = 1; } else { __int128 tmp = c; tmp *= x; tmp /= y; c = tmp; } } return sum >= k; } void solve() { cin >> n >> k; for (int i = 1; i <= (int)(n); ++i) { cin >> a[i]; } if (*max_element(a + 1, a + n + 1) >= k) { cout << 0; return; } long long l = 0, r = inf; while (r - l > 1) { long long mid = (l + r) / 2; if (check(mid)) { r = mid; } else { l = mid; } } cout << r; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int T = 1; while (T--) { solve(); } return 0; } ```
### Prompt Develop a solution in CPP to the problem described below: You have two variables a and b. Consider the following sequence of actions performed with these variables: 1. If a = 0 or b = 0, end the process. Otherwise, go to step 2; 2. If a β‰₯ 2Β·b, then set the value of a to a - 2Β·b, and repeat step 1. Otherwise, go to step 3; 3. If b β‰₯ 2Β·a, then set the value of b to b - 2Β·a, and repeat step 1. Otherwise, end the process. Initially the values of a and b are positive integers, and so the process will be finite. You have to determine the values of a and b after the process ends. Input The only line of the input contains two integers n and m (1 ≀ n, m ≀ 1018). n is the initial value of variable a, and m is the initial value of variable b. Output Print two integers β€” the values of a and b after the end of the process. Examples Input 12 5 Output 0 1 Input 31 12 Output 7 12 Note Explanations to the samples: 1. a = 12, b = 5 <image> a = 2, b = 5 <image> a = 2, b = 1 <image> a = 0, b = 1; 2. a = 31, b = 12 <image> a = 7, b = 12. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int guga[101][101]; int saba = 101; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); long long a, b; cin >> a >> b; while (a > 0 && b > 0) { if (a >= 2 * b) { a = a % (2 * b); continue; } if (b >= 2 * a) { b = b % (2 * a); continue; } else break; } cout << a << ' ' << b; return 0; } ```
### Prompt In Cpp, your task is to solve the following problem: Your task is to shuffle a deck of n cards, each of which is marked by a alphabetical letter. A single shuffle action takes out h cards from the bottom of the deck and moves them to the top of the deck. The deck of cards is represented by a string as follows. abcdeefab The first character and the last character correspond to the card located at the bottom of the deck and the card on the top of the deck respectively. For example, a shuffle with h = 4 to the above deck, moves the first 4 characters "abcd" to the end of the remaining characters "eefab", and generates the following deck: eefababcd You can repeat such shuffle operations. Write a program which reads a deck (a string) and a sequence of h, and prints the final state (a string). Constraints * The length of the string ≀ 200 * 1 ≀ m ≀ 100 * 1 ≀ hi < The length of the string * The number of datasets ≀ 10 Input The input consists of multiple datasets. Each dataset is given in the following format: A string which represents a deck The number of shuffle m h1 h2 . . hm The input ends with a single character '-' for the string. Output For each dataset, print a string which represents the final state in a line. Example Input aabc 3 1 2 1 vwxyz 2 3 4 - Output aabc xyzvw ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main(){ string str; cin>>str; int m,b; while(str!="-"){ cin>>m; int sum=0; for(int i=0;i<m;i++){ cin>>b; sum+=b; } sum%=str.size(); str=str.substr(sum,str.size()-sum)+str.substr(0,sum); cout<<str<<endl; cin>>str; } 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> using namespace std; int gcd(int a, int b) { if (b == 0) return a; a %= b; return gcd(b, a); } bool PALIN(string s) { long long int i = 0; long long int j = s.length() - 1; while (i <= j) { if (s[i] != s[j]) return false; j--; i++; } return true; } int main(void) { cin.tie(NULL); cout.tie(NULL); ios_base::sync_with_stdio(false); long long int t = 1; cin >> t; while (t--) { long long int n, x = 0; cin >> n; for (long long int i = 2; i * i <= n; i++) { if (n % i == 0) { x = i; break; } } if (x == 0) { x = n; } cout << n / x << " " << n - (n / x) << "\n"; } } ```
### Prompt Construct a CPP code solution to the problem outlined: Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has n buses and m trolleys, the buses are numbered by integers from 1 to n, the trolleys are numbered by integers from 1 to m. Public transport is not free. There are 4 types of tickets: 1. A ticket for one ride on some bus or trolley. It costs c1 burles; 2. A ticket for an unlimited number of rides on some bus or on some trolley. It costs c2 burles; 3. A ticket for an unlimited number of rides on all buses or all trolleys. It costs c3 burles; 4. A ticket for an unlimited number of rides on all buses and trolleys. It costs c4 burles. Vasya knows for sure the number of rides he is going to make and the transport he is going to use. He asked you for help to find the minimum sum of burles he will have to spend on the tickets. Input The first line contains four integers c1, c2, c3, c4 (1 ≀ c1, c2, c3, c4 ≀ 1000) β€” the costs of the tickets. The second line contains two integers n and m (1 ≀ n, m ≀ 1000) β€” the number of buses and trolleys Vasya is going to use. The third line contains n integers ai (0 ≀ ai ≀ 1000) β€” the number of times Vasya is going to use the bus number i. The fourth line contains m integers bi (0 ≀ bi ≀ 1000) β€” the number of times Vasya is going to use the trolley number i. Output Print a single number β€” the minimum sum of burles Vasya will have to spend on the tickets. Examples Input 1 3 7 19 2 3 2 5 4 4 4 Output 12 Input 4 3 2 1 1 3 798 1 2 3 Output 1 Input 100 100 8 100 3 5 7 94 12 100 1 47 0 42 Output 16 Note In the first sample the profitable strategy is to buy two tickets of the first type (for the first bus), one ticket of the second type (for the second bus) and one ticket of the third type (for all trolleys). It totals to (2Β·1) + 3 + 7 = 12 burles. In the second sample the profitable strategy is to buy one ticket of the fourth type. In the third sample the profitable strategy is to buy two tickets of the third type: for all buses and for all trolleys. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int c1, c2, c3, c4, n, m, i, x, y; scanf("%d", &c1); scanf("%d", &c2); scanf("%d", &c3); scanf("%d", &c4); scanf("%d", &n); scanf("%d", &m); int b1[n + 1]; int s1[m + 1]; for (i = 1; i <= n; i++) scanf("%d", &b1[i]); for (i = 1; i <= m; i++) scanf("%d", &s1[i]); int sum1 = 0, sum2 = 0, sum = 0; for (i = 1; i <= n; i++) { x = b1[i] * c1; y = c2; if (x >= y) sum1 += y; else sum1 += x; } if (sum1 >= c3) sum1 = c3; for (i = 1; i <= m; i++) { x = s1[i] * c1; y = c2; if (x >= y) sum2 += y; else sum2 += x; } if (sum2 >= c3) sum2 = c3; sum = sum1 + sum2; if (sum >= c4) sum = c4; printf("%d\n", sum); return 0; } ```
### Prompt Construct a Cpp code solution to the problem outlined: As Gerald sets the table, Alexander sends the greeting cards, and Sergey and his twins create an army of clone snowmen, Gennady writes a New Year contest. The New Year contest begins at 18:00 (6.00 P.M.) on December 31 and ends at 6:00 (6.00 A.M.) on January 1. There are n problems for the contest. The penalty time for each solved problem is set as the distance from the moment of solution submission to the New Year in minutes. For example, the problem submitted at 21:00 (9.00 P.M.) gets penalty time 180, as well as the problem submitted at 3:00 (3.00 A.M.). The total penalty time is calculated as the sum of penalty time for all solved problems. It is allowed to submit a problem exactly at the end of the contest, at 6:00 (6.00 A.M.). Gennady opened the problems exactly at 18:00 (6.00 P.M.) and managed to estimate their complexity during the first 10 minutes of the contest. He believes that writing a solution for the i-th problem will take ai minutes. Gennady can submit a solution for evaluation at any time after he completes writing it. Probably he will have to distract from writing some solution to send the solutions of other problems for evaluation. The time needed to send the solutions can be neglected, i.e. this time can be considered to equal zero. Gennady can simultaneously submit multiple solutions. Besides, he can move at any time from writing one problem to another, and then return to the first problem from the very same place, where he has left it. Thus the total solution writing time of the i-th problem always equals ai minutes. Of course, Gennady does not commit wrong attempts, and his solutions are always correct and are accepted from the first attempt. He can begin to write the solutions starting from 18:10 (6.10 P.M.). Help Gennady choose from the strategies that help him solve the maximum possible number of problems, the one with which his total penalty time will be minimum. Input The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of the problems. The next line contains n space-separated integers ai (1 ≀ ai ≀ 720) β€” each number shows how much time in minutes Gennady will spend writing a solution to the problem. Output Print two integers β€” the number of problems Gennady will solve and the total penalty time considering that he chooses the optimal strategy. Examples Input 3 30 330 720 Output 2 10 Note In the sample, one of Gennady's possible optimal strategies is as follows. At 18:10 (6:10 PM) he begins to write the first problem and solves it in 30 minutes (18:40 or 6.40 P.M.). At 18:40 (6.40 P.M.) he begins to write the second problem. There are 320 minutes left before the New Year, so Gennady does not have the time to finish writing the second problem before the New Year. At 0:00 (12.00 A.M.) he distracts from the second problem, submits the first one, and returns immediately to writing the second problem. At 0:10 (0.10 A.M.), he completes the solution for the second problem, submits it and gets 10 minute penalty time. Note that as the total duration of the contest is 720 minutes and Gennady has already spent 10 minutes on reading the problems, he will not have time to solve the third problem during the contest. Yes, such problems happen to exist. Competitions by the given rules are held annually on the site http://b23.ru/3wvc ### Response ```cpp #include <bits/stdc++.h> using namespace std; int arr[111]; int main() { int n; scanf("%d", &n); for (int i = (0); i < (n); ++i) scanf("%d", &arr[i]); sort(arr, arr + n); int t = 10; int ans = 0; int qts = 0; for (int i = (0); i < (n); ++i) { t += arr[i]; if (t > 720) break; qts++; if (t > 360) ans += (t - 360); } printf("%d %d\n", qts, ans); return 0; } ```
### Prompt Create a solution in cpp for the following problem: I decided to create a program that displays a "round and round pattern". The "round and round pattern" is as follows. * If the length of one side is n, it is displayed as a character string with n rows and n columns. * A spiral pattern that rotates clockwise with the lower left corner as the base point. * The part with a line is represented by # (half-width sharp), and the blank part is represented by "" (half-width blank). * Leave a space between the lines. Create a program that takes an integer n as an input and outputs a "round and round pattern" with a side length of n. Input The input is given in the following format: d n1 n2 :: nd The number of datasets d (d ≀ 20) is given to the first line, and the side length ni (1 ≀ ni ≀ 100) of the i-th round pattern is given to each of the following d lines. Output Please output a round and round pattern for each data set. Insert a blank line between the datasets. Example Input 2 5 6 Output ##### # # # # # # # # # ### ###### # # # ## # # # # # # # # #### ### Response ```cpp #include <iostream> #include <algorithm> using namespace std; char A[100][100]; int main() { int D; cin >> D; while(D--) { int N; cin >> N; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { A[i][j] = ' '; } } int x = 0, y = N; const int dx[] = { 0, 1, 0, -1 }; const int dy[] = { -1, 0, 1, 0 }; int dir = 0; for(int i = 0; i < N; i++) { int k; if(i == 0) k = N; else k = N + 1 - (i + 1) / 2 * 2; for(int j = 0; j < k; j++) { x += dx[dir]; y += dy[dir]; A[y][x] = '#'; } (dir += 1) %= 4; } for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { cout << A[i][j]; } cout << endl; } if(D != 0) cout << endl; } } ```
### Prompt Please provide a cpp coded solution to the problem described below: 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 MOD = 1000000007; double PI = 4 * atan(1); double val[100005]; int numc[100005], par[100005]; vector<int> child[100005]; int dfs(int node) { for (int i : child[node]) numc[node] += dfs(i); numc[node]++; return numc[node]; } void dfs2(int node) { val[node] = val[par[node]]; val[node] += double(numc[par[node]] - numc[node] + 1) / 2.0; for (int i : child[node]) dfs2(i); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; cin >> n; for (int i = 2; i < n + 1; i++) { int x; cin >> x; child[x].push_back(i); par[i] = x; } dfs(1); val[1] = 1.0; for (int i : child[1]) dfs2(i); cout << fixed << setprecision(1); for (int i = 1; i < n + 1; i++) cout << val[i] << " "; return 0; } ```
### Prompt Construct a Cpp code solution to the problem outlined: Given is a string S consisting of `0` and `1`. Find the number of strings, modulo 998244353, that can result from applying the following operation on S between 0 and K times (inclusive): * Choose a pair of integers i, j (1\leq i < j\leq |S|) such that the i-th and j-th characters of S are `0` and `1`, respectively. Remove the j-th character from S and insert it to the immediate left of the i-th character. Constraints * 1 \leq |S| \leq 300 * 0 \leq K \leq 10^9 * S consists of `0` and `1`. Input Input is given from Standard Input in the following format: S K Output Find the number of strings, modulo 998244353, that can result from applying the operation on S between 0 and K times (inclusive). Examples Input 0101 1 Output 4 Input 01100110 2 Output 14 Input 1101010010101101110111100011011111011000111101110101010010101010101 20 Output 113434815 ### Response ```cpp #include <iostream> #include <cstdio> #include <cstring> using namespace std; const int mod = 998244353; int f[305][305][305], n, m, a[305]; char s[305]; inline int abs(const int &x){return x<0?-x:x;} inline int add(const int &x, const int &y){return x+y>=mod?x+y-mod:x+y;} int main() { scanf("%s%d",s+1,&m); for(int i=1, L=strlen(s+1), pre=0;i<=L;i++) { if(s[i]=='0') { a[++n]=i-pre-1; pre=i; } else if(i==L) { a[++n]=i-pre; } } m=min(m,int(strlen(s+1))); f[n+1][0][0]=1; for(int i=n+1;i>1;i--) { for(int p=0;p<=m;p++) { for(int j=0;j<=m;j++) if(f[i][p][j]){ for(int k=0;k<=m;k++) { if(k<=p) { f[i-1][p-k][j]=add(f[i][p][j],f[i-1][p-k][j]); } if(k<=a[i-1]&&k) { f[i-1][p+k][j+k]=add(f[i][p][j],f[i-1][p+k][j+k]); } } } } } int ans=0; for(int i=0;i<=m;i++) ans=add(ans,f[1][0][i]); printf("%d\n",ans); return 0; } ```
### Prompt Create a solution in cpp for the following problem: Two beavers, Timur and Marsel, play the following game. There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins. Timur makes the first move. The players play in the optimal way. Determine the winner. Input The first line contains three integers n, m, k (1 ≀ n, m, k ≀ 109). Output Print "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes. Examples Input 1 15 4 Output Timur Input 4 9 5 Output Marsel Note In the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as k = 4. Thus, the winner is Timur. In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 1e5 + 100; const double EPS = 1e-9; const long long INF = 1000000000 + 5; int n, m, k; map<pair<int, int>, int> list; int main() { cin >> n >> m >> k; int ans = 0; for (int i = 1; i * i <= m; i++) { if (m % i == 0) { if (i >= k && m / i > 1) ans = 1; if (i > 1 && m / i >= k) ans = 1; } } if (n % 2 == 0) ans = 0; if (ans) printf("Timur"); else printf("Marsel"); return 0; } ```
### Prompt Create a solution in Cpp for the following problem: There are N stones arranged in a row. The i-th stone from the left is painted in the color C_i. Snuke will perform the following operation zero or more times: * Choose two stones painted in the same color. Repaint all the stones between them, with the color of the chosen stones. Find the number of possible final sequences of colors of the stones, modulo 10^9+7. Constraints * 1 \leq N \leq 2\times 10^5 * 1 \leq C_i \leq 2\times 10^5(1\leq i\leq N) * All values in input are integers. Input Input is given from Standard Input in the following format: N C_1 : C_N Output Print the number of possible final sequences of colors of the stones, modulo 10^9+7. Examples Input 5 1 2 1 2 2 Output 3 Input 6 4 2 5 4 2 4 Output 5 Input 7 1 3 1 2 3 3 2 Output 5 ### Response ```cpp #include <bits/stdc++.h> #define MOD 1000000007 using namespace std; int main() { int n; cin >> n; long ans = 1; int prev = -1; unordered_map<int, int> counter; for (int i = 0; i < n; i++) { int c; cin >> c; if (c != prev) { ans += counter[c]; ans %= MOD; } prev = c; counter[c] = ans; } cout << ans << endl; return 0; } ```
### Prompt Create a solution in Cpp for the following problem: You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of: * Operation AND ('&', ASCII code 38) * Operation OR ('|', ASCII code 124) * Operation NOT ('!', ASCII code 33) * Variables x, y and z (ASCII codes 120-122) * Parentheses ('(', ASCII code 40, and ')', ASCII code 41) If more than one expression of minimum length exists, you should find the lexicographically smallest one. Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar: E ::= E '|' T | T T ::= T '&' F | F F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z' Input The first line contains one integer n β€” the number of functions in the input (1 ≀ n ≀ 10 000). The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 β€” the truth table of the i-th function. The digit on position j (0 ≀ j < 8) equals to the value of the function in case of <image>, <image> and <image>. Output You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces. Example Input 4 00110011 00000111 11110000 00011111 Output y (y|z)&amp;x !x x|y&amp;z Note The truth table for the second function: <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1010; int n, U; char s[20]; struct table { int f, tp; string s; table(void) {} table(int _f, int t, string a) : f(_f), tp(t), s(a) {} inline bool operator<(const table &b) const { if (s.size() == b.s.size()) return s < b.s; return s.size() < b.s.size(); } }; table ans[N][4]; int vis[N][4]; set<table> S; set<table>::iterator it; vector<table> don; inline void Push(int f, int tp, string s) { table u = table(f, tp, s); if (!vis[f][tp]) { vis[f][tp] = 1; ans[f][tp] = u; S.insert(u); } else if (u < ans[f][tp]) { S.erase(ans[f][tp]); ans[f][tp] = u; S.insert(u); } } int main(void) { Push(240, 0, "x"); Push(204, 0, "y"); Push(170, 0, "z"); U = (1 << 8) - 1; while (!S.empty()) { it = S.begin(); table cur = *it; S.erase(it); Push(cur.f, 0, '(' + cur.s + ')'); if (cur.tp == 0) Push(cur.f ^ U, 0, '!' + cur.s); don.push_back(cur); for (table x : don) { if (cur.tp < 2 && x.tp < 2) Push(cur.f & x.f, 1, min(cur.s, x.s) + '&' + max(cur.s, x.s)); Push(cur.f | x.f, 2, min(cur.s, x.s) + '|' + max(cur.s, x.s)); } } for (int i = 0; i <= U; i++) ans[i][0] = min(ans[i][0], min(ans[i][1], ans[i][2])); scanf("%d", &n); while (n--) { scanf("%s", s); int f = 0; for (int i = 7; ~i; i--) f = f << 1 | (s[i] - '0'); cout << ans[f][0].s << endl; } return 0; } ```
### Prompt Your task is to create a cpp solution to the following problem: Input The input contains two integers N, M (1 ≀ N ≀ 1024, 2 ≀ M ≀ 16), separated by a single space. Output Output "YES" or "NO". Examples Input 2 3 Output YES Input 3 2 Output NO Input 33 16 Output YES Input 26 5 Output NO ### Response ```cpp /* Ψ¨Ψ³Ω… Ψ§Ω„Ω„Ω‡ Ψ§Ω„Ψ±Ψ­Ω…Ω† Ψ§Ω„Ψ±Ψ­ΩŠΩ… Ψ§Ω„Ψ¬Ψ§Ω…ΨΉΨ© Ψ§Ω„Ψ₯Ψ³Ω„Ψ§Ω…ΩŠΨ© Ψ§Ω„ΨΉΨ§Ω„Ω…ΩŠΨ© شيΨͺΨ§ΨΊΩˆΩ†ΨΊ Ω„Ψ§ ΨͺΨ­Ψ²Ω† Ψ§Ω† Ψ§Ω„Ω„Ω‡ Ω…ΨΉΩ†Ψ§ */ #include<bits/stdc++.h> using namespace std; #define ll long long #define fr(i, a, b) for (ll i=a; i<b; i++) ll gcd(ll a, ll b) { if (b==0) return a; return gcd(b, a%b); } void solve() { ll n, m, arr[1001] ={0}; cin >> n >> m; while(n) { arr[n % m] ++; n /= m; } ll f = 0; fr(i, 0, m) { if (arr[i] > 1) { f = 1; cout << "NO\n"; break; } } if (!f) cout << "YES\n"; } int main() { solve(); return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: Sonya was unable to think of a story for this problem, so here comes the formal description. You are given the array containing n positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operations. You are allowed to change elements in any way, they can become negative or equal to 0. Input The first line of the input contains a single integer n (1 ≀ n ≀ 3000) β€” the length of the array. Next line contains n integer ai (1 ≀ ai ≀ 109). Output Print the minimum number of operation required to make the array strictly increasing. Examples Input 7 2 1 5 11 5 9 11 Output 9 Input 5 5 4 3 2 1 Output 12 Note In the first sample, the array is going to look as follows: 2 3 5 6 7 9 11 |2 - 2| + |1 - 3| + |5 - 5| + |11 - 6| + |5 - 7| + |9 - 9| + |11 - 11| = 9 And for the second sample: 1 2 3 4 5 |5 - 1| + |4 - 2| + |3 - 3| + |2 - 4| + |1 - 5| = 12 ### Response ```cpp #include <bits/stdc++.h> using namespace std; void read_file(bool outToFile = true) {} const int nMax = 3000 + 1 + 9; int midian[nMax][nMax]; long long cost[nMax][nMax]; int A[nMax], B[nMax]; int n; long long dp[nMax], last[nMax]; void prepro() { for (int start = 1; start <= n; start++) { priority_queue<int> P; priority_queue<int, vector<int>, greater<int> > Q; long long sumP = 0, sumQ = 0; for (int i = start; i <= n; i++) { int minQ = Q.empty() ? -(2000000000) : Q.top(); if (B[i] >= minQ) { Q.push(B[i]); sumQ += B[i]; if (Q.size() == P.size() + 2) { int minQ = Q.top(); Q.pop(); sumQ -= minQ; P.push(minQ); sumP += minQ; } } else { P.push(B[i]); sumP += B[i]; if (P.size() == Q.size() + 1) { int maxP = P.top(); P.pop(); sumP -= maxP; Q.push(maxP); sumQ += maxP; } } int mid; mid = Q.top(); mid = Q.size() == P.size() + 1 ? mid : P.top(); midian[start][i] = mid; long long costP = 1LL * P.size() * mid - sumP; long long costQ = sumQ - 1LL * Q.size() * mid; cost[start][i] = costP + costQ; } } } void build_dp() { dp[0] = 0, last[0] = -(2000000000); for (int j = 1; j <= n; j++) { dp[j] = LLONG_MAX; for (int i = 0; i < j; i++) { if (last[i] >= midian[i + 1][j] + i + 1) continue; long long nw = dp[i] + cost[i + 1][j]; long long nwl = 0LL + midian[i + 1][j] + j; if (dp[j] > nw) { dp[j] = nw; last[j] = nwl; } else if (dp[j] == nw) { last[j] = min(last[j], nwl); } } } } int main() { read_file(); while (scanf("%d", &n) != EOF) { for (int i = 1; i <= n; i++) scanf("%d", &A[i]), B[i] = A[i] - i; prepro(); build_dp(); long long ans = dp[n]; printf("%lld\n", ans); } } ```
### Prompt Generate a CPP solution to the following problem: You are a given a list of integers a_1, a_2, …, a_n and s of its segments [l_j; r_j] (where 1 ≀ l_j ≀ r_j ≀ n). You need to select exactly m segments in such a way that the k-th order statistic of the multiset of a_i, where i is contained in at least one segment, is the smallest possible. If it's impossible to select a set of m segments in such a way that the multiset contains at least k elements, print -1. The k-th order statistic of a multiset is the value of the k-th element after sorting the multiset in non-descending order. Input The first line contains four integers n, s, m and k (1 ≀ m ≀ s ≀ 1500, 1 ≀ k ≀ n ≀ 1500) β€” the size of the list, the number of segments, the number of segments to choose and the statistic number. The second line contains n integers a_i (1 ≀ a_i ≀ 10^9) β€” the values of the numbers in the list. Each of the next s lines contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ n) β€” the endpoints of the segments. It is possible that some segments coincide. Output Print exactly one integer β€” the smallest possible k-th order statistic, or -1 if it's impossible to choose segments in a way that the multiset contains at least k elements. Examples Input 4 3 2 2 3 1 3 2 1 2 2 3 4 4 Output 2 Input 5 2 1 1 1 2 3 4 5 2 4 1 5 Output 1 Input 5 3 3 5 5 5 2 1 1 1 2 2 3 3 4 Output -1 Note In the first example, one possible solution is to choose the first and the third segment. Together they will cover three elements of the list (all, except for the third one). This way the 2-nd order statistic for the covered elements is 2. <image> ### Response ```cpp #include <bits/stdc++.h> const double eps = (1e-9); using namespace std; int dcmp(long double a, long double b) { return fabsl(a - b) <= eps ? 0 : (a > b) ? 1 : -1; } int getBit(long long num, int idx) { return ((num >> idx) & 1ll) == 1; } int setBit1(int num, int idx) { return num | (1 << idx); } long long setBit0(long long num, int idx) { return num & ~(1ll << idx); } long long flipBit(long long num, int idx) { return num ^ (1ll << idx); } void M() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); } int countNumBit1(int mask) { int ret = 0; while (mask) { mask &= (mask - 1); ++ret; } return ret; } int n, s, m, k, mem[1509][1509], arr1[1509], arr2[1509], nxt[1509]; vector<int> v1, org; vector<pair<int, int> > v2; int solve(int i, int rem) { if (rem <= 0) return 0; if (i == n) return m + 1; int &ret = mem[i][rem]; if (ret != -1) return ret; int ans; ans = solve(i + 1, rem); if (nxt[i] != -1) ans = min(ans, 1 + solve(nxt[i], rem - arr2[i])); return ret = ans; } bool check(int L) { memset(arr1, 0, sizeof(arr1)); for (int i = 0; i < n; i++) { if (org[i] <= L) arr1[i]++; if (i) arr1[i] += arr1[i - 1]; } for (int i = 0; i < n; i++) { if (nxt[i] == -1) continue; arr2[i] = arr1[nxt[i] - 1]; if (i) arr2[i] -= arr1[i - 1]; } memset(mem, -1, sizeof(mem)); return solve(0, k) <= m; } int main() { M(); cin >> n >> s >> m >> k; int no; for (int i = 0; i < n; i++) { cin >> no; org.push_back(no); v1.push_back(no); } sort(((v1).begin()), ((v1).end())); int l, r; for (int i = 0; i < s; i++) { cin >> l >> r; l--; r--; v2.push_back(make_pair(l, r)); } sort(((v2).begin()), ((v2).end())); memset(nxt, -1, sizeof(nxt)); for (int i = 0; i < s; i++) { for (int j = v2[i].first; j <= v2[i].second; j++) nxt[j] = max(nxt[j], v2[i].second + 1); } l = 0; r = n - 1; int mid, res = -1; while (l <= r) { int mid = (l + r) / 2; if (check(v1[mid])) { r = mid - 1; res = v1[mid]; } else l = mid + 1; } cout << res << endl; } ```
### Prompt Please create a solution in cpp to the following problem: Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t). In one move Koa: 1. selects some subset of positions p_1, p_2, …, p_k (k β‰₯ 1; 1 ≀ p_i ≀ n; p_i β‰  p_j if i β‰  j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). 2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x). 3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≀ i ≀ k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A. Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her! Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 10) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains one integer n (1 ≀ n ≀ 10^5) β€” the length of strings A and B. The second line of each test case contains string A (|A|=n). The third line of each test case contains string B (|B|=n). Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal. Example Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 Note * In the 1-st test case Koa: 1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β†’ \color{blue}{bb}b). 2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β†’ b\color{blue}{cc}). * In the 2-nd test case Koa has no way to make string A equal B. * In the 3-rd test case Koa: 1. selects position 1 and sets A_1 = t (\color{red}{a}bc β†’ \color{blue}{t}bc). 2. selects position 2 and sets A_2 = s (t\color{red}{b}c β†’ t\color{blue}{s}c). 3. selects position 3 and sets A_3 = r (ts\color{red}{c} β†’ ts\color{blue}{r}). ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { long long int n, m, i, j, k, l, t, x, y; string str = "abcdefghijklmnopqrst"; cin >> t; while (t--) { cin >> n; string a, b; cin >> a >> b; long long int f = 0; for (i = 0; i < n; i++) { if (a[i] > b[i]) { f = 1; break; } } if (f) { cout << -1 << endl; continue; } long long int sum = 0; for (j = 0; j < 20; j++) { char ch = str[j]; char c = 'z'; long long int qq = 0; for (i = 0; i < n; i++) { if (a[i] == ch && a[i] != b[i]) { qq = 1; if (b[i] < c) { c = b[i]; } } } sum += qq; for (l = 0; l < n; l++) { if (a[l] == ch && a[l] != b[l]) { a[l] = c; } } if (a == b) break; } cout << sum << endl; } } ```
### Prompt Please provide a CPP coded solution to the problem described below: Vova, the Ultimate Thule new shaman, wants to build a pipeline. As there are exactly n houses in Ultimate Thule, Vova wants the city to have exactly n pipes, each such pipe should be connected to the water supply. A pipe can be connected to the water supply if there's water flowing out of it. Initially Vova has only one pipe with flowing water. Besides, Vova has several splitters. A splitter is a construction that consists of one input (it can be connected to a water pipe) and x output pipes. When a splitter is connected to a water pipe, water flows from each output pipe. You can assume that the output pipes are ordinary pipes. For example, you can connect water supply to such pipe if there's water flowing out from it. At most one splitter can be connected to any water pipe. <image> The figure shows a 4-output splitter Vova has one splitter of each kind: with 2, 3, 4, ..., k outputs. Help Vova use the minimum number of splitters to build the required pipeline or otherwise state that it's impossible. Vova needs the pipeline to have exactly n pipes with flowing out water. Note that some of those pipes can be the output pipes of the splitters. Input The first line contains two space-separated integers n and k (1 ≀ n ≀ 1018, 2 ≀ k ≀ 109). 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 minimum number of splitters needed to build the pipeline. If it is impossible to build a pipeline with the given splitters, print -1. Examples Input 4 3 Output 2 Input 5 5 Output 1 Input 8 4 Output -1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long n, k; bool ok(long long x) { long long ans = (k * (k + 1)) / 2; ans -= ((k - x) * (k - x + 1)) / 2; ans -= x - 1; if (ans >= n) return true; return false; } int32_t main() { ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); cin >> n >> k; long long low = 0, high = k - 1; long long ans = -1; while (low <= high) { long long mid = (low + high) / 2; if (ok(mid)) { ans = mid; high = mid - 1; } else low = mid + 1; } cout << ans; return 0; } ```
### Prompt Your challenge is to write a Cpp solution to the following problem: Karen is getting ready for a new school day! <image> It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome. What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome? Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50. Input The first and only line of input contains a single string in the format hh:mm (00 ≀ hh ≀ 23, 00 ≀ mm ≀ 59). Output Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome. Examples Input 05:39 Output 11 Input 13:31 Output 0 Input 23:59 Output 1 Note In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome. In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome. In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome. ### Response ```cpp #include <bits/stdc++.h> using namespace std; string s, s1; int ans, h, hh, m, mm; int main() { cin >> s; while (1) { h = s[0] - 48; hh = s[1] - 48; m = s[3] - 48; mm = s[4] - 48; if (h == mm && hh == m) { break; } mm++; if (mm == 10) { mm = 0; m++; if (m == 6) { m = 0; hh++; if (hh == 10) { hh = 0; h++; } if (hh == 4 && h == 2) { hh = 0; h = 0; } } } s[0] = h + 48; s[1] = hh + 48; s[3] = m + 48; s[4] = mm + 48; ans++; } cout << ans; return 0; } ```
### Prompt Please provide a CPP coded solution to the problem described below: All Berland residents are waiting for an unprecedented tour of wizard in his Blue Helicopter over the cities of Berland! It is well-known that there are n cities in Berland, some pairs of which are connected by bidirectional roads. Each pair of cities is connected by no more than one road. It is not guaranteed that the road network is connected, i.e. it is possible that you can't reach some city from some other. The tour will contain several episodes. In each of the episodes: * the wizard will disembark at some city x from the Helicopter; * he will give a performance and show a movie for free at the city x; * he will drive to some neighboring city y using a road; * he will give a performance and show a movie for free at the city y; * he will drive to some neighboring to y city z; * he will give a performance and show a movie for free at the city z; * he will embark the Helicopter and fly away from the city z. It is known that the wizard doesn't like to use roads, so he agrees to use each road at most once (regardless of direction). In other words, for road between a and b he only can drive once from a to b, or drive once from b to a, or do not use this road at all. The wizards wants to plan as many episodes as possible without violation the above rules. Help the wizard! Please note that the wizard can visit the same city multiple times, the restriction is on roads only. Input The first line contains two integers n, m (1 ≀ n ≀ 2Β·105, 0 ≀ m ≀ 2Β·105) β€” the number of cities and the number of roads in Berland, respectively. The roads description follow, one in each line. Each description is a pair of two integers ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi), where ai and bi are the ids of the cities connected by the i-th road. It is guaranteed that there are no two roads connecting the same pair of cities. Every road is bidirectional. The cities are numbered from 1 to n. It is possible that the road network in Berland is not connected. Output In the first line print w β€” the maximum possible number of episodes. The next w lines should contain the episodes in format x, y, z β€” the three integers denoting the ids of the cities in the order of the wizard's visits. Examples Input 4 5 1 2 3 2 2 4 3 4 4 1 Output 2 1 4 2 4 3 2 Input 5 8 5 3 1 2 4 5 5 1 2 5 4 3 1 4 3 2 Output 4 1 4 5 2 3 4 1 5 3 5 2 1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long int gcd(long long int a, long long int b) { if (!b) return a; else return gcd(b, a % b); } const int MAXN = 2e5 + 5; vector<pair<int, pair<int, int>>> ans; vector<vector<int>> adj(MAXN); vector<bool> vis(MAXN, 0); vector<int> tin(MAXN, 0); int timer = 0; bool dfs(int v, int u) { vis[v] = 1; tin[v] = ++timer; vector<int> can; for (int x : adj[v]) { if (x == u) continue; if (!vis[x]) { if (dfs(x, v)) can.push_back(x); } else if (tin[x] < tin[v]) { can.push_back(x); } } for (int i = 1; i < (int)(can.size()); i += 2) { ans.push_back({can[i], {v, can[i - 1]}}); } if ((int)(can.size()) % 2 == 0) return 1; if (u != -1) { int s = (int)(can.size()) - 1; ans.push_back({can[s], {v, u}}); } return 0; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, m; cin >> n >> m; for (int i = 0; i < m; i++) { int v, u; cin >> v >> u; adj[v].push_back(u); adj[u].push_back(v); } for (int i = 1; i <= n; i++) { if (!vis[i]) { dfs(i, -1); } } cout << (int)(ans.size()) << '\n'; for (auto x : ans) { cout << x.first << " " << x.second.first << " " << x.second.second << '\n'; } } ```
### Prompt In cpp, your task is to solve the following problem: An atom of element X can exist in n distinct states with energies E1 < E2 < ... < En. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme. Three distinct states i, j and k are selected, where i < j < k. After that the following process happens: 1. initially the atom is in the state i, 2. we spend Ek - Ei energy to put the atom in the state k, 3. the atom emits a photon with useful energy Ek - Ej and changes its state to the state j, 4. the atom spontaneously changes its state to the state i, losing energy Ej - Ei, 5. the process repeats from step 1. Let's define the energy conversion efficiency as <image>, i. e. the ration between the useful energy of the photon and spent energy. Due to some limitations, Arkady can only choose such three states that Ek - Ei ≀ U. Help Arkady to find such the maximum possible energy conversion efficiency within the above constraints. Input The first line contains two integers n and U (3 ≀ n ≀ 105, 1 ≀ U ≀ 109) β€” the number of states and the maximum possible difference between Ek and Ei. The second line contains a sequence of integers E1, E2, ..., En (1 ≀ E1 < E2... < En ≀ 109). It is guaranteed that all Ei are given in increasing order. Output If it is not possible to choose three states that satisfy all constraints, print -1. Otherwise, print one real number Ξ· β€” the maximum possible energy conversion efficiency. Your answer is considered correct its absolute or relative error does not exceed 10 - 9. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if <image>. Examples Input 4 4 1 3 5 7 Output 0.5 Input 10 8 10 13 15 16 17 19 20 22 24 25 Output 0.875 Input 3 1 2 5 10 Output -1 Note In the first example choose states 1, 2 and 3, so that the energy conversion efficiency becomes equal to <image>. In the second example choose states 4, 5 and 9, so that the energy conversion efficiency becomes equal to <image>. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int Set(int n, int pos) { return n = n | (1 << pos); } int reset(int n, int pos) { return n = n & ~(1 << pos); } bool check(int n, int pos) { return (bool)(n & (1 << pos)); } long long gcd(long long a, long long b) { if (b == 0) return a; else return gcd(b, a % b); }; long long lcm(long long a, long long b) { return (a * b) / gcd(a, b); }; int ara[100005]; int ans = 0; int bs(int i, int n, int u) { int lo = i + 2, hi = n, mid; ans = 0; while (lo <= hi) { mid = (lo + hi) >> 1; if (ara[mid] - ara[i] <= u) { lo = mid + 1; ans = mid; } else hi = mid - 1; } return ans; } int main() { int n, u; scanf("%d%d", &n, &u); for (int i = 1; i <= n; i++) scanf("%d", &ara[i]); int lo = 1, hi = n; double ans = 0.0; for (int i = 1; i <= n; i++) { int k = bs(i, n, u); if (k == 0) continue; int tmp = ara[k] - ara[i + 1], tmp2 = ara[k] - ara[i]; double tmp3 = (1.0 * tmp) / (1.0 * tmp2); if (tmp3 > ans) { ans = tmp3; } } if (ans == 0.0) { printf("-1\n"); return 0; } printf("%.15lf", ans); } ```
### Prompt Your task is to create a Cpp solution to the following problem: Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if 1. the sequence consists of at least two elements 2. f0 and f1 are arbitrary 3. fn + 2 = fn + 1 + fn for all n β‰₯ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence. Input The first line of the input contains a single integer n (2 ≀ n ≀ 1000) β€” the length of the sequence ai. The second line contains n integers a1, a2, ..., an (|ai| ≀ 109). Output Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement. Examples Input 3 1 2 -1 Output 3 Input 5 28 35 7 14 21 Output 4 Note In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish. In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1000000 + 5; int a[1005], b[1005], sum[1005], pos[1005]; int main() { int res = 0, mx = -1, n, l = 0; scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d", &a[i]); mx = max(a[i], mx); if (a[i] == 0) ++res; } sort(a + 1, a + 1 + n); b[++l] = a[1]; for (int i = 2; i <= n; ++i) if (a[i] != a[i - 1]) b[++l] = a[i]; for (int i = 1; i <= n; ++i) { pos[i] = lower_bound(b + 1, b + 1 + l, a[i]) - b; ++sum[pos[i]]; } int ans = 2; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { if (j == i) continue; if (a[i] == 0 && a[j] == 0) continue; int x = a[i], y = a[j], cnt = 2; vector<int> t; t.clear(); sum[pos[i]]--; sum[pos[j]]--; t.push_back(pos[i]); t.push_back(pos[j]); while (x + y <= mx) { int z = lower_bound(b + 1, b + 1 + l, x + y) - b; if (z == l + 1 || b[z] != x + y || !sum[z]) break; sum[z]--; t.push_back(z); int tmp = x + y; x = y; y = tmp; ++cnt; } for (int k = 0; k < t.size(); k++) sum[t[k]]++; ans = max(ans, cnt); } } printf("%d\n", max(ans, res)); return 0; } ```
### Prompt Please create a solution in Cpp to the following problem: You are running for a governor in a small city in Russia. You ran some polls and did some research, and for every person in the city you know whom he will vote for, and how much it will cost to bribe that person to vote for you instead of whomever he wants to vote for right now. You are curious, what is the smallest amount of money you need to spend on bribing to win the elections. To win elections you need to have strictly more votes than any other candidate. Input First line contains one integer n (1 ≀ n ≀ 105) β€” number of voters in the city. Each of the next n lines describes one voter and contains two integers ai and bi (0 ≀ ai ≀ 105; 0 ≀ bi ≀ 104) β€” number of the candidate that voter is going to vote for and amount of money you need to pay him to change his mind. You are the candidate 0 (so if a voter wants to vote for you, ai is equal to zero, in which case bi will also be equal to zero). Output Print one integer β€” smallest amount of money you need to spend to win the elections. Examples Input 5 1 2 1 2 1 2 2 1 0 0 Output 3 Input 4 1 2 1 2 2 1 0 0 Output 2 Input 1 100000 0 Output 0 ### Response ```cpp #include <bits/stdc++.h> using namespace std; vector<int> v[100005]; int my = 0; int n; int check(int m) { int mx = 0; vector<int> nv; int ans = 0; int have = my; for (int i = 1; i <= 100000; ++i) { mx = max(mx, (int)v[i].size()); for (int j = 0, s = v[i].size(); j < s; ++j) { if (s - j <= m) nv.push_back(v[i][j]); else { ans += v[i][j]; have++; } } } int t = m - have; sort(nv.begin(), nv.end()); for (int i = 0; i < t + (mx >= m) && i < nv.size(); ++i) ans += nv[i]; return ans; } int main() { int a, b; scanf("%d", &n); for (int i = 0; i < n; ++i) { scanf("%d%d", &a, &b); if (a != 0) v[a].push_back(b); else my++; } for (int i = 1; i <= 100000; ++i) sort(v[i].begin(), v[i].end()); int l = 0, r = n; while (r - l > 2) { int m1 = l + (r - l) / 3; int m2 = r - (r - l) / 3; if (check(m1) < check(m2)) { r = m2; } else { l = m1; } } int ans = 0x3f3f3f3f; for (int i = l; i <= r; ++i) { ans = min(ans, check(i)); } cout << ans << endl; return 0; } ```
### Prompt Your challenge is to write a Cpp solution to the following problem: Takahashi has many red balls and blue balls. Now, he will place them in a row. Initially, there is no ball placed. Takahashi, who is very patient, will do the following operation 10^{100} times: * Place A blue balls at the end of the row of balls already placed. Then, place B red balls at the end of the row. How many blue balls will be there among the first N balls in the row of balls made this way? Constraints * 1 \leq N \leq 10^{18} * A, B \geq 0 * 0 < A + B \leq 10^{18} * All values in input are integers. Input Input is given from Standard Input in the following format: N A B Output Print the number of blue balls that will be there among the first N balls in the row of balls. Examples Input 8 3 4 Output 4 Input 8 0 4 Output 0 Input 6 2 4 Output 2 ### Response ```cpp #include <iostream> using namespace std; int main() { unsigned long long n,a,b; cin>>n>>a>>b; cout<<(n/(a+b))*a+min(n%(a+b),a); return 0; } ```
### Prompt Please create a solution in cpp to the following problem: wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentally switched on, if: * either it only contains uppercase letters; * or all letters except for the first one are uppercase. In this case we should automatically change the case of all letters. For example, the case of the letters that form words "hELLO", "HTTP", "z" should be changed. Write a program that applies the rule mentioned above. If the rule cannot be applied, the program should leave the word unchanged. Input The first line of the input data contains a word consisting of uppercase and lowercase Latin letters. The word's length is from 1 to 100 characters, inclusive. Output Print the result of the given word's processing. Examples Input cAPS Output Caps Input Lock Output Lock ### Response ```cpp #include <bits/stdc++.h> int main() { int i; int j, flag = 1; char Str[100]; scanf("%s", Str); for (i = 1; Str[i] != '\0'; i++) { if (Str[i] >= 97 && Str[i] <= 122) { flag = 0; break; } } if (flag == 1) { if (Str[0] >= 65 && Str[0] <= 90) Str[0] = Str[0] + 32; else Str[0] = Str[0] - 32; for (j = 1; Str[j] != '\0'; j++) { Str[j] = Str[j] + 32; } } printf("%s\n", Str); return 0; } ```
### Prompt Your task is to create a cpp solution to the following problem: Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting. Suppose the graph G is given. Subset A of its vertices is called a vertex cover of this graph, if for each edge uv there is at least one endpoint of it in this set, i.e. <image> or <image> (or both). Pari and Arya have won a great undirected graph as an award in a team contest. Now they have to split it in two parts, but both of them want their parts of the graph to be a vertex cover. They have agreed to give you their graph and you need to find two disjoint subsets of its vertices A and B, such that both A and B are vertex cover or claim it's impossible. Each vertex should be given to no more than one of the friends (or you can even keep it for yourself). Input The first line of the input contains two integers n and m (2 ≀ n ≀ 100 000, 1 ≀ m ≀ 100 000) β€” the number of vertices and the number of edges in the prize graph, respectively. Each of the next m lines contains a pair of integers ui and vi (1 ≀ ui, vi ≀ n), denoting an undirected edge between ui and vi. It's guaranteed the graph won't contain any self-loops or multiple edges. Output If it's impossible to split the graph between Pari and Arya as they expect, print "-1" (without quotes). If there are two disjoint sets of vertices, such that both sets are vertex cover, print their descriptions. Each description must contain two lines. The first line contains a single integer k denoting the number of vertices in that vertex cover, and the second line contains k integers β€” the indices of vertices. Note that because of m β‰₯ 1, vertex cover cannot be empty. Examples Input 4 2 1 2 2 3 Output 1 2 2 1 3 Input 3 3 1 2 2 3 1 3 Output -1 Note In the first sample, you can give the vertex number 2 to Arya and vertices numbered 1 and 3 to Pari and keep vertex number 4 for yourself (or give it someone, if you wish). In the second sample, there is no way to satisfy both Pari and Arya. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long MAXN = (long long)((1e5) + 10); long long gcd(long long a, long long b) { if (a == 0) return b; return gcd(b % a, a); } long long max(long long a, long long b) { if (a > b) return a; else return b; } long long min(long long a, long long b) { if (a < b) return a; else return b; } bool isPrime(long long N) { for (long long i = 2; i * i <= N; ++i) { if (N % i == 0) return false; } return true; } long long cbrt(long long x) { long long lo = 1, hi = min(2000000ll, x); while (hi - lo > 1) { long long mid = (lo + hi) / 2; if (mid * mid * mid < x) { lo = mid; } else hi = mid; } if (hi * hi * hi <= x) return hi; else return lo; } const long long dx[4] = {-1, 1, 0, 0}; const long long dy[4] = {0, 0, -1, 1}; const long long nax = (long long)(100000 + 10); vector<string> v; vector<long long> adj[200005], vec, nod, ans1, ans2; stack<long long> st; long long n, m, d, k, l = 0, r, mid, s = 0, a, b, q, t, flag = 1, bad = 0, c = 0; vector<vector<long long>> arr(200005, vector<long long>(3, 0)); long long vis[200005], par[200005], col[200005]; priority_queue<pair<long long, long long>, vector<pair<long long, long long>>, greater<pair<long long, long long>>> pq; map<long long, map<long long, long long>> ab; void bfs(long long u) { vis[u] = 1; col[u] = 1; queue<long long> q; q.push(u); while (!q.empty()) { long long u = q.front(); q.pop(); for (auto &i : adj[u]) { if (col[i] && col[u] == col[i]) { flag = false; } } for (auto &i : adj[u]) { if (!vis[i]) { col[i] = col[u] % 2 + 1; vis[i] = 1; q.push(i); } } } } signed main() { cin >> n >> m; for (long long i = 0; i < m; i++) { cin >> a >> b; adj[a].push_back(b); adj[b].push_back(a); } for (long long i = 1; i <= n; i++) { if (!vis[i] && adj[i].size() != 0) { bfs(i); } } for (long long i = 1; i <= n; i++) { if (col[i] == 1) { ans1.push_back(i); } else if (col[i] == 2) { ans2.push_back(i); } } if (!flag) { cout << -1 << "\n"; return 0; } cout << ans1.size() << "\n"; for (long long x : ans1) { cout << x << " "; } cout << "\n"; cout << ans2.size() << "\n"; for (long long x : ans2) { cout << x << " "; } } ```
### Prompt Develop a solution in CPP to the problem described below: You are given an array a of n points in k-dimensional space. Let the distance between two points a_x and a_y be βˆ‘ _{i = 1}^{k} |a_{x, i} - a_{y, i}| (it is also known as Manhattan distance). You have to process q queries of the following two types: * 1 i b_1 b_2 ... b_k β€” set i-th element of a to the point (b_1, b_2, ..., b_k); * 2 l r β€” find the maximum distance between two points a_i and a_j, where l ≀ i, j ≀ r. Input The first line contains two numbers n and k (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 5) β€” the number of elements in a and the number of dimensions of the space, respectively. Then n lines follow, each containing k integers a_{i, 1}, a_{i, 2}, ..., a_{i, k} (-10^6 ≀ a_{i, j} ≀ 10^6) β€” the coordinates of i-th point. The next line contains one integer q (1 ≀ q ≀ 2 β‹… 10^5) β€” the number of queries. Then q lines follow, each denoting a query. There are two types of queries: * 1 i b_1 b_2 ... b_k (1 ≀ i ≀ n, -10^6 ≀ b_j ≀ 10^6) β€” set i-th element of a to the point (b_1, b_2, ..., b_k); * 2 l r (1 ≀ l ≀ r ≀ n) β€” find the maximum distance between two points a_i and a_j, where l ≀ i, j ≀ r. There is at least one query of the second type. Output Print the answer for each query of the second type. Example Input 5 2 1 2 2 3 3 4 4 5 5 6 7 2 1 5 2 1 3 2 3 5 1 5 -1 -2 2 1 5 1 4 -1 -2 2 1 5 Output 8 4 4 12 10 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 8e5 + 10, M = 35; int n, k, q, seg[M][MAXN], a[MAXN]; void add(int ind, int val, int t, int b = 0, int e = n, int id = 1) { if (b + 1 == e) { seg[t][id] = val; return; } int mid = (b + e) / 2; if (ind < mid) add(ind, val, t, b, mid, id * 2); else add(ind, val, t, mid, e, id * 2 + 1); seg[t][id] = max(seg[t][id * 2], seg[t][id * 2 + 1]); return; } int get(int l, int r, int t, int b = 0, int e = n, int id = 1) { if (r <= b || e <= l) return -INT_MAX / 2; if (l <= b && e <= r) return seg[t][id]; int mid = (b + e) / 2; return max(get(l, r, t, b, mid, id * 2), get(l, r, t, mid, e, id * 2 + 1)); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> k; for (int i = 0; i < (1 << k); i++) for (int j = 0; j < MAXN; j++) seg[i][j] = -INT_MAX / 2; for (int i = 0; i < n; i++) { for (int j = 0; j < k; j++) cin >> a[j]; for (int m = 0; m < (1 << k); m++) { int x = 0; for (int j = 0; j < k; j++) { if ((m >> j) & 1) x += a[j]; else x -= a[j]; } add(i, x, m); } } cin >> q; while (q) { q--; int ty; cin >> ty; if (ty == 1) { int ind; cin >> ind, ind--; for (int i = 0; i < k; i++) cin >> a[i]; for (int i = 0; i < (1 << k); i++) { int x = 0; for (int j = 0; j < k; j++) { if ((i >> j) & 1) x += a[j]; else x -= a[j]; } add(ind, x, i); } } else { int l, r, ans = -INT_MAX / 2; cin >> l >> r, l--; for (int mask = 0; mask <= (1 << k) / 2; mask++) { ans = max(ans, get(l, r, mask) + get(l, r, (1 << k) - 1 - mask)); } cout << ans << endl; } } return 0; } ```
### Prompt Please provide a CPP coded solution to the problem described below: Vasya's got a birthday coming up and his mom decided to give him an array of positive integers a of length n. Vasya thinks that an array's beauty is the greatest common divisor of all its elements. His mom, of course, wants to give him as beautiful an array as possible (with largest possible beauty). Unfortunately, the shop has only one array a left. On the plus side, the seller said that he could decrease some numbers in the array (no more than by k for each number). The seller can obtain array b from array a if the following conditions hold: bi > 0; 0 ≀ ai - bi ≀ k for all 1 ≀ i ≀ n. Help mom find the maximum possible beauty of the array she will give to Vasya (that seller can obtain). Input The first line contains two integers n and k (1 ≀ n ≀ 3Β·105; 1 ≀ k ≀ 106). The second line contains n integers ai (1 ≀ ai ≀ 106) β€” array a. Output In the single line print a single number β€” the maximum possible beauty of the resulting array. Examples Input 6 1 3 6 10 12 13 16 Output 3 Input 5 3 8 21 52 15 77 Output 7 Note In the first sample we can obtain the array: 3 6 9 12 12 15 In the second sample we can obtain the next array: 7 21 49 14 77 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 300005; int a[maxn]; int n, m, ma, mi; int sum[2000005], ans[2000005]; bool ok(int mid) { int ans = 0, i; for (i = mid; i <= ma; i += mid) { ans += sum[i + m] - sum[i - 1]; } if (ans == n) return true; return false; } int main() { int i, j; scanf("%d %d", &n, &m); ma = 1, mi = 1000006; for (i = 0; i < n; i++) { scanf("%d", &a[i]); mi = min(mi, a[i]); ma = max(ma, a[i]); sum[a[i]]++; } if (m >= mi) { printf("%d\n", mi); return 0; } for (i = 1; i <= ma + m; i++) { sum[i] += sum[i - 1]; } for (i = mi; i > m; i--) { if (ok(i)) break; } printf("%d\n", i); return 0; } ```
### Prompt Generate a CPP solution to the following problem: In order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must. Little Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this... Given two integers p and k, find a polynomial f(x) with non-negative integer coefficients strictly less than k, whose remainder is p when divided by (x + k). That is, f(x) = q(x)Β·(x + k) + p, where q(x) is a polynomial (not necessarily with integer coefficients). Input The only line of input contains two space-separated integers p and k (1 ≀ p ≀ 1018, 2 ≀ k ≀ 2 000). Output If the polynomial does not exist, print a single integer -1, or output two lines otherwise. In the first line print a non-negative integer d β€” the number of coefficients in the polynomial. In the second line print d space-separated integers a0, a1, ..., ad - 1, describing a polynomial <image> fulfilling the given requirements. Your output should satisfy 0 ≀ ai < k for all 0 ≀ i ≀ d - 1, and ad - 1 β‰  0. If there are many possible solutions, print any of them. Examples Input 46 2 Output 7 0 1 0 0 1 1 1 Input 2018 214 Output 3 92 205 1 Note In the first example, f(x) = x6 + x5 + x4 + x = (x5 - x4 + 3x3 - 6x2 + 12x - 23)Β·(x + 2) + 46. In the second example, f(x) = x2 + 205x + 92 = (x - 9)Β·(x + 214) + 2018. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long p, k, ans[2018], cnt; int Write[20], WRI; void judge() { freopen(".in", "r", stdin); freopen(".out", "w", stdout); } int read() { int d = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') d = d * 10 + c - 48, c = getchar(); return d * f; } void write(int x) { if (!x) { putchar('0'); return; } if (x < 0) putchar('-'), x = -x; for (WRI = 1; x; x /= 10, WRI++) Write[WRI] = x % 10; for (int i = WRI - 1; i; i--) putchar((char)(Write[i] + 48)); } long long get() { long long x = p % k; if (x < 0) x += k; return x; } int main() { scanf("%lld%lld", &p, &k); for (; p; p /= (-k)) { ans[++cnt] = get(); p -= ans[cnt]; } printf("%lld\n", cnt); for (int i = 1; i <= cnt; i++) printf("%lld ", ans[i]); return 0; } ```
### Prompt Construct a cpp code solution to the problem outlined: One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from 1 to n. Let's assume that Misha chose number m, and Andrew chose number a. Then, by using a random generator they choose a random integer c in the range between 1 and n (any integer from 1 to n is chosen with the same probability), after which the winner is the player, whose number was closer to c. The boys agreed that if m and a are located on the same distance from c, Misha wins. Andrew wants to win very much, so he asks you to help him. You know the number selected by Misha, and number n. You need to determine which value of a Andrew must choose, so that the probability of his victory is the highest possible. More formally, you need to find such integer a (1 ≀ a ≀ n), that the probability that <image> is maximal, where c is the equiprobably chosen integer from 1 to n (inclusive). Input The first line contains two integers n and m (1 ≀ m ≀ n ≀ 109) β€” the range of numbers in the game, and the number selected by Misha respectively. Output Print a single number β€” such value a, that probability that Andrew wins is the highest. If there are multiple such values, print the minimum of them. Examples Input 3 1 Output 2 Input 4 3 Output 2 Note In the first sample test: Andrew wins if c is equal to 2 or 3. The probability that Andrew wins is 2 / 3. If Andrew chooses a = 3, the probability of winning will be 1 / 3. If a = 1, the probability of winning is 0. In the second sample test: Andrew wins if c is equal to 1 and 2. The probability that Andrew wins is 1 / 2. For other choices of a the probability of winning is less. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { long long int n, m; cin >> n >> m; long long int c1, c2; c1 = m - 1; c2 = n - m; if (n == 1) cout << 1; else if (c1 > c2) cout << --m; else if (c1 == c2) cout << --m; else cout << ++m; return 0; } ```
### Prompt Please formulate a CPP solution to the following problem: Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya has a number consisting of n digits without leading zeroes. He represented it as an array of digits without leading zeroes. Let's call it d. The numeration starts with 1, starting from the most significant digit. Petya wants to perform the following operation k times: find the minimum x (1 ≀ x < n) such that dx = 4 and dx + 1 = 7, if x is odd, then to assign dx = dx + 1 = 4, otherwise to assign dx = dx + 1 = 7. Note that if no x was found, then the operation counts as completed and the array doesn't change at all. You are given the initial number as an array of digits and the number k. Help Petya find the result of completing k operations. Input The first line contains two integers n and k (1 ≀ n ≀ 105, 0 ≀ k ≀ 109) β€” the number of digits in the number and the number of completed operations. The second line contains n digits without spaces representing the array of digits d, starting with d1. It is guaranteed that the first digit of the number does not equal zero. Output In the single line print the result without spaces β€” the number after the k operations are fulfilled. Examples Input 7 4 4727447 Output 4427477 Input 4 2 4478 Output 4478 Note In the first sample the number changes in the following sequence: 4727447 β†’ 4427447 β†’ 4427477 β†’ 4427447 β†’ 4427477. In the second sample: 4478 β†’ 4778 β†’ 4478. ### Response ```cpp #include <bits/stdc++.h> int main() { int n, k; char s[100010]; while (scanf("%d%d%s", &n, &k, s) != EOF) { for (int i = 0; i < n && k > 0; ++i) { if (s[i] == '4' && s[i + 1] == '7') { if (i > 0 && i % 2 == 1 && s[i - 1] == '4') { s[i] = (k % 2 == 0 ? '4' : '7'); break; } else { s[i] = s[i + 1] = (i % 2 == 0 ? '4' : '7'); } --k; } } puts(s); } return 0; } ```