text
stringlengths
424
69.5k
### Prompt Develop a solution in Cpp to the problem described below: Andre has very specific tastes. Recently he started falling in love with arrays. Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements β€” 6 β€” is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't divisible by 4. Andre calls an array a of length n perfect if the following conditions hold: * Every nonempty subarray of this array is good. * For every i (1 ≀ i ≀ n), 1 ≀ a_i ≀ 100. Given a positive integer n, output any perfect array of length n. We can show that for the given constraints such an array always exists. An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). Description of the test cases follows. The first and only line of every test case contains a single integer n (1 ≀ n ≀ 100). Output For every test, output any perfect array of length n on a separate line. Example Input 3 1 2 4 Output 24 19 33 7 37 79 49 Note Array [19, 33] is perfect as all 3 its subarrays: [19], [33], [19, 33], have sums divisible by their lengths, and therefore are good. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; for (int i = 0; i < n; i++) cout << 1 << " "; cout << "\n"; } } ```
### Prompt Create a solution in Cpp for the following problem: Recently, on a programming lesson little Petya showed how quickly he can create files and folders on the computer. But he got soon fed up with this activity, and he decided to do a much more useful thing. He decided to calculate what folder contains most subfolders (including nested folders, nested folders of nested folders, and so on) and what folder contains most files (including the files in the subfolders). More formally, the subfolders of the folder are all its directly nested folders and the subfolders of these nested folders. The given folder is not considered the subfolder of itself. A file is regarded as lying in a folder, if and only if it either lies directly in this folder, or lies in some subfolder of the folder. For a better understanding of how to count subfolders and files for calculating the answer, see notes and answers to the samples. You are given a few files that Petya has managed to create. The path to each file looks as follows: diskName:\folder1\folder2\...\ foldern\fileName * diskName is single capital letter from the set {C,D,E,F,G}. * folder1, ..., foldern are folder names. Each folder name is nonempty sequence of lowercase Latin letters and digits from 0 to 9. (n β‰₯ 1) * fileName is a file name in the form of name.extension, where the name and the extension are nonempty sequences of lowercase Latin letters and digits from 0 to 9. It is also known that there is no file whose path looks like diskName:\fileName. That is, each file is stored in some folder, but there are no files directly in the root. Also let us assume that the disk root is not a folder. Help Petya to find the largest number of subfolders, which can be in some folder, and the largest number of files that can be in some folder, counting all its subfolders. Input Each line of input data contains the description of one file path. The length of each line does not exceed 100, and overall there are no more than 100 lines. It is guaranteed, that all the paths are correct and meet the above rules. It is also guaranteed, that there are no two completely equal lines. That is, each file is described exactly once. There is at least one line in the input data. Output Print two space-separated numbers. The first one is the maximal number of possible subfolders in a folder (including nested folders, nested folders of nested folders, and so on). The second one is the maximal number of files in a folder (including nested files in subfolders). Note that the disks are not regarded as folders. Examples Input C:<span class="tex-span">\</span>folder1<span class="tex-span">\</span>file1.txt Output 0 1 Input C:<span class="tex-span">\</span>folder1<span class="tex-span">\</span>folder2<span class="tex-span">\</span>folder3<span class="tex-span">\</span>file1.txt C:<span class="tex-span">\</span>folder1<span class="tex-span">\</span>folder2<span class="tex-span">\</span>folder4<span class="tex-span">\</span>file1.txt D:<span class="tex-span">\</span>folder1<span class="tex-span">\</span>file1.txt Output 3 2 Input C:<span class="tex-span">\</span>file<span class="tex-span">\</span>file<span class="tex-span">\</span>file<span class="tex-span">\</span>file<span class="tex-span">\</span>file.txt C:<span class="tex-span">\</span>file<span class="tex-span">\</span>file<span class="tex-span">\</span>file<span class="tex-span">\</span>file2<span class="tex-span">\</span>file.txt Output 4 2 Note In the first sample we have one folder on the "C" disk. It has no subfolders, which is why the first number in the answer is 0. But this folder contains one file, so the second number of the answer is 1. In the second sample we have several different folders. Consider the "folder1" folder on the "C" disk. This folder directly contains one folder, "folder2". The "folder2" folder contains two more folders β€” "folder3" and "folder4". Thus, the "folder1" folder on the "C" drive has exactly 3 subfolders. Also this folder contains two files, even though they do not lie directly in the folder, but they are located in subfolders of "folder1". In the third example we see that the names of some folders and some subfolders are identical. Consider the "file" folder, which lies directly on the "C" disk. That folder contains another "file" folder, which in turn contains another "file" folder, which contains two more folders, "file" and "file2". Thus, the "file" folder, which lies directly on the "C" disk, contains 4 subfolders. ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct Node { map<string, int> folder, file; string name; }; vector<Node> tree; string s; int Sch = 4; void Build(int root) { int k = s.find('\\'); if (k == -1) { tree[root].file.insert(make_pair(s, 1)); } else { string nf = s.substr(0, k); s.erase(0, k + 1); if (tree[root].folder.find(nf) == tree[root].folder.end()) { Sch++; tree[Sch].name = nf; tree[root].folder.insert(make_pair(nf, Sch)); Build(Sch); } else Build(tree[root].folder[nf]); } } int tresfol = 0; int tresfile = 0; int resfol = 0; int resfile = 0; void r(int root) { map<string, int>::iterator it; resfol += tree[root].folder.size(); resfile += tree[root].file.size(); for (it = tree[root].folder.begin(); it != tree[root].folder.end(); it++) { r(it->second); } } int main() { tree.resize(30000); int root; while (cin >> s) { root = int(s[0] - 'A' - 2); s.erase(0, 3); Build(root); } for (int i = 0; i < 5; ++i) { map<string, int>::iterator it; for (it = tree[i].folder.begin(); it != tree[i].folder.end(); it++) { r(it->second); if (tresfol < resfol) tresfol = resfol; if (tresfile < resfile) tresfile = resfile; resfile = resfol = 0; } } cout << tresfol << ' ' << tresfile; return 0; } ```
### Prompt Please provide a Cpp coded solution to the problem described below: You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black. HW characters from A_{11} to A_{HW} represent the colors of the squares. A_{ij} is `#` if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is `.` if that square is white. We will repeatedly perform the following operation until all the squares are black: * Every white square that shares a side with a black square, becomes black. Find the number of operations that will be performed. The initial grid has at least one black square. Constraints * 1 \leq H,W \leq 1000 * A_{ij} is `#` or `.`. * The given grid has at least one black square. Input Input is given from Standard Input in the following format: H W A_{11}A_{12}...A_{1W} : A_{H1}A_{H2}...A_{HW} Output Print the number of operations that will be performed. Examples Input 3 3 ... .#. ... Output 2 Input 6 6 ..#..# ...... ..#.. ...... .#.... ....#. Output 3 ### Response ```cpp #include <iostream> #include <queue> #define pii pair<int,int> #define ppi pair<pii,int> #define fst first #define snd second const int dr[4][2]={{1,0},{0,1},{-1,0},{0,-1}}; using namespace std; queue<ppi> q;int n,m,mx=0;string mp[1001]={};bool bt[1001][1001]={}; bool isv(pii dt) {return dt.fst>=0&&dt.fst<n&&dt.snd>=0&&dt.snd<m;} int main() { ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); cin>>n>>m; for (int i=0;i<n;i++) { cin>>mp[i]; for (int j=0;j<m;j++) { if (mp[i][j]=='#') {q.push({{i,j},0});} } } while (!q.empty()) { ppi dt = q.front();q.pop(); if (!bt[dt.fst.fst][dt.fst.snd]) { bt[dt.fst.fst][dt.fst.snd] = 1; mx = dt.snd; for (int i=0;i<4;i++) { if (isv({dt.fst.fst+dr[i][0],dt.fst.snd+dr[i][1]})) {q.push({{dt.fst.fst+dr[i][0],dt.fst.snd+dr[i][1]},dt.snd+1});} } } } cout<<mx<<"\n"; return 0; } ```
### Prompt Develop a solution in CPP to the problem described below: You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a regular bracket sequence is well-known, so you can be familiar with it. Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS. For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not. Determine the least number of replaces to make the string s RBS. Input The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106. Output If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s. Examples Input [&lt;}){} Output 2 Input {()}[] Output 0 Input ]] Output Impossible ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); string s; cin >> s; map<char, bool> mp = {{'<', 1}, {'{', 1}, {'[', 1}, {'(', 1}, {']', 0}, {'}', 0}, {'>', 0}, {')', 0}}; map<char, char> m = {{'<', '>'}, {'{', '}'}, {'[', ']'}, {'(', ')'}}; stack<int> p; int ans = 0; for (auto c : s) { if (mp[c]) p.push(c); else { if (p.empty()) { cout << "Impossible\n"; return 0; } else if (c != m[p.top()]) ans++; p.pop(); } } if (p.empty()) cout << ans << endl; else cout << "Impossible\n"; return 0; } ```
### Prompt Generate a cpp solution to the following problem: Recently Luba bought a very interesting book. She knows that it will take t seconds to read the book. Luba wants to finish reading as fast as she can. But she has some work to do in each of n next days. The number of seconds that Luba has to spend working during i-th day is ai. If some free time remains, she can spend it on reading. Help Luba to determine the minimum number of day when she finishes reading. It is guaranteed that the answer doesn't exceed n. Remember that there are 86400 seconds in a day. Input The first line contains two integers n and t (1 ≀ n ≀ 100, 1 ≀ t ≀ 106) β€” the number of days and the time required to read the book. The second line contains n integers ai (0 ≀ ai ≀ 86400) β€” the time Luba has to spend on her work during i-th day. Output Print the minimum day Luba can finish reading the book. It is guaranteed that answer doesn't exceed n. Examples Input 2 2 86400 86398 Output 2 Input 2 86400 0 86400 Output 1 ### Response ```cpp #include <bits/stdc++.h> int a[1100]; int main() { int n, t; while (scanf("%d%d", &n, &t) != EOF) { memset(a, 0, sizeof(a)); for (int i = 0; i < n; ++i) { scanf("%d", &a[i]); } int result = 0; while (t > 0) { t -= 86400 - a[result]; ++result; } printf("%d\n", result); } return 0; } ```
### Prompt Your task is to create a CPP solution to the following problem: While some people enjoy spending their time solving programming contests, Dina prefers taking beautiful pictures. As soon as Byteland Botanical Garden announced Summer Oenothera Exhibition she decided to test her new camera there. The exhibition consists of l = 10^{100} Oenothera species arranged in a row and consecutively numbered with integers from 0 to l - 1. Camera lens allows to take a photo of w species on it, i.e. Dina can take a photo containing flowers with indices from x to x + w - 1 for some integer x between 0 and l - w. We will denote such photo with [x, x + w - 1]. She has taken n photos, the i-th of which (in chronological order) is [x_i, x_i + w - 1] in our notation. She decided to build a time-lapse video from these photos once she discovered that Oenothera blossoms open in the evening. Dina takes each photo and truncates it, leaving its segment containing exactly k flowers, then she composes a video of these photos keeping their original order and voilΓ , a beautiful artwork has been created! A scene is a contiguous sequence of photos such that the set of flowers on them is the same. The change between two scenes is called a cut. For example, consider the first photo contains flowers [1, 5], the second photo contains flowers [3, 7] and the third photo contains flowers [8, 12]. If k = 3, then Dina can truncate the first and the second photo into [3, 5], and the third photo into [9, 11]. First two photos form a scene, third photo also forms a scene and the transition between these two scenes which happens between the second and the third photos is a cut. If k = 4, then each of the transitions between photos has to be a cut. Dina wants the number of cuts to be as small as possible. Please help her! Calculate the minimum possible number of cuts for different values of k. Input The first line contains three positive integer n, w, q (1 ≀ n, q ≀ 100 000, 1 ≀ w ≀ 10^9) β€” the number of taken photos, the number of flowers on a single photo and the number of queries. Next line contains n non-negative integers x_i (0 ≀ x_i ≀ 10^9) β€” the indices of the leftmost flowers on each of the photos. Next line contains q positive integers k_i (1 ≀ k_i ≀ w) β€” the values of k for which you have to solve the problem. It's guaranteed that all k_i are distinct. Output Print q integers β€” for each width of the truncated photo k_i, the minimum number of cuts that is possible. Examples Input 3 6 5 2 4 0 1 2 3 4 5 Output 0 0 1 1 2 Input 6 4 3 1 2 3 4 3 2 1 2 3 Output 0 1 2 ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename T1, typename T2> inline void chkmin(T1 &x, T2 y) { if (x > y) x = y; } template <typename T1, typename T2> inline void chkmax(T1 &x, T2 y) { if (x < y) x = y; } using ll = long long; using ld = long double; const int MAXMEM = 200 * 1000 * 1024; char _memory[MAXMEM]; size_t _ptr = 0; void *operator new(size_t _x) { _ptr += _x; return _memory + _ptr - _x; } void operator delete(void *) noexcept {} const string FILENAME = "input"; const int MAXN = 100228; const int BLOCK = 30; const int BLOCK1 = 1300; int n, w, q; int x[MAXN]; int ans[MAXN]; int mx[18][MAXN]; int mx1[18][MAXN]; int gr[MAXN]; inline int getmax(const int l, const int r) { int grs = 31 - __builtin_clz(r - l + 1); return max(mx1[grs][l], mx1[grs][r - (1 << grs) + 1]); } inline int getmin(const int l, const int r) { int grs = 31 - __builtin_clz(r - l + 1); return min(mx[grs][l], mx[grs][r - (1 << grs) + 1]); } inline bool check(const int l, const int r, int k) { if (l > r || r >= n) { return false; } int f = getmin(l, r); int f1 = getmax(l, r); return f + w - f1 >= k; } inline int findGroupEnd(const int i, const int k) { int l = i; int r = n - 1; while (l < r) { int mid = (l + r + 1) >> 1; if (check(i, mid, k)) { l = mid; } else { r = mid - 1; } } return l + 1; } int curs[MAXN]; int jump[MAXN]; int target[MAXN]; int val; void calc(int i) { if (curs[i] == BLOCK) { jump[i] = 0; target[i] = i; } else { if (i + curs[i] >= n) { jump[i] = 1; target[i] = i + curs[i]; } else { if (target[curs[i] + i] >= i + BLOCK) { int t = i + curs[i]; int cnt = 1; while (curs[t] + t < i + BLOCK) { cnt++; t += curs[t]; } target[i] = t + curs[t]; jump[i] = cnt + 1; } else { jump[i] = 1 + jump[curs[i] + i]; target[i] = target[curs[i] + i]; } } } } void calc1(int i) { if (curs[i] == BLOCK) { jump[i] = 0; target[i] = i; } else { if (i + curs[i] >= n) { jump[i] = 1; target[i] = i + curs[i]; } } } int gt[MAXN]; int ls[MAXN]; int ft[MAXN]; int ukr; int nxt[MAXN]; bool used[MAXN]; int st[MAXN]; int uks; int grs; int stacker[MAXN]; int ukt = 0; int curuk[MAXN]; int curval[MAXN]; void dfs(int start) { ukt = 0; stacker[ukt] = start; curuk[start] = gt[start]; ukt++; uks = 0; curval[start] = 0; while (ukt) { int u = stacker[ukt - 1]; if (curuk[u] == gt[u]) { used[u] = true; if (u <= grs) { if (target[curs[u] + u] >= u + BLOCK) { while (curval[u] < uks && st[curval[u]] >= u + BLOCK) { curval[u]++; } int l = curval[u]; jump[u] = uks - l; if (curs[st[l]] == BLOCK) { target[u] = st[l]; } else { jump[u]++; target[u] = st[l] + curs[st[l]]; } } else { jump[u] = 1 + jump[curs[u] + u]; target[u] = target[curs[u] + u]; } } st[uks] = u; uks++; } if (curuk[u] == -1) { uks--; ukt--; continue; } int h = ft[curuk[u]]; curuk[u] = nxt[curuk[u]]; if (!used[h]) { stacker[ukt] = h; curval[h] = curval[u]; curuk[h] = gt[h]; ukt++; } } } void add(int a, int b) { if (gt[a] == -1) { gt[a] = ukr; ls[a] = ukr; ft[ukr] = b; nxt[ukr] = -1; ukr++; } else { nxt[ls[a]] = ukr; ft[ukr] = b; nxt[ukr] = -1; ls[a] = ukr; ukr++; } } void update(int i) { for (int j = i; j >= max(0, i - BLOCK - 1); j--) { calc(j); } } bool bad[MAXN]; int curs2[MAXN]; inline bool comp(const pair<int, pair<int, int> > &a, const pair<int, pair<int, int> > &b) { return a.first < b.first; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> w >> q; for (int i = 0; i < n; i++) { cin >> x[i]; mx[0][i] = x[i]; mx1[0][i] = x[i]; } for (int k = 1; k < 18; k++) { for (int i = 0; i < n; i++) { int t = min(i + (1 << (k - 1)), n - 1); mx[k][i] = min(mx[k - 1][i], mx[k - 1][t]); mx1[k][i] = max(mx1[k - 1][i], mx1[k - 1][t]); } } int cur = 1; int step = 0; for (int i = 1; i <= n; i++) { if (cur + cur <= i) { cur += cur; step++; } gr[i] = step; } vector<pair<int, int> > st; for (int it = 0; it < q; it++) { int k; cin >> k; st.push_back({k, it}); } sort((st).begin(), (st).end()); vector<pair<int, pair<int, int> > > g; vector<pair<int, int> > g1; for (int i = 0; i < n; i++) { for (int j = 1; j <= BLOCK; j++) { int maxk = 0; if (i + j - 1 >= n) { maxk = 0; } else { int s = getmin(i, i + j - 1); int s1 = getmax(i, i + j - 1); maxk = max(0, s + w - s1); } g.push_back({maxk + 1, {i, j - 1}}); if (maxk) { chkmax(curs[i], j); } } if (i + BLOCK1 <= n) { int s = getmin(i, i + BLOCK1 - 1); int s1 = getmax(i, i + BLOCK1 - 1); if (max(0, s + w - s1) != 0) { g1.push_back({max(0, s + w - s1) + 1, i}); bad[i] = true; } } curs2[i] = findGroupEnd(i, 1) - i; } sort((g).begin(), (g).end(), comp); sort((g1).begin(), (g1).end()); val = 1; int uk = 0; for (int i = n - 1; i >= 0; i--) { calc(i); } int uk1 = 0; for (int it = 0; it < q; it++) { val = st[it].first; while (uk < (int)(g).size() && g[uk].first <= val) { int gh = curs[g[uk].second.first]; chkmin(curs[g[uk].second.first], g[uk].second.second); if (curs[g[uk].second.first] != gh) { update(g[uk].second.first); } uk++; } while (uk1 < (int)(g1).size() && g1[uk1].first <= val) { bad[g1[uk1].second] = false; curs2[g1[uk1].second] = BLOCK1 - 1; uk1++; } int cur = 0; int cnt = 0; while (cur < n) { if (curs[cur] == BLOCK) { if (bad[cur]) { cnt++; cur = findGroupEnd(cur, val); } else { while (!check(cur, cur + curs2[cur] - 1, val)) { curs2[cur]--; } cnt++; int val = curs2[cur]; cur += val; } } else { cnt += jump[cur]; cur = target[cur]; } } ans[st[it].second] = cnt - 1; } for (int it = 0; it < q; it++) { cout << ans[it] << '\n'; } return 0; } ```
### Prompt Your challenge is to write a cpp solution to the following problem: <image> Input The input contains two integers a, b (1 ≀ a ≀ 10, 0 ≀ b ≀ 22Β·a - 1) separated by a single space. Output Output two integers separated by a single space. Examples Input 1 0 Output 0 0 Input 2 15 Output 3 0 Input 4 160 Output 12 12 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int a, b; scanf("%d%d", &a, &b); int x = 0, y = 0; for (int i = 1; i <= a; i++) { switch (b % 4) { case 0: swap(x, y); break; case 1: y += (1 << i) >> 1; break; case 2: x += (1 << i) >> 1; y += (1 << i) >> 1; break; case 3: int tx = ((1 << (i - 1)) - 1) ^ y; int ty = ((1 << (i - 1)) - 1) ^ x; x = tx + ((1 << i) >> 1); y = ty; break; } b /= 4; } printf("%d %d\n", x, y); return 0; } ```
### Prompt Please formulate a cpp solution to the following problem: There is a tree with N vertices numbered 1 through N. The i-th edge connects Vertex x_i and y_i. Each vertex is painted white or black. The initial color of Vertex i is represented by a letter c_i. c_i = `W` represents the vertex is white; c_i = `B` represents the vertex is black. A cat will walk along this tree. More specifically, she performs one of the following in one second repeatedly: * Choose a vertex that is adjacent to the vertex where she is currently, and move to that vertex. Then, invert the color of the destination vertex. * Invert the color of the vertex where she is currently. The cat's objective is to paint all the vertices black. She may start and end performing actions at any vertex. At least how many seconds does it takes for the cat to achieve her objective? Constraints * 1 ≀ N ≀ 10^5 * 1 ≀ x_i,y_i ≀ N (1 ≀ i ≀ N-1) * The given graph is a tree. * c_i = `W` or c_i = `B`. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} c_1c_2..c_N Output Print the minimum number of seconds required to achieve the objective. Examples Input 5 1 2 2 3 2 4 4 5 WBBWW Output 5 Input 6 3 1 4 5 2 6 6 1 3 4 WWBWBB Output 7 Input 1 B Output 0 Input 20 2 19 5 13 6 4 15 6 12 19 13 19 3 11 8 3 3 20 16 13 7 14 3 17 7 8 10 20 11 9 8 18 8 2 10 1 6 13 WBWBWBBWWWBBWWBBBBBW Output 21 ### Response ```cpp #include <cstdio> #include <iostream> #include <cstring> #include <algorithm> #include <queue> #include <string> using namespace std; typedef long long LL; const LL N = 100005; LL ec = 0,to[N << 1],nxt[N << 1],hed[N],deg[N]; LL cnt = 0; void add_edge(LL f,LL t){ ++ ec; to[ec] = t; nxt[ec] = hed[f]; hed[f] = ec; deg[t] ++; } LL vis[N] = {0},val[N],dis[N]; LL eu[N],ev[N],n; string s; void solve(){ queue <LL> q; for(LL i = 1;i <= n;i ++) if(deg[i] == 1 && s[i] == 'B') q.push(i); while(!q.empty()){ LL u = q.front(); q.pop(); vis[u] = 1; for(LL i = hed[u];i;i = nxt[i]){ LL v = to[i]; if(!vis[v]){ deg[v] --; if(deg[v] == 1 && s[v] == 'B') q.push(v); } } // cout << u << ' ' << id << ' ' << tot << endl; // if(tot == 1 && s[id] == 'B') q.push(id); } memset(deg,0,sizeof(deg)); memset(hed,0,sizeof(hed)); ec = 0; for(LL i = 1;i < n;i ++){ if(vis[eu[i]] || vis[ev[i]]) continue; add_edge(eu[i],ev[i]); add_edge(ev[i],eu[i]); // cout << eu[i] << ',' << ev[i] << endl; } for(LL i = 1;i <= n;i ++){ val[i] = 0; if(vis[i]) continue; if((s[i] == 'B' && deg[i] % 2 == 1) || (s[i] == 'W' && deg[i] % 2 == 0)){ val[i] = 2; cnt ++; } } } LL td = 0; LL d[N]; void dfs(LL u,LL f){ d[u] = val[u]; for(LL i = hed[u];i;i = nxt[i]){ LL v = to[i]; if(v == f) continue; dfs(v,u); td = max(td,d[u] + d[v]); d[u] = max(d[u],d[v] + val[u]); } } int main(){ ios::sync_with_stdio(false); cin >> n; for(LL i = 1;i < n;i ++){ cin >> eu[i] >> ev[i]; add_edge(eu[i],ev[i]); add_edge(ev[i],eu[i]); // deg[u] ++; deg[v] ++; } cin >> s; s = ' ' + s; solve(); LL trt = 1; for(LL i = 1;i <= n;i ++) if(!vis[i]) trt = i; dfs(trt,0); // cout << ec << ';' << cnt << ';' << endl; LL ans = ec + cnt - td; cout << ans << '\n'; return 0; } ```
### Prompt Develop a solution in CPP to the problem described below: Joe has been hurt on the Internet. Now he is storming around the house, destroying everything in his path. Joe's house has n floors, each floor is a segment of m cells. Each cell either contains nothing (it is an empty cell), or has a brick or a concrete wall (always something one of three). It is believed that each floor is surrounded by a concrete wall on the left and on the right. Now Joe is on the n-th floor and in the first cell, counting from left to right. At each moment of time, Joe has the direction of his gaze, to the right or to the left (always one direction of the two). Initially, Joe looks to the right. Joe moves by a particular algorithm. Every second he makes one of the following actions: * If the cell directly under Joe is empty, then Joe falls down. That is, he moves to this cell, the gaze direction is preserved. * Otherwise consider the next cell in the current direction of the gaze. * If the cell is empty, then Joe moves into it, the gaze direction is preserved. * If this cell has bricks, then Joe breaks them with his forehead (the cell becomes empty), and changes the direction of his gaze to the opposite. * If this cell has a concrete wall, then Joe just changes the direction of his gaze to the opposite (concrete can withstand any number of forehead hits). Joe calms down as soon as he reaches any cell of the first floor. The figure below shows an example Joe's movements around the house. <image> Determine how many seconds Joe will need to calm down. Input The first line contains two integers n and m (2 ≀ n ≀ 100, 1 ≀ m ≀ 104). Next n lines contain the description of Joe's house. The i-th of these lines contains the description of the (n - i + 1)-th floor of the house β€” a line that consists of m characters: "." means an empty cell, "+" means bricks and "#" means a concrete wall. It is guaranteed that the first cell of the n-th floor is empty. Output Print a single number β€” the number of seconds Joe needs to reach the first floor; or else, print word "Never" (without the quotes), if it can never happen. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 3 5 ..+.# #+..+ +.#+. Output 14 Input 4 10 ...+.##+.+ +#++..+++# ++.#++++.. .+##.++#.+ Output 42 Input 2 2 .. ++ Output Never ### Response ```cpp #include <bits/stdc++.h> using namespace std; char s[103][10003]; int main() { int n, m; scanf("%d %d", &n, &m); int i; for (i = 0; i < n; i++) scanf("%s", s[i]); int vz = 0; int pos = 0; long long ans = 0; int l, r; for (i = 0; i < n - 1; i++) { l = r = pos; bool ll, rr; ll = rr = false; while (true) { if (vz == 0) { if (s[i + 1][pos] == '.') { ans++; break; } if (pos == r) { if (r + 1 == m || s[i][r + 1] == '#') { vz ^= 1; rr = true; ans++; } else if (s[i][r + 1] == '.') { r++; pos++; ans++; } else { s[i][r + 1] = '.'; vz ^= 1; ans++; } } else { ans += r - pos; pos = r; } } else { if (s[i + 1][pos] == '.') { ans++; break; } else if (pos == l) { if (l == 0 || s[i][l - 1] == '#') { ll = true; ans++; vz ^= 1; } else if (s[i][l - 1] == '+') { s[i][l - 1] = '.'; ans++; vz ^= 1; } else { ans++; pos--; l--; } } else { ans += pos - l; pos = l; } } if (ll && rr) { printf("Never\n"); return 0; } } } printf("%I64d\n", ans); return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: Today on Informatics class Nastya learned about GCD and LCM (see links below). Nastya is very intelligent, so she solved all the tasks momentarily and now suggests you to solve one of them as well. We define a pair of integers (a, b) good, if GCD(a, b) = x and LCM(a, b) = y, where GCD(a, b) denotes the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) of a and b, and LCM(a, b) denotes the [least common multiple](https://en.wikipedia.org/wiki/Least_common_multiple) of a and b. You are given two integers x and y. You are to find the number of good pairs of integers (a, b) such that l ≀ a, b ≀ r. Note that pairs (a, b) and (b, a) are considered different if a β‰  b. Input The only line contains four integers l, r, x, y (1 ≀ l ≀ r ≀ 109, 1 ≀ x ≀ y ≀ 109). Output In the only line print the only integer β€” the answer for the problem. Examples Input 1 2 1 2 Output 2 Input 1 12 1 12 Output 4 Input 50 100 3 30 Output 0 Note In the first example there are two suitable good pairs of integers (a, b): (1, 2) and (2, 1). In the second example there are four suitable good pairs of integers (a, b): (1, 12), (12, 1), (3, 4) and (4, 3). In the third example there are good pairs of integers, for example, (3, 30), but none of them fits the condition l ≀ a, b ≀ r. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long mod = 1e9 + 7; long long ksm(long long x, long long y, long long o) { if (x == 0 && y == 0) return 1; if (x == 0) return 0; long long ret = 1; while (y) { if (y & 1) ret = (ret * x) % o; x = (x * x) % o; y >>= 1; } return (ret % o); } const int maxn = 1e6 + 7; long long l, r, x, y; int t; long long pri[maxn]; long long ans = 0; map<pair<long long, long long>, bool> mp; void dfs(long long a, long long b, int c) { if (c == t) { if (a >= l && a <= r && b >= l && b <= r && mp.find({a, b}) == mp.end()) { ans++; mp[{a, b}] = 1; } return; } dfs(a * pri[c], b, c + 1); dfs(a, b * pri[c], c + 1); } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); cin >> l >> r >> x >> y; if (y % x != 0) { cout << 0 << endl; return 0; } long long p = y; y /= x; t = 0; for (int i = 2; i * i <= y; i++) { int cnt = 0; while (y % i == 0) { y /= i; if (cnt == 0) { pri[t] = i; } else { pri[t] *= i; } cnt++; } if (cnt != 0) t++; } if (y != 0) pri[t++] = y; dfs(x, x, 0); cout << ans << endl; } ```
### Prompt Please provide a CPP coded solution to the problem described below: You are given an array a consisting of n elements. You may apply several operations (possibly zero) to it. During each operation, you choose two indices i and j (1 ≀ i, j ≀ n; i β‰  j), increase a_j by a_i, and remove the i-th element from the array (so the indices of all elements to the right to it decrease by 1, and n also decreases by 1). Your goal is to make the array a strictly ascending. That is, the condition a_1 < a_2 < ... < a_n should hold (where n is the resulting size of the array). Calculate the minimum number of actions required to make the array strictly ascending. Input The first line contains one integer T (1 ≀ T ≀ 10000) β€” the number of test cases. Each test case consists of two lines. The first line contains one integer n (1 ≀ n ≀ 15) β€” the number of elements in the initial array a. The second line contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^6). It is guaranteed that: * the number of test cases having n β‰₯ 5 is not greater than 5000; * the number of test cases having n β‰₯ 8 is not greater than 500; * the number of test cases having n β‰₯ 10 is not greater than 100; * the number of test cases having n β‰₯ 11 is not greater than 50; * the number of test cases having n β‰₯ 12 is not greater than 25; * the number of test cases having n β‰₯ 13 is not greater than 10; * the number of test cases having n β‰₯ 14 is not greater than 3; * the number of test cases having n β‰₯ 15 is not greater than 1. Output For each test case, print the answer as follows: In the first line, print k β€” the minimum number of operations you have to perform. Then print k lines, each containing two indices i and j for the corresponding operation. Note that the numeration of elements in the array changes after removing elements from it. If there are multiple optimal sequences of operations, print any one of them. Example Input 4 8 2 1 3 5 1 2 4 5 15 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1 2 3 3 14 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Output 3 6 8 1 6 4 1 7 1 15 1 13 1 11 1 9 1 7 1 5 1 3 1 2 1 0 Note In the first test case, the sequence of operations changes a as follows: [2, 1, 3, 5, 1, 2, 4, 5] β†’ [2, 1, 3, 5, 1, 4, 7] β†’ [1, 3, 5, 1, 6, 7] β†’ [2, 3, 5, 6, 7]. ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct stt { int t, u, s; stt(int T = 0, int U = 0, int S = 0) : t(T), u(U), s(S) {} } pre[16][16][1 << 16]; int f[16][16][1 << 16], a[16], g[1 << 16], id[16]; int main() { int t; scanf("%d", &t); while (t-- > 0) { int n; scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &a[i]); int m = (1 << n) - 1; for (int s = 0; s <= m; s++) g[s] = 0; for (int s = 0; s <= m; s++) for (int i = 0; i < n; i++) if (s & (1 << i)) g[s] += a[i]; for (int s = 0; s <= m; s++) for (int i = 0; i <= n; i++) for (int j = 0; j <= n; j++) f[i][j][s] = 100000000; f[0][0][0] = 0; for (int i = 0; i < n; i++) for (int u = 0; u < n; u++) for (int s = 0; s <= m; s++) if (f[i][u][s] < 100000000) for (int t = s ^ m; t; t = (t - 1) & (s ^ m)) if (g[t] > f[i][u][s] && (t >> u)) { int v = u + __builtin_ctz(t >> u) + 1; if (f[i + 1][v][s | t] > g[t]) { f[i + 1][v][s | t] = g[t]; pre[i + 1][v][s | t] = stt(i, u, s); } } stt u(-1, -1, -1), v; for (int i = n; i >= 1 && u.t == -1; i--) for (int j = 1; j <= n; j++) if (f[i][j][m] < 100000000) { u = stt(i, j, m); break; } printf("%d\n", n - u.t); for (int i = 0; i < n; i++) id[i] = i + 1; for (; u.t; u = v) { v = pre[u.t][u.u][u.s]; int t = u.s ^ v.s; for (int i = 0; i < n; i++) if ((t & (1 << i)) && i != u.u - 1) { printf("%d %d\n", id[i], id[u.u - 1]); for (int j = i + 1; j < n; j++) id[j]--; } } } return 0; } ```
### Prompt Develop a solution in cpp to the problem described below: If you draw a few infinitely long straight lines on an infinitely wide plane, this plane will be divided into several areas. For example, if you draw a straight line, the plane will be divided into two areas. Even if you draw the same number of straight lines, the number of areas obtained will differ depending on how you draw. For example, if you draw two straight lines in parallel, you get three areas, and if you draw two straight lines perpendicular to each other, you get four areas. <image> Create a program that outputs the maximum number of regions that can be obtained by drawing n straight lines. Input Given multiple datasets. Each dataset is given n (1 ≀ n ≀ 10,000) on one row. Please process until the end of the input. The number of datasets does not exceed 50. Output For each dataset, output the maximum number of divisions on one line. Example Input 1 3 Output 2 7 ### Response ```cpp #include<cstdio> int main(){for(int n;~scanf("%d",&n);printf("%d\n",n*(n+1)/2+1));} ```
### Prompt Your task is to create a Cpp solution to the following problem: I decided to do bowling as a recreation of the class. Create a program that inputs the pitching information for each participant and outputs the grade information in descending order of score. If there is a tie, output in ascending order of student ID number. However, it is assumed that the number of participants is 3 or more and 40 or less, and one game is thrown per person. Bowling is a sport in which the player rolls the ball toward 10 pins arranged in an equilateral triangle with the vertices facing the player and knocks down the pins. The case where all the players fall in the first pitch is called a strike, and only that pitch advances to the next frame. If it is not a strike, leave the remaining pins and make a second pitch. A spare is when all the pitches have fallen on the second pitch. After the second pitch, proceed to the next frame. One game consists of 10 frames, and each of the 1st to 9th frames can be pitched twice. At the beginning of each frame, all 10 pins are upright. In the 10th frame, if there is a strike or a spare, a total of 3 pitches will be thrown, otherwise 2 pitches will be made and the game will end. Score example 1 <image> Score example 2 (when the maximum score is 300 points) <image> How to calculate the score * If there are no spares or strikes in each frame, the number of pins defeated in two pitches will be the score for that frame. (4th and 8th frames of score example 1) * If you give a spare, in addition to the number of defeated 10 points, the number of defeated pins in the next pitch will be added to the score of this frame. (Relationship between the 1st frame and the 2nd frame of the score example 1) In the 1st frame of the score example 1, 20 points including 10 points (points) defeated by 1 throw of the 2nd frame will be scored. The calculation method is the same for the third frame. * If you strike, the number of pins you defeated in the next two pitches will be added to the number of defeated 10 points. (Relationship between the 2nd frame and the 3rd frame of score example 1) Of course, there may be a strike during the following 2 throws. (Relationship between the 5th frame and the 6th and 7th frames of score example 1) * If you give a spare or strike only in the 10th frame, the total number of pins you have thrown and defeated will be added as the score in the 10th frame. * The total score of each frame is the score of one game, and the maximum score is 300 points. Input A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format: m score1 score2 :: scorem The number of participants m (3 ≀ m ≀ 40) is given in the first line, and the i-th participant information scorei is given in the following m lines. Each participant information is given in the following format, one line at a time. id s1 s2 ... sn The student ID number id (0 ≀ id ≀ 9999) is given first, followed by the number of fall pins of the jth throw sj (0 ≀ sj ≀ 10). It is assumed that the total number of pitches n is 12 or more and 21 or less, and the number of pins required for score calculation is given in just proportion. Output For each input dataset, the student ID number and score are output in descending order of score (if there is a tie, the student ID number is in ascending order). Please separate your student ID number and score with one space and output them on one line. Example Input 3 1010 6 3 10 7 1 0 7 9 1 10 6 2 4 3 9 1 9 0 1200 5 3 9 1 7 1 0 0 8 1 10 10 4 3 9 1 8 2 9 1101 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 3321 8 2 10 9 1 7 0 10 10 10 0 8 10 10 10 10 3332 5 0 10 9 1 4 1 9 0 10 10 7 1 5 2 8 1 3335 10 10 10 10 10 10 10 10 10 10 10 10 3340 8 2 7 3 6 4 8 2 8 2 9 1 7 3 6 4 8 2 9 1 7 0 Output 1200 127 1010 123 1101 60 3335 300 3321 200 3340 175 3332 122 ### Response ```cpp #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { typedef pair<int, int> Pii; int N; while(cin >> N && N) { vector<Pii> SCORE(N); for(int m=0; m<N; m++){ cin >> SCORE[m].second; int all = 0; int strike[11] = {}; for(int i=1; i<=10; i++){ int sc; cin >> sc; if( strike[i-1] == 2 ) all += sc; if( i-2 >= 0 && strike[i-1] == 2 && strike[i-2] == 2 ) all += sc; if( strike[i-1] == 1 ) all += sc; if(sc == 10){ all += sc; strike[i] = 2; } else { int add; cin >> add; if( strike[i-1] == 2 ) all += add; all += sc + add; if( sc + add == 10 ) strike[i] = 1; } } if( strike[10] == 2 ){ int sc, add; cin >> sc >> add; all += sc + add; if( strike[9] == 2 ) all += sc; } else if( strike[10] == 1 ){ int sc; cin>>sc; all += sc; } SCORE[m].first = -all; } sort(SCORE.begin(), SCORE.end()); for(int i=0; i<N; i++){ cout << SCORE[i].second << ' ' << -SCORE[i].first << endl; } } return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: The King of Flatland will organize a knights' tournament! The winner will get half the kingdom and the favor of the princess of legendary beauty and wisdom. The final test of the applicants' courage and strength will be a fencing tournament. The tournament is held by the following rules: the participants fight one on one, the winner (or rather, the survivor) transfers to the next round. Before the battle both participants stand at the specified points on the Ox axis with integer coordinates. Then they make moves in turn. The first participant moves first, naturally. During a move, the first participant can transfer from the point x to any integer point of the interval [x + a; x + b]. The second participant can transfer during a move to any integer point of the interval [x - b; x - a]. That is, the options for the players' moves are symmetric (note that the numbers a and b are not required to be positive, and if a ≀ 0 ≀ b, then staying in one place is a correct move). At any time the participants can be located arbitrarily relative to each other, that is, it is allowed to "jump" over the enemy in any direction. A participant wins if he uses his move to transfer to the point where his opponent is. Of course, the princess has already chosen a husband and now she wants to make her sweetheart win the tournament. He has already reached the tournament finals and he is facing the last battle. The princess asks the tournament manager to arrange the tournament finalists in such a way that her sweetheart wins the tournament, considering that both players play optimally. However, the initial location of the participants has already been announced, and we can only pull some strings and determine which participant will be first and which one will be second. But how do we know which participant can secure the victory? Alas, the princess is not learned in the military affairs... Therefore, she asks you to determine how the battle will end considering that both opponents play optimally. Also, if the first player wins, your task is to determine his winning move. Input The first line contains four space-separated integers β€” x1, x2, a and b (x1 β‰  x2, a ≀ b, - 109 ≀ x1, x2, a, b ≀ 109) β€” coordinates of the points where the first and the second participant start, and the numbers that determine the players' moves, correspondingly. Output On the first line print the outcome of the battle as "FIRST" (without the quotes), if both players play optimally and the first player wins. Print "SECOND" (without the quotes) if the second player wins and print "DRAW" (without the quotes), if nobody is able to secure the victory. If the first player wins, print on the next line the single integer x β€” the coordinate of the point where the first player should transfer to win. The indicated move should be valid, that is, it should meet the following condition: x1 + a ≀ x ≀ x1 + b. If there are several winning moves, print any of them. If the first participant can't secure the victory, then you do not have to print anything. Examples Input 0 2 0 4 Output FIRST 2 Input 0 2 1 1 Output SECOND Input 0 2 0 1 Output DRAW Note In the first sample the first player can win in one move. In the second sample the first participant must go to point 1, where the second participant immediately goes and wins. In the third sample changing the position isn't profitable to either participant, so nobody wins. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1e5 + 10; int aa[N], bb[N], id[N]; int vis[N]; const int inf = 1 << 30; int sta[N], top; int sum[N * 2]; int main() { int l, r, a, b; while (scanf("%d%d%d%d", &l, &r, &a, &b) != EOF) { int flag = 0; if (l > r) { flag = 1; swap(l, r); swap(a, b); a *= -1; b *= -1; } if (r - l >= a && r - l <= b) { printf("FIRST\n"); if (!flag) printf("%d\n", r); else printf("%d\n", l); continue; } if (a <= 0) { printf("DRAW\n"); continue; } int x = (r - l) % (a + b); if (x >= 1 && x <= b) { if (x < a) printf("DRAW\n"); else { printf("FIRST\n"); if (!flag) printf("%d\n", l + x); else printf("%d\n", r - x); } } else { if (x != 0) printf("DRAW\n"); else printf("SECOND\n"); } } return 0; } ```
### Prompt Create a solution in CPP for the following problem: You've got an array consisting of n integers: a[1], a[2], ..., a[n]. Moreover, there are m queries, each query can be described by three integers li, ri, ki. Query li, ri, ki means that we should add <image> to each element a[j], where li ≀ j ≀ ri. Record <image> means the binomial coefficient, or the number of combinations from y elements into groups of x elements. You need to fulfil consecutively all queries and then print the final array. Input The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n integers a[1], a[2], ..., a[n] (0 ≀ ai ≀ 109) β€” the initial array. Next m lines contain queries in the format li, ri, ki β€” to all elements of the segment li... ri add number <image> (1 ≀ li ≀ ri ≀ n; 0 ≀ k ≀ 100). Output Print n integers: the i-th number is the value of element a[i] after all the queries. As the values can be rather large, print them modulo 1000000007 (109 + 7). Examples Input 5 1 0 0 0 0 0 1 5 0 Output 1 1 1 1 1 Input 10 2 1 2 3 4 5 0 0 0 0 0 1 6 1 6 10 2 Output 2 4 6 8 10 7 3 6 10 15 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, m; long long a[100005]; long long c[200005][105], f[100005][105]; const long long mod = 1e9 + 7; void add(long long &x, long long y) { x += y; x %= mod; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; ++i) scanf("%I64d", &a[i]); c[0][0] = 1; for (int i = 1; i <= 200000; ++i) { c[i][0] = 1; for (int j = 1; j <= 100; ++j) c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % mod; } for (int i = 1; i <= n; ++i) for (int j = 0; j <= 100; ++j) f[i][j] = 0; while (m--) { int l, r, k; scanf("%d%d%d", &l, &r, &k); for (int j = 0; j <= k; ++j) add(f[l][j], c[k][k - j]); for (int j = 0; j <= k; ++j) add(f[r + 1][j], mod - c[k + r - l + 1][k - j]); } for (int i = 1; i <= n; ++i) { for (int j = 0; j <= 100; ++j) { add(f[i][j], f[i - 1][j]); add(f[i][j], f[i - 1][j + 1]); } add(a[i], f[i][0]); printf("%I64d ", a[i]); } return 0; } ```
### Prompt Generate a cpp solution to the following problem: There are N(N+1)/2 dots arranged to form an equilateral triangle whose sides consist of N dots, as shown below. The j-th dot from the left in the i-th row from the top is denoted by (i, j) (1 \leq i \leq N, 1 \leq j \leq i). Also, we will call (i+1, j) immediately lower-left to (i, j), and (i+1, j+1) immediately lower-right to (i, j). <image> Takahashi is drawing M polygonal lines L_1, L_2, ..., L_M by connecting these dots. Each L_i starts at (1, 1), and visits the dot that is immediately lower-left or lower-right to the current dots N-1 times. More formally, there exist X_{i,1}, ..., X_{i,N} such that: * L_i connects the N points (1, X_{i,1}), (2, X_{i,2}), ..., (N, X_{i,N}), in this order. * For each j=1, 2, ..., N-1, either X_{i,j+1} = X_{i,j} or X_{i,j+1} = X_{i,j}+1 holds. Takahashi would like to draw these lines so that no part of L_{i+1} is to the left of L_{i}. That is, for each j=1, 2, ..., N, X_{1,j} \leq X_{2,j} \leq ... \leq X_{M,j} must hold. Additionally, there are K conditions on the shape of the lines that must be followed. The i-th condition is denoted by (A_i, B_i, C_i), which means: * If C_i=0, L_{A_i} must visit the immediately lower-left dot for the B_i-th move. * If C_i=1, L_{A_i} must visit the immediately lower-right dot for the B_i-th move. That is, X_{A_i, {B_i}+1} = X_{A_i, B_i} + C_i must hold. In how many ways can Takahashi draw M polygonal lines? Find the count modulo 1000000007. Constraints * 1 \leq N \leq 20 * 1 \leq M \leq 20 * 0 \leq K \leq (N-1)M * 1 \leq A_i \leq M * 1 \leq B_i \leq N-1 * C_i = 0 or 1 * No pair appears more than once as (A_i, B_i). Input Input is given from Standard Input in the following format: N M K A_1 B_1 C_1 A_2 B_2 C_2 : A_K B_K C_K Output Print the number of ways for Takahashi to draw M polygonal lines, modulo 1000000007. Examples Input 3 2 1 1 2 0 Output 6 Input 3 2 2 1 1 1 2 1 0 Output 0 Input 5 4 2 1 3 1 4 2 0 Output 172 Input 20 20 0 Output 881396682 ### Response ```cpp #include<bits/stdc++.h> #define ll long long using namespace std; const int p=1e9+7; int mx,n,m,k,i,j,nt,pr,s,ns,ans,x,y,w,a[22][22],f[2][1200010]; int lowbit(int x){ return x&(-x); } int main(){ scanf("%d%d%d",&n,&m,&k);n--; for(i=1;i<=k;i++){ scanf("%d%d%d",&x,&y,&w); a[x][y-1]=w+1; } mx=1<<n; f[0][0]=1; for(i=1;i<=m;i++){ for(j=0;j<n;j++){ nt^=1;pr=nt^1; memset(f[nt],0,sizeof(f[nt])); for(s=0;s<mx;s++)if(f[pr][s]){ if((s&(1<<j))==0&&a[i][j]!=2)f[nt][s]=(f[nt][s]+f[pr][s])%p; if(a[i][j]!=1){ if(s&(1<<j))ns=s; else{ int tmp=((-1)^((1<<(j+1))-1))&s,Ds=!tmp?0:lowbit(tmp); ns=s^(1<<j)^Ds; } f[nt][ns]=(f[nt][ns]+f[pr][s])%p; } } } } for(s=0;s<mx;s++)ans=(ans+f[nt][s])%p; printf("%d",ans); } ```
### Prompt Please create a solution in Cpp to the following problem: Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya has an array consisting of n numbers. He wants to perform m operations of two types: * add l r d β€” add an integer d to all elements whose indexes belong to the interval from l to r, inclusive (1 ≀ l ≀ r ≀ n, 1 ≀ d ≀ 104); * count l r β€” find and print on the screen how many lucky numbers there are among elements with indexes that belong to the interval from l to r inclusive (1 ≀ l ≀ r ≀ n). Each lucky number should be counted as many times as it appears in the interval. Petya has a list of all operations. The operations are such that after all additions the array won't have numbers that would exceed 104. Help Petya write a program that would perform these operations. Input The first line contains two integers n and m (1 ≀ n, m ≀ 105) β€” the number of numbers in the array and the number of operations correspondingly. The second line contains n positive integers, none of which exceeds 104 β€” those are the array numbers. Next m lines contain operations, one per line. They correspond to the description given in the statement. It is guaranteed that after all operations are fulfilled each number in the array will not exceed 104. Output For each operation of the second type print the single number on the single line β€” the number of lucky numbers in the corresponding interval. Examples Input 3 6 2 3 4 count 1 3 count 1 2 add 1 3 2 count 1 3 add 2 3 3 count 1 3 Output 1 0 1 1 Input 4 5 4 4 4 4 count 1 4 add 1 4 3 count 1 4 add 2 3 40 count 1 4 Output 4 4 4 Note In the first sample after the first addition the array will look in the following manner: 4 5 6 After the second addition: 4 8 9 The second sample after the first addition: 7 7 7 7 After the second addition: 7 47 47 7 ### Response ```cpp #include <bits/stdc++.h> int a[101000], cnt, luck[100000]; int sum[101000], n, m; char s[40000]; void add(int x, int y) { for (; x <= n; x += x & (-x)) sum[x] += y; } int ask(int x) { int ans = 0; for (; x; x -= x & (-x)) ans += sum[x]; return ans; } inline void dfs(long long x) { if (x > 1e4) return; luck[x]++; dfs(1ll * x * 10 + 4); dfs(1ll * x * 10 + 7); } int main() { dfs(0); scanf("%d %d", &n, &m); for (int i = 1; i <= n; ++i) { scanf("%d", &a[i]); if (luck[a[i]]) add(i, 1); } while (m--) { scanf(" %s", s + 1); if (s[1] == 'c') { int l, r; scanf("%d %d", &l, &r); printf("%d\n", ask(r) - ask(l - 1)); } else { int l, r, d; scanf("%d %d %d", &l, &r, &d); for (int i = l; i <= r; ++i) { int w = a[i]; a[i] += d; if (luck[a[i]] && !luck[w]) { add(i, 1); } if (luck[w] && !luck[a[i]]) { add(i, -1); } } } } return 0; } ```
### Prompt In Cpp, your task is to solve the following problem: Problem You decide to play a weird game with your friend A, who loves gathering. Given a set S of non-negative integers consisting of n elements that can be duplicated. Each element contained in the set S is a non-negative pi-ary number. With Steps 1 to 3 below as one turn for the set S, you and your opponent repeat the turn alternately. In each turn, operate in the order of this number. Step 1: Remove all the elements contained in the set S once, convert each removed element to a binary number, erase 0, divide it into one or more consecutive 1s, and divide the divided part. Add all to set S. Step 2: If Set S is empty at this time, the player currently playing this turn loses. Step 3: Select one element a contained in the set S, and subtract any integer x that satisfies 1 ≀ x ≀ a from that a. The figure below is an example of how to proceed for the first turn given the following inputs. Four 10 3 2 11 16 5 16 AE <image> The first is your turn. When both parties do their best for a given input, do you really win? Input The input is given in the following format: n p1 m1 p2 m2 ... pi mi ... pn mn N pi-ary numbers mi, which are elements of the set, are given. The number n of elements in the set does not exceed 105. Also, 2 ≀ pi ≀ 62 is satisfied. The pi-ary number mi uses 52 letters of the alphabet in addition to the usual numbers 0-9. The order is 012 ... 789 ABC ... XYZabc ... xyz in ascending order, and the characters up to the i-th are used. Also, the pi-ary mi does not exceed 218-1 in decimal. Output Output win if you win against the given input, lose if you lose. Examples Input 1 10 1 Output win Input 2 10 1 10 1 Output lose Input 3 25 53AI 43 3BI0 62 pn6 Output win ### Response ```cpp #include<bits/stdc++.h> using namespace std; int getNum(char c){ if('A'<=c&&c<='Z')return 10+c-'A'; if('a'<=c&&c<='z')return 36+c-'a'; return c-'0'; } int pto10(int p,string s){ int res=0,x=1; for(int i=0;i<s.size();i++)res+=x*getNum(s[i]),x*=p; return res; } int Cnt(int num){ int res=0; while(num)res++,num/=2; return res; } int main(){ int n,p,cnt1=0,cnt2=0; vector<int> v; string s; cin>>n; for(int i=0;i<n;i++){ cin>>p>>s; reverse(s.begin(),s.end()); int num=pto10(p,s),t=0; while(num){ if(num%2)t=t*10+1; else v.push_back(t),t=0; num/=2; } v.push_back(t); } for(int i=0;i<v.size();i++){ int cnt=Cnt(v[i]); if(!v[i])continue; if(cnt==1)cnt1++; else cnt2++; } if(cnt2||cnt1%2)cout<<"win"<<endl; else cout<<"lose"<<endl; return 0; } ```
### Prompt In cpp, your task is to solve the following problem: This time Baby Ehab will only cut and not stick. He starts with a piece of paper with an array a of length n written on it, and then he does the following: * he picks a range (l, r) and cuts the subsegment a_l, a_{l + 1}, …, a_r out, removing the rest of the array. * he then cuts this range into multiple subranges. * to add a number theory spice to it, he requires that the elements of every subrange must have their product equal to their [least common multiple (LCM)](https://en.wikipedia.org/wiki/Least_common_multiple). Formally, he partitions the elements of a_l, a_{l + 1}, …, a_r into contiguous subarrays such that the product of every subarray is equal to its LCM. Now, for q independent ranges (l, r), tell Baby Ehab the minimum number of subarrays he needs. Input The first line contains 2 integers n and q (1 ≀ n,q ≀ 10^5) β€” the length of the array a and the number of queries. The next line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^5) β€” the elements of the array a. Each of the next q lines contains 2 integers l and r (1 ≀ l ≀ r ≀ n) β€” the endpoints of this query's interval. Output For each query, print its answer on a new line. Example Input 6 3 2 3 10 7 5 14 1 6 2 4 3 5 Output 3 1 2 Note The first query asks about the whole array. You can partition it into [2], [3,10,7], and [5,14]. The first subrange has product and LCM equal to 2. The second has product and LCM equal to 210. And the third has product and LCM equal to 70. Another possible partitioning is [2,3], [10,7], and [5,14]. The second query asks about the range (2,4). Its product is equal to its LCM, so you don't need to partition it further. The last query asks about the range (3,5). You can partition it into [10,7] and [5]. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int v[100003]; int fv[100003]; int cnt; int prevv[21][100003]; void addnumber (int a) { for(int i=2;i*i<=a;++i) { if(a%i==0) { ++fv[i]; if(fv[i]==2) ++cnt; while(a%i==0) a/=i; } } if(a!=1) { ++fv[a]; if(fv[a]==2) ++cnt; } } void removenumber (int a) { for(int i=2;i*i<=a;++i) { if(a%i==0) { --fv[i]; if(fv[i]==1) --cnt; while(a%i==0) a/=i; } } if(a!=1) { --fv[a]; if(fv[a]==1) --cnt; } } int main() { ios_base::sync_with_stdio(false); int q,t,m,i,j,n; cin>>n>>m; for(i=1;i<=n;++i) cin>>v[i]; j=1,i=0; for(i=1;i<=n;++i) { addnumber(v[i]); while(cnt>0) removenumber(v[j++]); prevv[0][i]=j-1; } for(int put=1;put<=20;++put) { for(i=1;i<=n;++i) { prevv[put][i]=prevv[put-1][prevv[put-1][i]]; } } for(i=1;i<=m;++i) { int a,b; cin>>a>>b; int cnt=1; for(int put=20;put>=0;--put) { if(prevv[put][b]>=a) { cnt+=(1<<put); b=prevv[put][b]; } } cout<<cnt<<'\n'; } return 0; } ```
### Prompt Develop a solution in Cpp to the problem described below: There are N+1 towns. The i-th town is being attacked by A_i monsters. We have N heroes. The i-th hero can defeat monsters attacking the i-th or (i+1)-th town, for a total of at most B_i monsters. What is the maximum total number of monsters the heroes can cooperate to defeat? Constraints * All values in input are integers. * 1 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * 1 \leq B_i \leq 10^9 Input Input is given from Standard Input in the following format: N A_1 A_2 ... A_{N+1} B_1 B_2 ... B_N Output Print the maximum total number of monsters the heroes can defeat. Examples Input 2 3 5 2 4 5 Output 9 Input 3 5 6 3 8 5 100 8 Output 22 Input 2 100 1 1 1 100 Output 3 ### Response ```cpp #include<bits/stdc++.h> using namespace std; int main (){ int x,n,a[100005],b[100005]; long long cnt=0; cin>>n; for(int i=1;i<=n+1;i++)cin>>a[i]; for(int i=1;i<=n;i++)cin>>b[i]; for(int i=1;i<=n;i++){ x=a[i]+a[i+1]; if(x<=b[i]){ a[i+1]=0; cnt+=x; } else if(x>b[i]&&b[i]>=a[i]){ a[i+1]-=b[i]-a[i]; cnt+=b[i]; } else{ cnt+=b[i]; } } cout<<cnt<<endl; return 0; } ```
### Prompt Please formulate a cpp solution to the following problem: Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries: * Query number i is given as a pair of integers li, ri (1 ≀ li ≀ ri ≀ n). * The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0. Help Eugeny, answer all his queries. Input The first line contains integers n and m (1 ≀ n, m ≀ 2Β·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 ≀ li ≀ ri ≀ n). Output Print m integers β€” the responses to Eugene's queries in the order they occur in the input. Examples Input 2 3 1 -1 1 1 1 2 2 2 Output 0 1 0 Input 5 5 -1 1 1 1 -1 1 1 2 3 3 5 2 5 1 5 Output 0 1 0 1 0 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int a[200005]; int main() { int n, m, li, ri, i; cin >> n >> m; int sum1 = 0, sum2 = 0; for (i = 0; i < n; i++) { cin >> a[i]; if (a[i] == 1) sum1++; else sum2++; } while (m--) { cin >> li >> ri; int res = ri - li + 1; if (res == 1) cout << "0" << endl; else { if (res % 2) cout << "0" << endl; else { if (res / 2 <= min(sum1, sum2)) cout << "1" << endl; else cout << "0" << endl; } } } return 0; } ```
### Prompt Your task is to create a Cpp solution to the following problem: Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0. Input The first line of the input contains one integer, n (1 ≀ n ≀ 100 000). The next line contains n space separated integers given to Wet Shark. Each of these integers is in range from 1 to 109, inclusive. Output Print the maximum possible even sum that can be obtained if we use some of the given integers. Examples Input 3 1 2 3 Output 6 Input 5 999999999 999999999 999999999 999999999 999999999 Output 3999999996 Note In the first sample, we can simply take all three integers for a total sum of 6. In the second sample Wet Shark should take any four out of five integers 999 999 999. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n, min_n = 1000000001, curr; long long sum = 0; cin >> n; for (int i = 0; i < n; i++) { cin >> curr; sum += curr; if ((curr % 2 == 1) && (curr < min_n)) { min_n = curr; } } if (sum % 2 == 0) { cout << sum; } else { if (min_n < 1000000001) { cout << sum - min_n; } else { cout << 0; } } return 0; } ```
### Prompt Create a solution in CPP for the following problem: In the last war of PMP, he defeated all his opponents and advanced to the final round. But after the end of semi-final round evil attacked him from behind and killed him! God bless him. Before his death, PMP signed a contract with the bus rapid transit (BRT) that improves public transportations by optimizing time of travel estimation. You should help PMP finish his last contract. Each BRT line is straight line that passes n intersecting on its ways. At each intersection there is traffic light that periodically cycles between green and red. It starts illuminating green at time zero. During the green phase which lasts for g seconds, traffic is allowed to proceed. After the green phase the light changes to red and remains in this color for r seconds. During the red phase traffic is prohibited from proceeding. If a vehicle reaches the intersection exactly at a time when the light changes to red, it should stop, but the vehicle is clear to proceed if the light has just changed to green. <image> All traffic lights have the same timing and are synchronized. In other words the period of red (and green) phase is the same for all of traffic lights and they all start illuminating green at time zero. The BRT Company has calculated the time that a bus requires to pass each road segment. A road segment is the distance between two consecutive traffic lights or between a traffic light and source (or destination) station. More precisely BRT specialists provide n + 1 positive integers li, the time in seconds that a bus needs to traverse i-th road segment in the path from source to destination. The l1 value denotes the time that a bus needs to pass the distance between source and the first intersection. The ln + 1 value denotes the time between the last intersection and destination. In one day q buses leave the source station. The i-th bus starts from source at time ti (in seconds). Decision makers of BRT Company want to know what time a bus gets to destination? The bus is considered as point. A bus will always move if it can. The buses do not interfere with each other. Input The first line of input contains three space-separated positive integers n, g, r (1 ≀ n ≀ 105, 2 ≀ g + r ≀ 109) β€” the number of intersections, duration of green phase and duration of red phase. Next line contains n + 1 integers li (1 ≀ li ≀ 109) β€” the time to pass the i-th road segment in the path from source to destination. Next line contains a single integer q (1 ≀ q ≀ 105) β€” the number of buses in a day. The i-th of next q lines contains a single integer ti (1 ≀ ti ≀ 109) β€” the time when i-th bus leaves the source station. Output In the i-th line of output you should print a single integer β€” the time that i-th bus gets to destination. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier. Examples Input 1 3 2 5 2 5 1 2 3 4 5 Output 8 9 12 12 12 Input 5 3 7 10 1 1 8 900000005 1000000000 3 1 10 1000000000 Output 1900000040 1900000040 2900000030 Note In the first sample, buses #1, #2 and #5 will reach the destination without waiting behind the red light. But buses #3 and #4 should wait. In the second sample, first bus should wait at third, fourth and fifth intersections. Second and third buses should wait only at the fifth intersection. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 100050, maxm = 100050; int n, m; long long gt, rt, T, len[maxn], dep[maxn], stop[maxn + maxm], arrive[maxn]; set<pair<long long, int> > st; void updateStop(long long ll, long long rr, int sp) { pair<long long, int> low = make_pair(ll, -1); set<pair<long long, int> >::iterator dL = st.lower_bound(low), dR = dL; while (dR != st.end() && dR->first <= rr) { stop[dR->second] = sp; dR++; } st.erase(dL, dR); } int main() { cin >> n >> gt >> rt; T = gt + rt; for (int i = 1; i <= n + 1; i++) { cin >> len[i]; len[i] += len[i - 1]; } cin >> m; for (int i = 1; i <= m; i++) { cin >> dep[i]; st.insert(make_pair(dep[i] % T, n + 1 + i)); } for (int i = 1; i <= n + m + 1; i++) stop[i] = n + 1; for (int i = 1, sum = 0; i <= n; i++) { long long A = len[i] % T, B = gt; long long ll = (B - A + T) % T, rr = T - A - 1; updateStop(ll, rr < ll ? T - 1 : rr, i); if (rr < ll) updateStop(0, rr, i); long long ins = (T - len[i] % T) % T; st.insert(make_pair(ins, i)); } arrive[n + 1] = 0; for (int i = n; i >= 1; i--) { long long firstStop = len[stop[i]] - len[i]; long long wait = stop[i] == n + 1 ? 0 : (T - firstStop % T); arrive[i] = firstStop + wait + arrive[stop[i]]; } for (int i = 1; i <= m; i++) { long long firstStop = dep[i] + len[stop[n + 1 + i]]; long long wait = stop[n + 1 + i] == n + 1 ? 0 : (T - firstStop % T); long long res = firstStop + wait + arrive[stop[n + 1 + i]]; cout << res << endl; } return 0; } ```
### Prompt Please create a solution in CPP to the following problem: You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1. The decoding of the lever description is given below. * If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar. * If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar. * If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar. Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance. Input The first line contains the lever description as a non-empty string s (3 ≀ |s| ≀ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar. To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs. Output Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance. Examples Input =^== Output balance Input 9===^==1 Output left Input 2==^7== Output right Input 41^52== Output balance Note As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever. The pictures to the examples: <image> <image> <image> <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; inline int toInt(string s) { int v; istringstream sin(s); sin >> v; return v; } template <class T> inline string toString(T x) { ostringstream sout; sout << x; return sout.str(); } char str[1111111]; int main() { scanf("%s", str); char *c = strchr(str, '^'); char *d; d = c; long long w1 = 0, w2 = 0; int i = 0; while (1) { if ('0' <= (*d) && (*d) <= '9') w1 += ((*d) - '0') * i; i++; if (d == str) break; d--; } d = c; i = 0; while (1) { if ('0' <= (*d) && (*d) <= '9') w2 += ((*d) - '0') * i; i++; d++; if ((*d) == '\0') break; } if (w1 == w2) cout << "balance" << endl; else if (w1 > w2) cout << "left" << endl; else cout << "right" << endl; return 0; } ```
### Prompt In CPP, your task is to solve the following problem: Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw. The first player wrote number a, the second player wrote number b. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins? Input The single line contains two integers a and b (1 ≀ a, b ≀ 6) β€” the numbers written on the paper by the first and second player, correspondingly. Output Print three integers: the number of ways to throw the dice at which the first player wins, the game ends with a draw or the second player wins, correspondingly. Examples Input 2 5 Output 3 0 3 Input 2 4 Output 2 1 3 Note The dice is a standard cube-shaped six-sided object with each side containing a number from 1 to 6, and where all numbers on all sides are distinct. You can assume that number a is closer to number x than number b, if |a - x| < |b - x|. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int abs(int n) { if (n < 0) return -1 * n; else return n; } int main() { int a, b, i, a1 = 0, b1 = 0, d = 0; scanf("%d %d", &a, &b); for (i = 1; i <= 6; ++i) { if (abs(i - a) < abs(i - b)) a1++; if (abs(i - a) == abs(i - b)) d++; if (abs(i - a) > abs(i - b)) b1++; } printf("%d %d %d", a1, d, b1); return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: Given are an integer X and an integer sequence of length N: p_1, \ldots, p_N. Among the integers not contained in the sequence p_1, \ldots, p_N (not necessarily positive), find the integer nearest to X, that is, find the integer whose absolute difference with X is the minimum. If there are multiple such integers, report the smallest such integer. Constraints * 1 \leq X \leq 100 * 0 \leq N \leq 100 * 1 \leq p_i \leq 100 * p_1, \ldots, p_N are all distinct. * All values in input are integers. Input Input is given from Standard Input in the following format: X N p_1 ... p_N Output Print the answer. Examples Input 6 5 4 7 10 6 5 Output 8 Input 10 5 4 7 10 6 5 Output 9 Input 100 0 Output 100 ### Response ```cpp #include<iostream> #include<set> using namespace std; int X,N,P; int main() { cin>>X>>N; set<int>S; for(int i=0;i<N;i++) { cin>>P; S.insert(P); } for(int k=0;;k++) { if(S.find(X-k)==S.end()) { cout<<X-k<<endl; return 0; } else if(S.find(X+k)==S.end()) { cout<<X+k<<endl; return 0; } } } ```
### Prompt Your challenge is to write a Cpp solution to the following problem: There are N integers, A_1, A_2, ..., A_N, written on a blackboard. We will repeat the following operation N-1 times so that we have only one integer on the blackboard. * Choose two integers x and y on the blackboard and erase these two integers. Then, write a new integer x-y. Find the maximum possible value of the final integer on the blackboard and a sequence of operations that maximizes the final integer. Constraints * 2 \leq N \leq 10^5 * -10^4 \leq A_i \leq 10^4 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 A_2 ... A_N Output Print the maximum possible value M of the final integer on the blackboard, and a sequence of operations x_i, y_i that maximizes the final integer, in the format below. Here x_i and y_i represent the integers x and y chosen in the i-th operation, respectively. If there are multiple sequences of operations that maximize the final integer, any of them will be accepted. M x_1 y_1 : x_{N-1} y_{N-1} Output Print the maximum possible value M of the final integer on the blackboard, and a sequence of operations x_i, y_i that maximizes the final integer, in the format below. Here x_i and y_i represent the integers x and y chosen in the i-th operation, respectively. If there are multiple sequences of operations that maximize the final integer, any of them will be accepted. M x_1 y_1 : x_{N-1} y_{N-1} Examples Input 3 1 -1 2 Output 4 -1 1 2 -2 Input 3 1 1 1 Output 1 1 1 1 0 ### Response ```cpp #include <bits/stdc++.h> #define FOR(i, a, b) for (int i=(a); i<(b); i++) #define PPC(x) __builtin_popcount((x)) #define ALL(x) (x).begin(), (x).end() #define pb push_back using namespace std; const int maxN = 100042; int T[maxN]; vector <pair <int, int> > res; int main() { int n; scanf ("%d", &n); FOR(i, 0, n) scanf ("%d", T+i); sort(T, T+n); int i; for (i=1; T[i]<0; i++) res.pb({T[n-1], T[i]}), T[n-1] -= T[i]; for (; i<n-1; i++) res.pb({T[0], T[i]}), T[0] -= T[i]; res.pb({T[n-1], T[0]}); T[n-1] -= T[0]; printf("%d\n", T[n-1]); for (auto p : res) printf("%d %d\n", p.first, p.second); return 0; } ```
### Prompt Construct a cpp code solution to the problem outlined: Find the tangent lines between a point $p$ and a circle $c$. Constraints * $-1,000 \leq px, py, cx, cy \leq 1,000$ * $1 \leq r \leq 1,000$ * Distance between $p$ and the center of $c$ is greater than the radius of $c$. Input The input is given in the following format. $px \; py$ $cx \; cy \; r$ $px$ and $py$ represents the coordinate of the point $p$. $cx$, $cy$ and $r$ represents the center coordinate and radius of the circle $c$ respectively. All input values are given in integers. Output Print coordinates of the tangent points on the circle $c$ based on the following rules. * Print the coordinate with smaller $x$ first. In case of a tie, print the coordinate with smaller $y$ first. The output values should be in a decimal fraction with an error less than 0.00001. Examples Input 0 0 2 2 2 Output 0.0000000000 2.0000000000 2.0000000000 0.0000000000 Input -3 0 2 2 2 Output 0.6206896552 3.4482758621 2.0000000000 0.0000000000 ### Response ```cpp #include <cmath> #include <vector> #include <iostream> #include <algorithm> using namespace std; class Point { public: long double px, py; Point() : px(0), py(0) {}; Point(long double px_, long double py_) : px(px_), py(py_) {}; bool operator==(const Point& p) const { return px == p.px && py == p.py; } bool operator!=(const Point& p) const { return px != p.px || py != p.py; } bool operator<(const Point& p) const { return px < p.px ? true : (px == p.px && py < p.py); } bool operator>(const Point& p) const { return px > p.px ? true : (px == p.px && py > p.py); } bool operator<=(const Point& p) const { return !(Point(px, py) > p); } bool operator>=(const Point& p) const { return !(Point(px, py) < p); } Point operator+(const Point& p) const { return Point(px + p.px, py + p.py); } Point operator-(const Point& p) const { return Point(px - p.px, py - p.py); } Point operator/(long double d) const { return Point(px / d, py / d); } friend Point operator*(const Point p, long double d) { return Point(p.px * d, p.py * d); } friend Point operator*(long double d, const Point& p) { return p * d; } Point& operator+=(const Point& p1) { px += p1.px, py += p1.py; return *this; } Point& operator-=(const Point& p1) { px -= p1.px, py -= p1.py; return *this; } Point& operator*=(long double d) { px *= d, py *= d; return *this; } Point& operator/=(long double d) { px /= d, py /= d; return *this; } }; class Circle { public: Point p; long double r; Circle() : p(Point()), r(0.0L) {}; Circle(Point p_) : p(p_), r(0.0L) {}; Circle(Point p_, long double r_) : p(p_), r(r_) {}; Circle(long double x_, long double y_) : p(Point(x_, y_)), r(0.0L) {}; Circle(long double x_, long double y_, long double r_) : p(Point(x_, y_)), r(r_) {}; bool operator==(const Circle& c) const { return p == c.p && r == c.r; } bool operator!=(const Circle& c) const { return !(Circle(p, r) == c); } }; // ------ Functions ------ // long double norm(const Point& a) { return a.px * a.px + a.py * a.py; } long double abs(const Point& a) { return sqrtl(norm(a)); } long double arg(const Point& a) { return atan2l(a.py, a.px); } long double dot(const Point& a, const Point& b) { return a.px * b.px + a.py * b.py; } long double crs(const Point& a, const Point& b) { return a.px * b.py - a.py * b.px; } Point pol(long double r, long double d) { return Point(cosl(d) * r, sinl(d) * r); } long double dst(const Point& a, const Point& b) { return abs(b - a); } vector<Point> crp(Circle c1, Circle c2) { long double d = abs(c1.p - c2.p); long double a = acos((c1.r * c1.r + d * d - c2.r * c2.r) / (2 * c1.r * d)); long double t = arg(c2.p - c1.p); return{ c1.p + pol(c1.r, t + a), c1.p + pol(c1.r, t - a) }; } // ------ Main ------ // Point p, q; Circle c; int main() { cin >> p.px >> p.py >> c.p.px >> c.p.py >> c.r; vector<Point> v = crp(c, Circle((p + c.p) / 2, dst(p, c.p) / 2)); sort(v.begin(), v.end()); for(int i = 0; i < 2; i++) printf("%.9Lf %.9Lf\n", v[i].px, v[i].py); return 0; } ```
### Prompt Please create a solution in Cpp to the following problem: Given are a positive integer N and a sequence of length 2^N consisting of 0s and 1s: A_0,A_1,\ldots,A_{2^N-1}. Determine whether there exists a closed curve C that satisfies the condition below for all 2^N sets S \subseteq \\{0,1,\ldots,N-1 \\}. If the answer is yes, construct one such closed curve. * Let x = \sum_{i \in S} 2^i and B_S be the set of points \\{ (i+0.5,0.5) | i \in S \\}. * If there is a way to continuously move the closed curve C without touching B_S so that every point on the closed curve has a negative y-coordinate, A_x = 1. * If there is no such way, A_x = 0. For instruction on printing a closed curve, see Output below. Constraints * 1 \leq N \leq 8 * A_i = 0,1 \quad (0 \leq i \leq 2^N-1) * A_0 = 1 Input Input is given from Standard Input in the following format: N A_0A_1 \cdots A_{2^N-1} Output If there is no closed curve that satisfies the condition, print `Impossible`. If such a closed curve exists, print `Possible` in the first line. Then, print one such curve in the following format: L x_0 y_0 x_1 y_1 : x_L y_L This represents the closed polyline that passes (x_0,y_0),(x_1,y_1),\ldots,(x_L,y_L) in this order. Here, all of the following must be satisfied: * 0 \leq x_i \leq N, 0 \leq y_i \leq 1, and x_i, y_i are integers. (0 \leq i \leq L) * |x_i-x_{i+1}| + |y_i-y_{i+1}| = 1. (0 \leq i \leq L-1) * (x_0,y_0) = (x_L,y_L). Additionally, the length of the closed curve L must satisfy 0 \leq L \leq 250000. It can be proved that, if there is a closed curve that satisfies the condition in Problem Statement, there is also a closed curve that can be expressed in this format. Examples Input 1 10 Output Possible 4 0 0 0 1 1 1 1 0 0 0 Input 2 1000 Output Possible 6 1 0 2 0 2 1 1 1 0 1 0 0 1 0 Input 2 1001 Output Impossible Input 1 11 Output Possible 0 1 1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> P; #define fr first #define sc second #define chmax(a,b) a=max(a,b) #define chmin(a,b) a=min(a,b) vector<P> ret; void pos(int i){ for(int j=0;j<i;j++){ ret.push_back(P(j+1,0)); } ret.push_back(P(i,1)); ret.push_back(P(i+1,1)); ret.push_back(P(i+1,0)); ret.push_back(P(i,0)); for(int j=i-1;j>=0;j--){ ret.push_back(P(j,0)); } } void neg(int i){ for(int j=0;j<i;j++){ ret.push_back(P(j+1,0)); } ret.push_back(P(i+1,0)); ret.push_back(P(i+1,1)); ret.push_back(P(i,1)); ret.push_back(P(i,0)); for(int j=i-1;j>=0;j--){ ret.push_back(P(j,0)); } } vector<P> f(vector<P> vec,int t){ int cnt[300]={}; for(int i=0;i<vec.size();i++){ cnt[vec[i].sc]++; } int MIN=100; int id=-1; for(int i=0;i<300;i++){ if(cnt[i]==0)continue; if(MIN>cnt[i]){ MIN=cnt[i]; id=i; } } //cerr<<"id="<<id<<endl; vector<P> ret; for(int i=0;i<vec.size();i++){ if(vec[i].sc!=id)ret.push_back(vec[i]); else { if(vec[i].fr==1){ ret.push_back(P(1,id)); ret.push_back(P(1,t)); ret.push_back(P(-1,id)); ret.push_back(P(-1,t)); } else { ret.push_back(P(1,t)); ret.push_back(P(1,id)); ret.push_back(P(-1,t)); ret.push_back(P(-1,id)); } } } return ret; } bool zero(vector<P> vec, int x){ stack<P> st; for(P p: vec){ if((x>>p.sc)&1){ if(st.size()==0){ st.push(p); continue; } P q=st.top(); if(q.sc==p.sc&&p.fr+q.fr==0)st.pop(); else st.push(p); } } return st.size()==0; } int main(){ int n; string s; cin>>n>>s; int a[300]; for(int i=0;i<(1<<n);i++)a[i]=s[i]-'0'; bool used[300]; memset(used,0,sizeof used); int b[300]; for(int i=0;i<300;i++)b[i]=1; for(int x=1;x<(1<<n);x++){ used[x]=true; for(int y=0;y<x;y++){ if((x&y)==y)if(used[y])used[x]=false; } for(int y=0;y<(1<<n);y++){ if((x&y)==x)if(a[y]==1)used[x]=false; } if(used[x]){ for(int y=0;y<(1<<n);y++){ if((x&y)==x)b[y]=0; } } } bool ok=true; for(int i=0;i<(1<<n);i++)ok&=a[i]==b[i]; if(!ok){ puts("Impossible"); return 0; } vector<P> vv; /*for(int x=0;x<(1<<n);x++){ if(!used[x])continue; if(vv.size()==0){ vv.push_back(P(1,x)); } else{ vv=f(vv,x); } }*/ vector<P> vec[300]; ret.push_back(P(0,0)); for(int x=0;x<(1<<n);x++){ if(!used[x])continue; if(zero(vv,x)){ int cnt=0; int c[10]; for(int i=0;i<n;i++){ if((x>>i)&1)c[cnt++]=i; } vec[x].push_back(P(1,c[0])); for(int i=1;i<cnt;i++)vec[x]=f(vec[x],c[i]); vv.insert(vv.end(),vec[x].begin(),vec[x].end()); } } for(P p: vv){ if(p.fr==1)pos(p.sc); else neg(p.sc); } /*vector<P> ret2; for(P p: ret){ if(ret2.size()>=2&&ret2[ret2.size()-2]==p)ret2.pop_back(); else ret2.push_back(p); } ret=ret2;*/ assert(ret.size()<=250000); puts("Possible"); printf("%d\n",(int)(ret.size())-1); for(int i=0;i<ret.size();i++){ printf("%d %d\n",ret[i].fr,ret[i].sc); } } ```
### Prompt In cpp, your task is to solve the following problem: The Little Elephant loves playing with arrays. He has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai. Additionally the Little Elephant has m queries to the array, each query is characterised by a pair of integers lj and rj (1 ≀ lj ≀ rj ≀ n). For each query lj, rj the Little Elephant has to count, how many numbers x exist, such that number x occurs exactly x times among numbers alj, alj + 1, ..., arj. Help the Little Elephant to count the answers to all queries. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the size of array a and the number of queries to it. The next line contains n space-separated positive integers a1, a2, ..., an (1 ≀ ai ≀ 109). Next m lines contain descriptions of queries, one per line. The j-th of these lines contains the description of the j-th query as two space-separated integers lj and rj (1 ≀ lj ≀ rj ≀ n). Output In m lines print m integers β€” the answers to the queries. The j-th line should contain the answer to the j-th query. Examples Input 7 2 3 1 2 2 3 3 7 1 7 3 4 Output 3 1 ### Response ```cpp #include <bits/stdc++.h> #pragma comment(linker, "/STACK:100000000") using namespace std; int b[500][100005], c[500]; int main() { srand(time(0)); int n, m, i, j, k; scanf("%d %d", &n, &m); map<int, vector<int> > a; for (i = 0; i < n; i++) { scanf("%d", &k); if (k <= n) a[k].push_back(i + 1); } vector<int> v; map<int, vector<int> >::iterator it; for (it = a.begin(); it != a.end(); it++) if (it->first > it->second.size()) v.push_back(it->first); for (i = 0; i < v.size(); i++) a.erase(v[i]); k = 0; for (it = a.begin(); it != a.end(); it++) { c[k] = it->first; for (i = 0; i < it->second.size(); i++) b[k][it->second[i]] = 1; for (i = 1; i <= n; i++) b[k][i] += b[k][i - 1]; k++; } while (m--) { scanf("%d %d", &i, &j); int cnt = 0; for (n = 0; n < k; n++) if (c[n] == b[n][j] - b[n][i - 1]) cnt++; printf("%d\n", cnt); } return 0; } ```
### Prompt Your challenge is to write a cpp solution to the following problem: Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from 1 to n from top to bottom and the columns β€” from 1 to m, from left to right. We'll represent the cell on the intersection of the i-th row and j-th column as (i, j). Just as is expected, some cells of the giant candy matrix contain candies. Overall the matrix has p candies: the k-th candy is at cell (xk, yk). The time moved closer to dinner and Inna was already going to eat p of her favourite sweets from the matrix, when suddenly Sereja (for the reason he didn't share with anyone) rotated the matrix x times clockwise by 90 degrees. Then he performed the horizontal rotate of the matrix y times. And then he rotated the matrix z times counterclockwise by 90 degrees. The figure below shows how the rotates of the matrix looks like. <image> Inna got really upset, but Duma suddenly understood two things: the candies didn't get damaged and he remembered which cells contained Inna's favourite sweets before Sereja's strange actions. Help guys to find the new coordinates in the candy matrix after the transformation Sereja made! Input The first line of the input contains fix integers n, m, x, y, z, p (1 ≀ n, m ≀ 109; 0 ≀ x, y, z ≀ 109; 1 ≀ p ≀ 105). Each of the following p lines contains two integers xk, yk (1 ≀ xk ≀ n; 1 ≀ yk ≀ m) β€” the initial coordinates of the k-th candy. Two candies can lie on the same cell. Output For each of the p candies, print on a single line its space-separated new coordinates. Examples Input 3 3 3 1 1 9 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3 Output 1 3 1 2 1 1 2 3 2 2 2 1 3 3 3 2 3 1 Note Just for clarity. Horizontal rotating is like a mirroring of the matrix. For matrix: QWER REWQ ASDF -> FDSA ZXCV VCXZ ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, m, p; int x[111111], y[111111]; int main() { int d1, d2, d3; cin >> n >> m >> d1 >> d2 >> d3 >> p; for (int i = 1; i <= p; ++i) cin >> x[i] >> y[i]; for (int _i = 1; _i <= d1 % 4; ++_i) { for (int i = 1; i <= p; ++i) { int ny, nx; ny = n - x[i] + 1; nx = y[i]; x[i] = nx; y[i] = ny; } swap(n, m); } if (d2 & 1) for (int i = 1; i <= p; ++i) { y[i] = m - y[i] + 1; } for (int _i = 1; _i <= d3 % 4; ++_i) { for (int i = 1; i <= p; ++i) { int ny, nx; ny = x[i]; nx = m - y[i] + 1; x[i] = nx; y[i] = ny; } swap(n, m); } for (int i = 1; i <= p; ++i) { cout << x[i] << ' ' << y[i] << endl; } return 0; } ```
### Prompt Please formulate a CPP solution to the following problem: Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: * There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. * There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. * Masculine adjectives end with -lios, and feminine adjectives end with -liala. * Masculine nouns end with -etr, and feminime nouns end with -etra. * Masculine verbs end with -initis, and feminime verbs end with -inites. * Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. * It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language. * There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. * A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: * Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. * All words in the statement should have the same gender. After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language. Input The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language. Output If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes). Examples Input petr Output YES Input etis atis animatis etis atis amatis Output NO Input nataliala kataliala vetra feinites Output YES ### Response ```cpp #include <bits/stdc++.h> using namespace std; int mx[4] = {-1, 0, 1, 0}; int my[4] = {0, 1, 0, -1}; inline void OPEN(string s) { freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } int status; bool gender; char word[100001], line[100001]; void cekword(const string& word, bool& gender, int& type) { if (word.find("lios", (int)(word).size() - 4) != string::npos) { gender = false; type = 0; } else if (word.find("liala", (int)(word).size() - 5) != string::npos) { gender = true; type = 0; } else if (word.find("etr", (int)(word).size() - 3) != string::npos) { gender = false; type = 1; } else if (word.find("etra", (int)(word).size() - 4) != string::npos) { gender = true; type = 1; } else if (word.find("initis", (int)(word).size() - 6) != string::npos) { gender = false; type = 2; } else if (word.find("inites", (int)(word).size() - 6) != string::npos) { gender = true; type = 2; } else { type = -1; } } int main() { scanf("%[^\n]", line); int pos = 0; status = 0; int n = 0; int type; bool gender, inv, allgender, hasnoun = false; string kata; int len = strlen(line); inv = false; while (!inv && (pos < len)) { n++; sscanf(line + pos, "%s", word); kata = word; pos += kata.size() + 1; cekword(kata, gender, type); if (type == -1) { inv = true; break; } if (n != 1 && gender != allgender) { inv = true; break; } else { allgender = gender; } if (type == 1) { if (hasnoun) { inv = true; break; } hasnoun = true; } if (status == type) { continue; } if (n == 1 || status <= type) { status = type; } else { inv = true; break; } } if (inv || (n > 1 && !hasnoun) || (len == 0)) { cout << "NO" << endl; } else { cout << "YES" << endl; } return 0; } ```
### Prompt Generate a CPP solution to the following problem: Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key. Example Input 10 insert 30 insert 88 insert 12 insert 1 insert 20 find 12 insert 17 insert 25 find 16 print Output yes no 1 12 17 20 25 30 88 30 12 1 20 17 25 88 ### Response ```cpp #include <iostream> using namespace std; struct Node{ int key; Node *right, *left, *parent; }; Node *root, *NIL; void insert(int k){ Node *y=NIL; Node *x=root; Node *z=new Node; z->key=k; z->left=NIL; z->right=NIL; while(x!=NIL){ y=x; if(z->key < x->key) x=x->left; else x=x->right; } z->parent=y; if(y==NIL) root=z; else{ if(z->key<y->key) y->left=z; else y->right=z; } } Node *find(Node *u, int k){ while(u!=NIL && k!=u->key){ if(k<u->key) u=u->left; else u=u->right; } return u; } void inorder(Node *u){ if(u==NIL) return; inorder(u->left); cout << " " << u->key; inorder(u->right); } void preorder(Node *u){ if(u==NIL) return; cout << " " << u->key; preorder(u->left); preorder(u->right); } int main(){ int n, x; string com; cin >> n; for(int i=0; i<n; i++){ cin >> com; if(com=="insert"){ cin >> x; insert(x); } else if(com=="print"){ inorder(root); cout << endl; preorder(root); cout << endl; } else if(com[0]=='f'){ cin >> x; Node *t=find(root, x); if(t!=NIL) cout << "yes" << endl; else cout << "no" << endl; } } return 0; } ```
### Prompt In cpp, your task is to solve the following problem: On an IT lesson Valera studied data compression. The teacher told about a new method, which we shall now describe to you. Let {a1, a2, ..., an} be the given sequence of lines needed to be compressed. Here and below we shall assume that all lines are of the same length and consist only of the digits 0 and 1. Let's define the compression function: * f(empty sequence) = empty string * f(s) = s. * f(s1, s2) = the smallest in length string, which has one of the prefixes equal to s1 and one of the suffixes equal to s2. For example, f(001, 011) = 0011, f(111, 011) = 111011. * f(a1, a2, ..., an) = f(f(a1, a2, an - 1), an). For example, f(000, 000, 111) = f(f(000, 000), 111) = f(000, 111) = 000111. Valera faces a real challenge: he should divide the given sequence {a1, a2, ..., an} into two subsequences {b1, b2, ..., bk} and {c1, c2, ..., cm}, m + k = n, so that the value of S = |f(b1, b2, ..., bk)| + |f(c1, c2, ..., cm)| took the minimum possible value. Here |p| denotes the length of the string p. Note that it is not allowed to change the relative order of lines in the subsequences. It is allowed to make one of the subsequences empty. Each string from the initial sequence should belong to exactly one subsequence. Elements of subsequences b and c don't have to be consecutive in the original sequence a, i. e. elements of b and c can alternate in a (see samples 2 and 3). Help Valera to find the minimum possible value of S. Input The first line of input data contains an integer n β€” the number of strings (1 ≀ n ≀ 2Β·105). Then on n lines follow elements of the sequence β€” strings whose lengths are from 1 to 20 characters, consisting only of digits 0 and 1. The i + 1-th input line contains the i-th element of the sequence. Elements of the sequence are separated only by a newline. It is guaranteed that all lines have the same length. Output Print a single number β€” the minimum possible value of S. Examples Input 3 01 10 01 Output 4 Input 4 000 111 110 001 Output 8 Input 5 10101 01010 11111 01000 10010 Output 17 Note Detailed answers to the tests: * The best option is to make one of the subsequences empty, and the second one equal to the whole given sequence. |f(01, 10, 01)| = |f(f(01, 10), 01)| = |f(010, 01)| = |0101| = 4. * The best option is: b = {000, 001}, c = {111, 110}. S = |f(000, 001)| + |f(111, 110)| = |0001| + |1110| = 8. * The best option is: b = {10101, 01010, 01000}, c = {11111, 10010}. S = |10101000| + |111110010| = 17. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long linf = 1e18 + 5; const int mod = (int)1e9 + 7; const int logN = 18; const int inf = 2e9; const int N = 2e6 + 5; int all, cost[N], n, m, x, y, ters[N], duz[N], pre[N], t, t2, ans = inf; char str[22]; int dp[21][1 << 21]; int calc(int x, int y) { if (y == 1) return 0; int last = ters[x]; for (int j = m; j >= 0; j--) { int t = ters[y] >> (m - j); int t2 = ((1 << j) - 1) & last; if (t == t2) return j; } } int main() { scanf("%d", &n); memset(dp, 11, sizeof dp); dp[0][0] = 0; for (int i = 1; i <= n; i++) { scanf("%s", str); int t = 0; if (i == 1) m = strlen(str); for (int j = 1; j <= m; j++) { if (str[m - j] == '1') t += (1 << j - 1); } ters[i] = t; all += m - calc(i - 1, i); } for (int i = 2; i <= n; i++) { int ans = inf, cc = calc(i - 1, i); for (int j = 0; j <= m; j++) ans = min(ans, dp[j][ters[i] >> (m - j)] + cc - j); for (int j = 0; j <= m; j++) dp[j][ters[i - 1] & (1 << j) - 1] = min(dp[j][ters[i - 1] & (1 << j) - 1], ans); } int ans = inf; for (int i = 0; i <= m; i++) for (int j = 0; j <= (1 << i) - 1; j++) ans = min(ans, dp[i][j]); cout << all + ans << '\n'; return 0; } ```
### Prompt Your challenge is to write a Cpp solution to the following problem: Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you." <image> The problem is: You are given a lucky number n. Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. If we sort all lucky numbers in increasing order, what's the 1-based index of n? Tavas is not as smart as SaDDas, so he asked you to do him a favor and solve this problem so he can have his headphones back. Input The first and only line of input contains a lucky number n (1 ≀ n ≀ 109). Output Print the index of n among all lucky numbers. Examples Input 4 Output 1 Input 7 Output 2 Input 77 Output 6 ### Response ```cpp #include <bits/stdc++.h> using namespace std; char c1, c2; int mid1, mid2, low1, low2, high1, high2; int sz; int reverse(int n) { int temp = 0; while (n) { temp += n % 10; temp *= 10; n /= 10; } return temp / 10; } int main() { int n; cin >> n; n = reverse(n); int ans = 0; while (n) { ans = ans << 1; if (n % 10 == 7) ans += 2; else { ans += 1; } n /= 10; } cout << ans; return 0; } ```
### Prompt In cpp, your task is to solve the following problem: Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise. You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i > 1 the respective term satisfies the condition bi = bi - 1Β·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a1, a2, ..., am, and an integer l. Masha writes all progression terms one by one onto the board (including repetitive) while condition |bi| ≀ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term. But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers. Input The first line of input contains four integers b1, q, l, m (-109 ≀ b1, q ≀ 109, 1 ≀ l ≀ 109, 1 ≀ m ≀ 105) β€” the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively. The second line contains m distinct integers a1, a2, ..., am (-109 ≀ ai ≀ 109) β€” numbers that will never be written on the board. Output Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise. Examples Input 3 2 30 4 6 14 25 48 Output 3 Input 123 1 2143435 4 123 11 -5453 141245 Output 0 Input 123 1 2143435 4 54343 -13 6 124 Output inf Note In the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value. In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer. In the third case, Masha will write infinitely integers 123. ### Response ```cpp #include <bits/stdc++.h> using namespace std; set<long long> a; set<long long> b; int main() { long long b1; int q, l, m; scanf("%lld%d%d%d", &b1, &q, &l, &m); while (m--) { int k; scanf("%d", &k); a.insert(k); } int num = 0; bool u = false; while (abs(b1) <= l) { if (b.find(b1) != b.end()) { u = true; break; } b.insert(b1); if (a.find(b1) == a.end()) num++; b1 *= q; } if (u) { if (b1 == 0) { if (a.find(0) != a.end()) printf("%d", num); else printf("inf"); } else if (q == 1) { if (a.find(b1) != a.end()) printf("0"); else printf("inf"); } else if (q == 0) { if (a.find(0) == a.end()) printf("inf"); else printf("%d", num); } else if (q == -1) { if (a.find(b1) != a.end() && a.find(-b1) != a.end()) printf("0"); else printf("inf"); } } else printf("%d", num); return 0; } ```
### Prompt Your task is to create a Cpp solution to the following problem: You are given the following points with integer coordinates on the plane: M0, A0, A1, ..., An - 1, where n is odd number. Now we define the following infinite sequence of points Mi: Mi is symmetric to Mi - 1 according <image> (for every natural number i). Here point B is symmetric to A according M, if M is the center of the line segment AB. Given index j find the point Mj. Input On the first line you will be given an integer n (1 ≀ n ≀ 105), which will be odd, and j (1 ≀ j ≀ 1018), where j is the index of the desired point. The next line contains two space separated integers, the coordinates of M0. After that n lines follow, where the i-th line contain the space separated integer coordinates of the point Ai - 1. The absolute values of all input coordinates will not be greater then 1000. Output On a single line output the coordinates of Mj, space separated. Examples Input 3 4 0 0 1 1 2 3 -5 3 Output 14 0 Input 3 1 5 5 1000 1000 -1000 1000 3 100 Output 1995 1995 ### Response ```cpp #include <bits/stdc++.h> using namespace std; using ll = long long; struct point { ll x, y; point(ll _x = 0, ll _y = 0) { x = _x, y = _y; } point operator+(const point &p) { return {x + p.x, y + p.y}; } point operator-(const point &p) { return {x - p.x, y - p.y}; } point operator*(long long m) { return {x * m, y * m}; } void scan() { scanf("%lld%lld", &x, &y); } }; int main() { ll n, j; point m, ans, pt; scanf("%lld%lld", &n, &j); j--; j %= 2 * n; m.scan(); auto coef = [&](ll i) { if (j < i || j >= i + n) return 0; if (j % 2 == i % 2) return 1; return -1; }; for (ll i = 0; i < n; i++) { pt.scan(); ans = ans + (pt - m) * coef(i); } ans = (ans * 2) + m; printf("%lld %lld\n", ans.x, ans.y); return 0; } ```
### Prompt Your challenge is to write a cpp solution to the following problem: Polycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him β€” his keyboard will consist of only one row, where all 26 lowercase Latin letters will be arranged in some order. Polycarp uses the same password s on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in s, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in s, so, for example, the password cannot be password (two characters s are adjacent). Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible? Input The first line contains one integer T (1 ≀ T ≀ 1000) β€” the number of test cases. Then T lines follow, each containing one string s (1 ≀ |s| ≀ 200) representing the test case. s consists of lowercase Latin letters only. There are no two adjacent equal characters in s. Output For each test case, do the following: * if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); * otherwise, print YES (in upper case), and then a string consisting of 26 lowercase Latin letters β€” the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. Example Input 5 ababa codedoca abcda zxzytyz abcdefghijklmnopqrstuvwxyza Output YES bacdefghijklmnopqrstuvwxyz YES edocabfghijklmnpqrstuvwxyz NO YES xzytabcdefghijklmnopqrsuvw NO ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct node { int deg; int neighbor[3]; node() { deg = 0; neighbor[0] = neighbor[1] = -1; } }; bool mark[26] = {false}; bool flag = true; int main() { int t; cin >> t; while (t--) { memset(mark, false, sizeof(mark)); node key[26]; flag = true; string s; cin >> s; if (s.length() == 1) { cout << "YES" << endl; for (int i = 0; i < 26; printf("%c", 'a' + i++)) ; cout << endl; continue; } for (int i = 0; i < s.length() - 1; i++) { int p = s[i] - 'a', q = s[i + 1] - 'a'; bool d1 = false, d2 = false; if (key[p].neighbor[0] != q && key[p].neighbor[1] != q) { if (key[p].deg >= 2) { flag = false; break; } else { key[p].neighbor[key[p].deg++] = q; } } if (key[q].neighbor[0] != p && key[q].neighbor[1] != p) { if (key[q].deg >= 2) { flag = false; break; } else { key[q].neighbor[key[q].deg++] = p; } } } int in = -1; for (int i = 0; i < 26; i++) if (key[i].deg == 1) { in = i; break; } if (!flag || in == -1) printf("NO\n"); else { printf("YES\n%c", 'a' + in); mark[in] = true; int cur = key[in].neighbor[0]; while (!mark[cur]) { mark[cur] = true; printf("%c", 'a' + cur); if (key[cur].deg == 1) break; if (!mark[key[cur].neighbor[0]]) cur = key[cur].neighbor[0]; else if (!mark[key[cur].neighbor[1]]) cur = key[cur].neighbor[1]; } for (int i = 0; i < 26; i++) if (!mark[i]) printf("%c", 'a' + i); cout << endl; } } return 0; } ```
### Prompt Please provide a cpp coded solution to the problem described below: There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros. Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs. Look at the input part of the statement, s is given in a special form. Input In the first line you're given a string a (1 ≀ |a| ≀ 105), containing digits only. In the second line you're given an integer k (1 ≀ k ≀ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|Β·k. Output Print a single integer β€” the required number of ways modulo 1000000007 (109 + 7). Examples Input 1256 1 Output 4 Input 13990 2 Output 528 Input 555 2 Output 63 Note In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125. In the second case, remember to concatenate the copies of a. The actual plate is 1399013990. In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits. ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename T> inline int popcount(T t) { if (std::numeric_limits<T>::digits <= std::numeric_limits<unsigned int>::digits) { return __builtin_popcount(t); } else { return __builtin_popcountll(t); } } const long double EPS = 1e-8; const long double PI = acosl(0.0) * 2; const long long MOD = 1000000000 + 7; vector<vector<long long> > mul(const vector<vector<long long> >& a, const vector<vector<long long> >& b) { vector<vector<long long> > c(a.size(), vector<long long>(a.size())); for (int i = 0; i < int((a).size()); ++i) { for (int j = 0; j < int((a).size()); ++j) { for (int k = 0; k < int((a).size()); ++k) { c[i][j] += a[i][k] * b[k][j]; if (c[i][j] >= MOD) c[i][j] %= MOD; } } } return c; } vector<vector<long long> > pow(vector<vector<long long> > a, int k) { vector<vector<long long> > res(a.size(), vector<long long>(a.size())); for (int i = 0; i < int((res).size()); ++i) res[i][i] = 1; while (k > 0) { if (k & 1) { res = mul(res, a); } a = mul(a, a); k >>= 1; } return res; } void solve() { string a; getline(cin, a); int k; cin >> k; vector<vector<vector<long long> > > A(10); for (int c = 0; c < int(10); ++c) { A[c] = vector<vector<long long> >(5, vector<long long>(5)); for (int i = 0; i < int(5); ++i) { for (int j = 0; j < int(5); ++j) { if (c % 5 == i) { A[c][i][j] += 1; } } A[c][i][i] += 1; } } vector<vector<long long> > mt(5, vector<long long>(5)); for (int i = 0; i < int(5); ++i) mt[i][i] = 1; for (char c : a) { mt = mul(A[c - '0'], mt); } mt = pow(mt, k); cout << (mt[0][0] - 1) % MOD << endl; } int main() { ios_base::sync_with_stdio(false); solve(); return 0; } ```
### Prompt Generate a Cpp solution to the following problem: For a vector \vec{v} = (x, y), define |v| = √{x^2 + y^2}. Allen had a bit too much to drink at the bar, which is at the origin. There are n vectors \vec{v_1}, \vec{v_2}, β‹…β‹…β‹…, \vec{v_n}. Allen will make n moves. As Allen's sense of direction is impaired, during the i-th move he will either move in the direction \vec{v_i} or -\vec{v_i}. In other words, if his position is currently p = (x, y), he will either move to p + \vec{v_i} or p - \vec{v_i}. Allen doesn't want to wander too far from home (which happens to also be the bar). You need to help him figure out a sequence of moves (a sequence of signs for the vectors) such that his final position p satisfies |p| ≀ 1.5 β‹… 10^6 so that he can stay safe. Input The first line contains a single integer n (1 ≀ n ≀ 10^5) β€” the number of moves. Each of the following lines contains two space-separated integers x_i and y_i, meaning that \vec{v_i} = (x_i, y_i). We have that |v_i| ≀ 10^6 for all i. Output Output a single line containing n integers c_1, c_2, β‹…β‹…β‹…, c_n, each of which is either 1 or -1. Your solution is correct if the value of p = βˆ‘_{i = 1}^n c_i \vec{v_i}, satisfies |p| ≀ 1.5 β‹… 10^6. It can be shown that a solution always exists under the given constraints. Examples Input 3 999999 0 0 999999 999999 0 Output 1 1 -1 Input 1 -824590 246031 Output 1 Input 8 -67761 603277 640586 -396671 46147 -122580 569609 -2112 400 914208 131792 309779 -850150 -486293 5272 721899 Output 1 1 1 1 1 1 1 -1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 5; int n, ans[maxn]; struct Vector { int id, x, y; } a[maxn]; int main() { scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d %d", &a[i].x, &a[i].y); a[i].id = i; } while (true) { long long X = 0, Y = 0; for (int i = 0; i < n; i++) { if ((X + a[i].x) * (X + a[i].x) + (Y + a[i].y) * (Y + a[i].y) <= (X - a[i].x) * (X - a[i].x) + (Y - a[i].y) * (Y - a[i].y)) { ans[a[i].id] = 1; X += a[i].x; Y += a[i].y; } else { ans[a[i].id] = -1; X -= a[i].x; Y -= a[i].y; } } if (X * X + Y * Y <= 1.5e6 * 1.5e6) break; random_shuffle(a, a + n); } for (int i = 0; i < n; i++) printf("%d ", ans[i]); return 0; } ```
### Prompt Construct a CPP code solution to the problem outlined: You are playing a strange game with Li Chen. You have a tree with n nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you independently labeled the vertices from 1 to n. Neither of you know the other's labelling of the tree. You and Li Chen each chose a subtree (i.e., a connected subgraph) in that tree. Your subtree consists of the vertices labeled x_1, x_2, …, x_{k_1} in your labeling, Li Chen's subtree consists of the vertices labeled y_1, y_2, …, y_{k_2} in his labeling. The values of x_1, x_2, …, x_{k_1} and y_1, y_2, …, y_{k_2} are known to both of you. <image> The picture shows two labelings of a possible tree: yours on the left and Li Chen's on the right. The selected trees are highlighted. There are two common nodes. You want to determine whether your subtrees have at least one common vertex. Luckily, your friend Andrew knows both labelings of the tree. You can ask Andrew at most 5 questions, each of which is in one of the following two forms: * A x: Andrew will look at vertex x in your labeling and tell you the number of this vertex in Li Chen's labeling. * B y: Andrew will look at vertex y in Li Chen's labeling and tell you the number of this vertex in your labeling. Determine whether the two subtrees have at least one common vertex after asking some questions. If there is at least one common vertex, determine one of your labels for any of the common vertices. Interaction Each test consists of several test cases. The first line of input contains a single integer t (1 ≀ t ≀ 100) β€” the number of test cases. For each testcase, your program should interact in the following format. The first line contains a single integer n (1 ≀ n ≀ 1 000) β€” the number of nodes in the tree. Each of the next n-1 lines contains two integers a_i and b_i (1≀ a_i, b_i≀ n) β€” the edges of the tree, indicating an edge between node a_i and b_i according to your labeling of the nodes. The next line contains a single integer k_1 (1 ≀ k_1 ≀ n) β€” the number of nodes in your subtree. The next line contains k_1 distinct integers x_1,x_2,…,x_{k_1} (1 ≀ x_i ≀ n) β€” the indices of the nodes in your subtree, according to your labeling. It is guaranteed that these vertices form a subtree. The next line contains a single integer k_2 (1 ≀ k_2 ≀ n) β€” the number of nodes in Li Chen's subtree. The next line contains k_2 distinct integers y_1, y_2, …, y_{k_2} (1 ≀ y_i ≀ n) β€” the indices (according to Li Chen's labeling) of the nodes in Li Chen's subtree. It is guaranteed that these vertices form a subtree according to Li Chen's labelling of the tree's nodes. Test cases will be provided one by one, so you must complete interacting with the previous test (i.e. by printing out a common node or -1 if there is not such node) to start receiving the next one. You can ask the Andrew two different types of questions. * You can print "A x" (1 ≀ x ≀ n). Andrew will look at vertex x in your labeling and respond to you with the number of this vertex in Li Chen's labeling. * You can print "B y" (1 ≀ y ≀ n). Andrew will look at vertex y in Li Chen's labeling and respond to you with the number of this vertex in your labeling. You may only ask at most 5 questions per tree. When you are ready to answer, print "C s", where s is your label of a vertex that is common to both subtrees, or -1, if no such vertex exists. Printing the answer does not count as a question. Remember to flush your answer to start receiving the next test case. After printing a question do not forget to print end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. If the judge responds with -1, it means that you asked more queries than allowed, or asked an invalid query. Your program should immediately terminate (for example, by calling exit(0)). You will receive Wrong Answer; it means that you asked more queries than allowed, or asked an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream. Hack Format To hack, use the following format. Note that you can only hack with one test case. The first line should contain a single integer t (t=1). The second line should contain a single integer n (1 ≀ n ≀ 1 000). The third line should contain n integers p_1, p_2, …, p_n (1≀ p_i≀ n) β€” a permutation of 1 to n. This encodes the labels that Li Chen chose for his tree. In particular, Li Chen chose label p_i for the node you labeled i. Each of the next n-1 lines should contain two integers a_i and b_i (1≀ a_i, b_i≀ n). These edges should form a tree. The next line should contain a single integer k_1 (1 ≀ k_1 ≀ n). The next line should contain k_1 distinct integers x_1,x_2,…,x_{k_1} (1 ≀ x_i ≀ n). These vertices should form a subtree. The next line should contain a single integer k_2 (1 ≀ k_2 ≀ n). The next line should contain k_2 distinct integers y_1, y_2, …, y_{k_2} (1 ≀ y_i ≀ n). These vertices should form a subtree in Li Chen's tree according to the permutation above. Examples Input 1 3 1 2 2 3 1 1 1 2 2 1 Output A 1 B 2 C 1 Input 2 6 1 2 1 3 1 4 4 5 4 6 4 1 3 4 5 3 3 5 2 3 6 1 2 1 3 1 4 4 5 4 6 3 1 2 3 3 4 1 6 5 Output B 2 C 1 A 1 C -1 Note For the first sample, Li Chen's hidden permutation is [2, 3, 1], and for the second, his hidden permutation is [5, 3, 2, 4, 1, 6] for both cases. In the first sample, there is a tree with three nodes in a line. On the top, is how you labeled the tree and the subtree you chose, and the bottom is how Li Chen labeled the tree and the subtree he chose: <image> In the first question, you ask Andrew to look at node 1 in your labelling and tell you the label of it in Li Chen's labelling. Andrew responds with 2. At this point, you know that both of your subtrees contain the same node (i.e. node 1 according to your labeling), so you can output "C 1" and finish. However, you can also ask Andrew to look at node 2 in Li Chen's labelling and tell you the label of it in your labelling. Andrew responds with 1 (this step was given with the only reason β€” to show you how to ask questions). For the second sample, there are two test cases. The first looks is the one from the statement: <image> We first ask "B 2", and Andrew will tell us 3. In this case, we know 3 is a common vertex, and moreover, any subtree with size 3 that contains node 3 must contain node 1 as well, so we can output either "C 1" or "C 3" as our answer. In the second case in the second sample, the situation looks as follows: <image> In this case, you know that the only subtree of size 3 that doesn't contain node 1 is subtree 4,5,6. You ask Andrew for the label of node 1 in Li Chen's labelling and Andrew says 5. In this case, you know that Li Chen's subtree doesn't contain node 1, so his subtree must be consist of the nodes 4,5,6 (in your labelling), thus the two subtrees have no common nodes. ### Response ```cpp #include <bits/stdc++.h> using namespace std; vector<vector<int>> childrens(1010); vector<int> green(1010, 0), yellow(1010, 0); int topp; void dfs(int curr, int par) { if (green[curr] == 1) { topp = curr; return; } for (int i : childrens[curr]) { if (i != par) { dfs(i, curr); } } } int main() { int t; cin >> t; for (int p = 0; p < t; p += 1) { for (int i = 0; i <= 1000; i += 1) { childrens[i].clear(); } green.clear(); yellow.clear(); green.resize(1010, 0); yellow.resize(1010, 0); int n, a, b; cin >> n; for (int i = 0; i < n - 1; i += 1) { cin >> a >> b; childrens[a].push_back(b); childrens[b].push_back(a); } int m, k, f; cin >> m; for (int i = 0; i < m; i += 1) { cin >> a; green[a] = 1; } cin >> k; for (int i = 0; i < k; i += 1) { cin >> a; yellow[a] = 1; } cout << "B " << a << endl; cin >> f; dfs(f, -1); cout << "A " << topp << endl; cin >> f; if (yellow[f] == 1) { cout << "C " << topp << endl; } else { cout << "C " << -1 << endl; } } } ```
### Prompt Your challenge is to write a cpp solution to the following problem: In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position i + 1) if the type of this bumper is '>', or one position to the left (to i - 1) if the type of the bumper at position i is '<'. If there is no such position, in other words if i - 1 < 1 or i + 1 > n, the ball falls from the game field. Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. Input The first line of the input contains a single integer n (1 ≀ n ≀ 200 000) β€” the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. Output Print one integer β€” the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. Examples Input 4 &lt;&lt;&gt;&lt; Output 2 Input 5 &gt;&gt;&gt;&gt;&gt; Output 5 Input 4 &gt;&gt;&lt;&lt; Output 0 Note In the first sample, the ball will fall from the field if starts at position 1 or position 2. In the second sample, any starting position will result in the ball falling from the field. ### Response ```cpp #include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1; char ch = getchar(); for (; ch < '0' || ch > '9'; ch = getchar()) if (ch == '-') f = -f; for (; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0'; return x * f; } char s[210005]; int visited[210005]; int n; int main() { scanf("%d\n", &n); scanf("%s", s + 1); int y = 0; for (int i = 1; i <= n; i++) if (s[i] == '<') y++; else break; for (int i = n; i >= 1; i--) if (s[i] == '>') y++; else break; printf("%d\n", y); return 0; } ```
### Prompt Construct a CPP code solution to the problem outlined: You are given a sequence s consisting of n digits from 1 to 9. You have to divide it into at least two segments (segment β€” is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that each element belongs to exactly one segment and if the resulting division will be represented as an integer numbers sequence then each next element of this sequence will be strictly greater than the previous one. More formally: if the resulting division of the sequence is t_1, t_2, ..., t_k, where k is the number of element in a division, then for each i from 1 to k-1 the condition t_{i} < t_{i + 1} (using numerical comparing, it means that the integer representations of strings are compared) should be satisfied. For example, if s=654 then you can divide it into parts [6, 54] and it will be suitable division. But if you will divide it into parts [65, 4] then it will be bad division because 65 > 4. If s=123 then you can divide it into parts [1, 23], [1, 2, 3] but not into parts [12, 3]. Your task is to find any suitable division for each of the q independent queries. Input The first line of the input contains one integer q (1 ≀ q ≀ 300) β€” the number of queries. The first line of the i-th query contains one integer number n_i (2 ≀ n_i ≀ 300) β€” the number of digits in the i-th query. The second line of the i-th query contains one string s_i of length n_i consisting only of digits from 1 to 9. Output If the sequence of digits in the i-th query cannot be divided into at least two parts in a way described in the problem statement, print the single line "NO" for this query. Otherwise in the first line of the answer to this query print "YES", on the second line print k_i β€” the number of parts in your division of the i-th query sequence and in the third line print k_i strings t_{i, 1}, t_{i, 2}, ..., t_{i, k_i} β€” your division. Parts should be printed in order of the initial string digits. It means that if you write the parts one after another without changing their order then you'll get the string s_i. See examples for better understanding. Example Input 4 6 654321 4 1337 2 33 4 2122 Output YES 3 6 54 321 YES 3 1 3 37 NO YES 2 21 22 ### Response ```cpp #include <bits/stdc++.h> using namespace std; signed main() { ios::sync_with_stdio(false); int q; cin >> q; for (int i = 1; i <= q; i++) { int n; string s; cin >> n; cin >> s; if (n > 2) { cout << "YES\n"; cout << 2 << endl; cout << s[0] << " " << s.substr(1) << endl; } else if (s[0] < s[1]) { cout << "YES\n"; cout << 2 << endl; cout << s[0] << " " << s[1] << endl; } else { cout << "NO\n"; } } return 0; } ```
### Prompt Please provide a Cpp coded solution to the problem described below: Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences of days 0, 010, 01010 are zebras, while sequences 1, 0110, 0101 are not. Oleg tells you the story of days he lived in chronological order in form of string consisting of 0 and 1. Now you are interested if it is possible to divide Oleg's life history into several subsequences, each of which is a zebra, and the way it can be done. Each day must belong to exactly one of the subsequences. For each of the subsequences, days forming it must be ordered chronologically. Note that subsequence does not have to be a group of consecutive days. Input In the only line of input data there is a non-empty string s consisting of characters 0 and 1, which describes the history of Oleg's life. Its length (denoted as |s|) does not exceed 200 000 characters. Output If there is a way to divide history into zebra subsequences, in the first line of output you should print an integer k (1 ≀ k ≀ |s|), the resulting number of subsequences. In the i-th of following k lines first print the integer li (1 ≀ li ≀ |s|), which is the length of the i-th subsequence, and then li indices of days forming the subsequence. Indices must follow in ascending order. Days are numbered starting from 1. Each index from 1 to n must belong to exactly one subsequence. If there is no way to divide day history into zebra subsequences, print -1. Subsequences may be printed in any order. If there are several solutions, you may print any of them. You do not have to minimize nor maximize the value of k. Examples Input 0010100 Output 3 3 1 3 4 3 2 5 6 1 7 Input 111 Output -1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { string s; cin >> s; set<long long> zeros, ones; set<long long>::iterator it; for (long long int i = 0; i < int(s.size()); i++) { if ((s[i] - '0') == 0) { zeros.insert(i + 1); } else { ones.insert(i + 1); } } long long cur = 0, search = 0; vector<long long> tem; vector<vector<long long> > ans; bool f = true; while (1) { if (int(zeros.size()) == 0 && int(ones.size()) == 0) { break; } if (search == 0) { it = zeros.upper_bound(cur); if (it != zeros.end()) { tem.push_back(*it); cur = *it; zeros.erase(it); search = 1; } else { f = false; break; } } else if (search == 1) { it = ones.upper_bound(cur); if (it != ones.end()) { if (zeros.upper_bound(*it) != zeros.end()) { tem.push_back(*it); cur = *it; ones.erase(it); search = 0; } else { f = false; break; } } else { ans.push_back(tem); tem.clear(); search = 0; cur = 0; } } } if (!f) { cout << -1 << '\n'; } else { if (int(tem.size()) != 0) ans.push_back(tem); cout << int(ans.size()) << '\n'; for (long long int i = 0; i < int(ans.size()); i++) { cout << int(ans[i].size()) << " "; for (long long int j = 0; j < int(ans[i].size()); j++) { cout << ans[i][j] << " "; } cout << '\n'; } } return 0; } ```
### Prompt Develop a solution in cpp to the problem described below: Vasya has n different points A_1, A_2, … A_n on the plane. No three of them lie on the same line He wants to place them in some order A_{p_1}, A_{p_2}, …, A_{p_n}, where p_1, p_2, …, p_n β€” some permutation of integers from 1 to n. After doing so, he will draw oriented polygonal line on these points, drawing oriented segments from each point to the next in the chosen order. So, for all 1 ≀ i ≀ n-1 he will draw oriented segment from point A_{p_i} to point A_{p_{i+1}}. He wants to make this polygonal line satisfying 2 conditions: * it will be non-self-intersecting, so any 2 segments which are not neighbors don't have common points. * it will be winding. Vasya has a string s, consisting of (n-2) symbols "L" or "R". Let's call an oriented polygonal line winding, if its i-th turn left, if s_i = "L" and right, if s_i = "R". More formally: i-th turn will be in point A_{p_{i+1}}, where oriented segment from point A_{p_i} to point A_{p_{i+1}} changes to oriented segment from point A_{p_{i+1}} to point A_{p_{i+2}}. Let's define vectors \overrightarrow{v_1} = \overrightarrow{A_{p_i} A_{p_{i+1}}} and \overrightarrow{v_2} = \overrightarrow{A_{p_{i+1}} A_{p_{i+2}}}. Then if in order to rotate the vector \overrightarrow{v_1} by the smallest possible angle, so that its direction coincides with the direction of the vector \overrightarrow{v_2} we need to make a turn counterclockwise, then we say that i-th turn is to the left, and otherwise to the right. For better understanding look at this pictures with some examples of turns: <image> There are left turns on this picture <image> There are right turns on this picture You are given coordinates of the points A_1, A_2, … A_n on the plane and string s. Find a permutation p_1, p_2, …, p_n of the integers from 1 to n, such that the polygonal line, drawn by Vasya satisfy two necessary conditions. Input The first line contains one integer n β€” the number of points (3 ≀ n ≀ 2000). Next n lines contains two integers x_i and y_i, divided by space β€” coordinates of the point A_i on the plane (-10^9 ≀ x_i, y_i ≀ 10^9). The last line contains a string s consisting of symbols "L" and "R" with length (n-2). It is guaranteed that all points are different and no three points lie at the same line. Output If the satisfying permutation doesn't exists, print -1. In the other case, print n numbers p_1, p_2, …, p_n β€” the permutation which was found (1 ≀ p_i ≀ n and all p_1, p_2, …, p_n are different). If there exists more than one solution, you can find any. Examples Input 3 1 1 3 1 1 3 L Output 1 2 3 Input 6 1 0 0 1 0 2 -1 0 -1 -1 2 1 RLLR Output 6 1 3 4 2 5 Note This is the picture with the polygonal line from the 1 test: <image> As we see, this polygonal line is non-self-intersecting and winding, because the turn in point 2 is left. This is the picture with the polygonal line from the 2 test: <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 2010; int n; struct Point { long long x, y; int id; Point(int _x = 0, int _y = 0, int _id = 0) : x(_x), y(_y), id(_id) {} void Read(int i) { id = i; scanf("%lld%lld", &x, &y); } } ps[maxn]; Point operator-(Point a, Point b) { return Point(a.x - b.x, a.y - b.y); } long long cross(Point a, Point b) { return a.x * b.y - a.y * b.x; } Point base; int cmp(Point a, Point b) { return cross(a - base, b - base) > 0; } char s[maxn]; int vis[maxn], ans[maxn]; Point t[maxn]; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) ps[i].Read(i); scanf("%s", s + 1); base = ps[1]; for (int i = 2; i <= n; i++) { if (ps[i].y < base.y) base = ps[i]; } ans[1] = base.id; vis[ans[1]] = 1; for (int i = 2; i <= n; i++) { int cnt = 0; for (int j = 1; j <= n; j++) if (!vis[j]) t[++cnt] = ps[j]; sort(t + 1, t + 1 + cnt, cmp); if (s[i - 1] == 'L') { base = t[1]; ans[i] = base.id; vis[ans[i]] = 1; } else { base = t[cnt]; ans[i] = base.id; vis[ans[i]] = 1; } } for (int i = 1; i <= n; i++) printf("%d ", ans[i]); printf("\n"); return 0; } ```
### Prompt Construct a cpp code solution to the problem outlined: The capital of Berland has the only movie theater in the country. Besides, it consists of only one room. The room is divided into n rows, each row consists of m seats. There are k people lined up to the box office, each person wants to buy exactly one ticket for his own entertainment. Before the box office started selling tickets, each person found the seat that seemed best for him and remembered it as a pair of coordinates (xi, yi), where xi is the row number, and yi is the seat number in this row. It is possible that some people have chosen the same place, then when some people see their favorite seat taken in the plan of empty seats in the theater, they choose and buy a ticket to another place. Each of them has the following logic: let's assume that he originally wanted to buy a ticket to seat (x1, y1), then when he comes to the box office, he chooses such empty seat (x2, y2), which satisfies the following conditions: * the value of |x1 - x2| + |y1 - y2| is minimum * if the choice is not unique, then among the seats that satisfy the first condition, this person selects the one for which the value of x2 is minimum * if the choice is still not unique, among the seats that satisfy the first and second conditions, this person selects the one for which the value of y2 is minimum Your task is to find the coordinates of a seat for each person. Input The first input line contains three integers n, m, k (1 ≀ n, m ≀ 2000, 1 ≀ k ≀ min(nΒ·m, 105) β€” the number of rows in the room, the number of seats in each row and the number of people in the line, correspondingly. Each of the next k lines contains two integers xi, yi (1 ≀ xi ≀ n, 1 ≀ yi ≀ m) β€” the coordinates of the seat each person has chosen. Numbers on the same line are separated by a space. The pairs of coordinates are located in the order, in which people stand in the line, starting from the head (the first person in the line who stands in front of the box office) to the tail (the last person in the line). Output Print k lines, each containing a pair of integers. Print on the i-th line xi, yi β€” the coordinates of the seat, for which the person who stands i-th in the line will buy the ticket. Examples Input 3 4 6 1 1 1 1 1 1 1 2 1 3 1 3 Output 1 1 1 2 2 1 1 3 1 4 2 3 Input 4 3 12 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 Output 2 2 1 2 2 1 2 3 3 2 1 1 1 3 3 1 3 3 4 2 4 1 4 3 ### Response ```cpp #include <bits/stdc++.h> #pragma optimize("Ofast") #pragma GCC optimize("-funsafe-loop-optimizations") #pragma GCC optimize("-funroll-loops") #pragma GCC optimize("-fwhole-program") #pragma GCC optimize("-fthread-jumps") #pragma GCC optimize("-falign-functions") #pragma GCC optimize("-falign-jumps") #pragma GCC optimize("-falign-loops") #pragma GCC optimize("-falign-labels") #pragma GCC optimize("-fcaller-saves") #pragma GCC optimize("-fcrossjumping") #pragma GCC optimize("-fcse-follow-jumps") #pragma GCC optimize("-fcse-skip-blocks") #pragma GCC optimize("-fdelete-null-pointer-checks") #pragma GCC optimize("-fdevirtualize") #pragma GCC optimize("-fexpensive-optimizations") #pragma GCC optimize("-fgcse") #pragma GCC optimize("-fgcse-lm") #pragma GCC optimize("-fhoist-adjacent-loads") #pragma GCC optimize("-finline-small-functions") #pragma GCC optimize("-findirect-inlining") #pragma GCC optimize("-fipa-sra") #pragma GCC optimize("-foptimize-sibling-calls") #pragma GCC optimize("-fpartial-inlining") #pragma GCC optimize("-fpeephole2") #pragma GCC optimize("-freorder-blocks") #pragma GCC optimize("-freorder-functions") #pragma GCC optimize("-frerun-cse-after-loop") #pragma GCC optimize("-fsched-interblock") #pragma GCC optimize("-fsched-spec") #pragma GCC optimize("-fschedule-insns") #pragma GCC optimize("-fschedule-insns2") #pragma GCC optimize("-fstrict-aliasing") #pragma GCC optimize("-fstrict-overflow") #pragma GCC optimize("-ftree-switch-conversion") #pragma GCC optimize("-ftree-tail-merge") #pragma GCC optimize("-ftree-pre") #pragma GCC optimize("-ftree-vrp") #pragma comment(linker, "/STACK:16000000") using namespace std; namespace Geometry { struct point { double x; double y; void print() { printf("Point:x:%.8lf,y:%.8lf", x, y); } }; struct line { double x; double c; void print() { printf("Line:x:%.8lf,c:%.8lf\n", x, c); } }; line make_line(point a, point b) { double x = (a.x - b.x) / (a.y - b.y); double c = a.y - (a.x) * (x); return (line){x, c}; } } // namespace Geometry struct fastio { char s[100000]; int it, len; fastio() { it = len = 0; } inline char get() { if (it < len) return s[it++]; it = 0; len = fread(s, 1, 100000, stdin); if (len == 0) return EOF; else return s[it++]; } bool notend() { char c = get(); while (c == ' ' || c == '\n') c = get(); if (it > 0) it--; return c != EOF; } } _buff; inline int read() { int x; scanf("%d", &x); return x; } using namespace Geometry; const int inf = 0x3f3f3f3f; const long long inf2 = 0x3f3f3f3f3f3f3f3f; const double eps = 1e-6; const int mod = 1000000007; int n, m; int a[2005][2005], to[2005][2005]; int f1[4010000], f2[4010000]; int ansx, ansy; void change(int x, int y, int d, int i) { int xx = i / (m + 2), yy = i % (m + 2); if (xx > 0 && xx <= n && yy > 0 && yy <= m && abs(xx - x) + abs(yy - y) <= d) { if (ansx == -1 || xx < ansx || (xx == ansx && yy < ansy)) ansx = xx, ansy = yy; } } int find1(int x) { return x == f1[x] ? x : f1[x] = find1(f1[x]); } int find2(int x) { return x == f2[x] ? x : f2[x] = find2(f2[x]); } int q; bool check(int x, int y, int d) { int xx, yy; ansx = ansy = -1; xx = max(1, x - d); yy = x - xx + y - d; if (yy > 0) change(x, y, d, find1(to[xx][yy])); xx = max(1, x - d); yy = d - x + xx + y; if (yy <= m) change(x, y, d, find2(to[xx][yy])); if (ansx > 0) { printf("%d %d\n", ansx, ansy); f1[to[ansx][ansy]] = to[ansx + 1][ansy - 1]; f2[to[ansx][ansy]] = to[ansx + 1][ansy + 1]; return 1; } yy = max(y - d, 1); xx = d + x - y + yy; if (xx <= n) change(x, y, d, find2(to[xx][yy])); yy = min(y + d, m); xx = d + x - yy + y; if (xx <= n) change(x, y, d, find1(to[xx][yy])); if (ansx > 0) { printf("%d %d\n", ansx, ansy); f1[to[ansx][ansy]] = to[ansx + 1][ansy - 1]; f2[to[ansx][ansy]] = to[ansx + 1][ansy + 1]; return 1; } return 0; } int main() { n = read(); m = read(); for (int i = 0; i <= n; i++) for (int j = 0; j <= m; j++) { to[i][j] = i * (m + 2) + j; f1[i * (m + 2) + j] = f2[i * (m + 2) + j] = i * (m + 2) + j; } q = read(); while (q--) { int d = -inf; int x = read(), y = read(); for (int i = -1; i <= 1; i++) for (int j = -1; j <= 1; j++) d = max(d, a[x + i][y + j] - abs(i) - abs(j)); while (!check(x, y, d)) ++d; a[x][y] = d; } return 0; } ```
### Prompt Please create a solution in CPP to the following problem: On a clear night, a boy, Campanella looked up at the sky, there were many stars which have different colors such as red, yellow, green, blue, purple, etc. He was watching the stars and just lost track of time. Presently, he wondered, | <image> ---|--- "There are many stars in the space. What color is the universe if I look up it from outside?" Until he found the answer to this question, he couldn't sleep. After a moment's thought, he proposed a hypothesis, "When I observe the stars in the sky, if more than half of the stars have the same color, that is the color of the universe." He has collected data of stars in the universe after consistently observing them. However, when he try to count the number of star, he was in bed sick with a cold. You decided to help him by developing a program to identify the color of the universe. You are given an array A. Let |A| be the number of element in A, and let Nm be the number of m in A. For example, if A = {3, 1, 2, 3, 3, 1, 5, 3}, |A| = 8, N3 = 4, N1 = 2, N5 = 1. Your program have to find m such that: Nm > (|A| / 2 ) If there is no such m, you also have to report the fact. There is no such m for the above example, but for a array A = {5, 2, 5, 3, 4, 5, 5}, 5 is the answer. Input There are several test cases. For each test case, in the first line |A| is given. In the next line, there will be |A| integers. The integers are less than 231 and |A| < 1,000,000. The input terminate with a line which contains single 0. Output For each test case, output m in a line. If there is no answer, output "NO COLOR" in a line. Example Input 8 3 1 2 3 3 1 5 3 7 5 2 5 3 4 5 5 0 Output NO COLOR 5 ### Response ```cpp #include <iostream> #include <vector> #include <map> #include <algorithm> using namespace std; void solve() { int n; while (cin >> n, n) { vector<int> colors(n); map<int, int> Map; for (int i = 0; i < n; ++i) { cin >> colors[i]; Map[colors[i]]++; } map<int, int>::iterator it = Map.begin(); while (it != Map.end()) { if (it->second > n / 2) { cout << it->first << endl; goto END; } ++it; } cout << "NO COLOR" << endl; END: ; } } int main() { solve(); return(0); } ```
### Prompt In CPP, your task is to solve the following problem: Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special β€” it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from 0 to s and elevator initially starts on floor s at time 0. The elevator takes exactly 1 second to move down exactly 1 floor and negligible time to pick up passengers. Genos is given a list detailing when and on which floor passengers arrive. Please determine how long in seconds it will take Genos to bring all passengers to floor 0. Input The first line of input contains two integers n and s (1 ≀ n ≀ 100, 1 ≀ s ≀ 1000) β€” the number of passengers and the number of the top floor respectively. The next n lines each contain two space-separated integers fi and ti (1 ≀ fi ≀ s, 1 ≀ ti ≀ 1000) β€” the floor and the time of arrival in seconds for the passenger number i. Output Print a single integer β€” the minimum amount of time in seconds needed to bring all the passengers to floor 0. Examples Input 3 7 2 1 3 8 5 2 Output 11 Input 5 10 2 77 3 33 8 21 9 12 10 64 Output 79 Note In the first sample, it takes at least 11 seconds to bring all passengers to floor 0. Here is how this could be done: 1. Move to floor 5: takes 2 seconds. 2. Pick up passenger 3. 3. Move to floor 3: takes 2 seconds. 4. Wait for passenger 2 to arrive: takes 4 seconds. 5. Pick up passenger 2. 6. Go to floor 2: takes 1 second. 7. Pick up passenger 1. 8. Go to floor 0: takes 2 seconds. This gives a total of 2 + 2 + 4 + 1 + 2 = 11 seconds. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n, s, f, t, k = 0; cin >> n >> s; for (int i = 1; i <= n; i++) { cin >> f >> t; if (t + f > k) { k = t + f; } } if (k >= s) cout << k; else cout << s; } ```
### Prompt Please formulate a cpp solution to the following problem: Dima is living in a dormitory, as well as some cockroaches. At the moment 0 Dima saw a cockroach running on a table and decided to kill it. Dima needs exactly T seconds for aiming, and after that he will precisely strike the cockroach and finish it. To survive the cockroach has to run into a shadow, cast by round plates standing on the table, in T seconds. Shadow casted by any of the plates has the shape of a circle. Shadow circles may intersect, nest or overlap arbitrarily. The cockroach uses the following strategy: first he equiprobably picks a direction to run towards and then runs towards it with the constant speed v. If at some moment t ≀ T it reaches any shadow circle, it immediately stops in the shadow and thus will stay alive. Otherwise the cockroach is killed by the Dima's precise strike. Consider that the Dima's precise strike is instant. Determine the probability of that the cockroach will stay alive. Input In the first line of the input the four integers x0, y0, v, T (|x0|, |y0| ≀ 109, 0 ≀ v, T ≀ 109) are given β€” the cockroach initial position on the table in the Cartesian system at the moment 0, the cockroach's constant speed and the time in seconds Dima needs for aiming respectively. In the next line the only number n (1 ≀ n ≀ 100 000) is given β€” the number of shadow circles casted by plates. In the next n lines shadow circle description is given: the ith of them consists of three integers xi, yi, ri (|xi|, |yi| ≀ 109, 0 ≀ r ≀ 109) β€” the ith shadow circle on-table position in the Cartesian system and its radius respectively. Consider that the table is big enough for the cockroach not to run to the table edges and avoid Dima's precise strike. Output Print the only real number p β€” the probability of that the cockroach will stay alive. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 4. Examples Input 0 0 1 1 3 1 1 1 -1 -1 1 -2 2 1 Output 0.50000000000 Input 0 0 1 0 1 1 0 1 Output 1.00000000000 Note The picture for the first sample is given below. <image> Red color stands for points which being chosen as the cockroach's running direction will cause him being killed, green color for those standing for survival directions. Please note that despite containing a circle centered in ( - 2, 2) a part of zone is colored red because the cockroach is not able to reach it in one second. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int const N = (1e5) + 5; vector<long long> x, y, r; vector<pair<double, double>> seg; int n; double alpha(double dx, double dy, double dist) { double angle = acos(dx / dist); if (dy < 0) { angle += acos(-1.); } return angle; } int main() { long long x0, y0, v, T; cin >> x0 >> y0 >> v >> T; cin >> n; for (int i = 0; i < n; ++i) { int xi, yi, ri; scanf("%d %d %d", &xi, &yi, &ri); x.push_back(xi), y.push_back(yi), r.push_back(ri); } n = x.size(); double R = min(v * T, 6 * 1000000000LL); for (int i = 0; i < n; ++i) { double dx = x[i] - x0, dy = y[i] - y0; double dist = dx * dx + dy * dy; if ((x[i] - x0) * (x[i] - x0) + (y[i] - y0) * (y[i] - y0) <= r[i] * r[i]) { cout << 1; return 0; } dist = sqrt(dist); if (R + r[i] <= dist || r[i] == 0) { continue; } double ang1, ang2; double angl = atan2(dx, dy); double l = dist * dist - r[i] * r[i]; double al = asin(r[i] / dist); if (R * R + r[i] * r[i] < dist * dist) { double Cos = (R * R + dist * dist - r[i] * r[i]) / (2. * R * dist); al = acos(Cos); } ang1 = angl - al; ang2 = angl + al; if (ang1 < -acos(-1.)) { seg.push_back(make_pair(-acos(-1.), ang2)); seg.push_back(make_pair(ang1 + 2. * acos(-1.), acos(-1.))); } else if (ang2 > acos(-1.)) { seg.push_back(make_pair(ang1, acos(-1.))); seg.push_back(make_pair(-acos(-1.), ang2 - 2. * acos(-1.))); } else { seg.push_back(make_pair(ang1, ang2)); } } sort(seg.begin(), seg.end()); double len = 0, clen = 0; double en = -acos(-1.); for (int i = 0; i < seg.size(); ++i) { en = max(en, seg[i].first); if (seg[i].second - en > 0) len += seg[i].second - en; en = max(en, seg[i].second); } double p = len / (2 * acos(-1.)); cout << setprecision(9) << p << endl; return 0; } ```
### Prompt In CPP, your task is to solve the following problem: Given is a string S. Each character in S is either a digit (`0`, ..., `9`) or `?`. Among the integers obtained by replacing each occurrence of `?` with a digit, how many have a remainder of 5 when divided by 13? An integer may begin with 0. Since the answer can be enormous, print the count modulo 10^9+7. Constraints * S is a string consisting of digits (`0`, ..., `9`) and `?`. * 1 \leq |S| \leq 10^5 Input Input is given from Standard Input in the following format: S Output Print the number of integers satisfying the condition, modulo 10^9+7. Examples Input ??2??5 Output 768 Input ?44 Output 1 Input 7?4 Output 0 Input ?6?42???8??2??06243????9??3???7258??5??7???????774????4?1??17???9?5?70???76??? Output 153716888 ### Response ```cpp #include <bits/stdc++.h> using namespace std; typedef long long ll; const int MOD = 1000000007; int main() { string s; cin >> s; int sl = s.size(); vector<vector<ll>> dp(sl + 1, vector<ll>(13, 0)); dp[0][0] = 1; for (int i = 0; i < sl; ++i) { for (int j = 0; j < 13; ++j) { if (s[i] == '?') { for (int k = 0; k < 10; ++k) { (dp[i + 1][(j * 10 + k) % 13] += dp[i][j]) %= MOD; } } else { int k = s[i] - '0'; (dp[i + 1][(j * 10 + k) % 13] += dp[i][j]) %= MOD; } } } cout << dp[sl][5] << endl; return 0; } ```
### Prompt Create a solution in Cpp for the following problem: Limak is a little polar bear. According to some old traditions, his bear family prepared a New Year cake. And Limak likes cakes. As you may know, a New Year cake is a strictly convex polygon with n vertices. Parents won't allow Limak to eat more than half of a cake because he would get sick. After some thinking they decided to cut a cake along one of nΒ·(n - 3) / 2 diagonals. Then Limak will get a non-greater piece. Limak understands rules but he won't be happy if the second piece happens to be much bigger. Limak's disappointment will be equal to the difference between pieces' areas, multiplied by two. It can be proved that it will be integer for the given constraints. There are nΒ·(n - 3) / 2 possible scenarios. Consider them all and find the sum of values of Limak's disappointment, modulo 109 + 7. Input The first line of the input contains a single integer n (4 ≀ n ≀ 500 000) β€” the number of vertices in the polygon denoting the cake. Each of the next n lines contains two integers xi and yi (|xi|, |yi| ≀ 109) β€” coordinates of the i-th point. It's guaranteed that all points are distinct, polygon is strictly convex and points are given in the clockwise order. Output Print the sum of values of Limak's disappointment over all possible scenarios modulo 109 + 7. Examples Input 5 2 4 2 7 5 7 5 4 3 -2 Output 90 Input 4 -1000000000 -5000000 0 1234567 1 1 -5 -100000000 Output 525185196 Input 8 -10 0 -6 6 0 10 6 6 10 0 6 -6 0 -10 -6 -6 Output 5216 Note In the first sample possible values of Limak's disappointment are 0, 18, 18, 24, 30. ### Response ```cpp #include <bits/stdc++.h> using namespace std; pair<long long, long long> arr[530000], sk[530000]; long long ints[530000], rates[530000], n; void upd(long long a, long long b, long long r) { a += n, b += n; a %= n, b %= n; if (a <= b) ints[a] += r, ints[b + 1] -= r; else ints[0] += r, ints[b + 1] -= r, ints[a] += r; } void updr(long long a, long long b, long long r) { a += n, b += n; a %= n, b %= n; if (a <= b) { rates[a] += r; rates[b + 1] -= r; if (b + 1 < n) upd(b + 1, n - 1, -r * (b + 1 - a)); } else rates[0] += r, rates[b + 1] -= r, rates[a] += r, upd(b + 1, n - 1, -r * (b + 1)), upd(0, b, r * (n - a)); } pair<long long, long long> que(long long a, long long b) { a += n, b += n; a %= n, b %= n; if (a <= b) { return (a == 0) ? sk[b] : make_pair((1000000007 * 2 + sk[b].first - sk[a - 1].first) % 1000000007, (1000000007 * 2 + sk[b].second - sk[a - 1].second) % 1000000007); } else { return make_pair( (1000000007 * 2 + sk[b].first + sk[n - 1].first - sk[a - 1].first) % 1000000007, (1000000007 * 2 + sk[b].second + sk[n - 1].second - sk[a - 1].second) % 1000000007); } } long long prod(pair<long long, long long> a, pair<long long, long long> b) { return (((a.first) * (b.second)) - ((b.first) * (a.second))); } long long dif(long long a, long long b) { a += n, b += n; a %= n, b %= n; if (a <= b) return b - a + 1; else return b + 1 + n - a; } int main() { long long sum = 0, small = 0; cin >> n; for (long long i = 0; i < n; i++) scanf("%lld%lld", &arr[i].first, &arr[i].second); reverse(arr, arr + n); for (long long i = 0; i < n; i++) sum += prod(arr[i], arr[(i + 1) % n]); sk[0] = arr[0]; for (long long i = 1; i < n; i++) sk[i].first = (arr[i].first + sk[i - 1].first) % 1000000007, sk[i].second = (arr[i].second + sk[i - 1].second) % 1000000007; long long j = 0, cur = 0; for (long long i = 0; i < n; i++) { while (sum / 2 >= cur + prod(arr[j], arr[(j + 1) % n]) - prod(arr[j], arr[i]) + prod(arr[(j + 1) % n], arr[i])) { cur += prod(arr[j], arr[(j + 1) % n]) - prod(arr[j], arr[i]) + prod(arr[(j + 1) % n], arr[i]), j++, j %= n; } if (j == (i + 1) % n) updr(i + 2, i - 1, 1), upd(i - 1, i - 1, -1), small += prod(arr[i], que(i + 2, i - 2)); else { upd(i, j - 1, dif(i, j)); upd(i, i, -1); updr(i, j - 1, -1); upd(j, i - 1, 0); upd(i - 1, i - 1, -1); updr(j + 1, i - 1, 1); small += prod(que(i + 2, j), arr[i]), small %= 1000000007; if (j != (i - 2 + n) % n) small += prod(arr[i], que(j + 1, i - 2)), small %= 1000000007; } cur += -prod(arr[i], arr[i + 1]) - prod(arr[j], arr[i]) + prod(arr[j], arr[i + 1]); } for (long long i = 1; i < n; i++) ints[i] += ints[i - 1] % 1000000007; for (long long i = 1; i < n; i++) rates[i] += rates[i - 1] % 1000000007; for (long long i = 1; i < n; i++) rates[i] += rates[i - 1] % 1000000007; for (long long i = 0; i < n; i++) ints[i] += rates[i] % 1000000007; for (long long i = 0; i < n; i++) small += (ints[i] % 1000000007) * (prod(arr[i], arr[(i + 1) % n]) % 1000000007), small %= 1000000007; cout << ((sum % 1000000007) * ((n * (n - 3) / 2) % 1000000007) - small) % 1000000007 << endl; } ```
### Prompt Please formulate a Cpp solution to the following problem: The Little Elephant loves the LCM (least common multiple) operation of a non-empty set of positive integers. The result of the LCM operation of k positive integers x1, x2, ..., xk is the minimum positive integer that is divisible by each of numbers xi. Let's assume that there is a sequence of integers b1, b2, ..., bn. Let's denote their LCMs as lcm(b1, b2, ..., bn) and the maximum of them as max(b1, b2, ..., bn). The Little Elephant considers a sequence b good, if lcm(b1, b2, ..., bn) = max(b1, b2, ..., bn). The Little Elephant has a sequence of integers a1, a2, ..., an. Help him find the number of good sequences of integers b1, b2, ..., bn, such that for all i (1 ≀ i ≀ n) the following condition fulfills: 1 ≀ bi ≀ ai. As the answer can be rather large, print the remainder from dividing it by 1000000007 (109 + 7). Input The first line contains a single positive integer n (1 ≀ n ≀ 105) β€” the number of integers in the sequence a. The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” sequence a. Output In the single line print a single integer β€” the answer to the problem modulo 1000000007 (109 + 7). Examples Input 4 1 4 3 2 Output 15 Input 2 6 3 Output 13 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 7; const long long md = 1e9 + 7; int bit[maxn]; long long l[maxn]; vector<int> dv; int occ[maxn]; long long modexp(long long a, long long ex) { long long ans = 1; while (ex > 0) { if ((ex & 1) == 1) ans = (ans * a) % md; a = (a * a) % md; ex >>= 1; } return ans; } int qry(int x) { int ans = 0; while (x > 0) { ans += bit[x]; x -= x & (-x); } return ans; } void upd(int x, int v) { while (x < maxn) { bit[x] += v; x += x & (-x); } } int main() { int n; scanf("%d", &n); fill(occ, occ + maxn, 0); for (int i = 1; i <= n; i++) { int x; scanf("%d", &x); occ[x]++; } int lft = n; long long ans = 0; for (int v = 1; v < maxn; v++) { dv.clear(); for (int p = 1; p * p <= v; p++) { if (v % p != 0) continue; dv.push_back(p); if (v / p != p) dv.push_back(v / p); } sort(dv.begin(), dv.end()); int cur = 0; long long c = 1, d = 1; for (int j = dv.size() - 1; j >= 0; j--) { int y = dv[j]; int q = qry(y); c = (c * modexp(j + 1, q - cur)) % md; cur = q; } lft -= occ[v - 1]; upd(1, -lft); upd(v, lft); upd(1, lft); upd(v + 1, -lft); cur = 0; for (int j = dv.size() - 1; j >= 0; j--) { int y = dv[j]; int q = qry(y); d = (d * modexp(j + 1, q - cur)) % md; cur = q; } ans += d - c; } if (ans < 0) { ans = (-ans) % md; ans = (md - ans) % md; } else ans %= md; printf("%lld", (ans + 1) % md); printf("\n"); } ```
### Prompt Create a solution in cpp for the following problem: Let’s define a grid to be a set of tiles with 2 rows and 13 columns. Each tile has an English letter written in it. The letters don't have to be unique: there might be two or more tiles with the same letter written on them. Here is an example of a grid: ABCDEFGHIJKLM NOPQRSTUVWXYZ We say that two tiles are adjacent if they share a side or a corner. In the example grid above, the tile with the letter 'A' is adjacent only to the tiles with letters 'B', 'N', and 'O'. A tile is not adjacent to itself. A sequence of tiles is called a path if each tile in the sequence is adjacent to the tile which follows it (except for the last tile in the sequence, which of course has no successor). In this example, "ABC" is a path, and so is "KXWIHIJK". "MAB" is not a path because 'M' is not adjacent to 'A'. A single tile can be used more than once by a path (though the tile cannot occupy two consecutive places in the path because no tile is adjacent to itself). You’re given a string s which consists of 27 upper-case English letters. Each English letter occurs at least once in s. Find a grid that contains a path whose tiles, viewed in the order that the path visits them, form the string s. If there’s no solution, print "Impossible" (without the quotes). Input The only line of the input contains the string s, consisting of 27 upper-case English letters. Each English letter occurs at least once in s. Output Output two lines, each consisting of 13 upper-case English characters, representing the rows of the grid. If there are multiple solutions, print any of them. If there is no solution print "Impossible". Examples Input ABCDEFGHIJKLMNOPQRSGTUVWXYZ Output YXWVUTGHIJKLM ZABCDEFSRQPON Input BUVTYZFQSNRIWOXXGJLKACPEMDH Output Impossible ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long n; string s, ss[2]; string origS; int dx[] = {1, 0, -1, 1, -1, 1, 0, -1}; int dy[] = {1, 1, 1, 0, 0, -1, -1, -1}; void rotate() { char beg = ss[1][0]; char end = ss[0][12]; ss[0] = beg + ss[0].substr(0, 12); ss[1] = ss[1].substr(1, 12) + end; } bool pathExist(int count, int curx, int cury) { if (count == 26) { return true; } for (int i = 0; i < 8; i++) { int newx = curx + dx[i]; int newy = cury + dy[i]; if (newx >= 0 && newx < 26 && newy >= 0 && newy < 2 && ss[newy][newx] == origS[count + 1]) { return pathExist(count + 1, newx, newy); } } return false; } int main() { cin >> s; origS = s; for (int i = 0; i < s.size() - 1; i++) { if (s[i] == s[i + 1]) { cout << "Impossible" << endl; return 0; } } set<char> seen; for (int i = 0; i < 27; i++) { if (seen.count(s[i])) { s.erase(s.begin() + i); break; } seen.insert(s[i]); } ss[0] = s.substr(0, 13); ss[1] = s.substr(13, 13); reverse(ss[1].begin(), ss[1].end()); for (int i = 0; i < 26; i++) { int j = 0, k = 0; for (j = 0; j < 2; j++) { for (k = 0; k < 13; k++) { if (ss[j][k] == origS[0]) break; } if (ss[j][k] == origS[0]) break; } if (pathExist(0, k, j)) { cout << ss[0] << endl << ss[1] << endl; return 0; } rotate(); } return 0; } ```
### Prompt Generate a cpp solution to the following problem: Draw a rectangle which has a height of H cm and a width of W cm. Draw a 1-cm square by single '#'. Constraints * 1 ≀ H ≀ 300 * 1 ≀ W ≀ 300 Input The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space. The input ends with two 0 (when both H and W are zero). Output For each dataset, print the rectangle made of H Γ— W '#'. Print a blank line after each dataset. Example Input 3 4 5 6 2 2 0 0 Output #### #### #### ###### ###### ###### ###### ###### ## ## ### Response ```cpp #include<stdio.h> int main(void){ int H,W,i,I,j; for(j=0;j<10000;j++){ scanf("%d %d",&H,&W); if(H!=0){ for(i=0;i<H;i++){ for(I=0;I<W;I++){ printf("#"); } printf("\n"); } printf("\n"); }else{ break; } } return 0; } ```
### Prompt Create a solution in cpp for the following problem: A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of a thimbles per day after the k days are complete. Initially, no orders are pending. The factory receives updates of the form di, ai, indicating that ai new orders have been placed for the di-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes. As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day pi. Help the owner answer his questions. Input The first line contains five integers n, k, a, b, and q (1 ≀ k ≀ n ≀ 200 000, 1 ≀ b < a ≀ 10 000, 1 ≀ q ≀ 200 000) β€” the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively. The next q lines contain the descriptions of the queries. Each query is of one of the following two forms: * 1 di ai (1 ≀ di ≀ n, 1 ≀ ai ≀ 10 000), representing an update of ai orders on day di, or * 2 pi (1 ≀ pi ≀ n - k + 1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day pi? It's guaranteed that the input will contain at least one query of the second type. Output For each query of the second type, print a line containing a single integer β€” the maximum number of orders that the factory can fill over all n days. Examples Input 5 2 2 1 8 1 1 2 1 5 3 1 2 1 2 2 1 4 2 1 3 2 2 1 2 3 Output 3 6 4 Input 5 4 10 1 6 1 1 5 1 5 5 1 3 2 1 5 2 2 1 2 2 Output 7 1 Note Consider the first sample. We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days. For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled. For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 2e5 + 100; struct Fenwick { long long fen[N]; void clear() { memset(fen, 0, sizeof fen); } void ad(int p, long long val) { for (p++; p < N; p += p & -p) fen[p] += val; } long long gt(int p, long long ret = 0) { for (; p; p -= p & -p) ret += fen[p]; return ret; } }; long long n, k, a, b, q; int main() { ios::sync_with_stdio(0); cin.tie(0); Fenwick A, B; A.clear(); B.clear(); cin >> n >> k >> a >> b >> q; for (int i = 0; i < q; ++i) { int t; cin >> t; if (t == 1) { long long d, c; cin >> d >> c; long long x1 = A.gt(d + 1) - A.gt(d); long long x2 = B.gt(d + 1) - B.gt(d); A.ad(d, -x1); B.ad(d, -x2); x1 += c; x2 += c; A.ad(d, min(x1, a)); B.ad(d, min(x2, b)); } else { long long p; cin >> p; long long ans = 0; ans += B.gt(p); ans += A.gt(n + 1) - A.gt(p + k); cout << ans << "\n"; } } return 0; } ```
### Prompt Please formulate a cpp solution to the following problem: The city of D consists of n towers, built consecutively on a straight line. The height of the tower that goes i-th (from left to right) in the sequence equals hi. The city mayor decided to rebuild the city to make it beautiful. In a beautiful city all towers are are arranged in non-descending order of their height from left to right. The rebuilding consists of performing several (perhaps zero) operations. An operation constitutes using a crane to take any tower and put it altogether on the top of some other neighboring tower. In other words, we can take the tower that stands i-th and put it on the top of either the (i - 1)-th tower (if it exists), or the (i + 1)-th tower (of it exists). The height of the resulting tower equals the sum of heights of the two towers that were put together. After that the two towers can't be split by any means, but more similar operations can be performed on the resulting tower. Note that after each operation the total number of towers on the straight line decreases by 1. Help the mayor determine the minimum number of operations required to make the city beautiful. Input The first line contains a single integer n (1 ≀ n ≀ 5000) β€” the number of towers in the city. The next line contains n space-separated integers: the i-th number hi (1 ≀ hi ≀ 105) determines the height of the tower that is i-th (from left to right) in the initial tower sequence. Output Print a single integer β€” the minimum number of operations needed to make the city beautiful. Examples Input 5 8 2 7 3 1 Output 3 Input 3 5 2 1 Output 2 ### Response ```cpp #include <bits/stdc++.h> using namespace std; inline int ni() { int a; scanf("%d", &a); return a; } const int maxn = 5011; const int inf = 1000000000; int hs[maxn], d[maxn][maxn]; int main() { int n = ni(); for (int i = 0; i < int(n); i++) hs[i] = ni(); for (int i = 0; i < int(maxn); i++) for (int j = 0; j < int(maxn); j++) d[i][j] = inf; d[1][1] = 0; for (int taken = 1; taken <= n; taken++) { int lastSize = 0, curSize = 0, curPtr = taken; for (int lastSeg = 1; lastSeg <= taken; lastSeg++) { lastSize += hs[taken - lastSeg]; while (curPtr < n && curSize < lastSize) { curSize += hs[curPtr]; ++curPtr; } int minNeedTaken = -1; if (curSize >= lastSize) { minNeedTaken = curPtr - taken; } if (minNeedTaken != -1) { d[taken + minNeedTaken][minNeedTaken] = min(d[taken + minNeedTaken][minNeedTaken], d[taken][lastSeg] + (minNeedTaken - 1)); } d[taken + 1][lastSeg + 1] = min(d[taken + 1][lastSeg + 1], d[taken][lastSeg] + 1); } } int res = inf; for (int i = 0; i < int(maxn); i++) res = min(res, d[n][i]); cout << res << endl; return 0; } ```
### Prompt Construct a CPP code solution to the problem outlined: Write a program which manipulates a sequence $A$ = {$a_0, a_1, ..., a_{n-1}$} with the following operations: * $update(s, t, x)$: change $a_s, a_{s+1}, ..., a_t$ to $x$. * $getSum(s, t)$: print the sum of $a_s, a_{s+1}, ..., a_t$. Note that the initial values of $a_i ( i = 0, 1, ..., n-1 )$ are 0. Constraints * $1 ≀ n ≀ 100000$ * $1 ≀ q ≀ 100000$ * $0 ≀ s ≀ t < n$ * $-1000 ≀ x ≀ 1000$ Input $n$ $q$ $query_1$ $query_2$ : $query_q$ In the first line, $n$ (the number of elements in $A$) and $q$ (the number of queries) are given. Then, $i$-th query $query_i$ is given in the following format: 0 $s$ $t$ $x$ or 1 $s$ $t$ The first digit represents the type of the query. '0' denotes $update(s, t, x)$ and '1' denotes $find(s, t)$. Output For each $getSum$ query, print the sum in a line. Example Input 6 7 0 1 3 1 0 2 4 -2 1 0 5 1 0 1 0 3 5 3 1 3 4 1 0 5 Output -5 1 6 8 ### Response ```cpp #include <bits/stdc++.h> using namespace std; class segment_tree{ vector<int64_t> val; vector<pair<int64_t, int64_t>> op; vector<pair<size_t, size_t>> range; size_t N, depth; void merge(size_t target, int64_t alpha, int64_t beta){ op[target] = {op[target].first * alpha, op[target].second * alpha + beta}; } void propagate(size_t target){ // min, max -> width = 1 val[target] = op[target].first * val[target] + op[target].second * (range[target].second - range[target].first); if(target < N){ merge(2*target, op[target].first, op[target].second); merge(2*target+1, op[target].first, op[target].second); } op[target] = {1, 0}; } void eval(int n){ stack<size_t> stk; for(;n>0;n>>=1) stk.push(n); while(!stk.empty()){ propagate(stk.top()); stk.pop(); } } void get_target(vector<size_t> &target, size_t left, size_t right, stack<size_t> *refresh=nullptr){ queue<size_t> partial; if(left <= 0 && right >= N) target.push_back(1); else partial.push(1); while(!partial.empty()){ size_t i = partial.front(); if(refresh != nullptr) refresh->push(i); partial.pop(); propagate(i); if(left <= range[i].first){ if(right < range[i*2].second) partial.push(i*2); else{ target.push_back(i*2); if(range[i*2+1].first < right) partial.push(i*2+1); } }else{ if(left < range[i*2].second){ partial.push(i*2); if(range[i*2+1].second <= right) target.push_back(i*2+1); else if(range[i*2].second < right) partial.push(i*2+1); }else{ if(left <= range[i*2+1].first && range[i*2+1].second <= right) target.push_back(i*2+1); else partial.push(i*2+1); } } } } public: segment_tree(size_t n){ for(depth=0;(1ULL<<depth)<n;depth++); N = 1ULL<<depth; val.reserve(1ULL<<(++depth)); op.reserve(1ULL<<depth); range.reserve(1ULL<<depth); for(size_t i=2*N-1;i>0;i--){ if(i>=N) range[i] = {i-N, i-N+1}; else range[i] = {range[2*i].first, range[2*i+1].second}; } } int64_t operator[](size_t i){ eval(N+i); return val[N+i]; } void operate(int64_t alpha, int64_t beta, size_t left, size_t right){ if(right <= left) return; vector<size_t> target; stack<size_t> refresh; get_target(target, left, right, &refresh); for(auto i : target){ merge(i, alpha, beta); propagate(i); } while(!refresh.empty()){ size_t i = refresh.top(); refresh.pop(); //min, max -> change propagate(i*2); propagate(i*2+1); val[i] = val[i*2] + val[i*2+1]; } } int64_t get_sum(size_t left, size_t right){ if(right <= left) return 0; vector<size_t> target; get_target(target, left, right); int64_t ret = 0; for(auto i : target){ ret += op[i].first * val[i] + op[i].second * (range[i].second - range[i].first); } return ret; } void update(int64_t val, size_t pos){ operate(0, val, pos, pos+1); } void update(int64_t val, size_t left, size_t right){ operate(0, val, left, right); } void add(int64_t val, size_t pos){ operate(1, val, pos, pos+1); } void add(int64_t val, size_t left, size_t right){ operate(1, val, left, right); } void dump(){ for(int i=1;i<2*N;i++){ eval(i); cerr << val[i] << " "; } cerr << endl; } }; int main(){ int n, q; cin >> n >> q; segment_tree st(n); for(int i=0;i<q;i++){ int com; cin >> com; if(com == 0){ int s, t, x; cin >> s >> t >> x; st.update(x, s, t+1); }else{ int s, t; cin >> s >> t; cout << st.get_sum(s, t+1) << endl; } //st.dump(); } return 0; } ```
### Prompt Please create a solution in CPP to the following problem: Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters. Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings. Help him do this! Input The first line contains integer n (1 ≀ n ≀ 200 000) β€” the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters. Output In the first line, print number x β€” the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1 ≀ i, j ≀ n, i β‰  j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters. If there are multiple possible answers, print any of them. Examples Input 9 pergament permanent Output 1 4 6 Input 6 wookie cookie Output 1 -1 -1 Input 4 petr egor Output 2 1 2 Input 6 double bundle Output 2 4 1 Note In the second test it is acceptable to print i = 2, j = 3. ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct Letters { int num; char s; char t; }; vector<Letters> Str1[30]; vector<Letters> Str2[30]; string S, T; int main() { int n; while (cin >> n) { cin >> S >> T; for (int i = 0; i < 26; i++) { Str1[i].clear(); Str2[i].clear(); } Letters l; int k1, k2, tot = 0, ok; for (int i = 0; S[i]; i++) { if (S[i] != T[i]) { tot++; l.num = i + 1; l.s = S[i]; l.t = T[i]; k1 = S[i] - 'a'; k2 = T[i] - 'a'; ok = 1; for (int j = 0; j < Str1[k1].size(); j++) { if (Str1[k1][j].t == l.t) { ok = 0; break; } } if (ok) { Str1[k1].push_back(l); Str2[k2].push_back(l); } } } ok = 0; int x = -1, y = -1; for (int i = 0; i < 26; i++) { for (int j = 0; j < Str1[i].size(); j++) { for (int k = 0; k < Str2[i].size(); k++) { x = Str1[i][j].num; y = Str2[i][k].num; if (Str1[i][j].t == Str2[i][k].s) ok = 1; if (ok) break; } if (ok) break; } if (ok) break; } if (ok) tot -= 2; else if (x != -1) tot -= 1; cout << tot << endl; cout << x << " " << y << endl; } return 0; } ```
### Prompt Please create a solution in CPP to the following problem: Innokentiy likes tea very much and today he wants to drink exactly n cups of tea. He would be happy to drink more but he had exactly n tea bags, a of them are green and b are black. Innokentiy doesn't like to drink the same tea (green or black) more than k times in a row. Your task is to determine the order of brewing tea bags so that Innokentiy will be able to drink n cups of tea, without drinking the same tea more than k times in a row, or to inform that it is impossible. Each tea bag has to be used exactly once. Input The first line contains four integers n, k, a and b (1 ≀ k ≀ n ≀ 105, 0 ≀ a, b ≀ n) β€” the number of cups of tea Innokentiy wants to drink, the maximum number of cups of same tea he can drink in a row, the number of tea bags of green and black tea. It is guaranteed that a + b = n. Output If it is impossible to drink n cups of tea, print "NO" (without quotes). Otherwise, print the string of the length n, which consists of characters 'G' and 'B'. If some character equals 'G', then the corresponding cup of tea should be green. If some character equals 'B', then the corresponding cup of tea should be black. If there are multiple answers, print any of them. Examples Input 5 1 3 2 Output GBGBG Input 7 2 2 5 Output BBGBGBB Input 4 3 4 0 Output NO ### Response ```cpp #include <bits/stdc++.h> using namespace std; void fn(int n, int k, int a, int b) { int i; if (a == b) { for (i = 0; i < a; i++) cout << 'G' << 'B'; return; } if (a > b) { if (a > k && b > 0) { for (i = 0; i < k; i++) cout << 'G'; cout << 'B'; a -= k; b--; if (a > b) { fn(n - k - 1, k, a, b); return; } if (a == 0) return; cout << 'G'; a--; fn(n - k - 2, k, a, b); return; } for (i = 0; i < a; i++) cout << 'G'; for (i = 0; i < b; i++) cout << 'B'; return; } if (b > k && a > 0) { for (i = 0; i < k; i++) cout << 'B'; cout << 'G'; b -= k; a--; if (b > a) { fn(n - k - 1, k, a, b); return; } if (b == 0) return; cout << 'B'; b--; fn(n - k - 2, k, a, b); return; } for (i = 0; i < b; i++) cout << 'B'; for (i = 0; i < a; i++) cout << 'G'; return; } int main() { int n, k, a, b; cin >> n >> k >> a >> b; if ((n / (k + 1) > a) || (n / (k + 1) > b)) { cout << "NO" << endl; } else { fn(n, k, a, b); cout << endl; } return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: Recently Bob invented a new game with a tree (we should remind you, that a tree is a connected graph without cycles): he deletes any (possibly, zero) amount of edges of the tree, and counts the product of sizes of the connected components left after the deletion. Your task is to find out the maximum number that Bob can get in his new game for a given tree. Input The first input line contains integer number n (1 ≀ n ≀ 700) β€” amount of vertices in the tree. The following n - 1 lines contain the description of the edges. Each line contains the pair of vertices' indexes, joined by an edge, ai, bi (1 ≀ ai, bi ≀ n). It's guaranteed that the graph described in the input is a tree. Output Output the only number β€” the maximum product of sizes of the connected components, that Bob can get after deleting some of the tree's edges. Examples Input 5 1 2 2 3 3 4 4 5 Output 6 Input 8 1 2 1 3 2 4 2 5 3 6 3 7 6 8 Output 18 Input 3 1 2 1 3 Output 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; namespace Fastio { enum io_flags { ignore_int = 1 << 0, flush_stdout = 1 << 1, flush_stderr = 1 << 2, }; enum number_type_flags { output_double_stable = 1 << 0, output_double_faster = 1 << 1 }; struct Reader { char endch; Reader() { endch = '\0'; } Reader& operator>>(io_flags f) { if (f & ignore_int) { endch = getchar(); while ((!isdigit(endch)) && endch != '-' && endch != EOF) endch = getchar(); while (isdigit(endch = getchar())) ; } return *this; } Reader& operator>>(char& ch) { ch = getchar(); while (ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t') ch = getchar(); return *this; } Reader& operator>>(double& lf) { bool flag = 0; endch = getchar(); while ((!isdigit(endch)) && endch != '-' && endch != EOF) endch = getchar(); if (endch == '-') flag = 1, endch = getchar(); lf = endch & 15; while (isdigit(endch = getchar())) lf = lf * 10 + (endch & 15); if (endch == '.') { double digit = 0.1; while (isdigit(endch = getchar())) { lf += (endch & 15) * digit; digit *= 0.1; } } if (flag) lf = -lf; return *this; } template <typename Int> Reader& operator>>(Int& d) { bool flag = 0; endch = getchar(); while ((!isdigit(endch)) && endch != '-' && endch != EOF) endch = getchar(); if (endch == '-') flag = 1, endch = getchar(); d = endch & 15; while (isdigit(endch = getchar())) d = (d << 3) + (d << 1) + (endch & 15); if (flag) d = -d; return *this; } template <typename Int> inline Int get() { bool flag = 0; endch = getchar(); while ((!isdigit(endch)) && endch != '-' && endch != EOF) endch = getchar(); if (endch == '-') flag = 1, endch = getchar(); Int d = endch & 15; while (isdigit(endch = getchar())) d = (d << 3) + (d << 1) + (endch & 15); if (flag) d = -d; return d; } } read; struct Writer { Writer& operator<<(io_flags f) { if (f & flush_stdout) fflush(stdout); if (f & flush_stderr) fflush(stderr); return *this; } Writer& operator<<(const char* ch) { while (*ch) putchar(*(ch++)); return *this; } Writer& operator<<(const char ch) { putchar(ch); return *this; } template <typename Int> Writer& operator<<(Int x) { static char buffer[33]; static int top = 0; if (!x) { putchar('0'); return *this; } if (x < 0) putchar('-'), x = ~x + 1; while (x) { buffer[++top] = '0' | (x % 10); x /= 10; } while (top) putchar(buffer[top--]); return *this; } inline void operator()(double val, int eps_digit = 6, char endch = '\0', number_type_flags flg = output_double_faster) { if (flg & output_double_stable) { static char output_format[10]; sprintf(output_format, "%%.%dlf", eps_digit); printf(output_format, val); } else if (flg & output_double_faster) { if (val < 0) { putchar('-'); val = -val; } double eps_number = 0.5; for (int i = 1; i <= eps_digit; i++) eps_number /= 10; val += eps_number; (*this) << (long long)val; val -= (long long)val; if (eps_digit) putchar('.'); while (eps_digit--) { val *= 10; putchar((int)val | '0'); val -= (int)val; } } else { (*this) << '1'; if (eps_digit) { (*this) << ".E"; for (int i = 2; i <= eps_digit; i++) (*this) << '0'; } } if (endch) putchar(endch); } } write; } // namespace Fastio using namespace Fastio; namespace File_IO { void init_IO(const char* file_name) { char buff[107]; sprintf(buff, "%s.in", file_name); freopen(buff, "r", stdin); sprintf(buff, "%s.out", file_name); freopen(buff, "w", stdout); } } // namespace File_IO const int N = 700 + 3, DigByte = 100000000; struct Bint { unsigned long long atom[17]; int len; Bint(int number = 0) : len(0) { while (number) { atom[len++] = number % DigByte; number /= DigByte; } } Bint operator*(const Bint& b) const { Bint ret; memset(ret.atom, 0, sizeof(ret.atom)); ret.len = len + b.len; for (int i = 0; i < len; i++) for (int j = 0; j < b.len; j++) ret.atom[i + j] += atom[i] * b.atom[j]; for (int i = 1; i < ret.len; i++) { ret.atom[i] += ret.atom[i - 1] / DigByte; ret.atom[i - 1] %= DigByte; } if (!ret.atom[ret.len - 1]) --ret.len; return ret; } bool operator<(const Bint& b) const { if (len ^ b.len) return len < b.len; for (int i = len - 1; i >= 0; i--) if (atom[i] ^ b.atom[i]) return atom[i] < b.atom[i]; return false; } void print(char endch = '\0') const { if (len <= 0) { putchar('0'); if (endch) putchar(endch); return; } printf("%llu", atom[len - 1]); int i = len - 2; while (i >= 0) printf("%08llu", atom[i--]); if (endch) putchar(endch); } }; int n; Bint f[N][N], g[N]; vector<int> G[N]; int siz[N]; void sol(int u, int fa) { f[u][1] = f[u][0] = siz[u] = 1; for (size_t eid = 0; eid < G[u].size(); eid++) { int v = G[u][eid]; if (v == fa) continue; sol(v, u); for (int i = 0; i <= siz[u] + siz[v]; i++) g[i] = 0; for (int i = 0; i <= siz[v]; i++) for (int j = 0; j <= siz[u]; j++) g[i + j] = max(g[i + j], f[u][j] * f[v][i]); siz[u] += siz[v]; for (int i = 0; i <= siz[u]; i++) f[u][i] = g[i]; } for (int i = 1; i <= siz[u]; i++) f[u][0] = max(f[u][0], f[u][i] * i); } signed main() { read >> n; for (int i = 1, u, v; i < n; i++) { read >> u >> v; G[u].push_back(v); G[v].push_back(u); } sol(1, -1); f[1][0].print('\n'); return 0; } ```
### Prompt In cpp, your task is to solve the following problem: Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≀ n, k ≀ 100; 1 ≀ d ≀ k). Output Print a single integer β€” the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int mod = 1e9 + 7; void add(int &a, int val) { a += val; a %= mod; } signed main() { int n, k, d; cin >> n >> k >> d; vector<vector<int>> dp(n + 1, vector<int>(2, 0)); dp[0][0] = 1; dp[0][1] = 0; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= k; ++j) { if (j <= i) { if (j < d) { add(dp[i][0], dp[i - j][0]); add(dp[i][1], dp[i - j][1]); } else { add(dp[i][1], dp[i - j][1]); add(dp[i][1], dp[i - j][0]); } } } } cout << dp[n][1]; return 0; } ```
### Prompt Develop a solution in cpp to the problem described below: Santa has to send presents to the kids. He has a large stack of n presents, numbered from 1 to n; the topmost present has number a_1, the next present is a_2, and so on; the bottom present has number a_n. All numbers are distinct. Santa has a list of m distinct presents he has to send: b_1, b_2, ..., b_m. He will send them in the order they appear in the list. To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are k presents above the present Santa wants to send, it takes him 2k + 1 seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way). What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way. Your program has to answer t different test cases. Input The first line contains one integer t (1 ≀ t ≀ 100) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers n and m (1 ≀ m ≀ n ≀ 10^5) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ n, all a_i are unique) β€” the order of presents in the stack. The third line contains m integers b_1, b_2, ..., b_m (1 ≀ b_i ≀ n, all b_i are unique) β€” the ordered list of presents Santa has to send. The sum of n over all test cases does not exceed 10^5. Output For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack. Example Input 2 3 3 3 1 2 3 2 1 7 2 2 1 7 3 4 5 6 3 1 Output 5 8 ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long MOD = 1000000007; long long power(long long x, long long n, long long mod) { if (n == 0) { return 1; } long long temp = power(x, n / 2, mod); if (n % 2 == 1) { return (x * temp * temp) % mod; } else { return (temp * temp) % mod; } } long long abs(long long a, long long b) { if (a > b) { return a - b; } return b - a; } long long n; long long countt = 0; long long binary(long long n) { long long sum = 0; if (n <= 0) { return 10000000; } while (n > 0) { if (n % 2 == 1) { sum++; } n /= 2; } return sum; } vector<long long> primes; int main(int argc, const char* argv[]) { ios_base::sync_with_stdio(0); cin.tie(0); long long t; cin >> t; long long n, m; vector<long long> stackk; vector<long long> needed; long long temp; set<long long> passed; long long sol; long long biggest; for (long long i = 0; i <= t - 1; i++) { cin >> n >> m; stackk.clear(); needed.clear(); passed.clear(); sol = 0; biggest = -1; for (long long j = 0; j <= n - 1; j++) { cin >> temp; stackk.push_back(temp); } for (long long j = 0; j <= m - 1; j++) { cin >> temp; needed.push_back(temp); } for (long long j = 0; j <= m - 1; j++) { if (passed.count(needed[j])) { sol++; continue; } for (long long k = biggest; k <= n - 1; k++) { passed.insert(stackk[k]); if (needed[j] == stackk[k]) { sol += 2 * (k - j) + 1; biggest = k; break; } } } cout << sol << endl; } return 0; } ```
### Prompt Please provide a cpp coded solution to the problem described below: Let's denote d(n) as the number of divisors of a positive integer n. You are given three integers a, b and c. Your task is to calculate the following sum: <image> Find the sum modulo 1073741824 (230). Input The first line contains three space-separated integers a, b and c (1 ≀ a, b, c ≀ 2000). Output Print a single integer β€” the required sum modulo 1073741824 (230). Examples Input 2 2 2 Output 20 Input 4 4 4 Output 328 Input 10 10 10 Output 11536 Note For the first example. * d(1Β·1Β·1) = d(1) = 1; * d(1Β·1Β·2) = d(2) = 2; * d(1Β·2Β·1) = d(2) = 2; * d(1Β·2Β·2) = d(4) = 3; * d(2Β·1Β·1) = d(2) = 2; * d(2Β·1Β·2) = d(4) = 3; * d(2Β·2Β·1) = d(4) = 3; * d(2Β·2Β·2) = d(8) = 4. So the result is 1 + 2 + 2 + 3 + 2 + 3 + 3 + 4 = 20. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXSIZE = 10000020; int bufpos; char buf[MAXSIZE]; void init() { buf[fread(buf, 1, MAXSIZE, stdin)] = '\0'; bufpos = 0; } int readint() { int val = 0; for (; !isdigit(buf[bufpos]); bufpos++) ; for (; isdigit(buf[bufpos]); bufpos++) val = val * 10 + buf[bufpos] - '0'; return val; } char readchar() { for (; isspace(buf[bufpos]); bufpos++) ; return buf[bufpos++]; } int readstr(char* s) { int cur = 0; for (; isspace(buf[bufpos]); bufpos++) ; for (; !isspace(buf[bufpos]); bufpos++) s[cur++] = buf[bufpos]; s[cur] = '\0'; return cur; } int mu[5002], f[5002], c[5002]; void sieve(int n) { mu[1] = 1; for (int i = 1; i <= n; i++) { f[i]++; for (int j = i * 2; j <= n; j += i) mu[j] -= mu[i], f[j]++; } for (int i = 1; i <= n; i++) f[i] += f[i - 1]; } int lcm__[5002][5002]; int deg[5002]; vector<int> a[5002]; int main() { init(); int x = readint(), y = readint(), z = readint(), n = max(max(x, y), z); sieve(n); for (int i = 1; i <= n; i++) { lcm__[i][0] = lcm__[0][i] = i; for (int j = 1; j <= i; j++) lcm__[i][j] = lcm__[j][i] = lcm__[j][i % j]; } for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) lcm__[i][j] = i * j / lcm__[i][j]; int ans = 0; for (int i = 1; i <= n; i++) for (int j = i + 1; j <= n; j++) if (lcm__[i][j] <= n) { a[i].push_back(j); a[j].push_back(i); } for (int i = 1; i <= n; i++) { int u = i; for (int j = 0; j < a[i].size(); j++) { int v = a[i][j]; if (a[v].size() > a[i].size() || (a[v].size() == a[i].size() && i < v)) { for (int k = 0; k < a[i].size(); k++) { int w = a[i][k]; if (lcm__[v][w] <= n && w != v) { ans += mu[w] * mu[u] * mu[v] * (f[x / lcm__[u][v]] * f[y / lcm__[v][w]] * f[z / lcm__[u][w]] + f[x / lcm__[u][v]] * f[y / lcm__[u][w]] * f[z / lcm__[v][w]]); } } } } } for (int i = 1; i <= n; i++) { for (int j = 0; j < a[i].size(); j++) { int v = a[i][j], lc = lcm__[i][v]; ans += mu[i] * mu[i] * mu[v] * (f[x / i] * f[y / lc] * f[z / lc] + f[x / lc] * f[y / i] * f[z / lc] + f[x / lc] * f[y / lc] * f[z / i]); } ans += mu[i] * mu[i] * mu[i] * f[x / i] * f[y / i] * f[z / i]; } printf("%d", ans & ((1 << 30) - 1)); } ```
### Prompt Create a solution in Cpp for the following problem: Given is a string S of length N-1. Each character in S is `<` or `>`. A sequence of N non-negative integers, a_1,a_2,\cdots,a_N, is said to be good when the following condition is satisfied for all i (1 \leq i \leq N-1): * If S_i= `<`: a_i<a_{i+1} * If S_i= `>`: a_i>a_{i+1} Find the minimum possible sum of the elements of a good sequence of N non-negative integers. Constraints * 2 \leq N \leq 5 \times 10^5 * S is a string of length N-1 consisting of `<` and `>`. Input Input is given from Standard Input in the following format: S Output Find the minimum possible sum of the elements of a good sequence of N non-negative integers. Examples Input <>> Output 3 Input <>>><<><<<<<>>>< Output 28 ### Response ```cpp #include <bits/stdc++.h> #define N 500005 using namespace std; char s[N]; int l[N],r[N]; int main(){ scanf("%s",s+1); int n=strlen(s+1); long long ans=0; for(int i=1;i<=n;i++){ if(s[i]=='<') l[i]=l[i-1]+1; } for(int i=n;i>=1;i--){ if(s[i]=='>') r[i]=r[i+1]+1; } for(int i=1;i<=n+1;i++){ ans+=max(l[i-1],r[i]); } cout<<ans<<endl; } ```
### Prompt Your task is to create a CPP solution to the following problem: You are given an integer a that consists of n digits. You are also given a sequence of digits s of length m. The digit in position j (1 ≀ j ≀ m) of sequence s means that you can choose an arbitrary position i (1 ≀ i ≀ n) in a and replace the digit in the chosen position i with sj. Each element in the sequence s can participate in no more than one replacing operation. Your task is to perform such sequence of replacements, that the given number a gets maximum value. You are allowed to use not all elements from s. Input The first line contains positive integer a. Its length n is positive and doesn't exceed 105. The second line contains sequence of digits s. Its length m is positive and doesn't exceed 105. The digits in the sequence s are written consecutively without any separators. The given number a doesn't contain leading zeroes. Output Print the maximum value that can be obtained from a after a series of replacements. You are allowed to use not all elements from s. The printed number shouldn't contain any leading zeroes. Examples Input 1024 010 Output 1124 Input 987 1234567 Output 987 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { string a, s; char max; vector<char> v; cin >> a >> s; int i, j, sa, ss; sa = a.size(); ss = s.size(); for (i = 0; i < ss; i++) v.push_back(s[i]); sort(v.begin(), v.end()); for (i = 0; i < sa; i++) { max = v[v.size() - 1]; if (a[i] < max) { a[i] = max; v.pop_back(); } } cout << a << endl; return 0; } ```
### Prompt Construct a CPP code solution to the problem outlined: Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for a rubles, a pack of two copybooks for b rubles, and a pack of three copybooks for c rubles. Alyona already has n copybooks. What is the minimum amount of rubles she should pay to buy such number of copybooks k that n + k is divisible by 4? There are infinitely many packs of any type in the shop. Alyona can buy packs of different type in the same purchase. Input The only line contains 4 integers n, a, b, c (1 ≀ n, a, b, c ≀ 109). Output Print the minimum amount of rubles she should pay to buy such number of copybooks k that n + k is divisible by 4. Examples Input 1 1 3 4 Output 3 Input 6 2 1 1 Output 1 Input 4 4 4 4 Output 0 Input 999999999 1000000000 1000000000 1000000000 Output 1000000000 Note In the first example Alyona can buy 3 packs of 1 copybook for 3a = 3 rubles in total. After that she will have 4 copybooks which she can split between the subjects equally. In the second example Alyuna can buy a pack of 2 copybooks for b = 1 ruble. She will have 8 copybooks in total. In the third example Alyona can split the copybooks she already has between the 4 subject equally, so she doesn't need to buy anything. In the fourth example Alyona should buy one pack of one copybook. ### Response ```cpp #include <bits/stdc++.h> long long n, a, b, c, ans; using namespace std; int main(void) { cin >> n >> a >> b >> c; ans = -1; if (n % 4 == 0) ans = 0; else { for (long long i = 0; i < 30; i++) for (long long j = 0; j < 30; j++) for (long long k = 0; k < 30; k++) if ((n + i * 1 + j * 2 + k * 3) % 4 == 0) if (ans == -1 || ans > i * a + j * b + k * c) ans = i * a + j * b + k * c; } cout << ans << endl; return 0; } ```
### Prompt Please provide a CPP coded solution to the problem described below: You are given three strings a, b and c of the same length n. The strings consist of lowercase English letters only. The i-th letter of a is a_i, the i-th letter of b is b_i, the i-th letter of c is c_i. For every i (1 ≀ i ≀ n) you must swap (i.e. exchange) c_i with either a_i or b_i. So in total you'll perform exactly n swap operations, each of them either c_i ↔ a_i or c_i ↔ b_i (i iterates over all integers between 1 and n, inclusive). For example, if a is "code", b is "true", and c is "help", you can make c equal to "crue" taking the 1-st and the 4-th letters from a and the others from b. In this way a becomes "hodp" and b becomes "tele". Is it possible that after these swaps the string a becomes exactly the same as the string b? Input The input consists of multiple test cases. The first line 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 a string of lowercase English letters a. The second line of each test case contains a string of lowercase English letters b. The third line of each test case contains a string of lowercase English letters c. It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100. Output Print t lines with answers for all test cases. For each test case: If it is possible to make string a equal to string b print "YES" (without quotes), otherwise print "NO" (without quotes). You can print either lowercase or uppercase letters in the answers. Example Input 4 aaa bbb ccc abc bca bca aabb bbaa baba imi mii iim Output NO YES YES NO Note In the first test case, it is impossible to do the swaps so that string a becomes exactly the same as string b. In the second test case, you should swap c_i with a_i for all possible i. After the swaps a becomes "bca", b becomes "bca" and c becomes "abc". Here the strings a and b are equal. In the third test case, you should swap c_1 with a_1, c_2 with b_2, c_3 with b_3 and c_4 with a_4. Then string a becomes "baba", string b becomes "baba" and string c becomes "abab". Here the strings a and b are equal. In the fourth test case, it is impossible to do the swaps so that string a becomes exactly the same as string b. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { string a, b, c; cin >> a >> b >> c; int i, n = a.length(); int check = 1; for (i = 0; i < n; i++) { if (a[i] != b[i]) { if (a[i] == c[i] || b[i] == c[i]) continue; else { check = 0; break; } } else if (a[i] == b[i]) { if (a[i] == c[i]) continue; else { check = 0; break; } } } if (check == 0) cout << "NO" << endl; else cout << "YES" << endl; } return 0; } ```
### Prompt Your task is to create a CPP solution to the following problem: With your help, Heidi has prepared a plan of trap placement and defence. Yet suddenly, the Doctor popped out of the TARDIS and told her that he had spied on the Daleks' preparations, and there is more of them than ever. Desperate times require desperate measures, so Heidi is going to risk meeting with the Daleks and she will consider placing a trap along any Corridor. This means she needs your help again in calculating E_{max}(c) – the largest e ≀ 10^9 such that if we changed the energy requirement of c to e, then the Daleks might use c in their invasion – but this time for all Time Corridors. Input First line: number n of destinations, number m of corridors (2 ≀ n ≀ 10^5, n - 1 ≀ m ≀ 10^6). The next m lines: destinations a, b and energy e (1 ≀ a, b ≀ n, a β‰  b, 0 ≀ e ≀ 10^9). No pair \\{a, b\} will repeat. The graph is guaranteed to be connected. It is not guaranteed that all energy requirements e are distinct, or that the minimum spanning tree is unique. Output Output m lines, each containing one integer: E_{max}(c_i) for the i-th Corridor c_i from the input. Example Input 3 3 1 2 8 2 3 3 3 1 4 Output 4 8 8 ### Response ```cpp #include <bits/stdc++.h> using namespace std; inline long long read() { long long x = 0, f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -1; ch = getchar(); } while (isdigit(ch)) x = x * 10 + (ch ^ 48), ch = getchar(); return x * f; } inline bool char_read() { char ch = getchar(); while (!isalpha(ch)) return -1; return ch == 'B' ? 0 : 1; } void Write(long long x) { if (x < 0) putchar('-'), x = -x; if (x > 9) Write(x / 10); putchar(x % 10 + 48); } inline void writes(long long x) { Write(x), putchar(' '); } inline void Writes(long long x) { Write(x), putchar('\n'); } int n, m; int fa[205000], fa_e[205000], size[205000]; int ans[2006000]; bool vis[2006000]; struct node { int x, y, z, id; } E[2006000]; int head[205000], deg[205000], nxt[2006000], ver[2006000], edge[2006000], num[2006000], tot = 1; int f[205000][22], maxn[205000][22], dep[205000]; queue<int> q; void add(int x, int y, int z, int id) { ver[++tot] = y, nxt[tot] = head[x], head[x] = tot, edge[tot] = z, num[tot] = id; } bool cmp(const node &a, const node &b) { return a.z < b.z; } bool ccmp(const node &a, const node &b) { return a.id < b.id; } void Start() { for (int i = 1; i <= n; ++i) fa[i] = i; } int Get(int x) { return x == fa[x] ? x : fa[x] = Get(fa[x]); } void Merge(int x, int y) { x = Get(x), y = Get(y), fa[x] = y; } int GetMax(int x, int y) { int tmax = 0; if (dep[x] < dep[y]) swap(x, y); for (int i = 22 - 1; i >= 0; --i) if (dep[f[x][i]] >= dep[y]) tmax = max(maxn[x][i], tmax), x = f[x][i]; if (x == y) return tmax; for (int i = 22 - 1; i >= 0; --i) if (f[x][i] != f[y][i]) tmax = max(maxn[x][i], tmax), tmax = max(maxn[y][i], tmax), x = f[x][i], y = f[y][i]; tmax = max(tmax, maxn[x][0]), tmax = max(tmax, maxn[y][0]); return tmax; } int Lca(int x, int y) { if (dep[x] < dep[y]) swap(x, y); for (int i = 22 - 1; i >= 0; --i) if (dep[f[x][i]] >= dep[y]) x = f[x][i]; if (x == y) return x; for (int i = 22 - 1; i >= 0; --i) if (f[x][i] != f[y][i]) x = f[x][i], y = f[y][i]; return f[x][0]; } void dfs(int x, int in_edge) { fa_e[x] = in_edge; for (int i = head[x]; i; i = nxt[i]) { int y = ver[i]; if (y == f[x][0]) continue; dep[y] = dep[x] + 1, f[y][0] = x, maxn[y][0] = edge[i]; for (int j = 1; j < 22; ++j) f[y][j] = f[f[y][j - 1]][j - 1], maxn[y][j] = max(maxn[y][j - 1], maxn[f[y][j - 1]][j - 1]); dfs(y, i); } } signed main() { n = read(), m = read(); for (int i = 1, x, y, z; i <= m; ++i) x = read(), y = read(), z = read(), E[i] = (node){x, y, z, i}; sort(E + 1, E + 1 + m, cmp); Start(); for (int i = 1; i <= m; ++i) { int x = E[i].x, y = E[i].y, z = E[i].z, id = E[i].id; if (Get(x) == Get(y)) continue; Merge(x, y), ans[id] = 1000000000; add(x, y, z, i), add(y, x, z, i); } dep[1] = 1, dfs(1, 0); Start(); for (int i = 1; i <= m; ++i) { int x = E[i].x, y = E[i].y, z = E[i].z, id = E[i].id; if (ans[id]) continue; int lca = Lca(x, y); while (1) { x = Get(x); if (dep[x] <= dep[lca]) break; ans[E[num[fa_e[x]]].id] = z; Merge(x, f[x][0]); } while (1) { y = Get(y); if (dep[y] <= dep[lca]) break; ans[E[num[fa_e[y]]].id] = z; Merge(y, f[y][0]); } } sort(E + 1, E + 1 + m, ccmp); for (int i = 1; i <= m; ++i) { int x = E[i].x, y = E[i].y, z = E[i].z, id = E[i].id; if (ans[id]) Writes(ans[id]); else Writes(GetMax(x, y)); } return 0; } ```
### Prompt Your challenge is to write a Cpp solution to the following problem: In this task you need to process a set of stock exchange orders and use them to create order book. An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price pi, direction di β€” buy or sell, and integer qi. This means that the participant is ready to buy or sell qi stocks at price pi for one stock. A value qi is also known as a volume of an order. All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders. An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order. An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book. You are given n stock exhange orders. Your task is to print order book of depth s for these orders. Input The input starts with two positive integers n and s (1 ≀ n ≀ 1000, 1 ≀ s ≀ 50), the number of orders and the book depth. Next n lines contains a letter di (either 'B' or 'S'), an integer pi (0 ≀ pi ≀ 105) and an integer qi (1 ≀ qi ≀ 104) β€” direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order. Output Print no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input. Examples Input 6 2 B 10 3 S 50 2 S 40 1 S 50 6 B 20 4 B 25 10 Output S 50 8 S 40 1 B 25 10 B 20 4 Note Denote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two sell orders (50, 8), (40, 1) in the sample. You need to print no more than two best orders for each direction, so you shouldn't print the order (10 3) having the worst price among buy orders. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int by[100005], sl[100005]; int main() { int n, m, i, j, p, k, q; cin >> n >> m; for (i = 0; i < n; i++) { char ch; cin >> ch >> p >> q; if (ch == 'B') by[p] += q; else sl[p] += q; } int bm = m, sm = m; vector<int> vt; for (i = 0; i <= 100000; i++) { if (sl[i] > 0) { sm--; vt.push_back(i); } if (sm == 0) break; } for (i = vt.size() - 1; i >= 0; i--) { cout << "S " << vt[i] << " " << sl[vt[i]] << "\n"; } for (i = 100000; i >= 0; i--) { if (by[i] > 0) { bm--; cout << "B " << i << " " << by[i] << "\n"; } if (bm == 0) break; } return 0; } ```
### Prompt Please provide a CPP coded solution to the problem described below: You are given a string s consisting only of first 20 lowercase Latin letters ('a', 'b', ..., 't'). Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top". You can perform the following operation no more than once: choose some substring s[l; r] and reverse it (i.e. the string s_l s_{l + 1} ... s_r becomes s_r s_{r - 1} ... s_l). Your goal is to maximize the length of the maximum substring of s consisting of distinct (i.e. unique) characters. The string consists of distinct characters if no character in this string appears more than once. For example, strings "abcde", "arctg" and "minecraft" consist of distinct characters but strings "codeforces", "abacaba" do not consist of distinct characters. Input The only line of the input contains one string s consisting of no more than 10^6 characters 'a', 'b', ..., 't' (first 20 lowercase Latin letters). Output Print one integer β€” the maximum possible length of the maximum substring of s consisting of distinct characters after reversing no more than one its substring. Examples Input abacaba Output 3 Input abcdecdf Output 6 Input aabbcc Output 3 Input abcdeefc Output 6 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long double PI = acos(-1.0); int f[1 << 20]; int dp[1 << 20]; void solve() { string s; cin >> s; for (int i = 0; i < (int)s.size(); ++i) { int mask = 0; for (int j = i; j >= max(0, i - 19); --j) { if ((mask >> (s[j] - 'a')) & 1) { break; } else mask |= (1 << (s[j] - 'a')); f[mask]++; } } for (int i = 0; i < 1 << 20; ++i) { if (f[i]) { dp[i] = __builtin_popcount(i); } } for (int j = 0; j < 20; ++j) { for (int i = 0; i < 1 << 20; ++i) { if ((i >> j) & 1) { dp[i] = max(dp[i], dp[i ^ (1 << j)]); } } } int ans = 0; for (int i = 0; i < 1 << 20; ++i) { if (f[i]) ans = max(ans, __builtin_popcount(i) + dp[((1 << 20) - 1) ^ i]); } cout << ans << '\n'; } signed main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t = 1; while (t--) { solve(); } return 0; } ```
### Prompt Develop a solution in CPP to the problem described below: This story is happening in a town named BubbleLand. There are n houses in BubbleLand. In each of these n houses lives a boy or a girl. People there really love numbers and everyone has their favorite number f. That means that the boy or girl that lives in the i-th house has favorite number equal to fi. The houses are numerated with numbers 1 to n. The houses are connected with n - 1 bidirectional roads and you can travel from any house to any other house in the town. There is exactly one path between every pair of houses. A new dating had agency opened their offices in this mysterious town and the citizens were very excited. They immediately sent q questions to the agency and each question was of the following format: * a b β€” asking how many ways are there to choose a couple (boy and girl) that have the same favorite number and live in one of the houses on the unique path from house a to house b. Help the dating agency to answer the questions and grow their business. Input The first line contains an integer n (1 ≀ n ≀ 105), the number of houses in the town. The second line contains n integers, where the i-th number is 1 if a boy lives in the i-th house or 0 if a girl lives in i-th house. The third line contains n integers, where the i-th number represents the favorite number fi (1 ≀ fi ≀ 109) of the girl or boy that lives in the i-th house. The next n - 1 lines contain information about the roads and the i-th line contains two integers ai and bi (1 ≀ ai, bi ≀ n) which means that there exists road between those two houses. It is guaranteed that it's possible to reach any house from any other. The following line contains an integer q (1 ≀ q ≀ 105), the number of queries. Each of the following q lines represents a question and consists of two integers a and b (1 ≀ a, b ≀ n). Output For each of the q questions output a single number, the answer to the citizens question. Example Input 7 1 0 0 1 0 1 0 9 2 9 2 2 9 9 2 6 1 2 4 2 6 5 3 6 7 4 2 1 3 7 5 Output 2 3 Note In the first question from house 1 to house 3, the potential couples are (1, 3) and (6, 3). In the second question from house 7 to house 5, the potential couples are (7, 6), (4, 2) and (4, 5). ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int inf = 1e9; const long long INF = 1e18; const long double PI = acos(-1); const long double EPS = 1e-9; int mod = 998244353; const int MOD7 = 1000000007; const int MOD9 = 1000000009; const int MAXN = 2e5 + 228; int tin[MAXN]; int cnt[MAXN][2]; int tout[MAXN]; int tl = 0; vector<int> g[MAXN]; const int lgg = 17; int up[MAXN][lgg]; int order[MAXN]; void dfs(int v, int p) { up[v][0] = p; order[tl] = v; tin[v] = tl++; for (int i = 1; i < lgg; ++i) up[v][i] = up[up[v][i - 1]][i - 1]; for (int i : g[v]) { if (i != p) { dfs(i, v); } } order[tl] = v; tout[v] = tl++; } bool pp(int a, int b) { return tin[a] <= tin[b] && tout[a] >= tout[b]; } int lca(int a, int b) { if (pp(a, b)) return a; if (pp(b, a)) return b; for (int i = lgg - 1; i >= 0; --i) if (!pp(up[a][i], b)) a = up[a][i]; return up[a][0]; } int f[MAXN]; int tp[MAXN]; int n; int cum[MAXN]; long long ans = 0; long long answers[MAXN]; void del(int x, int tp) { ans -= cnt[x][tp ^ 1]; cnt[x][tp]--; } void add(int x, int tp) { ans += cnt[x][tp ^ 1]; cnt[x][tp]++; } void change(int v) { cum[v]++; if (cum[v] % 2) { add(f[v], tp[v]); } else { del(f[v], tp[v]); } } const int bl = 400; struct query { int l, r, i, pt; }; bool cmp(query a, query b) { if (a.l / bl == b.l / bl) { if ((a.l / bl) % 2) return a.r < b.r; return a.r > b.r; } return a.l < b.l; } vector<query> queries; signed main() { ios_base::sync_with_stdio(0); cout.tie(0); cin.tie(0); srand(time(NULL)); cin >> n; for (int i = 1; i <= n; ++i) cin >> tp[i]; for (int i = 1; i <= n; ++i) cin >> f[i]; vector<int> tf; for (int i = 1; i <= n; ++i) tf.push_back(f[i]); sort((tf).begin(), (tf).end()); (tf).resize(unique((tf).begin(), (tf).end()) - tf.begin()); ; for (int i = 1; i <= n; ++i) { f[i] = lower_bound((tf).begin(), (tf).end(), f[i]) - tf.begin(); } for (int i = 0; i < n - 1; ++i) { int a, b; cin >> a >> b; g[a].push_back(b); g[b].push_back(a); } dfs(1, 1); int q; cin >> q; for (int i = 0; i < q; ++i) { int a, b; cin >> a >> b; int x = lca(a, b); if (tin[a] > tin[b]) swap(a, b); if (x == a) { queries.push_back({tin[x], tin[b], i, 0}); continue; } queries.push_back({tout[a], tin[b], i, x}); } sort((queries).begin(), (queries).end(), cmp); int l = 0, r = -1; for (auto i : queries) { while (l < i.l) change(order[l++]); while (l > i.l) change(order[--l]); while (r < i.r) change(order[++r]); while (r > i.r) change(order[r--]); if (i.pt) change(i.pt); answers[i.i] = ans; if (i.pt) change(i.pt); } for (int i = 0; i < q; ++i) { cout << answers[i] << '\n'; } } ```
### Prompt In cpp, your task is to solve the following problem: Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process. There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems. You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day. Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days. Input The first line of input contains three integers n, m and k (1 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ k ≀ 106). The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≀ di ≀ 106, 0 ≀ fi ≀ n, 0 ≀ ti ≀ n, 1 ≀ ci ≀ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost. Output Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities. If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes). Examples Input 2 6 5 1 1 0 5000 3 2 0 5500 2 2 0 6000 15 0 2 9000 9 0 1 7000 8 0 2 6500 Output 24500 Input 2 4 5 1 2 0 5000 2 1 0 4500 2 1 0 3000 8 0 1 6000 Output -1 Note The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more. In the second sample it is impossible to send jury member from city 2 back home from Metropolis. ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct node { int d, f, t; long long c; } a[100005]; int cmp(node a, node b) { return a.d < b.d; } long long INF = 0x3f3f3f3f3f3f; long long cost[100005]; int vis[100005]; int cnt1[1000006]; int cnt2[1000006]; long long sum2[1000006]; long long sum1[1000006]; int main() { int n, m, k; memset(cnt1, 0, sizeof(cnt1)); memset(cnt2, 0, sizeof(cnt2)); memset(vis, 0, sizeof(vis)); memset(cost, INF, sizeof(cost)); memset(sum1, 0, sizeof(sum1)); memset(sum2, 0, sizeof(sum2)); scanf("%d%d%d", &n, &m, &k); for (int i = 1; i <= m; i++) { scanf("%d%d%d%I64d", &a[i].d, &a[i].f, &a[i].t, &a[i].c); } sort(a + 1, a + 1 + m, cmp); int pre = 0; for (int i = 1; i <= m; i++) { if (a[i].f == 0) continue; int f = a[i].f; int d = a[i].d; sum1[d] = sum1[pre]; cnt1[d] = cnt1[pre]; if (cost[f] > a[i].c) { if (vis[f] == 1) sum1[d] = sum1[d] - cost[f] + a[i].c; else sum1[d] += a[i].c; cost[f] = a[i].c; if (vis[f] == 0) { cnt1[d]++; vis[f] = 1; } } pre = d; } for (int i = 1; i <= 1000000; i++) { if (cnt1[i] == 0) cnt1[i] = cnt1[i - 1]; if (sum1[i] == 0) sum1[i] = sum1[i - 1]; } memset(vis, 0, sizeof(vis)); pre = 1000000; memset(cost, INF, sizeof(cost)); for (int i = m; i >= 1; i--) { if (a[i].t == 0) continue; int d = a[i].d; int t = a[i].t; sum2[d] = sum2[pre]; cnt2[d] = cnt2[pre]; if (cost[t] > a[i].c) { if (vis[t] == 1) sum2[d] = sum2[d] - cost[t] + a[i].c; else sum2[d] += a[i].c; cost[t] = a[i].c; if (vis[t] == 0) { cnt2[d]++; vis[t] = 1; } } pre = d; } for (int i = 1000000; i >= 0; i--) { if (cnt2[i] == 0) cnt2[i] = cnt2[i + 1]; if (sum2[i] == 0) sum2[i] = sum2[i + 1]; } long long ans = INF; for (int i = 1; i <= 1000000; i++) { if (i + k + 1 > 1000000) break; if (cnt1[i] == n && cnt2[i + k + 1] == n) ans = min(ans, (long long)sum1[i] + sum2[i + k + 1]); } if (ans == INF) { printf("-1\n"); return 0; } printf("%I64d\n", ans); return 0; } ```
### Prompt Please provide a CPP coded solution to the problem described below: There are N people standing in a queue from west to east. Given is a string S of length N representing the directions of the people. The i-th person from the west is facing west if the i-th character of S is `L`, and east if that character of S is `R`. A person is happy if the person in front of him/her is facing the same direction. If no person is standing in front of a person, however, he/she is not happy. You can perform the following operation any number of times between 0 and K (inclusive): Operation: Choose integers l and r such that 1 \leq l \leq r \leq N, and rotate by 180 degrees the part of the queue: the l-th, (l+1)-th, ..., r-th persons. That is, for each i = 0, 1, ..., r-l, the (l + i)-th person from the west will stand the (r - i)-th from the west after the operation, facing east if he/she is facing west now, and vice versa. What is the maximum possible number of happy people you can have? Constraints * N is an integer satisfying 1 \leq N \leq 10^5. * K is an integer satisfying 1 \leq K \leq 10^5. * |S| = N * Each character of S is `L` or `R`. Input Input is given from Standard Input in the following format: N K S Output Print the maximum possible number of happy people after at most K operations. Examples Input 6 1 LRLRRL Output 3 Input 13 3 LRRLRLRRLRLLR Output 9 Input 10 1 LLLLLRRRRR Output 9 Input 9 2 RRRLRLRLL Output 7 ### Response ```cpp #include<iostream> using namespace std; int main(){ int n,k; cin>>n>>k; string s; cin>>s; int ans=0; for(int i=1;i<s.size();i++) ans+=s[i]==s[i-1]; cout<<min(2*k+ans,n-1)<<endl; return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: Consider a [billiard table](https://en.wikipedia.org/wiki/Billiard_table) of rectangular size n Γ— m with four pockets. Let's introduce a coordinate system with the origin at the lower left corner (see the picture). <image> There is one ball at the point (x, y) currently. Max comes to the table and strikes the ball. The ball starts moving along a line that is parallel to one of the axes or that makes a 45^{\circ} angle with them. We will assume that: 1. the angles between the directions of the ball before and after a collision with a side are equal, 2. the ball moves indefinitely long, it only stops when it falls into a pocket, 3. the ball can be considered as a point, it falls into a pocket if and only if its coordinates coincide with one of the pockets, 4. initially the ball is not in a pocket. Note that the ball can move along some side, in this case the ball will just fall into the pocket at the end of the side. Your task is to determine whether the ball will fall into a pocket eventually, and if yes, which of the four pockets it will be. Input The only line contains 6 integers n, m, x, y, v_x, v_y (1 ≀ n, m ≀ 10^9, 0 ≀ x ≀ n; 0 ≀ y ≀ m; -1 ≀ v_x, v_y ≀ 1; (v_x, v_y) β‰  (0, 0)) β€” the width of the table, the length of the table, the x-coordinate of the initial position of the ball, the y-coordinate of the initial position of the ball, the x-component of its initial speed and the y-component of its initial speed, respectively. It is guaranteed that the ball is not initially in a pocket. Output Print the coordinates of the pocket the ball will fall into, or -1 if the ball will move indefinitely. Examples Input 4 3 2 2 -1 1 Output 0 0 Input 4 4 2 0 1 1 Output -1 Input 10 10 10 1 -1 0 Output -1 Note The first sample: <image> The second sample: <image> In the third sample the ball will never change its y coordinate, so the ball will never fall into a pocket. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1e5 + 7; const int inf = 0x3f3f3f3f; const long long INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-8; const double PI = acos(-1); template <class T, class S> inline void add(T& a, S b) { a += b; if (a >= mod) a -= mod; } template <class T, class S> inline void sub(T& a, S b) { a -= b; if (a < 0) a += mod; } template <class T, class S> inline bool chkmax(T& a, S b) { return a < b ? a = b, true : false; } template <class T, class S> inline bool chkmin(T& a, S b) { return a > b ? a = b, true : false; } long long x, y; long long exgcd(long long a, long long b, long long& x, long long& y) { if (!b) { x = 1; y = 0; return a; } else { long long gcd, t; gcd = exgcd(b, a % b, x, y); t = x; x = y; y = t - (a / b) * y; return gcd; } } long long n, m, sx, sy, vx, vy; long long gao(long long a, long long b, long long t1, long long t2) { long long c = t2 - t1; long long gcd = exgcd(a, b, x, y); if (c % gcd) return INF; x *= c / gcd; y *= c / gcd; long long mo = abs(b / gcd); x = (x % mo + mo) % mo; return 2 * n * x + t1; } long long calc(long long sx, long long sy, long long vx, long long vy, long long tx, long long ty) { long long t11 = 0, t12 = 0; long long t21 = 0, t22 = 0; if (vx > 0) { if (tx >= sx) t11 = tx - sx, t12 = t11 + 2 * (n - tx); else t11 = sx - tx + 2 * (n - sx), t12 = t11 + 2 * tx; } else { if (tx <= sx) t11 = sx - tx, t12 = t11 + 2 * tx; else t11 = tx - sx + 2 * sx, t12 = t11 + 2 * (n - tx); } if (vy > 0) { if (ty >= sy) t21 = ty - sy, t22 = t21 + 2 * (m - ty); else t21 = sy - ty + 2 * (m - sy), t22 = t21 + 2 * ty; } else { if (ty <= sy) t21 = sy - ty, t22 = t21 + 2 * ty; else t21 = ty - sy + 2 * sy, t22 = t21 + 2 * (m - ty); } long long tim = INF; chkmin(tim, gao(2 * n, -2 * m, t11, t21)); chkmin(tim, gao(2 * n, -2 * m, t11, t22)); chkmin(tim, gao(2 * n, -2 * m, t12, t21)); chkmin(tim, gao(2 * n, -2 * m, t12, t22)); return tim; } void print(int who) { if (who == 0) cout << "0 0" << "\n"; else if (who == 1) cout << n << " " << "0\n"; else if (who == 2) cout << "0 " << m << "\n"; else if (who == 3) cout << n << " " << m << "\n"; else cout << "-1" << "\n"; exit(0); } int main() { cin >> n >> m >> sx >> sy >> vx >> vy; if (!vx) { if (sx == 0 && vy == 1) print(2); else if (sx == 0 && vy == -1) print(0); else if (sx == n && vy == 1) print(3); else if (sx == n && vy == -1) print(1); else print(-1); } else if (!vy) { if (sy == 0 && vx == 1) print(1); else if (sy == 0 && vx == -1) print(0); else if (sy == m && vx == 1) print(3); else if (sy == m && vx == -1) print(2); else print(-1); } else { long long tim = INF, who = -1; if (chkmin(tim, calc(sx, sy, vx, vy, 0, 0))) who = 0; if (chkmin(tim, calc(sx, sy, vx, vy, n, 0))) who = 1; if (chkmin(tim, calc(sx, sy, vx, vy, 0, m))) who = 2; if (chkmin(tim, calc(sx, sy, vx, vy, n, m))) who = 3; print(who); } return 0; } ```
### Prompt In cpp, your task is to solve the following problem: Adilbek's house is located on a street which can be represented as the OX axis. This street is really dark, so Adilbek wants to install some post lamps to illuminate it. Street has n positions to install lamps, they correspond to the integer numbers from 0 to n - 1 on the OX axis. However, some positions are blocked and no post lamp can be placed there. There are post lamps of different types which differ only by their power. When placed in position x, post lamp of power l illuminates the segment [x; x + l]. The power of each post lamp is always a positive integer number. The post lamp shop provides an infinite amount of lamps of each type from power 1 to power k. Though each customer is only allowed to order post lamps of exactly one type. Post lamps of power l cost a_l each. What is the minimal total cost of the post lamps of exactly one type Adilbek can buy to illuminate the entire segment [0; n] of the street? If some lamps illuminate any other segment of the street, Adilbek does not care, so, for example, he may place a lamp of power 3 in position n - 1 (even though its illumination zone doesn't completely belong to segment [0; n]). Input The first line contains three integer numbers n, m and k (1 ≀ k ≀ n ≀ 10^6, 0 ≀ m ≀ n) β€” the length of the segment of the street Adilbek wants to illuminate, the number of the blocked positions and the maximum power of the post lamp available. The second line contains m integer numbers s_1, s_2, ..., s_m (0 ≀ s_1 < s_2 < ... s_m < n) β€” the blocked positions. The third line contains k integer numbers a_1, a_2, ..., a_k (1 ≀ a_i ≀ 10^6) β€” the costs of the post lamps. Output Print the minimal total cost of the post lamps of exactly one type Adilbek can buy to illuminate the entire segment [0; n] of the street. If illumintaing the entire segment [0; n] is impossible, print -1. Examples Input 6 2 3 1 3 1 2 3 Output 6 Input 4 3 4 1 2 3 1 10 100 1000 Output 1000 Input 5 1 5 0 3 3 3 3 3 Output -1 Input 7 4 3 2 4 5 6 3 14 15 Output -1 ### Response ```cpp #include <bits/stdc++.h> #pragma comment(linker, "/STACK:102400000,102400000") using namespace std; const int N = 1e6 + 10; int n, m, k; bool des[N]; int l[N], a[N]; int main() { cin >> n >> m >> k; for (int i = 1; i <= m; i++) { int t; scanf("%d", &t); des[t] = true; } for (int i = 1; i <= k; i++) scanf("%d", &a[i]); if (des[0]) { printf("-1\n"); return 0; } l[0] = 0; for (int i = 1; i < n; i++) if (des[i - 1]) l[i] = l[i - 1]; else l[i] = i; long long ans = 1ll << 62; for (int i = 1; i <= k; i++) { int cur = 0; long long tmp = 0; while (true) { tmp += a[i]; cur += i; if (cur >= n) break; if (des[cur]) { if (cur - l[cur] + 1 >= i) { tmp = 1ll << 62; break; } else { cur = l[cur] - 1; } } } ans = min(ans, tmp); } if (ans == 1ll << 62) puts("-1"); else cout << ans << endl; } ```
### Prompt Please create a solution in CPP to the following problem: ButCoder Inc. runs a programming competition site called ButCoder. In this site, a user is given an integer value called rating that represents his/her skill, which changes each time he/she participates in a contest. The initial value of a new user's rating is 0, and a user whose rating reaches K or higher is called Kaiden ("total transmission"). Note that a user's rating may become negative. Hikuhashi is a new user in ButCoder. It is estimated that, his rating increases by A in each of his odd-numbered contests (first, third, fifth, ...), and decreases by B in each of his even-numbered contests (second, fourth, sixth, ...). According to this estimate, after how many contests will he become Kaiden for the first time, or will he never become Kaiden? Constraints * 1 ≀ K, A, B ≀ 10^{18} * All input values are integers. Input Input is given from Standard Input in the following format: K A B Output If it is estimated that Hikuhashi will never become Kaiden, print `-1`. Otherwise, print the estimated number of contests before he become Kaiden for the first time. Examples Input 4000 2000 500 Output 5 Input 4000 500 2000 Output -1 Input 1000000000000000000 2 1 Output 1999999999999999997 ### Response ```cpp #include<iostream> #include<string> #include<algorithm> using namespace std; int main() { long long k, a, b; cin >> k >> a >> b; if (a >= k)cout << "1\n"; else if (a - b <= 0)cout << "-1\n"; else { long long p = k - a; a -= b; if (p%a != 0)p += a - (p % a); cout << p / a * 2 + 1 << endl; } return 0; } ```
### Prompt Please provide a cpp coded solution to the problem described below: There is a country with n citizens. The i-th of them initially has a_{i} money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have. Sometimes the government makes payouts to the poor: all citizens who have strictly less money than x are paid accordingly so that after the payout they have exactly x money. In this case the citizens don't send a receipt. You know the initial wealth of every citizen and the log of all events: receipts and payouts. Restore the amount of money each citizen has after all events. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^{5}) β€” the numer of citizens. The next line contains n integers a_1, a_2, ..., a_n (0 ≀ a_{i} ≀ 10^{9}) β€” the initial balances of citizens. The next line contains a single integer q (1 ≀ q ≀ 2 β‹… 10^{5}) β€” the number of events. Each of the next q lines contains a single event. The events are given in chronological order. Each event is described as either 1 p x (1 ≀ p ≀ n, 0 ≀ x ≀ 10^{9}), or 2 x (0 ≀ x ≀ 10^{9}). In the first case we have a receipt that the balance of the p-th person becomes equal to x. In the second case we have a payoff with parameter x. Output Print n integers β€” the balances of all citizens after all events. Examples Input 4 1 2 3 4 3 2 3 1 2 2 2 1 Output 3 2 3 4 Input 5 3 50 2 1 10 3 1 2 0 2 8 1 3 20 Output 8 8 20 8 10 Note In the first example the balances change as follows: 1 2 3 4 β†’ 3 3 3 4 β†’ 3 2 3 4 β†’ 3 2 3 4 In the second example the balances change as follows: 3 50 2 1 10 β†’ 3 0 2 1 10 β†’ 8 8 8 8 10 β†’ 8 8 20 8 10 ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct node { long long int ch, p, x; }; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long int n, q; cin >> n; vector<long long int> a(n); for (long long int i = 0; i < n; i++) { cin >> a[i]; } cin >> q; vector<node> query(q); long long int ch, p, x, index; long long int track = -1; for (long long int i = 0; i < q; i++) { cin >> ch; if (ch == 1) { cin >> p >> x; node n1; n1.ch = 1; n1.p = p; n1.x = x; query[i] = n1; } else { cin >> x; if (x > track) { track = x; index = i; } node n1; n1.ch = 2; n1.p = -1; n1.x = x; query[i] = n1; } } if (track != -1) { vector<long long int> vis(n, 0); long long int maxm = 0; for (long long int i = q - 1; i >= 0; i--) { if (query[i].ch == 1 && vis[query[i].p - 1] == 0) { a[query[i].p - 1] = max(query[i].x, maxm); vis[query[i].p - 1] = 1; } else if (query[i].ch == 2) { maxm = max(maxm, query[i].x); } } for (long long int i = 0; i < n; i++) { if (vis[i] == 0) a[i] = max(a[i], track); } } else { vector<long long int> vis(n, 0); for (long long int i = q - 1; i >= 0; i--) { if (query[i].ch == 1 && vis[query[i].p - 1] == 0) { a[query[i].p - 1] = query[i].x; vis[query[i].p - 1] = 1; } } } for (long long int i = 0; i < n; i++) { cout << a[i] << " "; } cout << endl; return 0; } ```
### Prompt Develop a solution in CPP to the problem described below: Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0. Input The first line of the input contains one integer, n (1 ≀ n ≀ 100 000). The next line contains n space separated integers given to Wet Shark. Each of these integers is in range from 1 to 109, inclusive. Output Print the maximum possible even sum that can be obtained if we use some of the given integers. Examples Input 3 1 2 3 Output 6 Input 5 999999999 999999999 999999999 999999999 999999999 Output 3999999996 Note In the first sample, we can simply take all three integers for a total sum of 6. In the second sample Wet Shark should take any four out of five integers 999 999 999. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int N; vector<long long> odd; cin >> N; long long res = 0, x; for (int i = 0; i < N; i++) { cin >> x; if (x % 2 == 0) { res += x; } else { odd.push_back(x); } } sort(odd.begin(), odd.end()); for (int i = 0; i < odd.size(); i++) { res += odd[i]; } if (res & 1) { res -= odd[0]; } cout << res; return 0; } ```
### Prompt Construct a CPP code solution to the problem outlined: The city administration of IT City decided to fix up a symbol of scientific and technical progress in the city's main square, namely an indicator board that shows the effect of Moore's law in real time. Moore's law is the observation that the number of transistors in a dense integrated circuit doubles approximately every 24 months. The implication of Moore's law is that computer performance as function of time increases exponentially as well. You are to prepare information that will change every second to display on the indicator board. Let's assume that every second the number of transistors increases exactly 1.000000011 times. Input The only line of the input contains a pair of integers n (1000 ≀ n ≀ 10 000) and t (0 ≀ t ≀ 2 000 000 000) β€” the number of transistors in the initial time and the number of seconds passed since the initial time. Output Output one number β€” the estimate of the number of transistors in a dence integrated circuit in t seconds since the initial time. The relative error of your answer should not be greater than 10 - 6. Examples Input 1000 1000000 Output 1011.060722383550382782399454922040 ### Response ```cpp #include <bits/stdc++.h> using namespace std; using namespace std; int main() { int n, j, i, t; double m; while (scanf("%d%d", &n, &t) != EOF) { m = pow(1.000000011, t); m = n * m; printf("%lf\n", m); } return 0; } ```
### Prompt Construct a CPP code solution to the problem outlined: The School β„–0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti: * ti = 1, if the i-th child is good at programming, * ti = 2, if the i-th child is good at maths, * ti = 3, if the i-th child is good at PE Each child happens to be good at exactly one of these three subjects. The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team. What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that? Input The first line contains integer n (1 ≀ n ≀ 5000) β€” the number of children in the school. The second line contains n integers t1, t2, ..., tn (1 ≀ ti ≀ 3), where ti describes the skill of the i-th child. Output In the first line output integer w β€” the largest possible number of teams. Then print w lines, containing three numbers in each line. Each triple represents the indexes of the children forming the team. You can print both the teams, and the numbers in the triplets in any order. The children are numbered from 1 to n in the order of their appearance in the input. Each child must participate in no more than one team. If there are several solutions, print any of them. If no teams can be compiled, print the only line with value w equal to 0. Examples Input 7 1 3 1 3 2 1 2 Output 2 3 5 2 6 7 4 Input 4 2 1 1 2 Output 0 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> m; vector<int> s; vector<int> p; for (int i = 1; i <= n; ++i) { int a; cin >> a; if (a == 1) { p.emplace_back(i); } else if (a == 2) m.emplace_back(i); else s.emplace_back(i); } if (m.size() >= 1 && s.size() >= 1 && p.size() >= 1) cout << min(min(m.size(), p.size()), s.size()) << endl; else cout << 0 << endl; do { if (m.size() && s.size() && p.size()) { cout << m.back() << " "; m.pop_back(); cout << s.back() << " "; s.pop_back(); cout << p.back(); p.pop_back(); cout << endl; } else { break; } } while (1); return 0; } ```
### Prompt Construct a cpp code solution to the problem outlined: It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces. Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question. Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other. Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring. By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure. Input The input consists of multiple datasets. Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30. There is one line containing only 0 at the end of the input. Output Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1. Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day. Example Input 4 1 1 2 2 3 2 1 2 3 3 4 5 0 Output 3 ### Response ```cpp #include <iostream> #include <vector> using namespace std; int main() { int n, m, d; while (cin >> n, n) { vector<vector<int>> f(n, vector<int>(31, 0)); vector<vector<long long>> dp(n, vector<long long>(31, 0)); for (int i = 0; i < n; i++) { cin >> m; while (m--) { cin >> d; f[i][d] = 1; } dp[i][0] = 1L << i; } int res = -1; for (int i = 1; i < 31; i++) { for (int j = 0; j < n; j++) { if (!f[j][i]) { dp[j][i] = dp [j][i - 1]; continue; } for (int k = 0; k < n; k++) { if (!f[k][i]) continue; dp[j][i] |= dp[k][i - 1]; } if (dp[j][i] == (1L << n) - 1) { res = i; break; } } if (res != -1) break; } cout << res << endl; } return 0; } ```
### Prompt Develop a solution in Cpp to the problem described below: Problem statement Meatishi can increase or decrease the number of fingers. There are n buns in front of Nikunishi-kun. Meatishi is trying to count the number of steamed buns by breaking his finger. There are only two shapes that Nishikun's fingers can take, whether they are broken or not. Nikunishi understands binary numbers. Nikunishi-kun can count numbers by associating each finger with a binary digit. Nikunishi doesn't understand the logarithm. Find the minimum number of fingers needed to count the buns instead of Nishikun. input n Constraint * An integer * 0 ≀ n ≀ 1018 output Print the answer on one line, and print a newline at the end. sample Sample input 1 0 Sample output 1 0 Sample input 2 Four Sample output 2 3 Sample input 3 31 Sample output 3 Five Sample input 4 36028797018963968 Sample output 4 56 Example Input 0 Output 0 ### Response ```cpp #define _USE_MATH_DEFINES #define _CRT_SECURE_NO_DEPRECATE #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <limits> #include <ctime> #include <cassert> #include <map> #include <set> #include <iostream> #include <memory> #include <string> #include <vector> #include <algorithm> #include <functional> #include <sstream> #include <stack> #include <queue> #include <numeric> #include <iterator> #include <bitset> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> Pii; typedef pair<ll, ll> Pll; #define FOR(i,n) for(int i = 0; i < (n); i++) #define sz(c) ((int)(c).size()) #define ten(x) ((int)1e##x) template<typename ...> static inline int getchar_unlocked(void) { return getchar(); } template<typename ...> static inline void putchar_unlocked(int c) { putchar(c); } #define mygc(c) (c)=getchar_unlocked() #define mypc(c) putchar_unlocked(c) void reader(int& x) { int k, m = 0; x = 0; for (;;) { mygc(k); if (k == '-') { m = 1; break; }if ('0' <= k&&k <= '9') { x = k - '0'; break; } }for (;;) { mygc(k); if (k<'0' || k>'9')break; x = x * 10 + k - '0'; }if (m) x = -x; } void reader(ll& x) { int k, m = 0; x = 0; for (;;) { mygc(k); if (k == '-') { m = 1; break; }if ('0' <= k&&k <= '9') { x = k - '0'; break; } }for (;;) { mygc(k); if (k<'0' || k>'9')break; x = x * 10 + k - '0'; }if (m) x = -x; } int reader(char c[]) { int i, s = 0; for (;;) { mygc(i); if (i != ' '&&i != '\n'&&i != '\r'&&i != '\t'&&i != EOF) break; }c[s++] = i; for (;;) { mygc(i); if (i == ' ' || i == '\n' || i == '\r' || i == '\t' || i == EOF) break; c[s++] = i; }c[s] = '\0'; return s; } template <class T, class S> void reader(T& x, S& y) { reader(x); reader(y); } template <class T, class S, class U> void reader(T& x, S& y, U& z) { reader(x); reader(y); reader(z); } template <class T, class S, class U, class V> void reader(T& x, S& y, U& z, V & w) { reader(x); reader(y); reader(z); reader(w); } void writer(int x, char c) { int s = 0, m = 0; char f[10]; if (x<0)m = 1, x = -x; while (x)f[s++] = x % 10, x /= 10; if (!s)f[s++] = 0; if (m)mypc('-'); while (s--)mypc(f[s] + '0'); mypc(c); } void writer(ll x, char c) { int s = 0, m = 0; char f[20]; if (x<0)m = 1, x = -x; while (x)f[s++] = x % 10, x /= 10; if (!s)f[s++] = 0; if (m)mypc('-'); while (s--)mypc(f[s] + '0'); mypc(c); } void writer(const char c[]) { int i; for (i = 0; c[i] != '\0'; i++)mypc(c[i]); } void writer(const char x[], char c) { int i; for (i = 0; x[i] != '\0'; i++)mypc(x[i]); mypc(c); } template<class T> void writerLn(T x) { writer(x, '\n'); } template<class T, class S> void writerLn(T x, S y) { writer(x, ' '); writer(y, '\n'); } template<class T, class S, class U> void writerLn(T x, S y, U z) { writer(x, ' '); writer(y, ' '); writer(z, '\n'); } template<class T> void writerArr(T x[], int n) { if (!n) { mypc('\n'); return; }FOR(i, n - 1)writer(x[i], ' '); writer(x[n - 1], '\n'); } ll mod_pow(ll a, ll n, ll mod) { ll ret = 1; ll p = a % mod; while (n) { if (n & 1) ret = ret * p % mod; p = p * p % mod; n >>= 1; } return ret; } template<class T> T extgcd(T a, T b, T& x, T& y) { for (T u = y = 1, v = x = 0; a;) { T q = b / a; swap(x -= q * u, u); swap(y -= q * v, v); swap(b -= q * a, a); } return b; } template<class T> T mod_inv(T a, T m) { T x, y; extgcd(a, m, x, y); return (m + x % m) % m; } template<class T> T gcd(T a, T b) { return b ? gcd(b, a % b) : a; } int main() { ll n; cin >> n; int ans = 0; while (n) ans++, n /= 2; cout << ans << endl; return 0; } ```
### Prompt Please provide a CPP coded solution to the problem described below: VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications. The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm. Input The first line of input consists of single integer n β€” the number of news categories (1 ≀ n ≀ 200 000). The second line of input consists of n integers a_i β€” the number of publications of i-th category selected by the batch algorithm (1 ≀ a_i ≀ 10^9). The third line of input consists of n integers t_i β€” time it takes for targeted algorithm to find one new publication of category i (1 ≀ t_i ≀ 10^5). Output Print one integer β€” the minimal required time for the targeted algorithm to get rid of categories with the same size. Examples Input 5 3 7 9 7 8 5 2 5 7 5 Output 6 Input 5 1 2 3 4 5 1 1 1 1 1 Output 0 Note In the first example, it is possible to find three publications of the second type, which will take 6 seconds. In the second example, all news categories contain a different number of publications. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 200000 + 10; struct Item { int a, t; }; struct Node { int left, right, cnt; }; Item item[N]; Node sgt[N * 20]; int tot; bool cmp(const Item& a, const Item& b) { return a.t < b.t; } int insert(int root, int begin, int end, int& x) { int mid, tmp; if (!root) root = ++tot; if (begin == end) { if (sgt[root].cnt == 0) sgt[root].cnt++; return root; } mid = (begin + end) / 2; if (x <= mid && (!sgt[root].left || sgt[sgt[root].left].cnt < mid - begin + 1)) { tmp = sgt[sgt[root].left].cnt; sgt[root].left = insert(sgt[root].left, begin, mid, x); if (sgt[sgt[root].left].cnt == tmp) { x = max(x, mid + 1); sgt[root].right = insert(sgt[root].right, mid + 1, end, x); } } else { x = max(x, mid + 1); sgt[root].right = insert(sgt[root].right, mid + 1, end, x); } sgt[root].cnt = sgt[sgt[root].left].cnt + sgt[sgt[root].right].cnt; return root; } int main() { long long res; int n, x, y, i; scanf("%d", &n); for (i = 0; i < n; i++) scanf("%d", &item[i].a); for (i = 0; i < n; i++) scanf("%d", &item[i].t); sort(item, item + n, cmp); res = 0; tot = 1; for (i = n - 1; i >= 0; i--) { y = x = item[i].a; insert(1, 1, 1000000000 + N, y); res += 1LL * item[i].t * (y - x); } printf("%lld\n", res); return 0; } ```
### Prompt Your challenge is to write a cpp solution to the following problem: Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence p1, p2, ..., pn for his birthday. Jeff hates inversions in sequences. An inversion in sequence a1, a2, ..., an is a pair of indexes i, j (1 ≀ i < j ≀ n), such that an inequality ai > aj holds. Jeff can multiply some numbers of the sequence p by -1. At that, he wants the number of inversions in the sequence to be minimum. Help Jeff and find the minimum number of inversions he manages to get. Input The first line contains integer n (1 ≀ n ≀ 2000). The next line contains n integers β€” sequence p1, p2, ..., pn (|pi| ≀ 105). The numbers are separated by spaces. Output In a single line print the answer to the problem β€” the minimum number of inversions Jeff can get. Examples Input 2 2 1 Output 0 Input 9 -2 0 -1 0 -1 2 1 0 -1 Output 6 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main(void) { int n, a[2005]; scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &a[i]); for (int i = 0; i < n; i++) if (a[i] < 0) a[i] = -a[i]; int m = 0, ans = n * n; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (a[i] > a[j]) ++m; ans = m; for (int i = 0; i < n; i++) { int k = 0; for (int j = 0; j < i; j++) { if (a[j] > a[i]) --k; if (a[j] > -a[i]) ++k; } for (int j = i + 1; j < n; j++) { if (a[i] > a[j]) --k; if (-a[i] > a[j]) ++k; } if (k <= 0) { a[i] = -a[i]; m += k; } ans = min(ans, m); } printf("%d\n", ans); return 0; } ```
### Prompt In cpp, your task is to solve the following problem: Mad scientist Mike has applied for a job. His task is to manage a system of water pumping stations. The system consists of n pumping stations, which are numbered by integers from 1 to n. Some pairs of stations are connected by bidirectional pipes through which water can flow in either direction (but only in one at a time). For each pipe you know its bandwidth β€” the maximum number of liters of water that can flow through it in one hour. Each pumping station can pump incoming water from some stations to other stations through the pipes, provided that in one hour the total influx of water to the station is equal to the total outflux of water from the station. It is Mike's responsibility to pump water between stations. From station a to station b through the pipes (possibly through other stations) within one hour one can transmit a certain number of liters of water according to the rules described above. During this time, water from other stations can not flow into station a, and can not flow out of the station b. However, any amount of water can flow out of station a or in station b. If a total of x litres of water flows out of the station a in an hour, then Mike gets x bollars more to his salary. To get paid, Mike needs to work for n - 1 days, according to the contract. On the first day he selects two stations v1 and v2, and within one hour he pumps a certain amount of water from v1 to v2. Next, on the i-th day Mike chooses a station vi + 1 that has been never selected before, and pumps a certain amount of water out of the station vi to station vi + 1 for one hour. The quantity of water he pumps on the i-th day does not depend on the amount of water pumped on the (i - 1)-th day. Mike needs to earn as much bollars as he can for his projects. Help Mike find such a permutation of station numbers v1, v2, ..., vn so Mike will be able to earn the highest possible salary. Input The first line of the input contains two space-separated integers n and m (2 ≀ n ≀ 200, 1 ≀ m ≀ 1000) β€” the number of stations and pipes in the system, accordingly. The i-th of the next m lines contains three space-separated integers ai, bi and ci (1 ≀ ai, bi ≀ n, ai β‰  bi, 1 ≀ ci ≀ 100) β€” the numbers of stations connected by the i-th pipe and the pipe's bandwidth, accordingly. It is guaranteed that any two stations are connected by at most one pipe and that there is a pipe path between any two stations. Output On the first line print a single integer β€” the maximum salary Mike can earn. On the second line print a space-separated permutation of n numbers from 1 to n β€” the numbers of stations in the sequence v1, v2, ..., vn. If there are multiple answers, print any of them. Examples Input 6 11 1 2 10 1 6 8 2 3 4 2 5 2 2 6 3 3 4 5 3 5 4 3 6 2 4 5 7 4 6 2 5 6 3 Output 77 6 2 1 5 3 4 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, c[1111][1111], pa[1111], pre[1111], w[1111], f[1111][1111]; void gomory_hu() { memset(pa, 0, sizeof(pa)); memset(w, 0, sizeof(w)); for (int s = 1; s < n; s++) { int t = pa[s], total = 0; memset(f, 0, sizeof(f)); while (1) { queue<int> q; q.push(s); memset(pre, -1, sizeof(pre)); pre[s] = -2; while (!q.empty() && pre[t] == -1) { int u = q.front(); q.pop(); for (int v = 0; v < n; v++) if (pre[v] == -1 && (c[u][v] - (f[u][v] - f[v][u])) > 0) pre[v] = u, q.push(v); } if (pre[t] == -1) break; int inc = 1000000000; for (int v = t, u = pre[v]; u >= 0; v = u, u = pre[v]) inc = (inc < (c[u][v] - (f[u][v] - f[v][u])) ? inc : (c[u][v] - (f[u][v] - f[v][u]))); for (int v = t, u = pre[v]; u >= 0; v = u, u = pre[v]) f[u][v] += inc; total += inc; } w[s] = total; for (int i = 0; i < n; i++) if (i != s && pre[i] != -1 && pa[i] == t) pa[i] = s; if (pre[pa[t]] != -1) pa[s] = pa[t], pa[t] = s, w[s] = w[t], w[t] = total; } } struct star { int x, y; star(int x, int y) : x(x), y(y) {} star() {} }; struct cmp { bool operator()(star a, star b) { return a.y < b.y; } }; int deg[1111], con[1111][1111]; int main() { int m, i, j, k; scanf("%d %d", &n, &m); memset(c, 0, sizeof(c)); while (m--) { scanf("%d %d %d", &i, &j, &k); i--; j--; c[i][j] = k; c[j][i] = k; } gomory_hu(); priority_queue<star, vector<star>, cmp> q; int ans = 0; for (i = 1; i < n; i++) ans += w[i]; printf("%d\n", ans); printf("1"); memset(deg, 0, sizeof(deg)); for (i = 1; i < n; i++) con[pa[i]][deg[pa[i]]++] = i; for (i = 0; i < deg[0]; i++) q.push(star(con[0][i], w[con[0][i]])); while (!q.empty()) { star u = q.top(); q.pop(); printf(" %d", u.x + 1); for (i = 0; i < deg[u.x]; i++) { j = con[u.x][i]; q.push(star(j, w[j])); } } } ```
### Prompt Please provide a cpp coded solution to the problem described below: The m-floor (m > 1) office of international corporation CodeForces has the advanced elevator control system established. It works as follows. All office floors are sequentially numbered with integers from 1 to m. At time t = 0, the elevator is on the first floor, the elevator is empty and nobody is waiting for the elevator on other floors. Next, at times ti (ti > 0) people come to the elevator. For simplicity, we assume that one person uses the elevator only once during the reported interval. For every person we know three parameters: the time at which the person comes to the elevator, the floor on which the person is initially, and the floor to which he wants to go. The movement of the elevator between the floors is as follows. At time t (t β‰₯ 0, t is an integer) the elevator is always at some floor. First the elevator releases all people who are in the elevator and want to get to the current floor. Then it lets in all the people waiting for the elevator on this floor. If a person comes to the elevator exactly at time t, then he has enough time to get into it. We can assume that all of these actions (going in or out from the elevator) are made instantly. After that the elevator decides, which way to move and at time (t + 1) the elevator gets to the selected floor. The elevator selects the direction of moving by the following algorithm. * If the elevator is empty and at the current time no one is waiting for the elevator on any floor, then the elevator remains at the current floor. * Otherwise, let's assume that the elevator is on the floor number x (1 ≀ x ≀ m). Then elevator calculates the directions' "priorities" pup and pdown: pup is the sum of the number of people waiting for the elevator on the floors with numbers greater than x, and the number of people in the elevator, who want to get to the floors with the numbers greater than x; pdown is the sum of the number of people waiting for the elevator on the floors with numbers less than x, and the number of people in the elevator, who want to get to the floors with the numbers less than x. If pup β‰₯ pdown, then the elevator goes one floor above the current one (that is, from floor x to floor x + 1), otherwise the elevator goes one floor below the current one (that is, from floor x to floor x - 1). Your task is to simulate the work of the elevator and for each person to tell the time when the elevator will get to the floor this person needs. Please note that the elevator is large enough to accommodate all the people at once. Input The first line contains two space-separated integers: n, m (1 ≀ n ≀ 105, 2 ≀ m ≀ 105) β€” the number of people and floors in the building, correspondingly. Next n lines each contain three space-separated integers: ti, si, fi (1 ≀ ti ≀ 109, 1 ≀ si, fi ≀ m, si β‰  fi) β€” the time when the i-th person begins waiting for the elevator, the floor number, where the i-th person was initially located, and the number of the floor, where he wants to go. Output Print n lines. In the i-th line print a single number β€” the moment of time, when the i-th person gets to the floor he needs. The people are numbered in the order, in which they are given in the input. Please don't 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 10 1 2 7 3 6 5 3 4 8 Output 7 11 8 Input 2 10 1 2 5 7 4 5 Output 5 9 Note In the first sample the elevator worked as follows: * t = 1. The elevator is on the floor number 1. The elevator is empty. The floor number 2 has one person waiting. pup = 1 + 0 = 1, pdown = 0 + 0 = 0, pup β‰₯ pdown. So the elevator goes to the floor number 2. * t = 2. The elevator is on the floor number 2. One person enters the elevator, he wants to go to the floor number 7. pup = 0 + 1 = 1, pdown = 0 + 0 = 0, pup β‰₯ pdown. So the elevator goes to the floor number 3. * t = 3. The elevator is on the floor number 3. There is one person in the elevator, he wants to go to floor 7. The floors number 4 and 6 have two people waiting for the elevator. pup = 2 + 1 = 3, pdown = 0 + 0 = 0, pup β‰₯ pdown. So the elevator goes to the floor number 4. * t = 4. The elevator is on the floor number 4. There is one person in the elevator who wants to go to the floor number 7. One person goes into the elevator, he wants to get to the floor number 8. The floor number 6 has one man waiting. pup = 1 + 2 = 3, pdown = 0 + 0 = 0, pup β‰₯ pdown. So the elevator goes to the floor number 5. * t = 5. The elevator is on the floor number 5. There are two people in the elevator, they want to get to the floors number 7 and 8, correspondingly. There is one person waiting for the elevator on the floor number 6. pup = 1 + 2 = 3, pdown = 0 + 0 = 0, pup β‰₯ pdown. So the elevator goes to the floor number 6. * t = 6. The elevator is on the floor number 6. There are two people in the elevator, they want to get to the floors number 7 and 8, correspondingly. One man enters the elevator, he wants to get to the floor number 5. pup = 0 + 2 = 2, pdown = 0 + 1 = 1, pup β‰₯ pdown. So the elevator goes to the floor number 7. * t = 7. The elevator is on the floor number 7. One person leaves the elevator, this person wanted to get to the floor number 7. There are two people in the elevator, they want to get to the floors with numbers 8 and 5, correspondingly. pup = 0 + 1 = 1, pdown = 0 + 1 = 1, pup β‰₯ pdown. So the elevator goes to the floor number 8. * t = 8. The elevator is on the floor number 8. One person leaves the elevator, this person wanted to go to the floor number 8. There is one person in the elevator, he wants to go to the floor number 5. pup = 0 + 0 = 0, pdown = 0 + 1 = 1, pup < pdown. So the elevator goes to the floor number 7. * t = 9. The elevator is on the floor number 7. There is one person in the elevator, this person wants to get to the floor number 5. pup = 0 + 0 = 0, pdown = 0 + 1 = 1, pup < pdown. So the elevator goes to the floor number 6. * t = 10. The elevator is on the floor number 6. There is one person in the elevator, he wants to get to the floor number 5. pup = 0 + 0 = 0, pdown = 0 + 1 = 1, pup < pdown. So the elevator goes to the floor number 5. * t = 11. The elevator is on the floor number 5. One person leaves the elevator, this person initially wanted to get to the floor number 5. The elevator is empty and nobody needs it, so the elevator remains at the floor number 5. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 100000, maxm = 100000; const long long inf = (long long)1e18; struct guy { long long t; int s, f, id; inline bool operator<(const guy &g) const { return t < g.t; } }; int n, m, fenw[maxm]; long long ans[maxn]; guy data[maxn]; set<pair<int, int> > dest, wait; inline void inc(int x, int d) { for (; x < m; x |= x + 1) fenw[x] += d; } inline int sum(int r) { int ans = 0; for (; r != -1; r = (r & (r + 1)) - 1) ans += fenw[r]; return ans; } inline int sum(int l, int r) { if (l > r) return 0; return sum(r) - sum(l - 1); } int main() { cin >> n >> m; for (int i = 0; i < n; i++) { cin >> data[i].t >> data[i].s >> data[i].f; data[i].s--, data[i].f--; data[i].id = i; } sort(data, data + n); int cur = 0, ptr = 0; long long curt = 0; memset(ans, -1, sizeof(ans)); while (curt != inf) { while (ptr < n && data[ptr].t == curt) { inc(data[ptr].s, 1); wait.insert(make_pair(data[ptr].s, ptr)); ptr++; } for (auto it = dest.lower_bound(make_pair(cur, -1)); it != dest.end() && it->first == cur; it = dest.lower_bound(make_pair(cur, -1))) { inc(it->first, -1); ans[data[it->second].id] = curt; dest.erase(it); } for (auto it = wait.lower_bound(make_pair(cur, -1)); it != wait.end() && it->first == cur; it = wait.lower_bound(make_pair(cur, -1))) { dest.insert(make_pair(data[it->second].f, it->second)); inc(it->first, -1); inc(data[it->second].f, 1); wait.erase(it); } if (sum(0, m - 1) == 0) { if (ptr == n) break; curt = data[ptr].t; continue; } int dir = sum(cur + 1, m - 1) >= sum(0, cur - 1) ? 1 : -1; long long arrive = inf; if (dir == -1) { auto it = dest.lower_bound(make_pair(cur, -1)); if (it != dest.begin()) { it--; arrive = min(arrive, curt + cur - it->first); } it = wait.lower_bound(make_pair(cur, -1)); if (it != wait.begin()) { it--; arrive = min(arrive, curt + cur - it->first); } } else { auto it = dest.lower_bound(make_pair(cur, -1)); if (it != dest.end()) arrive = min(arrive, curt + it->first - cur); it = wait.lower_bound(make_pair(cur, -1)); if (it != wait.end()) arrive = min(arrive, curt + it->first - cur); } if (ptr < n) arrive = min(arrive, data[ptr].t); cur += (arrive - curt) * dir; curt = arrive; } for (int i = 0; i < n; i++) { assert(ans[i] != -1); cout << ans[i] << endl; } return 0; } ```
### Prompt Please provide a cpp coded solution to the problem described below: Petya is preparing for IQ test and he has noticed that there many problems like: you are given a sequence, find the next number. Now Petya can solve only problems with arithmetic or geometric progressions. Arithmetic progression is a sequence a1, a1 + d, a1 + 2d, ..., a1 + (n - 1)d, where a1 and d are any numbers. Geometric progression is a sequence b1, b2 = b1q, ..., bn = bn - 1q, where b1 β‰  0, q β‰  0, q β‰  1. Help Petya and write a program to determine if the given sequence is arithmetic or geometric. Also it should found the next number. If the sequence is neither arithmetic nor geometric, print 42 (he thinks it is impossible to find better answer). You should also print 42 if the next element of progression is not integer. So answer is always integer. Input The first line contains exactly four integer numbers between 1 and 1000, inclusively. Output Print the required number. If the given sequence is arithmetic progression, print the next progression element. Similarly, if the given sequence is geometric progression, print the next progression element. Print 42 if the given sequence is not an arithmetic or geometric progression. Examples Input 836 624 412 200 Output -12 Input 1 334 667 1000 Output 1333 Note This problem contains very weak pretests! ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { float arr[4], c, fraction; int eq; for (int i = 0; i < 4; i++) { cin >> arr[i]; } if ((arr[1] - arr[0]) == (arr[2] - arr[1]) && (arr[2] - arr[1]) == (arr[3] - arr[2])) { eq = arr[3] + (arr[3] - arr[2]); cout << eq << endl; } else if ((arr[1] / arr[0]) == (arr[2] / arr[1]) && (arr[2] / arr[1]) == (arr[3] / arr[2])) { c = arr[3] / arr[2]; eq = arr[3] * c; fraction = arr[3] * c; if (fraction > eq) cout << "42" << endl; else cout << eq << endl; } else cout << "42" << endl; return 0; } ```
### Prompt Your task is to create a Cpp solution to the following problem: Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by n streets along the Eastern direction and m streets across the Southern direction. Naturally, this city has nm intersections. At any intersection of i-th Eastern street and j-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings. When Dora passes through the intersection of the i-th Eastern and j-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change. Formally, on every of nm intersections Dora solves an independent problem. She sees n + m - 1 skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer x and assign every skyscraper a height from 1 to x. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible x. For example, if the intersection and the two streets corresponding to it look as follows: <image> Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) <image> The largest used number is 5, hence the answer for this intersection would be 5. Help Dora to compute the answers for each intersection. Input The first line contains two integers n and m (1 ≀ n, m ≀ 1000) β€” the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following n lines contains m integers a_{i,1}, a_{i,2}, ..., a_{i,m} (1 ≀ a_{i,j} ≀ 10^9). The integer a_{i,j}, located on j-th position in the i-th line denotes the height of the skyscraper at the intersection of the i-th Eastern street and j-th Southern direction. Output Print n lines containing m integers each. The integer x_{i,j}, located on j-th position inside the i-th line is an answer for the problem at the intersection of i-th Eastern street and j-th Southern street. Examples Input 2 3 1 2 1 2 1 2 Output 2 2 2 2 2 2 Input 2 2 1 2 3 4 Output 2 3 3 2 Note In the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights. In the second example, the answers are as follows: * For the intersection of the first line and the first column <image> * For the intersection of the first line and the second column <image> * For the intersection of the second line and the first column <image> * For the intersection of the second line and the second column <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1003; int n, m; int a[N][N]; int v[N]; int zt[N], zs[N]; int t[N][N], s[N][N]; map<int, int> mp; int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { scanf("%d", &a[i][j]); } } for (int i = 1; i <= n; ++i) { mp.clear(); for (int j = 1; j <= m; ++j) v[j] = a[i][j]; sort(v + 1, v + m + 1); for (int j = 1; j <= m; ++j) { if (v[j] != v[j - 1]) mp[v[j]] = ++zt[i]; } for (int j = 1; j <= m; ++j) t[i][j] = mp[a[i][j]]; } for (int j = 1; j <= m; ++j) { mp.clear(); for (int i = 1; i <= n; ++i) v[i] = a[i][j]; sort(v + 1, v + n + 1); for (int i = 1; i <= n; ++i) { if (v[i] != v[i - 1]) mp[v[i]] = ++zs[j]; } for (int i = 1; i <= n; ++i) s[i][j] = mp[a[i][j]]; } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { int ans = max(s[i][j], t[i][j]) + max(zs[j] - s[i][j], zt[i] - t[i][j]); printf("%d ", ans); } printf("\n"); } return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: You have a malfunctioning microwave in which you want to put some bananas. You have n time-steps before the microwave stops working completely. At each time-step, it displays a new operation. Let k be the number of bananas in the microwave currently. Initially, k = 0. In the i-th operation, you are given three parameters t_i, x_i, y_i in the input. Based on the value of t_i, you must do one of the following: Type 1: (t_i=1, x_i, y_i) β€” pick an a_i, such that 0 ≀ a_i ≀ y_i, and perform the following update a_i times: k:=⌈ (k + x_i) βŒ‰. Type 2: (t_i=2, x_i, y_i) β€” pick an a_i, such that 0 ≀ a_i ≀ y_i, and perform the following update a_i times: k:=⌈ (k β‹… x_i) βŒ‰. Note that x_i can be a fractional value. See input format for more details. Also, ⌈ x βŒ‰ is the smallest integer β‰₯ x. At the i-th time-step, you must apply the i-th operation exactly once. For each j such that 1 ≀ j ≀ m, output the earliest time-step at which you can create exactly j bananas. If you cannot create exactly j bananas, output -1. Input The first line contains two space-separated integers n (1 ≀ n ≀ 200) and m (2 ≀ m ≀ 10^5). Then, n lines follow, where the i-th line denotes the operation for the i-th timestep. Each such line contains three space-separated integers t_i, x'_i and y_i (1 ≀ t_i ≀ 2, 1≀ y_i≀ m). Note that you are given x'_i, which is 10^5 β‹… x_i. Thus, to obtain x_i, use the formula x_i= \dfrac{x'_i} {10^5}. For type 1 operations, 1 ≀ x'_i ≀ 10^5 β‹… m, and for type 2 operations, 10^5 < x'_i ≀ 10^5 β‹… m. Output Print m integers, where the i-th integer is the earliest time-step when you can obtain exactly i bananas (or -1 if it is impossible). Examples Input 3 20 1 300000 2 2 400000 2 1 1000000 3 Output -1 -1 1 -1 -1 1 -1 -1 -1 3 -1 2 3 -1 -1 3 -1 -1 -1 3 Input 3 20 1 399999 2 2 412345 2 1 1000001 3 Output -1 -1 -1 1 -1 -1 -1 1 -1 -1 3 -1 -1 -1 3 -1 2 -1 3 -1 Note In the first sample input, let us see how to create 16 number of bananas in three timesteps. Initially, k=0. * In timestep 1, we choose a_1=2, so we apply the type 1 update β€” k := ⌈(k+3)βŒ‰ β€” two times. Hence, k is now 6. * In timestep 2, we choose a_2=0, hence value of k remains unchanged. * In timestep 3, we choose a_3=1, so we are applying the type 1 update k:= ⌈(k+10)βŒ‰ once. Hence, k is now 16. It can be shown that k=16 cannot be reached in fewer than three timesteps with the given operations. In the second sample input, let us see how to create 17 number of bananas in two timesteps. Initially, k=0. * In timestep 1, we choose a_1=1, so we apply the type 1 update β€” k := ⌈(k+3.99999)βŒ‰ β€” once. Hence, k is now 4. * In timestep 2, we choose a_2=1, so we apply the type 2 update β€” k := ⌈(kβ‹… 4.12345)βŒ‰ β€” once. Hence, k is now 17. It can be shown that k=17 cannot be reached in fewer than two timesteps with the given operations. ### Response ```cpp #include <bits/stdc++.h> using namespace std; //#pragma GCC optimize("O3") #define DIM 200009 #define INF ((long long)1e18+9ll) #define pairll pair<long long,long long> #define fi first #define se second #define ld long double #define amen exit(0) #define endl '\n' #define MODULO 1000000007 #define fast ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0) #define y1 trymax_lox #define y2 difjkdsdkf long long i,j,k,l,n,m,res; vector<pair<long long,pairll> >a; long long ans[DIM]; set<long long>st1,st2; int main() { fast; cin>>n>>m; for(i=1;i<=n;i++){ cin>>k>>l>>j; a.push_back({k,{l,j}}); } st1.insert(0); for(i=1;i<=m;i++)ans[i]=INF; for(int i=0;i<n;i++){ vector<long long>nums; for(auto to:st1)nums.push_back(to); reverse(nums.begin(),nums.end()); for(auto to:nums){ long long x=to; for(j=1;j<=a[i].se.se;j++){ if(a[i].fi==1)x=(x*100000+a[i].se.fi+99999)/100000; else x=(x*a[i].se.fi)/100000+((x*a[i].se.fi)%100000!=0); if(x>m || st1.count(x))break; ans[x]=i+1; st1.insert(x); } } } for(i=1;i<=m;i++){ if(st1.count(i))cout<<ans[i]<<' '; else cout<<-1<<' '; } cout<<endl; amen; } /* 100000 100001 100000 */ ```
### Prompt Generate a Cpp solution to the following problem: What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until... Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water their favourite flower all year, each day, in the morning, in the afternoon and in the evening. "Wait a second!" β€” thought Petya. He know for a fact that if he fulfills the parents' task in the i-th (1 ≀ i ≀ 12) month of the year, then the flower will grow by ai centimeters, and if he doesn't water the flower in the i-th month, then the flower won't grow this month. Petya also knows that try as he might, his parents won't believe that he has been watering the flower if it grows strictly less than by k centimeters. Help Petya choose the minimum number of months when he will water the flower, given that the flower should grow no less than by k centimeters. Input The first line contains exactly one integer k (0 ≀ k ≀ 100). The next line contains twelve space-separated integers: the i-th (1 ≀ i ≀ 12) number in the line represents ai (0 ≀ ai ≀ 100). Output Print the only integer β€” the minimum number of months when Petya has to water the flower so that the flower grows no less than by k centimeters. If the flower can't grow by k centimeters in a year, print -1. Examples Input 5 1 1 1 1 2 2 3 2 2 1 1 1 Output 2 Input 0 0 0 0 0 0 0 0 1 1 2 3 0 Output 0 Input 11 1 1 4 1 1 5 1 1 4 1 1 1 Output 3 Note Let's consider the first sample test. There it is enough to water the flower during the seventh and the ninth month. Then the flower grows by exactly five centimeters. In the second sample Petya's parents will believe him even if the flower doesn't grow at all (k = 0). So, it is possible for Petya not to water the flower at all. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int arr[12]; for (int i = 0; i < 12; i++) cin >> arr[i]; sort(arr, arr + 12); int len = 0; for (int i = 11; i >= 0; i--) { if (len >= n) { cout << 11 - i << endl; return 0; } len += arr[i]; } if (len >= n) cout << 12 << endl; else cout << -1 << endl; } ```
### Prompt Generate a CPP solution to the following problem: The game of Berland poker is played with a deck of n cards, m of which are jokers. k players play this game (n is divisible by k). At the beginning of the game, each player takes n/k cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to x - y, where x is the number of jokers in the winner's hand, and y is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get 0 points. Here are some examples: * n = 8, m = 3, k = 2. If one player gets 3 jokers and 1 plain card, and another player gets 0 jokers and 4 plain cards, then the first player is the winner and gets 3 - 0 = 3 points; * n = 4, m = 2, k = 4. Two players get plain cards, and the other two players get jokers, so both of them are winners and get 0 points; * n = 9, m = 6, k = 3. If the first player gets 3 jokers, the second player gets 1 joker and 2 plain cards, and the third player gets 2 jokers and 1 plain card, then the first player is the winner, and he gets 3 - 2 = 1 point; * n = 42, m = 0, k = 7. Since there are no jokers, everyone gets 0 jokers, everyone is a winner, and everyone gets 0 points. Given n, m and k, calculate the maximum number of points a player can get for winning the game. Input The first line of the input contains one integer t (1 ≀ t ≀ 500) β€” the number of test cases. Then the test cases follow. Each test case contains three integers n, m and k (2 ≀ n ≀ 50, 0 ≀ m ≀ n, 2 ≀ k ≀ n, k is a divisors of n). Output For each test case, print one integer β€” the maximum number of points a player can get for winning the game. Example Input 4 8 3 2 4 2 4 9 6 3 42 0 7 Output 3 0 1 0 Note Test cases of the example are described in the statement. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1e6 + 5; const int INF = INT_MAX; const int NEINF = INT_MIN; int main() { cin.tie(NULL); ios_base::sync_with_stdio(false); int t; cin >> t; while (t--) { int n, m, k; cin >> n >> m >> k; int tmp = n / k; if (tmp >= m) cout << m << endl; else { int left = m - tmp; k--; int tam; if (left % k == 0) tam = left / k; else tam = left / k + 1; cout << tmp - tam << endl; } } return 0; } ```
### Prompt Construct a CPP code solution to the problem outlined: There are n candies in a row, they are numbered from left to right from 1 to n. The size of the i-th candy is a_i. Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob β€” from right to left. The game ends if all the candies are eaten. The process consists of moves. During a move, the player eats one or more sweets from her/his side (Alice eats from the left, Bob β€” from the right). Alice makes the first move. During the first move, she will eat 1 candy (its size is a_1). Then, each successive move the players alternate β€” that is, Bob makes the second move, then Alice, then again Bob and so on. On each move, a player counts the total size of candies eaten during the current move. Once this number becomes strictly greater than the total size of candies eaten by the other player on their previous move, the current player stops eating and the move ends. In other words, on a move, a player eats the smallest possible number of candies such that the sum of the sizes of candies eaten on this move is strictly greater than the sum of the sizes of candies that the other player ate on the previous move. If there are not enough candies to make a move this way, then the player eats up all the remaining candies and the game ends. For example, if n=11 and a=[3,1,4,1,5,9,2,6,5,3,5], then: * move 1: Alice eats one candy of size 3 and the sequence of candies becomes [1,4,1,5,9,2,6,5,3,5]. * move 2: Alice ate 3 on the previous move, which means Bob must eat 4 or more. Bob eats one candy of size 5 and the sequence of candies becomes [1,4,1,5,9,2,6,5,3]. * move 3: Bob ate 5 on the previous move, which means Alice must eat 6 or more. Alice eats three candies with the total size of 1+4+1=6 and the sequence of candies becomes [5,9,2,6,5,3]. * move 4: Alice ate 6 on the previous move, which means Bob must eat 7 or more. Bob eats two candies with the total size of 3+5=8 and the sequence of candies becomes [5,9,2,6]. * move 5: Bob ate 8 on the previous move, which means Alice must eat 9 or more. Alice eats two candies with the total size of 5+9=14 and the sequence of candies becomes [2,6]. * move 6 (the last): Alice ate 14 on the previous move, which means Bob must eat 15 or more. It is impossible, so Bob eats the two remaining candies and the game ends. Print the number of moves in the game and two numbers: * a β€” the total size of all sweets eaten by Alice during the game; * b β€” the total size of all sweets eaten by Bob during the game. Input The first line contains an integer t (1 ≀ t ≀ 5000) β€” the number of test cases in the input. The following are descriptions of the t test cases. Each test case consists of two lines. The first line contains an integer n (1 ≀ n ≀ 1000) β€” the number of candies. The second line contains a sequence of integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 1000) β€” the sizes of candies in the order they are arranged from left to right. It is guaranteed that the sum of the values of n for all sets of input data in a test does not exceed 2β‹…10^5. Output For each set of input data print three integers β€” the number of moves in the game and the required values a and b. Example Input 7 11 3 1 4 1 5 9 2 6 5 3 5 1 1000 3 1 1 1 13 1 2 3 4 5 6 7 8 9 10 11 12 13 2 2 1 6 1 1 1 1 1 1 7 1 1 1 1 1 1 1 Output 6 23 21 1 1000 0 2 1 2 6 45 46 2 2 1 3 4 2 4 4 3 ### Response ```cpp #include <bits/stdc++.h> int main() { long t; scanf("%ld", &t); while (t--) { long m; scanf("%ld", &m); std::vector<long> ar(m); for (long i = 0; i < m; i++) { scanf("%ld", &ar[i]); } long c(0), a(0), b(0); long x(0), y(m - 1); long cu(0), p(0); while (x <= y) { while ((x <= y) && (cu <= p)) { cu += ar[x]; a += ar[x]; ++x; } p = cu; c += (cu > 0); cu = 0; while ((x <= y) && (cu <= p)) { cu += ar[y]; b += ar[y]; --y; } p = cu; c += (cu > 0); cu = 0; } printf("%ld %ld %ld\n", c, a, b); } return 0; } ```
### Prompt Construct a cpp code solution to the problem outlined: You are given an array a consisting of n positive integers. Initially, you have an integer x = 0. During one move, you can do one of the following two operations: 1. Choose exactly one i from 1 to n and increase a_i by x (a_i := a_i + x), then increase x by 1 (x := x + 1). 2. Just increase x by 1 (x := x + 1). The first operation can be applied no more than once to each i from 1 to n. Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by k (the value k is given). You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 2 β‹… 10^4) β€” the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and k (1 ≀ n ≀ 2 β‹… 10^5; 1 ≀ k ≀ 10^9) β€” the length of a and the required divisior. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9), where a_i is the i-th element of a. It is guaranteed that the sum of n does not exceed 2 β‹… 10^5 (βˆ‘ n ≀ 2 β‹… 10^5). Output For each test case, print the answer β€” the minimum number of moves required to obtain such an array that each its element is divisible by k. Example Input 5 4 3 1 2 1 3 10 6 8 7 1 8 3 7 5 10 8 9 5 10 20 100 50 20 100500 10 25 24 24 24 24 24 24 24 24 24 24 8 8 1 2 3 4 5 6 7 8 Output 6 18 0 227 8 Note Consider the first test case of the example: 1. x=0, a = [1, 2, 1, 3]. Just increase x; 2. x=1, a = [1, 2, 1, 3]. Add x to the second element and increase x; 3. x=2, a = [1, 3, 1, 3]. Add x to the third element and increase x; 4. x=3, a = [1, 3, 3, 3]. Add x to the fourth element and increase x; 5. x=4, a = [1, 3, 3, 6]. Just increase x; 6. x=5, a = [1, 3, 3, 6]. Add x to the first element and increase x; 7. x=6, a = [6, 3, 3, 6]. We obtained the required array. Note that you can't add x to the same element more than once. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int N; cin >> N; while (N--) { long long n, x = 0, s = 0, k, t; scanf("%lld%lld", &n, &k); multiset<long long> a; for (int i = 0; i < n; i++) { scanf("%lld", &t); long long tt = (k - t % k) % k; if (tt) a.insert(tt); } while (a.size()) { multiset<long long>::iterator it = a.lower_bound(x); long long tt = *it; if (it == a.end()) { s += k - x; x = 0; } else { s += tt + 1 - x; x = tt + 1; a.erase(it); } } printf("%lld\n", s); } return 0; } ```
### Prompt Your task is to create a cpp solution to the following problem: Bob is playing a popular game called "Dungeon". The game is played on a rectangular board consisting of W Γ— H squares. Each square is identified with its column and row number, thus the square located in the x-th column and the y-th row is represented as (x, y). The left-most square in the top row is (0, 0) and the right-most square in the bottom row is (W-1, H-1). Bob moves a character "BomBom" to clear the game. BomBom is initially located at (0, 0). The game is won if Bob successfully destroys all the enemy characters on the board by manipulating BomBom cleverly. The enemy characters are fixed on specific squares, and Bob can manipulate BomBom using the following two operations any number of times. * One-square movement in the up, down, left, or right direction within the board * Using a bomb, eliminate all the enemy characters that are located in the same column and row as that of BomBom BomBom consumes a Cost when it moves from one square to another. BomBom can use a bomb any number of times without consuming a Cost. Use of a bomb has no effect on BomBom’s behavior and it can move even to a square where an enemy character is located. Given the board size and enemy information, make a program to evaluate the minimum Cost BomBom consumes before it destroys all enemy characters. Input The input is given in the following format. W H N x_1 y_1 x_2 y_2 : x_N y_N The first line provides the number of squares in the horizontal direction W (1 ≀ W ≀ 105), in the vertical direction H (1 ≀ H ≀ 105), and the number of enemy characters N (1 ≀ N ≀ 105). Each of the subsequent N lines provides location information of the i-th enemy, column x_i (0 ≀ x_i ≀ W-1) and row y_i (0 ≀ y_i ≀ H-1). The number of enemy characters in a specific square can be either one or zero. Output Output the minimum Cost in a line. Examples Input 5 4 4 0 3 1 1 2 2 2 3 Output 2 Input 6 6 5 2 1 5 2 3 3 1 4 1 5 Output 4 Input 8 8 4 6 0 7 0 0 6 0 7 Output 0 ### Response ```cpp #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <set> #include <bitset> #include <cmath> #include <string> #define FI first #define SE second #define PF push_front #define PB push_back #define PPF pop_front #define PPB pop_back #define MA make_pair #define ll long long #define PA pair<int,int> #define VE vector<int> #define VP vector<PA> #define FOR(i,a,b) for(int i=a;i<b;i++) #define ROF(i,a,b) for(int i=b-1;i>=a;i--) #define YES(i) cout<<(i?"YES":"NO")<<endl #define Yes(i) cout<<(i?"Yes":"No")<<endl using namespace std; // const int INF=1e9+7; const int mod=1e9+7; // // struct poi{ int X;int Y;int Z; bool operator<(const poi&R)const{ return X==R.X ? Y==R.Y ? Z<R.Z : Y<R.Y : X<R.X; } }; // // int main(){ int W,H,N; VP V; cin>>W>>H>>N; FOR(i,0,N){ int X,Y; cin>>X>>Y; V.PB(MA(X,Y)); } sort(V.begin(),V.end()); if(N==1){ cout<<min(V[0].FI,V[0].SE)<<endl; return 0; } VP mid; int now=0; while(now<N-1){ while(now<N-1&&V[now].FI==V[now+1].FI){ now++; } mid.PB(V[now]); now++; if(now==N-1){ mid.PB(V[now]); } } VP ans; ans.PB(mid.back()); ROF(i,0,(int)mid.size()){ if(mid[i].SE>ans.back().SE){ ans.PB(mid[i]); } } reverse(ans.begin(),ans.end()); int a=min(ans[0].SE,ans.back().FI); FOR(i,0,(int)ans.size()-1){ a=min(a,ans[i].FI+ans[i+1].SE); } cout<<a<<endl; return 0; } ```
### Prompt In cpp, your task is to solve the following problem: One must train much to do well on wizardry contests. So, there are numerous wizardry schools and magic fees. One of such magic schools consists of n tours. A winner of each tour gets a huge prize. The school is organised quite far away, so one will have to take all the prizes home in one go. And the bags that you've brought with you have space for no more than k huge prizes. Besides the fact that you want to take all the prizes home, you also want to perform well. You will consider your performance good if you win at least l tours. In fact, years of organizing contests proved to the organizers that transporting huge prizes is an issue for the participants. Alas, no one has ever invented a spell that would shrink the prizes... So, here's the solution: for some tours the winner gets a bag instead of a huge prize. Each bag is characterized by number ai β€” the number of huge prizes that will fit into it. You already know the subject of all tours, so you can estimate the probability pi of winning the i-th tour. You cannot skip the tour under any circumstances. Find the probability that you will perform well on the contest and will be able to take all won prizes home (that is, that you will be able to fit all the huge prizes that you won into the bags that you either won or brought from home). Input The first line contains three integers n, l, k (1 ≀ n ≀ 200, 0 ≀ l, k ≀ 200) β€” the number of tours, the minimum number of tours to win, and the number of prizes that you can fit in the bags brought from home, correspondingly. The second line contains n space-separated integers, pi (0 ≀ pi ≀ 100) β€” the probability to win the i-th tour, in percents. The third line contains n space-separated integers, ai (1 ≀ ai ≀ 200) β€” the capacity of the bag that will be awarded to you for winning the i-th tour, or else -1, if the prize for the i-th tour is a huge prize and not a bag. Output Print a single real number β€” the answer to the problem. The answer will be accepted if the absolute or relative error does not exceed 10 - 6. Examples Input 3 1 0 10 20 30 -1 -1 2 Output 0.300000000000 Input 1 1 1 100 123 Output 1.000000000000 Note In the first sample we need either win no tour or win the third one. If we win nothing we wouldn't perform well. So, we must to win the third tour. Other conditions will be satisfied in this case. Probability of wining the third tour is 0.3. In the second sample we win the only tour with probability 1.0, and go back home with bag for it. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, l, k, i, p[256], a[256], j, w; double f[201][512][201], aa; int main() { scanf("%d%d%d", &n, &l, &k); k = min(k, n); for (i = 0; i < n; ++i) scanf("%d", p + i); for (i = 0; i < n; ++i) scanf("%d", a + i); f[0][k + 256][0] = 1; for (i = 0; i < n; ++i) for (j = -i; j <= n; ++j) for (w = 0; w <= i; ++w) if (f[i][j + 256][w] > 0) { f[i + 1][256 + min(j + a[i], n)][w + 1] += f[i][j + 256][w] * p[i] / 100; f[i + 1][j + 256][w] += f[i][j + 256][w] * (100 - p[i]) / 100; } for (j = 0; j <= n; ++j) for (w = l; w <= n; ++w) aa += f[n][j + 256][w]; printf("%.12lf\n", aa); return 0; } ```
### Prompt Develop a solution in cpp to the problem described below: You are given two integers b and w. You have a chessboard of size 10^9 Γ— 10^9 with the top left cell at (1; 1), the cell (1; 1) is painted white. Your task is to find a connected component on this chessboard that contains exactly b black cells and exactly w white cells. Two cells are called connected if they share a side (i.e. for the cell (x, y) there are at most four connected cells: (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)). A set of cells is called a connected component if for every pair of cells C_1 and C_2 from this set, there exists a sequence of cells c_1, c_2, ..., c_k such that c_1 = C_1, c_k = C_2, all c_i from 1 to k are belong to this set of cells and for every i ∈ [1, k - 1], cells c_i and c_{i + 1} are connected. Obviously, it can be impossible to find such component. In this case print "NO". Otherwise, print "YES" and any suitable connected component. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≀ q ≀ 10^5) β€” the number of queries. Then q queries follow. The only line of the query contains two integers b and w (1 ≀ b, w ≀ 10^5) β€” the number of black cells required and the number of white cells required. It is guaranteed that the sum of numbers of cells does not exceed 2 β‹… 10^5 (βˆ‘ w + βˆ‘ b ≀ 2 β‹… 10^5). Output For each query, print the answer to it. If it is impossible to find the required component, print "NO" on the first line. Otherwise, print "YES" on the first line. In the next b + w lines print coordinates of cells of your component in any order. There should be exactly b black cells and w white cells in your answer. The printed component should be connected. If there are several answers, you can print any. All coordinates in the answer should be in the range [1; 10^9]. Example Input 3 1 1 1 4 2 5 Output YES 2 2 1 2 YES 2 3 1 3 3 3 2 2 2 4 YES 2 3 2 4 2 5 1 3 1 5 3 3 3 5 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int b, w; cin >> b >> w; if (1 + min(b, w) * 3 < max(b, w)) { puts("NO"); continue; } else puts("YES"); if (w > b) { int x = 2; cout << "1 3" << endl; w--; while (w - b >= 1) { cout << x << " " << 3 << endl; if ((x & 1) == 0) { cout << x << " " << 2 << endl; cout << x << " " << 4 << endl; w -= 2, b--; } else w--; x++; } while (w || b) { cout << x << " " << 3 << endl; if ((x & 1) == 0) b--; else w--; x++; } } else { int x = 3; cout << "2 3" << endl; b--; while (b - w >= 1) { cout << x << " " << 3 << endl; if (x & 1) { cout << x << " " << 2 << endl; cout << x << " " << 4 << endl; b -= 2, w--; } else b--; x++; } while (w || b) { cout << x << " " << 3 << endl; if (x & 1) w--; else b--; x++; } } } return 0; } ```
### Prompt Please create a solution in CPP to the following problem: A New Year party is not a New Year party without lemonade! As usual, you are expecting a lot of guests, and buying lemonade has already become a pleasant necessity. Your favorite store sells lemonade in bottles of n different volumes at different costs. A single bottle of type i has volume 2i - 1 liters and costs ci roubles. The number of bottles of each type in the store can be considered infinite. You want to buy at least L liters of lemonade. How many roubles do you have to spend? Input The first line contains two integers n and L (1 ≀ n ≀ 30; 1 ≀ L ≀ 109) β€” the number of types of bottles in the store and the required amount of lemonade in liters, respectively. The second line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 109) β€” the costs of bottles of different types. Output Output a single integer β€” the smallest number of roubles you have to pay in order to buy at least L liters of lemonade. Examples Input 4 12 20 30 70 90 Output 150 Input 4 3 10000 1000 100 10 Output 10 Input 4 3 10 100 1000 10000 Output 30 Input 5 787787787 123456789 234567890 345678901 456789012 987654321 Output 44981600785557577 Note In the first example you should buy one 8-liter bottle for 90 roubles and two 2-liter bottles for 30 roubles each. In total you'll get 12 liters of lemonade for just 150 roubles. In the second example, even though you need only 3 liters, it's cheaper to buy a single 8-liter bottle for 10 roubles. In the third example it's best to buy three 1-liter bottles for 10 roubles each, getting three liters for 30 roubles. ### Response ```cpp #include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC target("avx,avx2,fma") #pragma GCC optimization("unroll-loops") const long long int inf = 9e18; const long double pi = 2 * acos(0.0); using namespace std; long long int power(long long int a, long long int n) { if (n == 0) { return 1; } long long int p = power(a, n / 2) % 1000000007; p = (p * p) % 1000000007; if (n % 2 == 1) { p = (p * a) % 1000000007; } return p % 1000000007; } long long int gcd(long long int a, long long int b) { if (a == 0) return b; return gcd(b % a, a); } const int N = 1e6 + 5; vector<long long int> sieve(N, 0); void si() { sieve[1] = 1; for (int i = 2; i < N; i++) { if (sieve[i] == 0) { sieve[i] = 1; for (int j = 2 * i; j < N; j += i) { sieve[j] = i; } } } } vector<long long int> dp(30, 0); long long int n, L; long long int solve(long long int val, long long int curr) { long long int bit = -1; for (long long int i = 29; i >= 0; i--) { if ((val) & (1 << i)) { bit = i; break; } } long long int curr1 = curr, curr2; if (bit != 29) { curr1 = curr + dp[bit + 1]; } else { curr1 = 1e18; } curr += dp[bit]; val = val - (1 << bit); if (val != 0) { curr2 = solve(val, curr); } else { curr2 = curr; } return min(curr1, curr2); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); ; cin >> n >> L; vector<long long int> a(n); ; for (long long int i = 0; i < n; i++) cin >> a[i]; ; dp[0] = a[0]; for (int i = 1; i < n; i++) { dp[i] = min(a[i], 2 * dp[i - 1]); } for (int i = n; i < 30; i++) { dp[i] = 2 * dp[i - 1]; } long long int mini = 1e18; for (int i = 29; i >= 0; i--) { if (mini < dp[i]) { dp[i] = mini; } mini = min(mini, dp[i]); } long long int ans = solve(L, 0); cout << ans << endl; return 0; } ```
### Prompt Develop a solution in cpp to the problem described below: Problem Statement Circles Island is known for its mysterious shape: it is a completely flat island with its shape being a union of circles whose centers are on the $x$-axis and their inside regions. The King of Circles Island plans to build a large square on Circles Island in order to celebrate the fiftieth anniversary of his accession. The King wants to make the square as large as possible. The whole area of the square must be on the surface of Circles Island, but any area of Circles Island can be used for the square. He also requires that the shape of the square is square (of course!) and at least one side of the square is parallel to the $x$-axis. You, a minister of Circles Island, are now ordered to build the square. First, the King wants to know how large the square can be. You are given the positions and radii of the circles that constitute Circles Island. Answer the side length of the largest possible square. $N$ circles are given in an ascending order of their centers' $x$-coordinates. You can assume that for all $i$ ($1 \le i \le N-1$), the $i$-th and $(i+1)$-st circles overlap each other. You can also assume that no circles are completely overlapped by other circles. <image> [fig.1 : Shape of Circles Island and one of the largest possible squares for test case #1 of sample input] Input The input consists of multiple datasets. The number of datasets does not exceed $30$. Each dataset is formatted as follows. > $N$ > $X_1$ $R_1$ > : > : > $X_N$ $R_N$ The first line of a dataset contains a single integer $N$ ($1 \le N \le 50{,}000$), the number of circles that constitute Circles Island. Each of the following $N$ lines describes a circle. The $(i+1)$-st line contains two integers $X_i$ ($-100{,}000 \le X_i \le 100{,}000$) and $R_i$ ($1 \le R_i \le 100{,}000$). $X_i$ denotes the $x$-coordinate of the center of the $i$-th circle and $R_i$ denotes the radius of the $i$-th circle. The $y$-coordinate of every circle is $0$, that is, the center of the $i$-th circle is at ($X_i$, $0$). You can assume the followings. * For all $i$ ($1 \le i \le N-1$), $X_i$ is strictly less than $X_{i+1}$. * For all $i$ ($1 \le i \le N-1$), the $i$-th circle and the $(i+1)$-st circle have at least one common point ($X_{i+1} - X_i \le R_i + R_{i+1}$). * Every circle has at least one point that is not inside or on the boundary of any other circles. The end of the input is indicated by a line containing a zero. Output For each dataset, output a line containing the side length of the square with the largest area. The output must have an absolute or relative error at most $10^{-4}$. Sample Input 2 0 8 10 8 2 0 7 10 7 0 Output for the Sample Input 12.489995996796796 9.899494936611665 Example Input 2 0 8 10 8 2 0 7 10 7 0 Output 12.489995996796796 9.899494936611665 ### Response ```cpp #include "bits/stdc++.h" using namespace std; using ld = long double; const ld eps = 1e-9; int N; bool check(const vector<pair<ld, ld>>&cs, const ld amid) { map<ld, int>mp; for (auto c : cs) { const ld r = c.second; const ld x = c.first; if (r > amid) { ld dis = sqrt(r*r - amid*amid); mp[x - dis]++; mp[x + dis]--; } } ld pre = -1; int num = 0; ld len = 0; bool preok = false; for (auto m : mp) { num += m.second; if (num) { if (!preok) { pre = m.first; } } else { if (preok) { len = max(len, m.first - pre); } } preok = num; } return amid*2 < len; } int main() { while (1) { cin >> N; if (!N)break; vector<pair<ld, ld>>cs; for (int i = 0; i < N; ++i) { int x, r; cin >> x >> r; cs.push_back(make_pair(x, r)); } ld amin = 0; ld amax = 1e6; int atime = 40; while (atime--) { ld amid = (amin + amax) / 2; if (check(cs, amid)) { amin = amid; } else { amax = amid; } } cout << setprecision(22) << fixed << amin*2 << endl; } return 0; } ```
### Prompt Construct a Cpp code solution to the problem outlined: We have a square grid with H rows and W columns. Snuke wants to write 0 or 1 in each of the squares. Here, all of the following conditions have to be satisfied: * For every row, the smaller of the following is A: the number of 0s contained in the row, and the number of 1s contained in the row. (If these two numbers are equal, β€œthe smaller” should be read as β€œeither”.) * For every column, the smaller of the following is B: the number of 0s contained in the column, and the number of 1s contained in the column. Determine if these conditions can be satisfied by writing 0 or 1 in each of the squares. If the answer is yes, show one way to fill the squares so that the conditions are satisfied. Constraints * 1 \leq H,W \leq 1000 * 0 \leq A * 2 \times A \leq W * 0 \leq B * 2 \times B \leq H * All values in input are integers. Input Input is given from Standard Input in the following format: H W A B Output If the conditions cannot be satisfied by writing 0 or 1 in each of the squares, print -1. If the conditions can be satisfied, print one way to fill the squares so that the conditions are satisfied, in the following format: s_{11}s_{12}\cdots s_{1W} s_{21}s_{22}\cdots s_{2W} \vdots s_{H1}s_{H2}\cdots s_{HW} Here s_{ij} is the digit written in the square at the i-th row from the top and the j-th column from the left in the grid. If multiple solutions exist, printing any of them will be accepted. Examples Input 3 3 1 1 Output 100 010 001 Input 1 5 2 0 Output 01010 ### Response ```cpp #include<bits/stdc++.h> using namespace std; int h, w, a, b; int main() { scanf("%d %d %d %d", &h, &w, &a, &b); for (int i = 1; i <= h; ++i) { for (int j = 1; j <= w; ++j) { if ( (i <= b) == (j <= a) ) cout << 0; else cout << 1; } cout << '\n'; } return 0; } ```
### Prompt Your task is to create a CPP solution to the following problem: Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≀ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1]. The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≀ x ≀ rj. Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k. Input The first line contains two integers n and k (1 ≀ n, k ≀ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≀ li ≀ ri ≀ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≀ i < j ≀ n) the following inequality holds, min(ri, rj) < max(li, lj). Output In a single line print a single integer β€” the answer to the problem. Examples Input 2 3 1 2 3 4 Output 2 Input 3 7 1 2 3 3 4 7 Output 0 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, k; int s; int main() { cin >> n >> k; for (int i = 0; i < n; i++) { int a, b; cin >> a >> b; s += (b - a + 1); } if (s % k == 0) cout << 0 << endl; else cout << (k - s % k) << endl; } ```