text
stringlengths
424
69.5k
### Prompt Your task is to create a Cpp solution to the following problem: Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem. Input The first input line contains integer n (1 ≤ n ≤ 100) — amount of numbers in the sequence. The second line contains n space-separated integer numbers — elements of the sequence. These numbers don't exceed 100 in absolute value. Output If the given sequence has the second order statistics, output this order statistics, otherwise output NO. Examples Input 4 1 2 2 -4 Output 1 Input 5 1 2 3 1 1 Output 2 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long int mod = 1000000000 + 7; const long long int N = 1000000 + 6; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin >> n; set<int> s; for (int i = 0; i < n; i++) { int aa; cin >> aa; s.insert(aa); } s.erase(s.begin()); if (s.begin() == s.end()) cout << "NO" << '\n'; else cout << *s.begin(); } ```
### Prompt Develop a solution in cpp to the problem described below: Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters. Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length. Input The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input. Output Print a single integer — the maximum possible total length of words in Andrew's article. Examples Input 4 abb cacc aaa bbb Output 9 Input 5 a a bcbcb cdecdecdecdecdecde aaaa Output 6 Note In the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}. In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 105; const int INF = 0x3f3f3f3f; int mar[30][30]; int vis[30]; char arr[MAXN][MAXN * 10]; int _get(int x) { int cnt = 0; while (x) { x &= (x - 1); cnt++; } return cnt; } int main() { int n; while (~scanf("%d", &n)) { memset(mar, 0, sizeof(mar)); for (int i = 0; i < n; i++) scanf("%s", arr[i]); for (int i = 0; i < n; i++) { int len = strlen(arr[i]); memset(vis, 0, sizeof(vis)); int cnt = 0, flag = 1; int a[5]; for (int j = 0; j < len; j++) { if (!vis[arr[i][j] - 'a']) { a[cnt++] = arr[i][j] - 'a'; vis[arr[i][j] - 'a'] = 1; } if (cnt > 2) { flag = 0; break; } } if (flag) { int xx = a[0], yy; if (cnt == 1) mar[xx][xx] += strlen(arr[i]); else { yy = a[1]; mar[xx][yy] += strlen(arr[i]); } } } int ans = 0; for (int i = 0; i < 26; i++) for (int j = i + 1; j < 26; j++) ans = max(ans, mar[i][j] + mar[j][i] + mar[i][i] + mar[j][j]); printf("%d\n", ans); } return 0; } ```
### Prompt Develop a solution in cpp to the problem described below: Amidakuji is a traditional method of lottery in Japan. To make an amidakuji, we first draw W parallel vertical lines, and then draw horizontal lines that connect them. The length of each vertical line is H+1 [cm], and the endpoints of the horizontal lines must be at 1, 2, 3, ..., or H [cm] from the top of a vertical line. A valid amidakuji is an amidakuji that satisfies the following conditions: * No two horizontal lines share an endpoint. * The two endpoints of each horizontal lines must be at the same height. * A horizontal line must connect adjacent vertical lines. <image> Find the number of the valid amidakuji that satisfy the following condition, modulo 1\ 000\ 000\ 007: if we trace the path from the top of the leftmost vertical line to the bottom, always following horizontal lines when we encounter them, we reach the bottom of the K-th vertical line from the left. For example, in the following amidakuji, we will reach the bottom of the fourth vertical line from the left. <image> Constraints * H is an integer between 1 and 100 (inclusive). * W is an integer between 1 and 8 (inclusive). * K is an integer between 1 and W (inclusive). Input Input is given from Standard Input in the following format: H W K Output Print the number of the amidakuji that satisfy the condition, modulo 1\ 000\ 000\ 007. Examples Input 1 3 2 Output 1 Input 1 3 1 Output 2 Input 2 3 3 Output 1 Input 2 3 1 Output 5 Input 7 1 1 Output 1 Input 15 8 5 Output 437760187 ### Response ```cpp #include <iostream> #include <vector> using namespace std; const long md=1000000007; const long f[10]={0, 1, 1, 2, 3, 5, 8, 13, 21, 34}; int main(){ int h, w, k; cin >> h >> w >> k; vector<vector<long>>dp(h+1, vector<long>(w+2, 0)); dp[0][1]=1; for(int n=1; n<=h; n++){ for(int k=1; k<=w; k++){ dp[n][k] = f[k-1]*f[w-k+1]*dp[n-1][k-1] + f[k]*f[w-k+1]*dp[n-1][k]+f[k]*f[w-k]*dp[n-1][k+1]; dp[n][k]%=md; } } cout << dp[h][k]; return 0; } ```
### Prompt Please provide a CPP coded solution to the problem described below: Cool J has recently become a businessman Mr. Jackson, and he has to make a lot of phone calls now. Today he has n calls planned. For each call we know the moment ti (in seconds since the start of the day) when it is scheduled to start and its duration di (in seconds). All ti are different. Mr. Jackson is a very important person, so he never dials anybody himself, all calls will be incoming. Mr. Jackson isn't Caesar and he can't do several things at once. If somebody calls him while he hasn't finished the previous conversation, Mr. Jackson puts the new call on hold in the queue. In this case immediately after the end of the current call Mr. Jackson takes the earliest incoming call from the queue and starts the conversation. If Mr. Jackson started the call at the second t, and the call continues for d seconds, then Mr. Jackson is busy at seconds t, t + 1, ..., t + d - 1, and he can start a new call at second t + d. Note that if Mr. Jackson is not busy talking when somebody calls, he can't put this call on hold. Mr. Jackson isn't Napoleon either, he likes to sleep. So sometimes he allows himself the luxury of ignoring a call, as if it never was scheduled. He can ignore at most k calls. Note that a call which comes while he is busy talking can be ignored as well. What is the maximum number of seconds Mr. Jackson can sleep today, assuming that he can choose an arbitrary continuous time segment from the current day (that is, with seconds from the 1-st to the 86400-th, inclusive) when he is not busy talking? Note that some calls can be continued or postponed to the next day or even later. However, the interval for sleep should be completely within the current day. Input The first input line contains a pair of integers n, k (0 ≤ k ≤ n ≤ 4000) separated by a space. Following n lines contain the description of calls for today. The description of each call is located on the single line and consists of two space-separated integers ti and di, (1 ≤ ti, di ≤ 86400). All ti are distinct, the calls are given in the order of strict increasing ti. Scheduled times of calls [ti, ti + di - 1] can arbitrarily intersect. Output Print a number from 0 to 86400, inclusive — the maximally possible number of seconds for Mr. Jackson to sleep today. Examples Input 3 2 30000 15000 40000 15000 50000 15000 Output 49999 Input 5 1 1 20000 10000 10000 20000 20000 25000 10000 80000 60000 Output 39999 Note In the first sample the most convenient way is to ignore the first two calls. In the second sample it is best to ignore the third call. In this case Mr. Jackson will have been speaking: * first call: from 1-st to 20000-th second, * second call: from 20001-st to 30000-th second, * fourth call: from 30001-st to 40000-th second (the third call is ignored), * fifth call: from 80000-th to 139999-th second. Thus, the longest period of free time is from the 40001-th to the 79999-th second. ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <class T> void pv(T a, T b) { for (T i = a; i != b; ++i) cout << *i << " "; cout << endl; } template <class T> void chmin(T &t, T f) { if (t > f) t = f; } template <class T> void chmax(T &t, T f) { if (t < f) t = f; } int in() { int x; scanf("%d", &x); return x; } const int T = 86400 + 1; int N, K; int A[4010], D[4010]; int dp[4010][4010]; int main() { int i, k; for (; ~scanf("%d%d", &N, &K);) { for (i = 0; i < N; ++i) { A[i] = in(); D[i] = in(); } A[N] = T; memset(dp, 0x3f, sizeof(dp)); for (k = 0; k <= K; ++k) { dp[0][k] = 1; } for (i = 0; i < N; ++i) { for (k = 0; k <= K; ++k) { chmin(dp[i + 1][k], max(dp[i][k], A[i]) + D[i]); chmin(dp[i + 1][k + 1], dp[i][k]); } } int ans = 0; for (i = 0; i <= N; ++i) { chmax(ans, A[i] - dp[i][K]); } printf("%d\n", ans); } return 0; } ```
### Prompt Your task is to create a CPP solution to the following problem: Let f(A, B), where A and B are positive integers, be the string satisfying the following conditions: * f(A, B) has length A + B; * f(A, B) contains exactly A letters `A` and exactly B letters `B`; * The length of the longest substring of f(A, B) consisting of equal letters (ex., `AAAAA` or `BBBB`) is as small as possible under the conditions above; * f(A, B) is the lexicographically smallest string satisfying the conditions above. For example, f(2, 3) = `BABAB`, and f(6, 4) = `AABAABAABB`. Answer Q queries: find the substring of f(A_i, B_i) from position C_i to position D_i (1-based). Constraints * 1 \leq Q \leq 10^3 * 1 \leq A_i, B_i \leq 5 \times 10^8 * 1 \leq C_i \leq D_i \leq A_i + B_i * D_i - C_i + 1 \leq 100 * All input values are integers. Input Input is given from Standard Input in the following format: Q A_1 B_1 C_1 D_1 A_2 B_2 C_2 D_2 : A_Q B_Q C_Q D_Q Output For each query i in order of input, print a line containing the substring of f(A_i, B_i) from position C_i to position D_i (1-based). Example Input 5 2 3 1 5 6 4 1 10 2 3 4 4 6 4 3 7 8 10 5 8 Output BABAB AABAABAABB A BAABA ABAB ### Response ```cpp #include<cstdio> #include<cstring> #include<algorithm> using namespace std; int q,a,b,c,d,len; bool check(int cnta) { int cntb=(cnta-1)/len; if((b-cntb)>1ll*(a-cnta+1)*len)return 0; return 1; } int main() { scanf("%d",&q); while(q--) { scanf("%d %d %d %d",&a,&b,&c,&d); len=a>b?(a+b)/(b+1):(a+b)/(a+1); int l=0,r=a,mid; while(l<r) { mid=l+r+1>>1; if(check(mid))l=mid; else r=mid-1; } int p=l/len*(len+1)+l%len; for(int i=c;i<=d;++i) { if(i<=p) { if(i%(len+1)==0)putchar('B'); else putchar('A'); } else { if((a+b-i+1)%(len+1)==0)putchar('A'); else putchar('B'); } } putchar('\n'); /* for(int i=1;i<=a+b;++i) { if(check(cnta,cntb,lcnt,lst,len)) { ++cnta; if(lst==0)++lcnt; else lst=0,lcnt=1; if(i>=c&&i<=d)putchar('A'); } else { ++cntb; if(lst==1)++lcnt; else lst=1,lcnt=1; if(i>=c&&i<=d)putchar('B'); } } putchar('\n');*/ } return 0; } ```
### Prompt Your task is to create a Cpp solution to the following problem: problem During this time of winter in Japan, hot days continue in Australia in the Southern Hemisphere. IOI, who lives in Australia, decided to plan what clothes to wear based on the weather forecast for a certain D day. The maximum temperature on day i (1 ≤ i ≤ D) is predicted to be Ti degrees. IOI has N kinds of clothes, which are numbered from 1 to N. Clothes j (1 ≤ j ≤ N) are suitable for wearing on days when the maximum temperature is above Aj and below Bj. In addition, each clothes has an integer called "flashiness", and the flashiness of clothes j is Cj. For each of the D days, IOI chooses to wear one of the clothes suitable for wearing when the maximum temperature follows the weather forecast. You may choose the same clothes as many times as you like, or you may choose clothes that are never chosen in D days. IOI, who wanted to avoid wearing similar clothes in succession, decided to maximize the total absolute value of the difference in the flashiness of the clothes worn on consecutive days. That is, assuming that the clothes xi are selected on the i-day, we want to maximize the values ​​| Cx1 --Cx2 | + | Cx2 --Cx3 | +… + | CxD-1 --CxD |. Create a program to find this maximum value. input The input consists of 1 + D + N lines. On the first line, two integers D and N (2 ≤ D ≤ 200, 1 ≤ N ≤ 200) are written with a blank as a delimiter. D is the number of days to plan clothes and N is the number of clothes types IOI has. One integer Ti (0 ≤ Ti ≤ 60) is written in the i-th line (1 ≤ i ≤ D) of the following D lines. This means that the maximum temperature on day i is forecast to be Ti degrees. In the jth line (1 ≤ j ≤ N) of the following N lines, three integers Aj, Bj, Cj (0 ≤ Aj ≤ Bj ≤ 60, 0 ≤ Cj ≤ 100) are written. These indicate that clothing j is suitable for wearing on days when the maximum temperature is above Aj and below Bj, and the flashiness is Cj. It is guaranteed that there will be at least one piece of clothing suitable for wearing when the maximum temperature follows the weather forecast for every D day. output Output the total absolute value of the difference in the flashiness of clothes worn on consecutive days, that is, the maximum value of the values ​​| Cx1 --Cx2 | + | Cx2 --Cx3 | +… + | CxD-1 --CxD | in one line. .. Input / output example Input example 1 3 4 31 27 35 20 25 30 23 29 90 21 35 60 28 33 40 Output example 1 80 In the input / output example 1, the candidates for clothes on the first day are clothes 3 and 4, the candidates for clothes on the second day are clothes 2 and clothes 3, and the candidates for clothes on the third day are only clothes 3. is there. Choose clothes 4 on the first day, clothes 2 on the second day, and clothes 3 on the third day. That is, x1 = 4, x2 = 2, x3 = 3. At this time, the absolute value of the difference in the flashiness of the clothes on the first day and the second day is | 40 --90 | = 50, and the absolute value of the difference in the flashiness of the clothes on the second and third days is | 90-60 | = 30. The total is 80, which is the maximum value. Input example 2 5 2 26 28 32 29 34 30 35 0 25 30 100 Output example 2 300 In Example 2 of input / output, clothes 2 on the first day, clothes 2 on the second day, clothes 1 on the third day, clothes 2 on the fourth day, and clothes 1 on the fifth day. You have to choose. At this time, the required value is | 100 --100 | + | 100 --0 | + | 0 --100 | + | 100 --0 | = 300. The question text and the data used for the automatic referee are the question text and the test data for scoring, which are created and published by the Japan Committee for Information Olympics. Example Input 3 4 31 27 35 20 25 30 23 29 90 21 35 60 28 33 40 Output 80 ### Response ```cpp #include <iostream> #include <algorithm> using namespace std; struct data{ int a,b,c; }; int main(){ int d,n; while(cin >> d >> n){ int t[200],dp[200][200],ans=0; data v[200]; for(int i=0;i<d;i++) cin >> t[i]; for(int i=0;i<n;i++) cin >> v[i].a >> v[i].b >> v[i].c; fill(dp[0],dp[200],0); for(int i=1;i<d;i++){ for(int j=0;j<n;j++){ if(v[j].a > t[i-1] || v[j].b < t[i-1]) continue; for(int k=0;k<n;k++){ if(v[k].a > t[i] || v[k].b < t[i]) continue; dp[i][k] = max(dp[i][k], dp[i-1][j] + abs(v[j].c-v[k].c)); } } } for(int i=0;i<n;i++) ans = max(ans,dp[d-1][i]); cout << ans << endl; } } ```
### Prompt Please create a solution in cpp to the following problem: You have an array a of length n. For every positive integer x you are going to perform the following operation during the x-th second: * Select some distinct indices i_{1}, i_{2}, …, i_{k} which are between 1 and n inclusive, and add 2^{x-1} to each corresponding position of a. Formally, a_{i_{j}} := a_{i_{j}} + 2^{x-1} for j = 1, 2, …, k. Note that you are allowed to not select any indices at all. You have to make a nondecreasing as fast as possible. Find the smallest number T such that you can make the array nondecreasing after at most T seconds. Array a is nondecreasing if and only if a_{1} ≤ a_{2} ≤ … ≤ a_{n}. You have to answer t independent test cases. Input The first line contains a single integer t (1 ≤ t ≤ 10^{4}) — the number of test cases. The first line of each test case contains single integer n (1 ≤ n ≤ 10^{5}) — the length of array a. It is guaranteed that the sum of values of n over all test cases in the input does not exceed 10^{5}. The second line of each test case contains n integers a_{1}, a_{2}, …, a_{n} (-10^{9} ≤ a_{i} ≤ 10^{9}). Output For each test case, print the minimum number of seconds in which you can make a nondecreasing. Example Input 3 4 1 7 6 5 5 1 2 3 4 5 2 0 -4 Output 2 0 3 Note In the first test case, if you select indices 3, 4 at the 1-st second and 4 at the 2-nd second, then a will become [1, 7, 7, 8]. There are some other possible ways to make a nondecreasing in 2 seconds, but you can't do it faster. In the second test case, a is already nondecreasing, so answer is 0. In the third test case, if you do nothing at first 2 seconds and select index 2 at the 3-rd second, a will become [0, 0]. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long int _; cin >> _; while (_--) { long long int n, k, ma = INT_MIN, mi = INT_MAX; cin >> n; long long int s = 0; for (int i = 0; i < n; i++) { cin >> k; if (ma < k) { ma = k; mi = k; } mi = min(mi, k); s = max(s, ma - mi); } s ? cout << (long long int)(log2(s) + 1) << "\n" : cout << "0\n"; } return 0; } ```
### Prompt Your task is to create a CPP solution to the following problem: This is the easy version of the problem. The difference between versions is the constraints on n and a_i. You can make hacks only if all versions of the problem are solved. First, Aoi came up with the following idea for the competitive programming problem: Yuzu is a girl who collecting candies. Originally, she has x candies. There are also n enemies numbered with integers from 1 to n. Enemy i has a_i candies. Yuzu is going to determine a permutation P. A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, \{2,3,1,5,4\} is a permutation, but \{1,2,2\} is not a permutation (2 appears twice in the array) and \{1,3,4\} is also not a permutation (because n=3 but there is the number 4 in the array). After that, she will do n duels with the enemies with the following rules: * If Yuzu has equal or more number of candies than enemy P_i, she wins the duel and gets 1 candy. Otherwise, she loses the duel and gets nothing. * The candy which Yuzu gets will be used in the next duels. Yuzu wants to win all duels. How many valid permutations P exist? This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea: Let's define f(x) as the number of valid permutations for the integer x. You are given n, a and a prime number p ≤ n. Let's call a positive integer x good, if the value f(x) is not divisible by p. Find all good integers x. Your task is to solve this problem made by Akari. Input The first line contains two integers n, p (2 ≤ p ≤ n ≤ 2000). It is guaranteed, that the number p is prime (it has exactly two divisors 1 and p). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 2000). Output In the first line, print the number of good integers x. In the second line, output all good integers x in the ascending order. It is guaranteed that the number of good integers x does not exceed 10^5. Examples Input 3 2 3 4 5 Output 1 3 Input 4 3 2 3 5 6 Output 2 3 4 Input 4 3 9 1 1 1 Output 0 Note In the first test, p=2. * If x ≤ 2, there are no valid permutations for Yuzu. So f(x)=0 for all x ≤ 2. The number 0 is divisible by 2, so all integers x ≤ 2 are not good. * If x = 3, \{1,2,3\} is the only valid permutation for Yuzu. So f(3)=1, so the number 3 is good. * If x = 4, \{1,2,3\} , \{1,3,2\} , \{2,1,3\} , \{2,3,1\} are all valid permutations for Yuzu. So f(4)=4, so the number 4 is not good. * If x ≥ 5, all 6 permutations are valid for Yuzu. So f(x)=6 for all x ≥ 5, so all integers x ≥ 5 are not good. So, the only good number is 3. In the third test, for all positive integers x the value f(x) is divisible by p = 3. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int f(int n, int p) { int ans = 0; while (n > 0) { n = n / p; ans += n; } return ans; } int calc(int n, int r, int p) { return f(n, p) - f(n - r, p); } int main() { int n, x; cin >> n >> x; int cnt[2005] = {0}; for (int i = 0; i < n; i++) { int pp; cin >> pp; cnt[pp]++; } vector<pair<int, int>> num; for (int i = 0; i < 2005; i++) if (cnt[i]) num.push_back({i, cnt[i]}); sort(num.begin(), num.end()); reverse(num.begin(), num.end()); vector<int> ans; for (int i = 1; i < 2005; i++) { int c = 0; int flag = 1; int done = 0; for (auto j : num) { int avail = 0; if (j.first > i + n - 1) { flag = 0; break; } avail = min(n, i + n - j.first) - done; if (avail < j.second) { flag = 0; break; } done += j.second; c += calc(avail, j.second, x); } if (c == 0 && flag == 1) { ans.push_back(i); } } cout << (int)ans.size() << '\n'; for (auto i : ans) cout << i << " "; return 0; } ```
### Prompt Please create a solution in Cpp to the following problem: Dreamoon has a string s and a pattern string p. He first removes exactly x characters from s obtaining string s' as a result. Then he calculates <image> that is defined as the maximal number of non-overlapping substrings equal to p that can be found in s'. He wants to make this number as big as possible. More formally, let's define <image> as maximum value of <image> over all s' that can be obtained by removing exactly x characters from s. Dreamoon wants to know <image> for all x from 0 to |s| where |s| denotes the length of string s. Input The first line of the input contains the string s (1 ≤ |s| ≤ 2 000). The second line of the input contains the string p (1 ≤ |p| ≤ 500). Both strings will only consist of lower case English letters. Output Print |s| + 1 space-separated integers in a single line representing the <image> for all x from 0 to |s|. Examples Input aaaaa aa Output 2 2 1 1 0 0 Input axbaxxb ab Output 0 1 1 2 1 1 0 0 Note For the first sample, the corresponding optimal values of s' after removal 0 through |s| = 5 characters from s are {"aaaaa", "aaaa", "aaa", "aa", "a", ""}. For the second sample, possible corresponding optimal values of s' are {"axbaxxb", "abaxxb", "axbab", "abab", "aba", "ab", "a", ""}. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long double PI = 3.1415926535897932384626433832795L; const long double EPS = 1e-9; long long gcd(long long a, long long b) { while (b) { a %= b; swap(a, b); } return a; } long long lcm(const long long a, const long long b) { return a / gcd(a, b) * b; } long long sign(const long long x) { return (x > 0) - (x < 0); } template <class T> const T sqr(const T x) { return x * x; } template <class T> const T binpow(const T a, const unsigned long long n, const T modulo) { return n == 0 ? 1 : sqr(binpow(a, n / 2, modulo)) % modulo * (n % 2 ? a : 1) % modulo; } const int MAXS = 2000; int min_length_p[MAXS], dp[MAXS + 1][MAXS + 1]; int main() { ios::sync_with_stdio(false); string s, p; cin >> s >> p; for (int i = 0; i < s.size(); i++) { int s_position = i, p_position; for (p_position = 0; s_position < s.size() && p_position < p.size(); ++s_position) { p_position += s[s_position] == p[p_position]; } if (p_position == p.size()) { min_length_p[i] = s_position - i; } else { min_length_p[i] = -1; } } memset(dp, 0, sizeof(dp)); for (int i = 0; i < s.size(); i++) { for (int j = 0; j <= i; j++) { dp[i + 1][j] = max(dp[i][j], dp[i + 1][j]); dp[i + 1][j + 1] = max(dp[i][j], dp[i + 1][j + 1]); if (min_length_p[i] != -1) { dp[i + min_length_p[i]][j + min_length_p[i] - p.size()] = max(dp[i][j] + 1, dp[i + min_length_p[i]][j + min_length_p[i] - p.size()]); } } } for (int j = 0; j <= s.size(); j++) { cout << dp[s.size()][j] << ' '; } return 0; } ```
### Prompt Please create a solution in Cpp to the following problem: The Berland capital (as you very well know) contains n junctions, some pairs of which are connected by two-way roads. Unfortunately, the number of traffic jams in the capital has increased dramatically, that's why it was decided to build several new roads. Every road should connect two junctions. The city administration noticed that in the cities of all the developed countries between any two roads one can drive along at least two paths so that the paths don't share any roads (but they may share the same junction). The administration decided to add the minimal number of roads so that this rules was fulfilled in the Berland capital as well. In the city road network should exist no more than one road between every pair of junctions before or after the reform. Input The first input line contains a pair of integers n, m (2 ≤ n ≤ 900, 1 ≤ m ≤ 100000), where n is the number of junctions and m is the number of roads. Each of the following m lines contains a description of a road that is given by the numbers of the connected junctions ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi). The junctions are numbered from 1 to n. It is possible to reach any junction of the city from any other one moving along roads. Output On the first line print t — the number of added roads. Then on t lines print the descriptions of the added roads in the format of the input data. You can use any order of printing the roads themselves as well as the junctions linked by every road. If there are several solutions to that problem, print any of them. If the capital doesn't need the reform, print the single number 0. If there's no solution, print the single number -1. Examples Input 4 3 1 2 2 3 3 4 Output 1 1 4 Input 4 4 1 2 2 3 2 4 3 4 Output 1 1 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int M = 1e5 + 5, N = 1002; std::vector<int> vtr[N]; int U[M], V[M]; bool isbridge[M], vis[N]; std::vector<int> tree[N], cmps[N]; queue<int> Q[N]; int arr[N], t = 0, ans = 0; int adj(int u, int e) { if (U[e] == u) return V[e]; return U[e]; } int dfs(int x, int edge) { vis[x] = 1; arr[x] = t++; int mn = arr[x]; for (int i = 0; i < vtr[x].size(); i++) { int e = vtr[x][i]; int u = adj(x, e); if (!vis[u]) mn = min(mn, dfs(u, e)); else if (e != edge) mn = min(arr[u], mn); } if (mn == arr[x] && edge != -1) { isbridge[edge] = 1; } return mn; } void DFS(int x) { vis[x] = 1; int curr = t; Q[curr].push(x); while (!Q[curr].empty()) { int u = Q[curr].front(); Q[curr].pop(); cmps[curr].push_back(u); for (int i = 0; i < vtr[u].size(); i++) { int e = vtr[u][i]; int v = adj(u, e); if (!vis[v]) { if (isbridge[e]) { t++; tree[curr].push_back(t); tree[t].push_back(curr); DFS(v); } else { Q[curr].push(v); vis[v] = 1; } } } } } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, m, i, u, v; cin >> n >> m; if (n == 2) { cout << "-1\n"; return 0; } set<pair<int, int>> ed; for (i = 1; i <= m; i++) { cin >> u >> v; U[i] = u; V[i] = v; vtr[u].push_back(i); vtr[v].push_back(i); ed.insert(make_pair(u, v)); ed.insert(make_pair(v, u)); } dfs(1, -1); for (i = 1; i <= n; i++) vis[i] = 0; t = 1; DFS(1); vector<int> leaves; for (int i = 1; i <= t; i++) { if ((int)tree[i].size() == 1) leaves.push_back(i); } vector<pair<int, int>> val; int off = (int)leaves.size() / 2; for (int j = off; j < (int)leaves.size(); j++) { int z = cmps[leaves[j - off]][0]; for (auto u : cmps[leaves[j]]) { if (ed.find({u, z}) == ed.end()) { val.push_back({u, z}); break; } } } cout << (int)val.size() << "\n"; for (auto u : val) cout << u.first << " " << u.second << "\n"; return 0; } ```
### Prompt Please create a solution in CPP to the following problem: The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≤ i < n there is an edge between the vertices of i and i+1. Denote the function f(l, r), which takes two integers l and r (l ≤ r): * We leave in the tree only vertices whose values ​​range from l to r. * The value of the function will be the number of connected components in the new graph. Your task is to calculate the following sum: $$$∑_{l=1}^{n} ∑_{r=l}^{n} f(l, r) $$$ Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the values of the vertices. Output Print one number — the answer to the problem. Examples Input 3 2 1 3 Output 7 Input 4 2 1 1 3 Output 11 Input 10 1 5 2 5 5 3 10 6 5 1 Output 104 Note In the first example, the function values ​​will be as follows: * f(1, 1)=1 (there is only a vertex with the number 2, which forms one component) * f(1, 2)=1 (there are vertices 1 and 2 that form one component) * f(1, 3)=1 (all vertices remain, one component is obtained) * f(2, 2)=1 (only vertex number 1) * f(2, 3)=2 (there are vertices 1 and 3 that form two components) * f(3, 3)=1 (only vertex 3) Totally out 7. In the second example, the function values ​​will be as follows: * f(1, 1)=1 * f(1, 2)=1 * f(1, 3)=1 * f(1, 4)=1 * f(2, 2)=1 * f(2, 3)=2 * f(2, 4)=2 * f(3, 3)=1 * f(3, 4)=1 * f(4, 4)=0 (there is no vertex left, so the number of components is 0) Totally out 11. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long maxn = 100005; long long n, ans; long long a[maxn]; inline long long read() { long long ret = 0, f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -f; ch = getchar(); } while (isdigit(ch)) { ret = ret * 10 + ch - '0'; ch = getchar(); } return ret * f; } signed main() { n = read(); for (long long k = 1; k <= n; k++) a[k] = read(); for (long long k = 1; k <= n; k++) { long long x = a[k], y = a[k - 1]; long long ll, lr, rl, rr; if (x > y) ll = y + 1, lr = x, rl = x, rr = n; else ll = 1, lr = x, rl = x, rr = y - 1; ans += (lr - ll + 1) * (rr - rl + 1); } printf("%lld\n", ans); return 0; } ```
### Prompt Please provide a Cpp coded solution to the problem described below: Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition. There are n flowers in a row in the exhibition. Sonya can put either a rose or a lily in the i-th position. Thus each of n positions should contain exactly one flower: a rose or a lily. She knows that exactly m people will visit this exhibition. The i-th visitor will visit all flowers from l_i to r_i inclusive. The girl knows that each segment has its own beauty that is equal to the product of the number of roses and the number of lilies. Sonya wants her exhibition to be liked by a lot of people. That is why she wants to put the flowers in such way that the sum of beauties of all segments would be maximum possible. Input The first line contains two integers n and m (1≤ n, m≤ 10^3) — the number of flowers and visitors respectively. Each of the next m lines contains two integers l_i and r_i (1≤ l_i≤ r_i≤ n), meaning that i-th visitor will visit all flowers from l_i to r_i inclusive. Output Print the string of n characters. The i-th symbol should be «0» if you want to put a rose in the i-th position, otherwise «1» if you want to put a lily. If there are multiple answers, print any. Examples Input 5 3 1 3 2 4 2 5 Output 01100 Input 6 3 5 6 1 4 4 6 Output 110010 Note In the first example, Sonya can put roses in the first, fourth, and fifth positions, and lilies in the second and third positions; * in the segment [1…3], there are one rose and two lilies, so the beauty is equal to 1⋅ 2=2; * in the segment [2…4], there are one rose and two lilies, so the beauty is equal to 1⋅ 2=2; * in the segment [2…5], there are two roses and two lilies, so the beauty is equal to 2⋅ 2=4. The total beauty is equal to 2+2+4=8. In the second example, Sonya can put roses in the third, fourth, and sixth positions, and lilies in the first, second, and fifth positions; * in the segment [5…6], there are one rose and one lily, so the beauty is equal to 1⋅ 1=1; * in the segment [1…4], there are two roses and two lilies, so the beauty is equal to 2⋅ 2=4; * in the segment [4…6], there are two roses and one lily, so the beauty is equal to 2⋅ 1=2. The total beauty is equal to 1+4+2=7. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; for (int i = 0; i < n; i++) { cout << i % 2; } cout << endl; return 0; } ```
### Prompt In Cpp, your task is to solve the following problem: Vasya has recently found out what a digital root of a number is and he decided to share his knowledge with you. Let's assume that S(n) is the sum of digits of number n, for example, S(4098) = 4 + 0 + 9 + 8 = 21. Then the digital root of number n equals to: 1. dr(n) = S(n), if S(n) < 10; 2. dr(n) = dr( S(n) ), if S(n) ≥ 10. For example, dr(4098) = dr(21) = 3. Vasya is afraid of large numbers, so the numbers he works with are at most 101000. For all such numbers, he has proved that dr(n) = S( S( S( S(n) ) ) ) (n ≤ 101000). Now Vasya wants to quickly find numbers with the given digital root. The problem is, he hasn't learned how to do that and he asked you to help him. You task is, given numbers k and d, find the number consisting of exactly k digits (the leading zeroes are not allowed), with digital root equal to d, or else state that such number does not exist. Input The first line contains two integers k and d (1 ≤ k ≤ 1000; 0 ≤ d ≤ 9). Output In a single line print either any number that meets the requirements (without the leading zeroes) or "No solution" (without the quotes), if the corresponding number does not exist. The chosen number must consist of exactly k digits. We assume that number 0 doesn't contain any leading zeroes. Examples Input 4 4 Output 5881 Input 5 1 Output 36172 Input 1 0 Output 0 Note For the first test sample dr(5881) = dr(22) = 4. For the second test sample dr(36172) = dr(19) = dr(10) = 1. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long double pi = 2 * acos(0.0); template <class T> bool umin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } template <class T> bool umax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template <class T, class TT> bool pal(T a, TT n) { int k = 0; for (int i = 0; i <= n / 2; i++) { if (a[i] != a[n - i - 1]) { k = 1; break; } } return k ? 0 : 1; } int main() { int k, d; cin >> k >> d; if (d == 0 && k > 1) return cout << "No solution\n", 0; k--; while (k--) cout << 9; cout << d; getchar(); getchar(); return 0; } ```
### Prompt Construct a cpp code solution to the problem outlined: Let's assume that we are given an n × m table filled by integers. We'll mark a cell in the i-th row and j-th column as (i, j). Thus, (1, 1) is the upper left cell of the table and (n, m) is the lower right cell. We'll assume that a circle of radius r with the center in cell (i0, j0) is a set of such cells (i, j) that <image>. We'll consider only the circles that do not go beyond the limits of the table, that is, for which r + 1 ≤ i0 ≤ n - r and r + 1 ≤ j0 ≤ m - r. <image> A circle of radius 3 with the center at (4, 5). Find two such non-intersecting circles of the given radius r that the sum of numbers in the cells that belong to these circles is maximum. Two circles intersect if there is a cell that belongs to both circles. As there can be more than one way to choose a pair of circles with the maximum sum, we will also be interested in the number of such pairs. Calculate the number of unordered pairs of circles, for instance, a pair of circles of radius 2 with centers at (3, 4) and (7, 7) is the same pair as the pair of circles of radius 2 with centers at (7, 7) and (3, 4). Input The first line contains three integers n, m and r (2 ≤ n, m ≤ 500, r ≥ 0). Each of the following n lines contains m integers from 1 to 1000 each — the elements of the table. The rows of the table are listed from top to bottom at the elements in the rows are listed from left to right. It is guaranteed that there is at least one circle of radius r, not going beyond the table limits. Output Print two integers — the maximum sum of numbers in the cells that are located into two non-intersecting circles and the number of pairs of non-intersecting circles with the maximum sum. If there isn't a single pair of non-intersecting circles, print 0 0. Examples Input 2 2 0 1 2 2 4 Output 6 2 Input 5 6 1 4 2 1 3 2 6 2 3 2 4 7 2 5 2 2 1 1 3 1 4 3 3 6 4 5 1 4 2 3 2 Output 34 3 Input 3 3 1 1 2 3 4 5 6 7 8 9 Output 0 0 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 555; int str[N][N]; int rightSum[N][N]; int centerDis[N]; int centerPos[N * 4]; int centerSum[N][N]; int rightMaxSum[N][N]; long long rightMaxNum[N][N]; int ans; long long ansNum; int main() { int m, n, r, i, j, h; while (~scanf("%d%d%d", &n, &m, &r)) { ans = 0; ansNum = 0; for (i = 0; i < n; i++) { rightSum[i][0] = 0; for (j = 0; j < m; j++) { scanf("%d", &str[i][j]); rightSum[i][j + 1] = rightSum[i][j] + str[i][j]; } } centerDis[0] = r; for (i = 1; i <= r; i++) { for (centerDis[i] = centerDis[i - 1]; i * i + centerDis[i] * centerDis[i] > r * r; centerDis[i]--) ; } centerPos[0] = 2 * r + 1; for (i = 1; i <= 2 * r; i++) { centerPos[i] = 0; for (h = 1; h <= r; h++) { if (h >= i - r && h <= i) { centerPos[i] = max(centerPos[i], centerDis[h] + centerDis[i - h] + 1); } } } for (i = r; i < n - r; i++) { for (j = r; j < m - r; j++) { centerSum[i][j] = rightSum[i][j + centerDis[0] + 1] - rightSum[i][j - centerDis[0]]; for (h = 1; h <= r; h++) { centerSum[i][j] += rightSum[i + h][j + centerDis[h] + 1] - rightSum[i + h][j - centerDis[h]]; centerSum[i][j] += rightSum[i - h][j + centerDis[h] + 1] - rightSum[i - h][j - centerDis[h]]; } } } for (i = r; i < n - r; i++) { rightMaxSum[i][m - r - 1] = centerSum[i][m - r - 1]; rightMaxNum[i][m - r - 1] = 1; for (j = m - r - 2; j >= r; j--) { if (centerSum[i][j] <= rightMaxSum[i][j + 1]) { rightMaxSum[i][j] = rightMaxSum[i][j + 1]; rightMaxNum[i][j] = rightMaxNum[i][j + 1]; if (centerSum[i][j] == rightMaxSum[i][j + 1]) { rightMaxNum[i][j]++; } } else { rightMaxSum[i][j] = centerSum[i][j]; rightMaxNum[i][j] = 1; } } } for (i = r; i < n - r; i++) { for (j = i + 2 * r + 1; j < n - r; j++) { if (rightMaxSum[i][r] + rightMaxSum[j][r] == ans) { ansNum += rightMaxNum[i][r] * rightMaxNum[j][r]; } else if (rightMaxSum[i][r] + rightMaxSum[j][r] > ans) { ans = rightMaxSum[i][r] + rightMaxSum[j][r]; ansNum = rightMaxNum[i][r] * rightMaxNum[j][r]; } } } for (i = r; i < n - r; i++) { for (j = r; j < m - r; j++) { for (h = 0; h <= 2 * r; h++) { if (j + centerPos[h] + r >= m) { continue; } if (i + h < n - r) { int score = centerSum[i][j] + rightMaxSum[i + h][j + centerPos[h]]; if (score == ans) { ansNum += rightMaxNum[i + h][j + centerPos[h]]; } else if (score > ans) { ans = score; ansNum = rightMaxNum[i + h][j + centerPos[h]]; } } if (h && i - h >= r) { int score = centerSum[i][j] + rightMaxSum[i - h][j + centerPos[h]]; if (score == ans) { ansNum += rightMaxNum[i - h][j + centerPos[h]]; } else if (score > ans) { ans = score; ansNum = rightMaxNum[i - h][j + centerPos[h]]; } } } } } printf("%d %lld\n", ans, ansNum); } return 0; } ```
### Prompt Please provide a cpp coded solution to the problem described below: In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation F1 = 1; F2 = 1; Fn = Fn - 1 + Fn - 2 (n > 2). DZY loves Fibonacci numbers very much. Today DZY gives you an array consisting of n integers: a1, a2, ..., an. Moreover, there are m queries, each query has one of the two types: 1. Format of the query "1 l r". In reply to the query, you need to add Fi - l + 1 to each element ai, where l ≤ i ≤ r. 2. Format of the query "2 l r". In reply to the query you should output the value of <image> modulo 1000000009 (109 + 9). Help DZY reply to all the queries. Input The first line of the input contains two integers n and m (1 ≤ n, m ≤ 300000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — initial array a. Then, m lines follow. A single line describes a single query in the format given in the statement. It is guaranteed that for each query inequality 1 ≤ l ≤ r ≤ n holds. Output For each query of the second type, print the value of the sum on a single line. Examples Input 4 4 1 2 3 4 1 1 4 2 1 4 1 2 4 2 1 3 Output 17 12 Note After the first query, a = [2, 3, 5, 7]. For the second query, sum = 2 + 3 + 5 + 7 = 17. After the third query, a = [2, 4, 6, 9]. For the fourth query, sum = 2 + 4 + 6 = 12. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = (int)3e5 + 5; const int MOD = (int)1e9 + 9; struct Mat { long long int m[2][2]; Mat() { for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { m[i][j] = 0; } } } Mat(bool id) { for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { m[i][j] = 1; } } if (id) { m[0][1] = m[1][0] = 0; } else { m[1][1] = 0; } } Mat operator*(const Mat& a) { Mat ans = Mat{}; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 2; k++) { ans.m[i][j] += m[i][k] * a.m[k][j]; ans.m[i][j] %= MOD; } } } return ans; } Mat operator+(const Mat& a) { Mat ans = Mat{}; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { ans.m[i][j] += m[i][j] + a.m[i][j]; if (ans.m[i][j] > MOD) { ans.m[i][j] -= MOD; } } } return ans; } }; struct Node { long long int sum; long long int Aup, Bup; Node() { sum = Aup = Bup = 0; } }; long long int a[MAXN]; Mat pw[MAXN]; Mat sum_pw[MAXN]; Node tree[4 * MAXN]; void pushdown(int node, int a, int b, long long int Aup, long long int Bup) { if (a == b) { return; } int mid = (a + b) / 2; tree[node * 2].Aup += Aup; tree[node * 2].Bup += Bup; tree[node * 2].Aup %= MOD; tree[node * 2].Bup %= MOD; long long int nAup = (pw[mid - a + 1].m[1][0] * Bup + pw[mid - a + 1].m[1][1] * Aup) % MOD; long long int nBup = (pw[mid - a + 1].m[0][0] * Bup + pw[mid - a + 1].m[0][1] * Aup) % MOD; tree[node * 2 + 1].Aup += nAup; tree[node * 2 + 1].Aup %= MOD; tree[node * 2 + 1].Bup += nBup; tree[node * 2 + 1].Bup %= MOD; return; } void resolve_lazy(int node, int a, int b) { if (tree[node].Aup != 0 || tree[node].Bup != 0) { tree[node].sum += sum_pw[b - a].m[1][0] * tree[node].Bup + sum_pw[b - a].m[1][1] * tree[node].Aup; tree[node].sum %= MOD; pushdown(node, a, b, tree[node].Aup, tree[node].Bup); tree[node].Aup = tree[node].Bup = 0; } return; } void update(int node, int a, int b, int l, int r, long long int Aup, long long int Bup) { resolve_lazy(node, a, b); if (b < l || a > r || a > b) { return; } if (l <= a && b <= r) { tree[node].sum += sum_pw[b - a].m[1][0] * Bup + sum_pw[b - a].m[1][1] * Aup; tree[node].sum %= MOD; pushdown(node, a, b, Aup, Bup); return; } int mid = (a + b) / 2; update(node * 2, a, mid, l, r, Aup, Bup); long long int nAup = (pw[max(0, mid - max(a, l) + 1)].m[1][0] * Bup + pw[max(0, mid - max(a, l) + 1)].m[1][1] * Aup) % MOD; long long int nBup = (pw[max(0, mid - max(a, l) + 1)].m[0][0] * Bup + pw[max(0, mid - max(a, l) + 1)].m[0][1] * Aup) % MOD; update(node * 2 + 1, mid + 1, b, l, r, nAup, nBup); tree[node].sum = tree[node * 2].sum + tree[node * 2 + 1].sum; tree[node].sum %= MOD; return; } long long int query(int node, int a, int b, int l, int r) { resolve_lazy(node, a, b); if (b < l || a > r || a > b) { return 0; } if (l <= a && b <= r) { return tree[node].sum; } int mid = (a + b) / 2; long long int q1 = query(node * 2, a, mid, l, r); long long int q2 = query(node * 2 + 1, mid + 1, b, l, r); return (q1 + q2) % MOD; } int main(void) { int n, m; int op, l, r; scanf(" %d %d", &n, &m); for (int i = 1; i <= n; i++) { scanf(" %lld", &a[i]); a[i] += a[i - 1]; } pw[0] = Mat(true); pw[1] = Mat(false); for (int i = 2; i <= n; i++) { pw[i] = pw[i - 1] * pw[1]; } sum_pw[0] = Mat(true); for (int i = 1; i <= n; i++) { sum_pw[i] = pw[i] + sum_pw[i - 1]; } while (m--) { scanf(" %d %d %d", &op, &l, &r); if (op == 1) { update(1, 1, n, l, r, 1, 1); } else { long long int ans = (a[r] - a[l - 1] + query(1, 1, n, l, r)) % MOD; printf("%lld\n", ans); } } return 0; } ```
### Prompt Your task is to create a Cpp solution to the following problem: The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: * If x = 1, exit the function. * Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. Input A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation. Output In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 2 1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n, i, j; scanf("%d", &n); if (n == 1) { printf("1\n"); return 0; } printf("%d", n); for (i = 1; i < n; i++) { printf(" %d", i); } printf("\n"); return 0; }; ```
### Prompt Construct a CPP code solution to the problem outlined: Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it. They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj < ai. A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally. Input The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card. Output If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes). Examples Input 3 4 5 7 Output Conan Input 2 1 1 Output Agasa Note In the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn. In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; const long long linf = 0x3f3f3f3fLL; const int EPS = 1e-6; const long long mod = 1000000007; int a[100010]; int maior[100010]; int main() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } sort(a, a + n); int last = a[n - 1]; int num = 0; int ind = 0; for (int i = n - 1; i >= 0; i--) { if (a[i] == last) { maior[ind]++; } else { ind++; maior[ind]++; last = a[i]; } } if (num % 2 == 1) { puts("Conan"); } else { for (int i = 0; i <= ind; i++) { if (maior[i] % 2 == 1) { puts("Conan"); return 0; } } puts("Agasa"); } return 0; } ```
### Prompt Please formulate a CPP solution to the following problem: Bob has a permutation of integers from 1 to n. Denote this permutation as p. The i-th element of p will be denoted as pi. For all pairs of distinct integers i, j between 1 and n, he wrote the number ai, j = min(pi, pj). He writes ai, i = 0 for all integer i from 1 to n. Bob gave you all the values of ai, j that he wrote down. Your job is to reconstruct any permutation that could have generated these values. The input will be formed so that it is guaranteed that there is at least one solution that is consistent with the information given. Input The first line of the input will contain a single integer n (2 ≤ n ≤ 50). The next n lines will contain the values of ai, j. The j-th number on the i-th line will represent ai, j. The i-th number on the i-th line will be 0. It's guaranteed that ai, j = aj, i and there is at least one solution consistent with the information given. Output Print n space separated integers, which represents a permutation that could have generated these values. If there are multiple possible solutions, print any of them. Examples Input 2 0 1 1 0 Output 2 1 Input 5 0 2 2 1 2 2 0 4 1 3 2 4 0 1 3 1 1 1 0 1 2 3 3 1 0 Output 2 5 4 1 3 Note In the first case, the answer can be {1, 2} or {2, 1}. In the second case, another possible answer is {2, 4, 5, 1, 3}. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long int x[100] = {0}; long long int a[100][100]; int solve() { long long int i, j, k, y, z, m, n, u, v, l, r, t, mx, mn, p; cin >> n; u = 0; for (i = 0; i < n; i++) { for (k = 0; k <= n; k++) x[k] = 0; mx = 0; for (j = 0; j < n; j++) { cin >> a[i][j]; if (i != j) x[a[i][j]]++; if (x[a[i][j]] > mx) { mx = x[a[i][j]]; v = a[i][j]; } } if (*max_element(x, x + n + 1) >= 2) { cout << v << " "; } else { if (u == 0) { cout << n << " "; u++; } else if (u == 1) { cout << n - 1 << " "; } } } return 0; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); solve(); return 0; } ```
### Prompt Develop a solution in CPP to the problem described below: After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards. Rules of this game are simple: each player bring his favourite n-digit credit card. Then both players name the digits written on their cards one by one. If two digits are not equal, then the player, whose digit is smaller gets a flick (knock in the forehead usually made with a forefinger) from the other player. For example, if n = 3, Sherlock's card is 123 and Moriarty's card has number 321, first Sherlock names 1 and Moriarty names 3 so Sherlock gets a flick. Then they both digit 2 so no one gets a flick. Finally, Sherlock names 3, while Moriarty names 1 and gets a flick. Of course, Sherlock will play honestly naming digits one by one in the order they are given, while Moriary, as a true villain, plans to cheat. He is going to name his digits in some other order (however, he is not going to change the overall number of occurences of each digit). For example, in case above Moriarty could name 1, 2, 3 and get no flicks at all, or he can name 2, 3 and 1 to give Sherlock two flicks. Your goal is to find out the minimum possible number of flicks Moriarty will get (no one likes flicks) and the maximum possible number of flicks Sherlock can get from Moriarty. Note, that these two goals are different and the optimal result may be obtained by using different strategies. Input The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of digits in the cards Sherlock and Moriarty are going to use. The second line contains n digits — Sherlock's credit card number. The third line contains n digits — Moriarty's credit card number. Output First print the minimum possible number of flicks Moriarty will get. Then print the maximum possible number of flicks that Sherlock can get from Moriarty. Examples Input 3 123 321 Output 0 2 Input 2 88 00 Output 2 0 Note First sample is elaborated in the problem statement. In the second sample, there is no way Moriarty can avoid getting two flicks. ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename A, typename B> string to_string(pair<A, B> p); template <typename A, typename B, typename C> string to_string(tuple<A, B, C> p); template <typename A, typename B, typename C, typename D> string to_string(tuple<A, B, C, D> p); string to_string(const string& s) { return '"' + s + '"'; } string to_string(const char* s) { return to_string((string)s); } string to_string(bool b) { return (b ? "true" : "false"); } string to_string(vector<bool> v) { bool first = true; string res = "{"; for (int i = 0; i < static_cast<int>(v.size()); i++) { if (!first) { res += ", "; } first = false; res += to_string(v[i]); } res += "}"; return res; } template <size_t N> string to_string(bitset<N> v) { string res = ""; for (size_t i = 0; i < N; i++) { res += static_cast<char>('0' + v[i]); } return res; } template <typename A> string to_string(A v) { bool first = true; string res = "{"; for (const auto& x : v) { if (!first) { res += ", "; } first = false; res += to_string(x); } res += "}"; return res; } template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; } template <typename A, typename B, typename C> string to_string(tuple<A, B, C> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")"; } template <typename A, typename B, typename C, typename D> string to_string(tuple<A, B, C, D> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")"; } void debug_out() { cerr << endl; } template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); } const double PI = 3.14159265359; const int mod = 1e9 + 7; const int inf = INT_MAX; const long long inf64 = LLONG_MAX; const unsigned long long uinf64 = ULLONG_MAX; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n; string a, b; cin >> n >> a >> b; vector<int> have_f(10, 0), have_s(10, 0); for (int i = 0; i < int(n); ++i) { ++have_f[a[i] - '0']; ++have_s[b[i] - '0']; } int min_Moriarty_get = 0; int max_Sherlock_get = 0; for (int i = 0; i < int(n); ++i) { int tg = b[i] - '0'; while (have_f[tg] == 0 && tg > 0) tg--; if (have_f[tg] > 0) { have_f[tg]--; } else { ++min_Moriarty_get; } tg = a[i] - '0'; int g = tg + 1; if (g == 10) continue; while (g < 9 && have_s[g] == 0) ++g; if (have_s[g] > 0) { --have_s[g]; ++max_Sherlock_get; } } cout << min_Moriarty_get << "\n"; cout << max_Sherlock_get << "\n"; } ```
### Prompt Construct a CPP code solution to the problem outlined: Ashish and Vivek play a game on a matrix consisting of n rows and m columns, where they take turns claiming cells. Unclaimed cells are represented by 0, while claimed cells are represented by 1. The initial state of the matrix is given. There can be some claimed cells in the initial state. In each turn, a player must claim a cell. A cell may be claimed if it is unclaimed and does not share a row or column with any other already claimed cells. When a player is unable to make a move, he loses and the game ends. If Ashish and Vivek take turns to move and Ashish goes first, determine the winner of the game if both of them are playing optimally. Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves. Input The first line consists of a single integer t (1 ≤ t ≤ 50) — the number of test cases. The description of the test cases follows. The first line of each test case consists of two space-separated integers n, m (1 ≤ n, m ≤ 50) — the number of rows and columns in the matrix. The following n lines consist of m integers each, the j-th integer on the i-th line denoting a_{i,j} (a_{i,j} ∈ \{0, 1\}). Output For each test case if Ashish wins the game print "Ashish" otherwise print "Vivek" (without quotes). Example Input 4 2 2 0 0 0 0 2 2 0 0 0 1 2 3 1 0 1 1 1 0 3 3 1 0 0 0 0 0 1 0 0 Output Vivek Ashish Vivek Ashish Note For the first case: One possible scenario could be: Ashish claims cell (1, 1), Vivek then claims cell (2, 2). Ashish can neither claim cell (1, 2), nor cell (2, 1) as cells (1, 1) and (2, 2) are already claimed. Thus Ashish loses. It can be shown that no matter what Ashish plays in this case, Vivek will win. For the second case: Ashish claims cell (1, 1), the only cell that can be claimed in the first move. After that Vivek has no moves left. For the third case: Ashish cannot make a move, so Vivek wins. For the fourth case: If Ashish claims cell (2, 3), Vivek will have no moves left. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int a[55][55]; int main() { int cs; scanf("%d", &cs); while (cs--) { int n, m; scanf("%d %d", &n, &m); int col = 0, row = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &a[i][j]); } } for (int i = 0; i < n; i++) { bool flag = true; for (int j = 0; j < m; j++) { if (a[i][j] & 1) { flag = false; break; } } if (flag) row++; } for (int i = 0; i < m; i++) { bool flag = true; for (int j = 0; j < n; j++) { if (a[j][i] & 1) { flag = false; break; } } if (flag) col++; } if (min(col, row) % 2) puts("Ashish"); else puts("Vivek"); } return 0; } ```
### Prompt In Cpp, your task is to solve the following problem: The array a with n integers is given. Let's call the sequence of one or more consecutive elements in a segment. Also let's call the segment k-good if it contains no more than k different values. Find any longest k-good segment. As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. Input The first line contains two integers n, k (1 ≤ k ≤ n ≤ 5·105) — the number of elements in a and the parameter k. The second line contains n integers ai (0 ≤ ai ≤ 106) — the elements of the array a. Output Print two integers l, r (1 ≤ l ≤ r ≤ n) — the index of the left and the index of the right ends of some k-good longest segment. If there are several longest segments you can print any of them. The elements in a are numbered from 1 to n from left to right. Examples Input 5 5 1 2 3 4 5 Output 1 5 Input 9 3 6 5 1 2 3 2 1 4 5 Output 3 7 Input 3 1 1 2 3 Output 1 1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxA = 1000000; pair<int, int> getMax(pair<int, int> a, pair<int, int> b) { if (a.second - a.first > b.second - b.first) return a; else return b; } int main() { int n, k, i, a; pair<int, int> result(-1, -1); cin >> n >> k; queue<int> q; int fr[maxA + 1] = {}, differentValues = 0; for (i = 0; i < n; i++) { cin >> a; if (!fr[a]) { differentValues++; q.push(a); fr[a]++; while (differentValues > k) { fr[q.front()]--; if (!fr[q.front()]) differentValues--; q.pop(); } } else q.push(a), fr[a]++; result = getMax(result, make_pair(i - ((int)q.size() - 1), i)); } cout << result.first + 1 << ' ' << result.second + 1; return 0; } ```
### Prompt Please formulate 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<cstdio> #include<algorithm> using namespace std; int n,x[101],y[101],h[101],X,Y,H,ans; int main() { scanf("%d",&n); for(int i=1;i<=n;++i) {scanf("%d%d%d",&x[i],&y[i],&h[i]);if(h[i]) {H=h[i];Y=y[i];X=x[i];}} for(int i=0;i<=100;++i) { for(int j=0;j<=100;++j) { ans=H+abs(X-i)+abs(Y-j); bool flag=false; for(int k=1;k<=n;++k) if((ans-abs(i-x[k])-abs(j-y[k])!=h[k]&&ans-abs(i-x[k])-abs(j-y[k])>=0)||(ans-abs(i-x[k])-abs(j-y[k])<0&&h[k]!=0)) {flag=true;break;} if(!flag) {printf("%d %d %d\n",i,j,ans);return 0;} } } return 0; } ```
### Prompt Please create a solution in CPP to the following problem: When little Petya grew up and entered the university, he started to take part in АСМ contests. Later he realized that he doesn't like how the АСМ contests are organised: the team could only have three members (and he couldn't take all his friends to the competitions and distribute the tasks between the team members efficiently), so he decided to organize his own contests PFAST Inc. — Petr and Friends Are Solving Tasks Corporation. PFAST Inc. rules allow a team to have unlimited number of members. To make this format of contests popular he organised his own tournament. To create the team he will prepare for the contest organised by the PFAST Inc. rules, he chose several volunteers (up to 16 people) and decided to compile a team from them. Petya understands perfectly that if a team has two people that don't get on well, then the team will perform poorly. Put together a team with as many players as possible given that all players should get on well with each other. Input The first line contains two integer numbers n (1 ≤ n ≤ 16) — the number of volunteers, and m (<image>) — the number of pairs that do not get on. Next n lines contain the volunteers' names (each name is a non-empty string consisting of no more than 10 uppercase and/or lowercase Latin letters). Next m lines contain two names — the names of the volunteers who do not get on. The names in pair are separated with a single space. Each pair of volunteers who do not get on occurs exactly once. The strings are case-sensitive. All n names are distinct. Output The first output line should contain the single number k — the number of people in the sought team. Next k lines should contain the names of the sought team's participants in the lexicographical order. If there are several variants to solve the problem, print any of them. Petya might not be a member of the sought team. Examples Input 3 1 Petya Vasya Masha Petya Vasya Output 2 Masha Petya Input 3 0 Pasha Lesha Vanya Output 3 Lesha Pasha Vanya ### Response ```cpp #include <bits/stdc++.h> using namespace std; const double eps = 1e-10; const int inf = (int)1e9; map<string, int> mm; const int maxn = 110; int a[maxn][maxn]; int bc[maxn * maxn * 10]; string ss[maxn]; int main() { int n, m; cin >> n >> m; string s; for (int i = 0; i < n; i++) { cin >> s; ss[i] = s; mm[s] = i; } string s1, s2; for (int i = 0; i < m; i++) { cin >> s1 >> s2; a[mm[s1]][mm[s2]] = 1; a[mm[s2]][mm[s1]] = 1; } for (int i = 1; i < (1 << n); i++) bc[i] = bc[i >> 1] + (i & 1); int res = 0, resm = 0; for (int i = 1; i < (1 << n); i++) { vector<int> v; for (int j = 0; j < n; j++) if ((i >> j) & 1) v.push_back(j); int good = 1; for (int i1 = 0; i1 < ((int)(v).size()) && good; i1++) for (int i2 = 0; i2 < ((int)(v).size()) && good; i2++) if (a[v[i1]][v[i2]]) good = 0; if (good && bc[i] > res) res = bc[i], resm = i; } cout << res << endl; vector<string> vs; for (int i = 0; i < n; i++) if ((resm >> i) & 1) vs.push_back(ss[i]); sort(vs.begin(), vs.end()); for (int i = 0; i < ((int)(vs).size()); i++) cout << vs[i] << endl; return 0; } ```
### Prompt Please provide a cpp coded solution to the problem described below: Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them. The tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point (0, 0). While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to OX or OY axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification. Alexey wants to make a polyline in such a way that its end is as far as possible from (0, 0). Please help him to grow the tree this way. Note that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches. Input The first line contains an integer n (1 ≤ n ≤ 100 000) — the number of sticks Alexey got as a present. The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10 000) — the lengths of the sticks. Output Print one integer — the square of the largest possible distance from (0, 0) to the tree end. Examples Input 3 1 2 3 Output 26 Input 4 1 1 2 2 Output 20 Note The following pictures show optimal trees for example tests. The squared distance in the first example equals 5 ⋅ 5 + 1 ⋅ 1 = 26, and in the second example 4 ⋅ 4 + 2 ⋅ 2 = 20. <image> <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; signed main() { ios_base::sync_with_stdio(false), cin.tie(0), cout.precision(17); long long n; cin >> n; long long a[n]; for (long long i = 0; i < n; i++) cin >> a[i]; sort(a, a + n); long long sa = 0, sb = 0; for (long long i = 0; i < n / 2; i++) sa += a[i]; for (long long i = 0; i < n; i++) sb += a[i]; sb -= sa; cout << sa * sa + sb * sb << endl; return 0; } ```
### Prompt Please provide a cpp coded solution to the problem described below: RJ Freight, a Japanese railroad company for freight operations has recently constructed exchange lines at Hazawa, Yokohama. The layout of the lines is shown in Figure B-1. <image> Figure B-1: Layout of the exchange lines A freight train consists of 2 to 72 freight cars. There are 26 types of freight cars, which are denoted by 26 lowercase letters from "a" to "z". The cars of the same type are indistinguishable from each other, and each car's direction doesn't matter either. Thus, a string of lowercase letters of length 2 to 72 is sufficient to completely express the configuration of a train. Upon arrival at the exchange lines, a train is divided into two sub-trains at an arbitrary position (prior to entering the storage lines). Each of the sub-trains may have its direction reversed (using the reversal line). Finally, the two sub-trains are connected in either order to form the final configuration. Note that the reversal operation is optional for each of the sub-trains. For example, if the arrival configuration is "abcd", the train is split into two sub-trains of either 3:1, 2:2 or 1:3 cars. For each of the splitting, possible final configurations are as follows ("+" indicates final concatenation position): [3:1] abc+d cba+d d+abc d+cba [2:2] ab+cd ab+dc ba+cd ba+dc cd+ab cd+ba dc+ab dc+ba [1:3] a+bcd a+dcb bcd+a dcb+a Excluding duplicates, 12 distinct configurations are possible. Given an arrival configuration, answer the number of distinct configurations which can be constructed using the exchange lines described above. Input The entire input looks like the following. > the number of datasets = m > 1st dataset > 2nd dataset > ... > m-th dataset > Each dataset represents an arriving train, and is a string of 2 to 72 lowercase letters in an input line. Output For each dataset, output the number of possible train configurations in a line. No other characters should appear in the output. Example Input 4 aa abba abcd abcde Output 1 6 12 18 ### Response ```cpp #include <bits/stdc++.h> using namespace std; #define rep(i,a,b) for(int i=a;i<b;i++) int main() { int m; cin >> m; rep(_m, 0, m) { string s; cin >> s; set<string> _set; _set.insert(s); rep(i, 1, s.length()) { string a = s.substr(0, i); string b = s.substr(i); string aa = a; reverse(aa.begin(), aa.end()); string bb = b; reverse(bb.begin(), bb.end()); _set.insert(a + bb); _set.insert(aa + b); _set.insert(aa + bb); _set.insert(b + a); _set.insert(b + aa); _set.insert(bb + a); _set.insert(bb + aa); } cout << _set.size() << endl; } } ```
### Prompt Generate a CPP solution to the following problem: The final round of Bayan Programming Contest will be held in Tehran, and the participants will be carried around with a yellow bus. The bus has 34 passenger seats: 4 seats in the last row and 3 seats in remaining rows. <image> The event coordinator has a list of k participants who should be picked up at the airport. When a participant gets on the bus, he will sit in the last row with an empty seat. If there is more than one empty seat in that row, he will take the leftmost one. In order to keep track of the people who are on the bus, the event coordinator needs a figure showing which seats are going to be taken by k participants. Your task is to draw the figure representing occupied seats. Input The only line of input contains integer k, (0 ≤ k ≤ 34), denoting the number of participants. Output Print the figure of a bus with k passengers as described in sample tests. Character '#' denotes an empty seat, while 'O' denotes a taken seat. 'D' is the bus driver and other characters in the output are for the purpose of beautifying the figure. Strictly follow the sample test cases output format. Print exactly six lines. Do not output extra space or other characters. Examples Input 9 Output +------------------------+ |O.O.O.#.#.#.#.#.#.#.#.|D|) |O.O.O.#.#.#.#.#.#.#.#.|.| |O.......................| |O.O.#.#.#.#.#.#.#.#.#.|.|) +------------------------+ Input 20 Output +------------------------+ |O.O.O.O.O.O.O.#.#.#.#.|D|) |O.O.O.O.O.O.#.#.#.#.#.|.| |O.......................| |O.O.O.O.O.O.#.#.#.#.#.|.|) +------------------------+ ### Response ```cpp #include <bits/stdc++.h> using namespace std; bool b[11][4]; int main() { int k; cin >> k; if (k > 0) b[0][0] = 1; if (k > 1) b[0][1] = 1; if (k > 2) b[0][2] = 1; if (k > 3) b[0][3] = 1; if (k > 4) { k = k - 4; int r = k % 3; int x = k / 3; for (int i = 1; i <= x; i++) { b[i][0] = 1; b[i][1] = 1; b[i][3] = 1; } if (r >= 1) b[x + 1][0] = 1; if (r >= 2) b[x + 1][1] = 1; } cout << '+'; for (int i = 0; i < 24; i++) cout << '-'; cout << '+'; cout << endl; cout << '|'; for (int i = 0; i < 11; i++) { if (b[i][0] == 1) cout << 'O' << '.'; else cout << '#' << '.'; } cout << "|D|)" << endl; cout << '|'; for (int i = 0; i < 11; i++) { if (b[i][1] == 1) cout << 'O' << '.'; else cout << '#' << '.'; } cout << "|.|" << endl; cout << '|'; if (b[0][2] == 1) cout << 'O' << '.'; else cout << '#' << '.'; for (int i = 0; i < 20; i++) cout << '.'; cout << "..|" << endl; cout << '|'; for (int i = 0; i < 11; i++) { if (b[i][3] == 1) cout << 'O' << '.'; else cout << '#' << '.'; } cout << "|.|)" << endl; cout << "+------------------------+" << endl; return 0; } ```
### Prompt Your challenge is to write a cpp solution to the following problem: Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to <image>. Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it. He painted a few lines, parallel to the sides of the hexagon. The lines split the hexagon into regular triangles with sides of 1 centimeter. Now Gerald wonders how many triangles he has got. But there were so many of them that Gerald lost the track of his counting. Help the boy count the triangles. Input The first and the single line of the input contains 6 space-separated integers a1, a2, a3, a4, a5 and a6 (1 ≤ ai ≤ 1000) — the lengths of the sides of the hexagons in centimeters in the clockwise order. It is guaranteed that the hexagon with the indicated properties and the exactly such sides exists. Output Print a single integer — the number of triangles with the sides of one 1 centimeter, into which the hexagon is split. Examples Input 1 1 1 1 1 1 Output 6 Input 1 2 1 2 1 2 Output 13 Note This is what Gerald's hexagon looks like in the first sample: <image> And that's what it looks like in the second sample: <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long a, b, c, d, e, f; int main() { cin >> a >> b >> c >> d >> e >> f; long long t = (e + f) * (4ll * a + 2ll * f + 2ll * b); long long s = (f * f + e * e + b * b + c * c); long long ans = t - s; assert(ans % 2ll == 0ll); cout << ans / 2ll << endl; } ```
### Prompt Generate a Cpp solution to the following problem: You have to handle a very complex water distribution system. The system consists of n junctions and m pipes, i-th pipe connects junctions x_i and y_i. The only thing you can do is adjusting the pipes. You have to choose m integer numbers f_1, f_2, ..., f_m and use them as pipe settings. i-th pipe will distribute f_i units of water per second from junction x_i to junction y_i (if f_i is negative, then the pipe will distribute |f_i| units of water per second from junction y_i to junction x_i). It is allowed to set f_i to any integer from -2 ⋅ 10^9 to 2 ⋅ 10^9. In order for the system to work properly, there are some constraints: for every i ∈ [1, n], i-th junction has a number s_i associated with it meaning that the difference between incoming and outcoming flow for i-th junction must be exactly s_i (if s_i is not negative, then i-th junction must receive s_i units of water per second; if it is negative, then i-th junction must transfer |s_i| units of water per second to other junctions). Can you choose the integers f_1, f_2, ..., f_m in such a way that all requirements on incoming and outcoming flows are satisfied? Input The first line contains an integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of junctions. The second line contains n integers s_1, s_2, ..., s_n (-10^4 ≤ s_i ≤ 10^4) — constraints for the junctions. The third line contains an integer m (0 ≤ m ≤ 2 ⋅ 10^5) — the number of pipes. i-th of the next m lines contains two integers x_i and y_i (1 ≤ x_i, y_i ≤ n, x_i ≠ y_i) — the description of i-th pipe. It is guaranteed that each unordered pair (x, y) will appear no more than once in the input (it means that there won't be any pairs (x, y) or (y, x) after the first occurrence of (x, y)). It is guaranteed that for each pair of junctions there exists a path along the pipes connecting them. Output If you can choose such integer numbers f_1, f_2, ..., f_m in such a way that all requirements on incoming and outcoming flows are satisfied, then output "Possible" in the first line. Then output m lines, i-th line should contain f_i — the chosen setting numbers for the pipes. Pipes are numbered in order they appear in the input. Otherwise output "Impossible" in the only line. Examples Input 4 3 -10 6 1 5 1 2 3 2 2 4 3 4 3 1 Output Possible 4 -6 8 -7 7 Input 4 3 -10 6 4 5 1 2 3 2 2 4 3 4 3 1 Output Impossible ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long int Pow(long long int a, long long int b, long long int md, long long int ans = 1) { for (; b; b >>= 1, a = a * a % md) if (b & 1) ans = ans * a % md; return ans % md; } const long long int MAXN = 1e6 + 10; const long long int INF = 8e18; const long long int MOD = 1e9 + 7; long long int U[MAXN], V[MAXN], par[MAXN], mark[MAXN], ans[MAXN], deg[MAXN], A[MAXN], d[MAXN], n, m, sum = 0; vector<long long int> adj[2][MAXN]; map<pair<long long int, long long int>, long long int> ind; void DFS(long long int v) { mark[v] = 1; for (long long int u : adj[0][v]) { if (mark[u] == 1) continue; d[u]++, d[v]++; adj[1][u].push_back(v); adj[1][v].push_back(u); par[u] = v; DFS(u); } } void BFS() { queue<long long int> Q; for (long long int i = 2; i <= n; i++) { if ((long long int)adj[1][i].size() == 1) Q.push(i); } while ((long long int)Q.size()) { long long int x, v = Q.front(); Q.pop(); x = A[v] - deg[v]; deg[par[v]] -= x; ans[ind[{v, par[v]}]] = ans[ind[{par[v], v}]] = x; d[par[v]]--; if (d[par[v]] == 1) Q.push(par[v]); } } int main() { scanf("%lld", &n); for (long long int i = 1; i <= n; i++) scanf("%lld", &A[i]), sum += A[i]; scanf("%lld", &m); for (long long int i = 1; i <= m; i++) { long long int u, v; scanf("%lld%lld", &u, &v); adj[0][v].push_back(u); adj[0][u].push_back(v); ind[{u, v}] = ind[{v, u}] = i, U[i] = u, V[i] = v; } if (sum != 0) return !printf("Impossible\n"); DFS(1); BFS(); printf("Possible\n"); for (long long int i = 1; i <= m; i++) { long long int u = U[i], v = V[i]; if (par[u] == v) printf("%lld\n", -ans[i]); else printf("%lld\n", ans[i]); } return 0; } ```
### Prompt Construct a CPP code solution to the problem outlined: Limak can repeatedly remove one of the first two characters of a string, for example abcxyx \rightarrow acxyx \rightarrow cxyx \rightarrow cyx. You are given N different strings S_1, S_2, \ldots, S_N. Among N \cdot (N-1) / 2 pairs (S_i, S_j), in how many pairs could Limak obtain one string from the other? Constraints * 2 \leq N \leq 200\,000 * S_i consists of lowercase English letters `a`-`z`. * S_i \neq S_j * 1 \leq |S_i| * |S_1| + |S_2| + \ldots + |S_N| \leq 10^6 Input Input is given from Standard Input in the following format. N S_1 S_2 \vdots S_N Output Print the number of unordered pairs (S_i, S_j) where i \neq j and Limak can obtain one string from the other. Examples Input 3 abcxyx cyx abc Output 1 Input 6 b a abc c d ab Output 5 ### Response ```cpp #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll,ll> pii; #define mkp make_pair const ll H1=257,H2=114,M1=1e9+7,M2=19260817; int n,T; char c[1000004]; bool ok[1000004][26]; string s[200004]; int p[200004]; map<pii,int>mp; ll ans=0; bool cmp(int a,int b){ return s[a].size()>s[b].size(); } void reads(string &S){ S="";register char ch=getchar(); for(;ch<'a'||ch>'z';ch=getchar()); for(;ch>='a'&&ch<='z';S+=ch,ch=getchar()); } int main(){ cin>>T; for(int i=0;i<T;i++)reads(s[i]),p[i]=i; sort(p,p+T,cmp); while(T>0){ T--; n=s[p[T]].size(); for(int i=0;i<n;i++)c[n-i-1]=s[p[T]][i]; for(int i=0;i<26;i++)ok[n][i]=0; for(int i=n-1;i>=0;i--){ for(int j=0;j<26;j++)ok[i][j]=ok[i+1][j]; ok[i][c[i]-'a']=1; } ll r1=0,r2=0; for(int i=0;i<n-1;i++){ int msk=mp[mkp(r1,r2)]; for(int j=0;j<26;j++)if((msk&(1<<j))>0&&ok[i][j])ans++; r1=(r1*H1+c[i])%M1,r2=(r2*H2+c[i])%M2; } mp[mkp(r1,r2)]|=(1<<(c[n-1]-'a')); } cout<<ans; } ```
### Prompt Please create a solution in cpp to the following problem: We have a grid with N rows and N columns. The cell at the i-th row and j-th column is denoted (i, j). Initially, M of the cells are painted black, and all other cells are white. Specifically, the cells (a_1, b_1), (a_2, b_2), ..., (a_M, b_M) are painted black. Snuke will try to paint as many white cells black as possible, according to the following rule: * If two cells (x, y) and (y, z) are both black and a cell (z, x) is white for integers 1≤x,y,z≤N, paint the cell (z, x) black. Find the number of black cells when no more white cells can be painted black. Constraints * 1≤N≤10^5 * 1≤M≤10^5 * 1≤a_i,b_i≤N * All pairs (a_i, b_i) are distinct. Input The input is given from Standard Input in the following format: N M a_1 b_1 a_2 b_2 : a_M b_M Output Print the number of black cells when no more white cells can be painted black. Examples Input 3 2 1 2 2 3 Output 3 Input 2 2 1 1 1 2 Output 4 Input 4 3 1 2 1 3 4 4 Output 3 ### Response ```cpp #include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #define File(s) freopen(s".in","r",stdin),freopen(s".out","w",stdout) #define maxn 100010 using namespace std; typedef long long llg; int hd[maxn],nt[maxn<<1],to[maxn<<1],c[maxn<<1],tt; int n,m,co[maxn],SIZ,cm,du[maxn]; bool vis[maxn],su; llg ans,ci[3]; void dfs(int u){ vis[u]=1; SIZ++; ci[co[u]]++; cm+=du[u]; for(int i=hd[u],v;v=to[i],i;i=nt[i]) if(!vis[v]) co[v]=(co[u]+c[i])%3,dfs(v); else if(co[v]!=(co[u]+c[i])%3) su=1; } int main(){ scanf("%d %d",&n,&m); for(int i=1,x,y;i<=m;i++){ scanf("%d %d",&x,&y); to[++tt]=y;nt[tt]=hd[x];hd[x]=tt; to[++tt]=x;nt[tt]=hd[y];hd[y]=tt; c[tt-1]=1; c[tt]=2; du[x]++,du[y]++; } for(int i=1,now;i<=n;i++) if(!vis[i]){ dfs(i); if(su) ans+=1ll*SIZ*SIZ; else{ now=(!ci[0])+(!ci[1])+(!ci[2]); if(!now) ans+=ci[0]*ci[1]+ci[1]*ci[2]+ci[2]*ci[0]; else ans+=cm>>1; } ci[0]=ci[1]=ci[2]=0; SIZ=cm=0; su=0; } printf("%lld",ans); return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: Polycarp likes to play with numbers. He takes some integer number x, writes it down on the board, and then performs with it n - 1 operations of the two kinds: * divide the number x by 3 (x must be divisible by 3); * multiply the number x by 2. After each operation, Polycarp writes down the result on the board and replaces x by the result. So there will be n numbers on the board after all. You are given a sequence of length n — the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board. Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number. It is guaranteed that the answer exists. Input The first line of the input contatins an integer number n (2 ≤ n ≤ 100) — the number of the elements in the sequence. The second line of the input contains n integer numbers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 3 ⋅ 10^{18}) — rearranged (reordered) sequence that Polycarp can wrote down on the board. Output Print n integer numbers — rearranged (reordered) input sequence that can be the sequence that Polycarp could write down on the board. It is guaranteed that the answer exists. Examples Input 6 4 8 6 3 12 9 Output 9 3 6 12 4 8 Input 4 42 28 84 126 Output 126 42 84 28 Input 2 1000000000000000000 3000000000000000000 Output 3000000000000000000 1000000000000000000 Note In the first example the given sequence can be rearranged in the following way: [9, 3, 6, 12, 4, 8]. It can match possible Polycarp's game which started with x = 9. ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename S, typename T> ostream& operator<<(ostream& out, const pair<S, T> p) { out << "(" << p.first << "," << p.second << ")"; return out; } template <typename T> ostream& operator<<(ostream& out, const vector<T>& v) { for (auto a : v) out << a << " "; return out; } template <typename T> ostream& operator<<(ostream& out, const set<T>& S) { for (auto a : S) cout << a << " "; return out; } template <typename T> ostream& operator<<(ostream& out, const multiset<T>& S) { for (auto a : S) cout << a << " "; return out; } template <typename S, typename T> ostream& operator<<(ostream& out, const map<S, T>& M) { for (auto m : M) cout << "(" << m.first << "->" << m.second << ") "; return out; } template <typename S, typename T> pair<S, T> operator+(pair<S, T> a, pair<S, T> b) { return make_pair(a.first + b.first, a.second + b.second); } template <typename S, typename T> pair<S, T> operator-(pair<S, T> a, pair<S, T> b) { return make_pair(a.first - b.first, a.second - b.second); } vector<long long> solve(vector<long long>& A) { int n = A.size(); vector<pair<int, int>> B; for (auto a : A) { int order_2 = 0; int order_3 = 0; while (a % 2 == 0) { a /= 2; order_2++; } while (a % 3 == 0) { a /= 3; order_3++; } B.emplace_back(order_2, order_3); } vector<int> sa(n); for (int i = 0; i < n; i++) sa[i] = i; sort(sa.begin(), sa.end(), [&](int x, int y) { if (B[x].first != B[y].first) return B[x].first < B[y].first; return B[x].second > B[y].second; }); vector<long long> ans(n); for (int i = 0; i < n; i++) ans[i] = A[sa[i]]; return ans; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; vector<long long> A; cin >> n; A.resize(n); for (int i = 0; i < n; i++) cin >> A[i]; auto ans = solve(A); cout << ans << endl; return 0; } ```
### Prompt Generate a cpp solution to the following problem: You are given a grid, consisting of 2 rows and n columns. Each cell of this grid should be colored either black or white. Two cells are considered neighbours if they have a common border and share the same color. Two cells A and B belong to the same component if they are neighbours, or if there is a neighbour of A that belongs to the same component with B. Let's call some bicoloring beautiful if it has exactly k components. Count the number of beautiful bicolorings. The number can be big enough, so print the answer modulo 998244353. Input The only line contains two integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ 2n) — the number of columns in a grid and the number of components required. Output Print a single integer — the number of beautiful bicolorings modulo 998244353. Examples Input 3 4 Output 12 Input 4 1 Output 2 Input 1 2 Output 2 Note One of possible bicolorings in sample 1: <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, k; const int mod = 998244353; long long dp[1005][2005][4]; int main() { scanf("%d%d", &n, &k); dp[1][1][0] = 1; dp[1][2][1] = 1; dp[1][2][2] = 1; dp[1][1][3] = 1; for (int i = 2; i <= n; i++) { for (int j = 1; j <= (i << 1); j++) { dp[i][j][0] = (dp[i][j][0] + dp[i - 1][j][0] + dp[i - 1][j][1] + dp[i - 1][j][2] + dp[i - 1][j - 1][3]) % mod; dp[i][j][1] = (dp[i][j][1] + dp[i - 1][j - 1][0] + dp[i - 1][j][1] + dp[i - 1][j - 2][2] + dp[i - 1][j - 1][3]) % mod; dp[i][j][2] = (dp[i][j][2] + dp[i - 1][j - 1][0] + dp[i - 1][j - 2][1] + dp[i - 1][j][2] + dp[i - 1][j - 1][3]) % mod; dp[i][j][3] = (dp[i][j][3] + dp[i - 1][j - 1][0] + dp[i - 1][j][1] + dp[i - 1][j][2] + dp[i - 1][j][3]) % mod; } } printf("%lld\n", (dp[n][k][0] + dp[n][k][1] + dp[n][k][2] + dp[n][k][3]) % mod); } ```
### Prompt Please provide a Cpp coded solution to the problem described below: You are given an array a consisting of n integers numbered from 1 to n. Let's define the k-amazing number of the array as the minimum number that occurs in all of the subsegments of the array having length k (recall that a subsegment of a of length k is a contiguous part of a containing exactly k elements). If there is no integer occuring in all subsegments of length k for some value of k, then the k-amazing number is -1. For each k from 1 to n calculate the k-amazing number of the array a. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5. Output For each test case print n integers, where the i-th integer is equal to the i-amazing number of the array. Example Input 3 5 1 2 3 4 5 5 4 4 4 4 2 6 1 3 1 5 3 1 Output -1 -1 3 2 1 -1 4 4 4 2 -1 -1 1 1 1 1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 3e5 + 7; int a[N], last[N], res[N], resk[N]; int main() { resk[0] = 0x3f3f3f3f; int T; scanf("%d", &T); while (T--) { int n; scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", &a[i]), last[a[i]] = -1, resk[i] = 0x3f3f3f3f; for (int i = 1; i <= n; ++i) { if (last[a[i]] == -1) res[a[i]] = i; else res[a[i]] = max(res[a[i]], i - last[a[i]]); last[a[i]] = i; } for (int i = 1; i <= n; ++i) res[a[i]] = max(res[a[i]], n - last[a[i]] + 1); for (int i = 1; i <= n; ++i) { resk[res[a[i]]] = min(resk[res[a[i]]], a[i]); } for (int i = 1; i <= n; ++i) resk[i] = min(resk[i], resk[i - 1]); for (int i = 1; i <= n; ++i) printf("%d ", (resk[i] == 0x3f3f3f3f ? -1 : resk[i])); puts(""); } return 0; } ```
### Prompt Generate a CPP solution to the following problem: Vasya plays The Elder Trolls IV: Oblivon. Oh, those creators of computer games! What they do not come up with! Absolutely unique monsters have been added to the The Elder Trolls IV: Oblivon. One of these monsters is Unkillable Slug. Why it is "Unkillable"? Firstly, because it can be killed with cutting weapon only, so lovers of two-handed amber hammers should find suitable knife themselves. Secondly, it is necessary to make so many cutting strokes to Unkillable Slug. Extremely many. Too many! Vasya has already promoted his character to 80-th level and in order to gain level 81 he was asked to kill Unkillable Slug. The monster has a very interesting shape. It looks like a rectangular parallelepiped with size x × y × z, consisting of undestructable cells 1 × 1 × 1. At one stroke Vasya can cut the Slug along an imaginary grid, i.e. cut with a plane parallel to one of the parallelepiped side. Monster dies when amount of parts it is divided reaches some critical value. All parts of monster do not fall after each cut, they remains exactly on its places. I. e. Vasya can cut several parts with one cut. Vasya wants to know what the maximum number of pieces he can cut the Unkillable Slug into striking him at most k times. Vasya's character uses absolutely thin sword with infinite length. Input The first line of input contains four integer numbers x, y, z, k (1 ≤ x, y, z ≤ 106, 0 ≤ k ≤ 109). Output Output the only number — the answer for the problem. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). Examples Input 2 2 2 3 Output 8 Input 2 2 2 1 Output 2 Note In the first sample Vasya make 3 pairwise perpendicular cuts. He cuts monster on two parts with the first cut, then he divides each part on two with the second cut, and finally he divides each of the 4 parts on two. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { long long k, i, j; vector<long long> x, cuts(3, 0); for (int i = 0; i < 3; ++i) { int f; cin >> f; x.push_back(f); } cin >> k; sort(x.begin(), x.end()); j = 0; while (k) { if (cuts[0] == x[0] - 1 && cuts[1] == x[1] - 1 && cuts[2] == x[2] - 1) break; if (cuts[j] < x[j] - 1) { cuts[j]++; k--; } j = (j + 1) % 3; } cout << (cuts[0] + 1) * (cuts[1] + 1) * (cuts[2] + 1) << "\n"; return 0; } ```
### Prompt Develop a solution in CPP to the problem described below: Melody Pond was stolen from her parents as a newborn baby by Madame Kovarian, to become a weapon of the Silence in their crusade against the Doctor. Madame Kovarian changed Melody's name to River Song, giving her a new identity that allowed her to kill the Eleventh Doctor. Heidi figured out that Madame Kovarian uses a very complicated hashing function in order to change the names of the babies she steals. In order to prevent this from happening to future Doctors, Heidi decided to prepare herself by learning some basic hashing techniques. The first hashing function she designed is as follows. Given two positive integers (x, y) she defines H(x,y):=x^2+2xy+x+1. Now, Heidi wonders if the function is reversible. That is, given a positive integer r, can you find a pair (x, y) (of positive integers) such that H(x, y) = r? If multiple such pairs exist, output the one with smallest possible x. If there is no such pair, output "NO". Input The first and only line contains an integer r (1 ≤ r ≤ 10^{12}). Output Output integers x, y such that H(x,y) = r and x is smallest possible, or "NO" if no such pair exists. Examples Input 19 Output 1 8 Input 16 Output NO ### Response ```cpp #include <bits/stdc++.h> using namespace std; int min(int a, int b) { if (a > b) return b; return a; } int main() { unsigned long long n; std::cin >> n; if (n == 1) { std::cout << "NO" << '\n'; return 0; } if (n % 2 == 0) { std::cout << "NO" << '\n'; return 0; } for (unsigned long long x = 1; x <= (sqrt(4 * n - 3) - 1) / 2; x++) { unsigned long long t = x * x + x + 1; if (t < n && t % 2 != 0) { std::cout << x << " " << (n - t) / 2 << '\n'; return 0; } } std::cout << "NO" << '\n'; return 0; } ```
### Prompt Your task is to create a CPP solution to the following problem: Snuke has a string S consisting of three kinds of letters: `a`, `b` and `c`. He has a phobia for palindromes, and wants to permute the characters in S so that S will not contain a palindrome of length 2 or more as a substring. Determine whether this is possible. Constraints * 1 \leq |S| \leq 10^5 * S consists of `a`, `b` and `c`. Input Input is given from Standard Input in the following format: S Output If the objective is achievable, print `YES`; if it is unachievable, print `NO`. Examples Input abac Output YES Input aba Output NO Input babacccabab Output YES ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { string S; cin >> S; int num[3] = { 0 }; for (char c : S) { num[c - 'a']++; } int max_num = INT_MIN, min_num = INT_MAX; for (int i = 0; i < 3; i++) { max_num = max(max_num, num[i]); min_num = min(min_num, num[i]); } if (max_num - min_num >= 2) { cout << "NO" << endl; } else { cout << "YES" << endl; } } ```
### Prompt Construct a Cpp code solution to the problem outlined: You are given two n × m matrices containing integers. A sequence of integers is strictly increasing if each next number is greater than the previous one. A row is strictly increasing if all numbers from left to right are strictly increasing. A column is strictly increasing if all numbers from top to bottom are strictly increasing. A matrix is increasing if all rows are strictly increasing and all columns are strictly increasing. For example, the matrix \begin{bmatrix} 9&10&11\\\ 11&12&14\\\ \end{bmatrix} is increasing because each individual row and column is strictly increasing. On the other hand, the matrix \begin{bmatrix} 1&1\\\ 2&3\\\ \end{bmatrix} is not increasing because the first row is not strictly increasing. Let a position in the i-th row (from top) and j-th column (from left) in a matrix be denoted as (i, j). In one operation, you can choose any two numbers i and j and swap the number located in (i, j) in the first matrix with the number in (i, j) in the second matrix. In other words, you can swap two numbers in different matrices if they are located in the corresponding positions. You would like to make both matrices increasing by performing some number of operations (possibly none). Determine if it is possible to do this. If it is, print "Possible", otherwise, print "Impossible". Input The first line contains two integers n and m (1 ≤ n,m ≤ 50) — the dimensions of each matrix. Each of the next n lines contains m integers a_{i1}, a_{i2}, …, a_{im} (1 ≤ a_{ij} ≤ 10^9) — the number located in position (i, j) in the first matrix. Each of the next n lines contains m integers b_{i1}, b_{i2}, …, b_{im} (1 ≤ b_{ij} ≤ 10^9) — the number located in position (i, j) in the second matrix. Output Print a string "Impossible" or "Possible". Examples Input 2 2 2 10 11 5 9 4 3 12 Output Possible Input 2 3 2 4 5 4 5 6 3 6 7 8 10 11 Output Possible Input 3 2 1 3 2 4 5 10 3 1 3 6 4 8 Output Impossible Note The first example, we can do an operation on the top left and bottom right cells of the matrices. The resulting matrices will be \begin{bmatrix} 9&10\\\ 11&12\\\ \end{bmatrix} and \begin{bmatrix} 2&4\\\ 3&5\\\ \end{bmatrix}. In the second example, we don't need to do any operations. In the third example, no matter what we swap, we can't fix the first row to be strictly increasing in both matrices. ### Response ```cpp #include <bits/stdc++.h> using namespace std; typedef long long int ll; typedef long double ld; const ll N = 1e9 + 7, N1 = 1e6 + 7; signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ; ll n, m; cin >> n >> m; ll a[n][m], b[n][m]; for (long long i = 0; i < n; i++) { for (long long j = 0; j < m; j++) { cin >> a[i][j]; } } for (long long i = 0; i < n; i++) { for (long long j = 0; j < m; j++) { cin >> b[i][j]; } } for (long long i = 0; i < m; i++) { for (long long j = 0; j < n - 1; j++) { if (a[j + 1][i] <= a[j][i]) { if (b[j + 1][i] > a[j][i] && a[j + 1][i] > b[j][i]) { swap(b[j + 1][i], a[j + 1][i]); } else { cout << "Impossible" << "\n"; return 0; } } } } for (long long i = 0; i < n; i++) { for (long long j = 0; j < m - 1; j++) { if (a[i][j + 1] <= a[i][j]) { if (b[i][j + 1] > a[i][j] && a[i][j + 1] > b[i][j]) { swap(b[i][j + 1], a[i][j + 1]); } else { cout << "Impossible" << "\n"; return 0; } } } } for (long long i = 0; i < m; i++) { for (long long j = 0; j < n - 1; j++) { if (b[j + 1][i] <= b[j][i]) { if (a[j + 1][i] > b[j][i] && b[j + 1][i] > a[j][i]) { swap(b[j + 1][i], a[j + 1][i]); } else { cout << "Impossible" << "\n"; return 0; } } } } for (long long i = 0; i < n; i++) { for (long long j = 0; j < m - 1; j++) { if (b[i][j + 1] <= b[i][j]) { if (a[i][j + 1] > b[i][j] && b[i][j + 1] > a[i][j]) { swap(b[i][j + 1], a[i][j + 1]); } else { cout << "Impossible" << "\n"; return 0; } } } } cout << "Possible" << "\n"; return 0; } ```
### Prompt Please create a solution in cpp 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; int dx[2] = {1, -1}; void go(char s[], int n, int stowaway, int controller, int dir) { int T = 0; for (int i = 1; s[i]; ++i) { if (s[i] == '1') { controller += dx[dir]; if (controller == n || controller == 1) dir ^= 1; if (controller == 1) { stowaway = n; } else if (controller == n) { stowaway = 1; } else { if (dir == 0) stowaway = 1; else stowaway = n; } } else { if (controller > stowaway && dir == 1 || controller < stowaway && dir == 0) { stowaway += dx[dir]; if (stowaway < 1 || stowaway > n) stowaway -= dx[dir]; } controller += dx[dir]; if (controller == n || controller == 1) dir ^= 1; } if (controller == stowaway) { T = i; break; } } if (T) { printf("Controller %d\n", T); } else { puts("Stowaway"); } } int main() { char buf[210]; int n, m, k; while (cin >> n >> m >> k) { scanf("%s%s", buf, buf); int dir = buf[0] == 'h'; scanf("%s", buf + 1); go(buf, n, m, k, dir); } return 0; } ```
### Prompt Please provide a CPP coded solution to the problem described below: Egor wants to achieve a rating of 1600 points on the well-known chess portal ChessForces and he needs your help! Before you start solving the problem, Egor wants to remind you how the chess pieces move. Chess rook moves along straight lines up and down, left and right, as many squares as it wants. And when it wants, it can stop. The queen walks in all directions vertically and diagonally at any distance. You can see the examples below. <image> To reach the goal, Egor should research the next topic: There is an N × N board. Each cell of the board has a number from 1 to N ^ 2 in it and numbers in all cells are distinct. In the beginning, some chess figure stands in the cell with the number 1. Note that this cell is already considered as visited. After that every move is determined by the following rules: 1. Among all not visited yet cells to which the figure can get in one move, it goes to the cell that has minimal number. 2. If all accessible cells were already visited and some cells are not yet visited, then the figure is teleported to the not visited cell that has minimal number. If this step happens, the piece pays a fee of 1 vun. 3. If all cells are already visited, the process is stopped. Egor should find an N × N board on which the rook pays strictly less vuns than the queen during the round with this numbering. Help him to find such N × N numbered board, or tell that it doesn't exist. Input The only line contains one integer N — the size of the board, 1≤ N ≤ 500. Output The output should contain N lines. In i-th line output N numbers — numbers on the i-th row of the board. All numbers from 1 to N × N must be used exactly once. On your board rook must pay strictly less vuns than the queen. If there are no solutions, print -1. If there are several solutions, you can output any of them. Examples Input 1 Output -1 Input 4 Output 4 3 6 12 7 5 9 15 14 1 11 10 13 8 16 2 Note In case we have 1 × 1 board, both rook and queen do not have a chance to pay fees. In second sample rook goes through cells 1 → 3 → 4 → 6 → 9 → 5 → 7 → 13 → 2 → 8 → 16 → 11 → 10 → 12 → 15 → (1 vun) → 14. Queen goes through 1 → 3 → 4 → 2 → 5 → 6 → 9 → 7 → 13 → 8 → 11 → 10 → 12 → 15 → (1 vun) → 14 → (1 vun) → 16. As a result rook pays 1 vun and queen pays 2 vuns. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; if (n < 3) { cout << "-1\n"; return 0; } for (int i = 0; i < n - 3; i++) { for (int j = 1; j <= n; j++) { if ((n % 2 && !(i % 2)) || (!(n % 2) && i % 2)) cout << j + i * n << " "; else cout << (i + 1) * n - j + 1 << " "; } cout << "\n"; } for (int i = 0; i < 3; i++) { for (int j = 0; j < n - 3; j++) { cout << n * n - 9 - i * (n - 3) - j << " "; } if (i == 0) cout << 1 + n * n - 9 << " " << 7 + n * n - 9 << " " << 9 + n * n - 9 << "\n"; if (i == 1) cout << 3 + n * n - 9 << " " << 2 + n * n - 9 << " " << 5 + n * n - 9 << "\n"; if (i == 2) cout << 4 + n * n - 9 << " " << 8 + n * n - 9 << " " << 6 + n * n - 9 << "\n"; } return 0; } ```
### Prompt Please formulate a CPP solution to the following problem: You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p). The problem consists of two 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 B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold. * In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold. Output Output n number forming the required permutation. Examples Input 2 2 Output 2 1 Input 3 2 Output 1 3 2 Note In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const double eps = 1e-6; vector<pair<int, string> > v; int x[10], n, m; bool d[10]; void makep() { int res; string s; res = 0; s = "0"; for (int i = 1; i <= n; i++) { s += "0"; s[i] = (char)(x[i] + 48); } for (int i = 1; i <= n; i++) { for (int j = i; j <= n; j++) { int t = 1000; for (int k = i; k <= j; k++) t = min(t, x[k]); res += t; } } v.push_back(pair<int, string>(res, s)); } void make(int pos) { for (int l = 1; l <= n; l++) if (!d[l]) { x[pos] = l; d[l] = 1; if (pos == n) makep(); else make(pos + 1); d[l] = 0; } } bool smaller(string X, string y) { for (int i = 1; i < X.length(); i++) if (X[i] < y[i]) return true; else if (X[i] > y[i]) return false; return false; } bool comp(pair<int, string> X, pair<int, string> y) { if (X.first > y.first) return true; if ((X.first == y.first) && smaller(X.second, y.second)) { return true; } return false; } int main() { cin >> n >> m; make(1); sort(v.begin(), v.end(), comp); string s = v[m - 1].second; for (int i = 1; i <= n; i++) { cout << s[i] << ' '; } } ```
### Prompt Develop a solution in cpp to the problem described below: Write a program which prints multiplication tables in the following format: 1x1=1 1x2=2 . . 9x8=72 9x9=81 Input No input. Output 1x1=1 1x2=2 . . 9x8=72 9x9=81 Example Input Output ### Response ```cpp #include<bits/stdc++.h> using namespace std; int main(){ for(int a=0;a<9;a++){ for(int b=0;b<9;b++)cout<<a+1<<'x'<<b+1<<'='<<(a+1)*(b+1)<<endl; } } ```
### Prompt Your task is to create a Cpp solution to the following problem: PolandBall has such a convex polygon with n veritces that no three of its diagonals intersect at the same point. PolandBall decided to improve it and draw some red segments. He chose a number k such that gcd(n, k) = 1. Vertices of the polygon are numbered from 1 to n in a clockwise way. PolandBall repeats the following process n times, starting from the vertex 1: Assume you've ended last operation in vertex x (consider x = 1 if it is the first operation). Draw a new segment from vertex x to k-th next vertex in clockwise direction. This is a vertex x + k or x + k - n depending on which of these is a valid index of polygon's vertex. Your task is to calculate number of polygon's sections after each drawing. A section is a clear area inside the polygon bounded with drawn diagonals or the polygon's sides. Input There are only two numbers in the input: n and k (5 ≤ n ≤ 106, 2 ≤ k ≤ n - 2, gcd(n, k) = 1). Output You should print n values separated by spaces. The i-th value should represent number of polygon's sections after drawing first i lines. Examples Input 5 2 Output 2 3 5 8 11 Input 10 3 Output 2 3 4 6 9 12 16 21 26 31 Note The greatest common divisor (gcd) of two integers a and b is the largest positive integer that divides both a and b without a remainder. For the first sample testcase, you should output "2 3 5 8 11". Pictures below correspond to situations after drawing lines. <image> <image> <image> <image> <image> <image> ### 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); } string toBin(long long a) { string res = ""; while (a) { res += char((a & 1) + '0'); a >>= 1; } reverse(res.begin(), res.end()); return res; } const int mod = 1e9 + 7; long long expo(long long base, long long pow) { long long ans = 1; while (pow != 0) { if (pow & 1 == 1) { ans = ans * base; ans = ans % mod; } base *= base; base %= mod; pow /= 2; } return ans; } long long inv(long long x) { return expo(x, mod - 2); } bool isPal(string ss) { int len = ss.length(); for (int i = 0; i < len / 2; i++) { int comp = len - i - 1; if (ss[i] != ss[comp]) return false; } return true; } double pi = 3.141592653589793238462643; double error = 0.0000001; const int M = 1001111; vector<int> BIT(M); long long res = 1; int isP[222]; int N, K, X = 0; void sieve() { isP[1] = 1; for (int i = 2; i < 100; i++) { if (isP[i]) continue; for (long long j = i * 1LL * i; j < 100; j += i) { isP[j] = 1; } } } long long dofor(int a, int b) { long long ult = 0; for (int r = b + 1; r > 0; r -= r & -r) ult += BIT[r]; for (int l = a; l > 0; l -= l & -l) ult -= BIT[l]; if (a > b) { for (int r = N; r > 0; r -= r & -r) ult += BIT[r]; } return ult; } void read() { cin >> N >> K; K = min(K, N - K); } void print(long long ans) { printf("%lld ", ans); } void up(int we) { we = we + 1; for (; we < M; we += we & -we) BIT[we]++; } void solve() { for (int i = 0; i < N; i++) { int st = (X + 1) % N; int en = (X + K - 1) % N; res += dofor(st, en) + 1; print(res); up(X); up((X + K) % N); X = (X + K) % N; } } int main() { sieve(); read(); solve(); } ```
### Prompt Please create a solution in CPP to the following problem: Snuke got positive integers s_1,...,s_N from his mother, as a birthday present. There may be duplicate elements. He will circle some of these N integers. Since he dislikes cubic numbers, he wants to ensure that if both s_i and s_j (i ≠ j) are circled, the product s_is_j is not cubic. For example, when s_1=1,s_2=1,s_3=2,s_4=4, it is not possible to circle both s_1 and s_2 at the same time. It is not possible to circle both s_3 and s_4 at the same time, either. Find the maximum number of integers that Snuke can circle. Constraints * 1 ≦ N ≦ 10^5 * 1 ≦ s_i ≦ 10^{10} * All input values are integers. Input The input is given from Standard Input in the following format: N s_1 : s_N Output Print the maximum number of integers that Snuke can circle. Examples Input 8 1 2 3 4 5 6 7 8 Output 6 Input 6 2 4 8 16 32 64 Output 3 Input 10 1 10 100 1000000007 10000000000 1000000009 999999999 999 999 999 Output 9 ### Response ```cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> #include<map> #include<cmath> using namespace std; typedef long long LL; const int N=100005; int n; LL a[N],b[N]; map<LL,int> ma; LL sqr(LL x) { return x*x; } int main() { scanf("%d",&n); for (int i=1;i<=n;i++) { LL x;scanf("%lld",&x); for (LL j=2;j*j*j<=x;j++) while (x%(j*j*j)==0) x/=j*j*j; ma[x]++;a[i]=x; LL y=1; for (LL j=2;j*j*j<=x;j++) if (x%j==0) { y*=(x%(j*j)==0)?j:j*j; while (x%j==0) x/=j; } if (sqr((LL)sqrt(x))==x) y*=(LL)sqrt(x); else y*=x*x; b[i]=y; } int ans=0; if (ma[1]) ans++,ma[1]=0; for (int i=1;i<=n;i++) ans+=max(ma[a[i]],ma[b[i]]),ma[a[i]]=ma[b[i]]=0; printf("%d",ans); return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: While walking down the street Vanya saw a label "Hide&Seek". Because he is a programmer, he used & as a bitwise AND for these two words represented as a integers in base 64 and got new word. Now Vanya thinks of some string s and wants to know the number of pairs of words of length |s| (length of s), such that their bitwise AND is equal to s. As this number can be large, output it modulo 109 + 7. To represent the string as a number in numeral system with base 64 Vanya uses the following rules: * digits from '0' to '9' correspond to integers from 0 to 9; * letters from 'A' to 'Z' correspond to integers from 10 to 35; * letters from 'a' to 'z' correspond to integers from 36 to 61; * letter '-' correspond to integer 62; * letter '_' correspond to integer 63. Input The only line of the input contains a single word s (1 ≤ |s| ≤ 100 000), consisting of digits, lowercase and uppercase English letters, characters '-' and '_'. Output Print a single integer — the number of possible pairs of words, such that their bitwise AND is equal to string s modulo 109 + 7. Examples Input z Output 3 Input V_V Output 9 Input Codeforces Output 130653412 Note For a detailed definition of bitwise AND we recommend to take a look in the corresponding article in Wikipedia. In the first sample, there are 3 possible solutions: 1. z&_ = 61&63 = 61 = z 2. _&z = 63&61 = 61 = z 3. z&z = 61&61 = 61 = z ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long a[1050] = {0}; long long mod = 1e9 + 7; string s; long long ans; int foo(char c) { int tmp; if ((c >= '0') && (c <= '9')) tmp = c - '0'; if ((c >= 'a') && (c <= 'z')) tmp = c - 'a' + 36; if ((c >= 'A') && (c <= 'Z')) tmp = c - 'A' + 10; if (c == '-') tmp = 62; if (c == '_') tmp = 63; return tmp; } int main() { cin >> s; for (int i = 0; i <= 63; i++) { for (int j = 0; j <= 63; j++) { a[i & j]++; } } ans = 1; for (int i = 0; i < s.size(); i++) { int gg; gg = foo(s[i]); ans *= a[gg]; ans %= mod; } cout << ans << endl; return 0; } ```
### Prompt Generate a Cpp solution to the following problem: For a connected undirected weighted graph G, MST (minimum spanning tree) is a subgraph of G that contains all of G's vertices, is a tree, and sum of its edges is minimum possible. You are given a graph G. If you run a MST algorithm on graph it would give you only one MST and it causes other edges to become jealous. You are given some queries, each query contains a set of edges of graph G, and you should determine whether there is a MST containing all these edges or not. Input The first line contains two integers n, m (2 ≤ n, m ≤ 5·105, n - 1 ≤ m) — the number of vertices and edges in the graph and the number of queries. The i-th of the next m lines contains three integers ui, vi, wi (ui ≠ vi, 1 ≤ wi ≤ 5·105) — the endpoints and weight of the i-th edge. There can be more than one edges between two vertices. It's guaranteed that the given graph is connected. The next line contains a single integer q (1 ≤ q ≤ 5·105) — the number of queries. q lines follow, the i-th of them contains the i-th query. It starts with an integer ki (1 ≤ ki ≤ n - 1) — the size of edges subset and continues with ki distinct space-separated integers from 1 to m — the indices of the edges. It is guaranteed that the sum of ki for 1 ≤ i ≤ q does not exceed 5·105. Output For each query you should print "YES" (without quotes) if there's a MST containing these edges and "NO" (of course without quotes again) otherwise. Example Input 5 7 1 2 2 1 3 2 2 3 1 2 4 1 3 4 1 3 5 2 4 5 2 4 2 3 4 3 3 4 5 2 1 7 2 1 2 Output YES NO YES NO Note This is the graph of sample: <image> Weight of minimum spanning tree on this graph is 6. MST with edges (1, 3, 4, 6), contains all of edges from the first query, so answer on the first query is "YES". Edges from the second query form a cycle of length 3, so there is no spanning tree including these three edges. Thus, answer is "NO". ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename T> void rd(T &x) { int f = 0, c; while (!isdigit(c = getchar())) f ^= !(c ^ 45); x = (c & 15); while (isdigit(c = getchar())) x = x * 10 + (c & 15); if (f) x = -x; } template <typename T> void pt(T x, int c = -1) { if (x < 0) putchar('-'), x = -x; if (x > 9) pt(x / 10); putchar(x % 10 + 48); if (c != -1) putchar(c); } template <typename T> void umax(T &x, const T &y) { if (x < y) x = y; } template <typename T> void umin(T &x, const T &y) { if (x > y) x = y; } using ll = long long; using ld = long double; using pii = pair<int, int>; using pll = pair<long, long>; const int inf = 0x3f3f3f3f; const int maxn = 5e5 + 5; const int mod = 1e9 + 7; struct UnionSet { int fa[maxn], siz[maxn], N, record; pii sta[maxn]; void setRecord() { record = N; } void init(int n) { N = 0; for (int i = 1; i <= n; i++) fa[i] = i, siz[i] = 1; } int Find(int x) { while (x != fa[x]) x = fa[x]; return x; } bool merge(int x, int y) { x = Find(x); y = Find(y); if (x == y) return false; if (siz[x] > siz[y]) swap(x, y); fa[x] = y; siz[y] += siz[x]; sta[++N] = {x, y}; return true; } void step() { int x, y; tie(x, y) = sta[N--]; siz[y] -= siz[x]; fa[x] = x; } void rallback() { while (N > record) step(); } } s; using tpl = tuple<int, int, int>; using vi = vector<int>; int n, m, q; tpl e[maxn], f[maxn]; vector<pair<int, vi> > g[maxn]; bool ok[maxn]; int main() { rd(n); rd(m); for (int i = 1; i <= m; i++) { rd(get<1>(e[i])); rd(get<2>(e[i])); rd(get<0>(e[i])); f[i] = e[i]; } sort(f + 1, f + m + 1); rd(q); for (int i = 1; i <= q; i++) { int k; rd(k); vi v(k, 0); for (auto &x : v) rd(x); sort((v).begin(), (v).end(), [](int a, int b) { int wa = get<0>(e[a]), wb = get<0>(e[b]); if (wa == wb) return a < b; return wa < wb; }); int j = 0; while (j < (int)v.size()) { int pos = j, w = get<0>(e[v[j]]); vi tmp; while (pos < (int)v.size() && get<0>(e[v[pos]]) == w) { tmp.push_back(v[pos++]); } g[w].push_back({i, tmp}); j = pos; } } s.init(n); s.setRecord(); fill(ok + 1, ok + q + 1, true); int pos = 1; for (int i = 1; i <= 500000; i++) { for (auto &p : g[i]) { if (!ok[p.first]) continue; for (auto h : p.second) { ok[p.first] &= s.merge(get<1>(e[h]), get<2>(e[h])); } s.rallback(); } while (pos <= m && get<0>(f[pos]) == i) { s.merge(get<1>(f[pos]), get<2>(f[pos])); pos++; } s.setRecord(); } for (int i = 1; i <= q; i++) { puts(ok[i] ? "YES" : "NO"); } return 0; } ```
### Prompt Construct a cpp code solution to the problem outlined: Arkady likes to walk around his kitchen. His labyrinthine kitchen consists of several important places connected with passages. Unfortunately it happens that these passages are flooded with milk so that it's impossible to pass through them. Namely, it's possible to pass through each passage in any direction only during some time interval. The lengths of all passages are equal and Arkady makes through them in one second. For security reasons, Arkady can never stop, also, he can't change direction while going through a passage. In other words, if he starts walking in some passage, he should reach its end and immediately leave the end. Today Arkady needs to quickly reach important place n from place 1. He plans to exit the place 1 at time moment 0 and reach the place n as early as he can. Please find the minimum time he should spend on his way. Input The first line contains two integers n and m (1 ≤ n ≤ 5·105, 0 ≤ m ≤ 5·105) — the number of important places and the number of passages, respectively. After that, m lines follow, each of them describe one passage. Each line contains four integers a, b, l and r (1 ≤ a, b ≤ n, a ≠ b, 0 ≤ l < r ≤ 109) — the places the passage connects and the time segment during which it's possible to use this passage. Output Print one integer — minimum time Arkady should spend to reach the destination. If he can't reach the place n, print -1. Examples Input 5 6 1 2 0 1 2 5 2 3 2 5 0 1 1 3 0 1 3 4 1 2 4 5 2 3 Output 3 Input 2 1 1 2 1 100 Output -1 Note In the first example Arkady should go through important places 1 → 3 → 4 → 5. In the second example Arkady can't start his walk because at time moment 0 it's impossible to use the only passage. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 5e5 + 5; int n, m, ans; int head[MAXN][2]; struct Tnode { int v, l, r; Tnode() {} Tnode(int vv, int ll, int rr) { v = vv; l = ll; r = rr; } friend bool operator<(Tnode A, Tnode B) { return A.l < B.l; } }; vector<Tnode> way[MAXN][2]; struct Tp { int x, y; Tp() {} Tp(int xx, int yy) { x = xx; y = yy; } friend bool operator<(Tp A, Tp B) { return A.y > B.y; } }; priority_queue<Tp> q; void init() { scanf("%d%d", &n, &m); for (int i = 1; i <= m; ++i) { int u, v, l, r; scanf("%d%d%d%d", &u, &v, &l, &r); for (int j = 0; j < 2; ++j) { way[u][j].push_back(Tnode(v, l, r)); way[v][j].push_back(Tnode(u, l, r)); } } for (int i = 1; i <= n; ++i) for (int j = 0; j < 2; ++j) sort(way[i][j].begin(), way[i][j].end()); } int dij() { int now, tim, xx, yy; q.push(Tp(1, 0)); while (!q.empty()) { xx = q.top().x; yy = now = q.top().y; tim = yy & 1; q.pop(); if (xx == n) return yy; for (int j = head[xx][tim]; j < way[xx][tim].size(); ++j) { Tnode w = way[xx][tim][j]; if (w.l > now) break; head[xx][tim] = j + 1; if (w.r < yy) continue; now = max(now, w.r); if (now - tim & 1) --now; int tmp = max(w.l, yy); if (tmp % 2 != tim) ++tmp; if (tmp + 1 <= w.r && tmp >= w.l) q.push(Tp(w.v, tmp + 1)); } } return -1; } int main() { init(); printf("%d\n", dij()); return 0; } ```
### Prompt In Cpp, your task is to solve the following problem: A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length 0 are not allowed). Let's consider empty cells are denoted by '.', then the following figures are stars: <image> The leftmost figure is a star of size 1, the middle figure is a star of size 2 and the rightmost figure is a star of size 3. You are given a rectangular grid of size n × m consisting only of asterisks '*' and periods (dots) '.'. Rows are numbered from 1 to n, columns are numbered from 1 to m. Your task is to draw this grid using any number of stars or find out that it is impossible. Stars can intersect, overlap or even coincide with each other. The number of stars in the output can't exceed n ⋅ m. Each star should be completely inside the grid. You can use stars of same and arbitrary sizes. In this problem, you do not need to minimize the number of stars. Just find any way to draw the given grid with at most n ⋅ m stars. Input The first line of the input contains two integers n and m (3 ≤ n, m ≤ 1000) — the sizes of the given grid. The next n lines contains m characters each, the i-th line describes the i-th row of the grid. It is guaranteed that grid consists of characters '*' and '.' only. Output If it is impossible to draw the given grid using stars only, print "-1". Otherwise in the first line print one integer k (0 ≤ k ≤ n ⋅ m) — the number of stars needed to draw the given grid. The next k lines should contain three integers each — x_j, y_j and s_j, where x_j is the row index of the central star character, y_j is the column index of the central star character and s_j is the size of the star. Each star should be completely inside the grid. Examples Input 6 8 ....*... ...**... ..*****. ...**... ....*... ........ Output 3 3 4 1 3 5 2 3 5 1 Input 5 5 .*... ****. .**** ..**. ..... Output 3 2 2 1 3 3 1 3 4 1 Input 5 5 .*... ***.. .*... .*... ..... Output -1 Input 3 3 *.* .*. *.* Output -1 Note In the first example the output 2 3 4 1 3 5 2 is also correct. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int leftRight[1005][1005], topDown[1005][1005]; int rightLeft[1005][1005], bottomUp[1005][1005]; int leftRightSum[1005][1005], topDownSum[1005][1005]; string grid[1005]; int main() { cin.tie(0); ios_base::sync_with_stdio(0); int n, m; cin >> n >> m; for (int i = 0; i < n; i++) cin >> grid[i]; for (int i = 0; i < n; i++) { int left = -1; for (int j = 0; j < m; j++) { if (grid[i][j] == '*') leftRight[i][j] = left; else left = j; } } for (int i = 0; i < n; i++) { int right = m; for (int j = m - 1; j >= 0; j--) { if (grid[i][j] == '*') rightLeft[i][j] = right; else right = j; } } for (int i = 0; i < m; i++) { int top = -1; for (int j = 0; j < n; j++) { if (grid[j][i] == '*') topDown[j][i] = top; else top = j; } } for (int i = 0; i < m; i++) { int bottom = n; for (int j = n - 1; j >= 0; j--) { if (grid[j][i] == '*') bottomUp[j][i] = bottom; else bottom = j; } } vector<int> is, js, sij; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == '*') { int a = i - topDown[i][j] - 1; int b = bottomUp[i][j] - i - 1; int c = j - leftRight[i][j] - 1; int d = rightLeft[i][j] - j - 1; int sizeij = min(a, min(b, min(c, d))); if (sizeij > 0) { leftRightSum[i][j - sizeij] += 1; leftRightSum[i][j + sizeij + 1] -= 1; topDownSum[i - sizeij][j] += 1; topDownSum[i + sizeij + 1][j] -= 1; is.push_back(i + 1); js.push_back(j + 1); sij.push_back(sizeij); } } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (j > 0) leftRightSum[i][j] = leftRightSum[i][j] + leftRightSum[i][j - 1]; } } for (int j = 0; j < m; j++) { for (int i = 0; i < n; i++) { if (i > 0) topDownSum[i][j] = topDownSum[i][j] + topDownSum[i - 1][j]; } } bool isPossible = true; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == '*') { if (topDownSum[i][j] < 1 && leftRightSum[i][j] < 1) isPossible = false; } else { if (topDownSum[i][j] != 0 || leftRightSum[i][j] != 0) isPossible = false; } } } if (isPossible) { cout << is.size() << "\n"; for (int i = 0; i < is.size(); i++) { cout << is[i] << " " << js[i] << " " << sij[i] << "\n"; } } else { cout << "-1\n"; } return 0; } ```
### Prompt Develop a solution in cpp to the problem described below: Lena is a programmer. She got a task to solve at work. There is an empty set of pairs of integers and n queries to process. Each query is one of three types: 1. Add a pair (a, b) to the set. 2. Remove a pair added in the query number i. All queries are numbered with integers from 1 to n. 3. For a given integer q find the maximal value x·q + y over all pairs (x, y) from the set. Help Lena to process the queries. Input The first line of input contains integer n (1 ≤ n ≤ 3·105) — the number of queries. Each of the next n lines starts with integer t (1 ≤ t ≤ 3) — the type of the query. A pair of integers a and b ( - 109 ≤ a, b ≤ 109) follows in the query of the first type. An integer i (1 ≤ i ≤ n) follows in the query of the second type. It is guaranteed that i is less than the number of the query, the query number i has the first type and the pair from the i-th query is not already removed. An integer q ( - 109 ≤ q ≤ 109) follows in the query of the third type. Output For the queries of the third type print on a separate line the desired maximal value of x·q + y. If there are no pairs in the set print "EMPTY SET". Example Input 7 3 1 1 2 3 3 1 1 -1 100 3 1 2 4 3 1 Output EMPTY SET 5 99 5 ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename T> T in() { char ch; T n = 0; bool ng = false; while (1) { ch = getchar(); if (ch == '-') { ng = true; ch = getchar(); break; } if (ch >= '0' && ch <= '9') break; } while (1) { n = n * 10 + (ch - '0'); ch = getchar(); if (ch < '0' || ch > '9') break; } return (ng ? -n : n); } template <typename T> inline T POW(T B, T P) { if (P == 0) return 1; if (P & 1) return B * POW(B, P - 1); else return (POW(B, P / 2) * POW(B, P / 2)); } template <typename T> inline T Gcd(T a, T b) { if (a < 0) return Gcd(-a, b); if (b < 0) return Gcd(a, -b); return (b == 0) ? a : Gcd(b, a % b); } template <typename T> inline T Lcm(T a, T b) { if (a < 0) return Lcm(-a, b); if (b < 0) return Lcm(a, -b); return a * (b / Gcd(a, b)); } long long Bigmod(long long base, long long power, long long MOD) { long long ret = 1; while (power) { if (power & 1) ret = (ret * base) % MOD; base = (base * base) % MOD; power >>= 1; } return ret; } bool isVowel(char ch) { ch = toupper(ch); if (ch == 'A' || ch == 'U' || ch == 'I' || ch == 'O' || ch == 'E') return true; return false; } template <typename T> long long int isLeft(T a, T b, T c) { return (a.x - b.x) * (b.y - c.y) - (b.x - c.x) * (a.y - b.y); } long long ModInverse(long long number, long long MOD) { return Bigmod(number, MOD - 2, MOD); } bool isConst(char ch) { if (isalpha(ch) && !isVowel(ch)) return true; return false; } int toInt(string s) { int sm; stringstream second(s); second >> sm; return sm; } struct line { long long a, b; double xleft; bool type; line(long long _a, long long _b) { a = _a; b = _b; type = 0; } bool operator<(const line &other) const { if (other.type) { return xleft < other.xleft; } return a > other.a; } }; double meet(line x, line y) { return 1.0 * (y.b - x.b) / (x.a - y.a); } struct cht { set<line> hull; cht() { hull.clear(); } bool hasleft(set<line>::iterator node) { return node != hull.begin(); } bool hasright(set<line>::iterator node) { return node != prev(hull.end()); } void updateborder(set<line>::iterator node) { if (hasright(node)) { line temp = *next(node); hull.erase(temp); temp.xleft = meet(*node, temp); hull.insert(temp); } if (hasleft(node)) { line temp = *node; temp.xleft = meet(*prev(node), temp); hull.erase(node); hull.insert(temp); } else { line temp = *node; hull.erase(node); temp.xleft = -2000000000000000000LL; hull.insert(temp); } } bool useless(line left, line middle, line right) { double x = meet(left, right); double y = x * middle.a + middle.b; double ly = left.a * x + left.b; return y > ly; } bool useless(set<line>::iterator node) { if (hasleft(node) && hasright(node)) { return useless(*prev(node), *node, *next(node)); } return 0; } void addline(long long m, long long c) { line temp = line(m, c); auto it = hull.lower_bound(temp); if (it != hull.end() && it->a == m) { if (it->b > c) { hull.erase(it); } else { return; } } hull.insert(temp); it = hull.find(temp); if (useless(it)) { hull.erase(it); return; } while (hasleft(it) && useless(prev(it))) { hull.erase(prev(it)); } while (hasright(it) && useless(next(it))) { hull.erase(next(it)); } updateborder(it); } long long getbest(long long x) { if (hull.empty()) { return 2000000000000000000LL; } line query(0, 0); query.xleft = x; query.type = 1; auto it = hull.lower_bound(query); it = prev(it); return it->a * x + it->b; } }; cht Tree[300007 * 4]; long long int m, c; void Upd(int id, int l, int r, int st, int ed) { if (st <= l && ed >= r) { Tree[id].addline(m, c); return; } int mid = (l + r) / 2; int lft = 2 * id; int rgt = lft + 1; if (ed <= mid) Upd(lft, l, mid, st, ed); else if (st > mid) Upd(rgt, mid + 1, r, st, ed); else { Upd(lft, l, mid, st, ed); Upd(rgt, mid + 1, r, st, ed); } } long long int ans; long long int P; void Qry(int id, int l, int r, int p) { ans = max(ans, Tree[id].getbest(P) * -1); if (l == r) { return; } int mid = (l + r) / 2; int lft = 2 * id; int rgt = lft + 1; if (p <= mid) Qry(lft, l, mid, p); else Qry(rgt, mid + 1, r, p); } int ar[300007]; int X[300007]; int Y[300007]; int Tp[300007]; int br[300007]; int main() { int n; n = in<int>(); for (int i = 1; i < n + 1; i++) { Tp[i] = in<int>(), ar[i] = in<int>(); if (Tp[i] == 1) { br[i] = in<int>(); Y[i] = n; } else if (Tp[i] == 2) { Y[ar[i]] = i; } } for (int i = 1; i < n + 1; i++) { if (Tp[i] == 1) { m = -ar[i], c = -br[i]; Upd(1, 1, n, i, Y[i]); } else if (Tp[i] == 3) { P = ar[i]; ans = -2000000000000000000LL; Qry(1, 1, n, i); if (ans == -2000000000000000000LL) printf("EMPTY SET\n"); else printf("%lld\n", ans); } } return 0; } ```
### Prompt Please create a solution in Cpp to the following problem: In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures. City i is established in year Y_i and belongs to Prefecture P_i. You can assume that there are no multiple cities that are established in the same year. It is decided to allocate a 12-digit ID number to each city. If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x. Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits. Find the ID numbers for all the cities. Note that there can be a prefecture with no cities. Constraints * 1 \leq N \leq 10^5 * 1 \leq M \leq 10^5 * 1 \leq P_i \leq N * 1 \leq Y_i \leq 10^9 * Y_i are all different. * All values in input are integers. Input Input is given from Standard Input in the following format: N M P_1 Y_1 : P_M Y_M Output Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...). Examples Input 2 3 1 32 2 63 1 12 Output 000001000002 000002000001 000001000001 Input 2 3 2 55 2 77 2 99 Output 000002000001 000002000002 000002000003 ### Response ```cpp #include<bits/stdc++.h> using namespace std; int n,m; int p[100005]; int y[100005]; vector<int>v[100005]; int main(){ scanf("%d%d",&n,&m); for(int i=1;i<=m;i++){ scanf("%d%d",&p[i],&y[i]); v[p[i]].push_back(y[i]); } for(int i=1;i<=n;i++) sort(v[i].begin(),v[i].end()); for(int i=1;i<=m;i++){ printf("%06d",p[i]); int k=lower_bound(v[p[i]].begin(),v[p[i]].end(),y[i])-v[p[i]].begin()+1; printf("%06d\n",k); } return 0; } ```
### Prompt Please create a solution in CPP to the following problem: Takahashi, who is A years old, is riding a Ferris wheel. It costs B yen (B is an even number) to ride the Ferris wheel if you are 13 years old or older, but children between 6 and 12 years old (inclusive) can ride it for half the cost, and children who are 5 years old or younger are free of charge. (Yen is the currency of Japan.) Find the cost of the Ferris wheel for Takahashi. Constraints * 0 ≤ A ≤ 100 * 2 ≤ B ≤ 1000 * B is an even number. Input Input is given from Standard Input in the following format: A B Output Print the cost of the Ferris wheel for Takahashi. Examples Input 30 100 Output 100 Input 12 100 Output 50 Input 0 100 Output 0 ### Response ```cpp #include <stdio.h> int main(){ int a, b; scanf("%d %d", &a, &b); if(a>=13) printf("%d", b); else if(a>=6) printf("%d", b/2); else printf("0"); } ```
### Prompt In cpp, your task is to solve the following problem: You are given three words s_1, s_2 and s_3, each composed of lowercase English letters, with spaces in between. Print the acronym formed from the uppercased initial letters of the words. Constraints * s_1, s_2 and s_3 are composed of lowercase English letters. * 1 ≤ |s_i| ≤ 10 (1≤i≤3) Input Input is given from Standard Input in the following format: s_1 s_2 s_3 Output Print the answer. Examples Input atcoder beginner contest Output ABC Input resident register number Output RRN Input k nearest neighbor Output KNN Input async layered coding Output ALC ### Response ```cpp #include<bits/stdc++.h> using namespace std; string s,ans; int main(){ for(int i=0;i<3;i++){ cin>>s; ans+=(s[0]-32); } cout<<ans; } ```
### Prompt Develop a solution in cpp to the problem described below: Ms. Iyo Kiffa-Australis has a balance and only two kinds of weights to measure a dose of medicine. For example, to measure 200mg of aspirin using 300mg weights and 700mg weights, she can put one 700mg weight on the side of the medicine and three 300mg weights on the opposite side (Figure 1). Although she could put four 300mg weights on the medicine side and two 700mg weights on the other (Figure 2), she would not choose this solution because it is less convenient to use more weights. You are asked to help her by calculating how many weights are required. <image> Figure 1: To measure 200mg of aspirin using three 300mg weights and one 700mg weight <image> Figure 2: To measure 200mg of aspirin using four 300mg weights and two 700mg weights Input The input is a sequence of datasets. A dataset is a line containing three positive integers a, b, and d separated by a space. The following relations hold: a ≠ b, a ≤ 10000, b ≤ 10000, and d ≤ 50000. You may assume that it is possible to measure d mg using a combination of a mg and b mg weights. In other words, you need not consider “no solution” cases. The end of the input is indicated by a line containing three zeros separated by a space. It is not a dataset. Output The output should be composed of lines, each corresponding to an input dataset (a, b, d). An output line should contain two nonnegative integers x and y separated by a space. They should satisfy the following three conditions. * You can measure d mg using x many a mg weights and y many b mg weights. * The total number of weights (x + y) is the smallest among those pairs of nonnegative integers satisfying the previous condition. * The total mass of weights (ax + by) is the smallest among those pairs of nonnegative integers satisfying the previous two conditions. No extra characters (e.g. extra spaces) should appear in the output. Example Input 700 300 200 500 200 300 500 200 500 275 110 330 275 110 385 648 375 4002 3 1 10000 0 0 0 Output 1 3 1 1 1 0 0 3 1 1 49 74 3333 1 ### Response ```cpp #include <bits/stdc++.h> #define For(i, a, b) for(int (i)=(int)(a); (i)<(int)(b); ++(i)) #define rFor(i, a, b) for(int (i)=(int)(a)-1; (i)>=(int)(b); --(i)) #define rep(i, n) For((i), 0, (n)) #define rrep(i, n) rFor((i), (n), 0) #define fi first #define se second using namespace std; typedef long long lint; typedef unsigned long long ulint; typedef pair<int, int> pii; template<class T> bool chmax(T &a, const T &b){if(a<b){a=b; return true;} return false;} template<class T> bool chmin(T &a, const T &b){if(a>b){a=b; return true;} return false;} template<class T> T div_floor(T a, T b){ if(b < 0) a *= -1, b *= -1; return a>=0 ? a/b : (a+1)/b-1; } template<class T> T div_ceil(T a, T b){ if(b < 0) a *= -1, b *= -1; return a>0 ? (a-1)/b+1 : a/b; } constexpr lint mod = 1e9+7; constexpr lint INF = mod * mod; constexpr int MAX = 200010; pair<pair<lint, lint>, lint> ext_gcd(lint a, lint b){ if(b == 0) return {{1, 0}, a}; else if(a < b){ auto p = ext_gcd(b, a); return {{p.fi.se, p.fi.fi}, p.se}; } else{ auto p = ext_gcd(b, a%b); lint s = p.fi.fi, t = p.fi.se; return {{t, s - a/b * t}, p.se}; } } int main(){ using pll = pair<lint, lint>; lint a, b, d; while(scanf("%lld%lld%lld", &a, &b, &d) && a){ lint s, t, g; auto p = ext_gcd(a, b); tie(s, t) = p.fi; g = p.se; s *= d / g; t *= d / g; pair<pll, pll> ans = {{INF, INF}, {INF, INF}}; lint A = a / g, B = b / g; lint L = min(-1.0*s/B, 1.0*t/A), R = max(-1.0*s/B, 1.0*t/A); For(k, L-5, R+5){ lint x = abs(B*k + s), y = abs(-A*k + t); chmin(ans, {{x+y, a*x+b*y}, {x, y}}); } printf("%lld %lld\n", ans.se.fi, ans.se.se); } } ```
### Prompt Please provide a Cpp coded solution to the problem described below: Array of integers is unimodal, if: * it is strictly increasing in the beginning; * after that it is constant; * after that it is strictly decreasing. The first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent. For example, the following three arrays are unimodal: [5, 7, 11, 11, 2, 1], [4, 4, 2], [7], but the following three are not unimodal: [5, 5, 6, 6, 1], [1, 2, 1, 2], [4, 5, 5, 6]. Write a program that checks if an array is unimodal. Input The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1 000) — the elements of the array. Output Print "YES" if the given array is unimodal. Otherwise, print "NO". You can output each letter in any case (upper or lower). Examples Input 6 1 5 5 5 4 2 Output YES Input 5 10 20 30 20 10 Output YES Input 4 1 2 1 2 Output NO Input 7 3 3 3 3 3 3 3 Output YES Note In the first example the array is unimodal, because it is strictly increasing in the beginning (from position 1 to position 2, inclusively), that it is constant (from position 2 to position 4, inclusively) and then it is strictly decreasing (from position 4 to position 6, inclusively). ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n; int flag; int a[200]; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); if (i == 1) continue; if (a[i] > a[i - 1]) { if (flag == 2 || flag == 3) { printf("NO"); return 0; } flag = 1; } if (a[i] == a[i - 1]) { if (flag == 3) { printf("NO"); return 0; } flag = 2; } if (a[i] < a[i - 1]) { flag = 3; } } printf("YES"); return 0; } ```
### Prompt Your challenge is to write a CPP solution to the following problem: Iahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of n integers. A sequence a1, a2, ..., an, consisting of n integers, is Hungry if and only if: * Its elements are in increasing order. That is an inequality ai < aj holds for any two indices i, j (i < j). * For any two indices i and j (i < j), aj must not be divisible by ai. Iahub is in trouble, so he asks you for help. Find a Hungry sequence with n elements. Input The input contains a single integer: n (1 ≤ n ≤ 105). Output Output a line that contains n space-separated integers a1 a2, ..., an (1 ≤ ai ≤ 107), representing a possible Hungry sequence. Note, that each ai must not be greater than 10000000 (107) and less than 1. If there are multiple solutions you can output any one. Examples Input 3 Output 2 9 15 Input 5 Output 11 14 20 27 31 ### Response ```cpp #include <bits/stdc++.h> using namespace std; void solve() { long long int n; cin >> n; for (long long int i = 0; i < n; i++) { cout << i + n << " "; } } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long int test = 1; while (test--) { solve(); } return 0; } ```
### Prompt Develop a solution in cpp to the problem described below: You are given a sequence of n integers a1, a2, ..., an. Determine a real number x such that the weakness of the sequence a1 - x, a2 - x, ..., an - x is as small as possible. The weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) of a sequence. The poorness of a segment is defined as the absolute value of sum of the elements of segment. Input The first line contains one integer n (1 ≤ n ≤ 200 000), the length of a sequence. The second line contains n integers a1, a2, ..., an (|ai| ≤ 10 000). Output Output a real number denoting the minimum possible weakness of a1 - x, a2 - x, ..., an - x. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6. Examples Input 3 1 2 3 Output 1.000000000000000 Input 4 1 2 3 4 Output 2.000000000000000 Input 10 1 10 2 9 3 8 4 7 5 6 Output 4.500000000000000 Note For the first case, the optimal value of x is 2 so the sequence becomes - 1, 0, 1 and the max poorness occurs at the segment "-1" or segment "1". The poorness value (answer) equals to 1 in this case. For the second sample the optimal value of x is 2.5 so the sequence becomes - 1.5, - 0.5, 0.5, 1.5 and the max poorness occurs on segment "-1.5 -0.5" or "0.5 1.5". The poorness value (answer) equals to 2 in this case. ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <class C> constexpr int sz(const C &c) { return int(c.size()); } using ll = long long; using ld = long double; constexpr const char nl = '\n', sp = ' '; template <class T, class F, class Cmp = less<T>> T tsearch(T lo, T hi, F f, int iters, Cmp cmp = less<T>()) { for (int it = 0; it < iters; it++) { T m1 = lo + (hi - lo) / 3, m2 = hi - (hi - lo) / 3; if (cmp(f(m1), f(m2))) lo = m1; else hi = m2; } return lo + (hi - lo) / 2; } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int N; cin >> N; vector<ld> A(N); for (auto &&a : A) cin >> a; auto f = [&](ld x) { ld ret = 0, cur = 0; for (auto &&a : A) { cur += a - x; if (cur < 0) cur = 0; if (ret < cur) ret = cur; } cur = 0; for (auto &&a : A) { cur -= a - x; if (cur < 0) cur = 0; if (ret < cur) ret = cur; } return ret; }; cout << fixed << setprecision(9) << f(tsearch(ld(-3e4), ld(3e4), f, 300, greater<ld>())) << nl; return 0; } ```
### Prompt Generate a Cpp solution to the following problem: This task is very simple. Given a string S of length n and q queries each query is on the format i j k which means sort the substring consisting of the characters from i to j in non-decreasing order if k = 1 or in non-increasing order if k = 0. Output the final string after applying the queries. Input The first line will contain two integers n, q (1 ≤ n ≤ 105, 0 ≤ q ≤ 50 000), the length of the string and the number of queries respectively. Next line contains a string S itself. It contains only lowercase English letters. Next q lines will contain three integers each i, j, k (1 ≤ i ≤ j ≤ n, <image>). Output Output one line, the string S after applying the queries. Examples Input 10 5 abacdabcda 7 10 0 5 8 1 1 4 0 3 6 0 7 10 1 Output cbcaaaabdd Input 10 1 agjucbvdfk 1 10 1 Output abcdfgjkuv Note First sample test explanation: <image> <image> <image> <image> <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; using ll = long long; using pii = pair<int, int>; using pli = pair<ll, int>; const int INF = 0x3f3f3f3f, N = 1e5 + 5; const ll LINF = 1e18 + 5; int n, q; char s[N]; struct seg { int l, r, cnt[26], tag[26]; } t[N << 2]; void pushup(int p) { for (int i = 0; i < 26; i++) t[p].cnt[i] = t[p << 1].cnt[i] + t[p << 1 | 1].cnt[i]; } void pushdown(int p, int z) { int &x = t[p].tag[z]; int l = t[p].l, r = t[p].r, mid = (l + r) >> 1; t[p << 1].tag[z] = t[p << 1 | 1].tag[z] = x; if (!x) t[p << 1].cnt[z] = t[p << 1 | 1].cnt[z] = 0; else t[p << 1].cnt[z] = mid - l + 1, t[p << 1 | 1].cnt[z] = r - mid; x = -1; } void build(int p, int l, int r) { t[p].l = l, t[p].r = r; for (int i = 0; i < 26; i++) t[p].cnt[i] = 0, t[p].tag[i] = -1; if (l == r) { t[p].cnt[s[l] - 'a'] = 1; return; } int mid = (l + r) >> 1; build(p << 1, l, mid); build(p << 1 | 1, mid + 1, r); pushup(p); } int query(int p, int x, int y, int z) { int l = t[p].l, r = t[p].r; if (l >= x && r <= y) return t[p].cnt[z]; if (~t[p].tag[z]) pushdown(p, z); int mid = (l + r) >> 1, ans = 0; if (x <= mid) ans += query(p << 1, x, y, z); if (y > mid) ans += query(p << 1 | 1, x, y, z); return ans; } void modify(int p, int x, int y, int z) { int l = t[p].l, r = t[p].r; if (l >= x && r <= y) { for (int i = 0; i < 26; i++) { if (i == z) { if (t[p].cnt[i] != r - l + 1) { t[p].cnt[i] = r - l + 1; t[p].tag[i] = 1; } } else { if (t[p].cnt[i] != 0) { t[p].cnt[i] = 0; t[p].tag[i] = 0; } } } return; } for (int i = 0; i < 26; i++) if (~t[p].tag[i]) pushdown(p, i); int mid = (l + r) >> 1; if (x <= mid) modify(p << 1, x, y, z); if (y > mid) modify(p << 1 | 1, x, y, z); pushup(p); } void update(int p) { int l = t[p].l, r = t[p].r; if (l == r) { for (int i = 0; i < 26; i++) if (t[p].cnt[i]) s[l] = 'a' + i; return; } for (int i = 0; i < 26; i++) if (~t[p].tag[i]) pushdown(p, i); update(p << 1); update(p << 1 | 1); } int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> n >> q; cin >> (s + 1); build(1, 1, n); for (int i = 1; i <= q; i++) { int x, y, z; cin >> x >> y >> z; vector<int> cnt(26); for (int j = 0; j < 26; j++) cnt[j] = query(1, x, y, j); int l = x; if (z) { for (int idx = 0; idx < 26; idx++) { if (!cnt[idx]) continue; int r = l + cnt[idx] - 1; modify(1, l, r, idx); l = r + 1; } } else { for (int idx = 25; idx >= 0; idx--) { if (!cnt[idx]) continue; int r = l + cnt[idx] - 1; modify(1, l, r, idx); l = r + 1; } } } update(1); cout << (s + 1); return 0; } ```
### Prompt Construct a cpp code solution to the problem outlined: The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row. Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same. The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task. Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added). Input The first line of the input contains a single number n (1 ≤ n ≤ 105) — the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≤ hi ≤ 109), where hi equals the number of floors in the i-th house. Output Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one. Examples Input 5 1 2 3 1 2 Output 3 2 0 2 0 Input 4 3 2 1 4 Output 2 3 4 0 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n; vector<int> h, s; int main() { ios_base::sync_with_stdio(false); cin >> n; h.resize(n); for (int i = 0; i < n; ++i) cin >> h[i]; s = h; for (int i = (int)s.size() - 2; i >= 0; --i) s[i] = max(s[i], s[i + 1]); for (int i = 0; i < (int)s.size(); ++i) { if (i + 1 == (int)s.size()) { cout << 0 << endl; } else if (s[i + 1] >= h[i]) { cout << s[i + 1] - h[i] + 1 << ' '; } else { cout << 0 << ' '; } } return 0; } ```
### Prompt Your task is to create a cpp solution to the following problem: We have a square grid with N rows and M columns. Takahashi will write an integer in each of the squares, as follows: * First, write 0 in every square. * For each i=1,2,...,N, choose an integer k_i (0\leq k_i\leq M), and add 1 to each of the leftmost k_i squares in the i-th row. * For each j=1,2,...,M, choose an integer l_j (0\leq l_j\leq N), and add 1 to each of the topmost l_j squares in the j-th column. Now we have a grid where each square contains 0, 1, or 2. Find the number of different grids that can be made this way, modulo 998244353. We consider two grids different when there exists a square with different integers. Constraints * 1 \leq N,M \leq 5\times 10^5 * N and M are integers. Input Input is given from Standard Input in the following format: N M Output Print the number of different grids that can be made, modulo 998244353. Examples Input 1 2 Output 8 Input 2 3 Output 234 Input 10 7 Output 995651918 Input 314159 265358 Output 70273732 ### Response ```cpp #pragma GCC optimize(2,3,"Ofast") #include<bits/stdc++.h> using namespace std; #define ll long long #define db double #define in inline namespace fast_io { char buf[1<<12],*p1=buf,*p2=buf,sr[1<<23],z[23],nc;int C=-1,Z=0,Bi=0,ny; in char gc() {return p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<12,stdin),p1==p2)?EOF:*p1++;} in int read() { int x=0;ny=1;while(nc=gc(),(nc<48||nc>57)&&nc!=EOF)if(nc==45)ny=-1;Bi=1;if(nc<0)return nc; x=nc-48;while(nc=gc(),47<nc&&nc<58&&nc!=EOF)x=(x<<3)+(x<<1)+(nc^48),Bi++;return x*ny; } in db gf() {int a=read(),y=ny,b=(nc!='.')?0:read();return (b?a+(db)b/pow(10,Bi)*y:a);} in int gs(char *s) {char c,*t=s;while(c=gc(),c<32);*s++=c;while(c=gc(),c>32)*s++=c;return s-t;} in void ot() {fwrite(sr,1,C+1,stdout);C=-1;} in void flush() {if(C>1<<22) ot();} template <typename T> in void write(T x,char t) { int y=0;if(x<0)y=1,x=-x;while(z[++Z]=x%10+48,x/=10); if(y)z[++Z]='-';while(sr[++C]=z[Z],--Z);sr[++C]=t;flush(); } in void write(char *s) {int l=strlen(s);for(int i=0;i<l;i++)sr[++C]=*s++;sr[++C]='\n';flush();} }; using namespace fast_io; const int N=5e5+5,p=998244353; int n,m,mx,mn,ans,cm[N],cn[N],fac[N],inv[N]; in void M(int &x) {x-=p;x+=x>>31&p;} in int qpow(int a,int b) {int c=1;for(;b;b>>=1,a=1ll*a*a%p)if(b&1)c=1ll*a*c%p;return c;} in int c(int n,int m) {return 1ll*fac[n]*inv[m]%p*inv[n-m]%p;} int main() { n=read(),m=read();mx=max(n,m);mn=min(n,m); fac[0]=cm[0]=cn[0]=1;for(int i=1;i<=mx;i++) fac[i]=1ll*fac[i-1]*i%p; inv[mx]=qpow(fac[mx],p-2);for(int i=mx-1;~i;i--) inv[i]=inv[i+1]*(i+1ll)%p; for(int i=1;i<=n;i++) cm[i]=cm[i-1]*(m+1ll)%p; for(int i=1;i<=m;i++) cn[i]=cn[i-1]*(n+1ll)%p; for(int i=0;i<=mn;i++) { int res=1ll*c(n,i)*c(m,i)%p*fac[i]%p*cm[n-i]%p*cn[m-i]%p; M(ans+=(i&1)?p-res:res); } write(ans,'\n'); return ot(),0; } //Author: disangan233 ```
### Prompt Please create a solution in cpp to the following problem: Problem Statement Fox Ciel is practicing miniature golf, a golf game played with a putter club only. For improving golf skills, she believes it is important how well she bounces the ball against walls. The field of miniature golf is in a two-dimensional plane and surrounded by $N$ walls forming a convex polygon. At first, the ball is placed at $(s_x, s_y)$ inside the field. The ball is small enough to be regarded as a point. Ciel can shoot the ball to any direction and stop the ball whenever she wants. The ball will move in a straight line. When the ball hits the wall, it rebounds like mirror reflection (i.e. incidence angle equals reflection angle). For practice, Ciel decided to make a single shot under the following conditions: * The ball hits each wall of the field exactly once. * The ball does NOT hit the corner of the field. Count the number of possible orders in which the ball hits the walls. Input The input contains several datasets. The number of datasets does not exceed $100$. Each dataset is in the following format. > $N$ > $s_x$ $s_y$ > $x_1$ $y_1$ > : > : > $x_N$ $y_N$ The first line contains an integer $N$ ($3 \leq N \leq 8$). The next line contains two integers $s_x$ and $s_y$ ($-50 \leq s_x, s_y \leq 50$), which describe the coordinates of the initial position of the ball. Each of the following $N$ lines contains two integers $x_i$ and $y_i$ ($-50 \leq x_i, y_i \leq 50$), which describe the coordinates of each corner of the field. The corners are given in counterclockwise order. You may assume given initial position $(s_x, s_y)$ is inside the field and the field is convex. It is guaranteed that there exists a shoot direction for each valid order of the walls that satisfies the following condition: distance between the ball and the corners of the field $(x_i, y_i)$ is always greater than $10^{-6}$ until the ball hits the last wall. The last dataset is followed by a line containing a single zero. Output For each dataset in the input, print the number of valid orders of the walls in a line. Sample Input 4 0 0 -10 -10 10 -10 10 10 -10 10 0 Output for the Sample Input 8 Example Input 4 0 0 -10 -10 10 -10 10 10 -10 10 0 Output 8 ### Response ```cpp #include <bits/stdc++.h> using namespace std; using ld = double; using point = std::complex<ld>; using polygon = std::vector<point>; struct line { line() : a(0, 0), b(0, 0) {} line(point a_, point b_) : a(a_), b(b_) {} point a, b; }; ld dot(point const& a, point const& b) { return std::real(std::conj(a) * b); } ld cross(point const& a, point const& b) { return std::imag(std::conj(a) * b); } point proj(line const& l, point const& p) { ld t = dot(p - l.a, l.a - l.b) / std::norm(l.a - l.b); return l.a + t * (l.a - l.b); } point reflect(line const& l, point const& p) { return p + (proj(l, p) - p) * 2.0; } point read_point() { ld x, y; cin >> x >> y; return point{x, y}; } int main() { int n; while(cin >> n, n) { const auto sp = read_point(); polygon ps; for(int i = 0; i < n; ++i) { ps.emplace_back(read_point()); } vector<int> ord(n); iota(begin(ord), end(ord), 0); int ans = 0; do { auto ts = ps; vector<point> lvs, rvs; for(auto i : ord) { const auto a = ts[i], b = ts[(i + 1) % n]; lvs.push_back(a + (b - a) / abs(b - a) * 1e-6 - sp); rvs.push_back(b + (a - b) / abs(b - a) * 1e-6 - sp); if(cross(rvs.back(), lvs.back()) < 0) swap(lvs.back(), rvs.back()); for(int j = 0; j < n; ++j) { if(j == i || (i + 1) % n == j) continue; ts[j] = reflect(line{a, b}, ts[j]); } } auto lv = lvs[0], rv = rvs[0]; bool check = true; for(int i = 1; i < n; ++i) { if(cross(lv, lvs[i]) <= 0) swap(lv, lvs[i]); if(cross(rv, rvs[i]) >= 0) swap(rv, rvs[i]); check &= cross(rv, lv) >= 0; } ans += check; } while(next_permutation(begin(ord), end(ord))); cout << ans << endl; } } ```
### Prompt Develop a solution in cpp to the problem described below: The main street of Berland is a straight line with n houses built along it (n is an even number). The houses are located at both sides of the street. The houses with odd numbers are at one side of the street and are numbered from 1 to n - 1 in the order from the beginning of the street to the end (in the picture: from left to right). The houses with even numbers are at the other side of the street and are numbered from 2 to n in the order from the end of the street to its beginning (in the picture: from right to left). The corresponding houses with even and odd numbers are strictly opposite each other, that is, house 1 is opposite house n, house 3 is opposite house n - 2, house 5 is opposite house n - 4 and so on. <image> Vasya needs to get to house number a as quickly as possible. He starts driving from the beginning of the street and drives his car to house a. To get from the beginning of the street to houses number 1 and n, he spends exactly 1 second. He also spends exactly one second to drive the distance between two neighbouring houses. Vasya can park at any side of the road, so the distance between the beginning of the street at the houses that stand opposite one another should be considered the same. Your task is: find the minimum time Vasya needs to reach house a. Input The first line of the input contains two integers, n and a (1 ≤ a ≤ n ≤ 100 000) — the number of houses on the street and the number of the house that Vasya needs to reach, correspondingly. It is guaranteed that number n is even. Output Print a single integer — the minimum time Vasya needs to get from the beginning of the street to house a. Examples Input 4 2 Output 2 Input 8 5 Output 3 Note In the first sample there are only four houses on the street, two houses at each side. House 2 will be the last at Vasya's right. The second sample corresponds to picture with n = 8. House 5 is the one before last at Vasya's left. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n, a; cin >> n >> a; if (a % 2 == 1) cout << a - (a / 2); else cout << n / 2 - a / 2 + 1; return 0; } ```
### Prompt Please provide a Cpp coded solution to the problem described below: You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times. Input The first line contains positive integer n (2 ≤ n ≤ 105) — size of the given array. The second line contains n integers a0, a1, ..., an - 1 (1 ≤ ai ≤ 109) — elements of the array. It is guaranteed that in the array a minimum occurs at least two times. Output Print the only number — distance between two nearest minimums in the array. Examples Input 2 3 3 Output 1 Input 3 5 6 5 Output 2 Input 9 2 1 3 5 4 1 2 3 1 Output 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int a[100020]; int main(void) { int n; int i; int o; vector<int> v; scanf("%d", &n); for (i = 1; i <= n; i++) scanf("%d", &a[i]); v.clear(); for (i = 2, v.push_back(1), o = n; i <= n; i++) { if (a[i] == a[v.at(0)]) { o = min(o, i - v.at(v.size() - 1)); v.push_back(i); } if (a[i] < a[v.at(0)]) { v.clear(); v.push_back(i); o = n; } } printf("%d\n", o); return 0; } ```
### Prompt Develop a solution in Cpp to the problem described below: You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges. During one move, you can choose some gift 1 ≤ i ≤ n and do one of the following operations: * eat exactly one candy from this gift (decrease a_i by one); * eat exactly one orange from this gift (decrease b_i by one); * eat exactly one candy and exactly one orange from this gift (decrease both a_i and b_i by one). Of course, you can not eat a candy or orange if it's not present in the gift (so neither a_i nor b_i can become less than zero). As said above, all gifts should be equal. This means that after some sequence of moves the following two conditions should be satisfied: a_1 = a_2 = ... = a_n and b_1 = b_2 = ... = b_n (and a_i equals b_i is not necessary). Your task is to find the minimum number of moves required to equalize all the given gifts. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 50) — the number of gifts. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the number of candies in the i-th gift. The third line of the test case contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the number of oranges in the i-th gift. Output For each test case, print one integer: the minimum number of moves required to equalize all the given gifts. Example Input 5 3 3 5 6 3 2 3 5 1 2 3 4 5 5 4 3 2 1 3 1 1 1 2 2 2 6 1 1000000000 1000000000 1000000000 1000000000 1000000000 1 1 1 1 1 1 3 10 12 8 7 5 4 Output 6 16 0 4999999995 7 Note In the first test case of the example, we can perform the following sequence of moves: * choose the first gift and eat one orange from it, so a = [3, 5, 6] and b = [2, 2, 3]; * choose the second gift and eat one candy from it, so a = [3, 4, 6] and b = [2, 2, 3]; * choose the second gift and eat one candy from it, so a = [3, 3, 6] and b = [2, 2, 3]; * choose the third gift and eat one candy and one orange from it, so a = [3, 3, 5] and b = [2, 2, 2]; * choose the third gift and eat one candy from it, so a = [3, 3, 4] and b = [2, 2, 2]; * choose the third gift and eat one candy from it, so a = [3, 3, 3] and b = [2, 2, 2]. ### Response ```cpp #include <bits/stdc++.h> using namespace std; bool isprime(long long int x) { if (x <= 1) { return false; } if (x <= 3) { return true; } for (long long int i = 5; i < sqrt(x); i += 6) { if (x % i == 0 || x % (i + 2) == 0) { return false; } } return true; } long long int gcd(long long int a, long long int b) { if (b == 0) { return a; } return gcd(b, a % b); } long long int lcm(long long int a, long long int b) { return (a * b) / (gcd(a, b)); } void swap(int& a, int& b) { a = a ^ b; b = a ^ b; a = a ^ b; } bool isPowerOfTwo(long long int n) { if (n == 0) return false; return (ceil(log2(n)) == floor(log2(n))); } long long int getcl(long long int a, long long int b) { return (a + b - 1) / b; } long long int min_of_3(long long int a, long long int b, long long int c) { a = min(a, b); c = min(a, c); return c; } long long int powMod(long long int x, long long int y, long long int p = 1000000007) { long long int res = 1; x = x % p; if (x == 0) return 0; while (y > 0) { if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } inline void solve() { long long int n, c = 0; cin >> n; vector<long long int> a(n), b(n); for (auto& i : a) cin >> i; for (auto& i : b) cin >> i; long long int amin = *min_element(a.begin(), a.end()); long long int bmin = *min_element(b.begin(), b.end()); for (int i = 0; i < n; ++i) { c += max(a[i] - amin, b[i] - bmin); } cout << c << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ; long long int t; cin >> t; while (t--) { solve(); } return 0; } ```
### Prompt Please create a solution in cpp to the following problem: The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thus, Sereja orders a number of pizzas so they can eat right after the end of the competition. Teams plan to train for n times during n consecutive days. During the training session Sereja orders exactly one pizza for each team that is present this day. He already knows that there will be ai teams on the i-th day. There are two types of discounts in Sereja's favourite pizzeria. The first discount works if one buys two pizzas at one day, while the second is a coupon that allows to buy one pizza during two consecutive days (two pizzas in total). As Sereja orders really a lot of pizza at this place, he is the golden client and can use the unlimited number of discounts and coupons of any type at any days. Sereja wants to order exactly ai pizzas on the i-th day while using only discounts and coupons. Note, that he will never buy more pizzas than he need for this particular day. Help him determine, whether he can buy the proper amount of pizzas each day if he is allowed to use only coupons and discounts. Note, that it's also prohibited to have any active coupons after the end of the day n. Input The first line of input contains a single integer n (1 ≤ n ≤ 200 000) — the number of training sessions. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 10 000) — the number of teams that will be present on each of the days. Output If there is a way to order pizzas using only coupons and discounts and do not buy any extra pizzas on any of the days, then print "YES" (without quotes) in the only line of output. Otherwise, print "NO" (without quotes). Examples Input 4 1 2 1 2 Output YES Input 3 1 0 1 Output NO Note In the first sample, Sereja can use one coupon to buy one pizza on the first and the second days, one coupon to buy pizza on the second and the third days and one discount to buy pizzas on the fourth days. This is the only way to order pizzas for this sample. In the second sample, Sereja can't use neither the coupon nor the discount without ordering an extra pizza. Note, that it's possible that there will be no teams attending the training sessions on some days. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int a[200005]; int main() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &a[i]); for (int i = 0; i < n; i++) { a[i] %= 2; if (a[i]) { if (a[i + 1]) a[i + 1]--; else { printf("NO\n"); return 0; } } } printf("YES\n"); return 0; } ```
### Prompt Your task is to create a Cpp solution to the following problem: After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of n horizontal and m vertical sticks. An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick. In the grid shown below, n = 3 and m = 3. There are n + m = 6 sticks in total (horizontal sticks are shown in red and vertical sticks are shown in green). There are n·m = 9 intersection points, numbered from 1 to 9. <image> The rules of the game are very simple. The players move in turns. Akshat won gold, so he makes the first move. During his/her move, a player must choose any remaining intersection point and remove from the grid all sticks which pass through this point. A player will lose the game if he/she cannot make a move (i.e. there are no intersection points remaining on the grid at his/her move). Assume that both players play optimally. Who will win the game? Input The first line of input contains two space-separated integers, n and m (1 ≤ n, m ≤ 100). Output Print a single line containing "Akshat" or "Malvika" (without the quotes), depending on the winner of the game. Examples Input 2 2 Output Malvika Input 2 3 Output Malvika Input 3 3 Output Akshat Note Explanation of the first sample: The grid has four intersection points, numbered from 1 to 4. <image> If Akshat chooses intersection point 1, then he will remove two sticks (1 - 2 and 1 - 3). The resulting grid will look like this. <image> Now there is only one remaining intersection point (i.e. 4). Malvika must choose it and remove both remaining sticks. After her move the grid will be empty. In the empty grid, Akshat cannot make any move, hence he will lose. Since all 4 intersection points of the grid are equivalent, Akshat will lose no matter which one he picks. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; int c = 0; int a; for (int i = 1; i <= n; i++) { a = (n - i) * (m - i); c++; if (a == 0) break; } if (c % 2 == 0) cout << "Malvika"; else cout << "Akshat"; } ```
### Prompt Please create a solution in cpp to the following problem: Vanya got an important task — he should enumerate books in the library and label each book with its number. Each of the n books should be assigned with a number from 1 to n. Naturally, distinct books should be assigned distinct numbers. Vanya wants to know how many digits he will have to write down as he labels the books. Input The first line contains integer n (1 ≤ n ≤ 109) — the number of books in the library. Output Print the number of digits needed to number all the books. Examples Input 13 Output 17 Input 4 Output 4 Note Note to the first test. The books get numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, which totals to 17 digits. Note to the second sample. The books get numbers 1, 2, 3, 4, which totals to 4 digits. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n, nn, c = 0; long long res = 0, nins = 9; cin >> n; nn = n; while (nn) { c++, nn /= 10; if (nn) res += nins * c, nins *= 10; } if (c == 1) cout << n; else { res += (n - (int)(pow(10, c - 1) + 1e-9) + 1LL) * c; cout << res; } } ```
### Prompt Generate a Cpp solution to the following problem: Find the sum of the weights of edges of the Minimum-Cost Arborescence with the root r for a given weighted directed graph G = (V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * 0 ≤ wi ≤ 10,000 * G has arborescence(s) with the root r Input |V| |E| r s0 t0 w0 s1 t1 w1 : s|E|-1 t|E|-1 w|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the root of the Minimum-Cost Arborescence. si and ti represent source and target verticess of i-th directed edge. wi represents the weight of the i-th directed edge. Output Print the sum of the weights the Minimum-Cost Arborescence. Examples Input 4 6 0 0 1 3 0 2 2 2 0 1 2 3 1 3 0 1 3 1 5 Output 6 Input 6 10 0 0 2 7 0 1 1 0 3 5 1 4 9 2 1 6 1 3 2 3 4 3 4 2 2 2 5 8 3 5 3 Output 11 ### Response ```cpp #include "bits/stdc++.h" using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; const int INF = 1e9; const ll LINF = 1e18; template<class S,class T> ostream& operator << (ostream& out,const pair<S,T>& o){ out << "(" << o.first << "," << o.second << ")"; return out; } template<class T> ostream& operator << (ostream& out,const vector<T> V){ for(int i = 0; i < V.size(); i++){ out << V[i]; if(i!=V.size()-1) out << " ";} return out; } template<class T> ostream& operator << (ostream& out,const vector<vector<T> > Mat){ for(int i = 0; i < Mat.size(); i++) { if(i != 0) out << endl; out << Mat[i];} return out; } template<class S,class T> ostream& operator << (ostream& out,const map<S,T> mp){ out << "{ "; for(auto it = mp.begin(); it != mp.end(); it++){ out << it->first << ":" << it->second; if(mp.size()-1 != distance(mp.begin(),it)) out << ", "; } out << " }"; return out; } // 最小全域有向木 O(EV) // 0-index // 例外判定のために Edge[0] => {-1,-1,-1} が必須なため 辺のindexは 1-index const int MAXV = 10010; const int MAXE = 10010; const int MAXW = 2147483647; struct Edge { int u, v, c; Edge(int x = -1, int y = 0, int z = 0) : u(x), v(y), c(z) {} }; int V, E, root; Edge edges[MAXE]; inline void addEdge(int u, int v, int c){ edges[++E] = Edge(u, v, c);} bool con[MAXV]; int mnInW[MAXV], prv[MAXV], cyc[MAXV], vis[MAXV]; inline int DMST() { fill(con, con + V, 0); int r1 = 0, r2 = 0; while (true) { fill(mnInW, mnInW + V, MAXW); fill(prv, prv + V, -1); for (int i = 1; i <= E; i++) { int u = edges[i].u, v = edges[i].v, c = edges[i].c; if (u != v && v != root && c < mnInW[v]){mnInW[v] = c; prv[v] = u;} } fill(vis, vis + V, -1); fill(cyc, cyc + V, -1); r1 = 0; bool jf = false; for (int i = 0; i < V; i++) { if (con[i]) continue; if (prv[i] == -1 && i != root) { return -1; } if (prv[i] >= 0) r1 += mnInW[i]; int s; for (s = i; s != -1 && vis[s] == -1; s = prv[s]) vis[s] = i; if (s >= 0 && vis[s] == i) { // get a cycle jf = true; int v = s; do { cyc[v] = s; con[v] = true; r2 += mnInW[v]; v = prv[v]; } while (v != s); con[s] = false; } } if (!jf) break; for (int i = 1; i <= E; i++) { int &u = edges[i].u; int &v = edges[i].v; if (cyc[v] >= 0) edges[i].c -= mnInW[edges[i].v]; if (cyc[u] >= 0) edges[i].u = cyc[edges[i].u]; if (cyc[v] >= 0) edges[i].v = cyc[edges[i].v]; if (u == v){ edges[i--] = edges[E--]; } } } return r1 + r2; } int main() { cin.tie(0); ios_base::sync_with_stdio(false); int e; cin >> V >> e >> root; for(int i = 0; i < e;i++) { int a, b, c; cin >> a >> b >> c; addEdge(a, b, c); } cout << DMST() << endl; return 0; } ```
### Prompt Generate a cpp solution to the following problem: One day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the results. Find out how the deminations of the coins differ or if Vasya has a mistake in the weighting results. No two coins are equal. Input The input data contains the results of all the weighting, one result on each line. It is guaranteed that every coin pair was weighted exactly once. Vasya labelled the coins with letters «A», «B» and «C». Each result is a line that appears as (letter)(> or < sign)(letter). For example, if coin "A" proved lighter than coin "B", the result of the weighting is A<B. Output It the results are contradictory, print Impossible. Otherwise, print without spaces the rearrangement of letters «A», «B» and «C» which represent the coins in the increasing order of their weights. Examples Input A&gt;B C&lt;B A&gt;C Output CBA Input A&lt;B B&gt;C C&gt;A Output ACB ### Response ```cpp #include <bits/stdc++.h> using namespace std; void solve() { string a, b, c; cin >> a >> b >> c; long long ar[3] = {0}; if (a[1] == '>') ar[a[0] - 'A']++; else ar[a[2] - 'A']++; if (b[1] == '>') ar[b[0] - 'A']++; else ar[b[2] - 'A']++; if (c[1] == '>') ar[c[0] - 'A']++; else ar[c[2] - 'A']++; if (ar[0] == ar[1]) { cout << "Impossible"; return; } vector<pair<long long, char> > v; v.push_back({ar[0], 'A'}); v.push_back({ar[1], 'B'}); v.push_back({ar[2], 'C'}); sort(v.begin(), v.end()); for (int i = 0; i < 3; i++) cout << v[i].second; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); solve(); } ```
### Prompt Generate a Cpp solution to the following problem: A new innovative ticketing systems for public transport is introduced in Bytesburg. Now there is a single travel card for all transport. To make a trip a passenger scan his card and then he is charged according to the fare. The fare is constructed in the following manner. There are three types of tickets: 1. a ticket for one trip costs 20 byteland rubles, 2. a ticket for 90 minutes costs 50 byteland rubles, 3. a ticket for one day (1440 minutes) costs 120 byteland rubles. Note that a ticket for x minutes activated at time t can be used for trips started in time range from t to t + x - 1, inclusive. Assume that all trips take exactly one minute. To simplify the choice for the passenger, the system automatically chooses the optimal tickets. After each trip starts, the system analyses all the previous trips and the current trip and chooses a set of tickets for these trips with a minimum total cost. Let the minimum total cost of tickets to cover all trips from the first to the current is a, and the total sum charged before is b. Then the system charges the passenger the sum a - b. You have to write a program that, for given trips made by a passenger, calculates the sum the passenger is charged after each trip. Input The first line of input contains integer number n (1 ≤ n ≤ 105) — the number of trips made by passenger. Each of the following n lines contains the time of trip ti (0 ≤ ti ≤ 109), measured in minutes from the time of starting the system. All ti are different, given in ascending order, i. e. ti + 1 > ti holds for all 1 ≤ i < n. Output Output n integers. For each trip, print the sum the passenger is charged after it. Examples Input 3 10 20 30 Output 20 20 10 Input 10 13 45 46 60 103 115 126 150 256 516 Output 20 20 10 0 20 0 0 20 20 10 Note In the first example, the system works as follows: for the first and second trips it is cheaper to pay for two one-trip tickets, so each time 20 rubles is charged, after the third trip the system understands that it would be cheaper to buy a ticket for 90 minutes. This ticket costs 50 rubles, and the passenger had already paid 40 rubles, so it is necessary to charge 10 rubles only. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { long long n, t; cin >> n; long long spent90 = 0, spent1440 = 0; bool flag90 = false, flag1440 = false; priority_queue<pair<long long, long long>, vector<pair<long long, long long> >, greater<pair<long long, long long> > > pq90, pq1440; for (long long i = 0; i < n; i++) { cin >> t; if (spent90 == 50 && t - pq90.top().first < 90 || spent1440 == 120 && t - pq1440.top().first < 1440) cout << 0 << endl; else { while (!pq1440.empty() && t - pq1440.top().first >= 1440) { spent1440 -= pq1440.top().second; pq1440.pop(); } while (!pq90.empty() && t - pq90.top().first >= 90) { spent90 -= pq90.top().second; pq90.pop(); } long long pay = min(120 - spent1440, min(50 - spent90, 20LL)); spent90 += pay; spent1440 += pay; pq90.push(make_pair(t, pay)); pq1440.push(make_pair(t, pay)); cout << pay << endl; } } return 0; } ```
### Prompt Your task is to create a CPP solution to the following problem: You are given a polynomial of degree N with integer coefficients: f(x)=a_Nx^N+a_{N-1}x^{N-1}+...+a_0. Find all prime numbers p that divide f(x) for every integer x. Constraints * 0 \leq N \leq 10^4 * |a_i| \leq 10^9(0\leq i\leq N) * a_N \neq 0 * All values in input are integers. Input Input is given from Standard Input in the following format: N a_N : a_0 Output Print all prime numbers p that divide f(x) for every integer x, in ascending order. Examples Input 2 7 -7 14 Output 2 7 Input 3 1 4 1 5 Output Input 0 998244353 Output 998244353 ### Response ```cpp #include <bits/stdc++.h> using namespace std; #define N 10010 int n, a[N], b[N]; bool isprime(int x) { for (int i = 2; 1ll * i * i <= x; ++i) { if (x % i == 0) { return false; } } return true; } int gcd(int a, int b) { return b ? gcd(b, a % b) : a; } bool ok(int p) { if (a[0] % p) { return false; } for (int i = 0; i <= n - 1; ++i) { b[i] = a[i + 1]; } for (int i = n; i >= p - 1; --i) { (b[i - (p - 1)] += b[i]) %= p; b[i] = 0; } for (int i = 0; i <= n - 1; ++i) { if (b[i] % p) { return false; } } return true; } int main() { while (scanf("%d", &n) != EOF) { int G = 0; for (int i = 0; i <= n; ++i) { scanf("%d", a + i); G = gcd(G, abs(a[i])); } reverse(a, a + 1 + n); vector <int> res; for (int i = 2; 1ll * i * i <= G; ++i) { if (G % i == 0) { res.push_back(i); while (G % i == 0) { G /= i; } } } if (G > 1) { res.push_back(G); } for (int i = 2; i <= n; ++i) { if (isprime(i) && ok(i)) { res.push_back(i); } } sort(res.begin(), res.end()); res.erase(unique(res.begin(), res.end()), res.end()); for (auto it : res) { printf("%d\n", it); } // puts("------------"); } return 0; } ```
### Prompt Generate a Cpp solution to the following problem: Vova's house is an array consisting of n elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The i-th element of the array is 1 if there is a heater in the position i, otherwise the i-th element of the array is 0. Each heater has a value r (r is the same for all heaters). This value means that the heater at the position pos can warm up all the elements in range [pos - r + 1; pos + r - 1]. Vova likes to walk through his house while he thinks, and he hates cold positions of his house. Vova wants to switch some of his heaters on in such a way that each element of his house will be warmed up by at least one heater. Vova's target is to warm up the whole house (all the elements of the array), i.e. if n = 6, r = 2 and heaters are at positions 2 and 5, then Vova can warm up the whole house if he switches all the heaters in the house on (then the first 3 elements will be warmed up by the first heater and the last 3 elements will be warmed up by the second heater). Initially, all the heaters are off. But from the other hand, Vova didn't like to pay much for the electricity. So he wants to switch the minimum number of heaters on in such a way that each element of his house is warmed up by at least one heater. Your task is to find this number of heaters or say that it is impossible to warm up the whole house. Input The first line of the input contains two integers n and r (1 ≤ n, r ≤ 1000) — the number of elements in the array and the value of heaters. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1) — the Vova's house description. Output Print one integer — the minimum number of heaters needed to warm up the whole house or -1 if it is impossible to do it. Examples Input 6 2 0 1 1 0 0 1 Output 3 Input 5 3 1 0 0 0 1 Output 2 Input 5 10 0 0 0 0 0 Output -1 Input 10 3 0 0 1 1 0 1 0 0 0 1 Output 3 Note In the first example the heater at the position 2 warms up elements [1; 3], the heater at the position 3 warms up elements [2, 4] and the heater at the position 6 warms up elements [5; 6] so the answer is 3. In the second example the heater at the position 1 warms up elements [1; 3] and the heater at the position 5 warms up elements [3; 5] so the answer is 2. In the third example there are no heaters so the answer is -1. In the fourth example the heater at the position 3 warms up elements [1; 5], the heater at the position 6 warms up elements [4; 8] and the heater at the position 10 warms up elements [8; 10] so the answer is 3. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int a[1100], n, r; cin >> n >> r; for (int i = 1; i <= n; i++) cin >> a[i]; int ultimul = 0; int cnt = 0; while (ultimul < n) { int pos = 0; for (int i = n; i > max(0, ultimul - (r - 1)); i--) if (a[i] && i - r <= ultimul) { pos = i; break; } if (!pos) { cout << "-1"; return 0; } cnt++; ultimul = pos + r - 1; } cout << cnt; } ```
### Prompt Develop a solution in CPP to the problem described below: There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens. Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought n packets with inflatable balloons, where i-th of them has exactly a_i balloons inside. They want to divide the balloons among themselves. In addition, there are several conditions to hold: * Do not rip the packets (both Grigory and Andrew should get unbroken packets); * Distribute all packets (every packet should be given to someone); * Give both Grigory and Andrew at least one packet; * To provide more fun, the total number of balloons in Grigory's packets should not be equal to the total number of balloons in Andrew's packets. Help them to divide the balloons or determine that it's impossible under these conditions. Input The first line of input contains a single integer n (1 ≤ n ≤ 10) — the number of packets with balloons. The second line contains n integers: a_1, a_2, …, a_n (1 ≤ a_i ≤ 1000) — the number of balloons inside the corresponding packet. Output If it's impossible to divide the balloons satisfying the conditions above, print -1. Otherwise, print an integer k — the number of packets to give to Grigory followed by k distinct integers from 1 to n — the indices of those. The order of packets doesn't matter. If there are multiple ways to divide balloons, output any of them. Examples Input 3 1 2 1 Output 2 1 2 Input 2 5 5 Output -1 Input 1 10 Output -1 Note In the first test Grigory gets 3 balloons in total while Andrey gets 1. In the second test there's only one way to divide the packets which leads to equal numbers of balloons. In the third test one of the boys won't get a packet at all. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int const N = 1e6 + 100; long long int const LINF = numeric_limits<long long int>::max(); int const INF = numeric_limits<int>::max(); int const BN = 31; long long int gcd(long long int a, long long int b) { return b ? gcd(b, a % b) : a; } long long int pow_mod(long long int a, long long int e, long long int m) { long long int res = 1; while (e) { if (e & 1) res = res * a % m; a = a * a % m; e >>= 1; } return res; } long long int inv_mod(long long int b, long long int m) { b %= m; long long int x = 0, y = 1, r, q, a = m; while (b) { q = a / b; r = a % b; a = b; b = r; r = x; x = y; y = r - q * y; } x += m; return x % m; } int main() { int n; cin >> n; vector<int> arr(n); for (int i = 0; i < n; i++) cin >> arr[i]; if (n == 1) cout << -1 << endl; else if (n == 2) { if (arr[0] == arr[1]) cout << -1 << endl; else cout << 1 << endl << 1 << endl; } else { int idx = 0, m = 10000; for (int i = 0; i < n; i++) { if (arr[i] < m) { idx = i + 1; m = arr[i]; } } cout << 1 << endl << idx << endl; } } ```
### Prompt Please formulate a cpp solution to the following problem: The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble. The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble. But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts: * each cup contains a mark — a number from 1 to n; all marks on the cups are distinct; * the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position). When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist. Input The first line contains integers n and m (1 ≤ n, m ≤ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 ≤ xi, yi ≤ n) — the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order. Output If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i. If there are multiple correct answers, you should print the lexicographically minimum one. Examples Input 2 1 2 1 Output 2 1 Input 3 2 1 2 1 1 Output 2 1 3 Input 3 3 1 3 2 3 1 3 Output -1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <class T> inline void read(T& x) { bool fu = 0; char c; for (c = getchar(); c <= 32; c = getchar()) ; if (c == '-') fu = 1, c = getchar(); for (x = 0; c > 32; c = getchar()) x = x * 10 + c - '0'; if (fu) x = -x; }; template <class T> inline void read(T& x, T& y) { read(x); read(y); } template <class T> inline void read(T& x, T& y, T& z) { read(x); read(y); read(z); } inline char getc() { char c; for (c = getchar(); c <= 32; c = getchar()) ; return c; } const int N = 8000010; int n, m, i, j, k, l, r, p, d, zz; int s[N], key[N], a[N], w[N]; void upd(int i) { s[i] = s[i * 2] + s[i * 2 + 1]; } int get(int i, int x, int y, int k) { if (x == y) return d = key[i], x; if (k <= s[i * 2]) return get(i * 2, x, (x + y) / 2, k); else return get(i * 2 + 1, (x + y) / 2 + 1, y, k - s[i * 2]); } void bui(int i, int x, int y) { if (x != y) { bui(i * 2, x, (x + y) / 2); bui(i * 2 + 1, (x + y) / 2 + 1, y); upd(i); } else s[i] = (x > m); } void ins(int i, int x, int y, int d, bool ki) { if (x == y) { if (ki) { key[i] = zz, s[i] = 1; w[zz] = d; } else s[i] = 0; return; } if (d <= (x + y) / 2) ins(i * 2, x, (x + y) / 2, d, ki); else ins(i * 2 + 1, (x + y) / 2 + 1, y, d, ki); upd(i); } bool have[N]; int main() { read(n, m); bui(1, 1, n + m); memset(w, -1, sizeof(w)); int x, y; l = m; for (int t = (1); t <= (m); t++) { read(x, y); zz = x; have[x] = 1; p = get(1, 1, n + m, y); if (w[x] != -1 && w[x] != p) { printf("-1\n"); return 0; } if (p > m) a[p - m] = x; if (d > 0 && x != d) { printf("-1\n"); return 0; } ins(1, 1, n + m, p, 0); l--; ins(1, 1, n + m, l, 1); } j = 1; for (i = 1; i <= n; i++) if (a[i] == 0) { for (; j <= n && have[j]; j++) ; a[i] = j++; } for (i = 1; i <= n; i++) printf("%d%s", a[i], i == n ? "\n" : " "); scanf("\n"); return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: Phoenix has a string s consisting of lowercase Latin letters. He wants to distribute all the letters of his string into k non-empty strings a_1, a_2, ..., a_k such that every letter of s goes to exactly one of the strings a_i. The strings a_i do not need to be substrings of s. Phoenix can distribute letters of s and rearrange the letters within each string a_i however he wants. For example, if s = baba and k=2, Phoenix may distribute the letters of his string in many ways, such as: * ba and ba * a and abb * ab and ab * aa and bb But these ways are invalid: * baa and ba * b and ba * baba and empty string (a_i should be non-empty) Phoenix wants to distribute the letters of his string s into k strings a_1, a_2, ..., a_k to minimize the lexicographically maximum string among them, i. e. minimize max(a_1, a_2, ..., a_k). Help him find the optimal distribution and print the minimal possible value of max(a_1, a_2, ..., a_k). String x is lexicographically less than string y if either x is a prefix of y and x ≠ y, or there exists an index i (1 ≤ i ≤ min(|x|, |y|)) such that x_i < y_i and for every j (1 ≤ j < i) x_j = y_j. Here |x| denotes the length of the string x. Input The input consists of multiple test cases. The first line contains an integer t (1 ≤ t ≤ 1000) — the number of test cases. Each test case consists of two lines. The first line of each test case consists of two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the length of string s and the number of non-empty strings, into which Phoenix wants to distribute letters of s, respectively. The second line of each test case contains a string s of length n consisting only of lowercase Latin letters. It is guaranteed that the sum of n over all test cases is ≤ 10^5. Output Print t answers — one per test case. The i-th answer should be the minimal possible value of max(a_1, a_2, ..., a_k) in the i-th test case. Example Input 6 4 2 baba 5 2 baacb 5 3 baacb 5 3 aaaaa 6 4 aaxxzz 7 1 phoenix Output ab abbc b aa x ehinopx Note In the first test case, one optimal solution is to distribute baba into ab and ab. In the second test case, one optimal solution is to distribute baacb into abbc and a. In the third test case, one optimal solution is to distribute baacb into ac, ab, and b. In the fourth test case, one optimal solution is to distribute aaaaa into aa, aa, and a. In the fifth test case, one optimal solution is to distribute aaxxzz into az, az, x, and x. In the sixth test case, one optimal solution is to distribute phoenix into ehinopx. ### Response ```cpp #include <bits/stdc++.h> using namespace std; void solve() { int n, k; cin >> n >> k; string s; cin >> s; sort(s.begin(), s.end()); if (s[0] != s[k - 1]) { cout << s[k - 1] << endl; return; } cout << s[0]; if (s[k] != s[n - 1]) { for (int i = k; i < n; i++) cout << s[i]; } else { for (int i = 0; i < (n - 1) / k; i++) cout << s[n - 1]; } cout << endl; } int main() { int t; cin >> t; while (t--) { solve(); } } ```
### Prompt In Cpp, your task is to solve the following problem: Dreamoon likes strings. Today he created a game about strings: String s_1, s_2, …, s_n is beautiful if and only if for each 1 ≤ i < n, s_i ≠ s_{i+1}. Initially, Dreamoon has a string a. In each step Dreamoon can choose a beautiful substring of a and remove it. Then he should concatenate the remaining characters (in the same order). Dreamoon wants to use the smallest number of steps to make a empty. Please help Dreamoon, and print any sequence of the smallest number of steps to make a empty. Input The first line contains an integer t (1 ≤ t ≤ 200 000), denoting the number of test cases in the input. For each test case, there's one line with a non-empty string of lowercase Latin letters a. The total sum of lengths of strings in all test cases is at most 200 000. Output For each test case, in the first line, you should print m: the smallest number of steps to make a empty. Each of the following m lines should contain two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ |a|), denoting, that the i-th step is removing the characters from index l_i to r_i in the current string. (indices are numbered starting from 1). Note that after the deletion of the substring, indices of remaining characters may change, and r_i should be at most the current length of a. If there are several possible solutions, you can print any. Example Input 4 aabbcc aaabbb aaa abacad Output 3 3 3 2 4 1 2 3 3 4 2 3 1 2 3 1 1 1 1 1 1 1 1 6 ### Response ```cpp #include <bits/stdc++.h> const int N = 1000005; int T, n, s[N], cnum[N], a[N]; char S[N]; inline int Max(const int p, const int q) { return p > q ? p : q; } int main() { scanf("%d", &T); while (T--) { scanf("%s", S + 1), n = strlen(S + 1); register int i, j, k, pos, top = 0, mx = 0, tot = 0; for (i = 0; i < 26; ++i) cnum[i] = 0; for (i = 1; i <= n; ++i) S[i] -= 'a'; for (i = 2; i <= n; ++i) cnum[S[i]] += (S[i] == S[i - 1]), tot += (S[i] == S[i - 1]); for (i = 0; i < 26; ++i) mx = (cnum[i] > mx ? cnum[i] : mx); printf("%d\n", Max(mx, tot + 1 >> 1) + 1); for (i = top = 0, j = 1; j <= n; ++j) { a[++i] = S[j]; if (i == 1 || a[i] != a[i - 1]) continue; if ((!top) || a[i] == a[s[top]]) { s[++top] = i; continue; } for (k = pos = 0; k < 26; ++k) pos = (cnum[k] > cnum[pos] ? k : pos); ((cnum[pos] << 1) < tot || pos == a[i] || pos == a[s[top]]) ? --tot, --cnum[a[i]], --tot, --cnum[a[s[top]]], printf("%d %d\n", s[top], i - 1), a[s[top]] = a[i], i = s[top--] : s[++top] = i; } for (j = i; i; --i) if (i == 1 || a[i] == a[i - 1]) printf("%d %d\n", i, j), j = i - 1; } return 0; } ```
### Prompt Your task is to create a CPP solution to the following problem: You are given an array a of n integers. You want to make all elements of a equal to zero by doing the following operation exactly three times: * Select a segment, for each number in this segment we can add a multiple of len to it, where len is the length of this segment (added integers can be different). It can be proven that it is always possible to make all elements of a equal to zero. Input The first line contains one integer n (1 ≤ n ≤ 100 000): the number of elements of the array. The second line contains n elements of an array a separated by spaces: a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9). Output The output should contain six lines representing three operations. For each operation, print two lines: * The first line contains two integers l, r (1 ≤ l ≤ r ≤ n): the bounds of the selected segment. * The second line contains r-l+1 integers b_l, b_{l+1}, ..., b_r (-10^{18} ≤ b_i ≤ 10^{18}): the numbers to add to a_l, a_{l+1}, …, a_r, respectively; b_i should be divisible by r - l + 1. Example Input 4 1 3 2 4 Output 1 1 -1 3 4 4 2 2 4 -3 -6 -6 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long int n; cin >> n; vector<long long int> a(n + 1); for (long long int i = 1; i <= n; i++) { cin >> a[i]; } if (n == 1) { cout << "1 1\n0\n1 1\n0\n1 1\n" << (-1) * a[1] << "\n"; } else { cout << "1 1\n" << (-1) * a[1] << "\n"; cout << "1 " << n << "\n"; for (long long int i = 1; i <= n; i++) { cout << (i == 1 ? 0 : (-n) * a[i]) << " "; } cout << "\n"; cout << "2 " << n << "\n"; for (long long int i = 2; i <= n; i++) { cout << (n - 1) * a[i] << " "; } cout << "\n"; } return 0; } ```
### Prompt Develop a solution in Cpp to the problem described below: On the Literature lesson Sergei noticed an awful injustice, it seems that some students are asked more often than others. Seating in the class looks like a rectangle, where n rows with m pupils in each. The teacher asks pupils in the following order: at first, she asks all pupils from the first row in the order of their seating, then she continues to ask pupils from the next row. If the teacher asked the last row, then the direction of the poll changes, it means that she asks the previous row. The order of asking the rows looks as follows: the 1-st row, the 2-nd row, ..., the n - 1-st row, the n-th row, the n - 1-st row, ..., the 2-nd row, the 1-st row, the 2-nd row, ... The order of asking of pupils on the same row is always the same: the 1-st pupil, the 2-nd pupil, ..., the m-th pupil. During the lesson the teacher managed to ask exactly k questions from pupils in order described above. Sergei seats on the x-th row, on the y-th place in the row. Sergei decided to prove to the teacher that pupils are asked irregularly, help him count three values: 1. the maximum number of questions a particular pupil is asked, 2. the minimum number of questions a particular pupil is asked, 3. how many times the teacher asked Sergei. If there is only one row in the class, then the teacher always asks children from this row. Input The first and the only line contains five integers n, m, k, x and y (1 ≤ n, m ≤ 100, 1 ≤ k ≤ 1018, 1 ≤ x ≤ n, 1 ≤ y ≤ m). Output Print three integers: 1. the maximum number of questions a particular pupil is asked, 2. the minimum number of questions a particular pupil is asked, 3. how many times the teacher asked Sergei. Examples Input 1 3 8 1 1 Output 3 2 3 Input 4 2 9 4 2 Output 2 1 1 Input 5 5 25 4 3 Output 1 1 1 Input 100 100 1000000000000000000 100 100 Output 101010101010101 50505050505051 50505050505051 Note The order of asking pupils in the first test: 1. the pupil from the first row who seats at the first table, it means it is Sergei; 2. the pupil from the first row who seats at the second table; 3. the pupil from the first row who seats at the third table; 4. the pupil from the first row who seats at the first table, it means it is Sergei; 5. the pupil from the first row who seats at the second table; 6. the pupil from the first row who seats at the third table; 7. the pupil from the first row who seats at the first table, it means it is Sergei; 8. the pupil from the first row who seats at the second table; The order of asking pupils in the second test: 1. the pupil from the first row who seats at the first table; 2. the pupil from the first row who seats at the second table; 3. the pupil from the second row who seats at the first table; 4. the pupil from the second row who seats at the second table; 5. the pupil from the third row who seats at the first table; 6. the pupil from the third row who seats at the second table; 7. the pupil from the fourth row who seats at the first table; 8. the pupil from the fourth row who seats at the second table, it means it is Sergei; 9. the pupil from the third row who seats at the first table; ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long max(long long x, long long y) { if (x > y) return x; return y; } long long min(long long x, long long y) { if (x < y) return x; return y; } long long n, m, k, x, y; long long a[101][101] = {0}; int main() { ios::sync_with_stdio(false); cin >> n >> m >> k >> x >> y; long long cycle_length; if (n < 2) cycle_length = m * n; else cycle_length = 2 * m * (n - 1); long long cycles = k / cycle_length; long long k1 = k - (max(0, cycles)) * cycle_length; for (long long i = 1; i <= n && k1 > 0; i++) for (long long j = 1; j <= m && k1 > 0; j++) { k1--; a[i][j]++; } for (long long i = n - 1; i >= 1 && k1 > 0; i--) for (long long j = 1; j <= m && k1 > 0; j++) { k1--; a[i][j]++; } long long minel = (long long)(1e9), maxel1 = 0, maxel2 = 0; for (long long j = 1; j <= m; j++) { minel = min(minel, min(a[1][j], a[n][j])); maxel2 = max(maxel2, max(a[1][j], a[n][j])); } if (n > 2) for (long long i = 2; i <= n - 1; i++) for (long long j = 1; j <= m; j++) maxel1 = max(maxel1, a[i][j]); else for (long long i = 1; i <= n; i++) for (long long j = 1; j <= m; j++) maxel1 = max(maxel1, a[i][j]); long long max_ask, min_ask, ask_me; min_ask = minel + cycles; ask_me = a[x][y] + cycles; if (n <= 2) max_ask = maxel2 + cycles; else max_ask = max(maxel2 + cycles, maxel1 + 2 * cycles); if (x != 1 && x != n) ask_me += cycles; cout << max_ask << " " << min_ask << " " << ask_me << endl; return 0; } ```
### Prompt In CPP, your task is to solve the following problem: Today the kindergarten has a new group of n kids who need to be seated at the dinner table. The chairs at the table are numbered from 1 to 4n. Two kids can't sit on the same chair. It is known that two kids who sit on chairs with numbers a and b (a ≠ b) will indulge if: 1. gcd(a, b) = 1 or, 2. a divides b or b divides a. gcd(a, b) — the maximum number x such that a is divisible by x and b is divisible by x. For example, if n=3 and the kids sit on chairs with numbers 2, 3, 4, then they will indulge since 4 is divided by 2 and gcd(2, 3) = 1. If kids sit on chairs with numbers 4, 6, 10, then they will not indulge. The teacher really doesn't want the mess at the table, so she wants to seat the kids so there are no 2 of the kid that can indulge. More formally, she wants no pair of chairs a and b that the kids occupy to fulfill the condition above. Since the teacher is very busy with the entertainment of the kids, she asked you to solve this problem. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. Each test case consists of one line containing an integer n (1 ≤ n ≤ 100) — the number of kids. Output Output t lines, which contain n distinct integers from 1 to 4n — the numbers of chairs that the kids should occupy in the corresponding test case. If there are multiple answers, print any of them. You can print n numbers in any order. Example Input 3 2 3 4 Output 6 4 4 6 10 14 10 12 8 ### Response ```cpp #include <bits/stdc++.h> #pragma GCC optimize("O3") using namespace std; using vi = vector<long long>; using ii = pair<long long, long long>; using vii = vector<ii>; constexpr long long INF = 1e18; constexpr long long MIN_INF = -1e18; ; int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ; long long t; cin >> t; while (t--) { long long n; cin >> n; long long a = 4 * n; for (long long i = 0; i < n; i++) { cout << a << " "; a -= 2; } cout << "\n"; } return 0; } ```
### Prompt Please create a solution in CPP to the following problem: Taro is planning a long trip by train during the summer vacation. However, in order for Taro, who is a high school student, to travel as far as possible during the summer vacation, which has only one month, he cannot make a good plan unless he finds the cheapest and the fastest way. Let's create a program to help Taro's plan so that he can enjoy a wonderful trip. <image> Create a program that outputs the minimum amount or the shortest time in response to inquiries by inputting track information and the number of stations. Input A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format: n m a1 b1 cost1 time1 a2 b2 cost2 time2 :: an bn costn timen k p1 q1 r1 p2 q2 r2 :: pk qk rk The first line gives the number of track information n (1 ≤ n ≤ 3000) and the number of stations m (1 ≤ m ≤ 100). The following n lines give information on the i-th line. As information on each line, the numbers ai, bi (1 ≤ ai, bi ≤ m) of the two stations connecting the lines, the toll costi (1 ≤ costi ≤ 1000), and the travel time timei (1 ≤ timei ≤ 1000) are given. I will. However, each station shall be numbered in order from 1 to m. If ai and bi are connected by railroad tracks, both ai to bi and bi to ai can be moved at the same rate and time. The following line is given the number of queries k (1 ≤ k ≤ 200). The next k line is given the i-th query. For each query, the departure station pi, the arrival station qi, and the type of value to output ri (0 or 1) are given. Inquiries must have a route. The number of datasets does not exceed 50. Output Outputs the minimum amount or minimum time on one line for each data set. When ri is 0, the minimum amount is output, and when ri is 1, the minimum time is output. Example Input 6 5 1 2 200 10 1 4 400 15 1 3 250 25 2 4 100 10 4 5 150 20 3 5 300 20 2 1 5 0 1 5 1 0 0 Output 450 35 ### Response ```cpp // 2013/11/25 Tazoe #include <iostream> #include <algorithm> using namespace std; const int INF = 1000000000; int main() { while(true){ int n, m; cin >> n >> m; if(n==0&&m==0) break; int C[100][100]; int T[100][100]; for(int i=0; i<m; i++){ for(int j=0; j<m; j++){ if(i==j){ C[i][j] = T[i][j] = 0; } else{ C[i][j] = T[i][j] = INF; } } } for(int i=0; i<n; i++){ int a, b, c, t; cin >> a >> b >> c >> t; C[a-1][b-1] = C[b-1][a-1] = c; T[a-1][b-1] = T[b-1][a-1] = t; } for(int k=0; k<m; k++){ for(int i=0; i<m; i++){ for(int j=0; j<m; j++){ C[i][j] = min(C[i][j], C[i][k]+C[k][j]); T[i][j] = min(T[i][j], T[i][k]+T[k][j]); } } } int k; cin >> k; for(int i=0; i<k; i++){ int p, q, r; cin >> p >> q >> r; if(r==0){ cout << C[p-1][q-1] << endl; } else{ cout << T[p-1][q-1] << endl; } } } return 0; } ```
### Prompt In Cpp, your task is to solve the following problem: Igor likes hexadecimal notation and considers positive integer in the hexadecimal notation interesting if each digit and each letter in it appears no more than t times. For example, if t = 3, then integers 13a13322, aaa, abcdef0123456789 are interesting, but numbers aaaa, abababab and 1000000 are not interesting. Your task is to find the k-th smallest interesting for Igor integer in the hexadecimal notation. The integer should not contain leading zeros. Input The first line contains the two integers k and t (1 ≤ k ≤ 2·109, 1 ≤ t ≤ 10) — the number of the required integer and the maximum number of times some integer or letter can appear in interesting integer. It can be shown that the answer always exists for such constraints. Output Print in the hexadecimal notation the only integer that is the k-th smallest interesting integer for Igor. Examples Input 17 1 Output 12 Input 1000000 2 Output fca2c Note The first 20 interesting integers if t = 1: 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f, 10, 12, 13, 14, 15. So the answer for the first example equals 12. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int64_t comb[100][100]; string hx = "0123456789abcdef"; string toHex(int64_t n) { string res; while (n > 0) { res += hx[n % 16]; n /= 16; } reverse(res.begin(), res.end()); return res; } vector<int> counter(int64_t n) { vector<int> cnt(16); while (n > 0) { cnt[n % 16]++; n /= 16; } return cnt; } int main() { int n, t; cin >> n >> t; for (int i = 0; i < 100; i++) { for (int j = 0; j <= i; j++) { if (i == j || j == 0) { comb[i][j] = 1; } else { comb[i][j] = comb[i - 1][j] + comb[i - 1][j - 1]; } } } if (t == 1) { for (int i = 1;; i++) { int64_t P = 15; for (int j = 1; j < i; j++) { P *= 16 - j; } if (n > P) { n -= P; } else { string ans; P /= 15; int fst = 1; string ls = "0123456789abcdef"; while (n > P) { fst++; n -= P; } ans += ls[fst]; ls.erase(fst, 1); for (int j = 1; j < i; j++) { P /= 16 - j; int snd = 0; while (n > P) { snd++; n -= P; } ans += ls[snd]; ls.erase(snd, 1); } cout << ans << endl; return 0; } } } else { for (int i = 1; i < 16 * 16 * 16 * 16; i++) { auto cnt = counter(i); if (*max_element(cnt.begin(), cnt.end()) <= t) { n--; if (n == 0) { cout << toHex(i) << endl; return 0; } } } for (int64_t pre = 1;; pre++) { static int64_t dp0[5]; static int64_t dp1[5]; memset(dp0, 0, sizeof(dp0)); vector<int> cnt = counter(pre); if (*max_element(cnt.begin(), cnt.end()) > t) { continue; } dp0[0] = 1; for (int i = 0; i < 16; i++) { memcpy(dp1, dp0, sizeof(dp1)); for (int j = 0; j < 4; j++) { for (int k = 1; k + cnt[i] <= t && j + k <= 4; k++) { dp1[j + k] += dp0[j] * comb[j + k][j]; dp1[j + k] = min(dp1[j + k], (int64_t)1e10); } } swap(dp0, dp1); } if (n > dp0[4]) { n -= dp0[4]; } else { for (int i = 0; i < 16 * 16 * 16 * 16; i++) { auto cnt = counter((pre << 16) + i); if (*max_element(cnt.begin(), cnt.end()) <= t) { n--; if (n == 0) { cout << toHex((pre << 16) + i) << endl; return 0; } } } } } } } ```
### Prompt Your challenge is to write a Cpp solution to the following problem: In this problem, a n × m rectangular matrix a is called increasing if, for each row of i, when go from left to right, the values strictly increase (that is, a_{i,1}<a_{i,2}<...<a_{i,m}) and for each column j, when go from top to bottom, the values strictly increase (that is, a_{1,j}<a_{2,j}<...<a_{n,j}). In a given matrix of non-negative integers, it is necessary to replace each value of 0 with some positive integer so that the resulting matrix is increasing and the sum of its elements is maximum, or find that it is impossible. It is guaranteed that in a given value matrix all values of 0 are contained only in internal cells (that is, not in the first or last row and not in the first or last column). Input The first line contains integers n and m (3 ≤ n, m ≤ 500) — the number of rows and columns in the given matrix a. The following lines contain m each of non-negative integers — the values in the corresponding row of the given matrix: a_{i,1}, a_{i,2}, ..., a_{i,m} (0 ≤ a_{i,j} ≤ 8000). It is guaranteed that for all a_{i,j}=0, 1 < i < n and 1 < j < m are true. Output If it is possible to replace all zeros with positive numbers so that the matrix is increasing, print the maximum possible sum of matrix elements. Otherwise, print -1. Examples Input 4 5 1 3 5 6 7 3 0 7 0 9 5 0 0 0 10 8 9 10 11 12 Output 144 Input 3 3 1 2 3 2 0 4 4 5 6 Output 30 Input 3 3 1 2 3 3 0 4 4 5 6 Output -1 Input 3 3 1 2 3 2 3 4 3 4 2 Output -1 Note In the first example, the resulting matrix is as follows: 1 3 5 6 7 3 6 7 8 9 5 7 8 9 10 8 9 10 11 12 In the second example, the value 3 must be put in the middle cell. In the third example, the desired resultant matrix does not exist. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, m, vis[505][505], sum; int main() { memset(vis, 8001, sizeof(vis)); scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) scanf("%d", &vis[i][j]); for (int i = n; i; i--) for (int j = m; j; j--) { if (vis[i][j] == 0) vis[i][j] = min(vis[i + 1][j], vis[i][j + 1]) - 1; } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { if (vis[i][j] >= min(vis[i + 1][j], vis[i][j + 1])) { puts("-1"); return 0; } else sum += vis[i][j]; } printf("%d\n", sum); return 0; } ```
### Prompt Generate a cpp solution to the following problem: A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon. A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, the line of performers can be represented by a sequence a1, a2, ..., an. Little Tommy is among them. He would like to choose an interval [l, r] (1 ≤ l ≤ r ≤ n), then reverse al, al + 1, ..., ar so that the length of the longest non-decreasing subsequence of the new sequence is maximum. A non-decreasing subsequence is a sequence of indices p1, p2, ..., pk, such that p1 < p2 < ... < pk and ap1 ≤ ap2 ≤ ... ≤ apk. The length of the subsequence is k. Input The first line contains an integer n (1 ≤ n ≤ 2000), denoting the length of the original sequence. The second line contains n space-separated integers, describing the original sequence a1, a2, ..., an (1 ≤ ai ≤ 2, i = 1, 2, ..., n). Output Print a single integer, which means the maximum possible length of the longest non-decreasing subsequence of the new sequence. Examples Input 4 1 2 1 2 Output 4 Input 10 1 1 2 2 2 1 1 2 2 1 Output 9 Note In the first example, after reversing [2, 3], the array will become [1, 1, 2, 2], where the length of the longest non-decreasing subsequence is 4. In the second example, after reversing [3, 7], the array will become [1, 1, 1, 1, 2, 2, 2, 2, 2, 1], where the length of the longest non-decreasing subsequence is 9. ### Response ```cpp #include <bits/stdc++.h> #pragma optimize GCC("Ofast") #pragma comment(linker, "/STACK:1073741824") using namespace std; using namespace placeholders; const int inf = (int)1e9 + 9; const long long linf = (long long)1e18; const long double eps = 1e-7; const int mod = (int)1e9 + 7; int main() { ios_base::sync_with_stdio(false); srand(time(0)); cin.tie(0); cout.tie(0); int n; cin >> n; vector<int> seq(n); for (int i = 0; i < n; i++) { cin >> seq[i]; } vector<int> cnt1(n + 1), cnt2(n + 1); for (int i = 1; i <= n; i++) { cnt1[i] = cnt1[i - 1]; if (seq[i - 1] == 1) { cnt1[i]++; } } for (int i = n - 1; i >= 0; i--) { cnt2[i] = cnt2[i + 1]; if (seq[i] == 2) { cnt2[i]++; } } vector<vector<int> > dp(n + 2, vector<int>(n + 1, 0)); for (int i = 1; i <= n; i++) { dp[i][i] = 1; for (int j = i + 1; j <= n; j++) { if (seq[j - 1] == 1) { dp[i][j] = max(dp[i][j - 1], cnt1[j] - cnt1[i - 1]); } else { dp[i][j] = dp[i][j - 1] + 1; } } } vector<vector<int> > dp_rev(n + 2, vector<int>(n + 1, 0)); vector<int> seq_rev(n); for (int i = 0; i < n; i++) { seq_rev[i] = 3 - seq[i]; } for (int i = 1; i <= n; i++) { dp_rev[i][i] = 1; for (int j = i + 1; j <= n; j++) { if (seq_rev[j - 1] == 1) { dp_rev[i][j] = max(dp_rev[i][j - 1], j - i + 1 - (cnt1[j] - cnt1[i - 1])); } else { dp_rev[i][j] = dp_rev[i][j - 1] + 1; } } } int res = 0; for (int i = 1; i <= n; i++) { int one = 0, two = 0; for (int j = i; j <= n; j++) { if (seq[j - 1] == 1) { one++; } else { two++; } res = max(res, dp[1][i - 1] + cnt2[j] + one); res = max(res, dp_rev[i][j] + cnt1[i - 1] + cnt2[j]); res = max(res, cnt1[i - 1] + two + dp[j + 1][n]); } } cout << res; } ```
### Prompt In CPP, your task is to solve the following problem: Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items? Input The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo. Output Print the only number — the minimum number of times Polycarpus has to visit the closet. Examples Input CPCPCPC Output 7 Input CCCCCCPPPPPP Output 4 Input CCCCCCPPCPPPPPPPPPP Output 6 Input CCCCCCCCCC Output 2 Note In the first sample Polycarpus needs to take one item to the closet 7 times. In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice. In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice. In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go). ### Response ```cpp #include <bits/stdc++.h> using namespace std; const double eps = 1e-11; const double Pi = acos(-1.0); template <class T> inline T countbit(T n) { return n ? 1 + countbit(n & (n - 1)) : 0; } template <class T> inline T sqr(T a) { return a * a; } template <class T> inline void checkmin(T &a, T b) { if (a == -1 || a > b) a = b; } template <class T> inline void checkmax(T &a, T b) { if (a < b) a = b; } int dx[] = {-1, 0, 1, 0}; int dy[] = {0, 1, 0, -1}; int main() { string s; cin >> s; int ans = 1, now = 1; for (int i = 1; i < s.size(); i++) { if (s[i] != s[i - 1] || now == 5) { ans++; now = 1; } else now++; } cout << ans << endl; return 0; } ```
### Prompt Your challenge is to write a cpp solution to the following problem: We have a string S consisting of uppercase English letters. Additionally, an integer N will be given. Shift each character of S by N in alphabetical order (see below), and print the resulting string. We assume that `A` follows `Z`. For example, shifting `A` by 2 results in `C` (`A` \to `B` \to `C`), and shifting `Y` by 3 results in `B` (`Y` \to `Z` \to `A` \to `B`). Constraints * 0 \leq N \leq 26 * 1 \leq |S| \leq 10^4 * S consists of uppercase English letters. Input Input is given from Standard Input in the following format: N S Output Print the string resulting from shifting each character of S by N in alphabetical order. Examples Input 2 ABCXYZ Output CDEZAB Input 0 ABCXYZ Output ABCXYZ Input 13 ABCDEFGHIJKLMNOPQRSTUVWXYZ Output NOPQRSTUVWXYZABCDEFGHIJKLM ### Response ```cpp #include<bits/stdc++.h> int main(){int n,i=0;char s[10002];std::cin>>n>>s;for(;i<strlen(s);i++)s[i]=(s[i]-65+n)%26+65;puts(s);} ```
### Prompt Develop a solution in Cpp to the problem described below: Taro, who aims to become a web designer, is currently training. My senior at the office tells me that the background color of this page is # ffe085, which is a color number peculiar to web design, but I can't think of what kind of color it is. This color number represents the intensity of each of the three primary colors of light, red, green, and blue. Specifically, it is a combination of three 2-digit hexadecimal numbers, and when the color number is “#RGB”, R is the intensity of red, G is the intensity of green, and is the intensity of blue. .. Each value is from 00 to ff. For Taro who is not familiar with color numbers, please create a program that inputs the color number and outputs the name of the closest color from the color table. The table of colors used is as follows. | Color name | Red intensity | Green intensity | Blue intensity --- | --- | --- | --- | --- | black | 00 | 00 | 00 | blue | 00 | 00 | ff | lime | 00 | ff | 00 aqua | 00 | ff | ff | red | ff | 00 | 00 | fuchsia | ff | 00 | ff | yellow | ff | ff | 00 | white | ff | ff | ff The "closest color" is defined as follows. When the intensities of red, green, and blue at a given color number are R, G, and B, respectively, and the intensities of red, green, and blue of the kth color in the table are Rk, Gk, and Bk, respectively. The color with the smallest dk value calculated by the following formula is the closest color. <image> If there are multiple colors with the same dk value, the color at the top of the table will be the closest color. Input A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. For each dataset, a string representing the color number is given on one line in #RGB format. The number of datasets does not exceed 1000. Output Outputs the name of the closest color for each dataset on one line. Examples Input #ffe085 #787878 #decade #ff55ff 0 Output white black white fuchsia Input ffe085 787878 decade ff55ff 0 Output white black white fuchsia ### Response ```cpp #include<bits/stdc++.h> using namespace std; int hext(string a){ int c,d; if(a[0]>='0'&&a[0]<='9')c=a[0]-'0'; else c=a[0]-'a'+10; if(a[1]>='0'&&a[1]<='9')d=a[1]-'0'; else d=a[1]-'a'+10; return c*16+d; } int main(){ string s; while(cin>>s&&s!="0"){ int r,g,b; r=hext(s.substr(1,2)); g=hext(s.substr(3,2)); b=hext(s.substr(5,2)); string ans; int d=1e9; if(d>((r*r)+(g*g)+(b*b)))ans="black",d=((r*r)+(g*g)+(b*b)); if(d>((r*r)+(g*g)+((b-255)*(b-255))))ans="blue",d=((r*r)+(g*g)+((b-255)*(b-255))); if(d>((r*r)+((g-255)*(g-255))+(b*b)))ans="lime",d=((r*r)+((g-255)*(g-255))+(b*b)); if(d>((r*r)+((g-255)*(g-255))+((b-255)*(b-255))))ans="aqua",d=((r*r)+((g-255)*(g-255))+((b-255)*(b-255))); if(d>((r-255)*(r-255))+(g*g)+(b*b))ans="red",d=((r-255)*(r-255))+(g*g)+(b*b); if(d>((r-255)*(r-255))+(g*g)+((b-255)*(b-255)))ans="fuchsia",d=((r-255)*(r-255))+(g*g)+((b-255)*(b-255)); if(d>((r-255)*(r-255))+((g-255)*(g-255))+(b*b))ans="yellow",d=((r-255)*(r-255))+((g-255)*(g-255))+(b*b); if(d>((r-255)*(r-255))+((g-255)*(g-255))+(b-255)*(b-255))ans="white"; cout<<ans<<endl; } return 0; } ```
### Prompt Generate a CPP solution to the following problem: problem President K decided to make a flag for IOI 2016 in Russia. Chairman K first took out the old flag from the warehouse. This flag is divided into squares of N rows and M columns, and each square is painted in one of white, blue, and red. Chairman K is trying to repaint some of the squares on this flag to make it the Russian flag. However, the Russian flag in this problem is as follows. * Several lines (one or more lines) from the top are all painted in white. * The next few lines (one or more lines) are all painted in blue. * All the cells in the other lines (one or more lines) are painted in red. Find the minimum number of squares that President K needs to repaint to turn the old flag into a Russian flag. input The input consists of 1 + N lines. On the first line, two integers N and M (3 ≤ N ≤ 50, 3 ≤ M ≤ 50) are written separated by a blank. This means that the flags are separated by N rows and M columns. The following N lines each contain a string of M characters, which represents the color information painted in the squares of the old flag. The jth character (1 ≤ i ≤ N, 1 ≤ j ≤ M) on the i-th line of the N-line represents the color of the cell on the i-th line and j-th column of the old flag. It is either B'or'R'. 'W' stands for white,'B' stands for blue, and'R' stands for red. output Output in one line the minimum number of squares that President K needs to repaint to turn the old flag into a Russian flag. Input / output example Input example 1 4 5 WRWRW BWRWB WRWRW RWBWR Output example 1 11 Input example 2 6 14 WWWWWWWWWWWWWW WBBBWWRRWWBBBW WWBWWRRRRWWBWW BWBWWRRRRWWBWW WBBWWWRRWWBBBW WWWWWWWWWWWWWW Output example 2 44 In I / O example 1, the old flag is colored as shown in the figure below. fig01 In the figure below, repaint the 11 squares with an'X'. fig02 This makes it possible to make the Russian flag as shown in the figure below. fig03 Since it is not possible to make a Russian flag by repainting less than 11 squares, 11 is output. In I / O example 2, the old flag is colored as shown in the figure below. fig04 Creative Commons License Information Olympics Japan Committee work "15th Japan Information Olympics JOI 2015/2016 Qualifying Competition Tasks" Example Input 4 5 WRWRW BWRWB WRWRW RWBWR Output 11 ### Response ```cpp #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> P; int n,m; char flag[55][55]; int cnt(int a, int b, int c){ int ret = 0; for (int i = 0;i < n;i++){ for (int j = 0;j < m;j++){ if(i < a){ if(flag[i][j] != 'W') ret++;} else if(i < b){ if( flag[i][j] != 'B') ret++;} else if(i < c){ if( flag[i][j] != 'R') ret++;} } } return ret; } int main() { cin.tie(0); ios::sync_with_stdio(false); cin >> n >> m; for (int i = 0;i < n;i++){ for (int j = 0;j < m;j++){ cin >> flag[i][j]; } } int ans = INT_MAX; for (int i = 1;i < n;i++){ for (int j = 1;j < n-i;j++){ ans = min(ans,cnt(i,i+j,n)); } } cout << ans << endl; return 0; } ```
### Prompt In Cpp, your task is to solve the following problem: Yaroslav calls an array of r integers a1, a2, ..., ar good, if it meets the following conditions: |a1 - a2| = 1, |a2 - a3| = 1, ..., |ar - 1 - ar| = 1, |ar - a1| = 1, at that <image>. An array of integers b1, b2, ..., br is called great, if it meets the following conditions: 1. The elements in it do not decrease (bi ≤ bi + 1). 2. If the inequalities 1 ≤ r ≤ n and 1 ≤ bi ≤ m hold. 3. If we can rearrange its elements and get at least one and at most k distinct good arrays. Yaroslav has three integers n, m, k. He needs to count the number of distinct great arrays. Help Yaroslav! As the answer may be rather large, print the remainder after dividing it by 1000000007 (109 + 7). Two arrays are considered distinct if there is a position in which they have distinct numbers. Input The single line contains three integers n, m, k (1 ≤ n, m, k ≤ 100). Output In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7). Examples Input 1 1 1 Output 0 Input 3 3 3 Output 2 ### Response ```cpp #include <bits/stdc++.h> const int md = 1000000007; void add(int& a, int b) { a += b; if (a >= md) a -= md; } int dp[55][111][55][111]; int C[222][222]; const int INF = 1 << 20; int main() { int n, m, k; scanf("%d%d%d", &n, &m, &k); for (int i = 0; i < 222; i++) { C[i][0] = 1; for (int j = 1; j <= i; j++) { C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; if (C[i][j] >= INF) C[i][j] = INF; } } int ans = 0; for (int i = 1; 2 * i <= n; i++) { for (int j = 2; j <= m; j++) { for (int ls = 1; ls <= i; ls++) { int bef = i - ls; if (bef == 0) dp[i][j][ls][1] = 1; else { for (int z = 1; z <= k; z++) { for (int pre = 1; pre <= bef; pre++) { int val = dp[bef][j - 1][pre][z]; int nz = C[ls + pre - 1][pre - 1] * z; if (nz > k) break; if (val == 0) continue; add(dp[i][j][ls][nz], val); } } } for (int z = 1; z <= k; z++) { add(ans, dp[i][j][ls][z]); } } } } printf("%d\n", ans); } ```
### Prompt Your task is to create a Cpp solution to the following problem: We have N sticks with negligible thickness. The length of the i-th stick is A_i. Snuke wants to select four different sticks from these sticks and form a rectangle (including a square), using the sticks as its sides. Find the maximum possible area of the rectangle. Constraints * 4 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * A_i is an integer. Input Input is given from Standard Input in the following format: N A_1 A_2 ... A_N Output Print the maximum possible area of the rectangle. If no rectangle can be formed, print 0. Examples Input 6 3 1 2 4 2 1 Output 2 Input 4 1 2 3 4 Output 0 Input 10 3 3 3 3 4 4 4 5 5 5 Output 20 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { for(int n;cin>>n&&n;){ vector<int> a(n); for(int& x:a) cin>>x; map<int,int> f; for(int x:a) f[x]++; vector<int> edges; for(int i=0;i<2;i++){ int edge=0; for(auto p:f) if(p.second>=2) edge=p.first; edges.push_back(edge); f[edge]-=2; } cout<<(long long)edges[0]*edges[1]<<endl; } } ```
### Prompt Construct a cpp code solution to the problem outlined: Misha walked through the snowy forest and he was so fascinated by the trees to decide to draw his own tree! Misha would like to construct a rooted tree with n vertices, indexed from 1 to n, where the root has index 1. Every other vertex has a parent p_i, and i is called a child of vertex p_i. Vertex u belongs to the subtree of vertex v iff v is reachable from u while iterating over the parents (u, p_{u}, p_{p_{u}}, ...). Clearly, v belongs to its own subtree, and the number of vertices in the subtree is called the size of the subtree. Misha is only interested in trees where every vertex belongs to the subtree of vertex 1. Below there is a tree with 6 vertices. The subtree of vertex 2 contains vertices 2, 3, 4, 5. Hence the size of its subtree is 4. <image> The branching coefficient of the tree is defined as the maximum number of children in any vertex. For example, for the tree above the branching coefficient equals 2. Your task is to construct a tree with n vertices such that the sum of the subtree sizes for all vertices equals s, and the branching coefficient is minimum possible. Input The only input line contains two integers n and s — the number of vertices in the tree and the desired sum of the subtree sizes (2 ≤ n ≤ 10^5; 1 ≤ s ≤ 10^{10}). Output If the required tree does not exist, output «No». Otherwise output «Yes» on the first line, and in the next one output integers p_2, p_3, ..., p_n, where p_i denotes the parent of vertex i. Examples Input 3 5 Output Yes 1 1 Input 4 42 Output No Input 6 15 Output Yes 1 2 3 1 5 Note Below one can find one of the possible solutions for the first sample case. The sum of subtree sizes equals 3 + 1 + 1 = 5, and the branching coefficient equals 2. <image> Below one can find one of the possible solutions for the third sample case. The sum of subtree sizes equals 6 + 3 + 2 + 1 + 2 + 1 = 15, and the branching coefficient equals 2. <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <class T> int getbit(T s, int i) { return (s >> i) & 1; } template <class T> T onbit(T s, int i) { return s | (T(1) << i); } template <class T> T offbit(T s, int i) { return s & (~(T(1) << i)); } template <class T> int cntbit(T s) { return __builtin_popcount(s); } template <class T> T gcd(T a, T b) { T r; while (b != 0) { r = a % b; a = b; b = r; } return a; } template <class T> T lcm(T a, T b) { return a / gcd(a, b) * b; } long long n, s; vector<int> V[300005]; int dad[300005]; long long TT(long long x) { return x * (x + 1) / 2; } long long tinh_max(long long d) { long long have = n; long long val = 1, res = 0; for (long long i = 1;; i++) { if (!have) break; long long A = min(val, have); have -= A; res += A * i; val *= d; } return res; } void cal(long long d) { long long have = n - 1; s -= (n); long long val = d; V[1].push_back(1); for (long long dep = 2;; dep++) { if (have == 0) break; int cur = 0; for (int i = n - have + 1; i <= n && i <= n - have + val; i++) { if (TT(n - i + 1) >= s) { V[dep].push_back(i); dad[i] = V[dep - 1][cur]; cur++; if (cur >= ((int)(V[dep - 1]).size())) cur = 0; s--; } } have -= ((int)(V[dep]).size()); s -= have; val = ((int)(V[dep]).size()) * d; } } void solve() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n >> s; if (s > (n * (n + 1)) / 2 || s < n + n - 1) { cout << "No" << endl; return; } cout << "Yes" << endl; for (int i = (1); i <= (n); ++i) if (tinh_max(i) <= s) { cal(i); for (int i = (2); i <= (n); ++i) { cout << dad[i]; if (i == n) cout << endl; else cout << " "; } return; } } int main() { solve(); return 0; } ```
### Prompt Please provide a cpp coded solution to the problem described below: You have c_1 letters 'a', c_2 letters 'b', ..., c_{26} letters 'z'. You want to build a beautiful string of length n from them (obviously, you cannot use the i-th letter more than c_i times). Each c_i is greater than n/3. A string is called beautiful if there are no palindromic contiguous substrings of odd length greater than 1 in it. For example, the string "abacaba" is not beautiful, it has several palindromic substrings of odd length greater than 1 (for example, "aca"). Another example: the string "abcaa" is beautiful. Calculate the number of different strings you can build, and print the answer modulo 998244353. Input The first line contains one integer n (3 ≤ n ≤ 400). The second line contains 26 integers c_1, c_2, ..., c_{26} (n/3 < c_i ≤ n). Output Print one integer — the number of strings you can build, taken modulo 998244353. Examples Input 4 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 Output 422500 Input 3 2 2 2 2 2 2 3 3 3 2 2 2 2 2 2 3 3 3 2 2 3 2 2 3 2 2 Output 16900 Input 400 348 322 247 158 209 134 151 267 268 176 214 379 372 291 388 135 147 304 169 149 193 351 380 368 181 340 Output 287489790 ### Response ```cpp #pragma GCC optimize(3) #pragma GCC target("avx") #pragma GCC optimize("Ofast") #pragma GCC optimize("inline") #pragma GCC optimize("-fgcse") #pragma GCC optimize("-fgcse-lm") #pragma GCC optimize("-fipa-sra") #pragma GCC optimize("-ftree-pre") #pragma GCC optimize("-ftree-vrp") #pragma GCC optimize("-fpeephole2") #pragma GCC optimize("-ffast-math") #pragma GCC optimize("-fsched-spec") #pragma GCC optimize("unroll-loops") #pragma GCC optimize("-falign-jumps") #pragma GCC optimize("-falign-loops") #pragma GCC optimize("-falign-labels") #pragma GCC optimize("-fdevirtualize") #pragma GCC optimize("-fcaller-saves") #pragma GCC optimize("-fcrossjumping") #pragma GCC optimize("-fthread-jumps") #pragma GCC optimize("-funroll-loops") #pragma GCC optimize("-fwhole-program") #pragma GCC optimize("-freorder-blocks") #pragma GCC optimize("-fschedule-insns") #pragma GCC optimize("inline-functions") #pragma GCC optimize("-ftree-tail-merge") #pragma GCC optimize("-fschedule-insns2") #pragma GCC optimize("-fstrict-aliasing") #pragma GCC optimize("-fstrict-overflow") #pragma GCC optimize("-falign-functions") #pragma GCC optimize("-fcse-skip-blocks") #pragma GCC optimize("-fcse-follow-jumps") #pragma GCC optimize("-fsched-interblock") #pragma GCC optimize("-fpartial-inlining") #pragma GCC optimize("no-stack-protector") #pragma GCC optimize("-freorder-functions") #pragma GCC optimize("-findirect-inlining") #pragma GCC optimize("-fhoist-adjacent-loads") #pragma GCC optimize("-frerun-cse-after-loop") #pragma GCC optimize("inline-small-functions") #pragma GCC optimize("-finline-small-functions") #pragma GCC optimize("-ftree-switch-conversion") #pragma GCC optimize("-foptimize-sibling-calls") #pragma GCC optimize("-fexpensive-optimizations") #pragma GCC optimize("-funsafe-loop-optimizations") #pragma GCC optimize("inline-functions-called-once") #pragma GCC optimize("-fdelete-null-pointer-checks") #include<iostream> #include<cstring> #include<cstdio> #include<climits> #include<algorithm> #include<queue> #include<vector> #define pii pair<int,int> #define mp make_pair #define pb push_back #define fi first #define se second #define int long long #define mod 998244353 using namespace std; inline int read(){ int f=1,ans=0; char c=getchar(); while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();} while(c>='0'&&c<='9'){ans=ans*10+c-'0';c=getchar();} return f*ans; } const int MAXN=411; int f[2][MAXN][MAXN][3][3],N,A[27],g[MAXN][MAXN]; signed main(){ //freopen("6.in","r",stdin); N=read(); for(int i=1;i<=26;i++) A[i]=read(); int cur=0; f[cur][0][0][0][0]=24*24; f[cur][1][0][0][1]=f[cur][1][0][1][0]=f[cur][0][1][2][0]=f[cur][0][1][0][2]=24; f[cur][1][1][1][2]=f[cur][1][1][2][1]=1; f[cur][2][0][1][1]=f[cur][0][2][2][2]=1; for(int i=2;i<N;i++){ memset(f[cur^1],0,sizeof(f[cur^1])),cur^=1; for(int j=0;j<=N;j++) for(int k=0;k<=N;k++){ if(i&1){ for(int p=0;p<=2;p++){ f[cur][j][k][p][0]+=23*f[cur^1][j][k][p][0]; f[cur][j][k][p][0]%=mod; f[cur][j+1][k][p][1]+=f[cur^1][j][k][p][0]; f[cur][j+1][k][p][1]%=mod; f[cur][j][k+1][p][2]+=f[cur^1][j][k][p][0]; f[cur][j][k+1][p][2]%=mod; f[cur][j][k][p][0]+=24*f[cur^1][j][k][p][1]; f[cur][j][k][p][0]%=mod; f[cur][j][k+1][p][2]+=f[cur^1][j][k][p][1]; f[cur][j][k+1][p][2]%=mod; f[cur][j][k][p][0]+=24*f[cur^1][j][k][p][2]; f[cur][j][k][p][0]%=mod; f[cur][j+1][k][p][1]+=f[cur^1][j][k][p][2]; f[cur][j+1][k][p][1]%=mod; } }else{ for(int p=0;p<=2;p++){ f[cur][j][k][0][p]+=23*f[cur^1][j][k][0][p]; f[cur][j][k][0][p]%=mod; f[cur][j+1][k][1][p]+=f[cur^1][j][k][0][p]; f[cur][j+1][k][1][p]%=mod; f[cur][j][k+1][2][p]+=f[cur^1][j][k][0][p]; f[cur][j][k+1][2][p]%=mod; f[cur][j][k][0][p]+=24*f[cur^1][j][k][1][p]; f[cur][j][k][0][p]%=mod; f[cur][j][k+1][2][p]+=f[cur^1][j][k][1][p]; f[cur][j][k+1][2][p]%=mod; f[cur][j][k][0][p]+=24*f[cur^1][j][k][2][p]; f[cur][j][k][0][p]%=mod; f[cur][j+1][k][1][p]+=f[cur^1][j][k][2][p]; f[cur][j+1][k][1][p]%=mod; } } } } for(int i=0;i<=N;i++) for(int j=0;j<=N;j++) for(int p1=0;p1<=2;p1++) for(int p2=0;p2<=2;p2++) g[i][j]+=f[cur][i][j][p1][p2],g[i][j]%=mod; for(int i=N;i>=0;i--) for(int j=N;j>=0;j--) g[i][j]+=g[i+1][j]+g[i][j+1]-g[i+1][j+1],g[i][j]=((g[i][j]%mod)+mod)%mod; int Ans=g[0][0]; for(int i=1;i<=26;i++) Ans-=g[A[i]+1][0],Ans=((Ans%mod)+mod)%mod; for(int i=1;i<=26;i++) for(int j=i+1;j<=26;j++) Ans+=g[A[i]+1][A[j]+1],Ans=((Ans%mod)+mod)%mod; printf("%lld\n",Ans); return 0; } ```
### Prompt Develop a solution in cpp to the problem described below: 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> using namespace std; int main() { int a,b,c; cin>>a>>b; c=6-a-b; cout<<c<<endl; } ```
### Prompt Construct a Cpp code solution to the problem outlined: Snuke has N hats. The i-th hat has an integer a_i written on it. There are N camels standing in a circle. Snuke will put one of his hats on each of these camels. If there exists a way to distribute the hats to the camels such that the following condition is satisfied for every camel, print `Yes`; otherwise, print `No`. * The bitwise XOR of the numbers written on the hats on both adjacent camels is equal to the number on the hat on itself. What is XOR? The bitwise XOR x_1 \oplus x_2 \oplus \ldots \oplus x_n of n non-negative integers x_1, x_2, \ldots, x_n is defined as follows: - When x_1 \oplus x_2 \oplus \ldots \oplus x_n is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if the number of integers among x_1, x_2, \ldots, x_n whose binary representations have 1 in the 2^k's place is odd, and 0 if that count is even. For example, 3 \oplus 5 = 6. Constraints * All values in input are integers. * 3 \leq N \leq 10^{5} * 0 \leq a_i \leq 10^{9} Input Input is given from Standard Input in the following format: N a_1 a_2 \ldots a_{N} Output Print the answer. Examples Input 3 1 2 3 Output Yes Input 4 1 2 4 8 Output No ### Response ```cpp #include<bits/stdc++.h> using namespace std; int main() { int N; cin>>N; int a,c=0; for(int i=1;i<=N;i++) { cin>>a; c^=a; } if(c==0) cout<<"Yes"; else cout<<"No"; } ```
### Prompt Develop a solution in CPP to the problem described below: You are playing a game of Jongmah. You don't need to know the rules to solve this problem. You have n tiles in your hand. Each tile has an integer between 1 and m written on it. To win the game, you will need to form some number of triples. Each triple consists of three tiles, such that the numbers written on the tiles are either all the same or consecutive. For example, 7, 7, 7 is a valid triple, and so is 12, 13, 14, but 2,2,3 or 2,4,6 are not. You can only use the tiles in your hand to form triples. Each tile can be used in at most one triple. To determine how close you are to the win, you want to know the maximum number of triples you can form from the tiles in your hand. Input The first line contains two integers integer n and m (1 ≤ n, m ≤ 10^6) — the number of tiles in your hand and the number of tiles types. The second line contains integers a_1, a_2, …, a_n (1 ≤ a_i ≤ m), where a_i denotes the number written on the i-th tile. Output Print one integer: the maximum number of triples you can form. Examples Input 10 6 2 3 3 3 4 4 4 5 5 6 Output 3 Input 12 6 1 5 3 3 3 4 3 5 3 2 3 3 Output 3 Input 13 5 1 1 5 1 2 3 3 2 4 2 3 4 5 Output 4 Note In the first example, we have tiles 2, 3, 3, 3, 4, 4, 4, 5, 5, 6. We can form three triples in the following way: 2, 3, 4; 3, 4, 5; 4, 5, 6. Since there are only 10 tiles, there is no way we could form 4 triples, so the answer is 3. In the second example, we have tiles 1, 2, 3 (7 times), 4, 5 (2 times). We can form 3 triples as follows: 1, 2, 3; 3, 3, 3; 3, 4, 5. One can show that forming 4 triples is not possible. ### Response ```cpp #include <bits/stdc++.h> using namespace std; void getint(int &v) { char ch, fu = 0; for (ch = '*'; (ch < '0' || ch > '9') && ch != '-'; ch = getchar()) ; if (ch == '-') fu = 1, ch = getchar(); for (v = 0; ch >= '0' && ch <= '9'; ch = getchar()) v = v * 10 + ch - '0'; if (fu) v = -v; } const int INF = 1e9 + 10; int n, ans, m, x, a[1000010], f[1000010][5][5]; int main() { cin >> n >> m; for (int i = 1; i <= n; ++i) getint(x), ++a[x]; for (int i = 0; i <= m; ++i) for (int j = 0; j <= 4; ++j) for (int k = 0; k <= 2; ++k) f[i][j][k] = INF; f[0][0][0] = 0; for (int i = 0; i <= m - 1; ++i) for (int j = 0; j <= 4; ++j) for (int k = 0; k <= 2; ++k) if (f[i][j][k] < INF) { for (int l = 0; l <= 2; ++l) { if (j + l > a[i + 1]) continue; f[i + 1][k + l][l] = min(f[i + 1][k + l][l], f[i][j][k] + (a[i + 1] - j - l) % 3); } } ans = (n - f[m][0][0]) / 3; cout << ans << endl; return 0; } ```
### Prompt Create a solution in Cpp for the following problem: Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing. Nura can buy gadgets for n days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds. Each day (from 1 to n) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during n days. Help Nura to find the minimum day index when she will have k gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to m in order of their appearing in input. Input First line contains four integers n, m, k, s (1 ≤ n ≤ 2·105, 1 ≤ k ≤ m ≤ 2·105, 1 ≤ s ≤ 109) — number of days, total number and required number of gadgets, number of burles Nura has. Second line contains n integers ai (1 ≤ ai ≤ 106) — the cost of one dollar in burles on i-th day. Third line contains n integers bi (1 ≤ bi ≤ 106) — the cost of one pound in burles on i-th day. Each of the next m lines contains two integers ti, ci (1 ≤ ti ≤ 2, 1 ≤ ci ≤ 106) — type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds. Output If Nura can't buy k gadgets print the only line with the number -1. Otherwise the first line should contain integer d — the minimum day index, when Nura will have k gadgets. On each of the next k lines print two integers qi, di — the number of gadget and the day gadget should be bought. All values qi should be different, but the values di can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1 to n. In case there are multiple possible solutions, print any of them. Examples Input 5 4 2 2 1 2 3 2 1 3 2 1 2 3 1 1 2 1 1 2 2 2 Output 3 1 1 2 3 Input 4 3 2 200 69 70 71 72 104 105 106 107 1 1 2 2 1 2 Output -1 Input 4 3 1 1000000000 900000 910000 940000 990000 990000 999000 999900 999990 1 87654 2 76543 1 65432 Output -1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename A, typename B> int print_value(A title, B val) { cout << title << " = " << val << "\n"; return 1; } int break_point() { char c; while ((c = getchar()) != '\n') ; return 0; } template <typename A> int logg(A v) { cout << v << "\n"; return 0; } template <typename T> void read_integer(T &r) { bool sign = 0; r = 0; char c; while (1) { c = getchar(); if (c == '-') { sign = 1; break; } if (c != ' ' && c != '\n') { r = c - '0'; break; } } while (1) { c = getchar(); if (c == ' ' || c == '\n') break; r = r * 10 + (c - '0'); } if (sign) r = -r; } void run(); int main() { srand(time(NULL)); do { run(); if (0) { 0 ? printf("-------------------------------\n") : 0; 0 ? printf("-------------------------------\n") : 0; } } while (0); return 0; } struct product { int num; int cost; product(int _n, int _c) : num(_n), cost(_c) {} bool operator<(const product &other) const { if (cost == other.cost) return num < other.num; return cost < other.cost; } }; vector<product> p[2]; int a[200005]; int b[200005]; int a_min[200005]; int b_min[200005]; long long cost_a[200005]; long long cost_b[200005]; void run() { int n, m, k, s; scanf("%d%d%d%d", &n, &m, &k, &s); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); if (i && a[i] >= a[a_min[i - 1]]) a_min[i] = a_min[i - 1]; else a_min[i] = i; } for (int i = 0; i < n; i++) { scanf("%d", &b[i]); if (i && b[i] >= b[b_min[i - 1]]) b_min[i] = b_min[i - 1]; else b_min[i] = i; } int v, d; for (int i = 0; i < m; i++) { scanf("%d%d", &v, &d); p[v - 1].push_back(product(i + 1, d)); } sort(p[0].begin(), p[0].end()); sort(p[1].begin(), p[1].end()); int l = 0, r = n - 1; int res = -2; int f_a, f_b; while (l <= r) { int mid = (l + r) >> 1; long long mincost = LLONG_MAX; int toa = min(k, (int)p[0].size()); int from_a = 0; int from_b = 0; for (int i = 0; i < toa; i++) { cost_a[i] = 1ll * a[a_min[mid]] * p[0][i].cost; if (i) cost_a[i] += cost_a[i - 1]; } if (toa >= k && mincost > cost_a[k - 1]) { from_a = k; mincost = cost_a[k - 1]; } int tob = min(k, (int)p[1].size()); for (int i = 0; i < tob; i++) { cost_b[i] = 1ll * b[b_min[mid]] * p[1][i].cost; if (i) cost_b[i] += cost_b[i - 1]; int remain = k - i - 1; if (toa >= remain && cost_b[i] + cost_a[remain - 1] < mincost) { mincost = cost_b[i] + cost_a[remain - 1]; from_a = remain; from_b = i + 1; } } if (mincost <= s) { res = mid; f_a = from_a; f_b = from_b; r = mid - 1; } else l = mid + 1; } printf("%d", res + 1); putchar('\n'); if (res != -2) { int day = a_min[res] + 1; for (int i = 0; i < f_a; i++) { printf("%d%c%d", p[0][i].num, ' ', day); putchar('\n'); } day = b_min[res] + 1; for (int i = 0; i < f_b; i++) { printf("%d%c%d", p[1][i].num, ' ', day); putchar('\n'); } } } ```
### Prompt Develop a solution in Cpp to the problem described below: Takahashi and Aoki are going to together construct a sequence of integers. First, Takahashi will provide a sequence of integers a, satisfying all of the following conditions: * The length of a is N. * Each element in a is an integer between 1 and K, inclusive. * a is a palindrome, that is, reversing the order of elements in a will result in the same sequence as the original. Then, Aoki will perform the following operation an arbitrary number of times: * Move the first element in a to the end of a. How many sequences a can be obtained after this procedure, modulo 10^9+7? Constraints * 1≤N≤10^9 * 1≤K≤10^9 Input The input is given from Standard Input in the following format: N K Output Print the number of the sequences a that can be obtained after the procedure, modulo 10^9+7. Examples Input 4 2 Output 6 Input 1 10 Output 10 Input 6 3 Output 75 Input 1000000000 1000000000 Output 875699961 ### Response ```cpp #include<cmath> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<map> using namespace std; const int mod=1e9+7; int n,k,tot,ans; map<int,int>mp; int f[100008],dor[100008]; int read() { int x=0,f=1;char ch=getchar(); for (;ch<'0'||ch>'9';ch=getchar()) if (ch=='-') f=-1; for (;ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0'; return x*f; } int power(int a,int k) { int sum=1; for (;k;k>>=1,a=1ll*a*a%mod) if (k&1) sum=1ll*sum*a%mod; return sum; } int main() { n=read(),k=read(); for (int i=1;1ll*i*i<=n;i++) if (n%i==0) { dor[++tot]=i; if (n/i!=i) dor[++tot]=n/i; } sort(dor+1,dor+tot+1); for (int i=1;i<=tot;i++) mp[dor[i]]=i; ans=f[1]=k; for (int i=2;i<=tot;i++) { if ((n/dor[i])&1) f[i]=(power(k,(dor[i]+1)/2)-f[1])%mod; else f[i]=(power(k,dor[i])-f[1])%mod; for (int j=2;1ll*j*j<=dor[i];j++) if (dor[i]%j==0) { f[i]=(f[i]-f[mp[j]])%mod; if (dor[i]/j!=j) f[i]=(f[i]-f[mp[dor[i]/j]])%mod; } ans=(ans+1ll*f[i]*dor[i]%mod)%mod; } ans=(ans+mod)%mod; printf("%d\n",ans); return 0; } ```
### Prompt Your task is to create a cpp solution to the following problem: Let's play the game using a bag containing several cards with integers written on it. In each game, participants first declare one of their favorite number n. Then, take out an appropriate number of cards from the bag at a time, and if the sum of the numbers written on those cards is equal to n, you will receive a luxurious prize. After each game, the cards will be returned to the bag. Create a program that inputs the information of m types of cards in the bag and the number declared by the participants in g games, and outputs how many combinations of cards can receive luxury products in each game. please. Input A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format: m a1 b1 a2 b2 :: am bm g n1 n2 :: ng The number of card types m (1 ≤ m ≤ 7) on the first line, the integer ai (1 ≤ ai ≤ 100) written on the i-type card on the following m line, and the number bi (1 ≤ bi ≤ 10) Are given with a space delimiter. The next line is given the number of games g (1 ≤ g ≤ 10), and the next g line is given the integer ni (1 ≤ ni ≤ 1,000) declared in game i. The number of datasets does not exceed 100. Output For each input dataset, the i line prints the number of card combinations that will give you a gorgeous prize in Game i. Example Input 5 1 10 5 3 10 3 25 2 50 2 4 120 500 100 168 7 1 10 3 10 5 10 10 10 25 10 50 10 100 10 3 452 574 787 0 Output 16 0 12 7 9789 13658 17466 ### Response ```cpp //Name: Sum of Cards //Level: 2 //Category: 動的計画法,DP //Note: /* * dp[i][j]をi種類目のカードまでを使ってjを作るパターン数とすると, * dp[i][j] = Σ(0≦k≦b_i) dp[i-1][j - a_i*k] * となる. * * 以下のコードでは,iのインデックスを1-originにしてベースケースを簡単にし,また配るDPにして書きやすくしている. * オーダーは O(M*G*B).ただしGは合計値の最大(1000),Bはカード枚数の最大(10). */ #include <iostream> #include <vector> using namespace std; int dp[8][1001]; int main() { cin.tie(0); ios::sync_with_stdio(0); while(true) { int M; cin >> M; if(!M) break; dp[0][0] = 1; for(int i = 1; i <= M; ++i) { int A, B; cin >> A >> B; for(int j = 0; j < 1001; ++j) dp[i][j] = 0; for(int j = 0; j < 1001; ++j) { for(int k = 0; k <= B; ++k) { const int next = j + A*k; if(next <= 1000) dp[i][next] += dp[i-1][j]; } } } int N; cin >> N; while(N--) { int NG; cin >> NG; cout << dp[M][NG] << endl; } } return 0; } ```
### Prompt Please create a solution in cpp to the following problem: We have a set S of N points in a two-dimensional plane. The coordinates of the i-th point are (x_i, y_i). The N points have distinct x-coordinates and distinct y-coordinates. For a non-empty subset T of S, let f(T) be the number of points contained in the smallest rectangle, whose sides are parallel to the coordinate axes, that contains all the points in T. More formally, we define f(T) as follows: * f(T) := (the number of integers i (1 \leq i \leq N) such that a \leq x_i \leq b and c \leq y_i \leq d, where a, b, c, and d are the minimum x-coordinate, the maximum x-coordinate, the minimum y-coordinate, and the maximum y-coordinate of the points in T) Find the sum of f(T) over all non-empty subset T of S. Since it can be enormous, print the sum modulo 998244353. Constraints * 1 \leq N \leq 2 \times 10^5 * -10^9 \leq x_i, y_i \leq 10^9 * x_i \neq x_j (i \neq j) * y_i \neq y_j (i \neq j) * All values in input are integers. Input Input is given from Standard Input in the following format: N x_1 y_1 : x_N y_N Output Print the sum of f(T) over all non-empty subset T of S, modulo 998244353. Examples Input 3 -1 3 2 1 3 -2 Output 13 Input 4 1 4 2 1 3 3 4 2 Output 34 Input 10 19 -11 -3 -12 5 3 3 -15 8 -14 -9 -20 10 -9 0 2 -7 17 6 -6 Output 7222 ### Response ```cpp #include <bits/stdc++.h> using namespace std; #define PB push_back #define ZERO (1e-10) #define INF int(1e9+1) #define CL(A,I) (memset(A,I,sizeof(A))) #define DEB printf("DEB!\n"); #define D(X) cout<<" "<<#X": "<<X<<endl; #define EQ(A,B) (A+ZERO>B&&A-ZERO<B) typedef long long ll; typedef pair<ll,ll> pll; typedef vector<int> vi; typedef pair<int,int> ii; typedef vector<ii> vii; #define IN(n) int n;scanf("%d",&n); #define FOR(i, m, n) for (int i(m); i < n; i++) #define F(n) FOR(i,0,n) #define FF(n) FOR(j,0,n) #define FT(m, n) FOR(k, m, n) #define aa first #define bb second void ga(int N,int *A){F(N)scanf("%d",A+i);} #define MOD 998244353 #define MX 222222 void rnm(int*A,int N){ static ii B[MX]; int L=0; F(N)B[i]={A[i],i}; sort(B,B+N); F(N)A[B[i].bb]=L+=i&&B[i].aa^B[i-1].aa; } struct FW{ int t[MX],S; void clr(int s){CL(t,0);S=s;} void inc(int i,int d){for(;i<S;i|=i+1)t[i]+=d;} int sum(int i){int s(0);while(~i)s+=t[i],i&=i+1,--i;return s;} int gt(int l,int r){return sum(r)-sum(l-1);} }F; int S,N,X[MX],Y[MX],H[MX],x[MX],y[MX],L[MX],R[MX],l[MX],r[MX]; ll P[MX]={1}; bool cp(int a,int b){return X[a]<X[b];} void lgr(int*L,int*R){ F.clr(MX-666); F(N)L[i]=F.sum(Y[i]),F.inc(Y[i],1),R[i]=i-L[i]; } #define E(I) (P[I]-1) ll go(int i){ return ((P[N-1]+E(L[i]+l[i])*E(R[i]+r[i])-E(L[i])*E(R[i])-E(l[i])*E(r[i]))%MOD+MOD)%MOD; } int main(void){ FT(1,MX)P[k]=P[k-1]*2%MOD; scanf("%d",&N),iota(H,H+N,0); F(N)scanf("%d%d",X+i,Y+i); rnm(X,N),rnm(Y,N); F(N)x[X[i]]=X[i],y[X[i]]=Y[i]; F(N)Y[i]=y[i],X[i]=i; lgr(L,R),reverse(Y,Y+N),lgr(l,r),reverse(Y,Y+N),reverse(l,l+N),reverse(r,r+N); // F(N)printf("[%d][%d]: <<%d/%d ... %d/%d>>\n",X[i],Y[i],L[i],R[i],l[i],r[i]); F(N)S=(S+go(i))%MOD; printf("%d\n",S); return 0; } ```
### Prompt Generate a CPP solution to the following problem: Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" — then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night. It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them. Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be. Input The first line of the input contains integer n (1 ≤ n ≤ 100), where n — the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 ≤ ti ≤ 1000). The last line contains integer T (1 ≤ T ≤ 1000) — the time interval during which the freebie was near the dormitory. Output Print a single integer — the largest number of people who will pass exam tomorrow because of the freebie visit. Examples Input 6 4 1 7 8 3 8 1 Output 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int ar[10000], vis[10000]; int main() { int i, j, k, l, t, r, s, m, md, n, a, b, c, d, e, f, g, h, u, v; scanf("%d", &n); for (i = 0; i < n; i++) { scanf("%d", &ar[i]); } sort(ar, ar + n); scanf("%d", &t); a = 0; m = 0; for (i = 0; i < n; i++) { l = i; h = n - 1; md = (h + l) / 2; b = ar[i] + t; while (l <= h) { if (ar[md] <= b) { if (md + 1 < n && ar[md + 1] <= b) l = md + 1; else break; } else h = md - 1; md = (l + h) / 2; } if (md - i + 1 > m) m = md - i + 1; } printf("%d\n", m); return 0; } ```
### Prompt Please formulate a cpp solution to the following problem: You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i. You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with length d_i after erasing the edges. Your goal is to erase the edges in such a way that the number of good vertices is maximized. Input The first line contains three integers n, m and k (2 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ m ≤ 3 ⋅ 10^5, n - 1 ≤ m, 0 ≤ k ≤ m) — the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively. Then m lines follow, each containing three integers x, y, w (1 ≤ x, y ≤ n, x ≠ y, 1 ≤ w ≤ 10^9), denoting an edge connecting vertices x and y and having weight w. The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices). Output In the first line print e — the number of edges that should remain in the graph (0 ≤ e ≤ k). In the second line print e distinct integers from 1 to m — the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible. Examples Input 3 3 2 1 2 1 3 2 1 1 3 3 Output 2 1 2 Input 4 5 2 4 1 8 2 4 1 2 1 3 3 4 9 3 1 5 Output 2 3 2 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 3e5 + 10; int n, m, k; int ans[N], F[N]; vector<pair<int, pair<int, int> > > g[N]; priority_queue<pair<long long, pair<int, int> > > pq; int main() { cin >> n >> m >> k; int u, v, w; for (int i = 1; i <= m; i++) { cin >> u >> v >> w; g[u].push_back({v, {w, i}}); g[v].push_back({u, {w, i}}); } pq.push({0, {1, 0}}); long long l = 0, res = 0, d = 0; while (!pq.empty()) { l = -pq.top().first; v = pq.top().second.first; d = pq.top().second.second; pq.pop(); if (F[v]) continue; F[v] = 1; if (v != 1) { if (res + 1 > k) break; res++; ans[res] = d; } for (int i = 0; i < g[v].size(); i++) { pq.push( {-l - g[v][i].second.first, {g[v][i].first, g[v][i].second.second}}); } } cout << res << "\n"; for (int i = 1; i <= res; i++) cout << ans[i] << " "; cout << "\n"; } ```
### Prompt Create a solution in CPP for the following problem: Last week, Hamed learned about a new type of equations in his math class called Modular Equations. Lets define i modulo j as the remainder of division of i by j and denote it by <image>. A Modular Equation, as Hamed's teacher described, is an equation of the form <image> in which a and b are two non-negative integers and x is a variable. We call a positive integer x for which <image> a solution of our equation. Hamed didn't pay much attention to the class since he was watching a movie. He only managed to understand the definitions of these equations. Now he wants to write his math exercises but since he has no idea how to do that, he asked you for help. He has told you all he knows about Modular Equations and asked you to write a program which given two numbers a and b determines how many answers the Modular Equation <image> has. Input In the only line of the input two space-separated integers a and b (0 ≤ a, b ≤ 109) are given. Output If there is an infinite number of answers to our equation, print "infinity" (without the quotes). Otherwise print the number of solutions of the Modular Equation <image>. Examples Input 21 5 Output 2 Input 9435152 272 Output 282 Input 10 10 Output infinity Note In the first sample the answers of the Modular Equation are 8 and 16 since <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int a, b; scanf("%d%d", &a, &b); if (b == a) { printf("infinity"); return 0; } if (b > a) { printf("0"); return 0; } int ans = 0; int m = a - b; int sq = sqrt(m); for (int i = 1; i <= sq; i++) { if (m % i == 0) { int temp = m / i; if (a % i == b) ans++; if (a % temp == b && temp != i) ans++; } } printf("%d", ans); return 0; } ```
### Prompt In Cpp, your task is to solve the following problem: We have N switches with "on" and "off" state, and M bulbs. The switches are numbered 1 to N, and the bulbs are numbered 1 to M. Bulb i is connected to k_i switches: Switch s_{i1}, s_{i2}, ..., and s_{ik_i}. It is lighted when the number of switches that are "on" among these switches is congruent to p_i modulo 2. How many combinations of "on" and "off" states of the switches light all the bulbs? Constraints * 1 \leq N, M \leq 10 * 1 \leq k_i \leq N * 1 \leq s_{ij} \leq N * s_{ia} \neq s_{ib} (a \neq b) * p_i is 0 or 1. * All values in input are integers. Input Input is given from Standard Input in the following format: N M k_1 s_{11} s_{12} ... s_{1k_1} : k_M s_{M1} s_{M2} ... s_{Mk_M} p_1 p_2 ... p_M Output Print the number of combinations of "on" and "off" states of the switches that light all the bulbs. Examples Input 2 2 2 1 2 1 2 0 1 Output 1 Input 2 3 2 1 2 1 1 1 2 0 0 1 Output 0 Input 5 2 3 1 2 5 2 2 3 1 0 Output 8 ### Response ```cpp #include<bits/stdc++.h> #define REP(i,n) for(int i=0;i<(n);++i) #define vi vector<int> #define vvi vector<vi > using namespace std; int main(){ int n,m; cin>>n>>m; vvi vec(m); REP(i,m){ int k; cin>>k; vec[i].resize(k); REP(j,k){ cin>>vec[i][j]; vec[i][j]--; } } vi p(m); REP(i,m) cin>>p[i]; int ans=0; for(int i=0;i<(1<<n);++i){//スイッチの付き方全通り試す. bool ok=true; for(int j=0;j<m;++j){//全ての電球を試す. int cnt=0; for(int id:vec[j]){ if((i>>id)&1) cnt++; } if((cnt%2)!=p[j]) ok=false; } if(ok) ans++; } cout<<ans<<endl; }//解説参考.bit全探索. ```