text
stringlengths
424
69.5k
### Prompt Please create a solution in cpp to the following problem: Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases: 1. They are equal. 2. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2, then one of the following is correct: 1. a1 is equivalent to b1, and a2 is equivalent to b2 2. a1 is equivalent to b2, and a2 is equivalent to b1 As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent. Gerald has already completed this home task. Now it's your turn! Input The first two lines of the input contain two strings given by the teacher. Each of them has the length from 1 to 200 000 and consists of lowercase English letters. The strings have the same length. Output Print "YES" (without the quotes), if these two strings are equivalent, and "NO" (without the quotes) otherwise. Examples Input aaba abaa Output YES Input aabb abab Output NO Note In the first sample you should split the first string into strings "aa" and "ba", the second one — into strings "ab" and "aa". "aa" is equivalent to "aa"; "ab" is equivalent to "ba" as "ab" = "a" + "b", "ba" = "b" + "a". In the second sample the first string can be splitted into strings "aa" and "bb", that are equivalent only to themselves. That's why string "aabb" is equivalent only to itself and to string "bbaa". ### Response ```cpp #include <bits/stdc++.h> using namespace std; string s1, s2; int n; bool iseq(int l1, int l2, int r1, int r2) { int len = l2 - l1 + 1; if (len % 2 == 1) { for (int k = 0; k < len; k++) { if (s1[k + l1] != s2[k + r1]) { return false; } } return true; } else { int m1 = l1 + len / 2; int m2 = r1 + len / 2; return (iseq(l1, m1 - 1, r1, m2 - 1) && iseq(m1, l2, m2, r2)) || (iseq(l1, m1 - 1, m2, r2) && iseq(m1, l2, r1, m2 - 1)); } } int main() { cin >> s1; cin >> s2; n = s1.size(); if (iseq(0, n - 1, 0, n - 1)) cout << "YES\n"; else cout << "NO\n"; return 0; } ```
### Prompt Develop a solution in Cpp to the problem described below: AtCoDeer is thinking of painting an infinite two-dimensional grid in a checked pattern of side K. Here, a checked pattern of side K is a pattern where each square is painted black or white so that each connected component of each color is a K × K square. Below is an example of a checked pattern of side 3: cba927b2484fad94fb5ff7473e9aadef.png AtCoDeer has N desires. The i-th desire is represented by x_i, y_i and c_i. If c_i is `B`, it means that he wants to paint the square (x_i,y_i) black; if c_i is `W`, he wants to paint the square (x_i,y_i) white. At most how many desires can he satisfy at the same time? Constraints * 1 ≤ N ≤ 10^5 * 1 ≤ K ≤ 1000 * 0 ≤ x_i ≤ 10^9 * 0 ≤ y_i ≤ 10^9 * If i ≠ j, then (x_i,y_i) ≠ (x_j,y_j). * c_i is `B` or `W`. * N, K, x_i and y_i are integers. Input Input is given from Standard Input in the following format: N K x_1 y_1 c_1 x_2 y_2 c_2 : x_N y_N c_N Output Print the maximum number of desires that can be satisfied at the same time. Examples Input 4 3 0 1 W 1 2 W 5 3 B 5 4 B Output 4 Input 2 1000 0 0 B 0 1 W Output 2 Input 6 2 1 2 B 2 1 W 2 2 B 1 0 B 0 6 W 4 5 W Output 4 ### Response ```cpp #include<iostream> using namespace std; int n,m,pd[100001],x1[100001],y1[100001],ans; int main() { cin>>n>>m; for(int i=1; i<=n; i++) { int x,y; char c; cin>>x>>y>>c; x%=2*m,y%=2*m; if(c=='W')pd[i]=1; else pd[i]=0; x1[i]=x; y1[i]=y; } for(int i=0; i<=m; i++) { int big=0,hh[10001]={0}; for(int j=1; j<=n; j++) { int p=(i<=x1[j]&&x1[j]<i+m); int q=(0<=y1[j]&&y1[j]<m); if(p^q==pd[j]) { big++; hh[y1[j]]++; } else{ hh[y1[j]]--; } } for(int j=0; j<=m; j++) { ans=max(big,max(ans,n-big)); if(j!=m)big=big-hh[j]-hh[j+m]; } } cout<<ans; } ```
### Prompt Please create a solution in cpp to the following problem: Problem Statement You are given a connected undirected graph which has even numbers of nodes. A connected graph is a graph in which all nodes are connected directly or indirectly by edges. Your task is to find a spanning tree whose median value of edges' costs is minimum. A spanning tree of a graph means that a tree which contains all nodes of the graph. Input The input consists of multiple datasets. The format of each dataset is as follows. n m s_1 t_1 c_1 ... s_m t_m c_m The first line contains an even number n (2 \leq n \leq 1,000) and an integer m (n-1 \leq m \leq 10,000). n is the nubmer of nodes and m is the number of edges in the graph. Then m lines follow, each of which contains s_i (1 \leq s_i \leq n), t_i (1 \leq s_i \leq n, t_i \neq s_i) and c_i (1 \leq c_i \leq 1,000). This means there is an edge between the nodes s_i and t_i and its cost is c_i. There is no more than one edge which connects s_i and t_i. The input terminates when n=0 and m=0. Your program must not output anything for this case. Output Print the median value in a line for each dataset. Example Input 2 1 1 2 5 4 6 1 2 1 1 3 2 1 4 3 2 3 4 2 4 5 3 4 6 8 17 1 4 767 3 1 609 8 3 426 6 5 972 8 1 607 6 4 51 5 1 683 3 6 451 3 4 630 8 7 912 3 7 43 4 7 421 3 5 582 8 4 538 5 7 832 1 6 345 8 2 608 0 0 Output 5 2 421 ### Response ```cpp #include <bits/stdc++.h> using namespace std; #define fi first #define se second #define repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++) #define repr(i,n) for(int i=(int)(n-1);i>=0;i--) #define rep(i,n) repl(i,0,n) #define each(itr,v) for(auto itr:v) #define pb(s) push_back(s) #define all(x) (x).begin(),(x).end() #define dbg(x) cout << #x" = " << x << endl #define print(x) cout << x << endl #define maxch(x,y) x=max(x,y) #define minch(x,y) x=min(x,y) #define uni(x) x.erase(unique(all(x)),x.end()) #define exist(x,y) (find(all(x),y)!=x.end()) #define bcnt(x) bitset<32>(x).count() typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> P; typedef pair<P, int> PPI; typedef pair<int, P> PIP; typedef pair<ll, ll> PL; typedef pair<P, ll> PPL; typedef set<int> S; #define INF INT_MAX/3 #define MAX_N 1000000001 int par[1000]; struct Edge { int s, t, c; }; bool operator<(const Edge &a, const Edge &b) { return a.c < b.c; } int find(int v) { if (v == par[v]) return v; return par[v] = find(par[v]); } void unite(int u, int v) { u = find(u); v = find(v); if (u == v) return; par[u] = v; } int main(){ cin.sync_with_stdio(false); int n, m; while(cin >> n >> m, n | m) { iota(par, par + n, 0); vector<Edge> e(m); rep(i, m) { cin >> e[i].s >> e[i].t >> e[i].c; e[i].s--, e[i].t--; } sort(all(e)); vector<int> cost; rep(i, m) { if (find(e[i].s) != find(e[i].t)) { unite(e[i].s, e[i].t); cost.pb(e[i].c); } } cout << cost[cost.size() / 2] << endl; } return 0; } ```
### Prompt Develop a solution in CPP to the problem described below: We have a grid with H rows and W columns. At first, all cells were painted white. Snuke painted N of these cells. The i-th ( 1 \leq i \leq N ) cell he painted is the cell at the a_i-th row and b_i-th column. Compute the following: * For each integer j ( 0 \leq j \leq 9 ), how many subrectangles of size 3×3 of the grid contains exactly j black cells, after Snuke painted N cells? Constraints * 3 \leq H \leq 10^9 * 3 \leq W \leq 10^9 * 0 \leq N \leq min(10^5,H×W) * 1 \leq a_i \leq H (1 \leq i \leq N) * 1 \leq b_i \leq W (1 \leq i \leq N) * (a_i, b_i) \neq (a_j, b_j) (i \neq j) Input The input is given from Standard Input in the following format: H W N a_1 b_1 : a_N b_N Output Print 10 lines. The (j+1)-th ( 0 \leq j \leq 9 ) line should contain the number of the subrectangles of size 3×3 of the grid that contains exactly j black cells. Examples Input 4 5 8 1 1 1 4 1 5 2 3 3 1 3 2 3 4 4 4 Output 0 0 0 2 4 0 0 0 0 0 Input 10 10 20 1 1 1 4 1 9 2 5 3 10 4 2 4 7 5 9 6 4 6 6 6 7 7 1 7 3 7 7 8 1 8 5 8 10 9 2 10 4 10 9 Output 4 26 22 10 2 0 0 0 0 0 Input 1000000000 1000000000 0 Output 999999996000000004 0 0 0 0 0 0 0 0 0 ### Response ```cpp #include<bits/stdc++.h> using namespace std; int H,W,N,a,b; long long res[10]; map<pair<int,int>,int>mp; int main(){ cin>>H>>W>>N; for(int i=0;i!=N;++i){ cin>>a>>b; for(int j=max(1,a-2);j<=a&&j<=H-2;++j) for(int k=max(1,b-2);k<=b&&k<=W-2;++k) ++mp[make_pair(j,k)]; } for(auto it=mp.begin();it!=mp.end();++it){ ++res[it->second]; } res[0]=(long long)(H-2)*(W-2); for(int i=1;i!=10;++i) res[0]-=res[i]; for(int i=0;i!=10;++i) cout<<res[i]<<endl; return 0; } ```
### Prompt Please formulate a cpp solution to the following problem: A non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, "abcba", "a", and "abba" are palindromes, while "abab" and "xy" are not. A string is called a substring of another string, if it can be obtained from that string by dropping some (possibly zero) number of characters from the beginning and from the end of it. For example, "abc", "ab", and "c" are substrings of the string "abc", while "ac" and "d" are not. Let's define a palindromic count of the string as the number of its substrings that are palindromes. For example, the palindromic count of the string "aaa" is 6 because all its substrings are palindromes, and the palindromic count of the string "abc" is 3 because only its substrings of length 1 are palindromes. You are given a string s. You can arbitrarily rearrange its characters. You goal is to obtain a string with the maximum possible value of palindromic count. Input The first line contains an integer n (1 ≤ n ≤ 100 000) — the length of string s. The second line contains string s that consists of exactly n lowercase characters of Latin alphabet. Output Print string t, which consists of the same set of characters (and each characters appears exactly the same number of times) as string s. Moreover, t should have the maximum possible value of palindromic count among all such strings strings. If there are multiple such strings, print any of them. Examples Input 5 oolol Output ololo Input 16 gagadbcgghhchbdf Output abccbaghghghgdfd Note In the first example, string "ololo" has 9 palindromic substrings: "o", "l", "o", "l", "o", "olo", "lol", "olo", "ololo". Note, that even though some substrings coincide, they are counted as many times as they appear in the resulting string. In the second example, the palindromic count of string "abccbaghghghgdfd" is 29. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int Alpha = 26; using Cnt = array<int, Alpha>; class TSolver { public: int n; string init; explicit TSolver(std::istream& in) { cnt.fill(0); string s; in >> n >> s; for (unsigned char c : s) { ++cnt[c - 'a']; } init = s; } Cnt cnt; string ans; void Solve() { while (n > int(ans.size())) { int max1 = -1, max2 = -1; for (int i = 0; i < Alpha; ++i) { if (cnt[i]) { if (max1 == -1 || cnt[i] > cnt[max1]) { max2 = max1; max1 = i; } else if (max2 == -1 || cnt[i] > cnt[max2]) { max2 = i; } } } assert(max1 != -1); while (cnt[max1]) { ans.push_back(char('a' + max1)); --cnt[max1]; if (max2 != -1 && cnt[max2]) { ans.push_back(char('a' + max2)); --cnt[max2]; } } } ans = init; sort((ans).begin(), (ans).end()); } void PrintAnswer(std::ostream& out) const { out << ans << '\n'; } }; int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); { auto solver = std::make_shared<TSolver>(std::cin); solver->Solve(); solver->PrintAnswer(std::cout); } do { } while (false); return 0; } ```
### Prompt In Cpp, your task is to solve the following problem: Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied. The classroom contains n rows of seats and there are m seats in each row. Then the classroom can be represented as an n × m matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find k consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs. Input The first line contains three positive integers n,m,k (1 ≤ n, m, k ≤ 2 000), where n,m represent the sizes of the classroom and k is the number of consecutive seats you need to find. Each of the next n lines contains m characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat. Output A single number, denoting the number of ways to find k empty seats in the same row or column. Examples Input 2 3 2 **. ... Output 3 Input 1 2 2 .. Output 1 Input 3 3 4 .*. *.* .*. Output 0 Note In the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement. * (1,3), (2,3) * (2,2), (2,3) * (2,1), (2,2) ### Response ```cpp #include <bits/stdc++.h> using namespace std; bool matrix[2005][2005]; int main() { ios::sync_with_stdio(false); int n, m, k; cin >> n >> m >> k; string s; getline(cin, s); for (int y = 0; y < n; y++) { getline(cin, s); for (int x = 0; x < m; x++) matrix[x][y] = s[x] == '.'; } int result = 0; for (int x = 0; x < m; x++) { int cnt = 0; for (int y = 0; y < n; y++) { if (matrix[x][y]) cnt++; else { result += max(0, cnt - k + 1); cnt = 0; } } result += max(0, cnt - k + 1); } if (k != 1) { for (int y = 0; y < n; y++) { int cnt = 0; for (int x = 0; x < m; x++) { if (matrix[x][y]) cnt++; else { result += max(0, cnt - k + 1); cnt = 0; } } result += max(0, cnt - k + 1); } } cout << result << endl; } ```
### Prompt Create a solution in CPP for the following problem: You are given an array a of size n, and q queries to it. There are queries of two types: * 1 li ri — perform a cyclic shift of the segment [li, ri] to the right. That is, for every x such that li ≤ x < ri new value of ax + 1 becomes equal to old value of ax, and new value of ali becomes equal to old value of ari; * 2 li ri — reverse the segment [li, ri]. There are m important indices in the array b1, b2, ..., bm. For each i such that 1 ≤ i ≤ m you have to output the number that will have index bi in the array after all queries are performed. Input The first line contains three integer numbers n, q and m (1 ≤ n, q ≤ 2·105, 1 ≤ m ≤ 100). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109). Then q lines follow. i-th of them contains three integer numbers ti, li, ri, where ti is the type of i-th query, and [li, ri] is the segment where this query is performed (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). The last line contains m integer numbers b1, b2, ..., bm (1 ≤ bi ≤ n) — important indices of the array. Output Print m numbers, i-th of which is equal to the number at index bi after all queries are done. Example Input 6 3 5 1 2 3 4 5 6 2 1 3 2 3 6 1 1 6 2 2 1 5 3 Output 3 3 1 5 2 ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct node { int ch, l, r; }; int main() { int n, q, m; scanf("%d%d%d", &n, &q, &m); int a[n]; for (int i = 0; i < n; i++) scanf("%d", &a[i]); node b[q]; for (int i = 0; i < q; i++) { scanf("%d%d%d", &b[i].ch, &b[i].l, &b[i].r); b[i].l--; b[i].r--; } while (m--) { int x; scanf("%d", &x); x--; for (int i = q - 1; i >= 0; i--) { if (x >= b[i].l && x <= b[i].r) { if (b[i].ch == 1) { if (x == b[i].l) x = b[i].r; else x--; } else { x = b[i].l + b[i].r - x; } } } printf("%d\n", a[x]); } return 0; } ```
### Prompt Your challenge is to write a CPP solution to the following problem: Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him? Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous). If it is possible to partition the array, also give any possible way of valid partitioning. Input The first line will contain three space separated integers n, k, p (1 ≤ k ≤ n ≤ 105; 0 ≤ p ≤ k). The next line will contain n space-separated distinct integers representing the content of array a: a1, a2, ..., an (1 ≤ ai ≤ 109). Output In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes). If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition. Examples Input 5 5 3 2 6 10 5 9 Output YES 1 9 1 5 1 10 1 6 1 2 Input 5 5 3 7 14 2 9 5 Output NO Input 5 3 1 1 2 3 7 5 Output YES 3 5 1 3 1 7 1 2 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n, odd, even; scanf("%d%d%d", &n, &odd, &even); odd -= even; vector<int> odd_num, even_num; for (int i = 0; i < n; i++) { int t; scanf("%d", &t); (t & 1 ? odd_num : even_num).push_back(t); } if (odd_num.size() < odd || (odd_num.size() - odd) & 1 || ((odd_num.size() - odd) >> 1) + even_num.size() < even) printf("NO\n"); else { printf("YES\n"); vector<vector<int> > odd_part(odd); for (int i = 0; i < odd; i++) { odd_part[i].push_back(odd_num.back()); odd_num.pop_back(); } vector<vector<int> > even_part(even); for (int i = 0; i < even; i++) { if (!even_num.empty()) { even_part[i].push_back(even_num.back()); even_num.pop_back(); } else { even_part[i].push_back(odd_num.back()); odd_num.pop_back(); even_part[i].push_back(odd_num.back()); odd_num.pop_back(); } } if (!odd_num.empty()) { if (odd > 0) for (; !odd_num.empty(); odd_num.pop_back()) odd_part[0].push_back(odd_num.back()); else for (; !odd_num.empty(); odd_num.pop_back()) even_part[0].push_back(odd_num.back()); } if (!even_num.empty()) { if (odd > 0) for (; !even_num.empty(); even_num.pop_back()) odd_part[0].push_back(even_num.back()); else for (; !even_num.empty(); even_num.pop_back()) even_part[0].push_back(even_num.back()); } for (int i = 0; i < odd; i++) { printf("%lu", odd_part[i].size()); for (int j = odd_part[i].size() - 1; j >= 0; j--) printf(" %d", odd_part[i][j]); printf("\n"); } for (int i = 0; i < even; i++) { printf("%lu", even_part[i].size()); for (int j = even_part[i].size() - 1; j >= 0; j--) printf(" %d", even_part[i][j]); printf("\n"); } } } ```
### Prompt Please create a solution in Cpp to the following problem: Furik loves painting stars. A star is a shape that results if we take a regular pentagon and paint all diagonals in it. <image> Recently he decided to teach Rubik to paint stars. After many years of training Rubik could paint stars easily. But now Furik decided to test Rubik and complicated the task. Rubik must paint n stars, observing the following rules: * all stars must be painted in a single move (i.e. it is forbidden to take the pen away from the paper); * it is forbidden to paint the same segment of non-zero length more than once; * the stars can intersect only in their vertexes; * the length of a side of the regular pentagon, in which Rubik paints each star, must equal 10. Help Rubik to cope with this hard task. Input A single line contains an integer (1 ≤ n ≤ 100) — the number of stars to paint. Output On the first line print an integer m (1 ≤ m ≤ 5·n). On the next m lines print coordinates of m distinct points with accuracy of at least 9 and at most 100 digits after decimal point. All coordinates should not exceed 5000 in their absolute value. On each of the next n lines print 5 integers — the indexes of the points that form the given star in the clockwise or counterclockwise order. On the next line print 5·n + 1 integers — the numbers of points in the order, in which Rubik paints stars. That is, if number with index i is ai, and number with index i + 1 is ai + 1, then points with indexes ai and ai + 1 will have a segment painted between them. You can consider all m printed points indexed from 1 to m in the order, in which they occur in the output. Separate the numbers on the lines with whitespaces. Note that the answer has an imprecise validation. Try to obtain as accurate a solution as possible. The validator performs all calculations considering that the absolute error of a participant's answer is not more than 10 - 8. Examples Input 1 Output 5 3.830127018922193 3.366025403784439 -3.601321235851749 10.057331467373021 0.466045194906253 19.192786043799030 10.411264148588986 18.147501411122495 12.490381056766580 8.366025403784439 1 2 3 4 5 1 3 5 2 4 1 Note The initial position of points in the sample is: <image> The order in which Rubik can paint segments is: <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 110; long double pi = acosl(-1); struct point { long double x, y; point(long double x = 0, long double y = 0) : x(x), y(y) {} point operator+(const point& A) const { return point(x + A.x, y + A.y); } void display() { printf("%.20Lf %.20Lf\n", x, y); } } pt[maxn * 5]; int main() { long double r = (long double)5 / cosl((long double)54 * pi / 180); long double len = (long double)10 * sinl((long double)54 * pi / 180) * 2; int n; scanf("%d", &n); int ind = 0; pt[ind++] = point(0, r); for (int i = 1; i < 4; i++) { long double xx = cosl((long double)72 * pi / 180), yy = sinl((long double)72 * pi / 180); pt[ind++] = point(pt[i - 1].x * xx - pt[i - 1].y * yy, pt[i - 1].x * yy + pt[i - 1].y * xx); } for (int i = 1; i < n; i++) { for (int j = 0; j < 4; j++, ind++) pt[ind] = pt[ind - 4] + point(len, 0); } pt[ind] = pt[ind - 3] + point(len, 0); ind++; printf("%d\n", ind); for (int i = 0; i < ind; i++) pt[i].display(); for (int i = 0; i < n; i++) { int st = i * 4; for (int j = 0; j < 4; j++) printf("%d ", st + j + 1); if (i == n - 1) printf("%d\n", ind); else printf("%d\n", st + 4 + 1 + 1); } printf("2"); for (int i = 1; i < n; i++) printf(" %d", i * 4 + 1 + 1); printf(" %d", ind); for (int i = n - 1; i >= 0; i--) { int st = i * 4; printf(" %d %d %d %d", st + 2 + 1, st + 1, st + 3 + 1, st + 1 + 1); } puts(""); return 0; } ```
### Prompt Generate a Cpp solution to the following problem: A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You are given a regular bracket sequence s and an integer number k. Your task is to find a regular bracket sequence of length exactly k such that it is also a subsequence of s. It is guaranteed that such sequence always exists. Input The first line contains two integers n and k (2 ≤ k ≤ n ≤ 2 ⋅ 10^5, both n and k are even) — the length of s and the length of the sequence you are asked to find. The second line is a string s — regular bracket sequence of length n. Output Print a single string — a regular bracket sequence of length exactly k such that it is also a subsequence of s. It is guaranteed that such sequence always exists. Examples Input 6 4 ()(()) Output ()() Input 8 8 (()(())) Output (()(())) ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename T> T gcd(T a, T b) { if (a == 0) return b; return gcd(b % a, a); } template <typename T> T pow(T a, T b) { if (b == 0) return 1; else { int c = pow(a, b / 2); if (b % 2 == 0) return c * c; else return a * c * c; } } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); ; int n, k; string s; cin >> n >> k; cin >> s; k = k / 2; int i, j, l; for (i = 0, j = 0, l = 0; j < n; ++j) { if (s[j] == '(' && i < k) { cout << s[j]; i++; } else if (s[j] == ')' && l < i) { cout << s[j]; l++; } } return 0; } ```
### Prompt Please create a solution in CPP to the following problem: This is a harder version of the problem. In this version, n ≤ 50 000. There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even. You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b. Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if min(x_a, x_b) ≤ x_c ≤ max(x_a, x_b), min(y_a, y_b) ≤ y_c ≤ max(y_a, y_b), and min(z_a, z_b) ≤ z_c ≤ max(z_a, z_b). Note that the bounding box might be degenerate. Find a way to remove all points in n/2 snaps. Input The first line contains a single integer n (2 ≤ n ≤ 50 000; n is even), denoting the number of points. Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 ≤ x_i, y_i, z_i ≤ 10^8), denoting the coordinates of the i-th point. No two points coincide. Output Output n/2 pairs of integers a_i, b_i (1 ≤ a_i, b_i ≤ n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once. We can show that it is always possible to remove all points. If there are many solutions, output any of them. Examples Input 6 3 1 0 0 3 0 2 2 0 1 0 0 1 3 0 0 1 0 Output 3 6 5 1 2 4 Input 8 0 1 1 1 0 1 1 1 0 1 1 1 2 2 2 3 2 2 2 3 2 2 2 3 Output 4 5 1 6 2 7 3 8 Note In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed. <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; vector<pair<pair<int, int>, pair<int, int> > > li; vector<pair<pair<int, int>, pair<int, int> > > tmp; vector<pair<pair<int, int>, pair<int, int> > > tmp2; int n; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { int x, y, z; scanf("%d%d%d", &x, &y, &z); li.push_back(make_pair(make_pair(x, y), make_pair(z, i))); } sort(li.begin(), li.end()); for (int i = 0; i < n; i++) { if (tmp.size() > 0 && tmp.back().first == li[i].first) { printf("%d %d\n", tmp.back().second.second, li[i].second.second); tmp.pop_back(); } else { tmp.push_back(li[i]); } } for (int i = 0; i < tmp.size(); i++) { if (tmp2.size() > 0 && tmp2.back().first.first == tmp[i].first.first) { printf("%d %d\n", tmp2.back().second.second, tmp[i].second.second); tmp2.pop_back(); } else { tmp2.push_back(tmp[i]); } } for (int i = 0; i < tmp2.size(); i += 2) { printf("%d %d\n", tmp2[i].second.second, tmp2[i + 1].second.second); } return 0; } ```
### Prompt Develop a solution in Cpp to the problem described below: Olesya loves numbers consisting of n digits, and Rodion only likes numbers that are divisible by t. Find some number that satisfies both of them. Your task is: given the n and t print an integer strictly larger than zero consisting of n digits that is divisible by t. If such number doesn't exist, print - 1. Input The single line contains two numbers, n and t (1 ≤ n ≤ 100, 2 ≤ t ≤ 10) — the length of the number and the number it should be divisible by. Output Print one such positive number without leading zeroes, — the answer to the problem, or - 1, if such number doesn't exist. If there are multiple possible answers, you are allowed to print any of them. Examples Input 3 2 Output 712 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int b, c, d, e, f, g, h, i, j, k, l, m, n, t; scanf("%d%d", &n, &t); int a[n]; if (t == 10 && n == 1) { printf("-1\n"); return 0; } if (t < 10) { for (i = 0; i < n; i++) { a[i] = t; } for (i = 0; i < n; i++) { printf("%d", a[i]); } printf("\n"); return 0; } a[0] = 1; if (t == 10 && n > 1) { for (i = 1; i < n; i++) { a[i] = 0; } } for (i = 0; i < n; i++) { printf("%d", a[i]); } printf("\n"); return 0; } ```
### Prompt Construct a CPP code solution to the problem outlined: 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 = 200500; int t[3][3 * N]; int a[N]; int getsum(int id, int l, int r) { int res = 0; while (l <= r) { if (l % 2 == 1) { res += t[id][l]; } if (r % 2 == 0) { res += t[id][r]; } l = (l + 1) / 2; r = (r - 1) / 2; } return res; } void upd(int id, int p) { while (p) { p /= 2; t[id][p] = t[id][p * 2] + t[id][p * 2 + 1]; } } int main() { srand(time(NULL)); int n, k, p1, p2, m; cin >> n >> k >> p1 >> p2 >> m; int sz = 1; while (sz < n) { sz *= 2; } for (int i = 1; i <= m; i++) { int type; cin >> type; if (type == 1) { int day, kol; cin >> day >> kol; a[day] += kol; t[1][sz + day - 1] = min(a[day], p1); t[2][sz + day - 1] = min(a[day], p2); upd(1, sz + day - 1); upd(2, sz + day - 1); } else { int pos; cin >> pos; cout << getsum(2, sz, sz + pos - 2) + getsum(1, sz + pos + k - 1, sz + n - 1) << endl; } } return 0; } ```
### Prompt Your challenge is to write a cpp solution to the following problem: You know, it's hard to conduct a show with lots of participants and spectators at the same place nowadays. Still, you are not giving up on your dream to make a car crash showcase! You decided to replace the real cars with remote controlled ones, call the event "Remote Control Kaboom Show" and stream everything online. For the preparation you arranged an arena — an infinite 2D-field. You also bought n remote controlled cars and set them up on the arena. Unfortunately, the cars you bought can only go forward without turning left, right or around. So you additionally put the cars in the direction you want them to go. To be formal, for each car i (1 ≤ i ≤ n) you chose its initial position (x_i, y_i) and a direction vector (dx_i, dy_i). Moreover, each car has a constant speed s_i units per second. So after car i is launched, it stars moving from (x_i, y_i) in the direction (dx_i, dy_i) with constant speed s_i. The goal of the show is to create a car collision as fast as possible! You noted that launching every car at the beginning of the show often fails to produce any collisions at all. Thus, you plan to launch the i-th car at some moment t_i. You haven't chosen t_i, that's yet to be decided. Note that it's not necessary for t_i to be integer and t_i is allowed to be equal to t_j for any i, j. The show starts at time 0. The show ends when two cars i and j (i ≠ j) collide (i. e. come to the same coordinate at the same time). The duration of the show is the time between the start and the end. What's the fastest crash you can arrange by choosing all t_i? If it's possible to arrange a crash then print the shortest possible duration of the show. Otherwise, report that it's impossible. Input The first line contains a single integer n (1 ≤ n ≤ 25000) — the number of cars. Each of the next n lines contains five integers x_i, y_i, dx_i, dy_i, s_i (-10^3 ≤ x_i, y_i ≤ 10^3; 1 ≤ |dx_i| ≤ 10^3; 1 ≤ |dy_i| ≤ 10^3; 1 ≤ s_i ≤ 10^3) — the initial position of the i-th car, its direction vector and its speed, respectively. It's guaranteed that all cars start at distinct positions (i. e. (x_i, y_i) ≠ (x_j, y_j) for i ≠ j). Output Print the shortest possible duration of the show if it's possible to arrange a crash by choosing all t_i. Otherwise, print "No show :(". Your answer is considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}. Examples Input 4 3 -1 -1 1 2 2 3 -3 -2 10 -4 2 1 -2 1 -2 -2 -1 2 4 Output 0.585902082262898 Input 2 -1 1 -1 1 200 1 1 1 5 200 Output No show :( Note Here is the picture for the first example: <image> The fastest cars to crash are cars 2 and 4. Let's launch car 2 at 0, car 4 at about 0.096762 and cars 1 and 3 at arbitrary time. That way cars 2 and 4 will crash into each other at about 0.585902. So here's what it looks like at the moment of the collision: <image> Here's the picture for the second example: <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1e5 + 10; const double inf = 4e19; int X[N], Y[N], DX[N], DY[N], s[N], n, a[N], b[N], c[N], s2[N]; void read() { cin >> n; for (int i = 1; i <= n; i++) cin >> X[i] >> Y[i] >> DX[i] >> DY[i] >> s[i]; } void process() { for (int i = 1; i <= n; i++) { a[i] = DY[i]; b[i] = -DX[i]; c[i] = a[i] * X[i] + b[i] * Y[i]; s2[i] = s[i] * s[i]; } int d, flag1, flag2; double res = inf, x, y, dx, dy; for (int i = 1; i < n; i++) for (int j = i + 1; j <= n; j++) { d = a[i] * b[j] - a[j] * b[i]; dx = c[i] * b[j]; dx -= c[j] * b[i]; dy = a[i] * c[j]; dy -= a[j] * c[i]; if (d == 0) { if (dx == 0) { flag1 = flag2 = 0; if ((X[j] - X[i]) * DX[i] > 0) flag1 = 1; if ((X[i] - X[j]) * DX[j] > 0) flag2 = 1; double dis = (X[i] - X[j]) * (X[i] - X[j]) + (Y[i] - Y[j]) * (Y[i] - Y[j]); if (flag1 && flag2) res = min(res, dis / ((s[i] + s[j]) * (s[i] + s[j]))); else if (flag1) res = min(res, dis / s2[i]); else if (flag2) res = min(res, dis / s2[j]); } continue; } x = dx / d; y = dy / d; if ((x - X[i]) * DX[i] < 0 || (x - X[j]) * DX[j] < 0) continue; res = min(res, max(((x - X[i]) * (x - X[i]) + (y - Y[i]) * (y - Y[i])) / s2[i], ((x - X[j]) * (x - X[j]) + (y - Y[j]) * (y - Y[j])) / s2[j])); } if (res == inf) cout << "No show :("; else cout << std::setprecision(15) << sqrt(res); } int main() { ios::sync_with_stdio(false); cin.tie(0); read(); process(); return 0; } ```
### Prompt Create a solution in CPP for the following problem: Gildong is experimenting with an interesting machine Graph Traveler. In Graph Traveler, there is a directed graph consisting of n vertices numbered from 1 to n. The i-th vertex has m_i outgoing edges that are labeled as e_i[0], e_i[1], …, e_i[m_i-1], each representing the destination vertex of the edge. The graph can have multiple edges and self-loops. The i-th vertex also has an integer k_i written on itself. A travel on this graph works as follows. 1. Gildong chooses a vertex to start from, and an integer to start with. Set the variable c to this integer. 2. After arriving at the vertex i, or when Gildong begins the travel at some vertex i, add k_i to c. 3. The next vertex is e_i[x] where x is an integer 0 ≤ x ≤ m_i-1 satisfying x ≡ c \pmod {m_i}. Go to the next vertex and go back to step 2. It's obvious that a travel never ends, since the 2nd and the 3rd step will be repeated endlessly. For example, assume that Gildong starts at vertex 1 with c = 5, and m_1 = 2, e_1[0] = 1, e_1[1] = 2, k_1 = -3. Right after he starts at vertex 1, c becomes 2. Since the only integer x (0 ≤ x ≤ 1) where x ≡ c \pmod {m_i} is 0, Gildong goes to vertex e_1[0] = 1. After arriving at vertex 1 again, c becomes -1. The only integer x satisfying the conditions is 1, so he goes to vertex e_1[1] = 2, and so on. Since Gildong is quite inquisitive, he's going to ask you q queries. He wants to know how many distinct vertices will be visited infinitely many times, if he starts the travel from a certain vertex with a certain value of c. Note that you should not count the vertices that will be visited only finite times. Input The first line of the input contains an integer n (1 ≤ n ≤ 1000), the number of vertices in the graph. The second line contains n integers. The i-th integer is k_i (-10^9 ≤ k_i ≤ 10^9), the integer written on the i-th vertex. Next 2 ⋅ n lines describe the edges of each vertex. The (2 ⋅ i + 1)-st line contains an integer m_i (1 ≤ m_i ≤ 10), the number of outgoing edges of the i-th vertex. The (2 ⋅ i + 2)-nd line contains m_i integers e_i[0], e_i[1], …, e_i[m_i-1], each having an integer value between 1 and n, inclusive. Next line contains an integer q (1 ≤ q ≤ 10^5), the number of queries Gildong wants to ask. Next q lines contains two integers x and y (1 ≤ x ≤ n, -10^9 ≤ y ≤ 10^9) each, which mean that the start vertex is x and the starting value of c is y. Output For each query, print the number of distinct vertices that will be visited infinitely many times, if Gildong starts at vertex x with starting integer y. Examples Input 4 0 0 0 0 2 2 3 1 2 3 2 4 1 4 3 1 2 1 6 1 0 2 0 3 -1 4 -2 1 1 1 5 Output 1 1 2 1 3 2 Input 4 4 -5 -3 -1 2 2 3 1 2 3 2 4 1 4 3 1 2 1 6 1 0 2 0 3 -1 4 -2 1 1 1 5 Output 1 1 1 3 1 1 Note The first example can be shown like the following image: <image> Three integers are marked on i-th vertex: i, k_i, and m_i respectively. The outgoing edges are labeled with an integer representing the edge number of i-th vertex. The travel for each query works as follows. It is described as a sequence of phrases, each in the format "vertex (c after k_i added)". * 1(0) → 2(0) → 2(0) → … * 2(0) → 2(0) → … * 3(-1) → 1(-1) → 3(-1) → … * 4(-2) → 2(-2) → 2(-2) → … * 1(1) → 3(1) → 4(1) → 1(1) → … * 1(5) → 3(5) → 1(5) → … The second example is same as the first example, except that the vertices have non-zero values. Therefore the answers to the queries also differ from the first example. <image> The queries for the second example works as follows: * 1(4) → 2(-1) → 2(-6) → … * 2(-5) → 2(-10) → … * 3(-4) → 1(0) → 2(-5) → 2(-10) → … * 4(-3) → 1(1) → 3(-2) → 4(-3) → … * 1(5) → 3(2) → 1(6) → 2(1) → 2(-4) → … * 1(9) → 3(6) → 2(1) → 2(-4) → … ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 2521, MOD = 2520; long long dp[1010][MAXN], vis[1010][MAXN], v[1010], n; pair<int, int> nxt[1010][MAXN]; int did[1010]; void go(int x, int y) { stack<pair<int, int> > st; while (1) { st.push({x, y}); vis[x][y] = 1; int nx = nxt[x][y].first, ny = nxt[x][y].second; if (dp[nx][ny] >= 0) { while (int(st.size())) { dp[st.top().first][st.top().second] = dp[nx][ny]; st.pop(); } break; } if (vis[nx][ny]) { vector<pair<int, int> > all; int ans = 0, fl = 0; while (int(st.size())) { int ax = st.top().first, ay = st.top().second; all.push_back({ax, ay}); if (!fl) ans += !did[ax], did[ax] = 1; if (nx == ax && ny == ay) fl = 1; st.pop(); } for (auto x : all) dp[x.first][x.second] = ans, did[x.first] = 0; break; } x = nx; y = ny; } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); memset(dp, -1, sizeof(dp)); cin >> n; for (int i = 0, ThxDem = n; i < ThxDem; ++i) cin >> v[i], v[i] %= MOD, v[i] += MOD, v[i] %= MOD; for (int i = 0, ThxDem = n; i < ThxDem; ++i) { int am; cin >> am; vector<int> xx(am); for (int j = 0, ThxDem = am; j < ThxDem; ++j) cin >> xx[j], xx[j]--; for (int j = 0, ThxDem = MAXN; j < ThxDem; ++j) { int wh = xx[j % am]; int vv = j + v[wh]; if (vv >= MOD) vv -= MOD; nxt[i][j] = {wh, vv}; } } for (int i = 0, ThxDem = n; i < ThxDem; ++i) for (int j = 0, ThxDem = MOD; j < ThxDem; ++j) if (dp[i][j] < 0) go(i, j); int q; cin >> q; while (q--) { int x, c; cin >> x >> c; x--; c += v[x]; c %= MOD; c += MOD; c %= MOD; cout << dp[x][c] << "\n"; } } ```
### Prompt Please create a solution in CPP to the following problem: There are N apple trees in a row. People say that one of them will bear golden apples. We want to deploy some number of inspectors so that each of these trees will be inspected. Each inspector will be deployed under one of the trees. For convenience, we will assign numbers from 1 through N to the trees. An inspector deployed under the i-th tree (1 \leq i \leq N) will inspect the trees with numbers between i-D and i+D (inclusive). Find the minimum number of inspectors that we need to deploy to achieve the objective. Constraints * All values in input are integers. * 1 \leq N \leq 20 * 1 \leq D \leq 20 Input Input is given from Standard Input in the following format: N D Output Print the minimum number of inspectors that we need to deploy to achieve the objective. Examples Input 6 2 Output 2 Input 14 3 Output 2 Input 20 4 Output 3 ### Response ```cpp #include<bits/stdc++.h> using namespace std; int main(){ int n,d; cin>>n>>d; double c=(double)n/((2*d)+1); cout<<ceil(c)<<endl; } ```
### Prompt Your task is to create a Cpp solution to the following problem: Anton came to a chocolate factory. There he found a working conveyor and decided to run on it from the beginning to the end. The conveyor is a looped belt with a total length of 2l meters, of which l meters are located on the surface and are arranged in a straight line. The part of the belt which turns at any moment (the part which emerges from under the floor to the surface and returns from the surface under the floor) is assumed to be negligibly short. The belt is moving uniformly at speed v1 meters per second. Anton will be moving on it in the same direction at the constant speed of v2 meters per second, so his speed relatively to the floor will be v1 + v2 meters per second. Anton will neither stop nor change the speed or the direction of movement. Here and there there are chocolates stuck to the belt (n chocolates). They move together with the belt, and do not come off it. Anton is keen on the chocolates, but he is more keen to move forward. So he will pick up all the chocolates he will pass by, but nothing more. If a chocolate is at the beginning of the belt at the moment when Anton starts running, he will take it, and if a chocolate is at the end of the belt at the moment when Anton comes off the belt, he will leave it. <image> The figure shows an example with two chocolates. One is located in the position a1 = l - d, and is now on the top half of the belt, the second one is in the position a2 = 2l - d, and is now on the bottom half of the belt. You are given the positions of the chocolates relative to the initial start position of the belt 0 ≤ a1 < a2 < ... < an < 2l. The positions on the belt from 0 to l correspond to the top, and from l to 2l — to the the bottom half of the belt (see example). All coordinates are given in meters. Anton begins to run along the belt at a random moment of time. This means that all possible positions of the belt at the moment he starts running are equiprobable. For each i from 0 to n calculate the probability that Anton will pick up exactly i chocolates. Input The first line contains space-separated integers n, l, v1 and v2 (1 ≤ n ≤ 105, 1 ≤ l, v1, v2 ≤ 109) — the number of the chocolates, the length of the conveyor's visible part, the conveyor's speed and Anton's speed. The second line contains a sequence of space-separated integers a1, a2, ..., an (0 ≤ a1 < a2 < ... < an < 2l) — the coordinates of the chocolates. Output Print n + 1 numbers (one per line): the probabilities that Anton picks up exactly i chocolates, for each i from 0 (the first line) to n (the last line). The answer will be considered correct if each number will have absolute or relative error of at most than 10 - 9. Examples Input 1 1 1 1 0 Output 0.75000000000000000000 0.25000000000000000000 Input 2 3 1 2 2 5 Output 0.33333333333333331000 0.66666666666666663000 0.00000000000000000000 Note In the first sample test Anton can pick up a chocolate if by the moment he starts running its coordinate is less than 0.5; but if by the moment the boy starts running the chocolate's coordinate is greater than or equal to 0.5, then Anton won't be able to pick it up. As all positions of the belt are equiprobable, the probability of picking up the chocolate equals <image>, and the probability of not picking it up equals <image>. ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct seg { long long v; int s; bool operator<(const seg &o) const { return v - o.v < 0 || (v == o.v && s > o.s); } } t[200005 * 4]; int n, m, v1, v2; long long a[200005 * 2], l, L, len; long long ans[200005]; void Init() { cin >> n >> l >> v1 >> v2; len = l * v2; l = l * (v1 + v2); L = l; for (int i = 1; i <= n; ++i) { scanf("%d", a + i); a[i] *= (v1 + v2); a[n + i] = a[i] + 2 * l; } } void Work() { long long l, r; for (int i = 1; i <= 2 * n; ++i) { l = a[i] - len; r = a[i]; l = ((l) > (0) ? (l) : (0)); r = ((r) < (2 * L) ? (r) : (2 * L)); if (l - r <= 1e-9) { t[++m].v = l; t[m].s = 1; t[++m].v = r; t[m].s = -1; } } sort(t + 1, t + 1 + m); int now = 0; long long last = 0, cnt = 0; for (int i = 1; i <= m; ++i) { ans[now] += t[i].v - last; cnt += t[i].v - last; last = t[i].v; now += t[i].s; } ans[0] += 2 * L - last; cnt = 0; for (int i = 0; i <= n; ++i) { printf("%.20lf\n", double(ans[i]) / (2 * L)); cnt += ans[i] / (2 * L); } } int main() { Init(); Work(); return 0; } ```
### Prompt Create a solution in Cpp for the following problem: In the country there are n cities and m bidirectional roads between them. Each city has an army. Army of the i-th city consists of ai soldiers. Now soldiers roam. After roaming each soldier has to either stay in his city or to go to the one of neighboring cities by at moving along at most one road. Check if is it possible that after roaming there will be exactly bi soldiers in the i-th city. Input First line of input consists of two integers n and m (1 ≤ n ≤ 100, 0 ≤ m ≤ 200). Next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 100). Next line contains n integers b1, b2, ..., bn (0 ≤ bi ≤ 100). Then m lines follow, each of them consists of two integers p and q (1 ≤ p, q ≤ n, p ≠ q) denoting that there is an undirected road between cities p and q. It is guaranteed that there is at most one road between each pair of cities. Output If the conditions can not be met output single word "NO". Otherwise output word "YES" and then n lines, each of them consisting of n integers. Number in the i-th line in the j-th column should denote how many soldiers should road from city i to city j (if i ≠ j) or how many soldiers should stay in city i (if i = j). If there are several possible answers you may output any of them. Examples Input 4 4 1 2 6 3 3 5 3 1 1 2 2 3 3 4 4 2 Output YES 1 0 0 0 2 0 0 0 0 5 1 0 0 0 2 1 Input 2 0 1 2 2 1 Output NO ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1000; const int INF = 1e9; struct Edge { int v, f, mf, pid; Edge() {} Edge(int v, int f, int mf, int pid) : v(v), f(f), mf(mf), pid(pid) {} }; int n, m; vector<Edge> g[N]; int data[N][N]; int a[N]; int b[N]; int st, fn, all; int dist[N]; int cur[N]; int res[N][N]; queue<int> q; void read() { scanf("%d%d", &n, &m); for (int i = 0; i < n; i++) scanf("%d", &a[i]); for (int i = 0; i < n; i++) scanf("%d", &b[i]); for (int i = 0; i < m; i++) { int v, u; scanf("%d%d", &v, &u); v--; u--; data[v][u] = data[u][v] = 1; } } void addE(int v, int u, int flow) { int szV = g[v].size(); int szU = g[u].size(); g[v].push_back(Edge(u, 0, flow, szU)); g[u].push_back(Edge(v, 0, 0, szV)); } int bfs() { memset(dist, 63, sizeof(dist)); dist[st] = 0; q.push(st); while (!q.empty()) { int v = q.front(); q.pop(); for (auto x : g[v]) { int u = x.v; if (dist[u] > dist[v] + 1 && x.f < x.mf) { dist[u] = dist[v] + 1; q.push(u); } } } return dist[fn] < INF; } int dfs(int v, int flow) { if (v == fn) return flow; for (; cur[v] < (int)g[v].size(); cur[v]++) { auto &x = g[v][cur[v]]; if (dist[x.v] == dist[v] + 1 && x.f < x.mf) { int r = dfs(x.v, min(flow, x.mf - x.f)); if (r > 0) { x.f += r; g[x.v][x.pid].f -= r; return r; } } } return 0; } void ret(int x) { if (x == 0) { printf("NO\n"); exit(0); } } void solve() { st = n * 2; fn = n * 2 + 1; all = n * 2 + 2; for (int i = 0; i < n; i++) { addE(st, i, a[i]); addE(i + n, fn, b[i]); } for (int i = 0; i < n; i++) data[i][i] = 1; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { int flow = data[i][j] * INF; addE(i, j + n, flow); } int sum1 = 0; int sum2 = 0; for (int i = 0; i < n; i++) { sum1 += b[i]; sum2 += a[i]; } if (sum1 != sum2) ret(0); while (bfs()) { for (int i = 0; i < all; i++) cur[i] = 0; while (true) { int x = dfs(st, INF); if (x == 0) break; sum1 -= x; } } assert(sum1 >= 0); if (sum1 > 0) ret(0); for (int i = 0; i < n; i++) for (int j = 0; j < (int)g[i].size(); j++) { int v = g[i][j].v - n; if (0 <= v && v < n) { res[i][v] = g[i][j].f; } } printf("YES\n"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf("%d ", res[i][j]); printf("\n"); } } void printAns() {} void stress() {} int main() { if (1) { int k = 1; for (int tt = 0; tt < k; tt++) { read(); solve(); printAns(); } } else { stress(); } return 0; } ```
### Prompt Create a solution in Cpp for the following problem: Zane the wizard had never loved anyone before, until he fell in love with a girl, whose name remains unknown to us. <image> The girl lives in house m of a village. There are n houses in that village, lining in a straight line from left to right: house 1, house 2, ..., house n. The village is also well-structured: house i and house i + 1 (1 ≤ i < n) are exactly 10 meters away. In this village, some houses are occupied, and some are not. Indeed, unoccupied houses can be purchased. You will be given n integers a1, a2, ..., an that denote the availability and the prices of the houses. If house i is occupied, and therefore cannot be bought, then ai equals 0. Otherwise, house i can be bought, and ai represents the money required to buy it, in dollars. As Zane has only k dollars to spare, it becomes a challenge for him to choose the house to purchase, so that he could live as near as possible to his crush. Help Zane determine the minimum distance from his crush's house to some house he can afford, to help him succeed in his love. Input The first line contains three integers n, m, and k (2 ≤ n ≤ 100, 1 ≤ m ≤ n, 1 ≤ k ≤ 100) — the number of houses in the village, the house where the girl lives, and the amount of money Zane has (in dollars), respectively. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 100) — denoting the availability and the prices of the houses. It is guaranteed that am = 0 and that it is possible to purchase some house with no more than k dollars. Output Print one integer — the minimum distance, in meters, from the house where the girl Zane likes lives to the house Zane can buy. Examples Input 5 1 20 0 27 32 21 19 Output 40 Input 7 3 50 62 0 0 0 99 33 22 Output 30 Input 10 5 100 1 0 1 0 0 0 0 0 1 1 Output 20 Note In the first sample, with k = 20 dollars, Zane can buy only house 5. The distance from house m = 1 to house 5 is 10 + 10 + 10 + 10 = 40 meters. In the second sample, Zane can buy houses 6 and 7. It is better to buy house 6 than house 7, since house m = 3 and house 6 are only 30 meters away, while house m = 3 and house 7 are 40 meters away. ### Response ```cpp #include <bits/stdc++.h> using namespace std; vector<int> vi; int main() { int n, m, k; cin >> n >> m >> k; vi.resize(n); for (int i = 0; i < n; ++i) { cin >> vi[i]; } int one = 99999999, two = 99999999; for (int i = m; i < n; ++i) { if (vi[i] <= k && vi[i] != 0) { one = i; break; } } for (int i = m - 2; i >= 0; --i) { if (vi[i] <= k && vi[i] != 0) { two = i; break; } } int dist1, dist2; m--; dist2 = abs(two - m); dist1 = abs(one - m); cout << min(dist1, dist2) * 10 << endl; return 0; } ```
### Prompt Construct a cpp code solution to the problem outlined: You are given two arithmetic progressions: a1k + b1 and a2l + b2. Find the number of integers x such that L ≤ x ≤ R and x = a1k' + b1 = a2l' + b2, for some integers k', l' ≥ 0. Input The only line contains six integers a1, b1, a2, b2, L, R (0 < a1, a2 ≤ 2·109, - 2·109 ≤ b1, b2, L, R ≤ 2·109, L ≤ R). Output Print the desired number of integers x. Examples Input 2 0 3 3 5 21 Output 3 Input 2 4 3 0 6 17 Output 2 ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename T1, typename T2> istream& operator>>(istream& in, pair<T1, T2>& a) { in >> a.first >> a.second; return in; } template <typename T1, typename T2> ostream& operator<<(ostream& out, pair<T1, T2> a) { out << a.first << " " << a.second; return out; } template <typename T, typename T1> T maxs(T& a, T1 b) { if (b > a) a = b; return a; } template <typename T, typename T1> T mins(T& a, T1 b) { if (b < a) a = b; return a; } long long gcd(long long a, long long b, long long& first, long long& second) { if (b == 0) { first = 1; second = 0; return a; } long long x1, y1; long long d = gcd(b, a % b, x1, y1); first = y1; second = x1 - y1 * (a / b); return d; } bool find_any_solution(long long a, long long b, long long c, long long& x0, long long& y0, long long& g) { g = gcd(abs(a), abs(b), x0, y0); if (c % g) { return false; } x0 *= c / g; y0 *= c / g; if (a < 0) x0 = -x0; if (b < 0) y0 = -y0; return true; } void shift_solution(long long& first, long long& second, long long a, long long b, long long cnt) { first += cnt * b; second -= cnt * a; } long long find_all_solutions(long long a, long long b, long long c, long long minx, long long maxx, long long miny, long long maxy) { long long first, second, g; if (!find_any_solution(a, b, c, first, second, g)) return 0; a /= g; b /= g; long long sign_a = a > 0 ? +1 : -1; long long sign_b = b > 0 ? +1 : -1; shift_solution(first, second, a, b, (minx - first) / b); if (first < minx) shift_solution(first, second, a, b, sign_b); if (first > maxx) return 0; long long lx1 = first; shift_solution(first, second, a, b, (maxx - first) / b); if (first > maxx) shift_solution(first, second, a, b, -sign_b); long long rx1 = first; shift_solution(first, second, a, b, -(miny - second) / a); if (second < miny) shift_solution(first, second, a, b, -sign_a); if (second > maxy) return 0; long long lx2 = first; shift_solution(first, second, a, b, -(maxy - second) / a); if (second > maxy) shift_solution(first, second, a, b, sign_a); long long rx2 = first; if (lx2 > rx2) swap(lx2, rx2); long long lx = max(lx1, lx2); long long rx = min(rx1, rx2); if (lx > rx) return 0; return (rx - lx) / abs(b) + 1; } long long solve() { long long a1, b1, a2, b2, l, r; cin >> a1 >> b1 >> a2 >> b2 >> l >> r; long long maxx = floor(1.0 * (r - b2) / a2); long long minx = ceil(1.0 * (l - b2) / a2); long long maxy = floor(1.0 * (r - b1) / a1); long long miny = ceil(1.0 * (l - b1) / a1); miny = max(0LL, miny); minx = max(0LL, minx); if (miny > maxy || minx > maxx) { cout << 0 << "\n"; return 0; } cout << find_all_solutions(a1, -a2, b2 - b1, miny, maxy, minx, maxx) << "\n"; return 0; } signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long t = 1; while (t--) { solve(); } return 0; } ```
### Prompt Develop a solution in Cpp to the problem described below: Tavas lives in Kansas. Kansas has n cities numbered from 1 to n connected with m bidirectional roads. We can travel from any city to any other city via these roads. Kansas is as strange as Tavas. So there may be a road between a city and itself or more than one road between two cities. Tavas invented a game and called it "Dashti". He wants to play Dashti with his girlfriends, Nafas. In this game, they assign an arbitrary integer value to each city of Kansas. The value of i-th city equals to pi. During the game, Tavas is in city s and Nafas is in city t. They play in turn and Tavas goes first. A player in his/her turn, must choose a non-negative integer x and his/her score increases by the sum of values of all cities with (shortest) distance no more than x from his/her city. Each city may be used once, or in the other words, after first time a player gets score from a city, city score becomes zero. There is an additional rule: the player must choose x such that he/she gets the point of at least one city that was not used before. Note that city may initially have value 0, such city isn't considered as been used at the beginning of the game, i. e. each player may use it to fullfill this rule. The game ends when nobody can make a move. A player's score is the sum of the points he/she earned during the game. The winner is the player with greater score, or there is a draw if players score the same value. Both players start game with zero points. <image> If Tavas wins, he'll break his girlfriend's heart, and if Nafas wins, Tavas will cry. But if their scores are equal, they'll be happy and Tavas will give Nafas flowers. They're not too emotional after all, so they'll play optimally. Your task is to tell Tavas what's going to happen after the game ends. Input The first line of input contains two integers n and m (2 ≤ n ≤ 2000, n - 1 ≤ m ≤ 105). The second line of input contains two integers s and t (1 ≤ s, t ≤ n, s ≠ t). The next line contains n integers p1, p2, ..., pn separated by spaces (|pi| ≤ 109). The next m lines contain the roads. Each line contains three integers v, u, w and it means that there's an road with length w between cities v and u (1 ≤ u, v ≤ n and 0 ≤ w ≤ 109). The road may lead from the city to itself, there may be several roads between each pair of cities. Output If Tavas wins, print "Break a heart". If Nafas wins print "Cry" and if nobody wins (i. e. the game ended with draw) print "Flowers". Examples Input 4 4 1 2 3 2 5 -11 1 4 2 3 4 2 3 1 5 3 2 1 Output Cry Input 5 4 1 2 2 2 -5 -4 6 1 2 4 2 3 5 2 4 2 4 5 2 Output Break a heart Input 2 1 1 2 -5 -5 1 2 10 Output Flowers ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, m, s, t, tot, X, Y; const long long N = 2010, M = 100010, inf = 1e18; int head[N], to[M << 1], nt[M << 1], len[M << 1], siz[N][N], vis[N], pos[2][N]; long long dis[2][N], val[N], sum[N][N], tmp[N], f[2][N][N], g[2][N][N]; void add(int f, int t, int d) { to[++tot] = t; len[tot] = d; nt[tot] = head[f]; head[f] = tot; } void DIJ(int s, long long *dis) { int x; priority_queue<pair<long long, int> > q; for (int i = 1; i <= n; ++i) dis[i] = inf, vis[i] = 0; dis[s] = 0; q.push(pair<long long, int>(0, s)); while (!q.empty()) { x = q.top().second; q.pop(); if (vis[x]) continue; vis[x] = 1; for (int i = head[x]; i; i = nt[i]) if (dis[to[i]] > dis[x] + len[i]) { dis[to[i]] = dis[x] + len[i]; q.push(pair<long long, int>(-dis[to[i]], to[i])); } } } void UNI(long long *a, int &m) { int cnt = 0; for (int i = 1; i <= n; ++i) tmp[++cnt] = a[i]; sort(tmp + 1, tmp + 1 + cnt); m = unique(tmp + 1, tmp + 1 + cnt) - tmp - 1; for (int i = 1; i <= n; ++i) a[i] = lower_bound(tmp + 1, tmp + 1 + m, a[i]) - tmp; } int query(int X1, int Y1, int X2, int Y2) { return siz[X1][Y1] - siz[X2][Y2]; } signed main() { cin >> n >> m >> s >> t; for (int i = 1; i <= n; ++i) scanf("%lld", &val[i]); for (int i = 1, x, y, z; i <= m; ++i) scanf("%d%d%d", &x, &y, &z), add(x, y, z), add(y, x, z); DIJ(s, dis[0]); DIJ(t, dis[1]); UNI(dis[0], X); UNI(dis[1], Y); for (int i = 1; i <= n; ++i) { sum[dis[0][i]][dis[1][i]] += val[i]; ++siz[dis[0][i]][dis[1][i]]; } for (int i = X; i >= 1; --i) for (int j = Y; j >= 1; --j) { sum[i][j] += sum[i + 1][j] + sum[i][j + 1] - sum[i + 1][j + 1]; siz[i][j] += siz[i + 1][j] + siz[i][j + 1] - siz[i + 1][j + 1]; } memset(f, -0x3f, sizeof(f)); for (int i = 1; i <= X; ++i) pos[1][i] = Y + 1; for (int j = 1; j <= Y; ++j) pos[0][j] = X + 1; for (int i = 1; i <= Y; ++i) pos[0][i] = X + 1; for (int i = 1; i <= X; ++i) pos[1][i] = Y + 1; for (int i = X + 1; i >= 1; --i) for (int j = Y + 1; j >= 1; --j) for (int now = 0; now <= 1; ++now) { if (!siz[i][j]) { f[now][i][j] = 0; continue; } if (now == 0) { while (query(i, j, pos[0][j] - 1, j)) --pos[0][j]; f[0][i][j] = sum[i][j] - g[1][pos[0][j]][j]; g[0][i][j] = min(g[0][i][j + 1], f[0][i][j] + sum[i][j]); } else { while (query(i, j, i, pos[1][i] - 1)) --pos[1][i]; f[1][i][j] = sum[i][j] - g[0][i][pos[1][i]]; g[1][i][j] = min(g[1][i + 1][j], f[1][i][j] + sum[i][j]); } } if (f[0][1][1] > 0) puts("Break a heart"); else if (f[0][1][1] == 0) puts("Flowers"); else puts("Cry"); return 0; } ```
### Prompt Create a solution in cpp for the following problem: You are given an undirected graph consisting of n vertices and m edges. Initially there is a single integer written on every vertex: the vertex i has p_i written on it. All p_i are distinct integers from 1 to n. You have to process q queries of two types: * 1 v — among all vertices reachable from the vertex v using the edges of the graph (including the vertex v itself), find a vertex u with the largest number p_u written on it, print p_u and replace p_u with 0; * 2 i — delete the i-th edge from the graph. Note that, in a query of the first type, it is possible that all vertices reachable from v have 0 written on them. In this case, u is not explicitly defined, but since the selection of u does not affect anything, you can choose any vertex reachable from v and print its value (which is 0). Input The first line contains three integers n, m and q (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 3 ⋅ 10^5; 1 ≤ q ≤ 5 ⋅ 10^5). The second line contains n distinct integers p_1, p_2, ..., p_n, where p_i is the number initially written on vertex i (1 ≤ p_i ≤ n). Then m lines follow, the i-th of them contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) and means that the i-th edge connects vertices a_i and b_i. It is guaranteed that the graph does not contain multi-edges. Then q lines follow, which describe the queries. Each line is given by one of the following formats: * 1 v — denotes a query of the first type with a vertex v (1 ≤ v ≤ n). * 2 i — denotes a query of the second type with an edge i (1 ≤ i ≤ m). For each query of the second type, it is guaranteed that the corresponding edge is not deleted from the graph yet. Output For every query of the first type, print the value of p_u written on the chosen vertex u. Example Input 5 4 6 1 2 5 4 3 1 2 2 3 1 3 4 5 1 1 2 1 2 3 1 1 1 2 1 2 Output 5 1 2 0 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 200010; const int M = 300010; struct OP { int opt, x; } op[500010]; int f[N], sz[N], vis[M], p[N]; vector<int> son[N], tmp; pair<int, int> edge[M], h[M]; set<pair<int, int>> st[N]; int find(int x) { if (f[x] == x) return x; return find(f[x]); } void dfs(int u, int z) { if (u == z) return; tmp.push_back(u); for (int v : son[u]) dfs(v, z); } void unite(int x, int y, int i) { int px = find(x), py = find(y); if (px == py) return; if (sz[px] >= sz[py]) { f[py] = px; son[px].push_back(py); sz[px] += sz[py]; h[i] = {py, px}; } else { f[px] = py; son[py].push_back(px); sz[py] += sz[px]; h[i] = {px, py}; } } int main() { int n, m, q; scanf("%d%d%d", &n, &m, &q); for (int i = 1; i <= n; i++) { scanf("%d", &p[i]); f[i] = i; sz[i] = 1; } for (int i = 1; i <= m; i++) { int u, v; scanf("%d%d", &u, &v); edge[i] = {u, v}; } for (int i = 1; i <= q; i++) { int opt, x; scanf("%d%d", &opt, &x); op[i] = {opt, x}; if (opt == 2) vis[x] = 1; } for (int i = 1; i <= m; i++) { if (vis[i]) continue; int u = edge[i].first, v = edge[i].second; unite(u, v, i); } for (int i = q; i >= 1; i--) { int opt = op[i].opt; if (opt == 1) continue; int x = op[i].x; int u = edge[x].first, v = edge[x].second; unite(u, v, x); } for (int i = 1; i <= n; i++) st[find(i)].insert({p[i], i}); for (int i = 1; i <= q; i++) { int opt = op[i].opt; if (opt == 1) { int x = find(op[i].x); auto it = --st[x].end(); int u = (*it).second; st[x].erase(it); printf("%d\n", p[u]); p[u] = 0; st[x].insert({p[u], u}); } else { int e = op[i].x; if (h[e].first == 0) continue; int x = h[e].first, y = h[e].second; if (sz[y] - sz[x] >= sz[x]) { dfs(x, 0); for (int u : tmp) { st[y].erase({p[u], u}); st[x].insert({p[u], u}); } tmp.clear(); } else { dfs(y, x); for (int u : tmp) { st[y].erase({p[u], u}); st[x].insert({p[u], u}); } swap(st[x], st[y]); } f[x] = x; son[y].pop_back(); sz[y] -= sz[x]; } } return 0; } ```
### Prompt Generate a Cpp solution to the following problem: There are n students standing in a circle in some order. The index of the i-th student is p_i. It is guaranteed that all indices of students are distinct integers from 1 to n (i. e. they form a permutation). Students want to start a round dance. A clockwise round dance can be started if the student 2 comes right after the student 1 in clockwise order (there are no students between them), the student 3 comes right after the student 2 in clockwise order, and so on, and the student n comes right after the student n - 1 in clockwise order. A counterclockwise round dance is almost the same thing — the only difference is that the student i should be right after the student i - 1 in counterclockwise order (this condition should be met for every i from 2 to n). For example, if the indices of students listed in clockwise order are [2, 3, 4, 5, 1], then they can start a clockwise round dance. If the students have indices [3, 2, 1, 4] in clockwise order, then they can start a counterclockwise round dance. Your task is to determine whether it is possible to start a round dance. Note that the students cannot change their positions before starting the dance; they cannot swap or leave the circle, and no other student can enter the circle. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≤ q ≤ 200) — the number of queries. Then q queries follow. The first line of the query contains one integer n (1 ≤ n ≤ 200) — the number of students. The second line of the query contains a permutation of indices p_1, p_2, ..., p_n (1 ≤ p_i ≤ n), where p_i is the index of the i-th student (in clockwise order). It is guaranteed that all p_i are distinct integers from 1 to n (i. e. they form a permutation). Output For each query, print the answer on it. If a round dance can be started with the given order of students, print "YES". Otherwise print "NO". Example Input 5 4 1 2 3 4 3 1 3 2 5 1 2 3 5 4 1 1 5 3 2 1 5 4 Output YES YES NO YES YES ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, ar[220020], fr[220020]; int main() { int t; cin >> t; while (t--) { cin >> n; int ok = 0; for (int i = 0; i < n; i++) cin >> ar[i]; for (int i = 1; i < n; i++) { if (abs(ar[i] - ar[i - 1]) == 1 || (ar[i] == n && ar[i - 1] == 1) || ar[i] == 1 && ar[i - 1] == n) continue; else { ok = 1; break; } } if (ok) cout << "NO" << endl; else cout << "YES" << endl; } return 0; } ```
### Prompt In cpp, your task is to solve the following problem: Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins. When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins. If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won. Input The first line contains number n — the number of techniques that the wrestlers have used (1 ≤ n ≤ 2·105). The following n lines contain integer numbers ai (|ai| ≤ 109, ai ≠ 0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with ( - ai) points. The techniques are given in chronological order. Output If the first wrestler wins, print string "first", otherwise print "second" Examples Input 5 1 2 -3 -4 3 Output second Input 3 -1 -2 3 Output first Input 2 4 -4 Output second Note Sequence x = x1x2... x|x| is lexicographically larger than sequence y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or there is such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. We use notation |a| to denote length of sequence a. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n, i, j, k; cin >> n; vector<int64_t> v2, v1; int64_t a[n], sum = 0; for (i = 0; i < n; i++) { cin >> a[i]; sum += a[i]; if (a[i] > 0) v1.push_back(a[i]); else v2.push_back(abs(a[i])); } if (sum > 0) { cout << "first"; return 0; } else if (sum < 0) { cout << "second"; return 0; } for (i = 0; i < v1.size() && i < v2.size(); i++) { if (v1[i] > v2[i]) { cout << "first"; return 0; } else if (v1[i] < v2[i]) { cout << "second"; return 0; } } if (a[n - 1] > 0) cout << "first"; else cout << "second"; return 0; } ```
### Prompt In cpp, your task is to solve the following problem: You are given a connected weighted undirected graph without any loops and multiple edges. Let us remind you that a graph's spanning tree is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The weight of a tree is defined as the sum of weights of the edges that the given tree contains. The minimum spanning tree (MST) of a graph is defined as the graph's spanning tree having the minimum possible weight. For any connected graph obviously exists the minimum spanning tree, but in the general case, a graph's minimum spanning tree is not unique. Your task is to determine the following for each edge of the given graph: whether it is either included in any MST, or included at least in one MST, or not included in any MST. Input The first line contains two integers n and m (2 ≤ n ≤ 105, <image>) — the number of the graph's vertexes and edges, correspondingly. Then follow m lines, each of them contains three integers — the description of the graph's edges as "ai bi wi" (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106, ai ≠ bi), where ai and bi are the numbers of vertexes connected by the i-th edge, wi is the edge's weight. It is guaranteed that the graph is connected and doesn't contain loops or multiple edges. Output Print m lines — the answers for all edges. If the i-th edge is included in any MST, print "any"; if the i-th edge is included at least in one MST, print "at least one"; if the i-th edge isn't included in any MST, print "none". Print the answers for the edges in the order in which the edges are specified in the input. Examples Input 4 5 1 2 101 1 3 100 2 3 2 2 4 2 3 4 1 Output none any at least one at least one any Input 3 3 1 2 1 2 3 1 1 3 2 Output any any none Input 3 3 1 2 1 2 3 1 1 3 1 Output at least one at least one at least one Note In the second sample the MST is unique for the given graph: it contains two first edges. In the third sample any two edges form the MST for the given graph. That means that each edge is included at least in one MST. ### Response ```cpp #include <bits/stdc++.h> #pragma comment(linker, "/stack:200000000") #pragma GCC optimize("Ofast") #pragma target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") using namespace std; const long long inf = 1ll << 62; inline long long read() { register long long x = 0, f = 1; register char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') f = -1; for (; isdigit(c); c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48); return x * f; } void write(long long x) { if (x < 0) x = -x, putchar('-'); if (x >= 10) write(x / 10); putchar(x % 10 + '0'); } void writeln(long long x) { write(x); puts(""); } const int maxn = 100233; struct Edge { int x, y, z, id; bool operator<(const Edge &w) const { return z < w.z; } } edge[maxn]; vector<pair<int, int> > V[maxn]; int fa[maxn], ans[maxn], pre[maxn], n, m; int dfsclk = 0; int dfs(int u, int fa) { int lowu = pre[u] = ++dfsclk; for (unsigned i = 0; i < V[u].size(); ++i) { int v = V[u][i].first; if (!pre[v]) { int lowv = dfs(v, V[u][i].second); lowu = ((lowu) < (lowv) ? (lowu) : (lowv)); if (lowv > pre[u]) ans[V[u][i].second] = 1; } else { if (pre[v] < pre[u] && V[u][i].second != fa) lowu = ((lowu) < (pre[v]) ? (lowu) : (pre[v])); } } return lowu; } inline int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); } void join(int x, int y) { x = find(x), y = find(y); if (x != y) { V[x].clear(), V[y].clear(); pre[x] = pre[y] = 0; fa[x] = y; } } int main() { dfsclk = 0; n = read(), m = read(); for (register int i = (1); i <= int(n); ++i) V[i].clear(); for (register int i = (1); i <= int(m); ++i) { edge[i].x = read(); edge[i].y = read(); edge[i].z = read(); edge[i].id = i; } memset(ans, 0, sizeof(ans)); memset(pre, 0, sizeof(pre)); for (register int i = (1); i <= int(n); ++i) fa[i] = i; sort(edge + 1, edge + 1 + m); for (int i = 1, j; i <= m; i = j + 1) { for (j = i; j + 1 <= m && edge[j + 1].z == edge[i].z; ++j) ; int cnt = 0; for (register int k = (i); k <= int(j); ++k) { int x = edge[k].x, y = edge[k].y; if (find(x) != find(y)) { V[find(x)].push_back(make_pair(find(y), edge[k].id)); V[find(y)].push_back(make_pair(find(x), edge[k].id)); ans[edge[k].id] = 2; } } for (register int k = (i); k <= int(j); ++k) { int x = edge[k].x, y = edge[k].y; if (find(x) != find(y) && !pre[find(x)]) { dfs(find(x), -1); } } for (register int k = (i); k <= int(j); ++k) join(edge[k].x, edge[k].y); } for (register int i = (1); i <= int(m); ++i) { if (ans[i] == 0) puts("none"); else if (ans[i] == 1) puts("any"); else puts("at least one"); } return 0; } ```
### Prompt Generate a Cpp solution to the following problem: In the Ancient Kingdom of Snuke, there was a pyramid to strengthen the authority of Takahashi, the president of AtCoder Inc. The pyramid had center coordinates (C_X, C_Y) and height H. The altitude of coordinates (X, Y) is max(H - |X - C_X| - |Y - C_Y|, 0). Aoki, an explorer, conducted a survey to identify the center coordinates and height of this pyramid. As a result, he obtained the following information: * C_X, C_Y was integers between 0 and 100 (inclusive), and H was an integer not less than 1. * Additionally, he obtained N pieces of information. The i-th of them is: "the altitude of point (x_i, y_i) is h_i." This was enough to identify the center coordinates and the height of the pyramid. Find these values with the clues above. Constraints * N is an integer between 1 and 100 (inclusive). * x_i and y_i are integers between 0 and 100 (inclusive). * h_i is an integer between 0 and 10^9 (inclusive). * The N coordinates (x_1, y_1), (x_2, y_2), (x_3, y_3), ..., (x_N, y_N) are all different. * The center coordinates and the height of the pyramid can be uniquely identified. Input Input is given from Standard Input in the following format: N x_1 y_1 h_1 x_2 y_2 h_2 x_3 y_3 h_3 : x_N y_N h_N Output Print values C_X, C_Y and H representing the center coordinates and the height of the pyramid in one line, with spaces in between. Examples Input 4 2 3 5 2 1 5 1 2 5 3 2 5 Output 2 2 6 Input 2 0 0 100 1 1 98 Output 0 0 100 Input 3 99 1 191 100 1 192 99 0 192 Output 100 0 193 ### Response ```cpp #include<bits/stdc++.h> using namespace std; int N,i,x[100],y[100],h[100],t,X,Y,H; int main(){ cin>>N; for(i=0;i<N;i++){ cin>>x[i]>>y[i]>>h[i]; if(h[i]>0)t=i; } for(X=0;X<101;X++)for(Y=0;Y<101;Y++){ H=h[t]+abs(x[t]-X)+abs(y[t]-Y); for(i=0;i<N;i++)if(max(H-abs(x[i]-X)-abs(y[i]-Y),0)!=h[i])break; if(i==N){cout<<X<<' '<<Y<<' '<<H<<endl;return 0;} } } ```
### Prompt Your task is to create a Cpp solution to the following problem: Vasiliy finally got to work, where there is a huge amount of tasks waiting for him. Vasiliy is given a matrix consisting of n rows and m columns and q tasks. Each task is to swap two submatrices of the given matrix. For each task Vasiliy knows six integers ai, bi, ci, di, hi, wi, where ai is the index of the row where the top-left corner of the first rectangle is located, bi is the index of its column, ci is the index of the row of the top-left corner of the second rectangle, di is the index of its column, hi is the height of the rectangle and wi is its width. It's guaranteed that two rectangles in one query do not overlap and do not touch, that is, no cell belongs to both rectangles, and no two cells belonging to different rectangles share a side. However, rectangles are allowed to share an angle. Vasiliy wants to know how the matrix will look like after all tasks are performed. Input The first line of the input contains three integers n, m and q (2 ≤ n, m ≤ 1000, 1 ≤ q ≤ 10 000) — the number of rows and columns in matrix, and the number of tasks Vasiliy has to perform. Then follow n lines containing m integers vi, j (1 ≤ vi, j ≤ 109) each — initial values of the cells of the matrix. Each of the following q lines contains six integers ai, bi, ci, di, hi, wi (1 ≤ ai, ci, hi ≤ n, 1 ≤ bi, di, wi ≤ m). Output Print n lines containing m integers each — the resulting matrix. Examples Input 4 4 2 1 1 2 2 1 1 2 2 3 3 4 4 3 3 4 4 1 1 3 3 2 2 3 1 1 3 2 2 Output 4 4 3 3 4 4 3 3 2 2 1 1 2 2 1 1 Input 4 2 1 1 1 1 1 2 2 2 2 1 1 4 1 1 2 Output 2 2 1 1 2 2 1 1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, m, q; struct cell { int val; cell *d, *r; cell(int _val) { val = _val; r = NULL; d = NULL; } } * p[1002][1002]; int a[1002][1002]; cell* get(int x, int y) { cell* ans = p[0][0]; while (x--) ans = ans->d; while (y--) ans = ans->r; return ans; } int main() { scanf("%d%d%d", &m, &n, &q); for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) scanf("%d", &a[i][j]); for (int i = 0; i <= m + 1; i++) for (int j = 0; j <= n + 1; j++) p[i][j] = new cell(a[i][j]); for (int i = 0; i <= m; i++) for (int j = 0; j <= n; j++) { p[i][j]->r = p[i][j + 1]; p[i][j]->d = p[i + 1][j]; } while (q--) { int a, b, c, d, h, w; scanf("%d%d%d%d%d%d", &a, &b, &c, &d, &h, &w); cell* u = get(a, b - 1); cell* v = get(c, d - 1); cell* u1 = get(a - 1, b); cell* v1 = get(c - 1, d); cell* u2 = get(a + h - 1, b); cell* v2 = get(c + h - 1, d); cell* u3 = get(a, b + w - 1); cell* v3 = get(c, d + w - 1); for (int i = 1; i <= h; i++) { swap(u->r, v->r); u = u->d; v = v->d; } for (int i = 1; i <= w; i++) { swap(u1->d, v1->d); u1 = u1->r; v1 = v1->r; } for (int i = 1; i <= w; i++) { swap(u2->d, v2->d); u2 = u2->r; v2 = v2->r; } for (int i = 1; i <= h; i++) { swap(u3->r, v3->r); u3 = u3->d; v3 = v3->d; } } for (int i = 1; i <= m; i++) { cell* u = get(i, 1); for (int j = 1; j <= n; j++) { printf("%d ", u->val); u = u->r; } printf("\n"); } } ```
### Prompt In CPP, your task is to solve the following problem: Let's call left cyclic shift of some string t_1 t_2 t_3 ... t_{n - 1} t_n as string t_2 t_3 ... t_{n - 1} t_n t_1. Analogically, let's call right cyclic shift of string t as string t_n t_1 t_2 t_3 ... t_{n - 1}. Let's say string t is good if its left cyclic shift is equal to its right cyclic shift. You are given string s which consists of digits 0–9. What is the minimum number of characters you need to erase from s to make it good? Input The first line contains single integer t (1 ≤ t ≤ 1000) — the number of test cases. Next t lines contains test cases — one per line. The first and only line of each test case contains string s (2 ≤ |s| ≤ 2 ⋅ 10^5). Each character s_i is digit 0–9. It's guaranteed that the total length of strings doesn't exceed 2 ⋅ 10^5. Output For each test case, print the minimum number of characters you need to erase from s to make it good. Example Input 3 95831 100120013 252525252525 Output 3 5 0 Note In the first test case, you can erase any 3 characters, for example, the 1-st, the 3-rd, and the 4-th. You'll get string 51 and it is good. In the second test case, we can erase all characters except 0: the remaining string is 0000 and it's good. In the third test case, the given string s is already good. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int gcd(long long a, long long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } int main() { ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); ; long long i, j, k, n, m, t = 1; cin >> t; while (t--) { string s; cin >> s; n = s.size(); map<char, long long> make_pair; long long mx = INT_MIN; for (i = 0; i < n; i++) { make_pair[s[i]]++; } for (char c = '0'; c <= '9'; c++) { if (make_pair[c] > mx) { mx = make_pair[c]; } } for (char c1 = '0'; c1 < '9'; c1++) { for (char c2 = c1 + 1; c2 <= '9'; c2++) { k = 0; char prev = '$'; for (i = 0; i < n; i++) { if (s[i] == c1) { if (prev == c2) { prev = c1; k++; } else if (prev == '$') { prev = c1; k++; } } else if (s[i] == c2) { if (prev == c1) { prev = c2; k++; } else if (prev == '$') { prev = c2; k++; } } } if (k > mx && k % 2 == 0) { mx = k; } else if ((k - 1) > mx && (k - 1) % 2 == 0) { mx = k - 1; } } } cout << s.size() - mx << endl; } return 0; } ```
### Prompt Please provide a Cpp coded solution to the problem described below: Gerald got tired of playing board games with the usual six-sided die, and he bought a toy called Randomizer. It functions as follows. A Randomizer has its own coordinate plane on which a strictly convex polygon is painted, the polygon is called a basic polygon. If you shake a Randomizer, it draws some nondegenerate (i.e. having a non-zero area) convex polygon with vertices at some vertices of the basic polygon. The result of the roll (more precisely, the result of the shaking) is considered to be the number of points with integer coordinates, which were strictly inside (the points on the border are not considered) the selected polygon. Now Gerald is wondering: what is the expected result of shaking the Randomizer? During the shaking the Randomizer considers all the possible non-degenerate convex polygons with vertices at the vertices of the basic polygon. Let's assume that there are k versions of the polygons. Then the Randomizer chooses each of them with probability <image>. Input The first line of the input contains a single integer n (3 ≤ n ≤ 100 000) — the number of vertices of the basic polygon. Next n lines contain the coordinates of the vertices of the basic polygon. The i-th of these lines contain two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex of the polygon. The vertices are given in the counter-clockwise order. Output Print the sought expected value with absolute or relative error at most 10 - 9. Examples Input 4 0 0 2 0 2 2 0 2 Output 0.2 Input 5 0 0 2 0 2 2 1 3 0 2 Output 0.8125 Note A polygon is called strictly convex if it is convex and no its vertices lie on the same line. Let's assume that a random variable takes values x1, ..., xn with probabilities p1, ..., pn, correspondingly. Then the expected value of this variable equals to <image>. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n; long long x[100005], y[100005]; long double P, ans, sum; long long gcd(long long x, long long y) { return x ? gcd(y % x, x) : y; } long long GCD(long long x, long long y) { if (x < 0) x = -x; if (y < 0) y = -y; if (x > y) swap(x, y); return gcd(x, y); } int main() { int i, j, k; scanf("%d", &n); for (i = 1; i <= n; i++) scanf("%I64d %I64d", &x[i], &y[i]); for (i = 1; i <= 90 && i < n; i++) { P = 1.0 / (pow(2, i + 1) - (1.0 + n + 0.5 * n * (n - 1)) / pow(2, n - i - 1)) - 1.0 / (pow(2, n) - 1 - n - 0.5 * n * (n - 1)); for (j = 1; j <= n; j++) { k = (j + i - 1) % n + 1; ans += (x[j] * y[k] - y[j] * x[k]) / 2.0 * P; sum += GCD(x[j] - x[k], y[j] - y[k]) * P; } } ans = ans - sum / 2.0 + 1; printf("%.10lf", (double)ans); return 0; } ```
### Prompt Generate a Cpp solution to the following problem: Koa the Koala has a matrix A of n rows and m columns. Elements of this matrix are distinct integers from 1 to n ⋅ m (each number from 1 to n ⋅ m appears exactly once in the matrix). For any matrix M of n rows and m columns let's define the following: * The i-th row of M is defined as R_i(M) = [ M_{i1}, M_{i2}, …, M_{im} ] for all i (1 ≤ i ≤ n). * The j-th column of M is defined as C_j(M) = [ M_{1j}, M_{2j}, …, M_{nj} ] for all j (1 ≤ j ≤ m). Koa defines S(A) = (X, Y) as the spectrum of A, where X is the set of the maximum values in rows of A and Y is the set of the maximum values in columns of A. More formally: * X = \{ max(R_1(A)), max(R_2(A)), …, max(R_n(A)) \} * Y = \{ max(C_1(A)), max(C_2(A)), …, max(C_m(A)) \} Koa asks you to find some matrix A' of n rows and m columns, such that each number from 1 to n ⋅ m appears exactly once in the matrix, and the following conditions hold: * S(A') = S(A) * R_i(A') is bitonic for all i (1 ≤ i ≤ n) * C_j(A') is bitonic for all j (1 ≤ j ≤ m) An array t (t_1, t_2, …, t_k) is called bitonic if it first increases and then decreases. More formally: t is bitonic if there exists some position p (1 ≤ p ≤ k) such that: t_1 < t_2 < … < t_p > t_{p+1} > … > t_k. Help Koa to find such matrix or to determine that it doesn't exist. Input The first line of the input contains two integers n and m (1 ≤ n, m ≤ 250) — the number of rows and columns of A. Each of the ollowing n lines contains m integers. The j-th integer in the i-th line denotes element A_{ij} (1 ≤ A_{ij} ≤ n ⋅ m) of matrix A. It is guaranteed that every number from 1 to n ⋅ m appears exactly once among elements of the matrix. Output If such matrix doesn't exist, print -1 on a single line. Otherwise, the output must consist of n lines, each one consisting of m space separated integers — a description of A'. The j-th number in the i-th line represents the element A'_{ij}. Every integer from 1 to n ⋅ m should appear exactly once in A', every row and column in A' must be bitonic and S(A) = S(A') must hold. If there are many answers print any. Examples Input 3 3 3 5 6 1 7 9 4 8 2 Output 9 5 1 7 8 2 3 6 4 Input 2 2 4 1 3 2 Output 4 1 3 2 Input 3 4 12 10 8 6 3 4 5 7 2 11 9 1 Output 12 8 6 1 10 11 9 2 3 4 5 7 Note Let's analyze the first sample: For matrix A we have: * Rows: * R_1(A) = [3, 5, 6]; max(R_1(A)) = 6 * R_2(A) = [1, 7, 9]; max(R_2(A)) = 9 * R_3(A) = [4, 8, 2]; max(R_3(A)) = 8 * Columns: * C_1(A) = [3, 1, 4]; max(C_1(A)) = 4 * C_2(A) = [5, 7, 8]; max(C_2(A)) = 8 * C_3(A) = [6, 9, 2]; max(C_3(A)) = 9 * X = \{ max(R_1(A)), max(R_2(A)), max(R_3(A)) \} = \{ 6, 9, 8 \} * Y = \{ max(C_1(A)), max(C_2(A)), max(C_3(A)) \} = \{ 4, 8, 9 \} * So S(A) = (X, Y) = (\{ 6, 9, 8 \}, \{ 4, 8, 9 \}) For matrix A' we have: * Rows: * R_1(A') = [9, 5, 1]; max(R_1(A')) = 9 * R_2(A') = [7, 8, 2]; max(R_2(A')) = 8 * R_3(A') = [3, 6, 4]; max(R_3(A')) = 6 * Columns: * C_1(A') = [9, 7, 3]; max(C_1(A')) = 9 * C_2(A') = [5, 8, 6]; max(C_2(A')) = 8 * C_3(A') = [1, 2, 4]; max(C_3(A')) = 4 * Note that each of this arrays are bitonic. * X = \{ max(R_1(A')), max(R_2(A')), max(R_3(A')) \} = \{ 9, 8, 6 \} * Y = \{ max(C_1(A')), max(C_2(A')), max(C_3(A')) \} = \{ 9, 8, 4 \} * So S(A') = (X, Y) = (\{ 9, 8, 6 \}, \{ 9, 8, 4 \}) ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int INF = 100000000; int main() { int n, m; cin >> n >> m; int a[252][252]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> a[i][j]; } } int x[252]{0}, y[252]{0}; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { x[i] = max(x[i], a[i][j]); } } for (int j = 0; j < m; j++) { for (int i = 0; i < n; i++) { y[j] = max(y[j], a[i][j]); } } sort(x, x + n); sort(y, y + m); x[n] = INF; y[m] = INF; int i = 0, j = 0, k = 1; bool b[100000]{0}; while (i < n && j < m) { if (x[i] < y[j]) { for (int l = m - 1; l > j; l--) { a[i][l] = k; b[k] = true; while (b[k]) { k++; } } b[x[i]] = true; a[i][j] = x[i]; i++; } else if (x[i] > y[j]) { for (int l = n - 1; l > i; l--) { a[l][j] = k; b[k] = true; while (b[k]) { k++; } } b[y[j]] = true; a[i][j] = y[j]; j++; } else { for (int l = m - 1; l > j; l--) { a[i][l] = k; b[k] = true; while (b[k]) { k++; } } for (int l = n - 1; l > i; l--) { a[l][j] = k; b[k] = true; while (b[k]) { k++; } } b[x[i]] = true; a[i][j] = x[i]; i++; j++; } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cout << a[i][j] << " "; } cout << endl; } } ```
### Prompt Please provide a cpp coded solution to the problem described below: Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city. There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1. The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip. For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored. Input The input consists of multiple datasets, each in the following format. > n m > s g > x 1 y 1 d 1 c 1 > ... > xm ym dm cm > Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space. The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero. The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive. The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive. No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions. The last dataset is followed by a line containing two zeros (separated by a space). Output For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces. If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase. Sample Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output for the Sample Input unreachable 4.00000 5.50000 11.25664 Example Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output unreachable 4.00000 5.50000 11.25664 ### Response ```cpp #include<cstdio> #include<cmath> #include<algorithm> #include<queue> #include<vector> using namespace std; typedef pair<pair<double,int>,pair<int,int> > P; class road{ public: int to,d,c; road(int x,int y,int z){to = x;d = y;c = z;}; }; vector<road> G[31]; int main(){ int n,m,s,g; int x,y,d,c; for(;;){ scanf("%d %d",&n,&m); if(!n && !m)break; scanf("%d %d",&s,&g); double t[31][31][31]; bool v[31][31][31]; for(int i=0;i<=n;i++)G[i].clear(); for(int i=0;i<m;i++){ scanf("%d %d %d %d",&x,&y,&d,&c); G[x].push_back(road(y,d,c)); G[y].push_back(road(x,d,c)); } for(int i=0;i<=n;i++) for(int j=0;j<=n;j++) for(int k=0;k<=30;k++){ t[i][j][k] = 1e10; v[i][j][k] = false; } t[s][0][0] = 0.0; priority_queue<P,vector<P>,greater<P> > q; q.push(P(pair<double,int>(0.0,s),pair<int,int>(0,0))); while(q.size()){ P p = q.top();q.pop(); double time = p.first.first; int now,prv,speed; now = p.first.second; prv = p.second.first; speed = p.second.second; if(v[now][prv][speed])continue; v[now][prv][speed] = true; for(int i=0;i<(int)G[now].size();i++){ road r = G[now][i]; if(r.to != prv){ for(int dif=-1;dif<=1;dif++){ if(speed+dif>0 && speed+dif<=r.c){ if(!v[r.to][now][speed+dif]){ if(t[r.to][now][speed+dif] > time+(double)r.d/(speed+dif)){ t[r.to][now][speed+dif] = time+(double)r.d/(speed+dif); q.push(P(pair<double,int>(t[r.to][now][speed+dif],r.to),pair<int,int>(now,speed+dif))); } } } } } } } double ans = 1e10; for(int i=0;i<=n;i++)ans = min(ans,t[g][i][1]); if(ans==1e10)printf("unreachable\n"); else printf("%.4lf\n",ans); } } ```
### Prompt Please formulate a CPP solution to the following problem: Takahashi is solving quizzes. He has easily solved all but the last one. The last quiz has three choices: 1, 2, and 3. With his supernatural power, Takahashi has found out that the choices A and B are both wrong. Print the correct choice for this problem. Constraints * Each of the numbers A and B is 1, 2, or 3. * A and B are different. Input Input is given from Standard Input in the following format: A B Output Print the correct choice. Examples Input 3 1 Output 2 Input 1 2 Output 3 ### Response ```cpp #include <iostream> int main(void) { int A, B; std::cin >> A >> B; std::cout << abs(6 - A - B); return 0; } ```
### Prompt Your task is to create a Cpp solution to the following problem: You are given two tables A and B of size n × m. We define a sorting by column as the following: we choose a column and reorder the rows of the table by the value in this column, from the rows with the smallest value to the rows with the largest. In case there are two or more rows with equal value in this column, their relative order does not change (such sorting algorithms are called stable). You can find this behavior of sorting by column in many office software for managing spreadsheets. Petya works in one, and he has a table A opened right now. He wants to perform zero of more sortings by column to transform this table to table B. Determine if it is possible to do so, and if yes, find a sequence of columns to sort by. Note that you do not need to minimize the number of sortings. Input The first line contains two integers n and m (1 ≤ n, m ≤ 1500) — the sizes of the tables. Each of the next n lines contains m integers a_{i,j} (1 ≤ a_{i, j} ≤ n), denoting the elements of the table A. Each of the next n lines contains m integers b_{i, j} (1 ≤ b_{i, j} ≤ n), denoting the elements of the table B. Output If it is not possible to transform A into B, print -1. Otherwise, first print an integer k (0 ≤ k ≤ 5000) — the number of sortings in your solution. Then print k integers c_1, …, c_k (1 ≤ c_i ≤ m) — the columns, by which Petya needs to perform a sorting. We can show that if a solution exists, there is one in no more than 5000 sortings. Examples Input 2 2 2 2 1 2 1 2 2 2 Output 1 1 Input 3 3 2 3 2 1 3 3 1 1 2 1 1 2 1 3 3 2 3 2 Output 2 1 2 Input 2 2 1 1 2 1 2 1 1 1 Output -1 Input 4 1 2 2 2 1 1 2 2 2 Output 1 1 Note Consider the second example. After the sorting by the first column the table becomes $$$\begin{matrix} 1&3&3\\\ 1&1&2\\\ 2&3&2. \end{matrix}$$$ After the sorting by the second column the table becomes $$$\begin{matrix} 1&1&2\\\ 1&3&3\\\ 2&3&2, \end{matrix}$$$ and this is what we need. In the third test any sorting does not change anything, because the columns are already sorted. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1505; int a[N][N], b[N][N], n, m, pa[N], pb[N], num[N], ida[N], idb[N]; bool is[N][N], ned[N]; queue<int> q; int ans[N], len; bool cmpa(int A, int B) { for (int j = 1; j <= m; j++) if (a[A][j] != a[B][j]) return a[A][j] < a[B][j]; return A < B; } bool cmpb(int A, int B) { for (int j = 1; j <= m; j++) if (b[A][j] != b[B][j]) return b[A][j] < b[B][j]; return A < B; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cin >> n >> m; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cin >> a[i][j]; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cin >> b[i][j]; for (int i = 1; i <= n; i++) pa[i] = pb[i] = i; sort(pa + 1, pa + 1 + n, cmpa); sort(pb + 1, pb + 1 + n, cmpb); for (int i = 1; i <= n; i++) ida[pa[i]] = i, idb[pb[i]] = i; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (a[pa[i]][j] != b[pb[i]][j]) { cout << "-1" << '\n'; return 0; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) if (b[i - 1][j] > b[i][j]) num[j]++, is[i][j] = 1; } for (int i = 1; i <= n; i++) ned[i] = 1; for (int i = 1; i <= m; i++) if (!num[i]) q.push(i); while (q.size()) { int x = q.front(); q.pop(); ans[++len] = x; for (int i = 1; i <= n; i++) if (b[i - 1][x] < b[i][x] && ned[i]) { ned[i] = 0; for (int j = 1; j <= m; j++) if (is[i][j]) { is[i][j] = 0; num[j]--; if (!num[j]) q.push(j); } } } bool flag = 0; for (int i = 1; i <= n; i++) if (ned[i] && pa[idb[i - 1]] > pa[idb[i]]) flag = 1; if (flag) { cout << "-1" << '\n'; return 0; } cout << len << '\n'; for (int i = len; i >= 1; i--) cout << ans[i] << ' '; cout << '\n'; return 0; } ```
### Prompt Construct a Cpp code solution to the problem outlined: Takahashi loves gold coins. He gains 1000 happiness points for each 500-yen coin he has and gains 5 happiness points for each 5-yen coin he has. (Yen is the currency of Japan.) Takahashi has X yen. If he exchanges his money so that he will gain the most happiness points, how many happiness points will he earn? (We assume that there are six kinds of coins available: 500-yen, 100-yen, 50-yen, 10-yen, 5-yen, and 1-yen coins.) Constraints * 0 \leq X \leq 10^9 * X is an integer. Input Input is given from Standard Input in the following format: X Output Print the maximum number of happiness points that can be earned. Examples Input 1024 Output 2020 Input 0 Output 0 Input 1000000000 Output 2000000000 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main(){ int X; cin>>X; int a=X/500,b=(X-a*500)/5; cout<<a*1000+b*5<<endl; } ```
### Prompt Your challenge is to write a Cpp solution to the following problem: There is an array a of 2^{30} integers, indexed from 0 to 2^{30}-1. Initially, you know that 0 ≤ a_i < 2^{30} (0 ≤ i < 2^{30}), but you do not know any of the values. Your task is to process queries of two types: * 1 l r x: You are informed that the bitwise xor of the subarray [l, r] (ends inclusive) is equal to x. That is, a_l ⊕ a_{l+1} ⊕ … ⊕ a_{r-1} ⊕ a_r = x, where ⊕ is the bitwise xor operator. In some cases, the received update contradicts past updates. In this case, you should ignore the contradicting update (the current update). * 2 l r: You are asked to output the bitwise xor of the subarray [l, r] (ends inclusive). If it is still impossible to know this value, considering all past updates, then output -1. Note that the queries are encoded. That is, you need to write an online solution. Input The first line contains a single integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries. Each of the next q lines describes a query. It contains one integer t (1 ≤ t ≤ 2) — the type of query. The given queries will be encoded in the following way: let last be the answer to the last query of the second type that you have answered (initially, last = 0). If the last answer was -1, set last = 1. * If t = 1, three integers follow, l', r', and x' (0 ≤ l', r', x' < 2^{30}), meaning that you got an update. First, do the following: l = l' ⊕ last, r = r' ⊕ last, x = x' ⊕ last and, if l > r, swap l and r. This means you got an update that the bitwise xor of the subarray [l, r] is equal to x (notice that you need to ignore updates that contradict previous updates). * If t = 2, two integers follow, l' and r' (0 ≤ l', r' < 2^{30}), meaning that you got a query. First, do the following: l = l' ⊕ last, r = r' ⊕ last and, if l > r, swap l and r. For the given query, you need to print the bitwise xor of the subarray [l, r]. If it is impossible to know, print -1. Don't forget to change the value of last. It is guaranteed there will be at least one query of the second type. Output After every query of the second type, output the bitwise xor of the given subarray or -1 if it is still impossible to know. Examples Input 12 2 1 2 2 1 1073741822 1 0 3 4 2 0 0 2 3 3 2 0 3 1 6 7 3 2 4 4 1 0 2 1 2 0 0 2 4 4 2 0 0 Output -1 -1 -1 -1 5 -1 6 3 5 Input 4 1 5 5 9 1 6 6 5 1 6 5 10 2 6 5 Output 12 Note In the first example, the real queries (without being encoded) are: * 12 * 2 1 2 * 2 0 1073741823 * 1 1 2 5 * 2 1 1 * 2 2 2 * 2 1 2 * 1 2 3 6 * 2 1 1 * 1 1 3 0 * 2 1 1 * 2 2 2 * 2 3 3 * The answers for the first two queries are -1 because we don't have any such information on the array initially. * The first update tells us a_1 ⊕ a_2 = 5. Note that we still can't be certain about the values a_1 or a_2 independently (for example, it could be that a_1 = 1, a_2 = 4, and also a_1 = 3, a_2 = 6). * After we receive all three updates, we have enough information to deduce a_1, a_2, a_3 independently. In the second example, notice that after the first two updates we already know that a_5 ⊕ a_6 = 12, so the third update is contradicting, and we ignore it. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int read() { int x = 0, f = 1; char c; while ((c = getchar()) < '0' || c > '9') { if (c == '-') f = -1; } while (c >= '0' && c <= '9') { x = (x << 3) + (x << 1) + (c ^ 48); c = getchar(); } return x * f; } int q, ans; map<int, int> fa, s; int find(int x) { if (!fa.count(x)) return x; int tmp = find(fa[x]); s[x] ^= s[fa[x]]; fa[x] = tmp; return fa[x]; } void merge(int u, int v, int c) { int x = find(u), y = find(v); if (x == y) return; fa[x] = y; s[x] = s[u] ^ c ^ s[v]; } signed main() { q = read(); while (q--) { int op = read(), l = read() ^ ans, r = read() ^ ans; if (l > r) swap(l, r); r++; if (op == 1) { int x = read() ^ ans; merge(l, r, x); } else { if (find(l) != find(r)) { ans = 1; puts("-1"); } else { ans = s[l] ^ s[r]; printf("%d\n", ans); } } } } ```
### Prompt Your task is to create a CPP solution to the following problem: The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers. Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits. Input The only line of input contains one integer n (1 ≤ n ≤ 55) — the maximum length of a number that a door-plate can hold. Output Output one integer — the maximum number of offices, than can have unique lucky numbers not longer than n digits. Examples Input 2 Output 6 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { long long int temp, n; cin >> n; temp = pow(2, n + 1) - 2; cout << temp; } ```
### Prompt Generate a Cpp solution to the following problem: Amr is a young coder who likes music a lot. He always wanted to learn how to play music but he was busy coding so he got an idea. Amr has n instruments, it takes ai days to learn i-th instrument. Being busy, Amr dedicated k days to learn how to play the maximum possible number of instruments. Amr asked for your help to distribute his free days between instruments so that he can achieve his goal. Input The first line contains two numbers n, k (1 ≤ n ≤ 100, 0 ≤ k ≤ 10 000), the number of instruments and number of days respectively. The second line contains n integers ai (1 ≤ ai ≤ 100), representing number of days required to learn the i-th instrument. Output In the first line output one integer m representing the maximum number of instruments Amr can learn. In the second line output m space-separated integers: the indices of instruments to be learnt. You may output indices in any order. if there are multiple optimal solutions output any. It is not necessary to use all days for studying. Examples Input 4 10 4 3 1 2 Output 4 1 2 3 4 Input 5 6 4 3 1 1 2 Output 3 1 3 4 Input 1 3 4 Output 0 Note In the first test Amr can learn all 4 instruments. In the second test other possible solutions are: {2, 3, 5} or {3, 4, 5}. In the third test Amr doesn't have enough time to learn the only presented instrument. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int mod = 1000000007; const int MAX = 100005; vector<pair<int, int> > myvec; int dp[110]; int main() { int n, k, ind = 0, cnt = 0; cin >> n >> k; for (int i = (0); i < (n); ++i) { int x; cin >> x; myvec.push_back(make_pair(x, ++cnt)); } sort(myvec.begin(), myvec.end()); int sum1 = 0; for (int i = (0); i < ((int)myvec.size()); ++i) { sum1 += myvec[i].first; dp[i] = sum1; } bool ok = true; while (ok) { if (dp[ind] <= k && dp[ind] != 0) { ind++; continue; } else ok = false; } cout << ind << '\n'; for (int i = (0); i < (ind); ++i) { cout << myvec[i].second; if (i != ind - 1) cout << ' '; else cout << '\n'; } return 0; } ```
### Prompt Please formulate a CPP solution to the following problem: There are n types of coins in Byteland. Conveniently, the denomination of the coin type k divides the denomination of the coin type k + 1, the denomination of the coin type 1 equals 1 tugrick. The ratio of the denominations of coin types k + 1 and k equals ak. It is known that for each x there are at most 20 coin types of denomination x. Byteasar has bk coins of type k with him, and he needs to pay exactly m tugricks. It is known that Byteasar never has more than 3·105 coins with him. Byteasar want to know how many ways there are to pay exactly m tugricks. Two ways are different if there is an integer k such that the amount of coins of type k differs in these two ways. As all Byteland citizens, Byteasar wants to know the number of ways modulo 109 + 7. Input The first line contains single integer n (1 ≤ n ≤ 3·105) — the number of coin types. The second line contains n - 1 integers a1, a2, ..., an - 1 (1 ≤ ak ≤ 109) — the ratios between the coin types denominations. It is guaranteed that for each x there are at most 20 coin types of denomination x. The third line contains n non-negative integers b1, b2, ..., bn — the number of coins of each type Byteasar has. It is guaranteed that the sum of these integers doesn't exceed 3·105. The fourth line contains single integer m (0 ≤ m < 1010000) — the amount in tugricks Byteasar needs to pay. Output Print single integer — the number of ways to pay exactly m tugricks modulo 109 + 7. Examples Input 1 4 2 Output 1 Input 2 1 4 4 2 Output 3 Input 3 3 3 10 10 10 17 Output 6 Note In the first example Byteasar has 4 coins of denomination 1, and he has to pay 2 tugricks. There is only one way. In the second example Byteasar has 4 coins of each of two different types of denomination 1, he has to pay 2 tugricks. There are 3 ways: pay one coin of the first type and one coin of the other, pay two coins of the first type, and pay two coins of the second type. In the third example the denominations are equal to 1, 3, 9. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 300300, P = 1000000007; int i, j, k, n, m, ch, An, ma; long long x; int a[N], b[N], f[N], g[N], A[N]; char s[N]; void R(int &x) { x = 0; ch = getchar(); while (ch < '0' || '9' < ch) ch = getchar(); while ('0' <= ch && ch <= '9') x = x * 10 + ch - '0', ch = getchar(); } int main() { R(n); a[1] = 1; for (i = 2; i <= n; i++) R(a[i]); for (i = 1; i <= n; i++) R(b[i]); scanf("%s", s + 1); m = strlen(s + 1); for (i = 1; i <= m; i++) A[i] = s[m - i + 1] - '0'; for (i = 1; i <= m; i += 4) A[++An] = A[i] + A[i + 1] * 10 + A[i + 2] * 100 + A[i + 3] * 1000; for (i = An + 1; i <= m; i++) A[i] = 0; f[0] = 1; for (i = 1; i <= n; i++) { if (a[i] != 1) { x = 0; for (j = An; j; j--) { x = x * 10000 + A[j]; A[j] = x / a[i]; x %= a[i]; } while (An > 1 && !A[An]) An--; for (j = 0; j <= ma; j++) { if (j + x > ma) f[j] = 0; else f[j] = f[j + x]; } while (ma && !f[ma]) ma--; for (j = 0; j * a[i] <= ma; j++) f[j] = f[j * a[i]]; for (; j <= ma; j++) f[j] = 0; while (ma && !f[ma]) ma--; } ma += b[i]; g[0] = f[0]; for (j = 1; j <= ma; j++) g[j] = (g[j - 1] + f[j]) % P; for (j = 0; j <= ma; j++) { f[j] = g[j]; if (j > b[i]) f[j] = (f[j] + P - g[j - b[i] - 1]) % P; } } if (An > 2) return puts("0"), 0; k = A[2] * 10000 + A[1]; if (k > ma) return puts("0"), 0; printf("%d\n", f[k]); } ```
### Prompt Develop a solution in cpp to the problem described below: Polycarpus loves lucky numbers. Everybody knows that lucky numbers are positive integers, whose decimal representation (without leading zeroes) contain only the lucky digits x and y. For example, if x = 4, and y = 7, then numbers 47, 744, 4 are lucky. Let's call a positive integer a undoubtedly lucky, if there are such digits x and y (0 ≤ x, y ≤ 9), that the decimal representation of number a (without leading zeroes) contains only digits x and y. Polycarpus has integer n. He wants to know how many positive integers that do not exceed n, are undoubtedly lucky. Help him, count this number. Input The first line contains a single integer n (1 ≤ n ≤ 109) — Polycarpus's number. Output Print a single integer that says, how many positive integers that do not exceed n are undoubtedly lucky. Examples Input 10 Output 10 Input 123 Output 113 Note In the first test sample all numbers that do not exceed 10 are undoubtedly lucky. In the second sample numbers 102, 103, 104, 105, 106, 107, 108, 109, 120, 123 are not undoubtedly lucky. ### Response ```cpp #include <bits/stdc++.h> using namespace std; string s; long long ans, n; int a[20]; void solve(int t) { int temp = t; for (int k = 0; k < n; k++) { a[k] = temp % 2; temp /= 2; } for (int i = 1; i < 9; i++) { for (int j = i + 1; j <= 9; j++) { bool flag = 1; for (int k = 0; k < n; k++) { int l = a[n - k - 1]; if (l == 0) l = i; else l = j; if (s[k] < l + '0') { flag = 0; k = n; } else if (l + '0' < s[k]) k = n; } if (flag) { ans++; } } } if (a[n - 1]) { for (int i = 1; i <= 9; i++) { bool flag = 1; for (int k = 0; k < n; k++) { int l = a[n - k - 1]; if (l) l = i; if (s[k] < l + '0') { flag = 0; k = n; } else if (l + '0' < s[k]) k = n; } if (flag) ans++; } } } void solve2() { for (int i = 1; i <= 9; i++) { bool flag = 1; for (int j = 0; j < n; j++) { if (s[j] - '0' > i) j = n; else if (s[j] - '0' < i) { flag = 0; j = n; } } if (flag) ans++; else return; } } int main() { cin >> s; n = s.size(); int p = pow(2, n) - 1; for (int i = 1; i < p; i++) { solve(i); } solve2(); if (n > 1) ans += 9; for (int i = 2; i < n; i++) { ans += (pow(2, i) - 2) * 36; ans += (pow(2, i - 1) - 1) * 9; ans += 9; } cout << ans; } ```
### Prompt Generate a cpp solution to the following problem: Berland has n cities, some of them are connected by bidirectional roads. For each road we know whether it is asphalted or not. The King of Berland Valera II wants to asphalt all roads of Berland, for that he gathered a group of workers. Every day Valera chooses exactly one city and orders the crew to asphalt all roads that come from the city. The valiant crew fulfilled the King's order in a day, then workers went home. Unfortunately, not everything is as great as Valera II would like. The main part of the group were gastarbeiters — illegal immigrants who are enthusiastic but not exactly good at understanding orders in Berlandian. Therefore, having received orders to asphalt the roads coming from some of the city, the group asphalted all non-asphalted roads coming from the city, and vice versa, took the asphalt from the roads that had it. Upon learning of this progress, Valera II was very upset, but since it was too late to change anything, he asked you to make a program that determines whether you can in some way asphalt Berlandian roads in at most n days. Help the king. Input The first line contains two space-separated integers n, m <image> — the number of cities and roads in Berland, correspondingly. Next m lines contain the descriptions of roads in Berland: the i-th line contains three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n; ai ≠ bi; 0 ≤ ci ≤ 1). The first two integers (ai, bi) are indexes of the cities that are connected by the i-th road, the third integer (ci) equals 1, if the road was initially asphalted, and 0 otherwise. Consider the cities in Berland indexed from 1 to n, and the roads indexed from 1 to m. It is guaranteed that between two Berlandian cities there is not more than one road. Output In the first line print a single integer x (0 ≤ x ≤ n) — the number of days needed to asphalt all roads. In the second line print x space-separated integers — the indexes of the cities to send the workers to. Print the cities in the order, in which Valera send the workers to asphalt roads. If there are multiple solutions, print any of them. If there's no way to asphalt all roads, print "Impossible" (without the quotes). Examples Input 4 4 1 2 1 2 4 0 4 3 1 3 2 0 Output 4 3 2 1 3 Input 3 3 1 2 0 2 3 0 3 1 0 Output Impossible ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 405; vector<int> g[MAXN]; vector<int> gr[MAXN]; vector<int> g2[MAXN]; int n, m; inline int neg(int u) { return ((u <= n) ? u + n : u - n); } bool mk[MAXN]; int order[MAXN], posord; void dfs1(int u, vector<int> *g) { if (mk[u]) { return; } mk[u] = true; for (int i = 0; i < (int)(g[u].size()); ++i) { dfs1(g[u][i], g); } order[posord--] = u; } int SCC[MAXN], sccnum; void dfs2(int u, int root) { if (mk[u]) { return; } mk[u] = true; SCC[u] = SCC[root]; for (int i = 0; i < (int)(gr[u].size()); ++i) { dfs2(g[u][i], root); } } int color[MAXN]; int SCCORD[MAXN]; int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> n >> m; for (int i = 0; i < (int)(m); ++i) { int u, v, c; cin >> u >> v >> c; if ((c == 1)) { g[u].push_back(v); g[v].push_back(u); g[neg(u)].push_back(neg(v)); g[neg(v)].push_back(neg(u)); } else { g[u].push_back(neg(v)); g[neg(v)].push_back(u); g[neg(u)].push_back(v); g[v].push_back(neg(u)); } } for (int i = 1; i <= (int)(2 * n); ++i) { int u; u = i; for (int i = 0; i < (int)(g[u].size()); ++i) { int v; v = g[u][i]; gr[v].push_back(u); } } posord = 2 * n; for (int i = 1; i <= (int)(2 * n); ++i) { int u; u = i; if (!mk[u]) { dfs1(u, g); } } fill(mk, mk + 2 * n + 1, false); sccnum = 0; for (int i = 1; i <= (int)(2 * n); ++i) { int u; u = order[i]; if (!mk[u]) { sccnum++; SCC[u] = sccnum; dfs2(u, u); } } for (int u = 1; u <= (int)(n); ++u) { cerr << SCC[u] << ' '; } cerr << '\n'; for (int u = 1; u <= (int)(n); ++u) { cerr << SCC[neg(u)] << ' '; } cerr << '\n'; for (int u = 1; u <= (int)(n); ++u) { if ((SCC[u] == SCC[neg(u)])) { cout << "Impossible\n"; return 0; } } for (int u = 1; u <= (int)(2 * n); ++u) { for (int i = 0; i < (int)(g[u].size()); ++i) { int v; v = g[u][i]; if (!(SCC[u] == SCC[v])) { g2[SCC[u]].push_back(SCC[v]); } } } fill(mk, mk + sccnum + 1, false); posord = sccnum; for (int u = 1; u <= (int)(sccnum); ++u) { if (!mk[u]) { dfs1(u, g2); } } for (int i = 1; i <= (int)(sccnum); ++i) { SCCORD[order[i]] = i; } vector<int> sol; for (int u = 1; u <= (int)(n); ++u) { if (SCCORD[SCC[u]] > SCCORD[SCC[neg(u)]]) { sol.push_back(u); } } cout << sol.size() << '\n'; for (int i = 0; i < (int)(sol.size()); ++i) { if (i > 0) { cout << ' '; } cout << sol[i]; } if (sol.size() > 0) { cout << '\n'; } } ```
### Prompt Your challenge is to write a Cpp solution to the following problem: Vasya has an array a_1, a_2, ..., a_n. You don't know this array, but he told you m facts about this array. The i-th fact is a triple of numbers t_i, l_i and r_i (0 ≤ t_i ≤ 1, 1 ≤ l_i < r_i ≤ n) and it means: * if t_i=1 then subbarray a_{l_i}, a_{l_i + 1}, ..., a_{r_i} is sorted in non-decreasing order; * if t_i=0 then subbarray a_{l_i}, a_{l_i + 1}, ..., a_{r_i} is not sorted in non-decreasing order. A subarray is not sorted if there is at least one pair of consecutive elements in this subarray such that the former is greater than the latter. For example if a = [2, 1, 1, 3, 2] then he could give you three facts: t_1=1, l_1=2, r_1=4 (the subarray [a_2, a_3, a_4] = [1, 1, 3] is sorted), t_2=0, l_2=4, r_2=5 (the subarray [a_4, a_5] = [3, 2] is not sorted), and t_3=0, l_3=3, r_3=5 (the subarray [a_3, a_5] = [1, 3, 2] is not sorted). You don't know the array a. Find any array which satisfies all the given facts. Input The first line contains two integers n and m (2 ≤ n ≤ 1000, 1 ≤ m ≤ 1000). Each of the next m lines contains three integers t_i, l_i and r_i (0 ≤ t_i ≤ 1, 1 ≤ l_i < r_i ≤ n). If t_i = 1 then subbarray a_{l_i}, a_{l_i + 1}, ... , a_{r_i} is sorted. Otherwise (if t_i = 0) subbarray a_{l_i}, a_{l_i + 1}, ... , a_{r_i} is not sorted. Output If there is no array that satisfies these facts in only line print NO (in any letter case). If there is a solution, print YES (in any letter case). In second line print n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the array a, satisfying all the given facts. If there are multiple satisfying arrays you can print any of them. Examples Input 7 4 1 1 3 1 2 5 0 5 6 1 6 7 Output YES 1 2 2 3 5 4 4 Input 4 2 1 1 4 0 2 3 Output NO ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0), cout.tie(0); int n, m; vector<int> t, l, r, comp; int i, j; int num = 10000; bool flag; cin >> n >> m; t.resize(m + 1); l.resize(m + 1); r.resize(m + 1); comp.resize(n + 1, 0); for (i = 0; i < m; i++) { cin >> t[i] >> l[i] >> r[i]; } for (i = 0; i < m; i++) { if (t[i]) { for (j = l[i]; j < r[i]; j++) { comp[j] = 1; } } } for (i = 0; i < m; i++) { if (!t[i]) { flag = false; for (j = l[i]; j < r[i]; j++) { if (!comp[j]) { flag = true; } } if (!flag) { cout << "NO\n"; return 0; } } } cout << "YES\n"; for (i = 1; i <= n; i++) { cout << num << " "; if (comp[i]) { num++; } else { num--; } } cout << endl; return 0; } ```
### Prompt Please provide a cpp coded solution to the problem described below: Innovation technologies are on a victorious march around the planet. They integrate into all spheres of human activity! A restaurant called "Dijkstra's Place" has started thinking about optimizing the booking system. There are n booking requests received by now. Each request is characterized by two numbers: ci and pi — the size of the group of visitors who will come via this request and the total sum of money they will spend in the restaurant, correspondingly. We know that for each request, all ci people want to sit at the same table and are going to spend the whole evening in the restaurant, from the opening moment at 18:00 to the closing moment. Unfortunately, there only are k tables in the restaurant. For each table, we know ri — the maximum number of people who can sit at it. A table can have only people from the same group sitting at it. If you cannot find a large enough table for the whole group, then all visitors leave and naturally, pay nothing. Your task is: given the tables and the requests, decide which requests to accept and which requests to decline so that the money paid by the happy and full visitors was maximum. Input The first line of the input contains integer n (1 ≤ n ≤ 1000) — the number of requests from visitors. Then n lines follow. Each line contains two integers: ci, pi (1 ≤ ci, pi ≤ 1000) — the size of the group of visitors who will come by the i-th request and the total sum of money they will pay when they visit the restaurant, correspondingly. The next line contains integer k (1 ≤ k ≤ 1000) — the number of tables in the restaurant. The last line contains k space-separated integers: r1, r2, ..., rk (1 ≤ ri ≤ 1000) — the maximum number of people that can sit at each table. Output In the first line print two integers: m, s — the number of accepted requests and the total money you get from these requests, correspondingly. Then print m lines — each line must contain two space-separated integers: the number of the accepted request and the number of the table to seat people who come via this request. The requests and the tables are consecutively numbered starting from 1 in the order in which they are given in the input. If there are multiple optimal answers, print any of them. Examples Input 3 10 50 2 100 5 30 3 4 6 9 Output 2 130 2 1 3 2 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long int N = 1e6 + 9; const long long int mod = 1e9 + 7; long long int powerk(long long int x, long long int y); vector<pair<pair<long long int, long long int>, long long int>> v; vector<pair<long long int, long long int>> ans; set<pair<long long int, long long int>> st; long long int a[N]; bool cmp(pair<pair<long long int, long long int>, long long int> a, pair<pair<long long int, long long int>, long long int> b) { if (a.first.first > b.first.first) return 1; else return 0; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long int n; cin >> n; for (int i = 1; i <= n; ++i) { long long int l, r; cin >> l >> r; v.push_back({{r, l}, i}); } long long int k; cin >> k; for (int i = 1; i <= k; ++i) { long long int l; cin >> l; st.insert({l, i}); } long long int cnt = 0, sum = 0; sort(v.begin(), v.end(), cmp); for (auto it : v) { auto itt = st.lower_bound({it.first.second, 0}); if (itt != st.end()) { cnt++; sum += it.first.first; auto iit = *itt; ans.push_back({it.second, iit.second}); st.erase(iit); } } sort(ans.begin(), ans.end()); cout << cnt << " " << sum << '\n'; for (auto it : ans) { cout << it.first << " " << it.second << '\n'; } } long long int powerk(long long int x, long long int y) { if (y == 0) return 1; if (y == 1) return x % mod; if (y & 1) return ((powerk((x * x) % mod, y / 2) % mod) * x) % mod; else return powerk((x * x) % mod, y / 2) % mod; } ```
### Prompt Construct a cpp code solution to the problem outlined: Phoenix is picking berries in his backyard. There are n shrubs, and each shrub has a_i red berries and b_i blue berries. Each basket can contain k berries. But, Phoenix has decided that each basket may only contain berries from the same shrub or berries of the same color (red or blue). In other words, all berries in a basket must be from the same shrub or/and have the same color. For example, if there are two shrubs with 5 red and 2 blue berries in the first shrub and 2 red and 1 blue berries in the second shrub then Phoenix can fill 2 baskets of capacity 4 completely: * the first basket will contain 3 red and 1 blue berries from the first shrub; * the second basket will contain the 2 remaining red berries from the first shrub and 2 red berries from the second shrub. Help Phoenix determine the maximum number of baskets he can fill completely! Input The first line contains two integers n and k ( 1≤ n, k ≤ 500) — the number of shrubs and the basket capacity, respectively. The i-th of the next n lines contain two integers a_i and b_i (0 ≤ a_i, b_i ≤ 10^9) — the number of red and blue berries in the i-th shrub, respectively. Output Output one integer — the maximum number of baskets that Phoenix can fill completely. Examples Input 2 4 5 2 2 1 Output 2 Input 1 5 2 3 Output 1 Input 2 5 2 1 1 3 Output 0 Input 1 2 1000000000 1 Output 500000000 Note The first example is described above. In the second example, Phoenix can fill one basket fully using all the berries from the first (and only) shrub. In the third example, Phoenix cannot fill any basket completely because there are less than 5 berries in each shrub, less than 5 total red berries, and less than 5 total blue berries. In the fourth example, Phoenix can put all the red berries into baskets, leaving an extra blue berry behind. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long N, K, A[503], B[503], suma, sumb, numa, numb; int main() { cin >> N >> K; for (int i = 1; i <= N; ++i) { cin >> A[i] >> B[i]; numa += (suma + A[i]) / K + (sumb + B[i]) / K; suma = (suma + A[i]) % K; sumb = (sumb + B[i]) % K; } if (suma + sumb >= K) { static int dp[503][503]; dp[0][suma] = 1; for (int j = 1; j <= N; ++j) { memcpy(dp[j], dp[j - 1], sizeof(dp[j])); for (int k = 0; k <= K; ++k) if (dp[j - 1][k]) for (int l = 1; l <= A[j] && l < K; ++l) if (K - l <= B[j]) dp[j][(k - l + K) % K] = 1; } for (int j = 0; j <= suma + sumb - K; ++j) if (dp[N][j]) { ++numa; break; } } cout << numa; return 0; } ```
### Prompt Develop a solution in Cpp to the problem described below: One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately. There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter. Input The first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city. Output Output n + 1 numbers — indexes of cities in one of the two possible routes of the letter. Examples Input 2 1 100 100 2 Output 2 100 1 Input 3 3 1 100 2 3 2 Output 100 2 3 1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 1e5 + 10; int main() { int n; while (scanf("%d", &n) != EOF) { map<int, int> ma; map<int, int> mb; set<int> s; set<int>::iterator ps; int a, b; for (int i = 0; i < n; i++) { scanf("%d%d", &a, &b); s.insert(a); s.insert(b); if (ma[a]) mb[a] = b; else ma[a] = b; if (ma[b]) mb[b] = a; else ma[b] = a; } int sta; for (ps = s.begin(); ps != s.end(); ps++) { if (mb[*ps] == 0) { sta = *ps; break; } } printf("%d ", sta); int pre = sta; int next = ma[sta]; if (next == 0) { printf("\n"); continue; } while (1) { printf("%d ", next); if (ma[next] == pre) { pre = next; next = mb[next]; if (next == 0) break; } else { pre = next; next = ma[next]; if (next == 0) break; } } printf("\n"); } return 0; } ```
### Prompt Please formulate a cpp solution to the following problem: There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), the height of Stone i is h_i. There is a frog who is initially on Stone 1. He will repeat the following action some number of times to reach Stone N: * If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on. Find the minimum possible total cost incurred before the frog reaches Stone N. Constraints * All values in input are integers. * 2 \leq N \leq 10^5 * 1 \leq K \leq 100 * 1 \leq h_i \leq 10^4 Input Input is given from Standard Input in the following format: N K h_1 h_2 \ldots h_N Output Print the minimum possible total cost incurred. Examples Input 5 3 10 30 40 50 20 Output 30 Input 3 1 10 20 10 Output 20 Input 2 100 10 10 Output 0 Input 10 4 40 10 20 70 80 10 20 70 80 60 Output 40 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main(){ long long N,K,dp[100001],h[100001]; fill(dp,dp+100001,1e9); dp[0]=0; cin>>N>>K; for(int i=0;i<N;i++)cin>>h[i]; for(int i=0;i<N;i++)for(int k=1;k<=K;k++)if(i+k<N)dp[i+k]=min(abs(h[i+k]-h[i])+dp[i],dp[i+k]); cout<<dp[N-1]<<endl; } ```
### Prompt Your task is to create a cpp solution to the following problem: Vladimir wants to modernize partitions in his office. To make the office more comfortable he decided to remove a partition and plant several bamboos in a row. He thinks it would be nice if there are n bamboos in a row, and the i-th from the left is ai meters high. Vladimir has just planted n bamboos in a row, each of which has height 0 meters right now, but they grow 1 meter each day. In order to make the partition nice Vladimir can cut each bamboo once at any height (no greater that the height of the bamboo), and then the bamboo will stop growing. Vladimir wants to check the bamboos each d days (i.e. d days after he planted, then after 2d days and so on), and cut the bamboos that reached the required height. Vladimir wants the total length of bamboo parts he will cut off to be no greater than k meters. What is the maximum value d he can choose so that he can achieve what he wants without cutting off more than k meters of bamboo? Input The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 1011) — the number of bamboos and the maximum total length of cut parts, in meters. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the required heights of bamboos, in meters. Output Print a single integer — the maximum value of d such that Vladimir can reach his goal. Examples Input 3 4 1 3 5 Output 3 Input 3 40 10 30 50 Output 32 Note In the first example Vladimir can check bamboos each 3 days. Then he will cut the first and the second bamboos after 3 days, and the third bamboo after 6 days. The total length of cut parts is 2 + 0 + 1 = 3 meters. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long n, k, ans, sum, a[101]; void check(long long t) { long long ret = 0; for (int i = 1; i <= n; ++i) { if (a[i] % t) ret += (a[i] / t + 1) * t - a[i]; } if (ret <= k) ans = max(ans, t); } int main() { scanf("%lld%lld", &n, &k), sum += k; for (int i = 1; i <= n; ++i) { scanf("%lld", &a[i]), sum += a[i]; } long long p = (long long)sqrt(sum); for (long long i = 1; i <= p; ++i) { if (sum / i > ans) check(sum / i); if (i > ans) check(i); } printf("%lld\n", ans); return 0; } ```
### Prompt Please create a solution in Cpp to the following problem: Alice and Bob are decorating a Christmas Tree. Alice wants only 3 types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have y yellow ornaments, b blue ornaments and r red ornaments. In Bob's opinion, a Christmas Tree will be beautiful if: * the number of blue ornaments used is greater by exactly 1 than the number of yellow ornaments, and * the number of red ornaments used is greater by exactly 1 than the number of blue ornaments. That is, if they have 8 yellow ornaments, 13 blue ornaments and 9 red ornaments, we can choose 4 yellow, 5 blue and 6 red ornaments (5=4+1 and 6=5+1). Alice wants to choose as many ornaments as possible, but she also wants the Christmas Tree to be beautiful according to Bob's opinion. In the example two paragraphs above, we would choose 7 yellow, 8 blue and 9 red ornaments. If we do it, we will use 7+8+9=24 ornaments. That is the maximum number. Since Alice and Bob are busy with preparing food to the New Year's Eve, they are asking you to find out the maximum number of ornaments that can be used in their beautiful Christmas Tree! It is guaranteed that it is possible to choose at least 6 (1+2+3=6) ornaments. Input The only line contains three integers y, b, r (1 ≤ y ≤ 100, 2 ≤ b ≤ 100, 3 ≤ r ≤ 100) — the number of yellow, blue and red ornaments. It is guaranteed that it is possible to choose at least 6 (1+2+3=6) ornaments. Output Print one number — the maximum number of ornaments that can be used. Examples Input 8 13 9 Output 24 Input 13 3 6 Output 9 Note In the first example, the answer is 7+8+9=24. In the second example, the answer is 2+3+4=9. ### Response ```cpp #include <bits/stdc++.h> #pragma GCC optimize("Ofast,unroll-loops") using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); ; int a, b, c; cin >> a >> b >> c; for (int(i) = (100); (i) >= (1); --(i)) { if (a >= i && b >= i + 1 && c >= i + 2) { cout << 3 * i + 3 << endl; return 0; } } return 0; } ```
### Prompt Please provide a CPP coded solution to the problem described below: Ichiro likes baseball and has decided to write a program which simulates baseball. The program reads events in an inning and prints score in that inning. There are only three events as follows: Single hit * put a runner on the first base. * the runner in the first base advances to the second base and the runner in the second base advances to the third base. * the runner in the third base advances to the home base (and go out of base) and a point is added to the score. Home run * all the runners on base advance to the home base. * points are added to the score by an amount equal to the number of the runners plus one. Out * The number of outs is increased by 1. * The runners and the score remain stationary. * The inning ends with three-out. Ichiro decided to represent these events using "HIT", "HOMERUN" and "OUT", respectively. Write a program which reads events in an inning and prints score in that inning. You can assume that the number of events is less than or equal to 100. Input The input consists of several datasets. In the first line, the number of datasets n is given. Each dataset consists of a list of events (strings) in an inning. Output For each dataset, prints the score in the corresponding inning. Example Input 2 HIT OUT HOMERUN HIT HIT HOMERUN HIT OUT HIT HIT HIT HIT OUT HIT HIT OUT HIT OUT OUT Output 7 0 ### Response ```cpp #include<iostream> #include<string> using namespace std; int main(void){ int n; cin >> n; while(n-->0){ int hits = 0; int inningScore = 0; int outNum = 0; while( outNum < 3 ){ string s; cin >> s; if( s.compare("HIT") == 0 ){ hits++; if( hits == 4 ){ inningScore++; hits = 3; } }else if( s.compare("HOMERUN") == 0 ){ inningScore += hits + 1; hits = 0; }else if( s.compare("OUT") == 0 ){ outNum++; /* inning end */ if( outNum == 3 ) break; } } cout << inningScore << '\n'; } return 0; } ```
### Prompt In cpp, your task is to solve the following problem: Example Input 2 1 2 Output 2 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main(){ int k,n,p,i,j,s,m=-1; cin>>n; int a[n]; for(i=0;i<n;i++)cin>>a[i]; for(i=0;i<n-1;i++){ for(j=i+1;j<n;j++){ s=a[i]*a[j]; k=s%10+1; while(s){ p=s%10; if(p!=k-1)goto L; s/=10; k=p; } m=max(m,a[i]*a[j]);L:; } } cout<<m<<endl; } ```
### Prompt Please provide a cpp coded solution to the problem described below: Write a program of the Insertion Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode: for i = 1 to A.length-1 key = A[i] /* insert A[i] into the sorted sequence A[0,...,j-1] */ j = i - 1 while j >= 0 and A[j] > key A[j+1] = A[j] j-- A[j+1] = key Note that, indices for array elements are based on 0-origin. To illustrate the algorithms, your program should trace intermediate result for each step. Hint Template in C Constraints 1 ≤ N ≤ 100 Input The first line of the input includes an integer N, the number of elements in the sequence. In the second line, N elements of the sequence are given separated by a single space. Output The output consists of N lines. Please output the intermediate sequence in a line for each step. Elements of the sequence should be separated by single space. Examples Input 6 5 2 4 6 1 3 Output 5 2 4 6 1 3 2 5 4 6 1 3 2 4 5 6 1 3 2 4 5 6 1 3 1 2 4 5 6 3 1 2 3 4 5 6 Input 3 1 2 3 Output 1 2 3 1 2 3 1 2 3 ### Response ```cpp #include<bits/stdc++.h> using namespace std; int n,a[105]; void pr() { int i; for(i=1;i<=n;i++) { if(i>1)printf(" "); printf("%d",a[i]); } printf("\n"); } void sor() { int i,j,k; for(i=2;i<=n;i++) { k=a[i]; j=i-1; while(j>=1&&a[j]>k) { a[j+1]=a[j]; j--; } a[j+1]=k; pr(); } } int main() { int i; scanf("%d",&n); for(i=1;i<=n;i++) scanf("%d",&a[i]); pr(); sor(); return 0; } ```
### Prompt Your challenge is to write a Cpp solution to the following problem: Write a program which reads a sequence A of n elements and an integer M, and outputs "yes" if you can make M by adding elements in A, otherwise "no". You can use an element only once. You are given the sequence A and q questions where each question contains Mi. Notes You can solve this problem by a Burte Force approach. Suppose solve(p, t) is a function which checkes whether you can make t by selecting elements after p-th element (inclusive). Then you can recursively call the following functions: solve(0, M) solve(1, M-{sum created from elements before 1st element}) solve(2, M-{sum created from elements before 2nd element}) ... The recursive function has two choices: you selected p-th element and not. So, you can check solve(p+1, t-A[p]) and solve(p+1, t) in solve(p, t) to check the all combinations. For example, the following figure shows that 8 can be made by A[0] + A[2]. <image> Constraints * n ≤ 20 * q ≤ 200 * 1 ≤ elements in A ≤ 2000 * 1 ≤ Mi ≤ 2000 Input In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers (Mi) are given. Output For each question Mi, print yes or no. Example Input 5 1 5 7 10 21 8 2 4 17 8 22 21 100 35 Output no no yes yes yes yes no no ### Response ```cpp #include<iostream> using namespace std; int n,a[100]; int slove(int i,int m); int main() { int i,qn,q; cin >> n; for(i=0;i<n;i++){ cin >> a[i]; } cin >> qn; for(i=0;i<qn;i++){ cin >>q; if ( slove(0,q)){ cout << "yes" << endl; }else{ cout << "no" << endl; } } } int slove(int i,int m) { int res; if (m==0) return 1; if (i>=n) return 0; res =slove(i+1,m) || slove(i+1,m-a[i]); return res; } ```
### Prompt In CPP, your task is to solve the following problem: I am a craftsman specialized in interior works. A customer asked me to perform wiring work on a wall whose entire rectangular surface is tightly pasted with pieces of panels. The panels are all of the same size (2 m in width, 1 m in height) and the wall is filled with an x (horizontal) by y (vertical) array of the panels. The customer asked me to stretch a wire from the left top corner of the wall to the right bottom corner whereby the wire is tied up at the crossing points with the panel boundaries (edges and vertexes) as shown in the figure. There are nine tied-up points in the illustrative figure shown below. <image> Fig: The wire is tied up at the edges and vertexes of the panels (X: 4 panels, Y: 6 panels) Write a program to provide the number of points where the wire intersects with the panel boundaries. Assume that the wire and boundary lines have no thickness. Input The input is given in the following format. x y A line of data is given that contains the integer number of panels in the horizontal direction x (1 ≤ x ≤ 1000) and those in the vertical direction y (1 ≤ y ≤ 1000). Output Output the number of points where the wire intersects with the panel boundaries. Examples Input 4 4 Output 5 Input 4 6 Output 9 ### Response ```cpp #include <bits/stdc++.h> #define rep(i,n) for (long long i = 0; i < (n); ++i) const int INF = 2147483647;//int max const long long int MOD = 1000000007; using namespace std; using ll = long long; using P = pair<int,int>; template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; } template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; } ll _gcd(ll x, ll y){ while(1){ if(x%y == 0)return y; else{ ll z = x%y; x = y; y = z; } } } //ミョ(-ω- ?) int main() { ll x,y; cin >> x >> y; cout << x + y - _gcd(x,y)+1 << endl; return 0; } ```
### Prompt Your task is to create a CPP solution to the following problem: A stowaway and a controller play the following game. The train is represented by n wagons which are numbered with positive integers from 1 to n from the head to the tail. The stowaway and the controller are initially in some two different wagons. Every minute the train can be in one of two conditions — moving or idle. Every minute the players move. The controller's move is as follows. The controller has the movement direction — to the train's head or to its tail. During a move the controller moves to the neighbouring wagon correspondingly to its movement direction. If at the end of his move the controller enters the 1-st or the n-th wagon, that he changes the direction of his movement into the other one. In other words, the controller cyclically goes from the train's head to its tail and back again during all the time of a game, shifting during each move by one wagon. Note, that the controller always have exactly one possible move. The stowaway's move depends from the state of the train. If the train is moving, then the stowaway can shift to one of neighbouring wagons or he can stay where he is without moving. If the train is at a station and is idle, then the stowaway leaves the train (i.e. he is now not present in any train wagon) and then, if it is not the terminal train station, he enters the train again into any of n wagons (not necessarily into the one he's just left and not necessarily into the neighbouring one). If the train is idle for several minutes then each such minute the stowaway leaves the train and enters it back. Let's determine the order of the players' moves. If at the given minute the train is moving, then first the stowaway moves and then the controller does. If at this minute the train is idle, then first the stowaway leaves the train, then the controller moves and then the stowaway enters the train. If at some point in time the stowaway and the controller happen to be in one wagon, then the controller wins: he makes the stowaway pay fine. If after a while the stowaway reaches the terminal train station, then the stowaway wins: he simply leaves the station during his move and never returns there again. At any moment of time the players know each other's positions. The players play in the optimal way. Specifically, if the controller wins, then the stowaway plays so as to lose as late as possible. As all the possible moves for the controller are determined uniquely, then he is considered to play optimally always. Determine the winner. Input The first line contains three integers n, m and k. They represent the number of wagons in the train, the stowaway's and the controller's initial positions correspondingly (2 ≤ n ≤ 50, 1 ≤ m, k ≤ n, m ≠ k). The second line contains the direction in which a controller moves. "to head" means that the controller moves to the train's head and "to tail" means that the controller moves to its tail. It is guaranteed that in the direction in which the controller is moving, there is at least one wagon. Wagon 1 is the head, and wagon n is the tail. The third line has the length from 1 to 200 and consists of symbols "0" and "1". The i-th symbol contains information about the train's state at the i-th minute of time. "0" means that in this very minute the train moves and "1" means that the train in this very minute stands idle. The last symbol of the third line is always "1" — that's the terminal train station. Output If the stowaway wins, print "Stowaway" without quotes. Otherwise, print "Controller" again without quotes, then, separated by a space, print the number of a minute, at which the stowaway will be caught. Examples Input 5 3 2 to head 0001001 Output Stowaway Input 3 2 1 to tail 0001 Output Controller 2 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long N = 1e9; const long long NN = 1e18; const int32_t M = 1e9 + 7; const int32_t MM = 998244353; template <typename T, typename T1> T maxn(T &a, T1 b) { if (b > a) a = b; return a; } template <typename T, typename T1> T minn(T &a, T1 b) { if (b < a) a = b; return a; } void solve() { long long int n, k, m; cin >> n >> k >> m; m--; k--; string to, dir; cin >> to >> dir; long long int chng = 0; if (dir == "head") chng = -1; else chng = 1; string second; cin >> second; for (long long int(i) = 0; (i) < ((long long int)second.size()); (i)++) { if (second[i] == '0') { if (m + chng >= n || m + chng < 0) chng *= -1; m += chng; if (m == k) { if (k + chng < n && k + chng >= 0) k += chng; } if (m == k) { cout << "Controller "; cout << i + 1; return; } } else { if (i == (long long int)second.size() - 1) { cout << "Stowaway"; return; } if (m + chng >= n || m + chng < 0) chng *= -1; if (chng > 0) { k = 0; } else { k = n - 1; } m += chng; } } cout << "Stowaway"; } signed main() { std::ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int testcase = 1; while (testcase--) solve(); return 0; } ```
### Prompt Please provide a cpp coded solution to the problem described below: You are given an array a consisting of n integers. In one move, you can choose some index i (1 ≤ i ≤ n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no more than n^2 such operations or say that it is impossible to do that. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (3 ≤ n ≤ 500) — the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 500), where a_i is the i-th element a. It is guaranteed that the sum of n does not exceed 500. Output For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations ans on the first line and ans integers idx_1, idx_2, ..., idx_{ans} (1 ≤ idx_i ≤ n - 2), where idx_i is the index of left border of the segment for the i-th operation. You should print indices in order of performing operations. Example Input 5 5 1 2 3 4 5 5 5 4 3 2 1 8 8 4 5 2 3 6 7 3 7 5 2 1 6 4 7 3 6 1 2 3 3 6 4 Output 0 6 3 1 3 2 2 3 13 2 1 1 6 4 2 4 3 3 4 4 6 6 -1 4 3 3 4 4 ### Response ```cpp #include <bits/stdc++.h> using namespace std; void culc(int& a, int& b, int& c) { swap(b, c), swap(a, b); } void solve() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; vector<int> ans; for (int i = 0; i < n - 2; i++) { auto it = min_element(a.begin() + i, a.end()) - a.begin(); if (i % 2 != it % 2) { if (it < n - 1) { culc(a[it - 1], a[it], a[it + 1]); ans.push_back(it - 1); it++; } else { culc(a[it - 2], a[it - 1], a[it]); culc(a[it - 2], a[it - 1], a[it]); ans.push_back(it - 2); ans.push_back(it - 2); it--; } } while (it != i) { culc(a[it - 2], a[it - 1], a[it]); ans.push_back(it - 2); it -= 2; } } bool flag = true; if (a[n - 1] < a[n - 2]) { flag = false; for (int i = n - 3; i >= 0; i--) { culc(a[i], a[i + 1], a[i + 2]); ans.push_back(i); if (a[i] <= a[i + 1]) { flag = true; break; } } } if (!flag) { cout << -1 << endl; return; } else { cout << ans.size() << endl; for (auto u : ans) cout << u + 1 << " "; cout << endl; } } int main() { int t; cin >> t; while (t--) { solve(); } } ```
### Prompt Create a solution in cpp for the following problem: The Prodiggers are quite a cool band and for this reason, they have been the surprise guest at the ENTER festival for the past 80 years. At the beginning of their careers, they weren’t so successful, so they had to spend time digging channels to earn money; hence the name. Anyway, they like to tour a lot and have surprising amounts of energy to do extremely long tours. However, they hate spending two consecutive days without having a concert, so they would like to avoid it. A tour is defined by a sequence of concerts and days-off. You need to count in how many ways The Prodiggers can select k different tours of the same length between l and r. For example if k = 2, l = 1 and r = 2, if we define concert day as {1} and day-off as {0}, here are all possible tours: {0}, {1}, {00}, {01}, {10}, {11}. But tour 00 can not be selected because it has 2 days-off in a row. Now, we need to count in how many ways we can select k = 2 tours of the same length in range [1;2]. Here they are: {0,1}; {01,10}; {01,11}; {10,11}. Since their schedule is quite busy, they want you to tell them in how many ways can do that, modulo 1 000 000 007 (109 + 7). Input The first line of the input contains three integers k, l and r (1 ≤ k ≤ 200, 1 ≤ l ≤ r ≤ 1018). Output Output a single number: the number of ways to select k different tours of the same length, modulo 1 000 000 007. Example Input 1 1 2 Output 5 ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <class T> inline void in(T &x) { x = 0; char c = getchar(); bool f = 0; while (!isdigit(c)) f |= (c == '-'), c = getchar(); while (isdigit(c)) x = x * 10 + (c ^ '0'), c = getchar(); f ? x = -x : 0; } template <class T> inline void out(T x, const char c = '\n') { static short st[30]; short m = 0; if (x < 0) putchar('-'), x = -x; do st[++m] = x % 10, x /= 10; while (x); while (m) putchar(st[m--] | '0'); putchar(c); } template <class T, class... Args> inline void in(T &x, Args &...args) { in(x); in(args...); } template <class T, class... Args> inline void out(const T &x, const Args &...args) { out(x, ' '); out(args...); } template <class T> inline void prt(T a[], int n) { for (register int i = 0; i < n; ++i) out(a[i], i == n - 1 ? '\n' : ' '); } template <class T> inline void clr(T a[], int n) { memset(a, 0, sizeof(T) * n); } template <class T> inline void clr(T *a, T *b) { memset(a, 0, sizeof(T) * (b - a)); } template <class T> inline bool ckmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; } template <class T> inline bool ckmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; } namespace MOD_CALC { const int md = 1e9 + 7, inv2 = (md + 1) / 2; inline int add(const int a, const int b) { return a + b >= md ? a + b - md : a + b; } inline int sub(const int a, const int b) { return a - b < 0 ? a - b + md : a - b; } inline int mul(const int a, const int b) { return (long long)a * b % md; } inline void inc(int &a, const int b) { (a += b) >= md ? a -= md : 0; } inline void dec(int &a, const int b) { (a -= b) < 0 ? a += md : 0; } inline int qpow(int a, int b) { int r = 1; for (; b; b >>= 1, a = mul(a, a)) if (b & 1) r = mul(r, a); return r; } inline int qpow(int a, int b, const int p) { int r = 1; for (; b; b >>= 1, a = (long long)a * a % p) if (b & 1) r = (long long)r * a % p; return r; } inline int mdinv(const int a) { return qpow(a, md - 2); } template <class... Args> inline int add(const int a, const int b, const Args &...args) { return add(add(a, b), args...); } template <class... Args> inline int mul(const int a, const int b, const Args &...args) { return mul(mul(a, b), args...); } } // namespace MOD_CALC using namespace MOD_CALC; namespace i207M { int c = 5; struct cpx { int x, y; cpx(const int _x, const int _y) { x = _x, y = _y; } cpx() {} inline friend cpx operator+(const cpx &a, const cpx &b) { return cpx(add(a.x, b.x), add(a.y, b.y)); } inline friend cpx operator-(const cpx &a, const cpx &b) { return cpx(sub(a.x, b.x), sub(a.y, b.y)); } inline friend cpx operator*(const cpx &a, const cpx &b) { return cpx(add(mul(a.x, b.x), mul(c, a.y, b.y)), add(mul(a.x, b.y), mul(a.y, b.x))); } inline cpx operator*(const int v) const { return cpx(mul(x, v), mul(y, v)); } inline cpx operator~() const { int t = mdinv(sub(mul(x, x), mul(c, y, y))); return cpx(mul(x, t), mul(md - y, t)); } inline friend cpx operator/(const cpx &a, const cpx &b) { return a * (~b); } }; inline cpx qpow(cpx a, long long b) { cpx r(1, 0); for (; b; b >>= 1, a = a * a) if (b & 1) r = r * a; return r; } int bi[505][505], s[505][505], ifac[505]; int solve(cpx A, cpx B, cpx C, cpx D, int K, long long n) { int ans = 0; cpx XX(1, 0), YY(1, 0); for (register int i = 0; i <= K; ++i, XX = XX * B, YY = YY * D) { int sum = 0; cpx X = XX, Y = YY; for (register int j = 0; j <= i; ++j, X = X * A / B, Y = Y * C / D) { cpx t = (qpow(X, n + 1) - cpx(1, 0)) / (X - cpx(1, 0)) * Y; if (X.x == 1 && X.y == 0) t = Y * ((n + 1) % md); inc(sum, mul(bi[i][j], t.x)); } sum = mul(s[K][i], sum); if ((K - i) & 1) dec(ans, sum); else inc(ans, sum); } ans = mul(ans, ifac[K]); return ans; } void prework() { bi[0][0] = s[0][0] = 1; for (register int i = 1; i <= 501; ++i) { bi[i][0] = 1; for (register int j = 1; j <= i; ++j) { bi[i][j] = add(bi[i - 1][j - 1], bi[i - 1][j]); s[i][j] = add(s[i - 1][j - 1], mul(s[i - 1][j], i - 1)); } } ifac[0] = 1; for (register int i = 1; i <= 501; ++i) ifac[i] = mul(ifac[i - 1], mdinv(i)); } const int inv10 = mdinv(10); cpx A(inv2, inv2), B(inv2, md - inv2), C(inv2, inv10), D(inv2, md - inv10); signed main() { long long l, r; int k, ans; prework(); in(k, l, r); ans = solve(A, B, C, D, k, r + 1); dec(ans, solve(A, B, C, D, k, l)); out(ans); return 0; } } // namespace i207M signed main() { i207M::main(); return 0; } ```
### Prompt Create a solution in CPP for the following problem: I came to the summer festival with the elementary school students in my neighborhood. To put it bluntly, it plays the role of a guardian, but the smell of yakisoba and takoyaki in the store, and the sound of fireworks that can be heard from time to time, are still exciting even at this age. But today I have to keep an eye on the curious children so they don't get lost. The children seemed to be interested in opening a store. When I looked into it, I was supposed to play a game using dice with the uncle who opened the store, and if I win, I would get a prize. The game is a simple one called High & Low. Participants and uncles roll one dice each, but before that, participants predict whether their rolls will be greater or lesser than their uncle's rolls. If the prediction is correct, it is a victory, and if the same result is rolled, both roll the dice again. The tricky part of this game is that the dice of the participants and the dice of the uncle may be different. Participants can see the development of both dice in advance, so they can expect it as a hint. In other words, it's a simple probability calculation. However, the probability is in the range of high school mathematics, and it may be a little heavy for elementary school students. Even the most clever of the kids are thinking, shaking their braided hair. I'll be asking for help soon. By the way, let's show you something that seems to be an adult once in a while. Input The input consists of multiple cases. In each case, a development of the dice is given in a 21x57 grid. The first 21x28 ((0,0) is the upper left, (20,27) is the lower right) grid represents the participants' dice. The last 21x28 ((0,29) is the upper left, (20,56) is the lower right) represents the uncle's dice. Each side of the participant's dice is 7x7 with (0,7), (7,0), (7,7), (7,14), (7,21), (14,7) as the upper left. Given in the subgrid of. The numbers written on the development drawing are the original numbers. Flip horizontal Flip left and right, then rotate 90 degrees counterclockwise Flip horizontal Flip left and right, then rotate 270 degrees counterclockwise Flip horizontal Flip upside down, then flip left and right It was made to do. Each side of the uncle's dice is 7x7 with (0,36), (7,29), (7,36), (7,43), (7,50), (14,36) as the upper left. Given in the subgrid. The numbers on the uncle's dice development are drawn according to the same rules as the participants' dice. One of 1 to 9 is written on each side of the dice. The numbers are given in a 7x7 grid like this: ..... # ... |. # ..... # ... |. # ..-.. # ..-.. # ... |. # ..-.. # . | ... # ..-.. # ..-.. # ... |. # ..-.. # ... |. # ..-.. # ..... # . |. |. # ..-.. # ... |. # ..... # ..-.. # . | ... # ..-.. # ... |. # ..-.. # ..-.. # . | ... # ..-.. # . |. |. # ..-.. # ..-.. # ... |. # ..... # ... |. # ..... # ..-.. # . |. |. # ..-.. # . |. |. # ..-.. # ..-.. # . |. |. # ..-.. # ... |. # ..-.. # However, when the above numbers are rotated 90 degrees or 270 degrees, the "|" and "-" are interchanged. The end of the input is given by a single 0 line The dice given as input are always correct. Also, dice that cannot be settled are not given. Output Output the one with the higher probability in one line when it becomes "HIGH" and when it becomes "LOW". If both probabilities are the same, output "HIGH". Examples Input .......#######......................#######.............. .......#.....#......................#..-..#.............. .......#.|...#......................#.|.|.#.............. .......#.....#......................#..-..#.............. .......#.|...#......................#.|...#.............. .......#..-..#......................#..-..#.............. .......#######......................#######.............. ############################.############################ #.....##..-..##.....##..-..#.#.....##..-..##.....##..-..# #.-.-.##...|.##.-.-.##.|.|.#.#.....##.|.|.##.-.-.##.|.|.# #|.|.|##..-..##|.|.|##..-..#.#....|##..-..##|.|.|##..-..# #...-.##.|...##...-.##.|.|.#.#.-.-.##.|...##...-.##.|...# #.....##..-..##.....##..-..#.#.....##..-..##.....##..-..# ############################.############################ .......#######......................#######.............. .......#..-..#......................#..-..#.............. .......#.|...#......................#.|...#.............. .......#..-..#......................#..-..#.............. .......#.|.|.#......................#...|.#.............. .......#..-..#......................#..-..#.............. .......#######......................#######.............. .......#######......................#######.............. .......#..-..#......................#..-..#.............. .......#.|...#......................#...|.#.............. .......#..-..#......................#..-..#.............. .......#...|.#......................#.|.|.#.............. .......#..-..#......................#..-..#.............. .......#######......................#######.............. ############################.############################ #.....##..-..##.....##..-..#.#.....##..-..##.....##..-..# #.-.-.##...|.##.-.-.##.|.|.#.#...-.##...|.##.-...##.|.|.# #|.|.|##..-..##|.|.|##..-..#.#|.|.|##..-..##|.|.|##..-..# #.-.-.##.|...##...-.##.|...#.#.-...##.|.|.##.-.-.##.|...# #.....##..-..##.....##..-..#.#.....##..-..##.....##..-..# ############################.############################ .......#######......................#######.............. .......#..-..#......................#..-..#.............. .......#...|.#......................#.|...#.............. .......#..-..#......................#..-..#.............. .......#.|...#......................#...|.#.............. .......#..-..#......................#..-..#.............. .......#######......................#######.............. .......#######......................#######.............. .......#..-..#......................#..-..#.............. .......#.|...#......................#.|.|.#.............. .......#..-..#......................#..-..#.............. .......#...|.#......................#.|...#.............. .......#..-..#......................#..-..#.............. .......#######......................#######.............. ############################.############################ #.....##..-..##.....##..-..#.#.....##..-..##.....##.....# #.-.-.##.|.|.##.-.-.##...|.#.#.....##.|.|.##...-.##.|...# #|.|.|##..-..##|....##..-..#.#....|##..-..##|.|.|##.....# #.-.-.##.|.|.##.....##.|.|.#.#.-.-.##.|.|.##.-...##.|...# #.....##..-..##.....##..-..#.#.....##..-..##.....##..-..# ############################.############################ .......#######......................#######.............. .......#..-..#......................#..-..#.............. .......#.|.|.#......................#.|...#.............. .......#..-..#......................#..-..#.............. .......#...|.#......................#...|.#.............. .......#..-..#......................#..-..#.............. .......#######......................#######.............. .......#######......................#######.............. .......#..-..#......................#..-..#.............. .......#.|...#......................#.|.|.#.............. .......#..-..#......................#..-..#.............. .......#...|.#......................#.|...#.............. .......#..-..#......................#..-..#.............. .......#######......................#######.............. ############################.############################ #.....##..-..##.....##..-..#.#.....##..-..##.....##..-..# #.-.-.##...|.##.-.-.##.|.|.#.#.-...##.|.|.##.-...##.|.|.# #|.|.|##..-..##|.|.|##..-..#.#|.|.|##..-..##|.|.|##..-..# #...-.##.|...##.-.-.##.|.|.#.#.-.-.##.|...##.-.-.##.|.|.# #.....##..-..##.....##..-..#.#.....##..-..##.....##..-..# ############################.############################ .......#######......................#######.............. .......#..-..#......................#..-..#.............. .......#...|.#......................#.|.|.#.............. .......#..-..#......................#..-..#.............. .......#.|...#......................#...|.#.............. .......#..-..#......................#..-..#.............. .......#######......................#######.............. 0 Output LOW HIGH HIGH LOW Input .......#######......................#######.............. .......#.....#......................#..-..#.............. .......#.|...#......................#.|.|.#.............. .......#.....#......................#..-..#.............. .......#.|...#......................#.|...#.............. .......#..-..#......................#..-..#.............. .......#######......................#######.............. .############################ .....##..-..##.....##..-..#.#.....##..-..##.....##..-..# .-.-.##...|.##.-.-.##.|.|.#.#.....##.|.|.##.-.-.##.|.|.# |.|.|##..-..##|.|.|##..-..#.#....|##..-..##|.|.|##..-..# ...-.##.|...##...-.##.|.|.#.#.-.-.##.|...##...-.##.|...# .....##..-..##.....##..-..#.#.....##..-..##.....##..-..# .############################ .......#######......................#######.............. .......#..-..#......................#..-..#.............. .......#.|...#......................#.|...#.............. .......#..-..#......................#..-..#.............. .......#.|.|.#......................#...|.#.............. .......#..-..#......................#..-..#.............. .......#######......................#######.............. .......#######......................#######.............. .......#..-..#......................#..-..#.............. .......#.|...#......................#...|.#.............. .......#..-..#......................#..-..#.............. .......#...|.#......................#.|.|.#.............. .......#..-..#......................#..-..#.............. .......#######......................#######.............. .############################ .....##..-..##.....##..-..#.#.....##..-..##.....##..-..# .-.-.##...|.##.-.-.##.|.|.#.#...-.##...|.##.-...##.|.|.# |.|.|##..-..##|.|.|##..-..#.#|.|.|##..-..##|.|.|##..-..# .-.-.##.|...##...-.##.|...#.#.-...##.|.|.##.-.-.##.|...# .....##..-..##.....##..-..#.#.....##..-..##.....##..-..# .############################ .......#######......................#######.............. .......#..-..#......................#..-..#.............. .......#...|.#......................#.|...#.............. .......#..-..#......................#..-..#.............. .......#.|...#......................#...|.#.............. .......#..-..#......................#..-..#.............. .......#######......................#######.............. .......#######......................#######.............. .......#..-..#......................#..-..#.............. .......#.|...#......................#.|.|.#.............. .......#..-..#......................#..-..#.............. .......#...|.#......................#.|...#.............. .......#..-..#......................#..-..#.............. .......#######......................#######.............. .############################ .....##..-..##.....##..-..#.#.....##..-..##.....##.....# .-.-.##.|.|.##.-.-.##...|.#.#.....##.|.|.##...-.##.|...# |.|.|##..-..##|....##..-..#.#....|##..-..##|.|.|##.....# .-.-.##.|.|.##.....##.|.|.#.#.-.-.##.|.|.##.-...##.|...# .....##..-..##.....##..-..#.#.....##..-..##.....##..-..# .############################ .......#######......................#######.............. .......#..-..#......................#..-..#.............. .......#.|.|.#......................#.|...#.............. .......#..-..#......................#..-..#.............. .......#...|.#......................#...|.#.............. .......#..-..#......................#..-..#.............. .......#######......................#######.............. .......#######......................#######.............. .......#..-..#......................#..-..#.............. .......#.|...#......................#.|.|.#.............. .......#..-..#......................#..-..#.............. .......#...|.#......................#.|...#.............. .......#..-..#......................#..-..#.............. .......#######......................#######.............. .############################ .....##..-..##.....##..-..#.#.....##..-..##.....##..-..# .-.-.##...|.##.-.-.##.|.|.#.#.-...##.|.|.##.-...##.|.|.# |.|.|##..-..##|.|.|##..-..#.#|.|.|##..-..##|.|.|##..-..# ...-.##.|...##.-.-.##.|.|.#.#.-.-.##.|...##.-.-.##.|.|.# .....##..-..##.....##..-..#.#.....##..-..##.....##..-..# .############################ .......#######......................#######.............. .......#..-..#......................#..-..#.............. .......#...|.#......................#.|.|.#.............. .......#..-..#......................#..-..#.............. .......#.|...#......................#...|.#.............. .......#..-..#......................#..-..#.............. .......#######......................#######.............. 0 Output LOW HIGH HIGH LOW ### Response ```cpp #include <iostream> #include <string> #include <algorithm> #include <cstdlib> #include <cassert> using namespace std; int dicea[6],diceb[6]; string str[21]; int mk_num(string *); void lr_hanten(string a[]){ for(int i=0;i<7;i++) for(int j=0;j<7/2;j++) swap(a[i][j],a[i][6-j]); } void ud_hanten(string a[]){ for(int i=0;i<7;i++) for(int j=0;j<7/2;j++) swap(a[j][i],a[6-j][i]); } void rol_90(string a[]){ string b[7]; for(int i=0;i<7;i++) for(int j=0;j<7;j++) { b[i] += a[j][6-i]; if(b[i][j] == '-') b[i][j] = '|'; else if(b[i][j] =='|') b[i][j] = '-'; } for(int i=0;i<7;i++) a[i] = b[i]; } void choice(string num[],int x,int y){ for(int i=0;i<7;i++){ num[i]=""; for(int j=0;j<7;j++) num[i]+=str[y+i][x+j]; } } void mk_dice(){ string num[2][7]; //ue choice(num[0],7,0),choice(num[1],36,0); lr_hanten(num[0]),lr_hanten(num[1]); dicea[0] = mk_num(num[0]),diceb[0]=mk_num(num[1]); //hidari choice(num[0],0,7),choice(num[1],29,7); lr_hanten(num[0]),lr_hanten(num[1]); rol_90(num[0]),rol_90(num[1]); dicea[1] = mk_num(num[0]),diceb[1] = mk_num(num[1]); //mid_hidari choice(num[0],7,7),choice(num[1],36,7); lr_hanten(num[0]),lr_hanten(num[1]); dicea[2] = mk_num(num[0]),diceb[2] = mk_num(num[1]); //mid_migi choice(num[0],14,7),choice(num[1],43,7); lr_hanten(num[0]),lr_hanten(num[1]); for(int i=0;i<3;i++)rol_90(num[0]),rol_90(num[1]); dicea[3] = mk_num(num[0]),diceb[3] = mk_num(num[1]); //migi choice(num[0],21,7),choice(num[1],50,7); lr_hanten(num[0]),lr_hanten(num[1]); dicea[4] = mk_num(num[0]),diceb[4] = mk_num(num[1]); //sita choice(num[0],7,14),choice(num[1],36,14); ud_hanten(num[0]),ud_hanten(num[1]); lr_hanten(num[0]),lr_hanten(num[1]); dicea[5] = mk_num(num[0]),diceb[5] = mk_num(num[1]); } int main(){ while(1) { for(int i=0;i<21;i++){ cin >> str[i]; if(str[i]=="0")break; } if(str[0]=="0")break; mk_dice(); int a=0,b=0; for(int i=0;i<6;i++) assert(dicea[i]!=-1 && diceb[i]!=-1); for(int i=0;i<6;i++) for(int j=0;j<6;j++) if(dicea[i] > diceb[j]) a++; else if(dicea[i]<diceb[j])b++; if(a>=b) cout<<"HIGH"<<endl; else cout <<"LOW"<<endl; } } int mk_num(string a[]){ if(a[1]=="#.....#" && a[2]=="#...|.#") return 1; if(a[1]=="#..-..#" && a[2]=="#...|.#" && a[3]=="#..-..#" && a[4]=="#.|...#" && a[5]=="#..-..#") return 2; if(a[1]=="#..-..#" && a[2]=="#...|.#" && a[3]=="#..-..#" && a[4]=="#...|.#" && a[5]=="#..-..#") return 3; if(a[1]=="#.....#" && a[5]=="#.....#") return 4; if(a[1]=="#..-..#" && a[2]=="#.|...#" && a[3]=="#..-..#" && a[4]=="#...|.#" && a[5]=="#..-..#") return 5; if(a[1]=="#..-..#" && a[2]=="#.|...#" && a[3]=="#..-..#" && a[4]=="#.|.|.#" && a[5]=="#..-..#") return 6; if(a[3]=="#.....#" && a[5]=="#.....#") return 7; if(a[1]=="#..-..#" && a[2]=="#.|.|.#" && a[3]=="#..-..#" && a[4]=="#.|.|.#" && a[5]=="#..-..#") return 8; if(a[1]=="#..-..#" && a[2]=="#.|.|.#" && a[3]=="#..-..#" && a[4]=="#...|.#" && a[5]=="#..-..#") return 9; return -1; } ```
### Prompt Generate a cpp solution to the following problem: Emuskald is an avid horticulturist and owns the world's longest greenhouse — it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line. Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left. Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders. Input The first line of input contains two space-separated integers n and m (1 ≤ n, m ≤ 5000, n ≥ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≤ si ≤ m), and one real number xi (0 ≤ xi ≤ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≤ i < n). Output Output a single integer — the minimum number of plants to be replanted. Examples Input 3 2 2 1 1 2.0 1 3.100 Output 1 Input 3 3 1 5.0 2 5.5 3 6.0 Output 0 Input 6 3 1 14.284235 2 17.921382 1 20.328172 3 20.842331 1 25.790145 1 27.204125 Output 2 Note In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1. In the second test case, the species are already in the correct order, so no replanting is needed. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int64_t MOD = 998244353; const int64_t INF = 1e18; const int64_t eps = 1e-18; void io(string s1 = "input.txt", string s2 = "output.txt") { freopen(s1.c_str(), "r", stdin); freopen(s2.c_str(), "w", stdout); } int64_t n, m; multiset<int64_t> st; signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> m; for (int64_t i = 0; i < n; i++) { int64_t x; cin >> x; long double d; cin >> d; st.insert(x); auto it = st.upper_bound(x); if (it != st.end()) st.erase(it); } cout << n - st.size(); } ```
### Prompt Create a solution in Cpp for the following problem: Sagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has 3 lanes getting into the intersection (one for each direction) and 3 lanes getting out of the intersection, so we have 4 parts in total. Each part has 4 lights, one for each lane getting into the intersection (l — left, s — straight, r — right) and a light p for a pedestrian crossing. <image> An accident is possible if a car can hit a pedestrian. This can happen if the light of a pedestrian crossing of some part and the light of a lane that can get to or from that same part are green at the same time. Now, Sagheer is monitoring the configuration of the traffic lights. Your task is to help him detect whether an accident is possible. Input The input consists of four lines with each line describing a road part given in a counter-clockwise order. Each line contains four integers l, s, r, p — for the left, straight, right and pedestrian lights, respectively. The possible values are 0 for red light and 1 for green light. Output On a single line, print "YES" if an accident is possible, and "NO" otherwise. Examples Input 1 0 0 1 0 1 0 0 0 0 1 0 0 0 0 1 Output YES Input 0 1 1 0 1 0 1 0 1 1 0 0 0 0 0 1 Output NO Input 1 0 0 0 0 0 0 1 0 0 0 0 1 0 1 0 Output NO Note In the first example, some accidents are possible because cars of part 1 can hit pedestrians of parts 1 and 4. Also, cars of parts 2 and 3 can hit pedestrians of part 4. In the second example, no car can pass the pedestrian crossing of part 4 which is the only green pedestrian light. So, no accident can occur. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int arr[4][4]; int ans = 0, i, j; for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) cin >> arr[i][j]; for (i = 0; i < 4; i++) { for (j = 0; j < 3; j++) if (arr[i][3] == 1 && arr[i][j] == 1) ans = 1; } if (arr[0][3] == 1 && (arr[1][0] == 1 || arr[2][1] == 1 || arr[3][2] == 1)) ans = 1; if (arr[1][3] == 1 && (arr[0][2] == 1 || arr[2][0] == 1 || arr[3][1] == 1)) ans = 1; if (arr[2][3] == 1 && (arr[0][1] == 1 || arr[1][2] == 1 || arr[3][0] == 1)) ans = 1; if (arr[3][3] == 1 && (arr[0][0] == 1 || arr[1][1] == 1 || arr[2][2] == 1)) ans = 1; if (ans == 1) printf("YES\n"); else cout << "NO" << endl; return 0; } ```
### Prompt Please provide a Cpp coded solution to the problem described below: A tuple of positive integers {x1, x2, ..., xk} is called simple if for all pairs of positive integers (i, j) (1 ≤ i < j ≤ k), xi + xj is a prime. You are given an array a with n positive integers a1, a2, ..., an (not necessary distinct). You want to find a simple subset of the array a with the maximum size. A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. Let's define a subset of the array a as a tuple that can be obtained from a by removing some (possibly all) elements of it. Input The first line contains integer n (1 ≤ n ≤ 1000) — the number of integers in the array a. The second line contains n integers ai (1 ≤ ai ≤ 106) — the elements of the array a. Output On the first line print integer m — the maximum possible size of simple subset of a. On the second line print m integers bl — the elements of the simple subset of the array a with the maximum size. If there is more than one solution you can print any of them. You can print the elements of the subset in any order. Examples Input 2 2 3 Output 2 3 2 Input 2 2 2 Output 1 2 Input 3 2 1 1 Output 3 1 1 2 Input 2 83 14 Output 2 14 83 ### Response ```cpp #include <bits/stdc++.h> using namespace std; bool prime[2000005]; void SieveOfEratosthenes(long long n) { memset(prime, true, sizeof(prime)); for (long long p = 2; p * p <= 2000000; p++) { if (prime[p] == true) { for (long long i = p * p; i <= n; i += p) prime[i] = false; } } return; } int main() { SieveOfEratosthenes(2000000); long long t; t = 1; while (t--) { long long n; cin >> n; long long ar[n]; for (long long i = 0; i < n; i++) cin >> ar[i]; ; long long freq[1000001]; memset(freq, 0, sizeof(freq)); for (long long val : ar) freq[val]++; if (freq[1] < 2) { pair<long long, long long> res; long long flg = 0; for (long long i = 0; i < n; i++) { for (long long j = i + 1; j <= n - 1; j++) { if (prime[ar[i] + ar[j]]) { flg = 1; res = {ar[i], ar[j]}; break; } } if (flg) break; } if (flg) { cout << 2 << "\n"; cout << res.first << " " << res.second << "\n"; } else { for (long long i = 0; i < n; i++) { if (prime[ar[i]]) { cout << "1\n" << ar[i] << "\n"; flg = 1; break; } } if (flg == 0) { cout << "1\n"; cout << ar[0] << "\n"; } } } else { long long vl = -1; for (long long i = 0; i < n; i++) { if (ar[i] != 1 and prime[ar[i] + 1ll]) { vl = ar[i]; break; } } if (vl != -1) { cout << (freq[1] + 1ll) << "\n"; } else cout << freq[1] << "\n"; for (long long i = 0; i < freq[1]; i++) cout << "1 "; if (vl != -1) cout << vl << "\n"; else cout << "\n"; } } return 0; } ```
### Prompt In cpp, your task is to solve the following problem: Formula 1 officials decided to introduce new competition. Cars are replaced by space ships and number of points awarded can differ per race. Given the current ranking in the competition and points distribution for the next race, your task is to calculate the best possible ranking for a given astronaut after the next race. It's guaranteed that given astronaut will have unique number of points before the race. Input The first line contains two integer numbers N (1 ≤ N ≤ 200000) representing number of F1 astronauts, and current position of astronaut D (1 ≤ D ≤ N) you want to calculate best ranking for (no other competitor will have the same number of points before the race). The second line contains N integer numbers S_k (0 ≤ S_k ≤ 10^8, k=1...N), separated by a single space, representing current ranking of astronauts. Points are sorted in non-increasing order. The third line contains N integer numbers P_k (0 ≤ P_k ≤ 10^8, k=1...N), separated by a single space, representing point awards for the next race. Points are sorted in non-increasing order, so winner of the race gets the maximum number of points. Output Output contains one integer number — the best possible ranking for astronaut after the race. If multiple astronauts have the same score after the race, they all share the best ranking. Example Input 4 3 50 30 20 10 15 10 7 3 Output 2 Note If the third ranked astronaut wins the race, he will have 35 points. He cannot take the leading position, but he can overtake the second position if the second ranked astronaut finishes the race at the last position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename T, typename U> std::pair<T, U> operator+(const std::pair<T, U>& l, const std::pair<T, U>& r) { return {l.first + r.first, l.second + r.second}; } typedef void (*callback_function)(void); const long long INF64 = 1e18; const long long INF32 = 1e9; const long long MOD = 1e9 + 7; const long double PI = acos(-1.0L); const long double EPS = static_cast<long double>(1e-9); int main() { ios_base::sync_with_stdio(false); cin.tie(); { long long n, d; cin >> n >> d; d--; pair<long long, long long> a[n]; for (long long i = (0); i < (n); i++) { cin >> a[i].first; a[i].second = i; } long long t; cin >> t; a[d].first += t; long long res = d; for (long long i = (1); i < (n); i++) { if (res == 0) break; cin >> t; if (a[res - 1].first + t > a[d].first) continue; res--; a[res].first += t; } cout << res + 1 << endl; } return 0; } ```
### Prompt Create a solution in cpp for the following problem: There are n rectangles in a row. You can either turn each rectangle by 90 degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangles. Find out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such). Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of rectangles. Each of the next n lines contains two integers w_i and h_i (1 ≤ w_i, h_i ≤ 10^9) — the width and the height of the i-th rectangle. Output Print "YES" (without quotes) if there is a way to make the rectangles go in order of non-ascending height, otherwise print "NO". You can print each letter in any case (upper or lower). Examples Input 3 3 4 4 6 3 5 Output YES Input 2 3 4 5 5 Output NO Note In the first test, you can rotate the second and the third rectangles so that the heights will be [4, 4, 3]. In the second test, there is no way the second rectangle will be not higher than the first one. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 2e5 + 2; vector<pair<int, int>> v; int n; bool solve(int s) { for (int i = (n - 2); i >= 0; i--) { if (s <= v[i].first) { s = v[i].first; } else if (s <= v[i].second) { s = v[i].second; } else return false; } return true; } int main() { scanf("%d", &n); for (int i = 0; i < (int)(n); ++i) { int a, b; scanf("%d%d", &a, &b); v.push_back({min(a, b), max(b, a)}); } if (solve(v[n - 1].first)) { puts("YES"); } else { puts("NO"); } return 0; } ```
### Prompt Please provide a cpp coded solution to the problem described below: Internet search engines, such as Google, automatically sort and categorize web pages around the world to create a huge database. It also parses the search keywords entered by the user and creates an inquiry statement for database search. In each case, complicated processing is performed to realize efficient search, but for the time being, all the basics are cutting out words from sentences. So, please try to cut out the word from the sentence. This time, we will target English sentences with clear word breaks as follows. * Target text: English text of 1024 characters or less, not including line breaks * Delimiter: All are half-width characters, only spaces, periods, and commas. * Words to cut out: Words with 3 to 6 letters (ignore words with 2 or less letters or 7 or more letters) input An English sentence consisting of delimiters and alphanumeric characters is given on one line (all half-width characters). output Please output the words separated by one space character (half-width) on one line. Examples Input Rain, rain, go to Spain. Output Rain rain Spain Input Win today's preliminary contest and be qualified to visit University of Aizu. Output Win and visit Aizu ### Response ```cpp #include <iostream> #include <cstring> using namespace std; int main(){ char c[2000]; int t = 0; while(cin >> c){ int idx = 0; if(c[strlen(c)-1] == ',' || c[strlen(c)-1] == '.') c[strlen(c)-1] = 0; int l = strlen(c); if(3 <= l && l <= 6){ if(t) cout << " "; cout << c; ++t; } } cout << endl; } ```
### Prompt Construct a CPP code solution to the problem outlined: Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are n people who plan to move to the cities. The wealth of the i of them is equal to ai. Authorities plan to build two cities, first for n1 people and second for n2 people. Of course, each of n candidates can settle in only one of the cities. Thus, first some subset of candidates of size n1 settle in the first city and then some subset of size n2 is chosen among the remaining candidates and the move to the second city. All other candidates receive an official refuse and go back home. To make the statistic of local region look better in the eyes of their bosses, local authorities decided to pick subsets of candidates in such a way that the sum of arithmetic mean of wealth of people in each of the cities is as large as possible. Arithmetic mean of wealth in one city is the sum of wealth ai among all its residents divided by the number of them (n1 or n2 depending on the city). The division should be done in real numbers without any rounding. Please, help authorities find the optimal way to pick residents for two cities. Input The first line of the input contains three integers n, n1 and n2 (1 ≤ n, n1, n2 ≤ 100 000, n1 + n2 ≤ n) — the number of candidates who want to move to the cities, the planned number of residents of the first city and the planned number of residents of the second city. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000), the i-th of them is equal to the wealth of the i-th candidate. Output Print one real value — the maximum possible sum of arithmetic means of wealth of cities' residents. You answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 2 1 1 1 5 Output 6.00000000 Input 4 2 1 1 4 2 3 Output 6.50000000 Note In the first sample, one of the optimal solutions is to move candidate 1 to the first city and candidate 2 to the second. In the second sample, the optimal solution is to pick candidates 3 and 4 for the first city, and candidate 2 for the second one. Thus we obtain (a3 + a4) / 2 + a2 = (3 + 2) / 2 + 4 = 6.5 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; const double PI = acos(-1.0); const int maxn = 1e5 + 5; template <class T> inline bool Read(T &ret) { char c; int sgn; if (c = getchar(), c == EOF) return 0; while (c != '-' && (c < '0' || c > '9')) c = getchar(); sgn = (c == '-') ? -1 : 1; ret = (c == '-') ? 0 : (c - '0'); while (c = getchar(), c >= '0' && c <= '9') ret = ret * 10 + (c - '0'); ret *= sgn; return 1; } void Out(int a) { if (a < 0) { putchar('-'); a = -a; } if (a >= 10) Out(a / 10); putchar(a % 10 + '0'); } double num[110000]; int main() { int a, b, c; scanf("%d%d%d", &(a), &(b), &(c)); for (int(i) = (0); (i) < (a); ++(i)) { Read(num[i]); } double res = 0; sort(num, num + a, greater<int>()); int b1, c1; c1 = max(b, c); b1 = min(b, c); for (int(i) = (0); (i) < (b1); ++(i)) { res += (num[i] / b1); } for (int(i) = (b1); (i) < (b1 + c1); ++(i)) { res += (num[i] / c1); } printf("%.8f\n", res); } ```
### Prompt Generate a cpp solution to the following problem: You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills). So, about the teams. Firstly, these two teams should have the same size. Two more constraints: * The first team should consist of students with distinct skills (i.e. all skills in the first team are unique). * The second team should consist of students with the same skills (i.e. all skills in the second team are equal). Note that it is permissible that some student of the first team has the same skill as a student of the second team. Consider some examples (skills are given): * [1, 2, 3], [4, 4] is not a good pair of teams because sizes should be the same; * [1, 1, 2], [3, 3, 3] is not a good pair of teams because the first team should not contain students with the same skills; * [1, 2, 3], [3, 4, 4] is not a good pair of teams because the second team should contain students with the same skills; * [1, 2, 3], [3, 3, 3] is a good pair of teams; * [5], [6] is a good pair of teams. Your task is to find the maximum possible size x for which it is possible to compose a valid pair of teams, where each team size is x (skills in the first team needed to be unique, skills in the second team should be the same between them). A student cannot be part of more than one team. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of students. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n), where a_i is the skill of the i-th student. Different students can have the same skills. It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5). Output For each test case, print the answer — the maximum possible size x for which it is possible to compose a valid pair of teams, where each team size is x. Example Input 4 7 4 2 4 1 4 3 4 5 2 1 5 4 3 1 1 4 1 1 1 3 Output 3 1 0 2 Note In the first test case of the example, it is possible to construct two teams of size 3: the first team is [1, 2, 4] and the second team is [4, 4, 4]. Note, that there are some other ways to construct two valid teams of size 3. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { if (b == 0) return a; return gcd(b, a % b); } void solve() { long long n; cin >> n; vector<long long> v(n + 1, 0); long long d = 0; long long s = 0; for (long long i = 0, _n = (n); i < _n; i++) { long long t; cin >> t; if (v[t] == 0) d++; v[t]++; s = max(s, v[t]); } if (s < d) cout << s << "\n"; else if (d < s) cout << d << "\n"; else cout << d - 1 << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout << setprecision(11); long long t; cin >> t; while (t--) { solve(); } return 0; } ```
### Prompt Your task is to create a cpp solution to the following problem: The University of Aizu has a park covered with grass, and there are no trees or buildings that block the sunlight. On sunny summer days, sprinklers installed in the park operate to sprinkle water on the lawn. The frog Pyonkichi lives in this park. Pyonkichi is not good at hot weather, and on summer days when the sun is strong, he will dry out and die if he is not exposed to the water of the sprinkler. The sprinklers installed in the park are supposed to sprinkle only one sprinkler at a time to save water, so Pyonkichi must move according to the operation of the sprinklers. <image> --- (a) Map of the park <image> | <image> --- | --- (b) Pyonkichi's jump range | (c) Sprinkler watering range The park is as shown in (a) of the above figure, the location in the park is represented by the coordinates 0 to 9 in each of the vertical and horizontal directions, and the black ● is the sprinkler, which indicates the order in which the numbers operate. This is just an example, and the location and order of operation of each sprinkler changes daily. Pyonkichi is clumsy, so he can only jump a certain distance to move. Pyonkichi's jumpable range is as shown in (b) above, and he cannot move to any other location. Moreover, one jump consumes a lot of physical strength, so you have to rest in the water for a while. The range in which the sprinkler can sprinkle water is as shown in the above figure (c), including the coordinates of the sprinkler itself. Each sprinkler will stop after a period of watering, and the next sprinkler will start working immediately. Pyonkichi shall jump only once at this time, and shall not jump until the next watering stops. Also, since the park is surrounded on all sides by scorching asphalt, it is assumed that you will not jump in a direction that would cause you to go out of the park. This summer was extremely hot. Was Pyonkichi able to survive? One day, read the initial position of Pyonkichi, the position of the sprinkler and the operation order, and if there is a movement path that Pyonkichi can survive, "OK", how? If you die even if you do your best, create a program that outputs "NA". However, the maximum number of sprinklers is 10, and Pyonkichi will jump from the initial position at the same time as the first sprinkler is activated. Input Given multiple datasets. Each dataset is given in the following format: px py n x1 y1 x2 y2 ... xn yn The first line gives the abscissa px and ordinate py of the initial position of Pyonkichi. The second line gives the number of sprinklers n. The third line gives the abscissa xi and the ordinate yi of the sprinkler that operates third. The input ends with two zero lines. The number of datasets does not exceed 20. Output For each dataset, print OK if it is alive, or NA on one line otherwise. Example Input 6 1 10 6 4 3 3 1 2 0 5 4 6 1 8 5 9 7 7 8 6 8 3 6 1 10 6 4 3 3 1 2 0 5 4 6 1 8 5 9 7 7 8 6 9 0 0 0 Output OK NA ### Response ```cpp #include<iostream> #include<cstdio> #include<queue> using namespace std; struct Data{ int y, x, dep; Data(){ dep = 0; } }; int main(){ int n, x_sp[10], y_sp[10]; Data s; int nx_phon[13] = { 0, 1, 2, 2, 2, 1, 0, -1, -2, -2, -2, -1 }, ny_phon[13] = { -2, -2, -1, 0, 1, 2, 2, 2, 1, 0, -1, -2 }; int nx_sp[9] = { 0, 0, 1, 1, 1, 0, -1, -1, -1 }, ny_sp[9] = { 0, -1, -1, 0, 1, 1, 1, 0, -1 }; while (cin >> s.x >> s.y, s.x != 0 || s.y != 0){ cin >> n; for (int i = 0; i < n; i++){ cin >> x_sp[i] >> y_sp[i]; } queue<Data> q; q.push(s); Data q_c, q_d; int px_phon, py_phon, px_sp, py_sp, ans = false; bool frst = true; while (!q.empty()){ bool memo[10][10] = {}; q_c = q.front(); q.pop(); for (int i = 0; i < 12; i++){ px_phon = q_c.x + nx_phon[i]; py_phon = q_c.y + ny_phon[i]; if (px_phon < 0 || 9 < px_phon || py_phon < 0 || 9 < py_phon) continue; for (int j = 0; j < 9; j++){ px_sp = x_sp[q_c.dep] + nx_sp[j]; py_sp = y_sp[q_c.dep] + ny_sp[j]; if (px_sp < 0 || 9 < px_sp || py_sp < 0 || 9 < py_sp) continue; //if (memo[px_sp][py_sp])continue; if (px_phon == px_sp && py_phon == py_sp){ //printf("%d",q_c.dep); if (q_c.dep == n - 1){ ans = true; goto END; } memo[px_sp][py_sp] = true; q_d.x = px_sp; q_d.y = py_sp; q_d.dep = q_c.dep + 1; if (q_d.dep == n){ q_d.dep = 0; frst = false; } q.push(q_d); break; } } } } END: if (ans) printf("OK\n"); else printf("NA\n"); } return 0; } ```
### Prompt Please create a solution in CPP to the following problem: Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute — health points, shortened to HP. In general, different values of HP are grouped into 4 categories: * Category A if HP is in the form of (4 n + 1), that is, when divided by 4, the remainder is 1; * Category B if HP is in the form of (4 n + 3), that is, when divided by 4, the remainder is 3; * Category C if HP is in the form of (4 n + 2), that is, when divided by 4, the remainder is 2; * Category D if HP is in the form of 4 n, that is, when divided by 4, the remainder is 0. The above-mentioned n can be any integer. These 4 categories ordered from highest to lowest as A > B > C > D, which means category A is the highest and category D is the lowest. While playing the game, players can increase the HP of the character. Now, Tokitsukaze wants you to increase her HP by at most 2 (that is, either by 0, 1 or 2). How much should she increase her HP so that it has the highest possible category? Input The only line contains a single integer x (30 ≤ x ≤ 100) — the value Tokitsukaze's HP currently. Output Print an integer a (0 ≤ a ≤ 2) and an uppercase letter b (b ∈ { A, B, C, D }), representing that the best way is to increase her HP by a, and then the category becomes b. Note that the output characters are case-sensitive. Examples Input 33 Output 0 A Input 98 Output 1 B Note For the first example, the category of Tokitsukaze's HP is already A, so you don't need to enhance her ability. For the second example: * If you don't increase her HP, its value is still 98, which equals to (4 × 24 + 2), and its category is C. * If you increase her HP by 1, its value becomes 99, which equals to (4 × 24 + 3), and its category becomes B. * If you increase her HP by 2, its value becomes 100, which equals to (4 × 25), and its category becomes D. Therefore, the best way is to increase her HP by 1 so that the category of her HP becomes B. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int x; cin >> x; if (x % 4 == 0) cout << "1 A"; if (x % 4 == 1) cout << "0 A"; if (x % 4 == 2) cout << "1 B"; if (x % 4 == 3) cout << "2 A"; return 0; } ```
### Prompt Please create a solution in Cpp to the following problem: You and your friend are playing the game Mortal Kombat XI. You are trying to pass a challenge tower. There are n bosses in this tower, numbered from 1 to n. The type of the i-th boss is a_i. If the i-th boss is easy then its type is a_i = 0, otherwise this boss is hard and its type is a_i = 1. During one session, either you or your friend can kill one or two bosses (neither you nor your friend can skip the session, so the minimum number of bosses killed during one session is at least one). After your friend session, your session begins, then again your friend session begins, your session begins, and so on. The first session is your friend's session. Your friend needs to get good because he can't actually kill hard bosses. To kill them, he uses skip points. One skip point can be used to kill one hard boss. Your task is to find the minimum number of skip points your friend needs to use so you and your friend kill all n bosses in the given order. For example: suppose n = 8, a = [1, 0, 1, 1, 0, 1, 1, 1]. Then the best course of action is the following: * your friend kills two first bosses, using one skip point for the first boss; * you kill the third and the fourth bosses; * your friend kills the fifth boss; * you kill the sixth and the seventh bosses; * your friend kills the last boss, using one skip point, so the tower is completed using two skip points. 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 one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of bosses. The second line of the test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1), where a_i is the type of the i-th boss. 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 skip points your friend needs to use so you and your friend kill all n bosses in the given order. Example Input 6 8 1 0 1 1 0 1 1 1 5 1 1 1 1 0 7 1 1 1 1 0 0 1 6 1 1 1 1 1 1 1 1 1 0 Output 2 2 2 2 1 0 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; int arr[n]; for (int i = 0; i < n; i++) { cin >> arr[i]; } int skip = arr[0]; for (int i = 1; i < n - 2; i++) { if (arr[i] && arr[i + 1] && arr[i + 2]) { skip++; i += 2; } } cout << skip << "\n"; } return 0; } ```
### Prompt Create a solution in cpp for the following problem: On a plane are n points (xi, yi) with integer coordinates between 0 and 106. The distance between the two points with numbers a and b is said to be the following value: <image> (the distance calculated by such formula is called Manhattan distance). We call a hamiltonian path to be some permutation pi of numbers from 1 to n. We say that the length of this path is value <image>. Find some hamiltonian path with a length of no more than 25 × 108. Note that you do not have to minimize the path length. Input The first line contains integer n (1 ≤ n ≤ 106). The i + 1-th line contains the coordinates of the i-th point: xi and yi (0 ≤ xi, yi ≤ 106). It is guaranteed that no two points coincide. Output Print the permutation of numbers pi from 1 to n — the sought Hamiltonian path. The permutation must meet the inequality <image>. If there are multiple possible answers, print any of them. It is guaranteed that the answer exists. Examples Input 5 0 7 8 10 3 4 5 0 9 12 Output 4 3 1 2 5 Note In the sample test the total distance is: <image> (|5 - 3| + |0 - 4|) + (|3 - 0| + |4 - 7|) + (|0 - 8| + |7 - 10|) + (|8 - 9| + |10 - 12|) = 2 + 4 + 3 + 3 + 8 + 3 + 1 + 2 = 26 ### Response ```cpp #include <bits/stdc++.h> const int MAXN = 1000009; using namespace std; int n; int x[MAXN], y[MAXN], id[MAXN]; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d %d", x + i, y + i); id[i] = i; } sort(id + 1, id + 1 + n, [](int a, int b) { if (x[a] / 1000 != x[b] / 1000) return x[a] / 1000 < x[b] / 1000; if ((x[a] / 1000) % 2 == 1) return y[a] > y[b]; return y[a] < y[b]; }); for (int i = 1; i <= n; i++) printf("%d ", id[i]); } ```
### Prompt In CPP, your task is to solve the following problem: A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care. There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell. An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable. Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met. 1. There is at least one south magnet in every row and every column. 2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement. 3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement. Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets). Input The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively. The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters. Output Output a single integer, the minimum possible number of north magnets required. If there is no placement of magnets that satisfies all conditions, print a single integer -1. Examples Input 3 3 .#. ### ##. Output 1 Input 4 2 ## .# .# ## Output -1 Input 4 5 ....# ####. .###. .#... Output 2 Input 2 1 . # Output -1 Input 3 5 ..... ..... ..... Output 0 Note In the first test, here is an example placement of magnets: <image> In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column. <image> In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets. <image> In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square. <image> In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); int n, m; cin >> n >> m; vector<vector<int>> a(n + 2, vector<int>(m + 2, 0)); for (int i = 1; i <= n; i++) { string s; cin >> s; for (int j = 1; j <= m; j++) a[i][j] = (s[j - 1] == '#'); } int row = 0; for (int i = 1; i <= n; i++) { int cnt = 0; for (int j = 1; j <= m; j++) { if (a[i][j] && (j == 1 || !a[i][j - 1])) ++cnt; } if (cnt > 1) return cout << "-1", 0; if (!cnt) row++; } int col = 0; for (int j = 1; j <= m; j++) { int cnt = 0; for (int i = 1; i <= n; i++) { if (a[i][j] && (i == 1 || !a[i - 1][j])) ++cnt; } if (cnt > 1) return cout << "-1", 0; if (!cnt) ++col; } if ((col > 0) != (row > 0)) return cout << "-1", 0; int ans = 0; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (!a[i][j]) continue; a[i][j] = 0; ++ans; deque<pair<int, int>> d; d.emplace_back(i, j); while ((int)d.size()) { auto x = d.front(); d.pop_front(); for (int di = -1; di <= 1; di++) { for (int dj = -1; dj <= 1; dj++) { if (di * di + dj * dj == 1) { int nx = x.first + di; int ny = x.second + dj; if (!a[nx][ny]) continue; a[nx][ny] = 0; d.emplace_back(nx, ny); } } } } } } cout << ans; } ```
### Prompt Develop a solution in Cpp to the problem described below: Amr lives in Lala Land. Lala Land is a very beautiful country that is located on a coordinate line. Lala Land is famous with its apple trees growing everywhere. Lala Land has exactly n apple trees. Tree number i is located in a position xi and has ai apples growing on it. Amr wants to collect apples from the apple trees. Amr currently stands in x = 0 position. At the beginning, he can choose whether to go right or left. He'll continue in his direction until he meets an apple tree he didn't visit before. He'll take all of its apples and then reverse his direction, continue walking in this direction until he meets another apple tree he didn't visit before and so on. In the other words, Amr reverses his direction when visiting each new apple tree. Amr will stop collecting apples when there are no more trees he didn't visit in the direction he is facing. What is the maximum number of apples he can collect? Input The first line contains one number n (1 ≤ n ≤ 100), the number of apple trees in Lala Land. The following n lines contains two integers each xi, ai ( - 105 ≤ xi ≤ 105, xi ≠ 0, 1 ≤ ai ≤ 105), representing the position of the i-th tree and number of apples on it. It's guaranteed that there is at most one apple tree at each coordinate. It's guaranteed that no tree grows in point 0. Output Output the maximum number of apples Amr can collect. Examples Input 2 -1 5 1 5 Output 10 Input 3 -2 2 1 4 -1 3 Output 9 Input 3 1 9 3 5 7 10 Output 9 Note In the first sample test it doesn't matter if Amr chose at first to go left or right. In both cases he'll get all the apples. In the second sample test the optimal solution is to go left to x = - 1, collect apples from there, then the direction will be reversed, Amr has to go to x = 1, collect apples from there, then the direction will be reversed and Amr goes to the final tree x = - 2. In the third sample test the optimal solution is to go right to x = 1, collect apples from there, then the direction will be reversed and Amr will not be able to collect anymore apples because there are no apple trees to his left. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int i, j, n; cin >> n; vector<pair<int, int> > a, b; int c1 = 0, c2 = 0; int p, q; for (i = 0; i < n; i++) { cin >> p >> q; if (p < 0) { a.push_back(make_pair(p, q)); } else b.push_back(make_pair(p, q)); } sort(b.begin(), b.end()); sort(a.rbegin(), a.rend()); long long int ans1 = 0, ans2 = 0; for (i = 0; i < n; ++i) { if (i % 2) { if (c1 == b.size()) break; else ans1 += b[c1++].second; } else { if (c2 == a.size()) break; else ans1 += a[c2++].second; } } c1 = 0, c2 = 0; for (i = 0; i < n; ++i) { if (i % 2 == 0) { if (c1 == b.size()) break; else ans2 += b[c1++].second; } else { if (c2 == a.size()) break; else ans2 += a[c2++].second; } } cout << max(ans1, ans2); return 0; } ```
### Prompt Construct a cpp code solution to the problem outlined: You can perfectly predict the price of a certain stock for the next N days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you don't own any. At the end of the N days you would like to again own zero shares, but want to have as much money as possible. Input Input begins with an integer N (2 ≤ N ≤ 3·105), the number of days. Following this is a line with exactly N integers p1, p2, ..., pN (1 ≤ pi ≤ 106). The price of one share of stock on the i-th day is given by pi. Output Print the maximum amount of money you can end up with at the end of N days. Examples Input 9 10 5 4 7 9 12 6 2 10 Output 20 Input 20 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 Output 41 Note In the first example, buy a share at 5, buy another at 4, sell one at 9 and another at 12. Then buy at 2 and sell at 10. The total profit is - 5 - 4 + 9 + 12 - 2 + 10 = 20. ### Response ```cpp #include <bits/stdc++.h> long long int MMM = 1000000007; int pw(long long int a, long long int b) { if (b == 0) return 1; long long int t = pw(a, b / 2); if (b % 2 == 0) return (t * t) % 1000000007; else return ((t * t) % 1000000007 * a) % 1000000007; } using namespace std; vector<int> pm; void prm(int n) { bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { if (prime[p] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } for (int p = 2; p <= n; p++) if (prime[p]) pm.push_back(p); } bool sortbysecdesc(const pair<long long int, long long int> &a, const pair<long long int, long long int> &b) { return a.first > b.first; } bool cmp(int x, int y) { return x > y; } long long int gcd(long long int a, long long int b) { if (!a) return b; return gcd(b % a, a); } int pa[26]; int find(int i) { if (i == pa[i]) return i; return pa[i] = find(pa[i]); } void join(int i, int j) { int a = find(i); int b = find(j); if (b >= a) pa[b] = a; else pa[a] = b; } int dx[] = {-1, -1, -1, 0, 1, 1, 1, 0}; int dy[] = {-1, 0, 1, 1, 1, 0, -1, -1}; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long int t, ans = 0; cin >> t; multiset<long long int> st; for (int i = 0; i < t; i++) { long long int x; cin >> x; if (!st.empty() && *st.begin() < x) { ans += x - *st.begin(); st.erase(st.begin()); st.insert(x); } st.insert(x); } cout << ans << endl; } ```
### Prompt Your task is to create a cpp solution to the following problem: You are given a string s consisting of lowercase Latin letters. Let the length of s be |s|. You may perform several operations on this string. In one operation, you can choose some index i and remove the i-th character of s (s_i) if at least one of its adjacent characters is the previous letter in the Latin alphabet for s_i. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index i should satisfy the condition 1 ≤ i ≤ |s| during each operation. For the character s_i adjacent characters are s_{i-1} and s_{i+1}. The first and the last characters of s both have only one adjacent character (unless |s| = 1). Consider the following example. Let s= bacabcab. 1. During the first move, you can remove the first character s_1= b because s_2= a. Then the string becomes s= acabcab. 2. During the second move, you can remove the fifth character s_5= c because s_4= b. Then the string becomes s= acabab. 3. During the third move, you can remove the sixth character s_6='b' because s_5= a. Then the string becomes s= acaba. 4. During the fourth move, the only character you can remove is s_4= b, because s_3= a (or s_5= a). The string becomes s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally. Input The first line of the input contains one integer |s| (1 ≤ |s| ≤ 100) — the length of s. The second line of the input contains one string s consisting of |s| lowercase Latin letters. Output Print one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally. Examples Input 8 bacabcab Output 4 Input 4 bcda Output 3 Input 6 abbbbb Output 5 Note The first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only, but it can be shown that the maximum possible answer to this test is 4. In the second example, you can remove all but one character of s. The only possible answer follows. 1. During the first move, remove the third character s_3= d, s becomes bca. 2. During the second move, remove the second character s_2= c, s becomes ba. 3. And during the third move, remove the first character s_1= b, s becomes a. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long int INF = 1e18L + 5; const long long int maxn = 205; long long int ceel(long long int a, long long int b) { if (a % b == 0) return a / b; return a / b + 1; } int main() { long long int n, i, j, k; string s; cin >> n >> s; long long int cnt = 0; for (i = 0; i < n; i++) { long long int idx = -1, mx = -1; for (j = 0; j < s.length(); j++) { if (((j > 0 and s[j] == s[j - 1] + 1) or (j < s.length() - 1 and s[j] == s[j + 1] + 1)) and s[j] > mx) { mx = s[j]; idx = j; } } if (mx == -1) break; s.erase(s.begin() + idx); cnt++; } cout << cnt << endl; return 0; } ```
### Prompt Please provide a Cpp coded solution to the problem described below: After all the events in Orlando we all know, Sasha and Roma decided to find out who is still the team's biggest loser. Thankfully, Masha found somewhere a revolver with a rotating cylinder of n bullet slots able to contain exactly k bullets, now the boys have a chance to resolve the problem once and for all. Sasha selects any k out of n slots he wishes and puts bullets there. Roma spins the cylinder so that every of n possible cylinder's shifts is equiprobable. Then the game starts, the players take turns, Sasha starts: he puts the gun to his head and shoots. If there was no bullet in front of the trigger, the cylinder shifts by one position and the weapon is given to Roma for make the same move. The game continues until someone is shot, the survivor is the winner. Sasha does not want to lose, so he must choose slots for bullets in such a way as to minimize the probability of its own loss. Of all the possible variant he wants to select the lexicographically minimal one, where an empty slot is lexicographically less than a charged one. More formally, the cylinder of n bullet slots able to contain k bullets can be represented as a string of n characters. Exactly k of them are "X" (charged slots) and the others are "." (uncharged slots). Let us describe the process of a shot. Suppose that the trigger is in front of the first character of the string (the first slot). If a shot doesn't kill anyone and the cylinder shifts, then the string shifts left. So the first character becomes the last one, the second character becomes the first one, and so on. But the trigger doesn't move. It will be in front of the first character of the resulting string. Among all the strings that give the minimal probability of loss, Sasha choose the lexicographically minimal one. According to this very string, he charges the gun. You have to help Sasha to charge the gun. For that, each xi query must be answered: is there a bullet in the positions xi? Input The first line contains three integers n, k and p (1 ≤ n ≤ 1018, 0 ≤ k ≤ n, 1 ≤ p ≤ 1000) — the number of slots in the cylinder, the number of bullets and the number of queries. Then follow p lines; they are the queries. Each line contains one integer xi (1 ≤ xi ≤ n) the number of slot to describe. Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is preferred to use cin, cout streams or the %I64d specificator. Output For each query print "." if the slot should be empty and "X" if the slot should be charged. Examples Input 3 1 3 1 2 3 Output ..X Input 6 3 6 1 2 3 4 5 6 Output .X.X.X Input 5 2 5 1 2 3 4 5 Output ...XX Note The lexicographical comparison of is performed by the < operator in modern programming languages. The a string is lexicographically less that the b string, if there exists such i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < i) aj = bj. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { long long n, k, p; while (cin >> n >> k >> p) { bool nono = false; if (k == 0) { nono = true; } if (n & 1) { n--; if (k) k--; } for (int i = 0; i < p; i++) { long long x; cin >> x; if (nono) { cout << '.'; } else { if (x == n + 1) { cout << 'X'; } else { if (((n - x) & 1) == 0) { if ((n - x) / 2 + 1 <= k) { cout << 'X'; } else { cout << '.'; } } else { if (k > n / 2) { if ((k - n / 2) >= (n - x + 1) / 2) { cout << 'X'; } else { cout << '.'; } } else { cout << '.'; } } } } } cout << endl; } return 0; } ```
### Prompt In Cpp, your task is to solve the following problem: You are given a tree (an undirected connected graph without cycles) and an integer s. Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible. Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path. Find the minimum possible diameter that Vanya can get. Input The first line contains two integer numbers n and s (2 ≤ n ≤ 10^5, 1 ≤ s ≤ 10^9) — the number of vertices in the tree and the sum of edge weights. Each of the following n−1 lines contains two space-separated integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the indexes of vertices connected by an edge. The edges are undirected. It is guaranteed that the given edges form a tree. Output Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} ≤ 10^{-6}. Examples Input 4 3 1 2 1 3 1 4 Output 2.000000000000000000 Input 6 1 2 1 2 3 2 5 5 4 5 6 Output 0.500000000000000000 Input 5 5 1 2 2 3 3 4 3 5 Output 3.333333333333333333 Note In the first example it is necessary to put weights like this: <image> It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter. In the second example it is necessary to put weights like this: <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MX = 1e5 + 3; int deg[MX]; pair<int, int> edge[MX]; int main() { ios::sync_with_stdio(0); cin.tie(0); int n, s; cin >> n >> s; for (int i = 0; i < n - 1; i++) { int u, v; cin >> u >> v; deg[u - 1]++; deg[v - 1]++; edge[i] = {u - 1, v - 1}; } int cnt = 0; for (int i = 0; i < n - 1; i++) { if (deg[edge[i].first] == 1 || deg[edge[i].second] == 1) cnt++; } cout << fixed << setprecision(10) << min((double)s / cnt * 2, (double)s); } ```
### Prompt Your challenge is to write a cpp solution to the following problem: You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1. Swap two neighboring matrix rows, that is, rows with indexes i and i + 1 for some integer i (1 ≤ i < 5). 2. Swap two neighboring matrix columns, that is, columns with indexes j and j + 1 for some integer j (1 ≤ j < 5). You think that a matrix looks beautiful, if the single number one of the matrix is located in its middle (in the cell that is on the intersection of the third row and the third column). Count the minimum number of moves needed to make the matrix beautiful. Input The input consists of five lines, each line contains five integers: the j-th integer in the i-th line of the input represents the element of the matrix that is located on the intersection of the i-th row and the j-th column. It is guaranteed that the matrix consists of 24 zeroes and a single number one. Output Print a single integer — the minimum number of moves needed to make the matrix beautiful. Examples Input 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Output 3 Input 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 Output 1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int A[5][5], x, y, p, q, sum; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { cin >> A[i][j]; if (A[i][j] == 1) { x = i; y = j; } } cout << endl; } if (x == 2 && y == 2) { p = 0; q = 0; } else if (x >= 2 && y >= 2) { p = x - 2; q = y - 2; } else if (x >= 2 && y <= 2) { p = x - 2; q = 2 - y; } else if (x <= 2 && y >= 2) { p = 2 - x; q = y - 2; } else if (x <= 2 && y <= 2) { p = 2 - x; q = 2 - y; } sum = p + q; cout << sum; return 0; } ```
### Prompt Construct a CPP code solution to the problem outlined: There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0). Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers. The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. Input The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. Output Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. Examples Input 4 0 0 1 1 2 2 2 0 -1 -1 Output 2 Input 2 1 2 1 1 1 0 Output 1 Note Explanation to the first and second samples from the statement, respectively: <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n, x, y; cin >> n >> x >> y; vector<pair<int, int> > v; for (int i = 0; i < n; i++) { int a, b; cin >> a >> b; v.push_back(make_pair(a, b)); } sort(v.begin(), v.end()); bool visit[n]; memset(visit, 0, sizeof visit); int ans = 0; for (int i = 0; i < n; i++) { pair<int, int> p = v[i]; if (visit[i] == false) { ans++; visit[i] = true; for (int j = i + 1; j < n; j++) { pair<int, int> p1 = v[j]; int temp = p1.second - p.second; int temp1 = x - p1.first; int temp2 = y - p1.second; int temp3 = p1.first - p.first; if (temp * temp1 == temp2 * temp3) { visit[j] = true; } } } } cout << ans << "\n"; } ```
### 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 N = 1e5 + 5; const int mod = 1e9 + 7; long long a[N], n, mx, cnt; vector<int> v, e; long long ans = 1; long long pw(long long a, long long b) { if (b == 0) return 1; long long res = pw(a, b / 2); res = res * res % mod; if (b % 2) res = res * a % mod; return res; } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &a[i]), mx = max(mx, a[i]); sort(a, a + n); for (int i = 2; i <= mx; i++) { v.clear(); e.clear(); for (int j = 1; j * j <= i; j++) { if (i % j == 0) { v.push_back(j); if (j * j != i) e.push_back(i / j); } } for (int j = (int)e.size() - 1; j >= 0; j--) v.push_back(e[j]); int now = 0; long long sum = 1, sum2 = 1; for (int j = 1; j < (int)v.size(); j++) { int to = lower_bound(a + now, a + n, v[j]) - a; sum = sum * pw(j, to - now) % mod; now = to; } sum = sum * pw((int)v.size(), n - now) % mod; now = 0; for (int j = 1; j < v.size() - 1; j++) { int to = lower_bound(a + now, a + n, v[j]) - a; sum2 = sum2 * pw(j, to - now) % mod; now = to; } sum2 = sum2 * pw((int)v.size() - 1, n - now) % mod; ans = (ans + sum) % mod; ans = (ans + mod - sum2) % mod; } ans = (ans + mod) % mod; printf("%lld\n", ans); return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: At a geometry lesson Bob learnt that a triangle is called right-angled if it is nondegenerate and one of its angles is right. Bob decided to draw such a triangle immediately: on a sheet of paper he drew three points with integer coordinates, and joined them with segments of straight lines, then he showed the triangle to Peter. Peter said that Bob's triangle is not right-angled, but is almost right-angled: the triangle itself is not right-angled, but it is possible to move one of the points exactly by distance 1 so, that all the coordinates remain integer, and the triangle become right-angled. Bob asks you to help him and find out if Peter tricks him. By the given coordinates of the triangle you should find out if it is right-angled, almost right-angled, or neither of these. Input The first input line contains 6 space-separated integers x1, y1, x2, y2, x3, y3 — coordinates of the triangle's vertices. All the coordinates are integer and don't exceed 100 in absolute value. It's guaranteed that the triangle is nondegenerate, i.e. its total area is not zero. Output If the given triangle is right-angled, output RIGHT, if it is almost right-angled, output ALMOST, and if it is neither of these, output NEITHER. Examples Input 0 0 2 0 0 1 Output RIGHT Input 2 3 4 5 6 6 Output NEITHER Input -1 0 2 0 0 1 Output ALMOST ### Response ```cpp #include <bits/stdc++.h> using namespace std; int dis(int x1, int y1, int x2, int y2) { int d = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); return d; } bool area(int x1, int y1, int x2, int y2, int x3, int y3) { int a = (x1 - x2) * (y2 - y3) - (y1 - y2) * (x2 - x3); if (a == 0) return 0; else return 1; } bool check(int x1, int y1, int x2, int y2, int x3, int y3) { int nnn = area(x1, y1, x2, y2, x3, y3); if (nnn == 0) return false; int a = dis(x1, y1, x2, y2); int b = dis(x1, y1, x3, y3); int c = dis(x2, y2, x3, y3); if (a + b == c) return true; if (a + c == b) return true; if (b + c == a) return true; return false; } int main() { int x1, x2, x3, y1, y2, y3; cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3; bool ans = false; bool temp = check(x1, y1, x2, y2, x3, y3); if (temp == true) { printf("RIGHT\n"); return 0; } temp = check(x1 + 1, y1, x2, y2, x3, y3); ans = ans or temp; temp = check(x1 - 1, y1, x2, y2, x3, y3); ans = ans or temp; temp = check(x1, y1 + 1, x2, y2, x3, y3); ans = ans or temp; temp = check(x1, y1 - 1, x2, y2, x3, y3); ans = ans or temp; temp = check(x1, y1, x2 + 1, y2, x3, y3); ans = ans or temp; temp = check(x1, y1, x2 - 1, y2, x3, y3); ans = ans or temp; temp = check(x1, y1, x2, y2 + 1, x3, y3); ans = ans or temp; temp = check(x1, y1, x2, y2 - 1, x3, y3); ans = ans or temp; temp = check(x1, y1, x2, y2, x3 + 1, y3); ans = ans or temp; temp = check(x1, y1, x2, y2, x3 - 1, y3); ans = ans or temp; temp = check(x1, y1, x2, y2, x3, y3 + 1); ans = ans or temp; temp = check(x1, y1, x2, y2, x3, y3 - 1); ans = ans or temp; if (ans == true) printf("ALMOST\n"); else printf("NEITHER\n"); } ```
### Prompt Your challenge is to write a Cpp solution to the following problem: You have n sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks. Let S be the area of the rectangle and P be the perimeter of the rectangle. The chosen rectangle should have the value (P^2)/(S) minimal possible. The value is taken without any rounding. If there are multiple answers, print any of them. Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (T ≥ 1) — the number of lists of sticks in the testcase. Then 2T lines follow — lines (2i - 1) and 2i of them describe the i-th list. The first line of the pair contains a single integer n (4 ≤ n ≤ 10^6) — the number of sticks in the i-th list. The second line of the pair contains n integers a_1, a_2, ..., a_n (1 ≤ a_j ≤ 10^4) — lengths of the sticks in the i-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all T lists doesn't exceed 10^6 in each testcase. Output Print T lines. The i-th line should contain the answer to the i-th list of the input. That is the lengths of the four sticks you choose from the i-th list, so that they form a rectangle and the value (P^2)/(S) of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them. Example Input 3 4 7 2 2 7 8 2 8 1 4 8 2 1 5 5 5 5 5 5 5 Output 2 7 7 2 2 2 1 1 5 5 5 5 Note There is only one way to choose four sticks in the first list, they form a rectangle with sides 2 and 7, its area is 2 ⋅ 7 = 14, perimeter is 2(2 + 7) = 18. (18^2)/(14) ≈ 23.143. The second list contains subsets of four sticks that can form rectangles with sides (1, 2), (2, 8) and (1, 8). Their values are (6^2)/(2) = 18, (20^2)/(16) = 25 and (18^2)/(8) = 40.5, respectively. The minimal one of them is the rectangle (1, 2). You can choose any four of the 5 given sticks from the third list, they will form a square with side 5, which is still a rectangle with sides (5, 5). ### Response ```cpp #include <bits/stdc++.h> using namespace std; ifstream fin("input.txt"); ofstream fout("output.txt"); bool isPrime(int x) { if (x <= 4 || x % 2 == 0 || x % 3 == 0) return x == 2 || x == 3; for (int i = 5; i * i <= x; i += 6) if (x % i == 0 || x % (i + 2) == 0) return 0; return 1; } inline void boostIO() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); } int main() { boostIO(); long long int T; cin >> T; for (int i = 0; i < (T); ++i) { long long int n; cin >> n; map<long long int, long long int> Map; vector<long double> A; for (int i = 0; i < (n); ++i) { long long int x; cin >> x; Map[x]++; if (Map[x] % 2 == 0) { A.push_back(x); } } long long int Prev = -1; long long int a = -1; long long int b = -1; long double Min = numeric_limits<long double>::max(); sort(A.begin(), A.end()); for (int i = 0; i < (A.size()); ++i) { if (Prev == -1) { Prev = A[i]; continue; } long double w = ((A[i] + Prev) * 2) * ((A[i] + Prev) * 2) / (A[i] * Prev); if (Min >= w) { Min = w; a = Prev; b = A[i]; if (a == b) break; } Prev = A[i]; } cout << a << " " << a << " " << b << " " << b << endl; } return 0; } ```
### Prompt Develop a solution in CPP to the problem described below: This is an output-only problem. You shouldn't read anything from the input. In short, your task is to simulate multiplication by using only comparison (x < y) and addition (x + y). There is no input in this problem, you just print a sequence of operations. Imagine that there is a big array a[0], a[1], ..., a[N-1] of length N. The first two values are initially two non-negative integers A and B (which are unknown to you), the other elements are zeros. Your goal is to get the product A \cdot B in a[2] at the end. You are allowed operations of two types, with the following format (where 0 \leq i, j, k < N): * `+ i j k` — applies operation a[k] = a[i] + a[j]. * `< i j k` — applies operation a[k] = a[i] < a[j]. That is, if a[i] < a[j] then a[k] becomes 1, otherwise it becomes 0. You can use at most Q operations. Elements of a can't exceed V. Indices (i, j, k) don't have to be distinct. It's allowed to modify any element of the array (including the first two). The actual checker simulates the process for multiple pairs (A, B) within a single test. Each time, the checker chooses values A and B, creates the array a = [A, B, 0, 0, \ldots, 0], applies all your operations and ensures that a[2] = A \cdot B. Constraints * 0 \leq A, B \leq 10^9 * N = Q = 200\,000 * V = 10^{19} = 10\,000\,000\,000\,000\,000\,000 Input The Standard Input is empty. Output In the first line, print the number of operations. Each operation should then be printed in a single line of format `+ i j k` or `< i j k`. Example Input Output ### Response ```cpp #define DIN freopen("input.txt","r",stdin); #define DOUT freopen("output.txt","w",stdout); #include <bits/stdc++.h> #include <cstdio> #define mem(a,b) memset(a,b,sizeof(a)) #define REP(i,a,b) for(int i=(a);i<=(int)(b);i++) #define REP_(i,a,b) for(int i=(a);i>=(b);i--) #define pb push_back using namespace std; typedef long long LL; typedef std::vector<int> VI; typedef std::pair<int,int> PI; int read() { int x=0,flag=1; char c=getchar(); while((c>'9' || c<'0') && c!='-') c=getchar(); if(c=='-') flag=0,c=getchar(); while(c<='9' && c>='0') {x=(x<<3)+(x<<1)+c-'0';c=getchar();} return flag?x:-x; } int n=97; void print(char c,int i,int j,int k) { printf("%c %d %d %d\n",c,i,j,k); } void a(int i) {print('+',i,i,i+1);} void f(int x,int i,int j) { for(int q=0;q<30;q++) { a(j+q-1); print('+',j+q,n,j+q); for(int s=j+q;s<j+29;s++) a(s); print('<',j+29,x,i+q); a(j+q-1); print('+',j+q,i+q,j+q); } } int main() { puts("3933"); print('+',0,1,n); print('<',2,n,n); print('+',0,n,3); print('+',1,n,4); f(3,5,36); f(4,36,67); for(int i=0;i<59;i++) { print('+',2,2,2); for(int j=0;j<=i;j++) if(i-30<j && j<30) { print('+',5+i-j,36+j,98); print('<',n,98,99); print('+',2,99,2); } } return 0; } ```
### Prompt In Cpp, your task is to solve the following problem: There is a sequence of length 2N: A_1, A_2, ..., A_{2N}. Each A_i is either -1 or an integer between 1 and 2N (inclusive). Any integer other than -1 appears at most once in {A_i}. For each i such that A_i = -1, Snuke replaces A_i with an integer between 1 and 2N (inclusive), so that {A_i} will be a permutation of 1, 2, ..., 2N. Then, he finds a sequence of length N, B_1, B_2, ..., B_N, as B_i = min(A_{2i-1}, A_{2i}). Find the number of different sequences that B_1, B_2, ..., B_N can be, modulo 10^9 + 7. Constraints * 1 \leq N \leq 300 * A_i = -1 or 1 \leq A_i \leq 2N. * If A_i \neq -1, A_j \neq -1, then A_i \neq A_j. (i \neq j) Input Input is given from Standard Input in the following format: N A_1 A_2 ... A_{2N} Output Print the number of different sequences that B_1, B_2, ..., B_N can be, modulo 10^9 + 7. Examples Input 3 1 -1 -1 3 6 -1 Output 5 Input 4 7 1 8 3 5 2 6 4 Output 1 Input 10 7 -1 -1 -1 -1 -1 -1 6 14 12 13 -1 15 -1 -1 -1 -1 20 -1 -1 Output 9540576 Input 20 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 6 -1 -1 -1 -1 -1 7 -1 -1 -1 -1 -1 -1 -1 -1 -1 34 -1 -1 -1 -1 31 -1 -1 -1 -1 -1 -1 -1 -1 Output 374984201 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 600, mod = 1e9 + 7; int n, cnt, is[maxn + 10]; int a[maxn + 10]; int f[maxn + 10][maxn + 10], g[maxn + 10][maxn + 10]; inline void addto(int &x, int y) { x += y; if (x >= mod) x -= mod; } void addin(int d) { if (d == 2) return; memset(g, 0, sizeof g); for (int i = 0; i <= n; ++i) for (int j = 0; j <= n; ++j) if (f[i][j]) { if (d == 0) { addto(g[i][j + 1], f[i][j]); if (i) addto(g[i - 1][j], 1ll * f[i][j] * i % mod); if (j) addto(g[i][j - 1], f[i][j]); } else { addto(g[i + 1][j], f[i][j]); if (j) addto(g[i][j - 1], f[i][j]); } } memcpy(f, g, sizeof g); } int main() { scanf("%d", &n); n *= 2; for (int i = 1; i <= n; ++i) { scanf("%d", &a[i]); if (a[i] != -1) is[a[i]] = 1; if (i % 2 == 0) { if (a[i] != -1 && a[i - 1] != -1) is[a[i]] = is[a[i - 1]] = 2; if (a[i] == -1 && a[i - 1] == -1) ++cnt; } } f[0][0] = 1; for (int i = n; i >= 1; --i) addin(is[i]); int ans = f[0][0]; for (int i = 1; i <= cnt; ++i) ans = 1ll * ans * i % mod; printf("%d", ans); } ```
### Prompt Your task is to create a Cpp solution to the following problem: A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not. The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2. One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside. Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song. Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix? Input The first and only input line contains two positive integers — n and m (2 ≤ n < m ≤ 50). It is guaranteed that n is prime. Pretests contain all the cases with restrictions 2 ≤ n < m ≤ 4. Output Print YES, if m is the next prime number after n, or NO otherwise. Examples Input 3 5 Output YES Input 7 11 Output YES Input 7 9 Output NO ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n, m, mm, i; cin >> n >> m; n = n + 1; for (i = 2; i < n; i++) { if (n % i != 0 && i == n - 1) mm = n; if (n % i == 0) { n = n + 1; i = 1; } } if (mm == m) cout << "YES\n"; else cout << "NO\n"; return 0; } ```
### Prompt Please create a solution in cpp to the following problem: Pupils decided to go to amusement park. Some of them were with parents. In total, n people came to the park and they all want to get to the most extreme attraction and roll on it exactly once. Tickets for group of x people are sold on the attraction, there should be at least one adult in each group (it is possible that the group consists of one adult). The ticket price for such group is c1 + c2·(x - 1)2 (in particular, if the group consists of one person, then the price is c1). All pupils who came to the park and their parents decided to split into groups in such a way that each visitor join exactly one group, and the total price of visiting the most extreme attraction is as low as possible. You are to determine this minimum possible total price. There should be at least one adult in each group. Input The first line contains three integers n, c1 and c2 (1 ≤ n ≤ 200 000, 1 ≤ c1, c2 ≤ 107) — the number of visitors and parameters for determining the ticket prices for a group. The second line contains the string of length n, which consists of zeros and ones. If the i-th symbol of the string is zero, then the i-th visitor is a pupil, otherwise the i-th person is an adult. It is guaranteed that there is at least one adult. It is possible that there are no pupils. Output Print the minimum price of visiting the most extreme attraction for all pupils and their parents. Each of them should roll on the attraction exactly once. Examples Input 3 4 1 011 Output 8 Input 4 7 2 1101 Output 18 Note In the first test one group of three people should go to the attraction. Then they have to pay 4 + 1 * (3 - 1)2 = 8. In the second test it is better to go to the attraction in two groups. The first group should consist of two adults (for example, the first and the second person), the second should consist of one pupil and one adult (the third and the fourth person). Then each group will have a size of two and for each the price of ticket is 7 + 2 * (2 - 1)2 = 9. Thus, the total price for two groups is 18. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAX_N = 2e5 + 10; const int MAX_LOG = 62; const long long INF = 1e18 + 1; const long long MOD = 1e9 + 7; long long n, c1, c2, ans = INF; string s; int m; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> c1 >> c2; cin >> s; for (int i = 0; i < n; i++) if (s[i] == '1') m++; for (int i = 1; i <= m; i++) { long long k = n / i; long long r = n % i; long long tmp = r * (c1 + c2 * (k)*k); tmp += (i - r) * (c1 + c2 * (k - 1) * (k - 1)); ans = min(ans, tmp); } cout << ans << endl; } ```
### Prompt Generate a CPP solution to the following problem: This problem consists of three subproblems: for solving subproblem F1 you will receive 8 points, for solving subproblem F2 you will receive 15 points, and for solving subproblem F3 you will receive 10 points. Manao has developed a model to predict the stock price of a company over the next n days and wants to design a profit-maximizing trading algorithm to make use of these predictions. Unfortunately, Manao's trading account has the following restrictions: * It only allows owning either zero or one shares of stock at a time; * It only allows buying or selling a share of this stock once per day; * It allows a maximum of k buy orders over the next n days; For the purposes of this problem, we define a trade to a be the act of buying one share of stock on day i, then holding the stock until some day j > i at which point the share is sold. To restate the above constraints, Manao is permitted to make at most k non-overlapping trades during the course of an n-day trading period for which Manao's model has predictions about the stock price. Even though these restrictions limit the amount of profit Manao can make compared to what would be achievable with an unlimited number of trades or the ability to hold more than one share at a time, Manao still has the potential to make a lot of money because Manao's model perfectly predicts the daily price of the stock. For example, using this model, Manao could wait until the price is low, then buy one share and hold until the price reaches a high value, then sell for a profit, and repeat this process up to k times until n days have passed. Nevertheless, Manao is not satisfied by having a merely good trading algorithm, and wants to develop an optimal strategy for trading subject to these constraints. Help Manao achieve this goal by writing a program that will determine when to buy and sell stock to achieve the greatest possible profit during the n-day trading period subject to the above constraints. Input The first line contains two integers n and k, separated by a single space, with <image>. The i-th of the following n lines contains a single integer pi (0 ≤ pi ≤ 1012), where pi represents the price at which someone can either buy or sell one share of stock on day i. The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem F1 (8 points), n will be between 1 and 3000, inclusive. * In subproblem F2 (15 points), n will be between 1 and 100000, inclusive. * In subproblem F3 (10 points), n will be between 1 and 4000000, inclusive. Output For this problem, the program will only report the amount of the optimal profit, rather than a list of trades that can achieve this profit. Therefore, the program should print one line containing a single integer, the maximum profit Manao can achieve over the next n days with the constraints of starting with no shares on the first day of trading, always owning either zero or one shares of stock, and buying at most k shares over the course of the n-day trading period. Examples Input 10 2 2 7 3 9 8 7 9 7 1 9 Output 15 Input 10 5 2 7 3 9 8 7 9 7 1 9 Output 21 Note In the first example, the best trade overall is to buy at a price of 1 on day 9 and sell at a price of 9 on day 10 and the second best trade overall is to buy at a price of 2 on day 1 and sell at a price of 9 on day 4. Since these two trades do not overlap, both can be made and the profit is the sum of the profits of the two trades. Thus the trade strategy looks like this: 2 | 7 | 3 | 9 | 8 | 7 | 9 | 7 | 1 | 9 buy | | | sell | | | | | buy | sell The total profit is then (9 - 2) + (9 - 1) = 15. In the second example, even though Manao is allowed up to 5 trades there are only 4 profitable trades available. Making a fifth trade would cost Manao money so he only makes the following 4: 2 | 7 | 3 | 9 | 8 | 7 | 9 | 7 | 1 | 9 buy | sell | buy | sell | | buy | sell | | buy | sell The total profit is then (7 - 2) + (9 - 3) + (9 - 7) + (9 - 1) = 21. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long dp[3010]; long long p[3010]; int main() { int n, k; cin >> n >> k; for (int i = 1; i <= n; i++) cin >> p[i]; for (int i = 1; i <= k; i++) { long long mx = -1000000000000000000ll; long long mx2 = 0; for (int j = 1; j <= n; j++) { mx = max(mx, mx2 - p[j]); mx2 = max(mx2, dp[j]); dp[j] = mx + p[j]; } } long long ans = 0; for (int i = 1; i <= n; i++) ans = max(ans, dp[i]); cout << ans << endl; } ```
### Prompt Create a solution in CPP for the following problem: During the archaeological research in the Middle East you found the traces of three ancient religions: First religion, Second religion and Third religion. You compiled the information on the evolution of each of these beliefs, and you now wonder if the followers of each religion could coexist in peace. The Word of Universe is a long word containing the lowercase English characters only. At each moment of time, each of the religion beliefs could be described by a word consisting of lowercase English characters. The three religions can coexist in peace if their descriptions form disjoint subsequences of the Word of Universe. More formally, one can paint some of the characters of the Word of Universe in three colors: 1, 2, 3, so that each character is painted in at most one color, and the description of the i-th religion can be constructed from the Word of Universe by removing all characters that aren't painted in color i. The religions however evolve. In the beginning, each religion description is empty. Every once in a while, either a character is appended to the end of the description of a single religion, or the last character is dropped from the description. After each change, determine if the religions could coexist in peace. Input The first line of the input contains two integers n, q (1 ≤ n ≤ 100 000, 1 ≤ q ≤ 1000) — the length of the Word of Universe and the number of religion evolutions, respectively. The following line contains the Word of Universe — a string of length n consisting of lowercase English characters. Each of the following line describes a single evolution and is in one of the following formats: * + i c (i ∈ \{1, 2, 3\}, c ∈ \{a, b, ..., z\}: append the character c to the end of i-th religion description. * - i (i ∈ \{1, 2, 3\}) – remove the last character from the i-th religion description. You can assume that the pattern is non-empty. You can assume that no religion will have description longer than 250 characters. Output Write q lines. The i-th of them should be YES if the religions could coexist in peace after the i-th evolution, or NO otherwise. You can print each character in any case (either upper or lower). Examples Input 6 8 abdabc + 1 a + 1 d + 2 b + 2 c + 3 a + 3 b + 1 c - 2 Output YES YES YES YES YES YES NO YES Input 6 8 abbaab + 1 a + 2 a + 3 a + 1 b + 2 b + 3 b - 1 + 2 z Output YES YES YES YES YES NO YES NO Note In the first example, after the 6th evolution the religion descriptions are: ad, bc, and ab. The following figure shows how these descriptions form three disjoint subsequences of the Word of Universe: <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, q; string w, r[3]; int dp[251][251][251], next_oc[100002][26]; void compute(int a, int b, int c) { int &val = dp[a][b][c]; val = n; if (a) val = min(val, next_oc[dp[a - 1][b][c] + 1][r[0][a - 1] - 'a']); if (b) val = min(val, next_oc[dp[a][b - 1][c] + 1][r[1][b - 1] - 'a']); if (c) val = min(val, next_oc[dp[a][b][c - 1] + 1][r[2][c - 1] - 'a']); } int main() { cin >> n >> q >> w; for (int i = 0; i < 26; i++) next_oc[n][i] = next_oc[n + 1][i] = n; for (int i = n - 1; i >= 0; i--) for (int j = 0; j < 26; j++) next_oc[i][j] = w[i] == 'a' + j ? i : next_oc[i + 1][j]; dp[0][0][0] = -1; int mx[3], mn[3]; while (q--) { int id; char c, flag; cin >> flag >> id; id--; if (flag == '+') { cin >> c; r[id] += c; for (int i = 0; i < 3; i++) mx[i] = r[i].size(); for (int i = 0; i < 3; i++) mn[i] = id == i ? mx[i] : 0; for (int i = mn[0]; i <= mx[0]; i++) for (int j = mn[1]; j <= mx[1]; j++) for (int k = mn[2]; k <= mx[2]; k++) compute(i, j, k); } else { r[id].pop_back(); } if (dp[r[0].size()][r[1].size()][r[2].size()] < n) puts("Yes"); else puts("No"); } } ```
### Prompt Please provide a cpp coded solution to the problem described below: Seen from above, there is a grid-like square shaped like Figure 1. The presence or absence of "walls" on each side of this grid is represented by a sequence of 0s and 1s. Create a program that stands at point A, puts your right hand on the wall, keeps walking in the direction of the arrow, and outputs the route to return to point A again. <image> --- Figure 1 --- Input The input consists of 9 lines and is given in the following format, with 1 being the presence of a wall and 0 being the absence of a wall, as shown in Figure 2 below. The first line is a character string that indicates the presence or absence of the top horizontal line wall as 0 and 1 from the left. The second line is a character string that indicates the presence or absence of the vertical line wall below it with 0 and 1 from the left. The third line is a character string that indicates the presence or absence of the wall of the second horizontal line from the top by 0 and 1 from the left. ... The 9th line is a character string representing the presence or absence of the bottom horizontal line wall with 0 and 1 from the left. <image> --- Figure 2 (Thick line shows where the wall is) (corresponding numbers) However, as shown by the thick line in Fig. 1, it is assumed that there is always a wall for one section to the right of point A. That is, the first character on the first line is always 1. Output "Advance one section to the left of the figure" is "L", "Advance one section to the right of the figure" is "R", "Advance one section to the top of the figure" is "U", "Figure" "Advance one block downward" is represented by "D", and "L", "R", "U", and "D" are output in the order of advance. Example Input 1111 00001 0110 01011 0010 01111 0010 01001 0111 Output RRRRDDDDLLLUUURRDDLURULLDDDRRRUUUULLLL ### Response ```cpp #include<stdio.h> int f[5][5],i,j,a,y,x,p; int main() { for(;i<9;++i){ char s[6]; scanf("%s",s); for(j=0;j<4+i%2;++j){ a=s[j]-48; f[i/2][j]|=a<<(1+i%2); f[i/2+i%2][j+!(i%2)]|=a<<3-i%2*3; } } do{ do p=(p+1)%4; while(!((f[y][x]>>p)&1)); putchar("URDL"[p]); x+=p?2-p:0; y+=p==3?0:p-1; p=(p+2)%4; }while(y!=0||x!=0||f[0][0]==6&&p==3); return !puts(""); } ```
### Prompt Generate a Cpp solution to the following problem: During the chemistry lesson Andrew learned that the saturated hydrocarbons (alkanes) enter into radical chlorination reaction. Andrew is a very curious boy, so he wondered how many different products of the reaction may be forms for a given alkane. He managed to solve the task for small molecules, but for large ones he faced some difficulties and asks you to help. Formally, you are given a tree consisting of n vertices, such that the degree of each vertex doesn't exceed 4. You have to count the number of distinct non-isomorphic trees that can be obtained by adding to this tree one new vertex and one new edge, such that the graph is still the tree and the degree of each vertex doesn't exceed 4. Two trees are isomorphic if there exists a bijection f(v) such that vertices u and v are connected by an edge if and only if vertices f(v) and f(u) are connected by an edge. Input The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the number of vertices in the tree. Then follow n - 1 lines with edges descriptions. Each edge is given by two integers ui and vi (1 ≤ ui, vi ≤ n) — indices of vertices connected by an edge. It's guaranteed that the given graph is a tree and the degree of each vertex doesn't exceed 4. Output Print one integer — the answer to the question. Examples Input 4 1 2 2 3 2 4 Output 2 Input 5 1 2 1 3 1 4 1 5 Output 1 Input 5 2 5 5 3 4 3 4 1 Output 3 Note In the first sample, one can add new vertex to any existing vertex, but the trees we obtain by adding a new vertex to vertices 1, 3 and 4 are isomorphic, thus the answer is 2. In the second sample, one can't add new vertex to the first vertex, as its degree is already equal to four. Trees, obtained by adding a new vertex to vertices 2, 3, 4 and 5 are isomorphic, thus the answer is 1. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 200000 + 10; const int inf = 0x3f3f3f3f; const long long mod = 1000000007; int n, cnt; vector<int> e[N]; map<vector<int>, int> H; map<int, int> mp[N]; set<int> st; int dp(int x, int fa) { if (mp[x][fa]) return mp[x][fa]; vector<int> cur; for (int i = 0; i < e[x].size(); i++) { if (e[x][i] != fa) { cur.push_back(dp(e[x][i], x)); } } sort(cur.begin(), cur.end()); if (!H[cur]) H[cur] = ++cnt; return mp[x][fa] = H[cur]; } int main() { scanf("%d", &n); for (int i = 1; i <= n - 1; i++) { int u, v; scanf("%d%d", &u, &v); e[u].push_back(v), e[v].push_back(u); } for (int i = 1; i <= n; i++) if (e[i].size() < 4) st.insert(dp(i, 0)); printf("%d", st.size()); return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: You have decided to write a book introducing good restaurants. There are N restaurants that you want to introduce: Restaurant 1, Restaurant 2, ..., Restaurant N. Restaurant i is in city S_i, and your assessment score of that restaurant on a 100-point scale is P_i. No two restaurants have the same score. You want to introduce the restaurants in the following order: * The restaurants are arranged in lexicographical order of the names of their cities. * If there are multiple restaurants in the same city, they are arranged in descending order of score. Print the identification numbers of the restaurants in the order they are introduced in the book. Constraints * 1 ≤ N ≤ 100 * S is a string of length between 1 and 10 (inclusive) consisting of lowercase English letters. * 0 ≤ P_i ≤ 100 * P_i is an integer. * P_i ≠ P_j (1 ≤ i < j ≤ N) Input Input is given from Standard Input in the following format: N S_1 P_1 : S_N P_N Output Print N lines. The i-th line (1 ≤ i ≤ N) should contain the identification number of the restaurant that is introduced i-th in the book. Examples Input 6 khabarovsk 20 moscow 10 kazan 50 kazan 35 moscow 60 khabarovsk 40 Output 3 4 6 1 5 2 Input 10 yakutsk 10 yakutsk 20 yakutsk 30 yakutsk 40 yakutsk 50 yakutsk 60 yakutsk 70 yakutsk 80 yakutsk 90 yakutsk 100 Output 10 9 8 7 6 5 4 3 2 1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main(){ int N; cin>>N; vector<tuple<string,int,int>> B; for(int i=0;i<N;i++){ string s; int p; cin>>s>>p; B.push_back(make_tuple(s,-p,i+1)); } sort(B.begin(),B.end()); for(int i=0;i<N;i++){ cout<<get<2>(B.at(i))<<endl; } } ```
### Prompt Create a solution in CPP for the following problem: Alex, Bob and Carl will soon participate in a team chess tournament. Since they are all in the same team, they have decided to practise really hard before the tournament. But it's a bit difficult for them because chess is a game for two players, not three. So they play with each other according to following rules: * Alex and Bob play the first game, and Carl is spectating; * When the game ends, the one who lost the game becomes the spectator in the next game, and the one who was spectating plays against the winner. Alex, Bob and Carl play in such a way that there are no draws. Today they have played n games, and for each of these games they remember who was the winner. They decided to make up a log of games describing who won each game. But now they doubt if the information in the log is correct, and they want to know if the situation described in the log they made up was possible (that is, no game is won by someone who is spectating if Alex, Bob and Carl play according to the rules). Help them to check it! Input The first line contains one integer n (1 ≤ n ≤ 100) — the number of games Alex, Bob and Carl played. Then n lines follow, describing the game log. i-th line contains one integer ai (1 ≤ ai ≤ 3) which is equal to 1 if Alex won i-th game, to 2 if Bob won i-th game and 3 if Carl won i-th game. Output Print YES if the situation described in the log was possible. Otherwise print NO. Examples Input 3 1 1 2 Output YES Input 2 1 2 Output NO Note In the first example the possible situation is: 1. Alex wins, Carl starts playing instead of Bob; 2. Alex wins, Bob replaces Carl; 3. Bob wins. The situation in the second example is impossible because Bob loses the first game, so he cannot win the second one. ### Response ```cpp #include <bits/stdc++.h> using namespace std; vector<long long> v; vector<string> str; string s; char c; int dp[1]; long long n, z, k, nab; int main() { cin >> n; nab = 3; for (int i = 0; i < n; i++) { cin >> z; if (z != nab) { if (nab == 1 && z == 2) { nab = 3; } else { if (nab == 2 && z == 3) { nab = 1; } else { if (nab == 1 && z == 3) { nab = 2; } else { if (nab == 2 && z == 1) { nab = 3; } else { if (nab == 3 && z == 2) { nab = 1; } else { if (nab == 3 && z == 1) { nab = 2; } } } } } } } else { cout << "NO"; return 0; } } cout << "YES"; return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: There are n cities in the country of Berland. Some of them are connected by bidirectional roads in such a way that there exists exactly one path, which visits each road no more than once, between every pair of cities. Each road has its own length. Cities are numbered from 1 to n. The travelling time between some cities v and u is the total length of the roads on the shortest path from v to u. The two most important cities in Berland are cities 1 and n. The Berland Ministry of Transport decided to build a single new road to decrease the traffic between the most important cities. However, lots of people are used to the current travelling time between the most important cities, so the new road shouldn't change it too much. The new road can only be built between such cities v and u that v ≠ u and v and u aren't already connected by some road. They came up with m possible projects. Each project is just the length x of the new road. Polycarp works as a head analyst at the Berland Ministry of Transport and it's his job to deal with all those m projects. For the i-th project he is required to choose some cities v and u to build the new road of length x_i between such that the travelling time between the most important cities is maximal possible. Unfortunately, Polycarp is not a programmer and no analyst in the world is capable to process all projects using only pen and paper. Thus, he asks you to help him to calculate the maximal possible travelling time between the most important cities for each project. Note that the choice of v and u can differ for different projects. Input The first line contains two integers n and m (3 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ m ≤ 3 ⋅ 10^5) — the number of cities and the number of projects, respectively. Each of the next n - 1 lines contains three integers v_i, u_i and w_i (1 ≤ v_i, u_i ≤ n, 1 ≤ w_i ≤ 10^9) — the description of the i-th road. It is guaranteed that there exists exactly one path, which visits each road no more than once, between every pair of cities. Each of the next m lines contains a single integer x_j (1 ≤ x_j ≤ 10^9) — the length of the road for the j-th project. Output Print m lines, the j-th line should contain a single integer — the maximal possible travelling time between the most important cities for the j-th project. Example Input 7 2 1 2 18 2 3 22 3 4 24 4 7 24 2 6 4 3 5 12 1 100 Output 83 88 Note The road network from the first example: <image> You can build the road with length 1 between cities 5 and 6 to get 83 as the travelling time between 1 and 7 (1 → 2 → 6 → 5 → 3 → 4 → 7 = 18 + 4 + 1 + 12 + 24 + 24 = 83). Other possible pairs of cities will give answers less or equal to 83. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int N, M; vector<pair<int, int> > conn[303030]; long long d1[303030], dN[303030]; void dfs(int a, int p, long long* d, long long w) { d[a] = w; for (auto [x, ww] : conn[a]) if (x != p) dfs(x, a, d, w + ww); } int main() { scanf("%d%d", &N, &M); for (int i = 0; i < N - 1; ++i) { int u, v, w; scanf("%d%d%d", &u, &v, &w); conn[u].emplace_back(v, w); conn[v].emplace_back(u, w); } dfs(1, 0, d1, 0); dfs(N, 0, dN, 0); vector<int> ord(N); iota(ord.begin(), ord.end(), 1); sort(ord.begin(), ord.end(), [&](int a, int b) { return d1[a] - dN[a] > d1[b] - dN[b]; }); set<pair<long long, int> > S; long long ans = 0; for (auto v : ord) { vector<pair<long long, int> > te; for (auto [x, _] : conn[v]) { auto qq = make_pair(dN[x], x); if (S.count(qq)) { te.push_back(qq); S.erase(qq); } } if (S.size()) ans = max(ans, d1[v] + S.rbegin()->first); for (auto qq : te) S.insert(qq); S.emplace(dN[v], v); } while (M--) { int t; scanf("%d", &t); printf("%lld\n", min(ans + t, d1[N])); } } ```
### Prompt Please provide a CPP coded solution to the problem described below: Welcome to PC Koshien, players. This year marks the 10th anniversary of Computer Koshien, but the number of questions and the total score will vary from year to year. Scores are set for each question according to the difficulty level. When the number of questions is 10 and the score of each question is given, create a program that outputs the total of them. input The input is given in the following format. s1 s2 .. .. s10 The input consists of 10 lines, and the i line is given the integer si (0 ≤ si ≤ 100) representing the score of problem i. output Output the total score on one line. Example Input 1 2 3 4 5 6 7 8 9 10 Output 55 ### Response ```cpp #include<cstdio> using namespace std; int main() { int i,s,sum; sum=0; for(i=0;i<10;i++){ scanf("%d",&s); sum+=s; } printf("%d\n",sum); return 0; } ```
### Prompt Please provide a CPP coded solution to the problem described below: Mike has a string s consisting of only lowercase English letters. He wants to change exactly one character from the string so that the resulting one is a palindrome. A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforces", "reality", "ab" are not. Input The first and single line contains string s (1 ≤ |s| ≤ 15). Output Print "YES" (without quotes) if Mike can change exactly one character so that the resulting string is palindrome or "NO" (without quotes) otherwise. Examples Input abccaa Output YES Input abbcca Output NO Input abcda Output YES ### Response ```cpp #include <bits/stdc++.h> using namespace std; string s; int cnt; int main() { cin >> s; for (int i = 0; i * 2 < s.size(); i++) if (s[i] != s[s.size() - i - 1]) cnt++; if (cnt == 1 || (cnt == 0 && s.size() % 2 == 1)) cout << "YES"; else cout << "NO"; return 0; } ```
### Prompt Your challenge is to write a CPP solution to the following problem: Welcome to the world of Pokermon, yellow little mouse-like creatures, who absolutely love playing poker! Yeah, right… In the ensuing Pokermon League, there are n registered Pokermon trainers, and t existing trainer teams each of which belongs to one of two conferences. Since there is a lot of jealousy between trainers, there are e pairs of trainers who hate each other. Their hate is mutual, there are no identical pairs among these, and no trainer hates himself (the world of Pokermon is a joyful place!). Each trainer has a wish-list of length li of teams he’d like to join. Your task is to divide players into teams and the teams into two conferences, so that: * each trainer belongs to exactly one team; * no team is in both conferences; * total hate between conferences is at least e / 2; * every trainer is in a team from his wish-list. Total hate between conferences is calculated as the number of pairs of trainers from teams from different conferences who hate each other. Input The first line of the input contains two integer n (4 ≤ n ≤ 50 000) and e (2 ≤ e ≤ 100 000) — the total number of Pokermon trainers and the number of pairs of trainers who hate each other. Pokermon trainers are numbered from 1 to n. Next e lines contain two integers a and b (1 ≤ a, b ≤ n) indicating that Pokermon trainers a and b hate each other. Next 2n lines are in a following format. Starting with Pokermon trainer 1, for each trainer in consecutive order: first number li (16 ≤ li ≤ 20) — a size of Pokermon trainers wish list, then li positive integers ti, j (1 ≤ ti, j ≤ T), providing the teams the i-th trainer would like to be on. Each trainers wish list will contain each team no more than once. Teams on the wish lists are numbered in such a way that the set of all teams that appear on at least 1 wish list is set of consecutive positive integers {1, 2, 3, …, T}. Here T might be up to 1 000 000. Output Print two lines. The first line should contain n numbers, specifying for each trainer the team he is in. The second line should contain T numbers, specifying the conference for each team (1 or 2). Example Input 4 3 1 2 2 3 4 1 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 16 15 16 2 3 4 5 6 7 8 9 10 11 12 13 14 15 17 18 16 2 3 4 5 6 7 8 9 10 11 12 13 14 15 18 19 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 16 19 Output 16 15 19 14 2 2 2 1 1 1 2 1 1 2 1 1 1 2 2 1 1 1 1 Note ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 50010; mt19937 rnd; int n, e; vector<int> l[MAXN]; vector<int> g[MAXN]; int team[MAXN]; int to[20 * MAXN], nxt[20 * MAXN], head[MAXN * 20], E, sz[20 * MAXN]; int color[MAXN * 20]; void addEdge(int a, int b) { sz[a]++; to[E] = b; nxt[E] = head[a]; head[a] = E++; } void paint(int v, int col = 1) { color[v] = col; for (int id = head[v]; ~id; id = nxt[id]) { if (!color[to[id]]) { paint(to[id], 3 - col); } } } bool good() { int res = 0; vector<int> teams; for (int i = 0; i < n; ++i) { teams.push_back(team[i]); } sort(teams.begin(), teams.end()); teams.erase(unique(teams.begin(), teams.end()), teams.end()); for (auto x : teams) { for (int id = head[x]; ~id; id = nxt[id]) { res += color[x] != color[to[id]]; } } return res >= e; } bool solve() { E = 0; for (int i = 0; i < n; ++i) { head[team[i]] = -1; sz[team[i]] = 0; color[team[i]] = 0; } for (int i = 0; i < n; ++i) { for (int to : g[i]) { if (team[i] != team[to]) addEdge(team[i], team[to]); } } int mx = -1; for (int i = 0; i < n; ++i) { mx = max(mx, sz[team[i]]); } for (int i = 0; i < n; ++i) { if (sz[team[i]] == mx) { paint(team[i]); return good(); } } } int main() { double start = clock(); ios_base::sync_with_stdio(false); cin.tie(0); cin >> n >> e; for (int i = 0, a, b; i < e; ++i) { cin >> a >> b; a--; b--; g[a].push_back(b); g[b].push_back(a); } rnd = mt19937(565345646); int T = 0; for (int i = 0, k; i < n; ++i) { cin >> k; l[i].resize(k); for (int j = 0; j < k; ++j) { cin >> l[i][j]; T = max(T, l[i][j]); } } do { for (int i = 0; i < n; ++i) { team[i] = l[i][rnd() % l[i].size()]; } } while (!solve()); for (int i = 0; i < n; ++i) { cout << team[i] << ' '; } cout << '\n'; for (int i = 1; i <= T; ++i) { cout << max(1, color[i]) << ' '; } clog << (clock() - start) / CLOCKS_PER_SEC << endl; return 0; } ```
### Prompt Please create a solution in CPP to the following problem: You are given plans of rooms of polygonal shapes. The walls of the rooms on the plans are placed parallel to either x-axis or y-axis. In addition, the walls are made of special materials so they reflect light from sources as mirrors do, but only once. In other words, the walls do not reflect light already reflected at another point of the walls. Now we have each room furnished with one lamp. Walls will be illuminated by the lamp directly or indirectly. However, since the walls reflect the light only once, some part of the walls may not be illuminated. You are requested to write a program that calculates the total length of unilluminated part of the walls. <image> Figure 10: The room given as the second case in Sample Input Input The input consists of multiple test cases. The first line of each case contains a single positive even integer N (4 ≤ N ≤ 20), which indicates the number of the corners. The following N lines describe the corners counterclockwise. The i-th line contains two integers xi and yi , where (xi , yi ) indicates the coordinates of the i-th corner. The last line of the case contains x' and y' , where (x' , y' ) indicates the coordinates of the lamp. To make the problem simple, you may assume that the input meets the following conditions: * All coordinate values are integers not greater than 100 in their absolute values. * No two walls intersect or touch except for their ends. * The walls do not intersect nor touch each other. * The walls turn each corner by a right angle. * The lamp exists strictly inside the room off the wall. * The x-coordinate of the lamp does not coincide with that of any wall; neither does the y-coordinate. The input is terminated by a line containing a single zero. Output For each case, output the length of the unilluminated part in one line. The output value may have an arbitrary number of decimal digits, but may not contain an error greater than 10-3 . Example Input 4 0 0 2 0 2 2 0 2 1 1 6 2 2 2 5 0 5 0 0 5 0 5 2 1 4 0 Output 0.000 3.000 ### Response ```cpp #include<bits/stdc++.h> #define REP(i,s,n) for(int i=s;i<n;i++) #define rep(i,n) REP(i,0,n) #define EPS (1e-6) #define COUNTER_CLOCKWISE 1 #define CLOCKWISE -1 #define ONLINE_BACK 2 #define ONLINE_FRONT -2 #define ON_SEGMENT 0 #define equals(a,b) (fabs((a)-(b)) < EPS) using namespace std; class Point{ public: double x,y; Point(double x = 0,double y = 0): x(x),y(y){} Point operator + (Point p){return Point(x+p.x,y+p.y);} Point operator - (Point p){return Point(x-p.x,y-p.y);} Point operator * (double a){return Point(a*x,a*y);} Point operator / (double a){return Point(x/a,y/a);} Point operator * (Point a){ return Point(x * a.x - y * a.y, x * a.y + y * a.x); } bool operator < (const Point& p) const{ return !equals(x,p.x)?x<p.x:(!equals(y,p.y)&&y<p.y); } bool operator == (const Point& p)const{ return fabs(x-p.x) < EPS && fabs(y-p.y) < EPS; } }; struct Segment{ Point p1,p2; Segment(Point p1 = Point(),Point p2 = Point()):p1(p1),p2(p2){} bool operator < (const Segment& s)const { return (p1==s.p1) ? p2 < s.p2 : p1 < s.p1; } bool operator == (const Segment& p)const { return ( p.p1 == p1 && p.p2 == p2 ) || ( p.p1 == p2 && p.p2 == p1 ); } }; typedef Point Vector; typedef Segment Line; typedef vector<Point> Polygon; double dot(Point a,Point b){ return a.x*b.x + a.y*b.y; } double cross(Point a,Point b){ return a.x*b.y - a.y*b.x; } double norm(Point a){ return a.x*a.x+a.y*a.y; } double abs(Point a){ return sqrt(norm(a)); } int ccw(Point p0,Point p1,Point p2){ Point a = p1-p0; Point b = p2-p0; if(cross(a,b) > EPS)return COUNTER_CLOCKWISE; if(cross(a,b) < -EPS)return CLOCKWISE; if(dot(a,b) < -EPS)return ONLINE_BACK; if(norm(a) < norm(b))return ONLINE_FRONT; return ON_SEGMENT; } bool intersectSS(Line s, Line t) { return ccw(s.p1,s.p2,t.p1)*ccw(s.p1,s.p2,t.p2) <= 0 && ccw(t.p1,t.p2,s.p1)*ccw(t.p1,t.p2,s.p2) <= 0; } Point projection(Line l,Point p) { double t = dot(p-l.p1, l.p1-l.p2) / norm(l.p1-l.p2); return l.p1 + (l.p1-l.p2)*t; } Point reflection(Line l,Point p) { return p + (projection(l, p) - p) * 2; } Point crosspoint(Line l,Line m){ double A = cross(l.p2-l.p1,m.p2-m.p1); double B = cross(l.p2-l.p1,l.p2-m.p1); if(abs(A) < EPS && abs(B) < EPS){ vector<Point> vec; vec.push_back(l.p1),vec.push_back(l.p2),vec.push_back(m.p1),vec.push_back(m.p2); sort(vec.begin(),vec.end()); return vec[1]; } if(abs(A) < EPS)assert(false); return m.p1 + (m.p2-m.p1)*(B/A); } double cross3p(Point p,Point q,Point r) { return (r.x-q.x) * (p.y -q.y) - (r.y - q.y) * (p.x - q.x); } bool collinear(Point p,Point q,Point r) { return fabs(cross3p(p,q,r)) < EPS; } bool onSegment(Point p,Point q,Point r){ return collinear(p,q,r) && equals(sqrt(pow(p.x-r.x,2)+pow(p.y-r.y,2)) + sqrt(pow(r.x-q.x,2) + pow(r.y-q.y,2) ),sqrt(pow(p.x-q.x,2)+pow(p.y-q.y,2)) ) ; } double angle(Point a,Point b,Point c) { double ux = b.x - a.x, uy = b.y - a.y; double vx = c.x - a.x, vy = c.y - a.y; return acos((ux*vx + uy*vy)/sqrt((ux*ux + uy*uy) * (vx*vx + vy*vy))); } //多角形poly内(線分上も含む)に点pが存在するかどうは判定する bool inPolygon(Polygon poly,Point p){ if((int)poly.size() == 0)return false; rep(i,poly.size()) if(onSegment(poly[i],poly[(i+1)%poly.size()],p))return true; double sum = 0; for(int i=0; i < (int)poly.size() ;i++) { if( equals(cross(poly[i]-p,poly[(i+1)%poly.size()]-p),0.0) ) continue; // 3点が平行だとangleがnanを返しsumがnanになり死ぬ if( cross3p(p,poly[i],poly[(i+1)%poly.size()]) < 0 ) sum -= angle(p,poly[i],poly[(i+1)%poly.size()]); else sum += angle(p,poly[i],poly[(i+1)%poly.size()]); } // あまり誤差を厳しくしすぎると良くないので以下のほうが良い const double eps = 1e-5; return (fabs(sum - 2*M_PI) < eps || fabs(sum + 2*M_PI) < eps); } bool inPolygon(const Polygon &poly,Segment seg){ vector<Point> vp; vp.push_back(seg.p1); vp.push_back(seg.p2); rep(i,(int)poly.size()) { Segment edge = Segment(poly[i],poly[(i+1)%(int)poly.size()]); if( equals(cross(seg.p1-seg.p2,edge.p1-edge.p2),0.0) ) { if( onSegment(seg.p1,seg.p2,edge.p1) ) vp.push_back(edge.p1); if( onSegment(seg.p1,seg.p2,edge.p2) ) vp.push_back(edge.p2); } else { if( intersectSS(seg,edge) ) vp.push_back(crosspoint(seg,edge)); } } sort(vp.begin(),vp.end()); vp.erase(unique(vp.begin(),vp.end()),vp.end()); rep(i,(int)vp.size()-1) { Point middle_point = ( vp[i] + vp[i+1] ) / 2.0; if( !inPolygon(poly,middle_point) ) return false; } return true; } int V; Polygon poly; Point light; // type 0 => =w=, type 1 => mirror void inner_add_new_points(Polygon &pol,vector<Point> &vp,int type,Line ref){ rep(i,V){ // ライトから普通のポリゴンの角をみる Vector e = ( poly[i] - light ) / abs( poly[i] - light ); Segment seg = Segment(light,light+e*10000); rep(j,V) { Segment poly_seg = Segment(pol[j],pol[(j+1)%V]); if( equals(cross(seg.p2-seg.p1,poly_seg.p2-poly_seg.p1),0.0) ) continue; if( intersectSS(poly_seg,seg) ) { if( !type ) vp.push_back(crosspoint(poly_seg,seg)); else vp.push_back(reflection(ref,crosspoint(poly_seg,seg))); } } // ライトから反転したポリゴンの角をみる e = ( pol[i] - light ) / abs( pol[i] - light ); seg = Segment(light,light+e*10000); rep(j,V) { Segment poly_seg = Segment(pol[j],pol[(j+1)%V]); if( equals(cross(seg.p2-seg.p1,poly_seg.p2-poly_seg.p1),0.0) ) continue; if( intersectSS(poly_seg,seg) ) { if( !type ) vp.push_back(crosspoint(poly_seg,seg)); else vp.push_back(reflection(ref,crosspoint(poly_seg,seg))); } } } } bool LT(double a,double b) { return !equals(a,b) && a < b; } bool LTE(double a,double b) { return equals(a,b) || a < b; } Point vir; bool comp_dist(const Point& p1,const Point& p2){ return LT(abs(vir-p1),abs(vir-p2)); } void add_new_points(Polygon &new_poly){ vector<Point> vp; inner_add_new_points(poly,vp,0,Line()); rep(i,V){ Line ref = Line(poly[i],poly[(i+1)%V]); Polygon rpoly(V); rep(j,V) { rpoly[j] = reflection(ref,poly[j]); if( equals(rpoly[j].x,0.0) ) rpoly[j].x = 0; if( equals(rpoly[j].y,0.0) ) rpoly[j].y = 0; } inner_add_new_points(rpoly,vp,1,ref); } rep(i,(int)vp.size()) { if( equals(vp[i].x,0.0) ) vp[i].x = 0; if( equals(vp[i].y,0.0) ) vp[i].y = 0; } vector<Point> tmp; rep(i,vp.size()) { bool failed = false; rep(j,V) if( vp[i] == poly[j] ) { failed = true; break; } if( !failed ) tmp.push_back(vp[i]); } vp = tmp; sort(vp.begin(),vp.end()); vp.erase(unique(vp.begin(),vp.end()),vp.end()); rep(i,V){ vector<Point> buf; Segment seg = Segment(poly[i],poly[(i+1)%V]); rep(j,(int)vp.size()) if( onSegment(seg.p1,seg.p2,vp[j]) ) buf.push_back(vp[j]); vir = seg.p1; sort(buf.begin(),buf.end(),comp_dist); rep(j,(int)buf.size()) new_poly.push_back(buf[j]); new_poly.push_back(seg.p2); } } void compute_saw(Polygon &npoly,bool *saw){ int nV = npoly.size(); // 直接見れる rep(i,nV) { Point mp = ( npoly[i] + npoly[(i+1)%nV] ) / 2.0; Segment vline = Segment(light,mp); bool failed = false; rep(j,V) { Segment seg = Segment(poly[j],poly[(j+1)%V]); if( equals(cross(seg.p1-seg.p2,vline.p1-vline.p2),0.0) ) continue; if( intersectSS(seg,vline) ) { if( onSegment(seg.p1,seg.p2,vline.p1) || onSegment(seg.p1,seg.p2,vline.p2) ) continue; if( onSegment(vline.p1,vline.p2,seg.p1) || onSegment(vline.p1,vline.p2,seg.p2) ) continue; failed = true; break; } } if( failed ) continue; saw[i] = true; } // 鏡一枚で見れる // 直接見える鏡だけを列挙 vector<Line> ref; rep(i,nV) { Point mp = ( npoly[i] + npoly[(i+1)%nV] ) / 2.0; Segment vline = Segment(light,mp); bool failed = false; rep(j,V) { Segment seg = Segment(poly[j],poly[(j+1)%V]); if( equals(cross(seg.p1-seg.p2,vline.p1-vline.p2),0.0) ) continue; if( intersectSS(seg,vline) ) { if( onSegment(seg.p1,seg.p2,vline.p1) || onSegment(seg.p1,seg.p2,vline.p2) ) continue; if( onSegment(vline.p1,vline.p2,seg.p1) || onSegment(vline.p1,vline.p2,seg.p2) ) continue; failed = true; break; } } if( !failed ) ref.push_back(Line(npoly[i],npoly[(i+1)%nV])); } vector<Polygon> ref_polies; rep(i,(int)ref.size()){ Polygon tmp_poly; rep(j,(int)poly.size()) tmp_poly.push_back(reflection(ref[i],poly[j])); ref_polies.push_back(tmp_poly); } rep(i,nV) if( !saw[i] ) { rep(j,(int)ref.size()){ Segment rev_edge = Segment(reflection(ref[j],npoly[i]),reflection(ref[j],npoly[(i+1)%nV])); Point rev_mp = ( rev_edge.p1 + rev_edge.p2 ) / 2.0; Segment rev_vline = Segment(light,rev_mp); if( equals(cross(rev_vline.p1-rev_vline.p2,ref[j].p1-ref[j].p2),0.0) ) continue; if( !intersectSS(rev_vline,ref[j]) ) continue; rev_vline.p1 = crosspoint(rev_vline,ref[j]); if( inPolygon(ref_polies[j],rev_vline) ) { saw[i] = true; break; } } } } void compute(){ Polygon npoly; add_new_points(npoly); int nV = npoly.size(); bool saw[nV]; rep(i,nV) saw[i] = false; compute_saw(npoly,saw); double sum = 0; rep(i,nV) if( !saw[i] )sum += abs(npoly[(i+1)%nV]-npoly[i]); sum = fabs(sum); printf("%.10lf\n",sum); } int main(){ while( cin >> V, V ){ poly.resize(V); rep(i,V) cin >> poly[i].x >> poly[i].y; cin >> light.x >> light.y; compute(); } return 0; } ```
### Prompt Generate a Cpp solution to the following problem: Every evening Vitalya sets n alarm clocks to wake up tomorrow. Every alarm clock rings during exactly one minute and is characterized by one integer ai — number of minute after midnight in which it rings. Every alarm clock begins ringing at the beginning of the minute and rings during whole minute. Vitalya will definitely wake up if during some m consecutive minutes at least k alarm clocks will begin ringing. Pay attention that Vitalya considers only alarm clocks which begin ringing during given period of time. He doesn't consider alarm clocks which started ringing before given period of time and continues ringing during given period of time. Vitalya is so tired that he wants to sleep all day long and not to wake up. Find out minimal number of alarm clocks Vitalya should turn off to sleep all next day. Now all alarm clocks are turned on. Input First line contains three integers n, m and k (1 ≤ k ≤ n ≤ 2·105, 1 ≤ m ≤ 106) — number of alarm clocks, and conditions of Vitalya's waking up. Second line contains sequence of distinct integers a1, a2, ..., an (1 ≤ ai ≤ 106) in which ai equals minute on which i-th alarm clock will ring. Numbers are given in arbitrary order. Vitalya lives in a Berland in which day lasts for 106 minutes. Output Output minimal number of alarm clocks that Vitalya should turn off to sleep all next day long. Examples Input 3 3 2 3 5 1 Output 1 Input 5 10 3 12 8 18 25 1 Output 0 Input 7 7 2 7 3 4 1 6 5 2 Output 6 Input 2 2 2 1 3 Output 0 Note In first example Vitalya should turn off first alarm clock which rings at minute 3. In second example Vitalya shouldn't turn off any alarm clock because there are no interval of 10 consequence minutes in which 3 alarm clocks will ring. In third example Vitalya should turn off any 6 alarm clocks. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, m, k, i, a[222222]; int main() { cin >> n >> m >> k; for (i = 1; i <= n; ++i) cin >> a[i]; sort(a + 1, a + 1 + n); for (i = 1; i <= n; ++i) if (*a + a - upper_bound(a + 1, a + 1 + *a, a[i] - m) + 2 < k) a[++*a] = a[i]; cout << n - *a << endl; } ```
### Prompt Your challenge is to write a CPP solution to the following problem: There are many caves deep in mountains found in the countryside. In legend, each cave has a treasure hidden within the farthest room from the cave's entrance. The Shogun has ordered his Samurais to explore these caves with Karakuri dolls (robots) and to find all treasures. These robots move in the caves and log relative distances and directions between rooms. Each room in a cave is mapped to a point on an integer grid (x, y >= 0). For each cave, the robot always starts from its entrance, runs along the grid and returns to the entrance (which also serves as the exit). The treasure in each cave is hidden in the farthest room from the entrance, using Euclid distance for measurement, i.e. the distance of the room at point (x, y) from the entrance (0, 0) is defined as the square root of (x*x+y*y). If more than one room has the same farthest distance from the entrance, the treasure is hidden in the room having the greatest value of x. While the robot explores a cave, it records how it has moved. Each time it takes a new direction at a room, it notes the difference (dx, dy) from the last time it changed its direction. For example, suppose the robot is currently in the room at point (2, 4). If it moves to room (6, 4), the robot records (4, 0), i.e. dx=6-2 and dy=4-4. The first data is defined as the difference from the entrance. The following figure shows rooms in the first cave of the Sample Input. In the figure, the farthest room is the square root of 61 distant from the entrance. <image> Based on the records that the robots bring back, your job is to determine the rooms where treasures are hidden. Input In the first line of the input, an integer N showing the number of caves in the input is given. Integers dxi and dyi are i-th data showing the differences between rooms. Note that since the robot moves along the grid, either dxi or dyi is zero. An integer pair dxi = dyi = 0 signals the end of one cave's data which means the robot finished the exploration for the cave and returned back to the entrance. The coordinates are limited to (0,0)-(1000,1000). Output Print the position (x, y) of the treasure room on a line for each cave. Example Input 3 1 0 0 1 -1 0 1 0 0 5 -1 0 0 -1 5 0 0 1 0 -1 1 0 0 -4 -3 0 0 3 2 0 0 -2 -1 0 0 1 0 -1 1 0 0 2 -2 0 0 -3 3 0 0 4 -4 0 0 -5 -2 0 0 0 1 0 -1 0 0 0 2 0 0 1 -1 0 0 1 -1 0 0 -2 0 0 Output 6 5 1 0 2 1 ### Response ```cpp #include<iostream> #include<algorithm> #include<set> #include<map> #include<vector> #include<queue> #include<cstring> #include<cmath> #include<cstdio> #include<cstdlib> using namespace std; #define REP(i,a,n) for(int i = a ; i < n ; i++) #define rep(i,n) REP(i,0,n) typedef long long ll; void solve(){ } int main(){ int T; cin>>T; while(T--){ int x = 0, y = 0; int tx,ty; int ansX,ansY; double ans = 0; while(cin>>tx>>ty,tx||ty){ x += tx; y += ty; int dist = x*x + y*y; if(dist > ans || ans == dist && ansX < x){ ans = dist; ansX = x; ansY = y; } } cout<<ansX<<" "<<ansY<<endl; } } ```
### Prompt Please formulate a CPP solution to the following problem: You are given a string s=s_1s_2... s_n of length n, which only contains digits 1, 2, ..., 9. A substring s[l ... r] of s is a string s_l s_{l + 1} s_{l + 2} … s_r. A substring s[l ... r] of s is called even if the number represented by it is even. Find the number of even substrings of s. Note, that even if some substrings are equal as strings, but have different l and r, they are counted as different substrings. Input The first line contains an integer n (1 ≤ n ≤ 65000) — the length of the string s. The second line contains a string s of length n. The string s consists only of digits 1, 2, ..., 9. Output Print the number of even substrings of s. Examples Input 4 1234 Output 6 Input 4 2244 Output 10 Note In the first example, the [l, r] pairs corresponding to even substrings are: * s[1 ... 2] * s[2 ... 2] * s[1 ... 4] * s[2 ... 4] * s[3 ... 4] * s[4 ... 4] In the second example, all 10 substrings of s are even substrings. Note, that while substrings s[1 ... 1] and s[2 ... 2] both define the substring "2", they are still counted as different substrings. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MN = 10000001; const long MOD = 1000000007; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; string s; cin >> s; vector<int> a(n + 1); a[n] = 0; long long amount = 0; for (int i = n - 1; i >= 0; --i) { if ((s[i] - '0') % 2 == 0) { a[i] = a[i + 1] + 1; } else a[i] = a[i + 1]; amount += a[i]; } cout << amount; return 0; } ```
### Prompt Create a solution in cpp for the following problem: Vasya has decided to build a zip-line on trees of a nearby forest. He wants the line to be as long as possible but he doesn't remember exactly the heights of all trees in the forest. He is sure that he remembers correct heights of all trees except, possibly, one of them. It is known that the forest consists of n trees staying in a row numbered from left to right with integers from 1 to n. According to Vasya, the height of the i-th tree is equal to hi. The zip-line of length k should hang over k (1 ≤ k ≤ n) trees i1, i2, ..., ik (i1 < i2 < ... < ik) such that their heights form an increasing sequence, that is hi1 < hi2 < ... < hik. Petya had been in this forest together with Vasya, and he now has q assumptions about the mistake in Vasya's sequence h. His i-th assumption consists of two integers ai and bi indicating that, according to Petya, the height of the tree numbered ai is actually equal to bi. Note that Petya's assumptions are independent from each other. Your task is to find the maximum length of a zip-line that can be built over the trees under each of the q assumptions. In this problem the length of a zip line is considered equal to the number of trees that form this zip-line. Input The first line of the input contains two integers n and m (1 ≤ n, m ≤ 400 000) — the number of the trees in the forest and the number of Petya's assumptions, respectively. The following line contains n integers hi (1 ≤ hi ≤ 109) — the heights of trees according to Vasya. Each of the following m lines contains two integers ai and bi (1 ≤ ai ≤ n, 1 ≤ bi ≤ 109). Output For each of the Petya's assumptions output one integer, indicating the maximum length of a zip-line that can be built under this assumption. Examples Input 4 4 1 2 3 4 1 1 1 4 4 3 4 5 Output 4 3 3 4 Input 4 2 1 3 2 6 3 5 2 4 Output 4 3 Note Consider the first sample. The first assumption actually coincides with the height remembered by Vasya. In the second assumption the heights of the trees are (4, 2, 3, 4), in the third one they are (1, 2, 3, 3) and in the fourth one they are (1, 2, 3, 5). ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct que { int x, v, id; bool operator<(const que &other) const { return x < other.x; } }; const int N = 4 * 1000 * 100 + 5; int n, m, h[N]; int a[N], b[N]; que q[N]; int arr[N], used[N]; int pre[N]; int suff[N]; set<int> pos[N]; int lis; void input() { scanf("%d %d", &n, &m); for (int i = 0; i < n; i++) scanf("%d", &h[i]); for (int i = 0; i < m; i++) { scanf("%d %d", &a[i], &b[i]); a[i]--; q[i] = {a[i], b[i], i}; } sort(q, q + m); fill(used, used + m, 1); } void solve_left() { fill(arr, arr + n, 2e9); int i, j; for (i = 0, j = 0; i < n; i++) { for (; j < m && q[j].x == i; j++) { used[q[j].id] += lower_bound(arr, arr + n, q[j].v) - arr; } int p = lower_bound(arr, arr + n, h[i]) - arr; pre[i] = p; arr[p] = h[i]; } } void solve_right() { fill(arr, arr + n, 2e9); for (int i = n - 1, j = m - 1; i >= 0; i--) { for (; j >= 0 && q[j].x == i; j--) { used[q[j].id] += lower_bound(arr, arr + n, -q[j].v) - arr; } int p = lower_bound(arr, arr + n, -h[i]) - arr; suff[i] = p; arr[p] = -h[i]; } } int ess[N]; int main() { fill(ess, ess + n, 0); input(); solve_left(); solve_right(); lis = 0; for (int i = 0; i < n; i++) { lis = max(lis, pre[i] + suff[i] + 1); } for (int i = 0; i < n; i++) { if (pre[i] + suff[i] + 1 == lis) { pos[pre[i]].insert(i + 1); } } for (int i = 0; i < n; i++) { if (pre[i] + suff[i] + 1 == lis) { if (pos[pre[i]].size() == 1) ess[i] = 1; } } for (int i = 0; i < m; i++) { printf("%d\n", max(lis - ess[a[i]], used[i])); } } ```
### Prompt Please create a solution in CPP to the following problem: There is a grid of squares with H horizontal rows and W vertical columns. The square at the i-th row from the top and the j-th column from the left is represented as (i, j). Each square is black or white. The color of the square is given as an H-by-W matrix (a_{i, j}). If a_{i, j} is `.`, the square (i, j) is white; if a_{i, j} is `#`, the square (i, j) is black. Snuke is compressing this grid. He will do so by repeatedly performing the following operation while there is a row or column that consists only of white squares: * Operation: choose any one row or column that consists only of white squares, remove it and delete the space between the rows or columns. It can be shown that the final state of the grid is uniquely determined regardless of what row or column is chosen in each operation. Find the final state of the grid. Constraints * 1 \leq H, W \leq 100 * a_{i, j} is `.` or `#`. * There is at least one black square in the whole grid. Input Input is given from Standard Input in the following format: H W a_{1, 1}...a_{1, W} : a_{H, 1}...a_{H, W} Output Print the final state of the grid in the same format as input (without the numbers of rows and columns); see the samples for clarity. Examples Input 4 4 ##.# .... ##.# .#.# Output ### ### .## Input 4 4 .# .... .# .#.# Output .## Input 3 3 .. .#. ..# Output .. .#. ..# Input 4 5 ..... ..... ..#.. ..... Output Input 7 6 ...... ....#. .#.... ..#... ..#... ...... .#..#. Output ..# .. .#. .#. .# ### Response ```cpp #include <bits/stdc++.h> #define rep(i,l,r) for(int i=(l);i<=(r);++i) #define per(i,r,l) for(int i=(r);i>=(l);--i) using namespace std; char a[110][110]; int n,m,b[110],c[110]; int main(){ scanf("%d%d",&n,&m); rep(i,1,n) rep(j,1,m){ scanf(" %c",&a[i][j]); if(a[i][j]=='#') b[i]|=1,c[j]|=1; } //rep(i,1,n) printf("%d",b[i]);puts(""); rep(i,1,n){ if(!b[i]) continue; rep(j,1,m) if(c[j]) printf("%c",a[i][j]); puts(""); } return 0; } ```
### Prompt Please create a solution in Cpp to the following problem: We will define the median of a sequence b of length M, as follows: * Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down. For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10. Snuke comes up with the following problem. You are given a sequence a of length N. For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a. We will list m_{l, r} for all pairs (l, r) to create a new sequence m. Find the median of m. Constraints * 1 \leq N \leq 10^5 * a_i is an integer. * 1 \leq a_i \leq 10^9 Input Input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output Print the median of m. Examples Input 3 10 30 20 Output 30 Input 1 10 Output 10 Input 10 5 9 5 9 8 9 3 5 4 3 Output 8 ### Response ```cpp #include<bits/stdc++.h> using namespace std; int a[100010],d[100010],b[100010],n; long long t,tt; void sol(int l,int r) { if(l>=r) return ; int mid=(l+r)/2,p,q,x,i; sol(l,mid); sol(mid+1,r); p=l; q=mid+1; x=l; while(p<=mid&&q<=r) { if(d[p]<d[q]) b[x++]=d[p++]; else { t+=(p-l); b[x++]=d[q++]; } } while(p<=mid) b[x++]=d[p++]; while(q<=r) { t+=(p-l); b[x++]=d[q++]; } for(i=l; i<=r; i++) d[i]=b[i]; } bool check(int x) { t=0; int i; for(i=1; i<=n; i++) if(a[i]<=x) d[i]=1; else d[i]=-1; for(i=1; i<=n; i++) d[i]+=d[i-1]; sol(0,n); return t>=(tt/2+1); } int main() { int i,l=1e9,r=-1e9,mid; tt=0; scanf("%d",&n); for(i=1; i<=n; i++) { scanf("%d",&a[i]); l=min(l,a[i]); r=max(r,a[i]); tt+=i; } while(l<r) { mid=(l+r)/2; if(check(mid)) r=mid; else l=mid+1; } printf("%d",r); return 0; } ```