text
stringlengths
424
69.5k
### Prompt Generate a cpp solution to the following problem: You are given a string s consisting only of lowercase Latin letters. You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it. Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not. You have to answer t independent queries. Input The first line of the input contains one integer t (1 ≀ t ≀ 100) β€” number of queries. Each of the next t lines contains one string. The i-th line contains a string s_i consisting only of lowercase Latin letter. It is guaranteed that the length of s_i is from 1 to 1000 (inclusive). Output Print t lines. In the i-th line print the answer to the i-th query: -1 if it is impossible to obtain a good string by rearranging the letters of s_i and any good string which can be obtained from the given one (by rearranging the letters) otherwise. Example Input 3 aa abacaba xdd Output -1 abaacba xdd Note In the first query we cannot rearrange letters to obtain a good string. Other examples (not all) of correct answers to the second query: "ababaca", "abcabaa", "baacaba". In the third query we can do nothing to obtain a good string. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int lim = 1e6; int inf = 1e9 + 7; bool ispal(string s) { int n = s.size(); bool ans = true; for (int i = 0; i < n / 2; i++) { if (s[i] != s[n - i - 1]) { ans = false; break; } } return ans; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; while (t--) { string s; cin >> s; if (!ispal(s)) { cout << s << '\n'; ; } else { char x = s[0]; bool check = false; string ans = s; for (int i = 1; i < s.size(); i++) { if (x != s[i]) { check = true; ans[0] = ans[i]; ans[i] = x; break; } } if (check) { cout << ans << '\n'; ; } else { cout << -1 << '\n'; ; } } } } ```
### Prompt Please create a solution in CPP to the following problem: We have N pieces of ropes, numbered 1 through N. The length of piece i is a_i. At first, for each i (1≀i≀N-1), piece i and piece i+1 are tied at the ends, forming one long rope with N-1 knots. Snuke will try to untie all of the knots by performing the following operation repeatedly: * Choose a (connected) rope with a total length of at least L, then untie one of its knots. Is it possible to untie all of the N-1 knots by properly applying this operation? If the answer is positive, find one possible order to untie the knots. Constraints * 2≀N≀10^5 * 1≀L≀10^9 * 1≀a_i≀10^9 * All input values are integers. Input The input is given from Standard Input in the following format: N L a_1 a_2 ... a_n Output If it is not possible to untie all of the N-1 knots, print `Impossible`. If it is possible to untie all of the knots, print `Possible`, then print another N-1 lines that describe a possible order to untie the knots. The j-th of those N-1 lines should contain the index of the knot that is untied in the j-th operation. Here, the index of the knot connecting piece i and piece i+1 is i. If there is more than one solution, output any. Examples Input 3 50 30 20 10 Output Possible 2 1 Input 2 21 10 10 Output Impossible Input 5 50 10 20 30 40 50 Output Possible 1 2 3 4 ### Response ```cpp #include <cstdio> #include <iostream> using namespace std; const int N = 120000; int a[N]; int main() { int n, l; cin >> n >> l; for(int i = 1; i <= n; i ++ ) cin >> a[i]; register int Cur = 1; while(Cur < n && a[Cur] + a[Cur+1] < l) Cur ++; if(Cur == n) { puts("Impossible"); return 0; } puts("Possible"); for(int i = 1; i < Cur; i ++ ) { printf("%d\n", i); } for(int i = n-1; i > Cur; i -- ) { printf("%d\n", i); } printf("%d\n", Cur); } ```
### Prompt Your challenge is to write a Cpp solution to the following problem: Input The only line of the input is a string of 7 characters. The first character is letter A, followed by 6 digits. The input is guaranteed to be valid (for certain definition of "valid"). Output Output a single integer. Examples Input A221033 Output 21 Input A223635 Output 22 Input A232726 Output 23 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { string s; cin >> s; int sum = 0; for (int i = 0; i < 7; i++) { if (s[i] == 'A') sum++; else if (s[i] == '1') sum += 10; else sum += s[i] - 48; } cout << sum << '\n'; return 0; } ```
### Prompt Generate a Cpp solution to the following problem: AtCoDeer the deer has N square tiles. The tiles are numbered 1 through N, and the number given to each tile is written on one side of the tile. Also, each corner of each tile is painted in one of the 1000 colors, which are represented by the integers 0 between 999. The top-left, top-right, bottom-right and bottom-left corner of the tile with the number i are painted in color C_{i,0}, C_{i,1}, C_{i,2} and C_{i,3}, respectively, when seen in the direction of the number written on the tile (See Figure 1). <image> Figure 1: The correspondence between the colors of a tile and the input AtCoDeer is constructing a cube using six of these tiles, under the following conditions: * For each tile, the side with the number must face outward. * For each vertex of the cube, the three corners of the tiles that forms it must all be painted in the same color. Help him by finding the number of the different cubes that can be constructed under the conditions. Since each tile has a number written on it, two cubes are considered different if the set of the used tiles are different, or the tiles are used in different directions, even if the formation of the colors are the same. (Each tile can be used in one of the four directions, obtained by 90Β° rotations.) Two cubes are considered the same only if rotating one in the three dimensional space can obtain an exact copy of the other, including the directions of the tiles. <image> Figure 2: The four directions of a tile Constraints * 6≦N≦400 * 0≦C_{i,j}≦999 (1≦i≦N , 0≦j≦3) Input The input is given from Standard Input in the following format: N C_{1,0} C_{1,1} C_{1,2} C_{1,3} C_{2,0} C_{2,1} C_{2,2} C_{2,3} : C_{N,0} C_{N,1} C_{N,2} C_{N,3} Output Print the number of the different cubes that can be constructed under the conditions. Examples Input 6 0 1 2 3 0 4 6 1 1 6 7 2 2 7 5 3 6 4 5 7 4 0 3 5 Output 1 Input 8 0 0 0 0 0 0 1 1 0 1 0 1 0 1 1 0 1 0 0 1 1 0 1 0 1 1 0 0 1 1 1 1 Output 144 Input 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Output 122880 ### Response ```cpp #include <bits/stdc++.h> using namespace std; typedef long long ll; tuple<int, int, int, int> mt(int *cc) { return make_tuple(cc[0], cc[1], cc[2], cc[3]); } void shift(int *cc, int k) { int hj[4]; for (int i = 0; i < 4; i++) hj[i] = cc[(i+k)%4]; for (int i = 0; i < 4; i++) cc[i] = hj[i]; } void normalize(int *cc) { int minidx; ll maxhsh = -1; for (int i = 0; i < 4; i++) { ll hsh = (ll)cc[0] + (ll)cc[1]*(1e3) + (ll)cc[2]*(1e6) + (ll)cc[3]*(1e9); if (hsh > maxhsh) { maxhsh = hsh; minidx = i; } shift(cc, 1); } shift(cc, minidx); } const int MAXN = 500; int c[MAXN][4]; map <tuple<int, int, int, int> , ll > m; map <tuple<int, int, int, int> , ll > mult; int main() { int n; cin >> n; for (int i = 0; i < n; i++) { for (int j = 0; j < 4; j++) cin >> c[i][j]; normalize(c[i]); if (c[i][0] == c[i][1] && c[i][0] == c[i][2] && c[i][0] == c[i][3]) mult[mt(c[i])] = 4; else if (c[i][0] == c[i][2] && c[i][1] == c[i][3]) mult[mt(c[i])] = 2; else mult[mt(c[i])] = 1; m[mt(c[i])]++; } ll ans = 0; for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) { m[mt(c[i])]--; m[mt(c[j])]--; for (int k = 0; k < 4; k++) { ll res = 1; int tile[4][4]; for (int l = 0; l < 4; l++) { //cout << i << " " << j << " " << k << " " << l << " " << m[make_tuple(6, 4, 5, 7)] << endl; tile[l][0] = c[i][l]; tile[l][1] = c[j][(-l+7)%4]; tile[l][2] = c[j][(-l+6)%4]; tile[l][3] = c[i][(l+1)%4]; normalize(tile[l]); res *= m[mt(tile[l])]* mult[mt(tile[l])]; m[mt(tile[l])]--; } for (int l = 0; l < 4; l++) m[mt(tile[l])]++; ans += res; shift(c[j], 1); } m[mt(c[i])]++; m[mt(c[j])]++; } } cout << ans/3; } ```
### Prompt Please create a solution in Cpp to the following problem: Takahashi has A cookies, and Aoki has B cookies. Takahashi will do the following action K times: * If Takahashi has one or more cookies, eat one of his cookies. * Otherwise, if Aoki has one or more cookies, eat one of Aoki's cookies. * If they both have no cookies, do nothing. In the end, how many cookies will Takahashi and Aoki have, respectively? Constraints * 0 \leq A \leq 10^{12} * 0 \leq B \leq 10^{12} * 0 \leq K \leq 10^{12} * All values in input are integers. Input Input is given from Standard Input in the following format: A B K Output Print the numbers of Takahashi's and Aoki's cookies after K actions. Examples Input 2 3 3 Output 0 2 Input 500000000000 500000000000 1000000000000 Output 0 0 ### Response ```cpp #include<bits/stdc++.h> using namespace std; int main() { long A,B,C; long d=0; cin>>A>>B>>C; if(A<C) cout<<0<<" "<<max(d,A+B-C)<<endl; else cout<<A-C<<" "<<B<<endl; } ```
### Prompt Your challenge is to write a cpp solution to the following problem: There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Currently, there are A_i stones placed on vertex i. Takahashi and Aoki will play a game using this tree. First, Takahashi will select a vertex and place a piece on it. Then, starting from Takahashi, they will alternately perform the following operation: * Remove one stone from the vertex currently occupied by the piece. * Then, move the piece to a vertex that is adjacent to the currently occupied vertex. The player who is left with no stone on the vertex occupied by the piece and thus cannot perform the operation, loses the game. Find all the vertices v such that Takahashi can place the piece on v at the beginning and win the game. Constraints * 2 ≦ N ≦ 3000 * 1 ≦ a_i,b_i ≦ N * 0 ≦ A_i ≦ 10^9 * The given graph is a tree. Input The input is given from Standard Input in the following format: N A_1 A_2 … A_N a_1 b_1 : a_{N-1} b_{N-1} Output Print the indices of the vertices v such that Takahashi can place the piece on v at the beginning and win the game, in a line, in ascending order. Examples Input 3 1 2 3 1 2 2 3 Output 2 Input 5 5 4 1 2 3 1 2 1 3 2 4 2 5 Output 1 2 Input 3 1 1 1 1 2 2 3 Output ### Response ```cpp #include <algorithm> #include <cstdio> #include <vector> #define pb push_back std::vector<int> adj[3005]; int arr[3005]; bool dfs(int u, int fa = -1) { for (int v : adj[u]) { if (v == fa) continue; if (arr[v] < arr[u] && !dfs(v, u)) return true; } return false; } int main() { // freopen("AGC010-F.in", "r", stdin); int n; scanf("%d", &n); std::for_each(arr, arr + n, [&] (int &x) { scanf("%d", &x); }); for (int i = 1; i < n; i++) { int u, v; scanf("%d%d", &u, &v); adj[--u].pb(--v); adj[v].pb(u); } for (int i = 0; i < n; i++) { if (dfs(i)) printf("%d ", i + 1); } return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself. Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank. There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation. Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero. Input The first line of the input contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of banks. The second line contains n integers ai ( - 109 ≀ ai ≀ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0. Output Print the minimum number of operations required to change balance in each bank to zero. Examples Input 3 5 0 -5 Output 1 Input 4 -1 0 1 0 Output 2 Input 4 1 2 3 -6 Output 3 Note In the first sample, Vasya may transfer 5 from the first bank to the third. In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first. In the third sample, the following sequence provides the optimal answer: 1. transfer 1 from the first bank to the second bank; 2. transfer 3 from the second bank to the third; 3. transfer 6 from the third bank to the fourth. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const int N = 1e5 + 5; map<long long, int> mp; int a[N]; int main() { int n; scanf("%d", &n); int ans = n - 1; long long sum = 0; for (int i = 1; i <= n; ++i) scanf("%d", &a[i]); int tmp = a[1]; for (int i = 1; i < n; ++i) a[i] = a[i + 1]; a[n] = tmp; for (int i = 1; i <= n; ++i) { sum += a[i]; ++mp[sum]; ans = min(ans, n - mp[sum]); } printf("%d\n", ans); return 0; } ```
### Prompt Please formulate a CPP solution to the following problem: If there is an integer not less than 0 satisfying the following conditions, print the smallest such integer; otherwise, print `-1`. * The integer has exactly N digits in base ten. (We assume 0 to be a 1-digit integer. For other integers, leading zeros are not allowed.) * The s_i-th digit from the left is c_i. \left(i = 1, 2, \cdots, M\right) Constraints * All values in input are integers. * 1 \leq N \leq 3 * 0 \leq M \leq 5 * 1 \leq s_i \leq N * 0 \leq c_i \leq 9 Input Input is given from Standard Input in the following format: N M s_1 c_1 \vdots s_M c_M Output Print the answer. Examples Input 3 3 1 7 3 2 1 7 Output 702 Input 3 2 2 1 2 3 Output -1 Input 3 1 1 0 Output -1 ### Response ```cpp #include<bits/stdc++.h> using namespace std; int n,m; int ans[10]; int main(){ memset(ans,-1,sizeof(ans)); scanf("%d%d",&n,&m); while(m--){ int s,c; scanf("%d%d",&s,&c); if(ans[s] == -1){ ans[s] = c; } else if(ans[s] != c){ printf("-1\n"); return 0; } } if(ans[1] == 0 && n > 1){ printf("-1\n"); return 0; } if(ans[1] == -1) { if(n == 1) ans[1] = 0; else ans[1] = 1; } for(int i=1;i<=n;i++){ if(ans[i] == -1) ans[i] = 0; printf("%d",ans[i]); } printf("\n"); return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. <image> Recently Xenia has bought n_r red gems, n_g green gems and n_b blue gems. Each of the gems has a weight. Now, she is going to pick three gems. Xenia loves colorful things, so she will pick exactly one gem of each color. Xenia loves balance, so she will try to pick gems with little difference in weight. Specifically, supposing the weights of the picked gems are x, y and z, Xenia wants to find the minimum value of (x-y)^2+(y-z)^2+(z-x)^2. As her dear friend, can you help her? Input The first line contains a single integer t (1≀ t ≀ 100) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers n_r,n_g,n_b (1≀ n_r,n_g,n_b≀ 10^5) β€” the number of red gems, green gems and blue gems respectively. The second line of each test case contains n_r integers r_1,r_2,…,r_{n_r} (1≀ r_i ≀ 10^9) β€” r_i is the weight of the i-th red gem. The third line of each test case contains n_g integers g_1,g_2,…,g_{n_g} (1≀ g_i ≀ 10^9) β€” g_i is the weight of the i-th green gem. The fourth line of each test case contains n_b integers b_1,b_2,…,b_{n_b} (1≀ b_i ≀ 10^9) β€” b_i is the weight of the i-th blue gem. It is guaranteed that βˆ‘ n_r ≀ 10^5, βˆ‘ n_g ≀ 10^5, βˆ‘ n_b ≀ 10^5 (the sum for all test cases). Output For each test case, print a line contains one integer β€” the minimum value which Xenia wants to find. Example Input 5 2 2 3 7 8 6 3 3 1 4 1 1 1 1 1 1000000000 2 2 2 1 2 5 4 6 7 2 2 2 1 2 3 4 6 7 3 4 1 3 2 1 7 3 3 4 6 Output 14 1999999996000000002 24 24 14 Note In the first test case, Xenia has the following gems: <image> If she picks the red gem with weight 7, the green gem with weight 6, and the blue gem with weight 4, she will achieve the most balanced selection with (x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14. ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename Arg1> void __f(const char* name, Arg1&& arg1) { cerr << name << " : " << arg1 << '\n'; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args) { const char* comma = strchr(names + 1, ','); cout.write(names, comma - names) << " : " << arg1 << " | "; __f(comma + 1, args...); } long long pows(long long a, long long b) { long long res = 1; while (b > 0) { if (b & 1) res = res * a; a = a * a; b >>= 1; } return res; } long long powm(long long x, long long y, long long m = 1000000007) { x = x % m; long long res = 1; while (y) { if (y & 1) res = res * x; res %= m; y = y >> 1; x = x * x; x %= m; } return res; } long long modInverse(long long a, long long m = 1000000007) { if (m == 1) return 0; long long m0 = m, y = 0, x = 1; while (a > 1) { long long q = a / m, t = m; m = a % m, a = t; t = y; y = x - q * y; x = t; } if (x < 0) x += m0; return x; } long long fa = 9e18; void calc(set<long long> st1, set<long long> st2, set<long long> st3) { for (auto i : st1) { long long x = i; auto it1 = st2.lower_bound(x); set<long long> gr, bl; if (it1 != st2.end()) { gr.insert(*it1); } if (it1 != st2.begin()) { it1--; gr.insert(*it1); } auto it2 = st2.upper_bound(x); if (it2 != st2.end()) { gr.insert(*it2); } it1 = st3.lower_bound(x); if (it1 != st3.end()) { bl.insert(*it1); } if (it1 != st3.begin()) { it1--; bl.insert(*it1); } it2 = st3.upper_bound(x); if (it2 != st3.end()) { bl.insert(*it2); } for (auto j : gr) { it1 = st3.lower_bound(j); if (it1 != st3.end()) { bl.insert(*it1); } if (it1 != st3.begin()) { it1--; bl.insert(*it1); } it2 = st3.upper_bound(j); if (it2 != st3.end()) { bl.insert(*it2); } } if (gr.size() > 0 && bl.size() > 0) { for (auto j : gr) { for (auto k : bl) { long long p = (x - j) * (x - j) + (j - k) * (j - k) + (k - x) * (k - x); fa = min(fa, p); } } } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long T; cin >> T; while (T--) { long long n, m, i, j, k, x, y, z, t, e, f, p, q, g, l, r, w, h, count1 = 0, prod = 1, a, b, c, d, index, x1, x2, y1, y2, diff, ans = 0, sum = 0, sum1 = 0, sum2 = 0, flag = 0, flag1 = 0, flag2 = 0; string s, s1, s2; cin >> a >> b >> c; fa = 9e18; set<long long> red, blue, green; for (i = 0; i < a; i++) { cin >> x; red.insert(x); } for (i = 0; i < b; i++) { cin >> a; green.insert(a); } for (i = 0; i < c; i++) { cin >> a; blue.insert(a); } calc(red, green, blue); calc(red, blue, green); calc(blue, green, red); calc(blue, red, green); calc(green, red, blue); calc(green, blue, red); cout << fa << "\n"; } } ```
### Prompt Please formulate a CPP solution to the following problem: Omkar and Akmar are playing a game on a circular board with n (2 ≀ n ≀ 10^6) cells. The cells are numbered from 1 to n so that for each i (1 ≀ i ≀ n-1) cell i is adjacent to cell i+1 and cell 1 is adjacent to cell n. Initially, each cell is empty. Omkar and Akmar take turns placing either an A or a B on the board, with Akmar going first. The letter must be placed on an empty cell. In addition, the letter cannot be placed adjacent to a cell containing the same letter. A player loses when it is their turn and there are no more valid moves. Output the number of possible distinct games where both players play optimally modulo 10^9+7. Note that we only consider games where some player has lost and there are no more valid moves. Two games are considered distinct if the number of turns is different or for some turn, the letter or cell number that the letter is placed on were different. A move is considered optimal if the move maximizes the player's chance of winning, assuming the other player plays optimally as well. More formally, if the player who has to move has a winning strategy, they have to make a move after which they will still have a winning strategy. If they do not, they can make any move. Input The only line will contain an integer n (2 ≀ n ≀ 10^6) β€” the number of cells on the board. Output Output a single integer β€” the number of possible distinct games where both players play optimally modulo 10^9+7. Examples Input 2 Output 4 Input 69420 Output 629909355 Input 42069 Output 675837193 Note For the first sample case, the first player has 4 possible moves. No matter what the first player plays, the second player only has 1 possible move, so there are 4 possible games. ### Response ```cpp #define _CRT_SECURE_NO_WARNINGS #include <vector> #include <string> #include <map> #include <queue> #include <unordered_map> #include <unordered_set> #include <cassert> #include <complex> #include <cstdio> #include <iostream> #include <iomanip> #include <cmath> #include <functional> #include <algorithm> #include <stack> #include <numeric> #include <set> #include <chrono> #include <random> #define all(X) (X).begin(), (X).end() #define int long long #define m_p make_pair #define endl '\n' using namespace std; mt19937_64 rnd(std::chrono::system_clock::now().time_since_epoch().count()); const int MAXN = 1e6 + 100, mod = 1e9 + 7; int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } void extgcd(int a, int b, int &x, int &y) { if (b == 0) { x = 1; y = 0; return; } else { extgcd(b, a % b, x, y); int temp = y; y = x - (a / b) * y; x = temp; } } int inv(int a, int mod) { int x, y; extgcd(a, mod, x, y); x = (x % mod + mod) % mod; return x; } int f[MAXN]; int c(int n, int k) { if (n < 0 || n < 0 || n - k < 0) return 0; return (f[n] * inv(f[n - k] * f[k], mod)) % mod; } signed main() { ios::sync_with_stdio(0); cin.tie(0); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); #endif int n; cin >> n; f[0] = 1; for (int i = 1; i <= n; i++) f[i] = (f[i - 1] * i) % mod; int ans = 0; for (int k = 0; k <= n; k++) { if ((n - k) % 2) continue; ans += (f[n - k] * ((2 * c(n - k - 1, k) + 4 * c(n - k - 1, k - 1)) % mod)) % mod; ans %= mod; } cout << ans; return 0; } ```
### Prompt Your challenge is to write a Cpp solution to the following problem: AtCoder Inc. has decided to lock the door of its office with a 3-digit PIN code. The company has an N-digit lucky number, S. Takahashi, the president, will erase N-3 digits from S and concatenate the remaining 3 digits without changing the order to set the PIN code. How many different PIN codes can he set this way? Both the lucky number and the PIN code may begin with a 0. Constraints * 4 \leq N \leq 30000 * S is a string of length N consisting of digits. Input Input is given from Standard Input in the following format: N S Output Print the number of different PIN codes Takahashi can set. Examples Input 4 0224 Output 3 Input 6 123123 Output 17 Input 19 3141592653589793238 Output 329 ### Response ```cpp #include <bits/stdc++.h> using namespace std; using ll = long long; int N; string S; bool ok(string t) { while(t.length()<3) t="0"+t; int idx = 0; for(int i=0;i<N;++i){ if(S[i]==t[idx]){ idx++; if(idx == 3) return true; } } return false; } void solve() { int ans = 0; for(int i=0;i<=999;++i){ if(ok(to_string(i))) ans++; } cout << ans << "\n"; } int main() { cin >> N >> S; solve(); return 0; } ```
### Prompt Please provide a Cpp coded solution to the problem described below: Vasilisa the Wise from a far away kingdom got a present from her friend Helga the Wise from a farther away kingdom. The present is a surprise box, yet Vasilisa the Wise doesn't know yet what the surprise actually is because she cannot open the box. She hopes that you can help her in that. The box's lock is constructed like that. The box itself is represented by an absolutely perfect black cube with the identical deepening on each face (those are some foreign nanotechnologies that the far away kingdom scientists haven't dreamt of). The box is accompanied by six gems whose form matches the deepenings in the box's faces. The box can only be opened after it is correctly decorated by the gems, that is, when each deepening contains exactly one gem. Two ways of decorating the box are considered the same if they can be obtained one from the other one by arbitrarily rotating the box (note that the box is represented by a perfect nanotechnological cube) Now Vasilisa the Wise wants to know by the given set of colors the following: in how many ways would she decorate the box in the worst case to open it? To answer this question it is useful to know that two gems of one color are indistinguishable from each other. Help Vasilisa to solve this challenging problem. Input The first line contains exactly 6 characters without spaces from the set {R, O, Y, G, B, V} β€” they are the colors of gems with which the box should be decorated. Output Print the required number of different ways to decorate the box. Examples Input YYYYYY Output 1 Input BOOOOB Output 2 Input ROYGBV Output 30 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 200000; const long long MOD = 1e9 + 7; const double eps = 1e-9; char s[7]; vector<char> a; set<string> all; int op[3][2] = {{0, 1}, {4, 2}, {3, 5}}; int op2[3][4] = {{2, 3, 4, 5}, {0, 3, 1, 5}, {0, 2, 1, 4}}; void rotate(int l, int r) { char t = a[l]; for (int i = l; i < r; i++) a[i] = a[i + 1]; a[r] = t; } string get() { string s = ""; for (int i = 0; i < a.size(); i++) s += char(a[i]); return s; } int main() { scanf("%s", s); int p[6] = {0, 1, 2, 3, 4, 5}; do { bool f = 1; for (int x = 0; x < 3 && f; x++) { a.clear(); a.push_back(s[p[op[x][0]]]); a.push_back(s[p[op[x][1]]]); for (int i = 0; i < 4; i++) a.push_back(s[p[op2[x][i]]]); for (int i = 0; i < 2 && f; i++) { for (int j = 0; j < 4; j++) { if (all.find(get()) != all.end()) { f = 0; break; } rotate(2, 5); } swap(a[0], a[1]); reverse(a.begin() + 2, a.end()); } } if (f) all.insert(get()); } while (next_permutation(p, p + 6)); printf("%d\n", all.size()); return 0; } ```
### Prompt In Cpp, your task is to solve the following problem: Entrance Examination The International Competitive Programming College (ICPC) is famous for its research on competitive programming. Applicants to the college are required to take its entrance examination. The successful applicants of the examination are chosen as follows. * The score of any successful applicant is higher than that of any unsuccessful applicant. * The number of successful applicants n must be between nmin and nmax, inclusive. We choose n within the specified range that maximizes the gap. Here, the gap means the difference between the lowest score of successful applicants and the highest score of unsuccessful applicants. * When two or more candidates for n make exactly the same gap, use the greatest n among them. Let's see the first couple of examples given in Sample Input below. In the first example, nmin and nmax are two and four, respectively, and there are five applicants whose scores are 100, 90, 82, 70, and 65. For n of two, three and four, the gaps will be 8, 12, and 5, respectively. We must choose three as n, because it maximizes the gap. In the second example, nmin and nmax are two and four, respectively, and there are five applicants whose scores are 100, 90, 80, 75, and 65. For n of two, three and four, the gap will be 10, 5, and 10, respectively. Both two and four maximize the gap, and we must choose the greatest number, four. You are requested to write a program that computes the number of successful applicants that satisfies the conditions. Input The input consists of multiple datasets. Each dataset is formatted as follows. > m nmin nmax > P1 > P2 > ... > Pm > The first line of a dataset contains three integers separated by single spaces. m represents the number of applicants, nmin represents the minimum number of successful applicants, and nmax represents the maximum number of successful applicants. Each of the following m lines contains an integer Pi, which represents the score of each applicant. The scores are listed in descending order. These numbers satisfy 0 < nmin < nmax < m ≀ 200, 0 ≀ Pi ≀ 10000 (1 ≀ i ≀ m) and Pnmin > Pnmax+1. These ensure that there always exists an n satisfying the conditions. The end of the input is represented by a line containing three zeros separated by single spaces. Output For each dataset, output the number of successful applicants in a line. Sample Input 5 2 4 100 90 82 70 65 5 2 4 100 90 80 75 65 3 1 2 5000 4000 3000 4 2 3 10000 10000 8000 8000 4 2 3 10000 10000 10000 8000 5 2 3 100 80 68 60 45 0 0 0 Output for the Sample Input 3 4 2 2 3 2 Example Input 5 2 4 100 90 82 70 65 5 2 4 100 90 80 75 65 3 1 2 5000 4000 3000 4 2 3 10000 10000 8000 8000 4 2 3 10000 10000 10000 8000 5 2 3 100 80 68 60 45 0 0 0 Output 3 4 2 2 3 2 ### Response ```cpp #include<bits/stdc++.h> using namespace std; bool compare(int a, int b){ return (a > b); } int s[10000]; int main(){ while(true){ int a,b,c,d,e,f; cin >> a >> b >> c; if(a==0&&b==0&&c==0){ break; } for(int n=0;n<a;n++){ cin >> d; s[n]=d; } sort(s,s+a, compare); a=0; for(int m=b;m<=c;m++){ e=s[m-1]-s[m]; if(a<=e){ a=e; f=m; } } printf("%d\n",f); } } ```
### Prompt Generate a Cpp solution to the following problem: Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems. You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all edges on the simple path between u and v. For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -0.5 on the path from 4 to 5. <image> Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations? Leaf is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice. Input The first line contains a single integer n (2 ≀ n ≀ 10^5) β€” the number of nodes. Each of the next n-1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree. Output If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO". Otherwise, output "YES". You can print each letter in any case (upper or lower). Examples Input 2 1 2 Output YES Input 3 1 2 2 3 Output NO Input 5 1 2 1 3 1 4 2 5 Output NO Input 6 1 2 1 3 1 4 2 5 2 6 Output YES Note In the first example, we can add any real x to the value written on the only edge (1, 2). <image> In the second example, one of configurations that we can't reach is 0 written on (1, 2) and 1 written on (2, 3). <image> Below you can see graphs from examples 3, 4: <image> <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 5; int read() { int x = 0, w = 1; char ch = 0; while (ch < '0' || ch > '9') { if (ch == '-') w = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + (ch - '0'); ch = getchar(); } return x * w; } vector<int> v[maxn]; int main() { int n; scanf("%d", &n); for (int i = 1; i < n; ++i) { int a, b; a = read(); b = read(); v[a].push_back(b); v[b].push_back(a); } for (int i = 1; i <= n; ++i) { if (v[i].size() == 2) { printf("NO\n"); return 0; } } printf("YES\n"); return 0; } ```
### Prompt Please create a solution in CPP to the following problem: There is a triangle formed by three points $(x_1, y_1)$, $(x_2, y_2)$, $(x_3, y_3)$ on a plain. Write a program which prints "YES" if a point $P$ $(x_p, y_p)$ is in the triangle and "NO" if not. Constraints You can assume that: * $ -100 \leq x_1, y_1, x_2, y_2, x_3, y_3, x_p, y_p \leq 100$ * 1.0 $\leq$ Length of each side of a tringle * 0.001 $\leq$ Distance between $P$ and each side of a triangle Input Input consists of several datasets. Each dataset consists of: $x_1$ $y_1$ $x_2$ $y_2$ $x_3$ $y_3$ $x_p$ $y_p$ All the input are real numbers. Input ends with EOF. The number of datasets is less than or equal to 100. Output For each dataset, print "YES" or "NO" in a line. Example Input 0.0 0.0 2.0 0.0 2.0 2.0 1.5 0.5 0.0 0.0 1.0 4.0 5.0 3.0 -1.0 3.0 Output YES NO ### Response ```cpp #include <iostream> #include <stdlib.h> #include <math.h> using namespace std; int main() { double x1, y1, x2, y2, x3, y3, xp ,yp,ss,s1,s2,s3; while(cin>>x1>>y1>>x2>>y2>>x3>>y3>>xp>>yp){ ss=fabs((x3-x1)*(y2-y1)-(x2-x1)*(y3-y1)); s1=fabs((x3-xp)*(y2-yp)-(x2-xp)*(y3-yp)); s2=fabs((x3-xp)*(y1-yp)-(x1-xp)*(y3-yp)); s3=fabs((x2-xp)*(y1-yp)-(x1-xp)*(y2-yp)); if(fabs(s1+s2+s3-ss)<0.001){ cout<<"YES"<<endl; } else{ cout<<"NO"<<endl; }} return 0; } ```
### Prompt Develop a solution in CPP to the problem described below: Maria participates in a bicycle race. The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west. Let's introduce a system of coordinates, directing the Ox axis from west to east, and the Oy axis from south to north. As a starting position of the race the southernmost point of the track is selected (and if there are several such points, the most western among them). The participants start the race, moving to the north. At all straight sections of the track, the participants travel in one of the four directions (north, south, east or west) and change the direction of movement only in bends between the straight sections. The participants, of course, never turn back, that is, they do not change the direction of movement from north to south or from east to west (or vice versa). Maria is still young, so she does not feel confident at some turns. Namely, Maria feels insecure if at a failed or untimely turn, she gets into the water. In other words, Maria considers the turn dangerous if she immediately gets into the water if it is ignored. Help Maria get ready for the competition β€” determine the number of dangerous turns on the track. Input The first line of the input contains an integer n (4 ≀ n ≀ 1000) β€” the number of straight sections of the track. The following (n + 1)-th line contains pairs of integers (xi, yi) ( - 10 000 ≀ xi, yi ≀ 10 000). The first of these points is the starting position. The i-th straight section of the track begins at the point (xi, yi) and ends at the point (xi + 1, yi + 1). It is guaranteed that: * the first straight section is directed to the north; * the southernmost (and if there are several, then the most western of among them) point of the track is the first point; * the last point coincides with the first one (i.e., the start position); * any pair of straight sections of the track has no shared points (except for the neighboring ones, they share exactly one point); * no pair of points (except for the first and last one) is the same; * no two adjacent straight sections are directed in the same direction or in opposite directions. Output Print a single integer β€” the number of dangerous turns on the track. Examples Input 6 0 0 0 1 1 1 1 2 2 2 2 0 0 0 Output 1 Input 16 1 1 1 5 3 5 3 7 2 7 2 9 6 9 6 7 5 7 5 3 4 3 4 4 3 4 3 2 5 2 5 1 1 1 Output 6 Note The first sample corresponds to the picture: <image> The picture shows that you can get in the water under unfortunate circumstances only at turn at the point (1, 1). Thus, the answer is 1. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, i, b, a; int main() { cin >> n; for (i = 0; i < n; i++) cin >> a >> b; cout << (n - 4) / 2 << endl; } ```
### Prompt Generate a Cpp solution to the following problem: You are policeman and you are playing a game with Slavik. The game is turn-based and each turn consists of two phases. During the first phase you make your move and during the second phase Slavik makes his move. There are n doors, the i-th door initially has durability equal to a_i. During your move you can try to break one of the doors. If you choose door i and its current durability is b_i then you reduce its durability to max(0, b_i - x) (the value x is given). During Slavik's move he tries to repair one of the doors. If he chooses door i and its current durability is b_i then he increases its durability to b_i + y (the value y is given). Slavik cannot repair doors with current durability equal to 0. The game lasts 10^{100} turns. If some player cannot make his move then he has to skip it. Your goal is to maximize the number of doors with durability equal to 0 at the end of the game. You can assume that Slavik wants to minimize the number of such doors. What is the number of such doors in the end if you both play optimally? Input The first line of the input contains three integers n, x and y (1 ≀ n ≀ 100, 1 ≀ x, y ≀ 10^5) β€” the number of doors, value x and value y, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^5), where a_i is the initial durability of the i-th door. Output Print one integer β€” the number of doors with durability equal to 0 at the end of the game, if you and Slavik both play optimally. Examples Input 6 3 2 2 3 1 3 4 2 Output 6 Input 5 3 3 1 2 4 2 3 Output 2 Input 5 5 6 1 2 6 10 3 Output 2 Note Clarifications about the optimal strategy will be ignored. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int isPrime(int n) { for (int i = 2; i * i <= n; i++) { if (n % i == 0) return 0; } return 1; } int main() { int n, x, y; cin >> n >> x >> y; if (x > y) { cout << n; return 0; } int a[n]; int c = 0; for (int i = 0; i < n; i++) { cin >> a[i]; if (a[i] <= x) c++; } if (c < 2) { cout << c; return 0; } c = c + 1; c = c / 2; cout << c; return 0; } ```
### Prompt Generate a cpp solution to the following problem: You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k. Find the number of pairs of indexes (i, j) (1 ≀ i < j ≀ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≑ k mod p. Input The first line contains integers n, p, k (2 ≀ n ≀ 3 β‹… 10^5, 2 ≀ p ≀ 10^9, 0 ≀ k ≀ p-1). p is guaranteed to be prime. The second line contains n integers a_1, a_2, …, a_n (0 ≀ a_i ≀ p-1). It is guaranteed that all elements are different. Output Output a single integer β€” answer to the problem. Examples Input 3 3 0 0 1 2 Output 1 Input 6 7 2 1 2 3 4 5 6 Output 3 Note In the first example: (0+1)(0^2 + 1^2) = 1 ≑ 1 mod 3. (0+2)(0^2 + 2^2) = 8 ≑ 2 mod 3. (1+2)(1^2 + 2^2) = 15 ≑ 0 mod 3. So only 1 pair satisfies the condition. In the second example, there are 3 such pairs: (1, 5), (2, 3), (4, 6). ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 3e5 + 11; long long a[maxn]; int main() { int n; long long p, k; scanf("%d %lld %lld", &n, &p, &k); int cnt = 0; for (int i = 1; i <= n; i++) { long long x; scanf("%lld", &x); a[++cnt] = (x * (((((x * x) % p) * x) % p - k + p) % p)) % p; } sort(a + 1, a + 1 + cnt); long long ans = 0; long long tmp = 1; long long last = a[1]; for (int i = 2; i <= cnt; i++) if (a[i] == last) tmp++; else { last = a[i]; if (tmp > 1) ans += (tmp - 1) * tmp / 2; tmp = 1; } if (tmp > 1) ans += (tmp - 1) * tmp / 2; printf("%lld\n", ans); } ```
### Prompt Create a solution in cpp for the following problem: Luba thinks about watering her garden. The garden can be represented as a segment of length k. Luba has got n buckets, the i-th bucket allows her to water some continuous subsegment of garden of length exactly ai each hour. Luba can't water any parts of the garden that were already watered, also she can't water the ground outside the garden. Luba has to choose one of the buckets in order to water the garden as fast as possible (as mentioned above, each hour she will water some continuous subsegment of length ai if she chooses the i-th bucket). Help her to determine the minimum number of hours she has to spend watering the garden. It is guaranteed that Luba can always choose a bucket so it is possible water the garden. See the examples for better understanding. Input The first line of input contains two integer numbers n and k (1 ≀ n, k ≀ 100) β€” the number of buckets and the length of the garden, respectively. The second line of input contains n integer numbers ai (1 ≀ ai ≀ 100) β€” the length of the segment that can be watered by the i-th bucket in one hour. It is guaranteed that there is at least one bucket such that it is possible to water the garden in integer number of hours using only this bucket. Output Print one integer number β€” the minimum number of hours required to water the garden. Examples Input 3 6 2 3 5 Output 2 Input 6 7 1 2 3 4 5 6 Output 7 Note In the first test the best option is to choose the bucket that allows to water the segment of length 3. We can't choose the bucket that allows to water the segment of length 5 because then we can't water the whole garden. In the second test we can choose only the bucket that allows us to water the segment of length 1. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MX = 200020; const int N = 1000060; const int mod = (int)1e9 + 7; int bc[1111][1111]; int main() { cin.tie(0); cin.sync_with_stdio(0); int n, k; cin >> n >> k; int a[n]; for (int i = 0; i < n; ++i) { cin >> a[i]; } sort(a, a + n); for (int i = n - 1; i >= 0; --i) { if (k % a[i] == 0) { cout << k / a[i] << endl; return 0; } } return 0; } ```
### Prompt Generate a CPP solution to the following problem: In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck). The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table: <image> You are given a string. Output a program in the described language which prints this string. You can download the language interpreter used for judging here: <https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp> (use C++11 to compile the code). Note several implementation details: * The first step of the language interpretation is conversion to a Brainfuck program, which is then executed. * The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters. * The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line. * Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256. * Console input (, command) is allowed in Brainfuck code but has no effect when executed. Input The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive. Output Output a program in the described language which, when executed, will print the given message. Example Input $$$ Output .......X....... ......XXX...... .....XXXXX..... ....XXXXXXX.... ...XXXXXXXXX... ..XXXXXXXXXXX.. .XXXXXXXXXXXXX. ............... X.............X X.............. X.............. X.............. Note The example corresponds to the following Brainfuck program: - >+< >+++< >+++++< >+++++++< >+++++++++< >+++++++++++< < > . . . The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = (int)(2e5 + 5); string second; char last; void go(char x) { while (last != x) { if (last & 1) cout << "X.\n"; else cout << ".X\n"; last--; } if (last & 1) cout << ".X\n"; else cout << "X.\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(); cin >> second; cout << "..\n"; for (int i = 0; i < second.length(); i++) go(second[i]); return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample. Limak will repeat the following operation till everything is destroyed. Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time. Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. Input The first line contains single integer n (1 ≀ n ≀ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≀ hi ≀ 109) β€” sizes of towers. Output Print the number of operations needed to destroy all towers. Examples Input 6 2 1 4 6 2 2 Output 3 Input 7 3 3 3 1 3 3 3 Output 2 Note The picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. <image> After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int M = 100007; int t[M], pre[M]; int main() { int n; scanf("%d", &n); int maksi = 0; for (int i = 0; i < n; i++) scanf("%d", &t[i]); t[0] = 1; t[n - 1] = 1; pre[0] = 0; for (int i = 1; i < n; i++) t[i] = min(t[i], t[i - 1] + 1); for (int i = n - 2; i >= 0; i--) t[i] = min(t[i], t[i + 1] + 1); for (int i = 0; i < n; i++) maksi = max(maksi, t[i]); printf("%d\n", maksi); } ```
### Prompt Your challenge is to write a cpp solution to the following problem: Ataru Oafoot of Aizu Gakuen University High School decided to play with a slot machine. When you insert a medal on this machine, three reels will start spinning and each reel will stop automatically. In a normal game (normal game), 3 medals are inserted, and when the symbols are aligned, the following medals are obtained according to the symbols. <image> A special service will be started depending on how the patterns are aligned. A big bonus starts when you have 3 of 7 symbols, and you can play 5 bonus games. Also, when you have 3 BAR symbols, the regular bonus will start and you can play 3 bonus games. If you have 3 star symbols, the free game will start and you will not be able to get medals, but you can start the next game without inserting medals. During the bonus game, if you insert 2 medals per game, you will automatically get 3 grape patterns and 15 medals. Oafoot started playing on the machine with 100 medals. After playing for a while, it ended in a normal game. How many medals did you have left? Create a program that inputs play information and outputs the number of medals left at hand. The play information is given as the number of big bonuses b, the number of regular bonuses r, the number of grapes aligned during a normal game g, the number of cherries aligned c, the number of stars aligned s, and the total number of games t. Note that t includes the number of bonus games. Also, medals will not disappear in the middle of the game. Input A sequence of multiple datasets is given as input. The end of the input is indicated by a zero line. Each dataset is given in the following format: b r g c s t b, r, g, c, and s are integers greater than or equal to 0 and less than 200, and t is an integer less than or equal to 1000. The number of datasets does not exceed 120. Output For each input dataset, the number of medals remaining at hand is output on one line. Example Input 3 2 30 3 26 226 9 0 18 3 20 118 5 5 12 2 15 203 7 4 19 2 22 197 7 4 24 4 17 209 0 0 0 0 0 0 Output 127 793 414 629 617 ### Response ```cpp #include <bits/stdc++.h> #define rep(i,l,n) for(int i=l;i<n;i++) #define rer(i,l,n) for(int i=l;i<=n;i++) #define all(a) a.begin(),a.end() #define o(a) cout<<a<<endl #define pb(a) push_back(a) #define mk(a,b) make_pair(a,b) #define fi first #define se second using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<vi> vvi; typedef pair<int,int> pii; int main(){ int b,r,g,c,s,t; while(1){ cin>>b>>r>>g>>c>>s>>t; if(b==0 && r==0 && g==0 && c==0 && s==0 && t==0) break; o(100+15*(b+r)+7*g+2*c+13*(5*b+3*r)-3*(t-5*b-3*r-s)); } } ```
### Prompt In cpp, your task is to solve the following problem: Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO". ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename T, typename TT> ostream &operator<<(ostream &s, pair<T, TT> t) { return s << "(" << t.first << "," << t.second << ")"; } template <typename T> ostream &operator<<(ostream &s, vector<T> t) { s << "{"; for (int i = 0; i < t.size(); i++) s << t[i] << (i == t.size() - 1 ? "" : ","); return s << "}" << endl; } map<string, int> ile; int vow[300]; int cnt(string g) { int w = 0; for (int i = 0; i < g.size(); i++) w += vow[g[i]]; return w; } int main() { ios_base::sync_with_stdio(0); vow['e'] = 1; vow['i'] = 1; vow['o'] = 1; vow['u'] = 1; vow['a'] = 1; int n, k; cin >> n >> k; for (int i = 0; i < n; i++) { string s[4]; for (int j = 0; j < 4; j++) cin >> s[j]; int sam[4]; for (int j = 0; j < 4; j++) sam[j] = cnt(s[j]); bool ok = 1; for (int j = 0; j < 4; j++) { if (sam[j] < k) ok = 0; } if (!ok) break; for (int j = 0; j < 4; j++) { int z = s[j].size(); int mam = 0; while (mam < k) { z--; mam += vow[s[j][z]]; } s[j] = s[j].substr(z); } if (s[0] == s[1] && s[2] == s[3]) ile["aabb"]++; if (s[0] == s[3] && s[2] == s[1]) ile["abba"]++; if (s[0] == s[2] && s[1] == s[3]) ile["abab"]++; if (s[0] == s[1] && s[2] == s[3] && s[2] == s[1]) ile["aaaa"]++; } if (ile["aaaa"] == n) { cout << "aaaa"; return 0; } for (typeof(ile.begin()) i = ile.begin(); i != ile.end(); i++) { if (i->second == n) { cout << i->first; return 0; } } cout << "NO"; return 0; } ```
### Prompt Please create a solution in Cpp to the following problem: There is a game called Sim Forest 2013. In this game, the player can become a forest god and raise forest animals. Animals hatch from eggs and breed. When certain conditions are met, eggs are mutated with a certain probability to give birth to new races of animals. There is an animal encyclopedia in this game, and when you get a new kind of animal, it will be recorded in the animal dictionary. Mori is an enthusiastic player of Sim Forest 2013. His animal dictionary is complete when the remaining one race is filled. Mori decided to obtain this remaining one race by mutation from the egg. The game progress is as follows. * N eggs will appear at the beginning of the stage. * N eggs hatch s minutes after the start of the stage. * Each egg has a 1 / p chance of targeting on a specific day of the week and within a specific time zone during the entire period * from appearance to hatching * (including the time of appearance and the moment of hatching). Mutates in animals. * The stage ends t minutes after the start of the stage, and the same stage starts immediately after that (starts with n eggs. The elapsed time is not reset). * The stage is repeated m times in a row. This game meets the following specifications. * Animals born from eggs do not lay eggs. * Eggs hatch only once per stage, s minutes after the start of the stage. * Mr. Sori can set the start day and start time of the first stage as desired. (The start time of the second and subsequent stages will be immediately after the end of the previous stage) * One of {all days, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday} is given as a mutable day. * One of {all time zones, morning, night} is given as a mutable time zone. Inputs are s, n, t, mutable day / time zone, p, m. Find the probability when you set the start day and start time of the first stage so that the probability of mutation occurring by the end of all stages is maximized. Input The input consists of multiple datasets. Each dataset is given in the following format: s n t weekday time p m Each dataset shows the time it takes for an egg to hatch from the start of the stage s, the number of eggs that appear at the start of the stage n, the time it takes to finish one stage t, the mutable day weekday, the mutable Time zone time, reciprocal of mutation probability p (mutation probability is 1 / p), total number of stages m. The input satisfies the following constraints. * 0 <s <= 500 * 0 <n <= 100 * s <t <= 1000 * weekday ∈ {All, Sun, Mon, Tue, Wed, Thu, Fri, Sat} * All means all days of the week * time ∈ {All, Day, Night} * All means [0: 00 ~ 24: 00), Day means [6: 00 ~ 18: 00), and Night means [18: 00 ~ 6: 00). * 1 <= p <= 99999 * 1 <= m <= 100 The end of the input is given on the following line. 0 0 0 None None 0 0 Output For each dataset, output the probability when the start day and start time of the first stage is set so that the probability of mutation occurring by the end of all stages is maximized. The error in the answer must not exceed 0.00000001 (10-8). Any number of digits after the decimal point may be output as long as the precision conditions are met. Sample Input 1 1 3 All All 1 1 2 37 5 All Night 150 1 16 2 20 All Day 5 10 1 14 15 Mon All 20000 100 0 0 0 None None 0 0 Output for Sample Input 1.0000000000 0.2192439716 0.9884707850 0.0649933899 Example Input 1 1 3 All All 1 1 2 37 5 All Night 150 1 16 2 20 All Day 5 10 1 14 15 Mon All 20000 100 0 0 0 None None 0 0 Output 1.0000000000 0.2192439716 0.9884707850 0.0649933899 ### Response ```cpp #define _USE_MATH_DEFINES #define INF 0x3f3f3f3f #include <iostream> #include <cstdio> #include <sstream> #include <cmath> #include <cstdlib> #include <algorithm> #include <queue> #include <stack> #include <limits> #include <map> #include <string> #include <cstring> #include <set> #include <deque> #include <bitset> #include <list> #include <cctype> #include <utility> using namespace std; typedef long long ll; typedef pair <int,int> P; typedef pair <int,P> PP; static const double EPS = 1e-8; int tx[] = {0,1,0,-1}; int ty[] = {-1,0,1,0}; const static char weekdays[][4] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; const static char times[][6] = {"Day","Night"}; const char* compute_weekday(int minutes){ int tmp = (minutes / (60 * 24)) % 7; return weekdays[tmp]; } const char* compute_time_band(int minutes){ int idx = 0; int tmp = minutes % (60 * 24); if(tmp >= 6 * 60 && tmp < 18 * 60){ idx = 0; } else{ idx = 1; } return times[idx]; } int main(){ int wait_hatch; int num_of_egg; int stage_life; char mutation_weekday[4]; char mutation_time_band[6]; int inv_mutation_prob; int total_stages; double probs[101]; while(~scanf("%d %d %d %s %s %d %d", &wait_hatch, &num_of_egg, &stage_life, mutation_weekday, mutation_time_band, &inv_mutation_prob, &total_stages)){ if(total_stages == 0) break; probs[0] = 1.0; for(int i=0;i<num_of_egg;i++){ probs[i+1] = probs[i] * (1.0 - 1.0/inv_mutation_prob); } double res = 0.0; for(int start=0; start < 60 * 24 * 7;start++){ int init_start = start; double prob = 1.0; for(int round = 0; round < total_stages; round++){ int time = init_start + wait_hatch; if(strcmp(mutation_weekday,"All") != 0 && strcmp(compute_weekday(time),mutation_weekday) != 0){ init_start += stage_life; continue; } if(strcmp(mutation_time_band,"All") != 0 && strcmp(compute_time_band(time),mutation_time_band) != 0){ init_start += stage_life; continue; } if(strcmp(mutation_weekday,"All") != 0 && strcmp(compute_weekday(init_start),compute_weekday(time)) != 0){ init_start += stage_life; continue; } if(strcmp(mutation_time_band,"All") != 0 && strcmp(compute_time_band(init_start),compute_time_band(time)) != 0){ init_start += stage_life; continue; } prob *= probs[num_of_egg]; init_start += stage_life; } res = max(res,1.0-prob); } printf("%.10f\n",res); } } ```
### Prompt Please create a solution in Cpp to the following problem: IT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that its pyramids will be not only quadrangular as in Egypt but also triangular and pentagonal. Of course the amount of the city budget funds for the construction depends on the pyramids' volume. Your task is to calculate the volume of the pilot project consisting of three pyramids β€” one triangular, one quadrangular and one pentagonal. The first pyramid has equilateral triangle as its base, and all 6 edges of the pyramid have equal length. The second pyramid has a square as its base and all 8 edges of the pyramid have equal length. The third pyramid has a regular pentagon as its base and all 10 edges of the pyramid have equal length. <image> Input The only line of the input contains three integers l3, l4, l5 (1 ≀ l3, l4, l5 ≀ 1000) β€” the edge lengths of triangular, quadrangular and pentagonal pyramids correspondingly. Output Output one number β€” the total volume of the pyramids. Absolute or relative error should not be greater than 10 - 9. Examples Input 2 5 3 Output 38.546168065709 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { double x, y, z; scanf("%lf%lf%lf", &x, &y, &z); double s = atan2(0, -1); double ans1 = 0; double ans2 = 0; double ans3 = 0; double k1 = x / 2 / sin(s / 3); double h1 = sqrt(x * x - k1 * k1); ans1 = k1 * x * sin(s / 6) * h1 / 2; double k2 = y / 2 / sin(s / 4); double h2 = sqrt(y * y - k2 * k2); ans2 = y * k2 * sin(s / 4) * 2 * h2 / 3; double k3 = z / 2 / sin(s / 5); double h3 = sqrt(z * z - k3 * k3); ans3 = 5 * z * k3 * sin(s / 5 * 3 / 2) * h3 / 6; printf("%.10lf\n", ans1 + ans2 + ans3); return 0; } ```
### Prompt Develop a solution in cpp to the problem described below: You have a grid with n rows and n columns. Each cell is either empty (denoted by '.') or blocked (denoted by 'X'). Two empty cells are directly connected if they share a side. Two cells (r1, c1) (located in the row r1 and column c1) and (r2, c2) are connected if there exists a sequence of empty cells that starts with (r1, c1), finishes with (r2, c2), and any two consecutive cells in this sequence are directly connected. A connected component is a set of empty cells such that any two cells in the component are connected, and there is no cell in this set that is connected to some cell not in this set. Your friend Limak is a big grizzly bear. He is able to destroy any obstacles in some range. More precisely, you can choose a square of size k Γ— k in the grid and Limak will transform all blocked cells there to empty ones. However, you can ask Limak to help only once. The chosen square must be completely inside the grid. It's possible that Limak won't change anything because all cells are empty anyway. You like big connected components. After Limak helps you, what is the maximum possible size of the biggest connected component in the grid? Input The first line of the input contains two integers n and k (1 ≀ k ≀ n ≀ 500) β€” the size of the grid and Limak's range, respectively. Each of the next n lines contains a string with n characters, denoting the i-th row of the grid. Each character is '.' or 'X', denoting an empty cell or a blocked one, respectively. Output Print the maximum possible size (the number of cells) of the biggest connected component, after using Limak's help. Examples Input 5 2 ..XXX XX.XX X.XXX X...X XXXX. Output 10 Input 5 3 ..... .XXX. .XXX. .XXX. ..... Output 25 Note In the first sample, you can choose a square of size 2 Γ— 2. It's optimal to choose a square in the red frame on the left drawing below. Then, you will get a connected component with 10 cells, marked blue in the right drawing. <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; using ll = long long; const vector<int> dx = {1, -1, 0, 0}; const vector<int> dy = {0, 0, 1, -1}; int n, k; vector<string> a; vector<vector<int>> num; vector<int> sz; inline bool ok(int x, int y) { return 0 <= min(x, y) && max(x, y) < n; } void dfs(int x, int y, vector<pair<int, int>> &comp) { num[x][y] = 0; comp.emplace_back(x, y); for (int d = 0; d < 4; d++) { int xx = x + dx[d]; int yy = y + dy[d]; if (ok(xx, yy) && num[xx][yy] == -1 && a[xx][yy] == '.') dfs(xx, yy, comp); } } signed main() { ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); cin >> n >> k; a.resize(n); for (auto &x : a) cin >> x; num.resize(n, vector<int>(n, -1)); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (num[i][j] != -1 || a[i][j] == 'X') continue; vector<pair<int, int>> comp; dfs(i, j, comp); for (auto [x, y] : comp) num[x][y] = sz.size(); sz.push_back(comp.size()); } } vector<vector<int>> pref(n + 1, vector<int>(n + 1, 0)); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) pref[i + 1][j + 1] = pref[i + 1][j] + pref[i][j + 1] - pref[i][j] + (a[i][j] == '.'); } auto get = [&](int x1, int y1, int x2, int y2) { return pref[x2 + 1][y2 + 1] - pref[x2 + 1][y1] - pref[x1][y2 + 1] + pref[x1][y1]; }; int ans = (sz.size() ? *max_element(sz.begin(), sz.end()) : 0); for (int i = 0; i + k <= n; i++) { vector<int> cnt(sz.size(), 0); int now = k * k; for (int j = 0; j < k && i; j++) { if (a[i - 1][j] == 'X') continue; if (!cnt[num[i - 1][j]]) now += sz[num[i - 1][j]]; cnt[num[i - 1][j]]++; } for (int j = 0; j < k && i + k != n; j++) { if (a[i + k][j] == 'X') continue; if (!cnt[num[i + k][j]]) now += sz[num[i + k][j]]; cnt[num[i + k][j]]++; } for (int j = i; j < i + k && k != n; j++) { if (a[j][k] == 'X') continue; if (!cnt[num[j][k]]) now += sz[num[j][k]]; cnt[num[j][k]]++; } for (int x = i; x < i + k; x++) { for (int y = 0; y < k; y++) { if (a[x][y] == 'X') continue; if (!cnt[num[x][y]]) now += sz[num[x][y]]; cnt[num[x][y]]++; } } ans = max(ans, now - get(i, 0, i + k - 1, k - 1)); for (int j = 1; j + k <= n; j++) { for (int x = i; x < i + k && j > 1; x++) { if (a[x][j - 2] == 'X') continue; cnt[num[x][j - 2]]--; if (!cnt[num[x][j - 2]]) now -= sz[num[x][j - 2]]; } for (int x = i; x < i + k && j + k < n; x++) { if (a[x][j + k] == 'X') continue; if (!cnt[num[x][j + k]]) now += sz[num[x][j + k]]; cnt[num[x][j + k]]++; } if (i) { if (a[i - 1][j - 1] == '.') { cnt[num[i - 1][j - 1]]--; if (!cnt[num[i - 1][j - 1]]) now -= sz[num[i - 1][j - 1]]; } if (a[i - 1][j + k - 1] == '.') { if (!cnt[num[i - 1][j + k - 1]]) now += sz[num[i - 1][j + k - 1]]; cnt[num[i - 1][j + k - 1]]++; } } if (i + k < n) { if (a[i + k][j - 1] == '.') { cnt[num[i + k][j - 1]]--; if (!cnt[num[i + k][j - 1]]) now -= sz[num[i + k][j - 1]]; } if (a[i + k][j + k - 1] == '.') { if (!cnt[num[i + k][j + k - 1]]) now += sz[num[i + k][j + k - 1]]; cnt[num[i + k][j + k - 1]]++; } } ans = max(ans, now - get(i, j, i + k - 1, j + k - 1)); } } cout << ans << '\n'; } ```
### Prompt Construct a Cpp code solution to the problem outlined: In this problem you will meet the simplified model of game King of Thieves. In a new ZeptoLab game called "King of Thieves" your aim is to reach a chest with gold by controlling your character, avoiding traps and obstacles on your way. <image> An interesting feature of the game is that you can design your own levels that will be available to other players. Let's consider the following simple design of a level. A dungeon consists of n segments located at a same vertical level, each segment is either a platform that character can stand on, or a pit with a trap that makes player lose if he falls into it. All segments have the same length, platforms on the scheme of the level are represented as '*' and pits are represented as '.'. One of things that affects speedrun characteristics of the level is a possibility to perform a series of consecutive jumps of the same length. More formally, when the character is on the platform number i1, he can make a sequence of jumps through the platforms i1 < i2 < ... < ik, if i2 - i1 = i3 - i2 = ... = ik - ik - 1. Of course, all segments i1, i2, ... ik should be exactly the platforms, not pits. Let's call a level to be good if you can perform a sequence of four jumps of the same length or in the other words there must be a sequence i1, i2, ..., i5, consisting of five platforms so that the intervals between consecutive platforms are of the same length. Given the scheme of the level, check if it is good. Input The first line contains integer n (1 ≀ n ≀ 100) β€” the number of segments on the level. Next line contains the scheme of the level represented as a string of n characters '*' and '.'. Output If the level is good, print the word "yes" (without the quotes), otherwise print the word "no" (without the quotes). Examples Input 16 .**.*..*.***.**. Output yes Input 11 .*.*...*.*. Output no Note In the first sample test you may perform a sequence of jumps through platforms 2, 5, 8, 11, 14. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { cout.sync_with_stdio(false); int x; cin >> x; string path; cin >> path; for (int i = 0; i < path.length(); i++) { if (path[i] == '.') continue; for (int j = 1; j <= path.length() / 4; j++) { int count = 0; for (int k = i + j; k < path.length(); k += j) { if (path[k] == '*') count++; else break; } if (count >= 4) { cout << "yes"; return 0; } } } cout << "no"; } ```
### Prompt In cpp, your task is to solve the following problem: Unary is a minimalistic Brainfuck dialect in which programs are written using only one token. Brainfuck programs use 8 commands: "+", "-", "[", "]", "<", ">", "." and "," (their meaning is not important for the purposes of this problem). Unary programs are created from Brainfuck programs using the following algorithm. First, replace each command with a corresponding binary code, using the following conversion table: * ">" β†’ 1000, * "<" β†’ 1001, * "+" β†’ 1010, * "-" β†’ 1011, * "." β†’ 1100, * "," β†’ 1101, * "[" β†’ 1110, * "]" β†’ 1111. Next, concatenate the resulting binary codes into one binary number in the same order as in the program. Finally, write this number using unary numeral system β€” this is the Unary program equivalent to the original Brainfuck one. You are given a Brainfuck program. Your task is to calculate the size of the equivalent Unary program, and print it modulo 1000003 (106 + 3). Input The input will consist of a single line p which gives a Brainfuck program. String p will contain between 1 and 100 characters, inclusive. Each character of p will be "+", "-", "[", "]", "<", ">", "." or ",". Output Output the size of the equivalent Unary program modulo 1000003 (106 + 3). Examples Input ,. Output 220 Input ++++[&gt;,.&lt;-] Output 61425 Note To write a number n in unary numeral system, one simply has to write 1 n times. For example, 5 written in unary system will be 11111. In the first example replacing Brainfuck commands with binary code will give us 1101 1100. After we concatenate the codes, we'll get 11011100 in binary system, or 220 in decimal. That's exactly the number of tokens in the equivalent Unary program. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long MOD = 1e6 + 3; long long power(int n) { int ans = 1; for (int i = 1; i <= n; i++) { ans = ((ans % MOD) * 2) % MOD; } return (ans % MOD); } int main() { map<char, string> mp; mp['>'] = "1000"; mp['<'] = "1001"; mp['+'] = "1010"; mp['-'] = "1011"; mp['.'] = "1100"; mp[','] = "1101"; mp['['] = "1110"; mp[']'] = "1111"; string t; cin >> t; string an = ""; for (int i = 0; i < t.size(); i++) { an += mp[t[i]]; } long long a = 0; for (int i = 0; i < an.size(); i++) { if (an[i] == '1') { a = (a % MOD + (power(an.size() - 1 - i))) % MOD; } } cout << a << endl; return 0; } ```
### Prompt Please create a solution in CPP to the following problem: This problem differs from the previous one only in the absence of the constraint on the equal length of all numbers a_1, a_2, ..., a_n. A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem. Let's denote a function that alternates digits of two numbers f(a_1 a_2 ... a_{p - 1} a_p, b_1 b_2 ... b_{q - 1} b_q), where a_1 ... a_p and b_1 ... b_q are digits of two integers written in the decimal notation without leading zeros. In other words, the function f(x, y) alternately shuffles the digits of the numbers x and y by writing them from the lowest digits to the older ones, starting with the number y. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below. For example: $$$f(1111, 2222) = 12121212 f(7777, 888) = 7787878 f(33, 44444) = 4443434 f(555, 6) = 5556 f(111, 2222) = 2121212$$$ Formally, * if p β‰₯ q then f(a_1 ... a_p, b_1 ... b_q) = a_1 a_2 ... a_{p - q + 1} b_1 a_{p - q + 2} b_2 ... a_{p - 1} b_{q - 1} a_p b_q; * if p < q then f(a_1 ... a_p, b_1 ... b_q) = b_1 b_2 ... b_{q - p} a_1 b_{q - p + 1} a_2 ... a_{p - 1} b_{q - 1} a_p b_q. Mishanya gives you an array consisting of n integers a_i, your task is to help students to calculate βˆ‘_{i = 1}^{n}βˆ‘_{j = 1}^{n} f(a_i, a_j) modulo 998 244 353. Input The first line of the input contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of elements in the array. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9) β€” the elements of the array. Output Print the answer modulo 998 244 353. Examples Input 3 12 3 45 Output 12330 Input 2 123 456 Output 1115598 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAX = (int)1e6 + 5, p = 998244353; int A[MAX], len[MAX], dig[13]; int e10[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1755647, 17556470, 175564700, 757402647, 586315999, 871938225, 733427426, 346563789, 470904831, 716070898, 172998509}; int main() { int n; while (scanf("%d", &n) == 1) { for (int i = 0; i < n; i++) scanf("%d", &A[i]); for (int i = 0; i < 13; i++) dig[i] = 0; int gg = 0; for (int i = 0; i < n; i++) { int x = A[i], count = 0; while (x > 0) { int add = (x % 10ll) * (e10[2 * count] + e10[2 * count + 1]) % p; gg = (gg + add) % p; x /= 10; count++; } len[i] = count; dig[count]++; } for (int i = 10; i >= 0; i--) dig[i] += dig[i + 1]; for (int i = 0; i < n; i++) { int x = A[i], count = 1, ex = 1; while (x > 0) { int add = (x % 10ll) * (dig[count] - 1ll) * e10[ex] % p; gg = (gg + add) % p; add = (x % 10ll) * (dig[count - 1] - 1ll) * e10[ex - 1] % p; gg = (gg + add) % p; for (int j = 1; j < count; j++) { add = (x % 10ll) * (dig[j] - dig[j + 1]) * e10[count + j - 1] % p; if (j < count - 1) add = (add + add) % p; gg = (gg + add) % p; } x /= 10; count++; ex += 2; } } printf("%d\n", gg); } return 0; } ```
### Prompt In Cpp, your task is to solve the following problem: Tomash keeps wandering off and getting lost while he is walking along the streets of Berland. It's no surprise! In his home town, for any pair of intersections there is exactly one way to walk from one intersection to the other one. The capital of Berland is very different! Tomash has noticed that even simple cases of ambiguity confuse him. So, when he sees a group of four distinct intersections a, b, c and d, such that there are two paths from a to c β€” one through b and the other one through d, he calls the group a "damn rhombus". Note that pairs (a, b), (b, c), (a, d), (d, c) should be directly connected by the roads. Schematically, a damn rhombus is shown on the figure below: <image> Other roads between any of the intersections don't make the rhombus any more appealing to Tomash, so the four intersections remain a "damn rhombus" for him. Given that the capital of Berland has n intersections and m roads and all roads are unidirectional and are known in advance, find the number of "damn rhombi" in the city. When rhombi are compared, the order of intersections b and d doesn't matter. Input The first line of the input contains a pair of integers n, m (1 ≀ n ≀ 3000, 0 ≀ m ≀ 30000) β€” the number of intersections and roads, respectively. Next m lines list the roads, one per line. Each of the roads is given by a pair of integers ai, bi (1 ≀ ai, bi ≀ n;ai β‰  bi) β€” the number of the intersection it goes out from and the number of the intersection it leads to. Between a pair of intersections there is at most one road in each of the two directions. It is not guaranteed that you can get from any intersection to any other one. Output Print the required number of "damn rhombi". Examples Input 5 4 1 2 2 3 1 4 4 3 Output 1 Input 4 12 1 2 1 3 1 4 2 1 2 3 2 4 3 1 3 2 3 4 4 1 4 2 4 3 Output 12 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 4096; const long long INF = 1e15 + 7; int n, m; vector<int> g[maxn]; int d[maxn]; int dfs(int x, int depth, int root) { if (depth == 2) return d[x]++; int ans = 0; for (int i = int(0); i <= int(g[x].size() - 1); ++i) if (g[x][i] != root) ans += dfs(g[x][i], depth + 1, root); return ans; } int calc(int x) { int ans = 0; for (int i = int(1); i <= int(n); ++i) d[i] = 0; return dfs(x, 0, x); } long long ans; int a, b; int main() { scanf("%d %d", &n, &m); for (int i = int(1); i <= int(m); ++i) { scanf("%d %d", &a, &b); g[a].push_back(b); } for (int i = int(1); i <= int(n); ++i) ans += calc(i); printf("%I64d", ans); return 0; } ```
### Prompt Construct a cpp code solution to the problem outlined: You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights. You are allowed the following operations: * put a brick on top of one pillar, the cost of this operation is A; * remove a brick from the top of one non-empty pillar, the cost of this operation is R; * move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M. You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0. What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height? Input The first line of input contains four integers N, A, R, M (1 ≀ N ≀ 10^{5}, 0 ≀ A, R, M ≀ 10^{4}) β€” the number of pillars and the costs of operations. The second line contains N integers h_{i} (0 ≀ h_{i} ≀ 10^{9}) β€” initial heights of pillars. Output Print one integer β€” the minimal cost of restoration. Examples Input 3 1 100 100 1 3 8 Output 12 Input 3 100 1 100 1 3 8 Output 9 Input 3 100 100 1 1 3 8 Output 4 Input 5 1 2 4 5 5 3 6 5 Output 4 Input 5 1 2 2 5 5 3 6 5 Output 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long int findCost(int arr[], int n, int a, int r, int m, int k) { long long int extra = 0, cost = 0; for (int i = 0; i < n; i++) { if (arr[i] >= k) { extra += (arr[i] - k); } else { long long int diff = k - arr[i]; long long int toUse = min(diff, extra); long long int op1 = diff * a + toUse * r; long long int op2 = toUse * m + max(0LL, diff - toUse) * a; if (op1 < op2) { cost += op1; } else { cost += op2; } extra -= toUse; } } cost += extra * r; return cost; } long long int restorerDistance(int arr[], int n, int a, int r, int m) { sort(arr, arr + n, greater<int>()); long long int start = 0, end = INT_MAX, ans = 1e18; while (start <= end) { long long int midLeft = start + (end - start) / 3, midRight = end - (end - start) / 3; long long int costLeft = findCost(arr, n, a, r, m, midLeft), costRight = findCost(arr, n, a, r, m, midRight); ans = min(ans, min(costLeft, costRight)); if (costLeft < costRight) end = midRight - 1; else start = midLeft + 1; } return ans; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, a, r, m; cin >> n >> a >> r >> m; int arr[n]; for (int i = 0; i < n; i++) cin >> arr[i]; long long int ans = restorerDistance(arr, n, a, r, m); cout << ans; return 0; } ```
### Prompt Please formulate a cpp solution to the following problem: You are given three integers n, k, m and m conditions (l_1, r_1, x_1), (l_2, r_2, x_2), ..., (l_m, r_m, x_m). Calculate the number of distinct arrays a, consisting of n integers such that: * 0 ≀ a_i < 2^k for each 1 ≀ i ≀ n; * bitwise AND of numbers a[l_i] \& a[l_i + 1] \& ... \& a[r_i] = x_i for each 1 ≀ i ≀ m. Two arrays a and b are considered different if there exists such a position i that a_i β‰  b_i. The number can be pretty large so print it modulo 998244353. Input The first line contains three integers n, k and m (1 ≀ n ≀ 5 β‹… 10^5, 1 ≀ k ≀ 30, 0 ≀ m ≀ 5 β‹… 10^5) β€” the length of the array a, the value such that all numbers in a should be smaller than 2^k and the number of conditions, respectively. Each of the next m lines contains the description of a condition l_i, r_i and x_i (1 ≀ l_i ≀ r_i ≀ n, 0 ≀ x_i < 2^k) β€” the borders of the condition segment and the required bitwise AND value on it. Output Print a single integer β€” the number of distinct arrays a that satisfy all the above conditions modulo 998244353. Examples Input 4 3 2 1 3 3 3 4 6 Output 3 Input 5 2 3 1 3 2 2 5 0 3 3 3 Output 33 Note You can recall what is a bitwise AND operation [here](https://en.wikipedia.org/wiki/Bitwise_operation#AND). In the first example, the answer is the following arrays: [3, 3, 7, 6], [3, 7, 7, 6] and [7, 3, 7, 6]. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 500010; const int mod = 998244353; int n, k, m, l[N], r[N], x[N], dp[N], c[N], lmx[N]; int solve(int b) { for (int i = 1; i <= n + 1; ++i) lmx[i] = 0, c[i] = 0, dp[i] = 0; for (int i = 1; i <= m; ++i) { if (x[i] >> b & 1) ++c[l[i]], --c[r[i] + 1]; else lmx[r[i] + 1] = max(lmx[r[i] + 1], l[i]); } for (int i = 1; i <= n + 1; ++i) lmx[i] = max(lmx[i], lmx[i - 1]), c[i] += c[i - 1]; int sdp = 1, j = 0; dp[0] = 1; for (int i = 1; i <= n + 1; ++i) { if (c[i] > 0) { dp[i] = 0; continue; } while (j < lmx[i]) sdp = (sdp - dp[j++] + mod) % mod; dp[i] = sdp; sdp = (sdp + dp[i]) % mod; } return dp[n + 1]; } int main() { scanf("%d%d%d", &n, &k, &m); for (int i = 1; i <= m; ++i) scanf("%d%d%d", &l[i], &r[i], &x[i]); int ans = 1; for (int i = 0; i < k; ++i) ans = 1ll * ans * solve(i) % mod; cout << ans << '\n'; return 0; } ```
### Prompt Your challenge is to write a Cpp solution to the following problem: You are given a rectangular field of n Γ— m cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side. Let's call a connected component any non-extendible set of cells such that any two of them are connected by the path of adjacent cells. It is a typical well-known definition of a connected component. For each impassable cell (x, y) imagine that it is an empty cell (all other cells remain unchanged) and find the size (the number of cells) of the connected component which contains (x, y). You should do it for each impassable cell independently. The answer should be printed as a matrix with n rows and m columns. The j-th symbol of the i-th row should be "." if the cell is empty at the start. Otherwise the j-th symbol of the i-th row should contain the only digit β€”- the answer modulo 10. The matrix should be printed without any spaces. To make your output faster it is recommended to build the output as an array of n strings having length m and print it as a sequence of lines. It will be much faster than writing character-by-character. As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. Input The first line contains two integers n, m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the field. Each of the next n lines contains m symbols: "." for empty cells, "*" for impassable cells. Output Print the answer as a matrix as described above. See the examples to precise the format of the output. Examples Input 3 3 *.* .*. *.* Output 3.3 .5. 3.3 Input 4 5 **..* ..*** .*.*. *.*.* Output 46..3 ..732 .6.4. 5.4.3 Note In first example, if we imagine that the central cell is empty then it will be included to component of size 5 (cross). If any of the corner cell will be empty then it will be included to component of size 3 (corner). ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, m, g[1005][1005], c[1005][1005], ch[1005][1005], ans[1005][1005], k = 1, dix[4] = {0, 0, 1, -1}, diy[4] = {1, -1, 0, 0}; char tb[1005][1005]; int main() { int co; scanf("%d %d", &n, &m); for (int i = 0; i < n; i++) scanf("%s", tb[i]); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (tb[i][j] == '.' && !ch[i][j]) { co = 0; queue<pair<int, int>> q; q.push(make_pair(i, j)); while (!q.empty()) { int x = q.front().first, y = q.front().second; q.pop(); if (ch[x][y]) continue; co++; ch[x][y] = 1; g[x][y] = k; for (int z = 0; z < 4; z++) { int a = x + dix[z], b = y + diy[z]; if ((a >= 0 && a < n) && (b >= 0 && b < m)) if (tb[a][b] == '.' && !ch[a][b]) q.push(make_pair(a, b)); } } k++; q.push(make_pair(i, j)); while (!q.empty()) { int x = q.front().first, y = q.front().second; q.pop(); if (c[x][y] > 0) continue; c[x][y] = co; for (int z = 0; z < 4; z++) { int a = x + dix[z], b = y + diy[z]; if ((a >= 0 && a < n) && (b >= 0 && b < m)) if (tb[a][b] == '.' && c[a][b] == 0) q.push(make_pair(a, b)); } } } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (tb[i][j] == '.') ans[i][j] = '.'; else { int k = 1; set<int> s; for (int z = 0; z < 4; z++) { int x = i + dix[z], y = j + diy[z]; if ((x >= 0 && x < n) && (y >= 0 && y < m)) if (tb[x][y] == '.' && s.count(g[x][y]) == 0) { k += c[x][y]; s.insert(g[x][y]); } } s.clear(); k %= 10; ans[i][j] = k + '0'; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) printf("%c", ans[i][j]); printf("\n"); } } ```
### Prompt Please create a solution in Cpp to the following problem: Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them. A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s. Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end. Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend. Input You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters. Output Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes. Examples Input fixprefixsuffix Output fix Input abcdabc Output Just a legend ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1000 * 1000 + 10; int l[N]; int main() { ios_base::sync_with_stdio(false); string s; cin >> s; int n = ((int)(s).size()); l[0] = -1; for (int i = (1); i <= (n); i++) { l[i] = l[i - 1]; while (l[i] != -1 && s[i - 1] != s[l[i]]) l[i] = l[l[i]]; l[i]++; } if (l[n] == 0) { cout << "Just a legend\n"; return 0; } for (int i = (0); i <= (n - 1); i++) if (l[i] == l[n]) { for (int j = (0); j <= (l[i] - 1); j++) cout << s[j]; cout << '\n'; return 0; } if (l[l[n]] == 0) { cout << "Just a legend\n"; return 0; } for (int i = (0); i <= (n - 1); i++) if (l[i] == l[l[n]]) { for (int j = (0); j <= (l[l[n]] - 1); j++) cout << s[j]; cout << '\n'; return 0; } return 0; } ```
### Prompt Construct a Cpp code solution to the problem outlined: There are n cards (n is even) in the deck. Each card has a positive integer written on it. n / 2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player. Find the way to distribute cards such that the sum of values written of the cards will be equal for each player. It is guaranteed that it is always possible. Input The first line of the input contains integer n (2 ≀ n ≀ 100) β€” the number of cards in the deck. It is guaranteed that n is even. The second line contains the sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is equal to the number written on the i-th card. Output Print n / 2 pairs of integers, the i-th pair denote the cards that should be given to the i-th player. Each card should be given to exactly one player. Cards are numbered in the order they appear in the input. It is guaranteed that solution exists. If there are several correct answers, you are allowed to print any of them. Examples Input 6 1 5 7 4 4 3 Output 1 3 6 2 4 5 Input 4 10 10 10 10 Output 1 2 3 4 Note In the first sample, cards are distributed in such a way that each player has the sum of numbers written on his cards equal to 8. In the second sample, all values ai are equal. Thus, any distribution is acceptable. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { cin.tie(NULL); ios_base ::sync_with_stdio(false); int n; cin >> n; vector<pair<int, int> > ve; for (int i = 0; i < n; ++i) { int t; cin >> t; ve.push_back(make_pair(t, i + 1)); } sort(ve.begin(), ve.end()); for (int i = 0; i < n / 2; ++i) { cout << ve[i].second << " " << ve[n - 1 - i].second << "\n"; } return 0; } ```
### Prompt Please formulate a CPP solution to the following problem: Little beaver is a beginner programmer, so informatics is his favorite subject. Soon his informatics teacher is going to have a birthday and the beaver has decided to prepare a present for her. He planted n flowers in a row on his windowsill and started waiting for them to grow. However, after some time the beaver noticed that the flowers stopped growing. The beaver thinks it is bad manners to present little flowers. So he decided to come up with some solutions. There are m days left to the birthday. The height of the i-th flower (assume that the flowers in the row are numbered from 1 to n from left to right) is equal to ai at the moment. At each of the remaining m days the beaver can take a special watering and water w contiguous flowers (he can do that only once at a day). At that each watered flower grows by one height unit on that day. The beaver wants the height of the smallest flower be as large as possible in the end. What maximum height of the smallest flower can he get? Input The first line contains space-separated integers n, m and w (1 ≀ w ≀ n ≀ 105; 1 ≀ m ≀ 105). The second line contains space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output Print a single integer β€” the maximum final height of the smallest flower. Examples Input 6 2 3 2 2 2 2 1 1 Output 2 Input 2 5 1 5 8 Output 9 Note In the first sample beaver can water the last 3 flowers at the first day. On the next day he may not to water flowers at all. In the end he will get the following heights: [2, 2, 2, 3, 2, 2]. The smallest flower has height equal to 2. It's impossible to get height 3 in this test. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long N, M, w, a[100007], st[400007], lazy[400007], b[100007]; void build(int l, int r, int p) { if (l == r) { st[p] = b[l]; return; } int mid = (l + r) / 2; build(l, mid, p * 2); build(mid + 1, r, p * 2 + 1); st[p] = min(st[p * 2], st[p * 2 + 1]); } void push_lazy(int l, int r, int p) { if (lazy[p] == 0) return; st[p] += lazy[p]; if (l != r) { lazy[p * 2] += lazy[p]; lazy[p * 2 + 1] += lazy[p]; } else b[l] += lazy[p]; lazy[p] = 0; } void update_lazy(int l, int r, int p, int i, int j, long long val) { push_lazy(l, r, p); if (i > r || j < l) return; if (i <= l && j >= r) { st[p] += val; if (l == r) b[l] += val; else { lazy[p * 2] += val; lazy[p * 2 + 1] += val; } lazy[p] = 0; return; } int mid = (l + r) / 2; update_lazy(l, mid, p * 2, i, j, val); update_lazy(mid + 1, r, p * 2 + 1, i, j, val); st[p] = min(st[p * 2], st[p * 2 + 1]); } bool check(long long mid) { memset(lazy, 0, sizeof lazy); for (int i = 0; i < N; i++) b[i] = a[i]; build(0, N - 1, 1); long long times = 0; for (int i = 0; i < N; i++) { update_lazy(0, N - 1, 1, i, i, 0); if (b[i] < mid) { long long val = mid - b[i]; times += val; update_lazy(0, N - 1, 1, i, i + w - 1, val); } } return times <= M; } long long BS() { long long first = 0, last = 1e9 + 1e5 + 7, mid, ans = -1; while (first <= last) { mid = (first + last) / 2; if (check(mid)) { ans = mid; first = mid + 1; } else last = mid - 1; } return ans; } int main() { ios::sync_with_stdio(false); cin >> N >> M >> w; for (int i = 0; i < N; i++) cin >> a[i]; cout << BS(); return 0; } ```
### Prompt Please provide a CPP coded solution to the problem described below: Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question: Given two binary numbers a and b of length n. How many different ways of swapping two digits in a (only in a, not b) so that bitwise OR of these two numbers will be changed? In other words, let c be the bitwise OR of a and b, you need to find the number of ways of swapping two bits in a so that bitwise OR will not be equal to c. Note that binary numbers can contain leading zeros so that length of each number is exactly n. [Bitwise OR](https://en.wikipedia.org/wiki/Bitwise_operation#OR) is a binary operation. A result is a binary number which contains a one in each digit if there is a one in at least one of the two numbers. For example, 01010_2 OR 10011_2 = 11011_2. Well, to your surprise, you are not Rudolf, and you don't need to help him… You are the security staff! Please find the number of ways of swapping two bits in a so that bitwise OR will be changed. Input The first line contains one integer n (2≀ n≀ 10^5) β€” the number of bits in each number. The second line contains a binary number a of length n. The third line contains a binary number b of length n. Output Print the number of ways to swap two bits in a so that bitwise OR will be changed. Examples Input 5 01011 11001 Output 4 Input 6 011000 010011 Output 6 Note In the first sample, you can swap bits that have indexes (1, 4), (2, 3), (3, 4), and (3, 5). In the second example, you can swap bits that have indexes (1, 2), (1, 3), (2, 4), (3, 4), (3, 5), and (3, 6). ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n, i, a[100005], b[100005], rec[100005]; cin >> n; string s1, s2; cin >> s1 >> s2; long long int n0 = 0, n1 = 0, n2 = 0, n3 = 0; for (i = 0; i < n; i++) { if (s1[i] == '0') a[i] = 0; else a[i] = 1; } for (i = 0; i < n; i++) { if (s2[i] == '0') b[i] = 0; else b[i] = 1; } for (i = 0; i < n; i++) { if (a[i] == b[i] && a[i] == 0) n0++; else if (a[i] == b[i] && a[i] == 1) n3++; else if (a[i] == 1 && b[i] == 0) n2++; else n1++; } long long int ans = 0; ans = (n0 * n2) + (n0 * n3); ans += (n1 * n2); cout << ans << endl; return 0; } ```
### Prompt Create a solution in Cpp for the following problem: The Shuseki Islands are an archipelago of 30001 small islands in the Yutampo Sea. The islands are evenly spaced along a line, numbered from 0 to 30000 from the west to the east. These islands are known to contain many treasures. There are n gems in the Shuseki Islands in total, and the i-th gem is located on island pi. Mr. Kitayuta has just arrived at island 0. With his great jumping ability, he will repeatedly perform jumps between islands to the east according to the following process: * First, he will jump from island 0 to island d. * After that, he will continue jumping according to the following rule. Let l be the length of the previous jump, that is, if his previous jump was from island prev to island cur, let l = cur - prev. He will perform a jump of length l - 1, l or l + 1 to the east. That is, he will jump to island (cur + l - 1), (cur + l) or (cur + l + 1) (if they exist). The length of a jump must be positive, that is, he cannot perform a jump of length 0 when l = 1. If there is no valid destination, he will stop jumping. Mr. Kitayuta will collect the gems on the islands visited during the process. Find the maximum number of gems that he can collect. Input The first line of the input contains two space-separated integers n and d (1 ≀ n, d ≀ 30000), denoting the number of the gems in the Shuseki Islands and the length of the Mr. Kitayuta's first jump, respectively. The next n lines describe the location of the gems. The i-th of them (1 ≀ i ≀ n) contains a integer pi (d ≀ p1 ≀ p2 ≀ ... ≀ pn ≀ 30000), denoting the number of the island that contains the i-th gem. Output Print the maximum number of gems that Mr. Kitayuta can collect. Examples Input 4 10 10 21 27 27 Output 3 Input 8 8 9 19 28 36 45 55 66 78 Output 6 Input 13 7 8 8 9 16 17 17 18 21 23 24 24 26 30 Output 4 Note In the first sample, the optimal route is 0 β†’ 10 (+1 gem) β†’ 19 β†’ 27 (+2 gems) β†’ ... In the second sample, the optimal route is 0 β†’ 8 β†’ 15 β†’ 21 β†’ 28 (+1 gem) β†’ 36 (+1 gem) β†’ 45 (+1 gem) β†’ 55 (+1 gem) β†’ 66 (+1 gem) β†’ 78 (+1 gem) β†’ ... In the third sample, the optimal route is 0 β†’ 7 β†’ 13 β†’ 18 (+1 gem) β†’ 24 (+2 gems) β†’ 30 (+1 gem) β†’ ... ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, d, tr[30003], a, dp[500][30003], calc[500][30003]; int solve(int dis, int cur) { int jj = dis - d + 250; if (cur > 30000) return 0; if (calc[jj][cur]) return dp[jj][cur]; calc[jj][cur] = 1; int res = tr[cur]; int mx = max(solve(dis, cur + dis), solve(dis + 1, cur + dis + 1)); if (dis > 1) mx = max(mx, solve(dis - 1, cur + dis - 1)); res += mx; return dp[jj][cur] = res; } int main() { scanf("%d%d", &n, &d); for (int i = 0; i < n; i++) { scanf("%d", &a); tr[a]++; } printf("%d\n", solve(d, d)); return 0; } ```
### Prompt Construct a Cpp code solution to the problem outlined: One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on. These events are given as a sequence of strings "name1 reposted name2", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed. Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke. Input The first line of the input contains integer n (1 ≀ n ≀ 200) β€” the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as "name1 reposted name2". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive. We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user. Output Print a single integer β€” the maximum length of a repost chain. Examples Input 5 tourist reposted Polycarp Petr reposted Tourist WJMZBMR reposted Petr sdya reposted wjmzbmr vepifanov reposted sdya Output 6 Input 6 Mike reposted Polycarp Max reposted Polycarp EveryOne reposted Polycarp 111 reposted Polycarp VkCup reposted Polycarp Codeforces reposted Polycarp Output 2 Input 1 SoMeStRaNgEgUe reposted PoLyCaRp Output 2 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long int M = 1e9 + 7, N = 1e5 + 1; vector<int> v[N]; map<string, int> m; int visited[N] = {0}; int level[N] = {0}, ans = 0; void bfs(int node) { queue<int> q; visited[node] = 1; q.push(node); level[node] = 1; while (!q.empty()) { int y = q.front(); visited[y] = 1; q.pop(); for (auto x : v[y]) { if (!visited[x]) { q.push(x); level[x] = level[y] + 1; } } } } int main() { long long int n; cin >> n; int j = 1; m["polycarp"] = j++; for (int i = 1; i <= n; i++) { string a, b, c; cin >> a >> b >> c; for (int i = 0; i < a.size(); i++) a[i] = tolower(a[i]); for (int i = 0; i < c.size(); i++) c[i] = tolower(c[i]); m.insert({a, j++}); m.insert({c, j++}); v[m[c]].push_back(m[a]); v[m[a]].push_back(m[c]); } bfs(1); for (int i = 1; i <= j; i++) { ans = max(ans, level[i]); } cout << ans; return 0; } ```
### Prompt Your task is to create a cpp solution to the following problem: Ivan has number b. He is sorting through the numbers a from 1 to 10^{18}, and for every a writes ([a, b])/(a) on blackboard. Here [a, b] stands for least common multiple of a and b. Ivan is very lazy, that's why this task bored him soon. But he is interested in how many different numbers he would write on the board if he would finish the task. Help him to find the quantity of different numbers he would write on the board. Input The only line contains one integer β€” b (1 ≀ b ≀ 10^{10}). Output Print one number β€” answer for the problem. Examples Input 1 Output 1 Input 2 Output 2 Note In the first example [a, 1] = a, therefore ([a, b])/(a) is always equal to 1. In the second example [a, 2] can be equal to a or 2 β‹… a depending on parity of a. ([a, b])/(a) can be equal to 1 and 2. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long n, c, q; int main() { cin >> n; q = 2; c = 2; if (n == 1) { cout << 1; return 0; } while (q * q < n) { if (n % q == 0) c += 2; q++; } if (q * q == n) c++; cout << c; } ```
### Prompt Develop a solution in cpp to the problem described below: At many competitions that have a word Β«cupΒ» in its official name the winner is presented with an actual cup. This time the organizers of one unusual programming competition have decided to please the winner even more and to add a nameplate to the cup with the handle of the winner. The nameplate is to be rectangular and the text on it will be printed as a table of several rows and columns. Having some measurements done, the organizers have found out that the number a of rows cannot be greater than 5 while the number b of columns cannot exceed 20. Every cell of the table will contain either an asterisk (Β«*Β») or a letter of user's handle. Furthermore, the organizers want the rows of the table to be uniform, which means that the number of asterisks used in different rows should differ by at most one (i.e. you can't have two asterisks in the first row and none in the second). The main goal, however, is to obtain the winner's handle precisely when reading the table from top to bottom and from left to right in every row (skipping asterisks). The organizers want for the nameplate to have as few rows as possible and among all valid tables with the minimum number of rows they want to choose the one that has the minimum number of columns. The winner is not yet determined so your task is to write a program that, given a certain handle, generates the necessary table. Input The only line contains one string s (1 ≀ |s| ≀ 100), comprised of uppercase and lowercase Latin letters, β€” the handle of the winner. Output In the first line output the minimum number a of rows in the table and the minimum number b of columns in an optimal table with rows. The following a lines should contain b characters each β€” any valid table. Examples Input tourist Output 1 7 tourist Input MyNameIsLifeIAmForeverByYourSideMyNameIsLife Output 3 15 MyNameIsLifeIAm ForeverByYourSi deMyNameIsL*ife ### Response ```cpp #include <bits/stdc++.h> using namespace std; int32_t main() { ios_base::sync_with_stdio(false); string str; cin >> str; for (int64_t h = 1; h <= 5; ++h) { int64_t len = str.size() / h; if (str.size() % h) ++len; if (len > 20) continue; int64_t idx = 0; cout << h << ' ' << len << endl; for (int64_t i = 0; i < h; ++i) { for (int64_t j = 0; j < len - 1; ++j) { cout << str[idx]; ++idx; } if (i < str.size() % h || str.size() % h == 0) { cout << str[idx]; ++idx; } else cout << '*'; cout << endl; } return 0; } } ```
### Prompt In CPP, your task is to solve the following problem: You are given a string s consisting of n lowercase Latin letters. n is even. For each position i (1 ≀ i ≀ n) in string s you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Letter in every position must be changed exactly once. For example, letter 'p' should be changed either to 'o' or to 'q', letter 'a' should be changed to 'b' and letter 'z' should be changed to 'y'. That way string "codeforces", for example, can be changed to "dpedepqbft" ('c' β†’ 'd', 'o' β†’ 'p', 'd' β†’ 'e', 'e' β†’ 'd', 'f' β†’ 'e', 'o' β†’ 'p', 'r' β†’ 'q', 'c' β†’ 'b', 'e' β†’ 'f', 's' β†’ 't'). String s is called a palindrome if it reads the same from left to right and from right to left. For example, strings "abba" and "zz" are palindromes and strings "abca" and "zy" are not. Your goal is to check if it's possible to make string s a palindrome by applying the aforementioned changes to every position. Print "YES" if string s can be transformed to a palindrome and "NO" otherwise. Each testcase contains several strings, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (1 ≀ T ≀ 50) β€” the number of strings in a testcase. Then 2T lines follow β€” lines (2i - 1) and 2i of them describe the i-th string. The first line of the pair contains a single integer n (2 ≀ n ≀ 100, n is even) β€” the length of the corresponding string. The second line of the pair contains a string s, consisting of n lowercase Latin letters. Output Print T lines. The i-th line should contain the answer to the i-th string of the input. Print "YES" if it's possible to make the i-th string a palindrome by applying the aforementioned changes to every position. Print "NO" otherwise. Example Input 5 6 abccba 2 cf 4 adfa 8 abaazaba 2 ml Output YES NO YES NO NO Note The first string of the example can be changed to "bcbbcb", two leftmost letters and two rightmost letters got changed to the next letters, two middle letters got changed to the previous letters. The second string can be changed to "be", "bg", "de", "dg", but none of these resulting strings are palindromes. The third string can be changed to "beeb" which is a palindrome. The fifth string can be changed to "lk", "lm", "nk", "nm", but none of these resulting strings are palindromes. Also note that no letter can remain the same, so you can't obtain strings "ll" or "mm". ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { string s; int t, n, i, dis; cin >> t; while (t--) { cin >> n >> s; string a, b; int flag = 0; for (i = 0; i < n / 2; i++) a += s[i]; for (i = n / 2; i < n; i++) b += s[i]; reverse(b.begin(), b.end()); for (i = 0; i < n / 2; i++) { dis = abs(a[i] - b[i]); if (dis == 1 || dis > 2) { flag = 1; break; } } if (flag == 0) cout << "YES" << endl; else cout << "NO" << endl; } return 0; } ```
### Prompt Your challenge is to write a Cpp solution to the following problem: The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" β€” the HR manager thought. "Just raise number 5 to the power of n and get last two digits of the number. Yes, of course, n can be rather big, and one cannot find the power using a calculator, but we need people who are able to think, not just follow the instructions." Could you pass the interview in the machine vision company in IT City? Input The only line of the input contains a single integer n (2 ≀ n ≀ 2Β·1018) β€” the power in which you need to raise number 5. Output Output the last two digits of 5n without spaces between them. Examples Input 2 Output 25 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { long long int n; cin >> n; cout << 25 << endl; return 0; } ```
### Prompt In CPP, your task is to solve the following problem: Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; namespace zzc { int read() { int x = 0, f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -1; ch = getchar(); } while (isdigit(ch)) { x = (x << 1) + (x << 3) + ch - 48; ch = getchar(); } return x * f; } const int maxn = 1e5 + 5; int head[maxn], rd[maxn], fa[maxn]; int n, cnt = 0, m, ans; bool vis[maxn], ins[maxn], dsu[maxn]; queue<int> q; struct edge { int to, nxt; } e[maxn]; int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); } void add(int u, int v) { e[++cnt].to = v; e[cnt].nxt = head[u]; head[u] = cnt; rd[v]++; } void work() { int a, b; n = read(); m = read(); for (int i = 1; i <= n; i++) fa[i] = i; for (int i = 1; i <= m; i++) { a = read(); b = read(); add(a, b); if (!vis[a]) { vis[a] = true; ans++; } if (!vis[b]) { vis[b] = true; ans++; } int fx = find(a); int fy = find(b); if (fx != fy) fa[fy] = fx; } for (int i = 1; i <= n; i++) if (!rd[i]) q.push(i), ins[i] = true; while (!q.empty()) { int u = q.front(); q.pop(); for (int i = head[u]; i; i = e[i].nxt) { int v = e[i].to; if (--rd[v] == 0) q.push(v), ins[v] = true; } } for (int i = 1; i <= n; i++) if (vis[i] && !ins[i] && !dsu[find(i)]) dsu[find(i)] = true; for (int i = 1; i <= n; i++) if (vis[i] && find(i) == i && !dsu[i]) ans--; printf("%d\n", ans); } } // namespace zzc int main() { zzc::work(); return 0; } ```
### Prompt Please create a solution in CPP to the following problem: Ralph has a magic field which is divided into n Γ— m blocks. That is to say, there are n rows and m columns on the field. Ralph can put an integer in each block. However, the magic field doesn't always work properly. It works only if the product of integers in each row and each column equals to k, where k is either 1 or -1. Now Ralph wants you to figure out the number of ways to put numbers in each block in such a way that the magic field works properly. Two ways are considered different if and only if there exists at least one block where the numbers in the first way and in the second way are different. You are asked to output the answer modulo 1000000007 = 109 + 7. Note that there is no range of the numbers to put in the blocks, but we can prove that the answer is not infinity. Input The only line contains three integers n, m and k (1 ≀ n, m ≀ 1018, k is either 1 or -1). Output Print a single number denoting the answer modulo 1000000007. Examples Input 1 1 -1 Output 1 Input 1 3 1 Output 1 Input 3 3 -1 Output 16 Note In the first example the only way is to put -1 into the only block. In the second example the only way is to put 1 into every block. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 20; long long a, b, c; int g[N][N]; int solve(int x) { if (x == a) { int can = 1; for (int x = 0, qwe = a; x < qwe; x++) { int tmp = 1; for (int y = 0, qwe = b; y < qwe; y++) tmp *= g[x][y]; can &= tmp == c; } for (int y = 0, qwe = b; y < qwe; y++) { int tmp = 1; for (int x = 0, qwe = a; x < qwe; x++) tmp *= g[x][y]; can &= tmp == c; } return can; } else { int tmp = 0; for (int m = 0, qwe = 1 << b; m < qwe; m++) { for (int y = 0, qwe = b; y < qwe; y++) g[x][y] = m & (1 << y) ? 1 : -1; tmp += solve(x + 1); } return tmp; } } const long long m = 1e9 + 7; long long fe(long long b, long long e) { long long r = 1; while (e) if (e & 1) r = (r * b) % m, e--; else b = (b * b) % m, e /= 2; return r; } int main() { cin >> a >> b >> c; if (a > b) swap(a, b); long long tmp = fe(2, a - 1); tmp = fe(tmp, b - 1); if (c == -1) { if (a % 2 == b % 2) cout << tmp << endl; else cout << "0\n"; } else { cout << tmp << endl; } } ```
### Prompt Please provide a CPP coded solution to the problem described below: You are given an array a consisting of n integers. Your task is to determine if a has some subsequence of length at least 3 that is a palindrome. Recall that an array b is called a subsequence of the array a if b can be obtained by removing some (possibly, zero) elements from a (not necessarily consecutive) without changing the order of remaining elements. For example, [2], [1, 2, 1, 3] and [2, 3] are subsequences of [1, 2, 1, 3], but [1, 1, 2] and [4] are not. Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array a of length n is the palindrome if a_i = a_{n - i - 1} for all i from 1 to n. For example, arrays [1234], [1, 2, 1], [1, 3, 2, 2, 3, 1] and [10, 100, 10] are palindromes, but arrays [1, 2] and [1, 2, 3, 1] are not. 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. Next 2t lines describe test cases. The first line of the test case contains one integer n (3 ≀ n ≀ 5000) β€” the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ n), where a_i is the i-th element of a. It is guaranteed that the sum of n over all test cases does not exceed 5000 (βˆ‘ n ≀ 5000). Output For each test case, print the answer β€” "YES" (without quotes) if a has some subsequence of length at least 3 that is a palindrome and "NO" otherwise. Example Input 5 3 1 2 1 5 1 2 2 3 2 3 1 1 2 4 1 2 2 1 10 1 1 2 2 3 3 4 4 5 5 Output YES YES NO YES NO Note In the first test case of the example, the array a has a subsequence [1, 2, 1] which is a palindrome. In the second test case of the example, the array a has two subsequences of length 3 which are palindromes: [2, 3, 2] and [2, 2, 2]. In the third test case of the example, the array a has no subsequences of length at least 3 which are palindromes. In the fourth test case of the example, the array a has one subsequence of length 4 which is a palindrome: [1, 2, 2, 1] (and has two subsequences of length 3 which are palindromes: both are [1, 2, 1]). In the fifth test case of the example, the array a has no subsequences of length at least 3 which are palindromes. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int fun(vector<int> &v, int x, vector<vector<int> > &fq) { int i, j, k, n = v.size(), mx = 0, cnt = 0; i = 0; j = n - 1; while (true) { while (i < n && v[i] != x) i++; while (j >= 0 && v[j] != x) j--; if (i >= j) return max(mx, 1); cnt++; for (k = 1; k < 201; k++) { mx = max(mx, (2 * cnt) + fq[j - 1][k] - fq[i][k]); } i++; j--; } return mx; } void solve() { int i, j, k, n; cin >> n; vector<int> v(n); for (auto &i : v) cin >> i; ; vector<vector<int> > fq(n, vector<int>(201, 0)); fq[0][v[0]]++; for (i = 1; i < n; i++) { for (j = 1; j < 201; j++) { fq[i][j] = fq[i - 1][j] + (j == v[i]); } } int mx = -10; for (i = 1; i < 201; i++) mx = max(mx, fun(v, i, fq)); cout << mx << '\n'; } int main() { ios::sync_with_stdio(0); cin.tie(0); int t = 1; cin >> t; while (t--) { solve(); } return 0; } ```
### Prompt In CPP, your task is to solve the following problem: You're given an array a of n integers, such that a_1 + a_2 + β‹…β‹…β‹… + a_n = 0. In one operation, you can choose two different indices i and j (1 ≀ i, j ≀ n), decrement a_i by one and increment a_j by one. If i < j this operation is free, otherwise it costs one coin. How many coins do you have to spend in order to make all elements equal to 0? Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 5000). Description of the test cases follows. The first line of each test case contains an integer n (1 ≀ n ≀ 10^5) β€” the number of elements. The next line contains n integers a_1, …, a_n (-10^9 ≀ a_i ≀ 10^9). It is given that βˆ‘_{i=1}^n a_i = 0. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the minimum number of coins we have to spend in order to make all elements equal to 0. Example Input 7 4 -3 5 -3 1 2 1 -1 4 -3 2 -3 4 4 -1 1 1 -1 7 -5 7 -6 -4 17 -13 4 6 -1000000000 -1000000000 -1000000000 1000000000 1000000000 1000000000 1 0 Output 3 0 4 1 8 3000000000 0 Note Possible strategy for the first test case: * Do (i=2, j=3) three times (free), a = [-3, 2, 0, 1]. * Do (i=2, j=1) two times (pay two coins), a = [-1, 0, 0, 1]. * Do (i=4, j=1) one time (pay one coin), a = [0, 0, 0, 0]. ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename A, typename B> string to_string(pair<A, B> p); template <typename A, typename B, typename C> string to_string(tuple<A, B, C> p); template <typename A, typename B, typename C, typename D> string to_string(tuple<A, B, C, D> p); string to_string(const string &s) { return '"' + s + '"'; } string to_string(const char *s) { return to_string((string)s); } string to_string(char c) { return to_string(string(1, c)); } string to_string(bool b) { return (b ? "true" : "false"); } string to_string(vector<bool> v) { bool first = true; string res = "{"; for (int i = 0; i < static_cast<int>(v.size()); i++) { if (!first) { res += ", "; } first = false; res += to_string(v[i]); } res += "}"; return res; } template <size_t N> string to_string(bitset<N> v) { string res = ""; for (size_t i = 0; i < N; i++) { res += static_cast<char>('0' + v[i]); } return res; } template <typename A> string to_string(A v) { bool first = true; string res = "{"; for (const auto &x : v) { if (!first) { res += ", "; } first = false; res += to_string(x); } res += "}"; return res; } template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; } template <typename A, typename B, typename C> string to_string(tuple<A, B, C> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")"; } template <typename A, typename B, typename C, typename D> string to_string(tuple<A, B, C, D> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")"; } void debug_out() { cerr << endl; } template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); } void solve(const int &test_id) { int n; long long c = 0; cin >> n; vector<long long> x(n); for (auto &e : x) cin >> e; for (int i = 0; i < n; i++) { if (x[i] > 0) c += x[i]; else c -= min(c, -x[i]); } cout << c << endl; } void solve_cases() { int test_cases = 1; cin >> test_cases; for (int i = 1; i <= test_cases; i++) solve(i); } void fast_io() { ios::sync_with_stdio(false); srand(time(NULL)); cin.tie(0); cout.tie(0); cout << fixed << setprecision(15); cerr << fixed << setprecision(15); } int main() { fast_io(); solve_cases(); return EXIT_SUCCESS; } ```
### Prompt Develop a solution in CPP to the problem described below: After lessons Nastya decided to read a book. The book contains n chapters, going one after another, so that one page of the book belongs to exactly one chapter and each chapter contains at least one page. Yesterday evening Nastya did not manage to finish reading the book, so she marked the page with number k as the first page which was not read (i.e. she read all pages from the 1-st to the (k-1)-th). The next day Nastya's friend Igor came and asked her, how many chapters remain to be read by Nastya? Nastya is too busy now, so she asks you to compute the number of chapters she has not completely read yet (i.e. the number of chapters she has not started to read or has finished reading somewhere in the middle). Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of chapters in the book. There are n lines then. The i-th of these lines contains two integers l_i, r_i separated by space (l_1 = 1, l_i ≀ r_i) β€” numbers of the first and the last pages of the i-th chapter. It's guaranteed that l_{i+1} = r_i + 1 for all 1 ≀ i ≀ n-1, and also that every chapter contains at most 100 pages. The (n+2)-th line contains a single integer k (1 ≀ k ≀ r_n) β€” the index of the marked page. Output Print a single integer β€” the number of chapters which has not been completely read so far. Examples Input 3 1 3 4 7 8 11 2 Output 3 Input 3 1 4 5 9 10 12 9 Output 2 Input 1 1 7 4 Output 1 Note In the first example the book contains 11 pages and 3 chapters β€” [1;3], [4;7] and [8;11]. Nastya marked the 2-nd page, so she finished in the middle of the 1-st chapter. So, all chapters has not been read so far, so the answer is 3. The book in the second example contains 12 pages and 3 chapters too, but Nastya finished reading in the middle of the 2-nd chapter, so that the answer is 2. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 2; const long long int MOD = 1e9 + 7; bool comp(const pair<long long int, long long int> &p1, const pair<long long int, long long int> &p2) { long long int x = abs(p1.first - p1.second); long long int y = abs(p2.first - p2.second); if (x > y) return true; else return false; } void Solve() { long long int n, k; cin >> n; vector<pair<long long int, long long int> > v; for (long long int i = 0; i < n; i++) { long long int a, b; cin >> a >> b; v.push_back({a, b}); } cin >> k; sort(v.begin(), v.end()); long long int ans = n; for (long long int i = 0; i < n; i++) { pair<long long int, long long int> p = v[i]; if (p.first == k || p.second == k) break; if (k >= p.first && k <= p.second) break; else ans--; } cout << ans << "\n"; } int main() { ios_base::sync_with_stdio(0); cin.tie(nullptr); ; int T = 1; while (T--) { Solve(); } return 0; } ```
### Prompt Please provide a CPP coded solution to the problem described below: Vasya is developing his own programming language VPL (Vasya Programming Language). Right now he is busy making the system of exceptions. He thinks that the system of exceptions must function like that. The exceptions are processed by try-catch-blocks. There are two operators that work with the blocks: 1. The try operator. It opens a new try-catch-block. 2. The catch(<exception_type>, <message>) operator. It closes the try-catch-block that was started last and haven't yet been closed. This block can be activated only via exception of type <exception_type>. When we activate this block, the screen displays the <message>. If at the given moment there is no open try-catch-block, then we can't use the catch operator. The exceptions can occur in the program in only one case: when we use the throw operator. The throw(<exception_type>) operator creates the exception of the given type. Let's suggest that as a result of using some throw operator the program created an exception of type a. In this case a try-catch-block is activated, such that this block's try operator was described in the program earlier than the used throw operator. Also, this block's catch operator was given an exception type a as a parameter and this block's catch operator is described later that the used throw operator. If there are several such try-catch-blocks, then the system activates the block whose catch operator occurs earlier than others. If no try-catch-block was activated, then the screen displays message "Unhandled Exception". To test the system, Vasya wrote a program that contains only try, catch and throw operators, one line contains no more than one operator, the whole program contains exactly one throw operator. Your task is: given a program in VPL, determine, what message will be displayed on the screen. Input The first line contains a single integer: n (1 ≀ n ≀ 105) the number of lines in the program. Next n lines contain the program in language VPL. Each line contains no more than one operator. It means that input file can contain empty lines and lines, consisting only of spaces. The program contains only operators try, catch and throw. It is guaranteed that the program is correct. It means that each started try-catch-block was closed, the catch operators aren't used unless there is an open try-catch-block. The program has exactly one throw operator. The program may have spaces at the beginning of a line, at the end of a line, before and after a bracket, a comma or a quote mark. The exception type is a nonempty string, that consists only of upper and lower case english letters. The length of the string does not exceed 20 symbols. Message is a nonempty string, that consists only of upper and lower case english letters, digits and spaces. Message is surrounded with quote marks. Quote marks shouldn't be printed. The length of the string does not exceed 20 symbols. Length of any line in the input file does not exceed 50 symbols. Output Print the message the screen will show after the given program is executed. Examples Input 8 try try throw ( AE ) catch ( BE, "BE in line 3") try catch(AE, "AE in line 5") catch(AE,"AE somewhere") Output AE somewhere Input 8 try try throw ( AE ) catch ( AE, "AE in line 3") try catch(BE, "BE in line 5") catch(AE,"AE somewhere") Output AE in line 3 Input 8 try try throw ( CE ) catch ( BE, "BE in line 3") try catch(AE, "AE in line 5") catch(AE,"AE somewhere") Output Unhandled Exception Note In the first sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(BE,"BE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so the second block will be activated, because operator catch(AE,"AE somewhere") has exception type AE as parameter and operator catch(BE,"BE in line 3") has exception type BE. In the second sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(AE,"AE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so both blocks can be activated, but only the first one will be activated, because operator catch(AE,"AE in line 3") is described earlier than catch(AE,"AE somewhere") In the third sample there is no blocks that can be activated by an exception of type CE. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, m, pnt; vector<pair<int, pair<string, string> > > op; char line[64]; bool isEmpty() { for (int i = 0; i < m; i++) { if (isalpha(line[i])) return false; } return true; } void getToken1(char *token) { int length = 0; for (; !isalpha(line[pnt]); pnt++) ; for (; isalpha(line[pnt]); token[length++] = line[pnt++]) ; token[length] = '\0'; } void getToken2(char *token) { int length = 0; for (; line[pnt] != '\"'; pnt++) ; pnt++; for (; line[pnt] != '\"'; token[length++] = line[pnt++]) ; token[length] = '\0'; } stack<int> s; int main() { scanf("%d", &n); gets(line); for (int i = 0; i < n; i++) { gets(line); m = strlen(line); if (isEmpty()) continue; pnt = 0; char token[64]; getToken1(token); if (token[1] == 'r') { op.push_back(make_pair(0, make_pair("", ""))); } else if (token[1] == 'h') { getToken1(token); op.push_back(make_pair(1, make_pair(token, ""))); } else { char token2[64]; getToken1(token); getToken2(token2); op.push_back(make_pair(2, make_pair(token, token2))); } } bool found = false; string throwException; n = op.size(); for (int i = 0; i < n; i++) { if (op[i].first == 0) { s.push(0); } else if (op[i].first == 1) { throwException = op[i].second.first; s.push(1); } else { if (s.top() == 0) { s.pop(); } else if (op[i].second.first == throwException) { found = true; puts(op[i].second.second.c_str()); break; } else { s.pop(); if (s.empty()) { break; } s.pop(); s.push(1); } } } if (!found) { puts("Unhandled Exception"); } return 0; } ```
### Prompt In CPP, your task is to solve the following problem: One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? Input The first line contains integer n (3 ≀ n ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the i-th number in the list is the number of rounds the i-th person wants to play. Output In a single line print a single integer β€” the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 3 3 2 2 Output 4 Input 4 2 2 2 2 Output 3 Note You don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long a; int main() { long long n, mx = 0, i, sum = 0, m, k; cin >> n; for (i = 0; i < n; i++) { cin >> a; mx = max(mx, a); sum += a; } if (mx * (n - 1) >= sum) { cout << mx; return 0; } else { m = sum - mx * (n - 1); k = m / (n - 1); if (m % (n - 1) == 0) k--; cout << mx + k + 1; return 0; } } ```
### Prompt Create a solution in cpp for the following problem: The array a with n integers is given. Let's call the sequence of one or more consecutive elements in a segment. Also let's call the segment k-good if it contains no more than k different values. Find any longest k-good segment. As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. Input The first line contains two integers n, k (1 ≀ k ≀ n ≀ 5Β·105) β€” the number of elements in a and the parameter k. The second line contains n integers ai (0 ≀ ai ≀ 106) β€” the elements of the array a. Output Print two integers l, r (1 ≀ l ≀ r ≀ n) β€” the index of the left and the index of the right ends of some k-good longest segment. If there are several longest segments you can print any of them. The elements in a are numbered from 1 to n from left to right. Examples Input 5 5 1 2 3 4 5 Output 1 5 Input 9 3 6 5 1 2 3 2 1 4 5 Output 3 7 Input 3 1 1 2 3 Output 1 1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long n, k; cin >> n >> k; long long a[n], i, m = 0, s = 0, e, len = 0, start, end; for (i = 0; i < n; i++) cin >> a[i]; map<long long, long long> mp; for (e = 0; e < n; e++) { mp[a[e]]++; while (mp.size() > k && s < n) { mp[a[s]]--; if (mp[a[s]] <= 0) { mp.erase(a[s]); } s++; } len = e - s + 1; if (len > m) { m = len; start = s; end = e; } } cout << start + 1 << " " << end + 1 << "\n"; } ```
### Prompt Your challenge is to write a Cpp solution to the following problem: It is a balmy spring afternoon, and Farmer John's n cows are ruminating about link-cut cacti in their stalls. The cows, labeled 1 through n, are arranged so that the i-th cow occupies the i-th stall from the left. However, Elsie, after realizing that she will forever live in the shadows beyond Bessie's limelight, has formed the Mischievous Mess Makers and is plotting to disrupt this beautiful pastoral rhythm. While Farmer John takes his k minute long nap, Elsie and the Mess Makers plan to repeatedly choose two distinct stalls and swap the cows occupying those stalls, making no more than one swap each minute. Being the meticulous pranksters that they are, the Mischievous Mess Makers would like to know the maximum messiness attainable in the k minutes that they have. We denote as pi the label of the cow in the i-th stall. The messiness of an arrangement of cows is defined as the number of pairs (i, j) such that i < j and pi > pj. Input The first line of the input contains two integers n and k (1 ≀ n, k ≀ 100 000) β€” the number of cows and the length of Farmer John's nap, respectively. Output Output a single integer, the maximum messiness that the Mischievous Mess Makers can achieve by performing no more than k swaps. Examples Input 5 2 Output 10 Input 1 10 Output 0 Note In the first sample, the Mischievous Mess Makers can swap the cows in the stalls 1 and 5 during the first minute, then the cows in stalls 2 and 4 during the second minute. This reverses the arrangement of cows, giving us a total messiness of 10. In the second sample, there is only one cow, so the maximum possible messiness is 0. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 212345, LG = 21, mod = 1000000007; const double eps = 1e-3, pi = acos(-1.0); char s[5], t[5], a[3]; int main() { long long n, k; scanf("%lld", &n), scanf("%lld", &k); if (n / 2 > k) { printf("%lld\n", k * (2 * k - 1) + (n - 2 * k) * 2 * k); } else { printf("%lld\n", (n * (n - 1)) / 2); } return 0; } ```
### Prompt Please create a solution in CPP to the following problem: Two best friends Serozha and Gena play a game. Initially there is one pile consisting of n stones on the table. During one move one pile should be taken and divided into an arbitrary number of piles consisting of a1 > a2 > ... > ak > 0 stones. The piles should meet the condition a1 - a2 = a2 - a3 = ... = ak - 1 - ak = 1. Naturally, the number of piles k should be no less than two. The friends play in turns. The player who cannot make a move loses. Serozha makes the first move. Who will win if both players play in the optimal way? Input The single line contains a single integer n (1 ≀ n ≀ 105). Output If Serozha wins, print k, which represents the minimal number of piles into which he can split the initial one during the first move in order to win the game. If Gena wins, print "-1" (without the quotes). Examples Input 3 Output 2 Input 6 Output -1 Input 100 Output 8 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1e5 + 10; int n, a, k, ans = N, gx, xr[N]; bool win = 0, vis[N]; int main() { cin >> n; for (int i = 1; i <= n; i++) { k = 2; memset(vis, 0, sizeof vis); while ((2 * i + k - k * k) >= 1) { if ((2 * i + k - k * k) % (2 * k)) { k++; continue; } a = (2 * i + k - k * k) / (2 * k); vis[xr[a + k - 1] ^ xr[a - 1]] = true; if ((xr[a + k - 1] ^ xr[a - 1]) == 0 && i == n) ans = min(ans, k); k++; } for (int j = 0; j < N; j++) if (!vis[j]) { gx = j; break; } xr[i] = xr[i - 1] ^ gx; } cout << ((xr[n] ^ xr[n - 1]) == 0 ? -1 : ans); return 0; } ```
### Prompt Your task is to create a cpp solution to the following problem: This problem is same as the next one, but has smaller constraints. Aki is playing a new video game. In the video game, he will control Neko, the giant cat, to fly between planets in the Catniverse. There are n planets in the Catniverse, numbered from 1 to n. At the beginning of the game, Aki chooses the planet where Neko is initially located. Then Aki performs k - 1 moves, where in each move Neko is moved from the current planet x to some other planet y such that: * Planet y is not visited yet. * 1 ≀ y ≀ x + m (where m is a fixed constant given in the input) This way, Neko will visit exactly k different planets. Two ways of visiting planets are called different if there is some index i such that the i-th planet visited in the first way is different from the i-th planet visited in the second way. What is the total number of ways to visit k planets this way? Since the answer can be quite large, print it modulo 10^9 + 7. Input The only line contains three integers n, k and m (1 ≀ n ≀ 10^5, 1 ≀ k ≀ min(n, 12), 1 ≀ m ≀ 4) β€” the number of planets in the Catniverse, the number of planets Neko needs to visit and the said constant m. Output Print exactly one integer β€” the number of different ways Neko can visit exactly k planets. Since the answer can be quite large, print it modulo 10^9 + 7. Examples Input 3 3 1 Output 4 Input 4 2 1 Output 9 Input 5 5 4 Output 120 Input 100 1 2 Output 100 Note In the first example, there are 4 ways Neko can visit all the planets: * 1 β†’ 2 β†’ 3 * 2 β†’ 3 β†’ 1 * 3 β†’ 1 β†’ 2 * 3 β†’ 2 β†’ 1 In the second example, there are 9 ways Neko can visit exactly 2 planets: * 1 β†’ 2 * 2 β†’ 1 * 2 β†’ 3 * 3 β†’ 1 * 3 β†’ 2 * 3 β†’ 4 * 4 β†’ 1 * 4 β†’ 2 * 4 β†’ 3 In the third example, with m = 4, Neko can visit all the planets in any order, so there are 5! = 120 ways Neko can visit all the planets. In the fourth example, Neko only visit exactly 1 planet (which is also the planet he initially located), and there are 100 ways to choose the starting planet for Neko. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 210; const long long mod = 1e9 + 7; struct matrix { int n, m; long long arr[N][N]; matrix(int _n = N - 1, int _m = N - 1, int v = 0) { n = _n; m = _m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { arr[i][j] = v; } } } matrix operator*(matrix b) { matrix c(n, b.m, 0); for (int i = 1; i <= n; i++) { for (int k = 1; k <= b.n; k++) { for (int j = 1; j <= b.m; j++) { c.arr[i][j] += arr[i][k] * b.arr[k][j] % mod; c.arr[i][j] %= mod; } } } return c; } matrix pow(long long k) { matrix a(n, n); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { a.arr[i][j] = arr[i][j]; } } matrix b(n, n, 0); for (int i = 1; i <= n; i++) b.arr[i][i] = 1; while (k) { if (k & 1) b = b * a; a = a * a; k >>= 1; } return b; } }; int cnt[N], rec[15][20]; matrix A, R; int main() { long long n, ans; int k, m, tot, state; scanf("%I64d %d %d", &n, &k, &m); for (int i = 0; i < (1 << m); i++) cnt[i] = __builtin_popcount(i); tot = 0; for (int i = 0; i <= k; i++) { for (int j = 0; j < (1 << m); j++) { rec[i][j] = ++tot; } } for (int i = 0; i <= k; i++) { for (int j = 0; j < (1 << m); j++) { state = (j << 1) & ((1 << m) - 1); A.arr[rec[i][j]][rec[i][state]]++; if (i < k) A.arr[rec[i][j]][rec[i + 1][state | 1]] += cnt[j] + 1; } } R = A.pow(n); ans = 0; for (int i = 0; i < (1 << m); i++) { ans += R.arr[1][rec[k][i]]; ans %= mod; } printf("%I64d\n", ans); return 0; } ```
### Prompt Create a solution in Cpp for the following problem: You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings. Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2'). Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest. Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'. It is guaranteed that the answer exists. Input The first line of the input contains one integer n (3 ≀ n ≀ 3 β‹… 10^5, n is divisible by 3) β€” the number of characters in s. The second line contains the string s consisting of exactly n characters '0', '1' and '2'. Output Print one string β€” the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. Because n is divisible by 3 it is obvious that the answer exists. And it is obvious that there is only one possible answer. Examples Input 3 121 Output 021 Input 6 000000 Output 001122 Input 6 211200 Output 211200 Input 6 120110 Output 120120 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int a[300005]; bool defi[300005]; int sum[4]; int main() { int n; cin >> n; for (int i = 1; i <= n; i++) { scanf("%1d", &a[i]); sum[a[i]]++; } for (int i = 1; i <= n; i++) { if (sum[a[i]] < n / 3) { defi[i] = true; } } for (int i = 1; i <= n; i++) { if (sum[a[i]] > n / 3 && sum[0] < n / 3 && a[i] != 0) { sum[a[i]]--; a[i] = 0; sum[0]++; defi[i] = true; } } for (int i = n; i >= 1; i--) { if (sum[a[i]] > n / 3 && sum[2] < n / 3 && a[i] != 2) { sum[a[i]]--; a[i] = 2; sum[2]++; defi[i] = true; } } for (int i = 1; i <= n; i++) { if (defi[i] == false && sum[a[i]] > n / 3 && a[i] == 2) { sum[a[i]]--; a[i] = 1; sum[1]++; } } for (int i = n; i >= 1; i--) { if (defi[i] == false && sum[a[i]] > n / 3 && a[i] == 0) { sum[a[i]]--; a[i] = 1; sum[1]++; } } for (int i = 1; i <= n; i++) { printf("%d", a[i]); } cout << "\n"; return 0; } ```
### Prompt Create a solution in cpp for the following problem: Taro is playing with a puzzle that places numbers 1-9 in 9x9 squares. In this puzzle, you have to arrange the numbers according to the following rules. * One number appears exactly once in the same column * A number appears exactly once on the same line * In each of the 3x3 ranges separated by double lines, a number appears exactly once. For example, Figure 1 below is one arrangement that meets such a rule. However, Taro often creates an arrangement that violates the rules, as shown in Figure 2. The "2" appears twice in the leftmost column, the "1" never appears, the "1" appears twice in the second column from the left, and the "2" never appears. .. <image> | <image> --- | --- Figure 1 | Figure 2 To help Taro, write a program that reads the arrangement of numbers, checks if the arrangement meets the rules, and outputs the location if it violates the rules. Please display * (half-width asterisk) before the number that is incorrect (appears more than once) according to the three rules, and blank before the number that is not incorrect. Input Given multiple datasets. The first row gives the number of datasets n (n ≀ 20). Each dataset is given a 9-character, 9-line numeric string that indicates the state of the puzzle. Output Output the following for each dataset. Given number, * (half-width asterisk) and blank. Add * before the wrong number and a half-width space before the wrong number. Insert a blank line between the datasets. Example Input 2 2 1 3 4 5 6 7 8 9 4 5 6 7 8 9 1 2 3 7 8 9 1 2 3 4 5 6 2 3 4 5 6 7 8 9 1 5 6 7 8 9 1 2 3 4 8 9 1 2 3 4 5 6 7 3 4 5 6 7 8 9 1 2 6 7 8 9 1 2 3 4 5 9 1 2 3 4 5 6 7 8 2 1 3 4 5 6 7 8 9 4 5 6 7 8 9 1 2 3 7 8 9 1 2 3 4 5 6 2 3 4 5 6 7 8 9 1 5 6 7 8 9 1 2 3 4 8 9 1 2 3 4 5 6 7 3 4 5 6 7 8 9 1 2 6 7 8 9 1 2 3 4 5 9 1 2 3 4 5 6 7 8 Output *2*1 3 4 5 6 7 8 9 4 5 6 7 8 9 1 2 3 7 8 9 1 2 3 4 5 6 *2 3 4 5 6 7 8 9 1 5 6 7 8 9 1 2 3 4 8 9 1 2 3 4 5 6 7 3 4 5 6 7 8 9 1 2 6 7 8 9 1 2 3 4 5 9*1 2 3 4 5 6 7 8 *2*1 3 4 5 6 7 8 9 4 5 6 7 8 9 1 2 3 7 8 9 1 2 3 4 5 6 *2 3 4 5 6 7 8 9 1 5 6 7 8 9 1 2 3 4 8 9 1 2 3 4 5 6 7 3 4 5 6 7 8 9 1 2 6 7 8 9 1 2 3 4 5 9*1 2 3 4 5 6 7 8 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int mp[9][9],flg[9][9],visited[9][9]; void mark(int x,int y, int num){ for(int i=y;i<y+3;i++) for(int j=x;j<x+3;j++) if(mp[i][j]==num) flg[i][j]=1; } void check(int y,int x){ int used[10]={}; for(int i=y;i<y+3;i++) for(int j=x;j<x+3;j++){ if(used[mp[i][j]]) mark(x,y,mp[i][j]); used[mp[i][j]]=visited[i][j]=1; } } int main(){ int q; cin>>q; int cnt=0; while(q--){ if(cnt)cout <<endl; cnt=1; for(int i=0;i<9;i++) for(int j=0;j<9;j++)cin>>mp[i][j]; memset(flg,0,sizeof(flg)); for(int i=0;i<9;i++){ int used[10]={}; for(int j=0;j<9;j++){ for(int k=0;k<9&&used[mp[i][j]];k++) if(mp[i][k]==mp[i][j])flg[i][k]=1; used[mp[i][j]]=1; } } for(int i=0;i<9;i++){ int used[10]={}; for(int j=0;j<9;j++) { if(used[mp[j][i]]) for(int k=0;k<9;k++) if(mp[j][i]==mp[k][i])flg[k][i]=1; used[mp[j][i]]=1; } } memset(visited,0,sizeof(visited)); for(int i=0;i<9;i++) for(int j=0;j<9;j++) if(visited[i][j]==0) check(i,j); for(int i=0;i<9;i++){ for(int j=0;j<9;j++)cout <<(flg[i][j]?"*":" ")<<mp[i][j]; cout <<endl; } } return 0; } ```
### Prompt Please create a solution in cpp to the following problem: Example Input 4 3 1000 1 2000 2 3000 3 Output 2 3 4 4 ### Response ```cpp #include <iostream> #include <cstring> #include <vector> #include <map> #include <algorithm> using namespace std; int low[200001], hi[200001]; int main() { int n, m; cin >> n >> m; for (int i = 0; i < n; ++i) { low[i] = hi[i] = i; } std::vector<std::pair<int, int>> arm; for (int i = 0; i < m; ++i) { int x, y; cin >> x >> y; arm.push_back(make_pair(x, n - 1 - y)); } sort(arm.begin(), arm.end()); for (int i = 0; i < m; ++i) { int y = arm[i].second; // cout << "swap " << y << " " << low[y] << " " << hi[y] << ", " << // low[y+1] << " " << hi[y+1]; low[y + 1] = low[y]; hi[y] = hi[y + 1]; // cout << " -> " << low[y] << " " << hi[y] << ", " << low[y+1] << " " << hi[y+1] <<endl; } for (int i = n - 1; i >= 0; --i) { if (i != n - 1) { cout << " "; } cout << hi[i] - low[i] + 1; } cout << endl; return 0; } ```
### Prompt Please create a solution in CPP to the following problem: Takahashi is going to buy N items one by one. The price of the i-th item he buys is A_i yen (the currency of Japan). He has M discount tickets, and he can use any number of them when buying an item. If Y tickets are used when buying an item priced X yen, he can get the item for \frac{X}{2^Y} (rounded down to the nearest integer) yen. What is the minimum amount of money required to buy all the items? Constraints * All values in input are integers. * 1 \leq N, M \leq 10^5 * 1 \leq A_i \leq 10^9 Input Input is given from Standard Input in the following format: N M A_1 A_2 ... A_N Output Print the minimum amount of money required to buy all the items. Examples Input 3 3 2 13 8 Output 9 Input 4 4 1 9 3 5 Output 6 Input 1 100000 1000000000 Output 0 Input 10 1 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 Output 9500000000 ### Response ```cpp #include<bits/stdc++.h> #include<cstring> #include<algorithm> using namespace std; int main(){ priority_queue<int>q; int m,n,t,i; long long s=0; cin>>n>>m; for(i=0;i<n;i++){ cin>>t; q.push(t); } while(m>0){ t=q.top()/2; q.push(t); q.pop(); m--; } while(!q.empty()){ s+=q.top(); q.pop(); } cout<<s; return 0; } ```
### Prompt Please create a solution in CPP to the following problem: Hanh is a famous biologist. He loves growing trees and doing experiments on his own garden. One day, he got a tree consisting of n vertices. Vertices are numbered from 1 to n. A tree with n vertices is an undirected connected graph with n-1 edges. Initially, Hanh sets the value of every vertex to 0. Now, Hanh performs q operations, each is either of the following types: * Type 1: Hanh selects a vertex v and an integer d. Then he chooses some vertex r uniformly at random, lists all vertices u such that the path from r to u passes through v. Hanh then increases the value of all such vertices u by d. * Type 2: Hanh selects a vertex v and calculates the expected value of v. Since Hanh is good at biology but not math, he needs your help on these operations. Input The first line contains two integers n and q (1 ≀ n, q ≀ 150 000) β€” the number of vertices on Hanh's tree and the number of operations he performs. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n), denoting that there is an edge connecting two vertices u and v. It is guaranteed that these n - 1 edges form a tree. Each of the last q lines describes an operation in either formats: * 1 v d (1 ≀ v ≀ n, 0 ≀ d ≀ 10^7), representing a first-type operation. * 2 v (1 ≀ v ≀ n), representing a second-type operation. It is guaranteed that there is at least one query of the second type. Output For each operation of the second type, write the expected value on a single line. Let M = 998244353, it can be shown that the expected value can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≑ 0 \pmod{M}. Output the integer equal to p β‹… q^{-1} mod M. In other words, output such an integer x that 0 ≀ x < M and x β‹… q ≑ p \pmod{M}. Example Input 5 12 1 2 1 3 2 4 2 5 1 1 1 2 1 2 2 2 3 2 4 2 5 1 2 2 2 1 2 2 2 3 2 4 2 5 Output 1 199648871 399297742 199648871 199648871 598946614 199648873 2 2 2 Note The image below shows the tree in the example: <image> For the first query, where v = 1 and d = 1: * If r = 1, the values of all vertices get increased. * If r = 2, the values of vertices 1 and 3 get increased. * If r = 3, the values of vertices 1, 2, 4 and 5 get increased. * If r = 4, the values of vertices 1 and 3 get increased. * If r = 5, the values of vertices 1 and 3 get increased. Hence, the expected values of all vertices after this query are (1, 0.4, 0.8, 0.4, 0.4). For the second query, where v = 2 and d = 2: * If r = 1, the values of vertices 2, 4 and 5 get increased. * If r = 2, the values of all vertices get increased. * If r = 3, the values of vertices 2, 4 and 5 get increased. * If r = 4, the values of vertices 1, 2, 3 and 5 get increased. * If r = 5, the values of vertices 1, 2, 3 and 4 get increased. Hence, the expected values of all vertices after this query are (2.2, 2.4, 2, 2, 2). ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 4e5 + 5; int n, m, mod = 998244353, r, szz; int tour[N], sz[N], w[N], p[N]; vector<int> heavy; vector<int> g[N], pos[N]; int f[N]; int add(int a, int b) { return (a + b) % mod; } int mul(int a, int b) { return (1LL * a * b) % mod; } void DFS(int i, int j) { tour[++r] = i; pos[i].push_back(r); sz[i] = 1; for (int s = 0; s < g[i].size(); ++s) { int u = g[i][s]; if (u != j) { DFS(u, i); sz[i] += sz[u]; p[u] = i; tour[++r] = i; pos[i].push_back(r); } } } int up(int l, int r, int val) { for (int i = l; i <= szz; i += i & -i) f[i] = add(f[i], val); r++; for (int i = r; i <= szz; i += i & -i) f[i] = (f[i] + mod - val) % mod; } int get(int i) { int ret = 0; for (; i; i -= i & -i) ret = add(ret, f[i]); return ret; } int powmod(int a, int b) { int res = 1; while (b) { if (b & 1) res = mul(res, a); a = mul(a, a); b >>= 1; } return res; } void sp(int &num) { num = 0; register int c; for (c = getchar(); c < 48 || c > 57; c = getchar()) ; for (; c >= 48 && c <= 57; c = getchar()) num = num * 10 + c - 48; } int main() { ios::sync_with_stdio(0); cin.tie(0); sp(n); sp(m); for (int i = 1; i <= n - 1; ++i) { int x, y; sp(x); sp(y); g[x].push_back(y); g[y].push_back(x); } int inv = powmod(n, mod - 2); DFS(1, -1); int k = 300; for (int i = 1; i <= n; ++i) if (g[i].size() >= k) heavy.push_back(i); szz = 2 * n - 1; for (int i = 1; i <= m; ++i) { int type, u, val; sp(type); if (type == 1) { sp(u); sp(val); w[u] = add(w[u], val); if (g[u].size() < k) { for (int s = 0; s < g[u].size(); ++s) { int v = g[u][s]; if (v != p[u]) up(pos[v][0], pos[v].back(), mul(mul(n - sz[v], val), inv)); } if (u == 1) continue; up(1, pos[u][0] - 1, mul(mul(sz[u], val), inv)); up(pos[u].back() + 1, szz, mul(mul(sz[u], val), inv)); } } else { sp(u); int ans = 0; ans = add(w[u], get(pos[u][0])); for (int s = 0; s < heavy.size(); ++s) { int v = heavy[s]; if (u == v) continue; auto it = lower_bound(pos[v].begin(), pos[v].end(), pos[u][0]); if (it == pos[v].begin() || it == pos[v].end()) ans = add(ans, mul(mul(sz[v], w[v]), inv)); else { int p = tour[*(--it) + 1]; ans = add(ans, mul(mul(n - sz[p], w[v]), inv)); } } cout << ans << "\n"; } } } ```
### Prompt Please provide a Cpp coded solution to the problem described below: The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph. Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| β‰₯ wi + wj. Find the size of the maximum clique in such graph. Input The first line contains the integer n (1 ≀ n ≀ 200 000) β€” the number of points. Each of the next n lines contains two numbers xi, wi (0 ≀ xi ≀ 109, 1 ≀ wi ≀ 109) β€” the coordinate and the weight of a point. All xi are different. Output Print a single number β€” the number of vertexes in the maximum clique of the given graph. Examples Input 4 2 3 3 1 6 1 0 2 Output 3 Note If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars! The picture for the sample test. <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; int N; struct Interval { int L, R; } I[200000 + 1]; bool CmpI(const Interval x, const Interval y) { return x.R < y.R; } int main() { scanf("%d", &N); for (int i = 1; i <= N; i++) { int X, W; scanf("%d%d", &X, &W); I[i].L = X - W, I[i].R = X + W; } sort(I + 1, I + N + 1, CmpI); int j = -0X3FFFFFFF, Ans = 0; for (int i = 1; i <= N; i++) if (j <= I[i].L) { j = I[i].R; Ans++; } printf("%d\n", Ans); return 0; } ```
### Prompt Your task is to create a CPP solution to the following problem: Example Input 3 1 3 3 2 1 2 1 3 Output 5 ### Response ```cpp #include <iostream> #include <vector> #include <algorithm> #include <utility> #include <set> #include <map> using namespace std; typedef long long int lli; struct UnionFindTree{ vector<int> v; vector<int> rank; UnionFindTree(int n): v(n, -1), rank(n, 0){} int Find(int x){ if(v[x] < 0) return x; return v[x] = Find(v[x]); } void Union(int a, int b){ a = Find(a); b = Find(b); if(a == b) return; if(rank[a] < rank[b]) swap(a, b); if(rank[a] == rank[b]) rank[a]++; v[b] = a; } }; lli solve(vector<int> &c, vector<vector<int> > &adj){ int n = c.size(); //unite nodes that must be equal UnionFindTree uft(n); for(int i=0; i<n; i++){ map<int, vector<int> > ctoi; for(int j: adj[i]){ ctoi[c[j]].push_back(j); } for(auto itr: ctoi){ vector<int> &a = itr.second; for(int j=0; j<(int)a.size()-1; j++){ if(c[a[j]] == c[a[j+1]]) uft.Union(a[j], a[j+1]); } } } map<int, set<int> > tmp; for(int i=0; i<n; i++){ tmp[uft.Find(i)].insert(i); } map<int, set<int> > eq;// for(auto itr : tmp){ set<int> &a = itr.second; if((int)a.size() <= 1) continue; eq[*max_element(a.begin(), a.end())] = a; } vector<pair<int, int> > con(n);// for(int i=0; i<n; i++){ con[i] = make_pair(c[i], i); } sort(con.begin(), con.end()); //calc saraly vector<int> salary(n); vector<int> slast(n, 0), clast(n, 0); for(int i=0; i<n; i++){ int node = con[i].second; int s = 1; for(int j: adj[node]){ if(clast[j] < c[node]){ s = max(s, slast[j] +1); }else{ s = max(s, slast[j]); } } for(int j: adj[node]){ slast[j] = s; clast[j] = c[node]; } salary[node] = s; //propagation if(eq.count(node) != 0){ int s = 1; for(int j: eq[node]){ s = max(s, salary[j]); } for(int j: eq[node]){ salary[j] = s; for(int k: adj[j]){ slast[k] = s; } } } } lli ret = 0; for(int i=0; i<n; i++){ ret += salary[i]; } return ret; } int main(){ int n; cin >> n; vector<int> c(n); for(int i=0; i<n; i++){ cin >> c[i]; } int m; cin >> m; vector<vector<int> > adj(n); for(int i=0; i<m; i++){ int a,b; cin >> a >> b; a--; b--; adj[a].push_back(b); adj[b].push_back(a); } for(int i=0; i<n; i++){ adj[i].push_back(i); } cout << solve(c, adj) << endl; return 0; } ```
### Prompt Please formulate a CPP solution to the following problem: Mahmoud and Ehab live in a country with n cities numbered from 1 to n and connected by n - 1 undirected roads. It's guaranteed that you can reach any city from any other using these roads. Each city has a number ai attached to it. We define the distance from city x to city y as the xor of numbers attached to the cities on the path from x to y (including both x and y). In other words if values attached to the cities on the path from x to y form an array p of length l then the distance between them is <image>, where <image> is bitwise xor operation. Mahmoud and Ehab want to choose two cities and make a journey from one to another. The index of the start city is always less than or equal to the index of the finish city (they may start and finish in the same city and in this case the distance equals the number attached to that city). They can't determine the two cities so they try every city as a start and every city with greater index as a finish. They want to know the total distance between all pairs of cities. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the number of cities in Mahmoud and Ehab's country. Then the second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 106) which represent the numbers attached to the cities. Integer ai is attached to the city i. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting that there is an undirected road between cities u and v. It's guaranteed that you can reach any city from any other using these roads. Output Output one number denoting the total distance between all pairs of cities. Examples Input 3 1 2 3 1 2 2 3 Output 10 Input 5 1 2 3 4 5 1 2 2 3 3 4 3 5 Output 52 Input 5 10 9 8 7 6 1 2 2 3 3 4 3 5 Output 131 Note A bitwise xor takes two bit integers of equal length and performs the logical xor operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. You can read more about bitwise xor operation here: <https://en.wikipedia.org/wiki/Bitwise_operation#XOR>. In the first sample the available paths are: * city 1 to itself with a distance of 1, * city 2 to itself with a distance of 2, * city 3 to itself with a distance of 3, * city 1 to city 2 with a distance of <image>, * city 1 to city 3 with a distance of <image>, * city 2 to city 3 with a distance of <image>. The total distance between all pairs of cities equals 1 + 2 + 3 + 3 + 0 + 1 = 10. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int NMAX = 100000 + 5; int N; int a[NMAX]; vector<int> graph[NMAX]; bool val[NMAX]; bool simpleVal[NMAX]; void dfsCompute(int node, int bit, int father) { for (auto it : graph[node]) if (it != father) { if (a[it] & (1 << bit)) simpleVal[it] = 1; else simpleVal[it] = 0; val[it] = val[node] ^ simpleVal[it]; dfsCompute(it, bit, node); } } long long int ans = 0; int sz[NMAX][2]; void dfsSolve(int node, int bit, int father) { sz[node][val[node]] = 1; sz[node][val[node] ^ 1] = 0; for (auto it : graph[node]) if (it != father) { dfsSolve(it, bit, node); ans += ((1LL << bit) * sz[it][0] * sz[node][1 ^ simpleVal[node]]); ans += ((1LL << bit) * sz[it][1] * sz[node][0 ^ simpleVal[node]]); sz[node][0] += sz[it][0]; sz[node][1] += sz[it][1]; } } int main() { ios_base ::sync_with_stdio(false); cin.tie(0); cin >> N; for (int i = 1; i <= N; ++i) cin >> a[i]; for (int i = 1; i < N; ++i) { int a, b; cin >> a >> b; graph[a].push_back(b); graph[b].push_back(a); } for (int bit = 0; bit < 20; ++bit) { if (a[1] & (1 << bit)) val[1] = simpleVal[1] = 1; else val[1] = simpleVal[1] = 0; dfsCompute(1, bit, 0); dfsSolve(1, bit, 0); } for (int i = 1; i <= N; ++i) ans += a[i]; cout << ans << '\n'; return 0; } ```
### Prompt Please create a solution in CPP to the following problem: You are given an undirected graph with N vertices and M edges. Here, N-1≀M≀N holds and the graph is connected. There are no self-loops or multiple edges in this graph. The vertices are numbered 1 through N, and the edges are numbered 1 through M. Edge i connects vertices a_i and b_i. The color of each vertex can be either white or black. Initially, all the vertices are white. Snuke is trying to turn all the vertices black by performing the following operation some number of times: * Select a pair of adjacent vertices with the same color, and invert the colors of those vertices. That is, if the vertices are both white, then turn them black, and vice versa. Determine if it is possible to turn all the vertices black. If the answer is positive, find the minimum number of times the operation needs to be performed in order to achieve the objective. Constraints * 2≀N≀10^5 * N-1≀M≀N * 1≀a_i,b_i≀N * There are no self-loops or multiple edges in the given graph. * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 a_2 b_2 : a_M b_M Output If it is possible to turn all the vertices black, print the minimum number of times the operation needs to be performed in order to achieve the objective. Otherwise, print `-1` instead. Examples Input 6 5 1 2 1 3 1 4 2 5 2 6 Output 5 Input 3 2 1 2 2 3 Output -1 Input 4 4 1 2 2 3 3 4 4 1 Output 2 Input 6 6 1 2 2 3 3 1 1 4 1 5 1 6 Output 7 ### Response ```cpp #include<cstdio> #include<cmath> #include<algorithm> using namespace std; #define MAXN 100010 int n,m,ans; int Adj[MAXN],V[MAXN*2],nxt[MAXN*2],c; void AddEdge(int u,int v) { c++;V[c]=v,nxt[c]=Adj[u];Adj[u]=c; } int Sum[MAXN],vis[MAXN],flag[MAXN],cir,cx,cy,tot; int st[MAXN],r; void dfs(int u,int p) { tot+=Sum[u]; vis[u]=1; for(int i=Adj[u];i;i=nxt[i]) if(V[i]!=p) { if(vis[V[i]]) { cx=u,cy=V[i]; cir=(Sum[V[i]]==Sum[u]); continue; } Sum[V[i]]=-Sum[u]; dfs(V[i],u); } } void Solve(int u,int p) { vis[u]=0; for(int i=Adj[u];i;i=nxt[i]) if(V[i]!=p&&vis[V[i]]) { Solve(V[i],u); Sum[u]+=Sum[V[i]]; flag[u]+=flag[V[i]]; } } int main() { scanf("%d%d",&n,&m); int u,v; for(int i=1;i<=m;i++) { scanf("%d%d",&u,&v); AddEdge(u,v); AddEdge(v,u); } Sum[1]=1; dfs(1,0); if(m==n-1) { if(tot!=0) { printf("-1\n"); return 0; } } else if(cir) { if(tot%2!=0) { printf("-1\n"); return 0; } Sum[cx]-=tot/2; Sum[cy]-=tot/2; ans+=abs(tot)/2; } else { if(tot!=0) { printf("-1\n"); return 0; } flag[cx]=-1,flag[cy]=1; } Solve(1,0); for(int i=1;i<=n;i++) { if(flag[i]==0) ans+=abs(Sum[i]); else { if(flag[i]==1) Sum[i]=-Sum[i]; st[++r]=Sum[i]; } } sort(st,st+r+1); int K=st[r/2]; for(int i=0;i<=r;i++) ans+=abs(st[i]-K); printf("%d\n",ans); } ```
### Prompt Construct a cpp code solution to the problem outlined: Polycarpus likes giving presents to Paraskevi. He has bought two chocolate bars, each of them has the shape of a segmented rectangle. The first bar is a1 Γ— b1 segments large and the second one is a2 Γ— b2 segments large. Polycarpus wants to give Paraskevi one of the bars at the lunch break and eat the other one himself. Besides, he wants to show that Polycarpus's mind and Paraskevi's beauty are equally matched, so the two bars must have the same number of squares. To make the bars have the same number of squares, Polycarpus eats a little piece of chocolate each minute. Each minute he does the following: * he either breaks one bar exactly in half (vertically or horizontally) and eats exactly a half of the bar, * or he chips of exactly one third of a bar (vertically or horizontally) and eats exactly a third of the bar. In the first case he is left with a half, of the bar and in the second case he is left with two thirds of the bar. Both variants aren't always possible, and sometimes Polycarpus cannot chip off a half nor a third. For example, if the bar is 16 Γ— 23, then Polycarpus can chip off a half, but not a third. If the bar is 20 Γ— 18, then Polycarpus can chip off both a half and a third. If the bar is 5 Γ— 7, then Polycarpus cannot chip off a half nor a third. What is the minimum number of minutes Polycarpus needs to make two bars consist of the same number of squares? Find not only the required minimum number of minutes, but also the possible sizes of the bars after the process. Input The first line of the input contains integers a1, b1 (1 ≀ a1, b1 ≀ 109) β€” the initial sizes of the first chocolate bar. The second line of the input contains integers a2, b2 (1 ≀ a2, b2 ≀ 109) β€” the initial sizes of the second bar. You can use the data of type int64 (in Pascal), long long (in Π‘++), long (in Java) to process large integers (exceeding 231 - 1). Output In the first line print m β€” the sought minimum number of minutes. In the second and third line print the possible sizes of the bars after they are leveled in m minutes. Print the sizes using the format identical to the input format. Print the sizes (the numbers in the printed pairs) in any order. The second line must correspond to the first bar and the third line must correspond to the second bar. If there are multiple solutions, print any of them. If there is no solution, print a single line with integer -1. Examples Input 2 6 2 3 Output 1 1 6 2 3 Input 36 5 10 16 Output 3 16 5 5 16 Input 3 5 2 1 Output -1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int mod = (int)1e9 + 7; void solve() { int count2a = 0, count3a = 0, count2b = 0, count3b = 0; int x1, x2, y1, y2; cin >> x1 >> y1 >> x2 >> y2; long long area1 = 1ll * x1 * y1, area2 = 1ll * x2 * y2; while (area1 % 2 == 0) { area1 /= 2; count2a++; } while (area1 % 3 == 0) { area1 /= 3; count3a++; } while (area2 % 2 == 0) { area2 /= 2; count2b++; } while (area2 % 3 == 0) { area2 /= 3; count3b++; } if (area1 != area2) { cout << "-1\n"; return; } int time, rem; rem = abs(count3a - count3b); time = rem; if (count3a > count3b) { count2a += rem; while (rem > 0) { if (x1 % 3 == 0) { x1 /= 3; x1 *= 2; } else { y1 /= 3; y1 *= 2; } rem--; } } else { count2b += rem; while (rem > 0) { if (x2 % 3 == 0) { x2 /= 3; x2 *= 2; } else { y2 /= 3; y2 *= 2; } rem--; } } rem = abs(count2a - count2b); time += rem; if (count2a > count2b) { while (rem > 0) { if (x1 % 2 == 0) x1 /= 2; else y1 /= 2; rem--; } } else { while (rem > 0) { if (x2 % 2 == 0) x2 /= 2; else y2 /= 2; rem--; } } cout << time << "\n" << x1 << " " << y1 << "\n" << x2 << " " << y2 << "\n"; } int main() { cin.tie(0), cout.tie(0)->sync_with_stdio(0); int tc = 1; while (tc--) { solve(); } return 0; } ```
### Prompt In CPP, your task is to solve the following problem: A group of n dancers rehearses a performance for the closing ceremony. The dancers are arranged in a row, they've studied their dancing moves and can't change positions. For some of them, a white dancing suit is already bought, for some of them β€” a black one, and for the rest the suit will be bought in the future. On the day when the suits were to be bought, the director was told that the participants of the olympiad will be happy if the colors of the suits on the scene will form a palindrome. A palindrome is a sequence that is the same when read from left to right and when read from right to left. The director liked the idea, and she wants to buy suits so that the color of the leftmost dancer's suit is the same as the color of the rightmost dancer's suit, the 2nd left is the same as 2nd right, and so on. The director knows how many burls it costs to buy a white suit, and how many burls to buy a black suit. You need to find out whether it is possible to buy suits to form a palindrome, and if it's possible, what's the minimal cost of doing so. Remember that dancers can not change positions, and due to bureaucratic reasons it is not allowed to buy new suits for the dancers who already have suits, even if it reduces the overall spending. Input The first line contains three integers n, a, and b (1 ≀ n ≀ 20, 1 ≀ a, b ≀ 100) β€” the number of dancers, the cost of a white suit, and the cost of a black suit. The next line contains n numbers c_i, i-th of which denotes the color of the suit of the i-th dancer. Number 0 denotes the white color, 1 β€” the black color, and 2 denotes that a suit for this dancer is still to be bought. Output If it is not possible to form a palindrome without swapping dancers and buying new suits for those who have one, then output -1. Otherwise, output the minimal price to get the desired visual effect. Examples Input 5 100 1 0 1 2 1 2 Output 101 Input 3 10 12 1 2 0 Output -1 Input 3 12 1 0 1 0 Output 0 Note In the first sample, the cheapest way to obtain palindromic colors is to buy a black suit for the third from left dancer and a white suit for the rightmost dancer. In the second sample, the leftmost dancer's suit already differs from the rightmost dancer's suit so there is no way to obtain the desired coloring. In the third sample, all suits are already bought and their colors form a palindrome. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n, black, white, a[25], i, j, total = 0, temp = 0; cin >> n >> white >> black; for (i = 0; i < n; i++) { cin >> a[i]; } for (i = 0; i < n / 2; i++) { j = i + 1; if (a[i] != a[n - j] || (a[i] == 2 && a[n - j] == 2)) { if (a[i] + a[n - j] == 1) { temp = 1; break; } else { if ((a[n - j] == 1 && a[i] == 2) || ((a[n - j] == 2 && a[i] == 1))) { total += black; } else if ((a[n - j] == 0 && a[i] == 2) || ((a[n - j] == 2 && a[i] == 0))) { total += white; } else { total += (min(black, white) * 2); } } } } if (n % 2 == 1 && a[n / 2] == 2) total += min(black, white); if (temp == 0) cout << total << endl; else cout << "-1" << endl; } ```
### Prompt Construct a cpp code solution to the problem outlined: We have a sequence of length N consisting of non-negative integers. Consider performing the following operation on this sequence until the largest element in this sequence becomes N-1 or smaller. * Determine the largest element in the sequence (if there is more than one, choose one). Decrease the value of this element by N, and increase each of the other elements by 1. It can be proved that the largest element in the sequence becomes N-1 or smaller after a finite number of operations. You are given an integer K. Find an integer sequence a_i such that the number of times we will perform the above operation is exactly K. It can be shown that there is always such a sequence under the constraints on input and output in this problem. Constraints * 0 ≀ K ≀ 50 \times 10^{16} Input Input is given from Standard Input in the following format: K Output Print a solution in the following format: N a_1 a_2 ... a_N Here, 2 ≀ N ≀ 50 and 0 ≀ a_i ≀ 10^{16} + 1000 must hold. Examples Input 0 Output 4 3 3 3 3 Input 1 Output 3 1 0 3 Input 2 Output 2 2 2 Input 3 Output 7 27 0 0 0 0 0 0 Input 1234567894848 Output 10 1000 193 256 777 0 1 1192 1234567891011 48 425 ### Response ```cpp #include<bits/stdc++.h> using namespace std; typedef long long LL; LL K, n, r; int main(){ scanf("%lld", &K); puts("50"); n = K / 50; r = K % 50; for (int i=1; i<=r; i++) printf("%lld ", 99-r+n); for (int i=r+1; i<=50; i++) printf("%lld ", 49-r+n); return 0; } ```
### Prompt Your task is to create a Cpp solution to the following problem: This is an easier version of the problem. In this version n ≀ 1000 The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot. Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it. Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 ≀ a_i ≀ m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i. The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors. Input The first line contains a single integer n (1 ≀ n ≀ 1000) β€” the number of plots. The second line contains the integers m_1, m_2, …, m_n (1 ≀ m_i ≀ 10^9) β€” the limit on the number of floors for every possible number of floors for a skyscraper on each plot. Output Print n integers a_i β€” the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible. If there are multiple answers possible, print any of them. Examples Input 5 1 2 3 2 1 Output 1 2 3 2 1 Input 3 10 6 8 Output 10 6 6 Note In the first example, you can build all skyscrapers with the highest possible height. In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10, 6, 6] is optimal. Note that the answer of [6, 6, 8] also satisfies all restrictions, but is not optimal. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, m[1001], a[1001], ans[1001], s = 0; long long tot, sum; int main() { cin >> n; for (int i = 0; i < n; i++) cin >> m[i]; for (int i = 0; i < n; i++) { a[i] = m[i], sum = m[i]; for (int j = i - 1; j >= 0; j--) a[j] = min(m[j], a[j + 1]), sum += a[j]; for (int j = i + 1; j < n; j++) a[j] = min(m[j], a[j - 1]), sum += a[j]; if (tot < sum) { tot = sum; for (int j = 0; j < n; j++) ans[j] = a[j]; } } for (int i = 0; i < n - 1; i++) cout << ans[i] << " "; cout << ans[n - 1] << endl; cin.clear(); cin.sync(); cin.get(); return 0; } ```
### Prompt Please create a solution in Cpp to the following problem: Recently Anton found a box with digits in his room. There are k2 digits 2, k3 digits 3, k5 digits 5 and k6 digits 6. Anton's favorite integers are 32 and 256. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task! Each digit can be used no more than once, i.e. the composed integers should contain no more than k2 digits 2, k3 digits 3 and so on. Of course, unused digits are not counted in the sum. Input The only line of the input contains four integers k2, k3, k5 and k6 β€” the number of digits 2, 3, 5 and 6 respectively (0 ≀ k2, k3, k5, k6 ≀ 5Β·106). Output Print one integer β€” maximum possible sum of Anton's favorite integers that can be composed using digits from the box. Examples Input 5 1 3 4 Output 800 Input 1 1 1 1 Output 256 Note In the first sample, there are five digits 2, one digit 3, three digits 5 and four digits 6. Anton can compose three integers 256 and one integer 32 to achieve the value 256 + 256 + 256 + 32 = 800. Note, that there is one unused integer 2 and one unused integer 6. They are not counted in the answer. In the second sample, the optimal answer is to create on integer 256, thus the answer is 256. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAX_N = 1e5 + 1; const long long MOD = 1e9 + 7; const long long INF = 1e9; void solve() { int k2, k3, k5, k6; cin >> k2 >> k3 >> k5 >> k6; int big = min(k2, min(k5, k6)), ans = 0; ans += big * 256; k2 -= big; if (k2 > 0 and k3 > 0) { int small = min(k2, k3); ans += small * 32; } cout << ans; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); solve(); } ```
### Prompt Please create a solution in cpp to the following problem: Bob is playing with 6-sided dice. A net of such standard cube is shown below. <image> He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice. For example, the number of visible pips on the tower below is 29 β€” the number visible on the top is 1, from the south 5 and 3, from the west 4 and 2, from the north 2 and 4 and from the east 3 and 5. <image> The one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total. Bob also has t favourite integers x_i, and for every such integer his goal is to build such a tower that the number of visible pips is exactly x_i. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of favourite integers of Bob. The second line contains t space-separated integers x_i (1 ≀ x_i ≀ 10^{18}) β€” Bob's favourite integers. Output For each of Bob's favourite integers, output "YES" if it is possible to build the tower, or "NO" otherwise (quotes for clarity). Example Input 4 29 34 19 38 Output YES YES YES NO Note The first example is mentioned in the problem statement. In the second example, one can build the tower by flipping the top dice from the previous tower. In the third example, one can use a single die that has 5 on top. The fourth example is impossible. ### Response ```cpp #include <bits/stdc++.h> using namespace std; map<int, int> m; int main() { int n; cin >> n; while (n--) { long long k; cin >> k; if (k % 14 <= 6 && k % 14 >= 1 && k > 14) cout << "YES"; else cout << "NO"; cout << endl; } } ```
### Prompt Your challenge is to write a Cpp solution to the following problem: Hakone Ekiden is one of the Japanese New Year's traditions. In Hakone Ekiden, 10 runners from each team aim for the goal while connecting the sashes at each relay station. In the TV broadcast, the ranking change from the previous relay station is displayed along with the passing order of each team at the relay station. So, look at it and tell us how many possible passage orders for each team at the previous relay station. The number of possible transit orders can be very large, so answer by the remainder divided by 1,000,000,007. Input The input is given in the form: > n > c1 > c2 > ... > cn > The number n (1 ≀ n ≀ 200) representing the number of teams is on the first line, and the ranking changes from the previous relay station in order from the first place on the following n lines. If it is'`U`', the ranking is up, if it is'`-`', the ranking is not changed) is written. Output Please output in one line by dividing the number of passages that could have been the previous relay station by 1,000,000,007. Examples Input 3 - U D Output 1 Input 5 U U - D D Output 5 Input 8 U D D D D D D D Output 1 Input 10 U D U D U D U D U D Output 608 Input 2 D U Output 0 ### Response ```cpp #include <bits/stdc++.h> using namespace std; #define int long long int dp[210][210][210]; string s[210]; int M[210]; int Dcnt,Ucnt; int D[210]; int U[210]; int n; // x: ?????? // a: ???????????Β¨????????Β° // b: ?????Β£?????????U?????Β° // U int mod = 1000000007; int dfs(int x,int a,int b){ if( x == n ){ return a == 0 && b == 0; } if( dp[x][a][b] != -1 ) return dp[x][a][b]; if( s[x] == "-" ) return dfs(x+1,a,b); int ans = 0; if( s[x] == "U" ){ //??????????????Β΄??? ans += dfs(x+1,a+1,b+1); if(b) ans += dfs(x+1,a,b) * b; }else{ // D????????Β£??? U??????????????? if(a) ans += dfs(x+1,a,b) * a; //?????Β£????????? if(a&&b){ ans += dfs(x+1,a-1,b-1) * a * b; } } ans %= mod; return dp[x][a][b] = ans; } signed main(){ memset(dp,-1,sizeof(dp)); cin >> n; int cnt = 0; for(int i = 0 ; i < n ; i++){ cin >> s[i]; } cout << dfs(0,0,0) << endl; } ```
### Prompt Please provide a CPP coded solution to the problem described below: A non-empty string s is called binary, if it consists only of characters "0" and "1". Let's number the characters of binary string s from 1 to the string's length and let's denote the i-th character in string s as si. Binary string s with length n is periodical, if there is an integer 1 ≀ k < n such that: * k is a divisor of number n * for all 1 ≀ i ≀ n - k, the following condition fulfills: si = si + k For example, binary strings "101010" and "11" are periodical and "10" and "10010" are not. A positive integer x is periodical, if its binary representation (without leading zeroes) is a periodic string. Your task is to calculate, how many periodic numbers are in the interval from l to r (both ends are included). Input The single input line contains two integers l and r (1 ≀ l ≀ r ≀ 1018). The numbers are separated by a space. 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, showing how many periodic numbers are in the interval from l to r (both ends are included). Examples Input 1 10 Output 3 Input 25 38 Output 2 Note In the first sample periodic numbers are 3, 7 and 10. In the second sample periodic numbers are 31 and 36. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long N = 67, OO = 1e8, M = 1e9 + 7, P = 6151, sq = 360, lg = 23; vector<long long> p[N]; long long g[N][N], pw[N]; long long get(long long x) { if (x == 1) return 0; long long cnt = 0; for (auto u : p[x]) cnt += pw[u]; return cnt + get(x - 1); } long long ans(long long x) { if (x <= 1) return 0; long long k = log2(x); vector<bool> v; long long cnt = get(k); long long hn = 0, y = x; while (x > 0) v.push_back(x % 2), hn += (x % 2), x /= 2; k++; reverse(v.begin(), v.end()); for (long long i = 0; i < p[k].size(); i++) { long long t = p[k][i]; g[k][t] = 0; for (long long j = 1; j < t; j++) { if (v[j] == 0) continue; g[k][t] += (1ll << (t - j - 1)); } bool u = true; for (long long j = 0; j < k; j++) { if (v[j % t] < v[j]) break; if (v[j % t] == v[j]) continue; u = false; break; } g[k][t] += u; for (long long j = 0; j < i; j++) { long long z = p[k][j]; if (t % z != 0) continue; g[k][t] -= g[k][z]; } cnt += g[k][t]; } return cnt; } int32_t main() { ios::sync_with_stdio(false), cin.tie(0), cout.tie(0); long long l, r; for (long long i = 1; i < 64; i++) { bool u = true; pw[i] = (1ll << (i - 1)); for (long long j = 1; j < i; j++) if (i % j == 0) p[i].push_back(j), pw[i] -= pw[j]; } cin >> l >> r; cout << ans(r) - ans(l - 1) << endl; return 0; } ```
### Prompt Please create a solution in cpp to the following problem: Some company is going to hold a fair in Byteland. There are n towns in Byteland and m two-way roads between towns. Of course, you can reach any town from any other town using roads. There are k types of goods produced in Byteland and every town produces only one type. To hold a fair you have to bring at least s different types of goods. It costs d(u,v) coins to bring goods from town u to town v where d(u,v) is the length of the shortest path from u to v. Length of a path is the number of roads in this path. The organizers will cover all travel expenses but they can choose the towns to bring goods from. Now they want to calculate minimum expenses to hold a fair in each of n towns. Input There are 4 integers n, m, k, s in the first line of input (1 ≀ n ≀ 10^{5}, 0 ≀ m ≀ 10^{5}, 1 ≀ s ≀ k ≀ min(n, 100)) β€” the number of towns, the number of roads, the number of different types of goods, the number of different types of goods necessary to hold a fair. In the next line there are n integers a_1, a_2, …, a_n (1 ≀ a_{i} ≀ k), where a_i is the type of goods produced in the i-th town. It is guaranteed that all integers between 1 and k occur at least once among integers a_{i}. In the next m lines roads are described. Each road is described by two integers u v (1 ≀ u, v ≀ n, u β‰  v) β€” the towns connected by this road. It is guaranteed that there is no more than one road between every two towns. It is guaranteed that you can go from any town to any other town via roads. Output Print n numbers, the i-th of them is the minimum number of coins you need to spend on travel expenses to hold a fair in town i. Separate numbers with spaces. Examples Input 5 5 4 3 1 2 4 3 2 1 2 2 3 3 4 4 1 4 5 Output 2 2 2 2 3 Input 7 6 3 2 1 2 3 3 2 2 1 1 2 2 3 3 4 2 5 5 6 6 7 Output 1 1 1 2 2 1 1 Note Let's look at the first sample. To hold a fair in town 1 you can bring goods from towns 1 (0 coins), 2 (1 coin) and 4 (1 coin). Total numbers of coins is 2. Town 2: Goods from towns 2 (0), 1 (1), 3 (1). Sum equals 2. Town 3: Goods from towns 3 (0), 2 (1), 4 (1). Sum equals 2. Town 4: Goods from towns 4 (0), 1 (1), 5 (1). Sum equals 2. Town 5: Goods from towns 5 (0), 4 (1), 3 (2). Sum equals 3. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int const N = 1e5 + 5; int const NN = 105; int n, m, k, s; int d[N][NN], que[N]; vector<int> a[N]; vector<int> ver[NN]; void bfs(int type) { int top = 0, bot = 1; for (int i : ver[type]) { que[++top] = i; d[i][type] = 0; } while (bot <= top) { int u = que[bot]; bot++; for (int v : a[u]) { if (d[v][type] == -1) { d[v][type] = d[u][type] + 1; que[++top] = v; } } } } int main() { scanf("%d %d %d %d", &n, &m, &k, &s); for (int i = 1; i <= n; i++) { int type; scanf("%d", &type); ver[type].push_back(i); } for (int i = 1; i <= m; i++) { int u, v; scanf("%d %d", &u, &v); a[u].push_back(v); a[v].push_back(u); } memset(d, -1, sizeof(d)); for (int i = 1; i <= k; i++) { bfs(i); } for (int i = 1; i <= n; i++) { sort(d[i] + 1, d[i] + k + 1); int ans = 0; for (int type = 1; type <= s; type++) { ans += d[i][type]; } printf("%d ", ans); } printf("\n"); } ```
### Prompt Create a solution in CPP for the following problem: The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages! In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage. But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces). The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero. Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens. Input The first line contains an integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 1012) β€” Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Print a single integer β€” the maximum pleasure BitHaval and BitAryo can get from the dinner. Examples Input 2 1 2 Output 3 Input 3 1 2 3 Output 3 Input 2 1000 1000 Output 1000 ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct Node { struct Node *next[2]; long long num; int cnt; } * root; int n; bool bit[45]; long long a[200005], pre[200005], maxi; struct Node *Create(long long num) { struct Node *tmp = (struct Node *)malloc(sizeof(struct Node)); tmp->num = num; tmp->cnt = 0; tmp->next[0] = tmp->next[1] = NULL; return tmp; } void Insert(long long num) { struct Node *ptr = root; for (int i = 0; i < 40; i++) { if (ptr->next[bit[i]] == NULL) ptr->next[bit[i]] = Create(i == 39 ? num : 0LL); ptr = ptr->next[bit[i]]; } ptr->cnt += 1; } bool Delete(struct Node *ptr, int i) { if (i == 40) { ptr->cnt -= 1; if (ptr->cnt == 0) { free(ptr); return true; } else { return false; } } else { if (Delete(ptr->next[bit[i]], i + 1)) { ptr->next[bit[i]] = NULL; if (ptr->next[0] == NULL && ptr->next[1] == NULL) { free(ptr); return true; } else { return false; } } else { return false; } } } void freeAll(struct Node *ptr) { for (int i = 0; i < 2; i++) if (ptr->next[i] != NULL) freeAll(ptr->next[i]); free(ptr); } long long Find() { struct Node *ptr = root; for (int i = 0; i < 40; i++) { if (ptr->next[!bit[i]] != NULL) ptr = ptr->next[!bit[i]]; else ptr = ptr->next[bit[i]]; } return ptr->num; } void change(long long num) { long long tmp = 1LL << 39; for (int i = 0; i < 40; i++) { if ((tmp & num) == tmp) bit[i] = 1; else bit[i] = 0; tmp /= 2; } } void go() { root = Create(0LL); maxi = 0; change(0LL); Insert(0LL); for (int i = 1; i <= n * 2; i++) { if (i <= n) { change(pre[i]); maxi = max(maxi, pre[i]); Insert(pre[i]); } else { change(pre[i - n - 1]); Delete(root, 0); change(pre[i]); maxi = max(maxi, pre[i] ^ Find()); } } for (int i = n + 1; i < n * 2; i++) maxi = max(maxi, pre[i] ^ pre[2 * n]); printf("%I64d\n", maxi); freeAll(root); } int main() { while (scanf(" %d", &n) != EOF) { for (int i = 1; i <= n; i++) { scanf(" %I64d", &a[i]); a[i + n] = a[i]; } pre[0] = 0; for (int i = 1; i <= 2 * n; i++) pre[i] = pre[i - 1] ^ a[i]; go(); } return 0; } ```
### Prompt Develop a solution in CPP to the problem described below: DLS and JLS are bored with a Math lesson. In order to entertain themselves, DLS took a sheet of paper and drew n distinct lines, given by equations y = x + p_i for some distinct p_1, p_2, …, p_n. Then JLS drew on the same paper sheet m distinct lines given by equations y = -x + q_i for some distinct q_1, q_2, …, q_m. DLS and JLS are interested in counting how many line pairs have integer intersection points, i.e. points with both coordinates that are integers. Unfortunately, the lesson will end up soon, so DLS and JLS are asking for your help. Input The first line contains one integer t (1 ≀ t ≀ 1000), the number of test cases in the input. Then follow the test case descriptions. The first line of a test case contains an integer n (1 ≀ n ≀ 10^5), the number of lines drawn by DLS. The second line of a test case contains n distinct integers p_i (0 ≀ p_i ≀ 10^9) describing the lines drawn by DLS. The integer p_i describes a line given by the equation y = x + p_i. The third line of a test case contains an integer m (1 ≀ m ≀ 10^5), the number of lines drawn by JLS. The fourth line of a test case contains m distinct integers q_i (0 ≀ q_i ≀ 10^9) describing the lines drawn by JLS. The integer q_i describes a line given by the equation y = -x + q_i. The sum of the values of n over all test cases in the input does not exceed 10^5. Similarly, the sum of the values of m over all test cases in the input does not exceed 10^5. In hacks it is allowed to use only one test case in the input, so t=1 should be satisfied. Output For each test case in the input print a single integer β€” the number of line pairs with integer intersection points. Example Input 3 3 1 3 2 2 0 3 1 1 1 1 1 2 1 1 Output 3 1 0 Note The picture shows the lines from the first test case of the example. Black circles denote intersection points with integer coordinates. <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; int t, n, x, cnt_0[2], cnt_1[2]; void read(int* a) { fill(a, a + 2, 0); cin >> n; while (n--) { cin >> x; a[x & 1]++; } } int main() { ios::sync_with_stdio(false), cin.tie(0); cin >> t; while (t--) { read(cnt_0); read(cnt_1); cout << 1LL * cnt_0[0] * cnt_1[0] + 1LL * cnt_0[1] * cnt_1[1] << '\n'; } return 0; } ```
### Prompt Construct a cpp code solution to the problem outlined: It's been long after the events of the previous problems, and Karen has now moved on from student life and is looking to relocate to a new neighborhood. <image> The neighborhood consists of n houses in a straight line, labelled 1 to n from left to right, all an equal distance apart. Everyone in this neighborhood loves peace and quiet. Because of this, whenever a new person moves into the neighborhood, he or she always chooses the house whose minimum distance to any occupied house is maximized. If there are multiple houses with the maximum possible minimum distance, he or she chooses the leftmost one. Note that the first person to arrive always moves into house 1. Karen is the k-th person to enter this neighborhood. If everyone, including herself, follows this rule, which house will she move into? Input The first and only line of input contains two integers, n and k (1 ≀ k ≀ n ≀ 1018), describing the number of houses in the neighborhood, and that Karen was the k-th person to move in, respectively. Output Output a single integer on a line by itself, the label of the house Karen will move into. Examples Input 6 4 Output 2 Input 39 3 Output 20 Note In the first test case, there are 6 houses in the neighborhood, and Karen is the fourth person to move in: 1. The first person moves into house 1. 2. The second person moves into house 6. 3. The third person moves into house 3. 4. The fourth person moves into house 2. In the second test case, there are 39 houses in the neighborhood, and Karen is the third person to move in: 1. The first person moves into house 1. 2. The second person moves into house 39. 3. The third person moves into house 20. ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct th { long long num, len, ans; th(long long a, long long b) { num = a, len = b; } bool operator<(const th &a) const { if (num != a.num) return num < a.num; return len < a.len; } }; set<th> ans; long long get(long long len, long long num) { th new1 = th(num, len); set<th>::iterator it = ans.find(new1); if (it != ans.end()) return (*it).ans; long long mid = (1 + len) >> 1; new1.ans = 0; if (mid - 1 >= num) new1.ans = 1 + get(mid, num) + get(len - mid + 1, num); ans.insert(new1); return new1.ans; } long long gpl(long long len, long long num, long long id) { if (len == 1) return 1; long long mid = (1 + len) >> 1; long long ans = 0; if (id == 1) ans = mid; else { long long lans = get(mid, num); long long rans = get(len - mid + 1, num + 1); if (lans + rans + 1 >= id && lans) ans = gpl(mid, num, id - rans - 1); else ans = mid - 1 + gpl(len - mid + 1, num, id - lans - 1); } return ans; } int main() { long long n, k; scanf("%I64d%I64d", &n, &k); if (k == 1) { puts("1\n"); return 0; } if (k == 2) { printf("%I64d\n", n); return 0; } k -= 2; long long l = 0, r = n; while (l < r) { long long mid = (l + r) >> 1; if (get(n, mid + 1) >= k) l = mid + 1; else r = mid; } printf("%I64d\n", gpl(n, l, k)); return 0; } ```
### Prompt Construct a CPP code solution to the problem outlined: A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string. You are given a string s, consisting of lowercase English letters and a positive integer k. Your task is to reorder the letters in the string s in such a way that the resulting string is a k-string. Input The first input line contains integer k (1 ≀ k ≀ 1000). The second line contains s, all characters in s are lowercase English letters. The string length s satisfies the inequality 1 ≀ |s| ≀ 1000, where |s| is the length of string s. Output Rearrange the letters in string s in such a way that the result is a k-string. Print the result on a single output line. If there are multiple solutions, print any of them. If the solution doesn't exist, print "-1" (without quotes). Examples Input 2 aazz Output azaz Input 3 abcabcabz Output -1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int counter[32]; int k; string getString() { for (int i = (0); i < (int)(32); i++) if (counter[i] % k) return "-1"; string pattern = ""; for (int i = (0); i < (int)(32); i++) { for (int j = (0); j < (int)(counter[i] / k); j++) { pattern += (char)('a' + i); } } string res = ""; for (int i = (0); i < (int)(k); i++) res += pattern; return res; } int main() { memset(counter, 0, sizeof(counter)); cin >> k; char c; while (cin >> c) { counter[c - 'a']++; } cout << getString() << endl; } ```
### Prompt Please formulate a cpp solution to the following problem: You are given an array a consisting of n integers, and additionally an integer m. You have to choose some sequence of indices b1, b2, ..., bk (1 ≀ b1 < b2 < ... < bk ≀ n) in such a way that the value of <image> is maximized. Chosen sequence can be empty. Print the maximum possible value of <image>. Input The first line contains two integers n and m (1 ≀ n ≀ 35, 1 ≀ m ≀ 109). The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output Print the maximum possible value of <image>. Examples Input 4 4 5 2 4 1 Output 3 Input 3 20 199 41 299 Output 19 Note In the first example you can choose a sequence b = {1, 2}, so the sum <image> is equal to 7 (and that's 3 after taking it modulo 4). In the second example you can choose a sequence b = {3}. ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename t> using V = vector<t>; int n, m; V<int> tab[2]; V<int> val[2]; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cin >> n >> m; for (int i = 0; i < n; ++i) { int p; cin >> p; tab[i % 2].push_back(p); } for (int i = 0; i < 2; ++i) { for (int k = 0; k < (1 << tab[i].size()); ++k) { long long sum = 0; for (int j = 0; j < tab[i].size(); ++j) if ((1 << j) & k) sum += tab[i][j]; sum %= m; val[i].push_back(sum); } } int res = 0; sort((val[1]).begin(), (val[1]).end()); for (int i = 0; i < val[0].size(); ++i) { int szuk = m - val[0][i]; int lo = -1; for (int b = val[1].size(); b >= 1; b /= 2) while (lo + b < val[1].size() and val[1][lo + b] < szuk) lo += b; res = max(res, val[1][lo] + val[0][i]); } cout << res << '\n'; } ```
### Prompt Create a solution in Cpp for the following problem: You're given a tree with n vertices rooted at 1. We say that there's a k-ary heap of depth m located at u if the following holds: * For m = 1 u itself is a k-ary heap of depth 1. * For m > 1 vertex u is a k-ary heap of depth m if at least k of its children are k-ary heaps of depth at least m - 1. Denote dpk(u) as maximum depth of k-ary heap in the subtree of u (including u). Your goal is to compute <image>. Input The first line contains an integer n denoting the size of the tree (2 ≀ n ≀ 3Β·105). The next n - 1 lines contain two integers u, v each, describing vertices connected by i-th edge. It's guaranteed that the given configuration forms a tree. Output Output the answer to the task. Examples Input 4 1 3 2 3 4 3 Output 21 Input 4 1 2 2 3 3 4 Output 22 Note Consider sample case one. For k β‰₯ 3 all dpk will be equal to 1. For k = 2 dpk is 2 if <image> and 1 otherwise. For k = 1 dpk values are (3, 1, 2, 1) respectively. To sum up, 4Β·1 + 4Β·1 + 2Β·2 + 2Β·1 + 3 + 1 + 2 + 1 = 21. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 3e5 + 100; vector<int> G[N]; int dp[N][75]; int sub[N][75]; int dp1[N], dp2[N]; int M, n; long long ans; void dfs(int u, int p) { int child = 0; vector<int> ch_sz; for (int v : G[u]) { if (v == p) continue; dfs(v, u); for (int k = 1; k < M; k++) { sub[u][k] = max(sub[u][k], sub[v][k]); } dp1[u] = max(dp1[u], dp1[v]); dp2[u] = max(dp2[u], dp2[v]); child++; ch_sz.push_back(G[v].size() - 1); } sort(ch_sz.rbegin(), ch_sz.rend()); for (int k = 1; k <= min(child, M - 1); k++) { vector<int> opts; for (int v : G[u]) { if (v == p) continue; opts.push_back(-dp[v][k]); } nth_element(opts.begin(), opts.begin() + k - 1, opts.end()); dp[u][k] = max(dp[u][k], -opts[k - 1] + 1); } for (int k = 1; k < M; k++) { sub[u][k] = max(sub[u][k], dp[u][k]); ans += sub[u][k] + 1; } if (ch_sz.size() > 0 && ch_sz[0] > 0) { int lo = 1, hi = ch_sz.size(); while (hi > lo) { int mid = (hi + lo + 1) / 2; if (ch_sz[mid - 1] >= mid) lo = mid; else hi = mid - 1; } dp1[u] = max(dp1[u], lo); } dp2[u] = max(dp2[u], (int)ch_sz.size()); ans += (n - M + 1); if (dp1[u] >= M) ans += (dp1[u] - M + 1); if (dp2[u] >= M) ans += (dp2[u] - M + 1); } int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> n; M = min(70, n + 1); for (int i = 1; i < n; i++) { int u, v; cin >> u >> v; G[u].push_back(v); G[v].push_back(u); } dfs(1, -1); cout << ans << endl; return 0; } ```
### Prompt Your task is to create a CPP solution to the following problem: Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the `0` key, the `1` key and the backspace key. To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this string is empty. When each key on the keyboard is pressed, the following changes occur to the string: * The `0` key: a letter `0` will be inserted to the right of the string. * The `1` key: a letter `1` will be inserted to the right of the string. * The backspace key: if the string is empty, nothing happens. Otherwise, the rightmost letter of the string is deleted. Sig has launched the editor, and pressed these keys several times. You are given a string s, which is a record of his keystrokes in order. In this string, the letter `0` stands for the `0` key, the letter `1` stands for the `1` key and the letter `B` stands for the backspace key. What string is displayed in the editor now? Constraints * 1 ≦ |s| ≦ 10 (|s| denotes the length of s) * s consists of the letters `0`, `1` and `B`. * The correct answer is not an empty string. Input The input is given from Standard Input in the following format: s Output Print the string displayed in the editor in the end. Examples Input 01B0 Output 00 Input 0BB1 Output 1 ### Response ```cpp #include<bits/stdc++.h> using namespace std; typedef long long ll; int main () { string s,ans; cin >> s; for(int i=0;i<s.size();i++){ if(s[i]=='B'){ if(ans.size()!=0) ans.erase(ans.size()-1); }else{ ans+=s[i]; } } cout<<ans<<endl; return 0; } ```
### Prompt Please create a solution in CPP to the following problem: Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai. Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard? Input The first line of the input contains two integers n and h (1 ≀ n ≀ 1000, 1 ≀ h ≀ 1000) β€” the number of friends and the height of the fence, respectively. The second line contains n integers ai (1 ≀ ai ≀ 2h), the i-th of them is equal to the height of the i-th person. Output Print a single integer β€” the minimum possible valid width of the road. Examples Input 3 7 4 5 14 Output 4 Input 6 1 1 1 1 1 1 1 Output 6 Input 6 5 7 6 8 9 10 5 Output 11 Note In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4. In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough. In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n, h; cin >> n >> h; int ans = 0; for (int i = 1; i <= n; i++) { int t; cin >> t; if (t > h) ans += 2; else ans += 1; } cout << ans << endl; return 0; } ```
### Prompt Construct a Cpp code solution to the problem outlined: There is a grid with H rows and W columns. The square at the i-th row and j-th column contains a string S_{i,j} of length 5. The rows are labeled with the numbers from 1 through H, and the columns are labeled with the uppercase English letters from `A` through the W-th letter of the alphabet. <image> Exactly one of the squares in the grid contains the string `snuke`. Find this square and report its location. For example, the square at the 6-th row and 8-th column should be reported as `H6`. Constraints * 1≦H, W≦26 * The length of S_{i,j} is 5. * S_{i,j} consists of lowercase English letters (`a`-`z`). * Exactly one of the given strings is equal to `snuke`. Input The input is given from Standard Input in the following format: H W S_{1,1} S_{1,2} ... S_{1,W} S_{2,1} S_{2,2} ... S_{2,W} : S_{H,1} S_{H,2} ... S_{H,W} Output Print the labels of the row and the column of the square containing the string `snuke`, with no space inbetween. Examples Input 15 10 snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snuke snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake snake Output H6 Input 1 1 snuke Output A1 ### Response ```cpp #include <cstdio> #include <cstring> int main() { int n, m; scanf("%d%d", &n, &m); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { char s[10]; scanf("%s", s); if (strcmp(s, "snuke") == 0) { printf("%c%d\n", 'A' + j, i + 1); return 0; } } } return 0; } ```
### Prompt Develop a solution in CPP to the problem described below: One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by n machines, and the power of the i-th machine is a_i. This year 2D decided to cultivate a new culture, but what exactly he didn't say. For the successful growth of the new culture, it is necessary to slightly change the powers of the machines. 2D can at most once choose an arbitrary integer x, then choose one machine and reduce the power of its machine by x times, and at the same time increase the power of one another machine by x times (powers of all the machines must stay positive integers). Note that he may not do that if he wants. More formally, 2D can choose two such indices i and j, and one integer x such that x is a divisor of a_i, and change powers as following: a_i = (a_i)/(x), a_j = a_j β‹… x Sasha is very curious, that's why he wants to calculate the minimum total power the farmer can reach. There are too many machines, and Sasha can't cope with computations, help him! Input The first line contains one integer n (2 ≀ n ≀ 5 β‹… 10^4) β€” the number of machines. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 100) β€” the powers of the machines. Output Print one integer β€” minimum total power. Examples Input 5 1 2 3 4 5 Output 14 Input 4 4 2 4 4 Output 14 Input 5 2 4 2 3 7 Output 18 Note In the first example, the farmer can reduce the power of the 4-th machine by 2 times, and increase the power of the 1-st machine by 2 times, then the powers will be: [2, 2, 3, 2, 5]. In the second example, the farmer can reduce the power of the 3-rd machine by 2 times, and increase the power of the 2-nd machine by 2 times. At the same time, the farmer can leave is be as it is and the total power won't change. In the third example, it is optimal to leave it be as it is. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n, sum = 0, ans, p; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; sort(a.begin(), a.end()); for (int i = 0; i < n; i++) sum += a[i]; ans = sum; for (int i = 2; i <= 100; i++) { int f1 = 0; p = sum; for (int j = n - 1; j; j--) { if (!f1 && !(a[j] % i)) { p -= a[j]; p += a[j] / i; f1 = 1; p -= a[0]; p += a[0] * i; break; } } if (f1) { ans = min(ans, p); } } cout << ans; } ```
### Prompt Your task is to create a Cpp solution to the following problem: <image> At the request of a friend who started learning abacus, you decided to create a program to display the abacus beads. Create a program that takes a certain number as input and outputs a row of abacus beads. However, the number of digits of the abacus to be displayed is 5 digits, and the arrangement of beads from 0 to 9 is as follows using'*' (half-width asterisk),''(half-width blank), and'=' (half-width equal). It shall be expressed as. <image> Input Multiple test cases are given. Up to 5 digits (integer) are given on one line for each test case. The number of test cases does not exceed 1024. Output Output the abacus bead arrangement for each test case. Insert a blank line between the test cases. Example Input 2006 1111 Output **** * ===== * * **** * *** ***** ***** ***** ===== **** * ***** ***** ***** ### Response ```cpp #include <iostream> #include <cstdio> #include <cstdlib> using namespace std; int main() { char s[6], r[5][8], d; int n, i, j, c, b = 0; while (cin >> n) { if (cin.eof()) break; if (b) cout << endl; sprintf(s, "%05d", n); for (i = 0; i < 5; i++) { d = (char)s[i]; c = atoi(&d); if (c < 5) { r[i][0] = '*'; r[i][1] = ' '; } else { r[i][0] = ' '; r[i][1] = '*'; } r[i][2] = '='; for (j = 3; j < 8; j++) { if (c != j-3 && c != j+2) r[i][j] = '*'; else r[i][j] = ' '; } } for (i = 0; i < 8; i++) { for (j = 0; j < 5; j++) { cout << r[j][i]; } cout << endl; } b = 1; } } ```
### Prompt In Cpp, your task is to solve the following problem: There are n segments drawn on a plane; the i-th segment connects two points (x_{i, 1}, y_{i, 1}) and (x_{i, 2}, y_{i, 2}). Each segment is non-degenerate, and is either horizontal or vertical β€” formally, for every i ∈ [1, n] either x_{i, 1} = x_{i, 2} or y_{i, 1} = y_{i, 2} (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points. We say that four segments having indices h_1, h_2, v_1 and v_2 such that h_1 < h_2 and v_1 < v_2 form a rectangle if the following conditions hold: * segments h_1 and h_2 are horizontal; * segments v_1 and v_2 are vertical; * segment h_1 intersects with segment v_1; * segment h_2 intersects with segment v_1; * segment h_1 intersects with segment v_2; * segment h_2 intersects with segment v_2. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions h_1 < h_2 and v_1 < v_2 should hold. Input The first line contains one integer n (1 ≀ n ≀ 5000) β€” the number of segments. Then n lines follow. The i-th line contains four integers x_{i, 1}, y_{i, 1}, x_{i, 2} and y_{i, 2} denoting the endpoints of the i-th segment. All coordinates of the endpoints are in the range [-5000, 5000]. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical. Output Print one integer β€” the number of ways to choose four segments so they form a rectangle. Examples Input 7 -1 4 -1 -2 6 -1 -2 -1 -2 3 6 3 2 -2 2 4 4 -1 4 3 5 3 5 1 5 2 1 2 Output 7 Input 5 1 5 1 0 0 1 5 1 5 4 0 4 4 2 4 0 4 3 4 5 Output 0 Note The following pictures represent sample cases: <image> <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int off = 5001, N = 10009; vector<pair<int, int>> vs[N], hs[N]; vector<int> open[N]; int bit[N]; int sum(int id) { int ans = 0; while (id > 0) ans += bit[id], id -= id & -id; return ans; } void update(int id, int val) { while (id <= N) bit[id] += val, id += id & -id; } int query(int l, int r) { return sum(r) - sum(l - 1); } void __sol() { int n; cin >> n; for (int i = 0; i < n; i++) { int x1, x2, y1, y2; cin >> x1 >> y1 >> x2 >> y2; x1 += off, x2 += off, y1 += off, y2 += off; if (y1 == y2) hs[y1].push_back({min(x1, x2), max(x1, x2)}); else vs[x1].push_back({min(y1, y2), max(y1, y2)}); } long long ans = 0; for (int fix_y = 1; fix_y < N; fix_y++) for (auto &s1 : hs[fix_y]) { memset(bit, 0, sizeof(bit)); int l = s1.first, r = s1.second; for (int x = l; x <= r; x++) for (auto &s2 : vs[x]) if (s2.first <= fix_y && fix_y < s2.second) { open[s2.second].push_back(x); update(x, 1); } for (int y = fix_y + 1; y < N; y++) { for (auto &s2 : hs[y]) { int curr = query(s2.first, s2.second); ans += curr * (curr - 1) / 2; } for (auto &x : open[y]) update(x, -1); open[y].clear(); } } cout << ans << "\n"; return; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); long long int tc = 1; while (tc--) __sol(); return 0; } ```
### Prompt Generate a CPP solution to the following problem: Each student eagerly awaits the day he would pass the exams successfully. Thus, Vasya was ready to celebrate, but, alas, he didn't pass it. However, many of Vasya's fellow students from the same group were more successful and celebrated after the exam. Some of them celebrated in the BugDonalds restaurant, some of them β€” in the BeaverKing restaurant, the most successful ones were fast enough to celebrate in both of restaurants. Students which didn't pass the exam didn't celebrate in any of those restaurants and elected to stay home to prepare for their reexamination. However, this quickly bored Vasya and he started checking celebration photos on the Kilogramm. He found out that, in total, BugDonalds was visited by A students, BeaverKing β€” by B students and C students visited both restaurants. Vasya also knows that there are N students in his group. Based on this info, Vasya wants to determine either if his data contradicts itself or, if it doesn't, how many students in his group didn't pass the exam. Can you help him so he won't waste his valuable preparation time? Input The first line contains four integers β€” A, B, C and N (0 ≀ A, B, C, N ≀ 100). Output If a distribution of N students exists in which A students visited BugDonalds, B β€” BeaverKing, C β€” both of the restaurants and at least one student is left home (it is known that Vasya didn't pass the exam and stayed at home), output one integer β€” amount of students (including Vasya) who did not pass the exam. If such a distribution does not exist and Vasya made a mistake while determining the numbers A, B, C or N (as in samples 2 and 3), output -1. Examples Input 10 10 5 20 Output 5 Input 2 2 0 4 Output -1 Input 2 2 2 1 Output -1 Note The first sample describes following situation: 5 only visited BugDonalds, 5 students only visited BeaverKing, 5 visited both of them and 5 students (including Vasya) didn't pass the exam. In the second sample 2 students only visited BugDonalds and 2 only visited BeaverKing, but that means all 4 students in group passed the exam which contradicts the fact that Vasya didn't pass meaning that this situation is impossible. The third sample describes a situation where 2 students visited BugDonalds but the group has only 1 which makes it clearly impossible. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int a, b, c, n; cin >> a >> b >> c >> n; if (c > a || c > b) cout << -1 << endl; else { int fail1 = n - a - b + c; if (fail1 < 1) cout << -1 << endl; else cout << fail1 << endl; } return 0; } ```
### Prompt Develop a solution in CPP to the problem described below: Today is tuesday, that means there is a dispute in JOHNNY SOLVING team again: they try to understand who is Johnny and who is Solving. That's why guys asked Umnik to help them. Umnik gave guys a connected graph with n vertices without loops and multiedges, such that a degree of any vertex is at least 3, and also he gave a number 1 ≀ k ≀ n. Because Johnny is not too smart, he promised to find a simple path with length at least n/k in the graph. In reply, Solving promised to find k simple by vertices cycles with representatives, such that: * Length of each cycle is at least 3. * Length of each cycle is not divisible by 3. * In each cycle must be a representative - vertex, which belongs only to this cycle among all printed cycles. You need to help guys resolve the dispute, for that you need to find a solution for Johnny: a simple path with length at least n/k (n is not necessarily divided by k), or solution for Solving: k cycles that satisfy all the conditions above. If there is no any solution - print -1. Input The first line contains three integers n, m and k (1 ≀ k ≀ n ≀ 2.5 β‹… 10^5, 1 ≀ m ≀ 5 β‹… 10^5) Next m lines describe edges of the graph in format v, u (1 ≀ v, u ≀ n). It's guaranteed that v β‰  u and all m pairs are distinct. It's guaranteed that a degree of each vertex is at least 3. Output Print PATH in the first line, if you solve problem for Johnny. In the second line print the number of vertices in the path c (c β‰₯ n/k). And in the third line print vertices describing the path in route order. Print CYCLES in the first line, if you solve problem for Solving. In the following lines describe exactly k cycles in the following format: in the first line print the size of the cycle c (c β‰₯ 3). In the second line print the cycle in route order. Also, the first vertex in the cycle must be a representative. Print -1 if there is no any solution. The total amount of printed numbers in the output must be at most 10^6. It's guaranteed, that if exists any solution then there is a correct output satisfies this restriction. Examples Input 4 6 2 1 2 1 3 1 4 2 3 2 4 3 4 Output PATH 4 1 2 3 4 Input 10 18 2 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 2 3 3 4 2 4 5 6 6 7 5 7 8 9 9 10 8 10 Output CYCLES 4 4 1 2 3 4 7 1 5 6 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, m, k, len, tot, head[250005], qu[250005], id[250005], cnt, vis[250005]; struct edge { int u, v, nxt; } edg[250005 << 2]; inline void addedg(int u, int v) { edg[tot].u = u; edg[tot].v = v; edg[tot].nxt = head[u]; head[u] = tot++; } bool dfs1(int u, int fa) { if (cnt == len) return true; for (int i = head[u]; i != -1; i = edg[i].nxt) { int v = edg[i].v; if (v != fa && !vis[v]) { qu[cnt++] = v; vis[v] = 1; if (dfs1(v, u)) return true; --cnt; } } return false; } void dfs2(int u, int fa) { int flag = 0; if (k == 0) return; for (int i = head[u]; i != -1; i = edg[i].nxt) { int v = edg[i].v; if (v != fa && !vis[v]) { flag = 1; qu[cnt] = v; id[v] = cnt; vis[v] = 1; ++cnt; dfs2(v, u); --cnt; } } if (!flag) { int fa1 = -1, fa2 = -1; for (int i = head[u]; i != -1; i = edg[i].nxt) { int v = edg[i].v; if (v != fa) { if (fa1 == -1) fa1 = v; else { fa2 = v; break; } } } if (id[fa1] < id[fa2]) swap(fa1, fa2); flag = 0; if ((id[u] - id[fa1] + 1) % 3) flag = fa1; else if ((id[u] - id[fa2] + 1) % 3) flag = fa2; if (flag) { len = id[u] - id[flag] + 1; printf("%d\n", len); for (int i = id[u]; i >= id[flag]; --i) printf("%d ", qu[i]); printf("\n"); --k; } else { len = id[fa1] - id[fa2] + 2; printf("%d\n", len); printf("%d ", u); for (int i = id[fa1]; i >= id[fa2]; --i) printf("%d ", qu[i]); printf("\n"); --k; } } } int main() { scanf("%d%d%d", &n, &m, &k); memset(head, -1, 4 * n + 4); tot = cnt = 0; int u, v; for (int i = 1; i <= m; ++i) { scanf("%d%d", &u, &v); addedg(u, v); addedg(v, u); } len = n / k; if (n % k) ++len; vis[1] = 1; qu[cnt++] = 1; if (dfs1(1, 1)) { printf("PATH\n%d\n", len); for (int i = 0; i < cnt; ++i) printf("%d ", qu[i]); } else { memset(vis, 0, 4 * n + 4); cnt = 0; printf("CYCLES\n"); qu[cnt++] = 1; id[1] = 0; vis[1] = 1; dfs2(1, 1); } return 0; } ```
### Prompt Generate a Cpp solution to the following problem: One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name s, a user can pick number p and character c and delete the p-th occurrence of character c from the name. After the user changed his name, he can't undo the change. For example, one can change name "arca" by removing the second occurrence of character "a" to get "arc". Polycarpus learned that some user initially registered under nickname t, where t is a concatenation of k copies of string s. Also, Polycarpus knows the sequence of this user's name changes. Help Polycarpus figure out the user's final name. Input The first line contains an integer k (1 ≀ k ≀ 2000). The second line contains a non-empty string s, consisting of lowercase Latin letters, at most 100 characters long. The third line contains an integer n (0 ≀ n ≀ 20000) β€” the number of username changes. Each of the next n lines contains the actual changes, one per line. The changes are written as "pi ci" (without the quotes), where pi (1 ≀ pi ≀ 200000) is the number of occurrences of letter ci, ci is a lowercase Latin letter. It is guaranteed that the operations are correct, that is, the letter to be deleted always exists, and after all operations not all letters are deleted from the name. The letters' occurrences are numbered starting from 1. Output Print a single string β€” the user's final name after all changes are applied to it. Examples Input 2 bac 3 2 a 1 b 2 c Output acb Input 1 abacaba 4 1 a 1 a 1 c 2 b Output baa Note Let's consider the first sample. Initially we have name "bacbac"; the first operation transforms it into "bacbc", the second one β€” to "acbc", and finally, the third one transforms it into "acb". ### Response ```cpp #include <bits/stdc++.h> void Read(); void Count(); void Write(); int main() { Read(); Count(); Write(); return 0; } int loop_time; char star_string[110]; void Read() { scanf("%d%s", &loop_time, star_string); return; } const int maxnum = 201000; class TREE_ARRAY { private: int v[210000]; public: TREE_ARRAY() { for (int k = 0; (1 << k) <= maxnum; k++) for (int i = 1; (i << k) <= maxnum; i += 2) v[i << k] = 1 << k; return; } inline void Dele(int pos) { for (int i = 1; pos <= maxnum; i <<= 1) if (i & pos) { v[pos]--; pos += i; } return; } inline int Rank(int pos) { int val = 0; for (int i = 1; pos; i <<= 1) if (i & pos) { val += v[pos]; pos ^= i; } return val; } } array[26]; class SET { public: int belong[210000]; SET() { for (int i = 1; i <= maxnum; i++) belong[i] = i; return; } int Find(int x) { if (belong[x] == x) return x; else return belong[x] = Find(belong[x]); } } vset[26]; inline int ToFind(int k, int val) { int m = (maxnum + 1) >> 1; for (int l = 1, r = maxnum;; m = (l + r) >> 1) { int rank = array[k].Rank(m); if (rank == val) break; else if (rank < val) l = m + 1; else r = m; } return vset[k].Find(m); } int lnum[30] = {0}, lpos[30][110] = {0}; ; bool disapper[210000] = {0}; void Count() { int len = strlen(star_string); for (int i = 0, v; i < len; i++) { v = star_string[i] - 'a'; lpos[v][++lnum[v]] = i + 1; } int n; char s[10]; scanf("%d", &n); for (int i = 0, p, k; i < n; i++) { scanf("%d%s", &p, s); p = ToFind(k = *s - 'a', p); array[k].Dele(p); vset[k].belong[p] = p - 1; disapper[(p - 1) / lnum[k] * len + lpos[k][(p - 1) % lnum[k] + 1]] = true; } return; } void Write() { int i = 0, k = 0, len = strlen(star_string); while (1) { if (!disapper[i + 1]) printf("%c", star_string[i % len]); i++; if (i % len == 0) k++; if (k >= loop_time) break; } printf("\n"); return; } ```
### Prompt Your task is to create a Cpp solution to the following problem: You are the gym teacher in the school. There are n students in the row. And there are two rivalling students among them. The first one is in position a, the second in position b. Positions are numbered from 1 to n from left to right. Since they are rivals, you want to maximize the distance between them. If students are in positions p and s respectively, then distance between them is |p - s|. You can do the following operation at most x times: choose two adjacent (neighbouring) students and swap them. Calculate the maximum distance between two rivalling students after at most x swaps. Input The first line contains one integer t (1 ≀ t ≀ 100) β€” the number of test cases. The only line of each test case contains four integers n, x, a and b (2 ≀ n ≀ 100, 0 ≀ x ≀ 100, 1 ≀ a, b ≀ n, a β‰  b) β€” the number of students in the row, the number of swaps which you can do, and positions of first and second rivaling students respectively. Output For each test case print one integer β€” the maximum distance between two rivaling students which you can obtain. Example Input 3 5 1 3 2 100 33 100 1 6 0 2 3 Output 2 99 1 Note In the first test case you can swap students in positions 3 and 4. And then the distance between the rivals is equal to |4 - 2| = 2. In the second test case you don't have to swap students. In the third test case you can't swap students. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long n, t, a, b; int main() { cin >> t; while (t--) { long long a, b, x; cin >> n >> x >> a >> b; if (a > b) { swap(a, b); } long long diff = b - a; if (diff + x <= n - 1) { cout << diff + x << endl; } else { cout << n - 1 << endl; } } return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: Shubham has an array a of size n, and wants to select exactly x elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct. Tell him whether he can do so. Input The first line of the input contains a single integer t (1≀ t ≀ 100) β€” the number of test cases. The description of the test cases follows. The first line of each test case contains two integers n and x (1 ≀ x ≀ n ≀ 1000) β€” the length of the array and the number of elements you need to choose. The next line of each test case contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 1000) β€” elements of the array. Output For each test case, print "Yes" or "No" depending on whether it is possible to choose x elements such that their sum is odd. You may print every letter in any case you want. Example Input 5 1 1 999 1 1 1000 2 1 51 50 2 2 51 50 3 3 101 102 103 Output Yes No Yes Yes No Note For 1st case: We must select element 999, and the sum is odd. For 2nd case: We must select element 1000, so overall sum is not odd. For 3rd case: We can select element 51. For 4th case: We must select both elements 50 and 51 β€” so overall sum is odd. For 5th case: We must select all elements β€” but overall sum is not odd. ### Response ```cpp #include <bits/stdc++.h> int main() { int testcase, n, x; scanf("%d", &testcase); for (int i = 0; i < testcase; i++) { scanf("%d %d", &n, &x); int num[n]; int odd = 0, even = 0; for (int j = 0; j < n; j++) { scanf("%d", &num[j]); if (num[j] % 2 != 0) { odd++; } else if (num[j] % 2 == 0) { even++; } } if (x == n) { if (odd % 2 != 0) { printf("Yes\n"); } else { printf("No\n"); } } else if (x % 2 == 0) { if (odd > 0 && even > 0) { printf("Yes\n"); } else { printf("No\n"); } } else if (x % 2 != 0) { if (odd > 0) { printf("Yes\n"); } else { printf("No\n"); } } odd = 0; even = 0; } return 0; } ```
### Prompt Develop a solution in cpp to the problem described below: You are given n strings ti. Each string has cost ci. Let's define the function of string <image>, where ps, i is the number of occurrences of s in ti, |s| is the length of the string s. Find the maximal value of function f(s) over all strings. Note that the string s is not necessarily some string from t. Input The first line contains the only integer n (1 ≀ n ≀ 105) β€” the number of strings in t. Each of the next n lines contains contains a non-empty string ti. ti contains only lowercase English letters. It is guaranteed that the sum of lengths of all strings in t is not greater than 5Β·105. The last line contains n integers ci ( - 107 ≀ ci ≀ 107) β€” the cost of the i-th string. Output Print the only integer a β€” the maximal value of the function f(s) over all strings s. Note one more time that the string s is not necessarily from t. Examples Input 2 aa bb 2 1 Output 4 Input 2 aa ab 2 1 Output 5 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 100001; const int MAXS = 500001; const int MAXNS = MAXN + MAXS; const int MAXST = MAXNS * 2; int n; string s[MAXN]; int c[MAXN]; char buf[MAXS]; int len; int a[MAXNS]; long long ans; struct node { int l, r; int fa, lnk; map<int, int> sons; node(int l = 0, int r = 0, int fa = -1) : l(l), r(r), fa(fa) { lnk = -1; sons.clear(); } int len() { return r - l; } }; struct v_node { int v; int len; v_node(int v = 0, int len = 0) : v(v), len(len) {} }; int stn; node st[MAXST]; v_node active; set<pair<int, int>> pos; void init() { scanf("%d", &n); for (int i = 0; i < n; ++i) { scanf("%s", buf); s[i] = buf; } for (int i = 0; i < n; ++i) scanf("%d", &c[i]); len = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < s[i].size(); ++j) { a[len++] = s[i][j] - 'a'; } pos.insert(make_pair(len, c[i])); a[len++] = 26 + i; } } inline bool vnode_full(v_node vnode) { return vnode.len == st[vnode.v].len(); } bool vnode_extend(v_node &vnode, int i) { if (vnode_full(vnode)) { if (st[vnode.v].sons.count(a[i])) { vnode.v = st[vnode.v].sons[a[i]]; vnode.len = 0; } else { return false; } } if (a[st[vnode.v].l + vnode.len] == a[i]) { ++vnode.len; } else { return false; } return true; } int node_split(v_node vnode, int i) { int mid = vnode.v; if (!vnode_full(vnode)) { mid = stn++; int L = st[vnode.v].l; int M = L + vnode.len; st[mid] = node(L, M, st[vnode.v].fa); st[mid].lnk = 0; st[st[vnode.v].fa].sons[a[L]] = mid; st[vnode.v].l = M; st[vnode.v].fa = mid; st[mid].sons.clear(); st[mid].sons[a[M]] = vnode.v; } st[stn] = node(i, len, mid); st[mid].sons[a[i]] = stn; ++stn; return mid; } void st_extend(int i) { int last = -1; while (!vnode_extend(active, i)) { int mid = node_split(active, i); if (last != -1) { st[last].lnk = mid; } last = mid; if (active.v == 0) return; if (st[mid].fa == 0) { if (active.len == 1) { active.v = 0; active.len = 0; } else { --active.len; active.v = st[0].sons[a[i - active.len]]; } } else { active.v = st[st[st[mid].fa].lnk].sons[a[i - active.len]]; } while (active.len > st[active.v].len()) { active.len -= st[active.v].len(); active.v = st[active.v].sons[a[i - active.len]]; } } if (last != -1) st[last].lnk = st[active.v].fa; } void build_tree() { st[0] = node(); stn = 1; active = v_node(0, 0); for (int i = 0; i < len; ++i) { st_extend(i); } } long long dfs(int i, int len) { long long sum = 0; auto it = pos.lower_bound(make_pair(st[i].l, INT_MIN)); if (it != pos.end() && it->first < st[i].r) { sum += it->second; if (it->first > st[i].l) { len += it->first - st[i].l; if (ans < sum * len) ans = sum * len; } return sum; } len += st[i].len(); for (map<int, int>::iterator it = st[i].sons.begin(); it != st[i].sons.end(); ++it) { sum += dfs(it->second, len); } if (ans < sum * len) ans = sum * len; return sum; } int dfs2(int i, int len) { long long sum = 0; auto it = pos.lower_bound(make_pair(st[i].l, INT_MIN)); if (it != pos.end() && it->first < st[i].r) { sum += it->second; if (it->first > st[i].l) { len -= st[i].r - it->first; if (ans < sum * len) ans = sum * len; } return sum; } for (map<int, int>::iterator it = st[i].sons.begin(); it != st[i].sons.end(); ++it) { sum += dfs(it->second, len + st[it->second].len()); } if (ans < sum * len) ans = sum * len; return sum; } void solve() { build_tree(); dfs(0, 0); } void print() { cout << ans << endl; } int main() { init(); solve(); print(); } ```
### Prompt Develop a solution in cpp to the problem described below: Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move. Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him. Input The first line contains two integers, n and k (1 ≀ n ≀ 105; 1 ≀ k ≀ 109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters. Output If the player who moves first wins, print "First", otherwise print "Second" (without the quotes). Examples Input 2 3 a b Output First Input 3 1 a b c Output First Input 1 2 ab Output Second ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MX = 2000000; const long long inf = 1e18; const long long mod = 1e9 + 7; struct node { int in[26]; node() { memset(in, -1, sizeof(in)); } }; node T[MX]; int av; void add(string s) { int p = 0; for (int i = 0; i < s.size(); i++) { int id = s[i] - 'a'; if (T[p].in[id] == -1) T[p].in[id] = ++av; p = T[p].in[id]; } } int dp[MX], dp2[MX]; void dfs(int x) { bool flg = 0, flg2 = 0; int cn = 0, cn2 = 0; for (int i = 0; i < 26; i++) { if (T[x].in[i] != -1) { flg2 = 1; cn++; dfs(T[x].in[i]); if (dp[T[x].in[i]] == 0) cn2++; } } if (cn == cn2) dp[x] = 1; else dp[x] = 0; if (!flg2) dp[x] = 1; } void dfs2(int x) { bool flg2 = 0, flg = 0; int cn = 0, cn2 = 0; for (int i = 0; i < 26; i++) { if (T[x].in[i] != -1) { flg2 = 1; cn++; dfs2(T[x].in[i]); if (dp2[T[x].in[i]] == 1) cn2++; } } if (cn == cn2) dp2[x] = 0; else dp2[x] = 1; if (!flg2) dp2[x] = 1; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, k; cin >> n >> k; memset(T, -1, sizeof(T)); for (int i = 0; i < n; i++) { string s; cin >> s; add(s); } dfs(0); dfs2(0); bool flg = 0, flg2 = 0; for (int i = 0; i < 26; i++) if (T[0].in[i] != -1) flg |= (dp[T[0].in[i]]), flg2 |= (dp2[T[0].in[i]] == 0); if (flg == 0) cout << "Second" << endl; else { if (flg2 || k & 1) cout << "First" << endl; else cout << "Second" << endl; } return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: problem You are looking for a constellation in a picture of the starry sky. The photo always contains exactly one figure with the same shape, orientation, and size as the constellation you are looking for. However, there is a possibility that extra stars are shown in the photograph other than the stars that make up the constellation. For example, the constellations in Figure 1 are included in the photo in Figure 2 (circled). If you translate the coordinates of a star in a given constellation by 2 in the x direction and βˆ’3 in the y direction, it will be the position in the photo. Given the shape of the constellation you want to look for and the position of the star in the picture, write a program that answers the amount to translate to convert the coordinates of the constellation to the coordinates in the picture. <image> | <image> --- | --- Figure 1: The constellation you want to find | Figure 2: Photograph of the starry sky input The input consists of multiple datasets. Each dataset is given in the following format. The first line of the input contains the number of stars m that make up the constellation you want to find. In the following m line, the integers indicating the x and y coordinates of the m stars that make up the constellation you want to search for are written separated by blanks. The number n of stars in the photo is written on the m + 2 line. In the following n lines, the integers indicating the x and y coordinates of the n stars in the photo are written separated by blanks. The positions of the m stars that make up the constellation are all different. Also, the positions of the n stars in the picture are all different. 1 ≀ m ≀ 200, 1 ≀ n ≀ 1000. The x and y coordinates of a star are all 0 or more and 1000000 or less. When m is 0, it indicates the end of input. The number of datasets does not exceed 5. output The output of each dataset consists of one line, with two integers separated by blanks. These show how much the coordinates of the constellation you want to find should be translated to become the coordinates in the photo. The first integer is the amount to translate in the x direction, and the second integer is the amount to translate in the y direction. Examples Input 5 8 5 6 4 4 3 7 10 0 10 10 10 5 2 7 9 7 8 10 10 2 1 2 8 1 6 7 6 0 0 9 5 904207 809784 845370 244806 499091 59863 638406 182509 435076 362268 10 757559 866424 114810 239537 519926 989458 461089 424480 674361 448440 81851 150384 459107 795405 299682 6700 254125 362183 50795 541942 0 Output 2 -3 -384281 179674 Input None Output None ### Response ```cpp #include <iostream> #include <vector> #include <string> #include <algorithm> #include <cmath> #include <map> #include <stack> #include <queue> #include <cstdio> #include <cstdlib> #include <utility> using namespace std; int main(){ int m, n; pair<int, int> p1[202]; pair<int, int> p2[1002]; while(cin >> m, m){ fill(p1, p1+202, make_pair(-1, -1)); fill(p2, p2+1002, make_pair(-1, -1)); for(int i = 0;i < m;i++)cin >> p1[i].first >> p1[i].second; cin >> n; for(int i = 0;i < n;i++)cin >> p2[i].first >> p2[i].second; sort(p1, p1+m); sort(p2, p2+n); pair<int, int> t; int ans[3] = {0, 0, 0}; for(int i = 0;i < n;i++){ ans[0] = 0; for(int j = 1;j < m;j++){ t.first = p2[i].first+(p1[j].first-p1[0].first); t.second = p2[i].second+(p1[j].second-p1[0].second); ans[0] += binary_search(p2, p2+n, t); } if(ans[0] == m-1){ ans[1] = p2[i].first - p1[0].first; ans[2] = p2[i].second - p1[0].second; } } cout << ans[1] << " " << ans[2] << endl; } return 0; } ```
### Prompt Your task is to create a cpp solution to the following problem: problem Hanako is playing with n (4 ≀ n ≀ 10) cards side by side. Each card has one integer between 1 and 99. Hanako chose k cards (2 ≀ k ≀ 4) from these cards and arranged them in a horizontal row to make an integer. How many kinds of integers can Hanako make in total? For example, consider that you are given five cards of 1, 2, 3, 13, 21 and choose three of them to make an integer. By arranging 2, 1, and 13 in this order, we can make an integer 2113. Also, by arranging 21, 1, and 3 in this order, the same integer 2113 can be created. In this way, the same integer may be created from a combination of different cards. Given the integers written on n cards, create a program to find the number of integers that can be created by selecting k cards from them and arranging them in a horizontal row. input The input consists of multiple datasets. Each dataset is given in the following format. Each dataset consists of 2 + n rows. The number of cards n (4 ≀ n ≀ 10) is written on the first line, and the number of cards to be selected k (2 ≀ k ≀ 4) is written on the second line. On the 2 + i line (1 ≀ i ≀ n), the integer from 1 to 99 written on the i-th card is written. When both n and k are 0, it indicates the end of input. The number of data sets does not exceed 5. output For each data set, the number of integers that Hanako can create is output on one line. Examples Input 4 2 1 2 12 1 6 3 72 2 12 7 2 1 0 0 Output 7 68 Input None Output None ### Response ```cpp #include <bits/stdc++.h> #define PB push_back #define MP make_pair #define rep(i,n) for (int i=0;i<(n);i++) using namespace std; typedef long long ll; int to_i(string s){ int k=1,res=0; for(int i=s.size()-1;i>=0;i--){ res+=(s[i]-'0')*k; k*=10; } } int main(){ int n,k; while(cin>>n>>k&&n&&k){ string a[n]; for(int i=0;i<n;i++)cin>>a[i]; set<string> f; int ans=0; for(int i=0;i<1<<n;i++){ int c=0; vector<string> t; for(int j=0;j<n;j++)if((i>>j)&1){ c++;t.PB(a[j]); } if(c!=k)continue; sort(t.begin(),t.end()); do{ string res=""; for(int j=0;j<t.size();j++)res+=t[j]; if(f.count(res)==0){ ans++; f.insert(res); } }while(next_permutation(t.begin(),t.end())); } cout<<f.size()<<endl; } } ```
### Prompt Your task is to create a CPP solution to the following problem: Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β€” coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them. Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 ≀ i ≀ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good. Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set? Input The first line contains a single integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” number of test cases. Then t test cases follow. The first line of each test case contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of segments. This is followed by n lines describing the segments. Each segment is described by two integers l and r (1 ≀ l ≀ r ≀ 10^9) β€” coordinates of the beginning and end of the segment, respectively. It is guaranteed that the sum of n for all test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the minimum number of segments that need to be deleted in order for the set of remaining segments to become good. Example Input 4 3 1 4 2 3 3 6 4 1 2 2 3 3 5 4 5 5 1 2 3 8 4 5 6 7 9 10 5 1 5 2 4 3 5 3 8 4 8 Output 0 1 2 0 ### Response ```cpp #include <bits/stdc++.h> #define pb push_back #define mp make_pair #define sz(x) (int)(x).size() #define S second #define F first #define all(x) (x).begin(), (x).end() using namespace std; using ll = long long; void setIO(string name = "") { ios_base::sync_with_stdio(NULL); cin.tie(NULL); cout.tie(NULL); if (sz(name)) { freopen((name + ".in").c_str(), "r", stdin); freopen((name + ".out").c_str(), "w", stdout); } } const int inf = 1e9; const ll INF = 1e18; const int mod = 1e9 + 7; const int MAXN = 5e5 + 5; int n; int l[MAXN], r[MAXN]; int pref[MAXN], suff[MAXN]; void solve() { cin >> n; vector<int> v; for (int i = 1; i <= n; i++) { cin >> l[i] >> r[i]; v.pb(l[i]); v.pb(r[i]); } sort (all(v)); v.erase(unique(all(v)), v.end()); for (int i = 1; i <= n; i++) { l[i] = lower_bound(all(v), l[i]) - v.begin() + 1; r[i] = lower_bound(all(v), r[i]) - v.begin() + 1; } for (int i = 0; i <= sz(v) + 1; i++) { pref[i] = 0; suff[i] = 0; } for (int i = 1; i <= n; i++) { pref[r[i] + 1]++; suff[l[i] - 1]++; } for (int i = 1; i <= sz(v); i++) { pref[i] += pref[i - 1]; } for (int i = sz(v); i >= 1; i--) { suff[i] += suff[i + 1]; } int res = inf; for (int i = 1; i <= n; i++) { int ct = pref[l[i]] + suff[r[i]]; res = min(res, ct); } cout << res << '\n'; } int main() { setIO(); int tt = 1; cin >> tt; while (tt--) { solve(); } return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: A string s of length n (1 ≀ n ≀ 26) is called alphabetical if it can be obtained using the following algorithm: * first, write an empty string to s (i.e. perform the assignment s := ""); * then perform the next step n times; * at the i-th step take i-th lowercase letter of the Latin alphabet and write it either to the left of the string s or to the right of the string s (i.e. perform the assignment s := c+s or s := s+c, where c is the i-th letter of the Latin alphabet). In other words, iterate over the n first letters of the Latin alphabet starting from 'a' and etc. Each time we prepend a letter to the left of the string s or append a letter to the right of the string s. Strings that can be obtained in that way are alphabetical. For example, the following strings are alphabetical: "a", "ba", "ab", "bac" and "ihfcbadeg". The following strings are not alphabetical: "z", "aa", "ca", "acb", "xyz" and "ddcba". From the given string, determine if it is alphabetical. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case is written on a separate line that contains one string s. String s consists of lowercase letters of the Latin alphabet and has a length between 1 and 26, inclusive. Output Output t lines, each of them must contain the answer to the corresponding test case. Output YES if the given string s is alphabetical and NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive answer). Example Input 11 a ba ab bac ihfcbadeg z aa ca acb xyz ddcba Output YES YES YES YES YES NO NO NO NO NO NO Note The example contains test cases from the main part of the condition. ### Response ```cpp #include<iostream> #include<vector> #include<deque> #include<algorithm> #include<map> #include<array> #include<utility> #include<cmath> #include<queue> #include<string> #include<assert.h> #define MAX64 0x7fffffffffffffff #define MAX32 0x7fffffff typedef int_fast64_t ll; typedef int_fast64_t i64; typedef int_fast32_t i32; int main (){ std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); i32 test_cases; std::cin>> test_cases; while(test_cases--){ std::string s; std::cin >> s; i32 loc_of_a = 0; for(i32 i = 0; i < s.size(); i++){ if(s[i] == 'a') loc_of_a = i; } char current = 'a'; i32 l = loc_of_a, r = loc_of_a + 1; bool suffice = true; while(current <= 'a' + s.size() - 1){ if(l >= 0 && s[l] == current){ l -= 1; current += 1; continue; } if(r < s.size() && s[r] == current){ r += 1; current += 1; continue; } suffice = false; break; } if(suffice) std::cout <<"YES\n"; else std::cout << "NO\n"; } } ```
### Prompt Please create a solution in CPP to the following problem: Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX β€” beautiful, but little-known northern country. Here are some interesting facts about XXX: 1. XXX consists of n cities, k of whose (just imagine!) are capital cities. 2. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. 3. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 β€” 2 β€” ... β€” n β€” 1. Formally, for every 1 ≀ i < n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. 4. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≀ i ≀ n, i β‰  x, there is a road between cities x and i. 5. There is at most one road between any two cities. 6. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ciΒ·cj. Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a < b), such that there is a road between a and b you are to find sum of products caΒ·cb. Will you help her? Input The first line of the input contains two integers n and k (3 ≀ n ≀ 100 000, 1 ≀ k ≀ n) β€” the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 10 000) β€” beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≀ idi ≀ n) β€” indices of capital cities. Indices are given in ascending order. Output Print the only integer β€” summary price of passing each of the roads in XXX. Examples Input 4 1 2 3 1 2 3 Output 17 Input 5 2 3 5 2 2 4 1 4 Output 71 Note This image describes first sample case: <image> It is easy to see that summary price is equal to 17. This image describes second sample case: <image> It is easy to see that summary price is equal to 71. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long int isCap[100005], capitals[100005], beauty[100005]; int main() { long long int n, cap; long long int i, j; cin >> n >> cap; for (i = 0; i < n; i++) cin >> beauty[i]; for (i = 0; i < cap; i++) { cin >> j; j--; capitals[i] = j; isCap[j] = 1; } long long int sum = 0, ans = 0; for (i = 0; i < n - 1; i++) if (!(isCap[i] && isCap[i + 1])) ans += beauty[i] * beauty[i + 1]; if (!(isCap[0] && isCap[n - 1])) ans += beauty[0] * beauty[n - 1]; for (i = 0; i < n; i++) if (isCap[i] == 0) sum += beauty[i]; for (i = 0; i < cap; i++) { long long int neigh1 = (capitals[i] + 1) % n, neigh2 = (capitals[i] - 1 + n) % n; long long int tempSum = sum; if (isCap[neigh1] == 0) tempSum -= beauty[neigh1]; if (isCap[neigh2] == 0) tempSum -= beauty[neigh2]; ans += tempSum * beauty[capitals[i]]; } long long int sumCapitals = 0; for (i = 0; i < cap; i++) { sumCapitals += beauty[capitals[i]]; } for (i = 0; i < cap; i++) { sumCapitals -= beauty[capitals[i]]; ans += sumCapitals * beauty[capitals[i]]; } cout << ans; return 0; } ```
### Prompt Generate a CPP solution to the following problem: Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change. You have to find the minimum number of digits in which these two numbers can differ. Input The first line contains integer k (1 ≀ k ≀ 109). The second line contains integer n (1 ≀ n < 10100000). There are no leading zeros in n. It's guaranteed that this situation is possible. Output Print the minimum number of digits in which the initial number and n can differ. Examples Input 3 11 Output 1 Input 3 99 Output 0 Note In the first example, the initial number could be 12. In the second example the sum of the digits of n is not less than k. The initial number could be equal to n. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int k; char s[100010]; int a[100010]; int main() { cin >> k; scanf("%s", s); int len = strlen(s); for (int i = 0; i < len; i++) { a[i] = s[i] - '0'; k -= a[i]; a[i] = 9 - a[i]; } sort(a, a + len); int ans = 0; for (int i = len - 1; i >= 0; i--) { if (k > 0) k -= a[i], ans++; else break; } cout << ans; return 0; } ```
### Prompt Please create a solution in Cpp to the following problem: Little C loves number Β«3Β» very much. He loves all things about it. Now he has a positive integer n. He wants to split n into 3 positive integers a,b,c, such that a+b+c=n and none of the 3 integers is a multiple of 3. Help him to find a solution. Input A single line containing one integer n (3 ≀ n ≀ 10^9) β€” the integer Little C has. Output Print 3 positive integers a,b,c in a single line, such that a+b+c=n and none of them is a multiple of 3. It can be proved that there is at least one solution. If there are multiple solutions, print any of them. Examples Input 3 Output 1 1 1 Input 233 Output 77 77 79 ### Response ```cpp #include <bits/stdc++.h> using namespace std; void e(int l) { if ((l - 2) % 3 != 0) cout << "1 1 " << l - 2; else cout << "1 2 " << l - 3; } int main() { int k; cin >> k; e(k); return 0; } ```
### Prompt Construct a cpp code solution to the problem outlined: There are N men and N women, both numbered 1, 2, \ldots, N. For each i, j (1 \leq i, j \leq N), the compatibility of Man i and Woman j is given as an integer a_{i, j}. If a_{i, j} = 1, Man i and Woman j are compatible; if a_{i, j} = 0, they are not. Taro is trying to make N pairs, each consisting of a man and a woman who are compatible. Here, each man and each woman must belong to exactly one pair. Find the number of ways in which Taro can make N pairs, modulo 10^9 + 7. Constraints * All values in input are integers. * 1 \leq N \leq 21 * a_{i, j} is 0 or 1. Input Input is given from Standard Input in the following format: N a_{1, 1} \ldots a_{1, N} : a_{N, 1} \ldots a_{N, N} Output Print the number of ways in which Taro can make N pairs, modulo 10^9 + 7. Examples Input 3 0 1 1 1 0 1 1 1 1 Output 3 Input 4 0 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0 Output 1 Input 1 0 Output 0 Input 21 0 0 0 0 0 0 0 1 1 0 1 1 1 1 0 0 0 1 0 0 1 1 1 1 0 0 1 0 0 0 1 0 0 0 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 0 1 0 0 1 1 0 0 0 1 1 0 1 1 0 1 1 0 1 0 1 0 0 1 0 0 0 0 0 1 1 0 1 1 0 0 1 0 1 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 0 1 1 1 0 1 1 1 0 0 0 1 1 1 1 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 1 1 0 0 1 1 0 1 0 0 0 0 0 1 1 0 0 1 1 0 0 0 0 0 1 1 1 1 1 1 0 0 1 0 0 1 0 0 1 0 1 1 0 0 1 0 1 0 1 1 1 0 0 0 0 1 1 0 0 1 1 1 0 0 0 0 1 1 0 0 0 1 0 1 1 0 1 1 0 0 1 1 0 0 0 1 1 1 1 0 1 1 0 0 0 1 0 0 1 1 1 1 0 1 1 0 1 1 1 0 0 0 0 1 0 1 1 0 0 1 1 1 1 0 0 0 1 0 1 1 0 1 0 1 1 1 1 1 1 1 0 0 0 0 1 0 0 1 1 0 1 1 1 0 0 1 0 0 0 1 1 0 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 0 1 1 0 1 0 1 0 0 1 0 0 1 1 0 1 0 1 1 0 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 1 1 0 0 1 0 0 0 1 0 0 1 1 0 1 0 1 0 1 1 0 0 1 1 0 1 0 0 0 0 1 1 1 0 1 0 1 1 1 0 1 1 0 0 1 1 0 1 1 0 1 1 0 0 1 1 0 1 1 0 1 1 1 1 1 0 1 0 1 0 0 1 1 0 1 1 1 1 1 0 1 0 1 1 0 0 0 0 0 Output 102515160 ### Response ```cpp #include<bits/stdc++.h> using namespace std; int n,dp[4200003]; bool a[22][22]; int main(){ cin>>n; for(int i=0;i<n;i++) for(int j=0;j<n;j++) cin>>a[i][j]; dp[0]=1; for(int i=0;i<1<<n;i++){ int cnt=0,tmp=i; while(tmp) cnt+=tmp%2, tmp/=2; //cout<<i<<' '<<cnt<<endl; for(int j=0;j<n;j++) if(a[cnt][j]&&~i&(1<<j)) dp[i+(1<<j)]=(dp[i+(1<<j)]+dp[i])%1000000007; } cout<<dp[(1<<n)-1]; } ```
### Prompt Your challenge is to write a cpp solution to the following problem: Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≀ i ≀ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: 1. If i β‰  n, move from pile i to pile i + 1; 2. If pile located at the position of student is not empty, remove one box from it. GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed. Input The first line contains two integers n and m (1 ≀ n, m ≀ 105), the number of piles of boxes and the number of GukiZ's students. The second line contains n integers a1, a2, ... an (0 ≀ ai ≀ 109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty. Output In a single line, print one number, minimum time needed to remove all the boxes in seconds. Examples Input 2 1 1 1 Output 4 Input 3 2 1 0 2 Output 5 Input 4 100 3 4 5 4 Output 5 Note First sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second). Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds. Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 100005; int n, m, a[N]; int check(long long t) { int cnt = m; long long canmove = 0; for (int i = n; i >= 1; --i) { while (canmove < a[i]) { canmove += t - i; if (--cnt < 0) return 0; } canmove -= a[i]; } return 1; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; ++i) { scanf("%d", a + i); } long long l = 0, r = 1LL << 60, res; while (l <= r) { long long mid = (l + r) / 2; if (check(mid)) { res = mid; r = mid - 1; } else l = mid + 1; } printf("%I64d\n", res); return 0; } ```