text
stringlengths 424
69.5k
|
---|
### Prompt
In cpp, your task is to solve the following problem:
Snuke is having a barbeque party.
At the party, he will make N servings of Skewer Meal.
<image>
Example of a serving of Skewer Meal
He has a stock of 2N skewers, all of which will be used in Skewer Meal. The length of the i-th skewer is L_i. Also, he has an infinite supply of ingredients.
To make a serving of Skewer Meal, he picks 2 skewers and threads ingredients onto those skewers. Let the length of the shorter skewer be x, then the serving can hold the maximum of x ingredients.
What is the maximum total number of ingredients that his N servings of Skewer Meal can hold, if he uses the skewers optimally?
Constraints
* 1≦N≦100
* 1≦L_i≦100
* For each i, L_i is an integer.
Input
The input is given from Standard Input in the following format:
N
L_1 L_2 ... L_{2N}
Output
Print the maximum total number of ingredients that Snuke's N servings of Skewer Meal can hold.
Examples
Input
2
1 3 1 2
Output
3
Input
5
100 1 2 3 14 15 58 58 58 29
Output
135
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int n,ans;
int a[201];
int main(){
cin>>n;
for(int i=1;i<=2*n;i++)
cin>>a[i];
sort(a+1,a+1+2*n);
for(int i=1;i<=2*n;i+=2)
ans+=a[i];
cout<<ans;
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 5000) — lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters — string A.
The third line contains a string consisting of m lowercase Latin letters — string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 ⋅ |abb|) - |abb| - |abab| = 4 ⋅ 3 - 3 - 4 = 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void c_p_c() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
int32_t main() {
c_p_c();
long long n, m;
cin >> n >> m;
string str1;
string str2;
cin >> str1;
cin >> str2;
vector<vector<long long> > dp(n + 1, vector<long long>(m + 1, 0));
for (long long i = n - 1; i >= 0; i--) {
for (long long j = m - 1; j >= 0; j--) {
if (i == n or j == m) {
dp[i][j] = 0;
continue;
}
if (str1[i] == str2[j]) {
dp[i][j] = 2 + dp[i + 1][j + 1];
}
dp[i][j] = max(dp[i + 1][j] - 1, dp[i][j]);
dp[i][j] = max(dp[i][j + 1] - 1, dp[i][j]);
}
}
long long ans = 0;
for (long long i = 0; i < n; i++) {
for (long long j = 0; j < m; j++) ans = max(ans, dp[i][j]);
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
You are given four integers: H, W, h and w (1 ≤ h ≤ H, 1 ≤ w ≤ W). Determine whether there exists a matrix such that all of the following conditions are held, and construct one such matrix if the answer is positive:
* The matrix has H rows and W columns.
* Each element of the matrix is an integer between -10^9 and 10^9 (inclusive).
* The sum of all the elements of the matrix is positive.
* The sum of all the elements within every subrectangle with h rows and w columns in the matrix is negative.
Constraints
* 1 ≤ h ≤ H ≤ 500
* 1 ≤ w ≤ W ≤ 500
Input
Input is given from Standard Input in the following format:
H W h w
Output
If there does not exist a matrix that satisfies all of the conditions, print `No`.
Otherwise, print `Yes` in the first line, and print a matrix in the subsequent lines in the following format:
a_{11} ... a_{1W}
:
a_{H1} ... a_{HW}
Here, a_{ij} represents the (i,\ j) element of the matrix.
Examples
Input
3 3 2 2
Output
Yes
1 1 1
1 -4 1
1 1 1
Input
2 4 1 2
Output
No
Input
3 4 2 3
Output
Yes
2 -5 8 7
3 -5 -4 -5
2 1 -1 7
### Response
```cpp
#include<stdio.h>
int main(){int H,W,h,w;scanf("%d%d%d%d",&H,&W,&h,&w);if(H%h||W%w){puts("Yes");for(int i=1;i<=H;++i,puts("")) for(int j=1;j<=W;++j)printf("%d ",(i%h||j%w)?1000:-1000*(h*w-1)-1);}else puts("No");return 0;}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
You are given n strings a_1, a_2, …, a_n: all of them have the same length m. The strings consist of lowercase English letters.
Find any string s of length m such that each of the given n strings differs from s in at most one position. Formally, for each given string a_i, there is no more than one position j such that a_i[j] ≠ s[j].
Note that the desired string s may be equal to one of the given strings a_i, or it may differ from all the given strings.
For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
Input
The first line contains an integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow.
Each test case starts with a line containing two positive integers n (1 ≤ n ≤ 10) and m (1 ≤ m ≤ 10) — the number of strings and their length.
Then follow n strings a_i, one per line. Each of them has length m and consists of lowercase English letters.
Output
Print t answers to the test cases. Each answer (if it exists) is a string of length m consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
Example
Input
5
2 4
abac
zbab
2 4
aaaa
bbbb
3 3
baa
aaa
aab
2 2
ab
bb
3 1
a
b
c
Output
abab
-1
aaa
ab
z
Note
The first test case was explained in the statement.
In the second test case, the answer does not exist.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e9 + 5;
const double EPS = 1e-9;
int main() {
long long TC;
cin >> TC;
while (TC--) {
int n, m;
cin >> n >> m;
vector<string> a(n);
for (auto &i : a) cin >> i;
auto makeset = [&](string s) {
set<string> sset;
for (int i = 0; i < m; i++)
for (char ch = 'a'; ch <= 'z'; ch++) {
string t = s;
t[i] = ch;
sset.insert(t);
}
return sset;
};
set<string> sset = makeset(a[0]);
for (int i = 1; i < n; i++) {
set<string> tempset = makeset(a[i]), intersect;
set_intersection(tempset.begin(), tempset.end(), sset.begin(), sset.end(),
inserter(intersect, intersect.begin()));
sset = intersect;
}
if (sset.size())
cout << *sset.begin() << '\n';
else
cout << -1 << '\n';
}
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Codeforces is a wonderful platform and one its feature shows how much someone contributes to the community. Every registered user has contribution — an integer number, not necessarily positive. There are n registered users and the i-th of them has contribution ti.
Limak is a little polar bear and he's new into competitive programming. He doesn't even have an account in Codeforces but he is able to upvote existing blogs and comments. We assume that every registered user has infinitely many blogs and comments.
* Limak can spend b minutes to read one blog and upvote it. Author's contribution will be increased by 5.
* Limak can spend c minutes to read one comment and upvote it. Author's contribution will be increased by 1.
Note that it's possible that Limak reads blogs faster than comments.
Limak likes ties. He thinks it would be awesome to see a tie between at least k registered users. To make it happen he is going to spend some time on reading and upvoting. After that, there should exist an integer value x that at least k registered users have contribution exactly x.
How much time does Limak need to achieve his goal?
Input
The first line contains four integers n, k, b and c (2 ≤ k ≤ n ≤ 200 000, 1 ≤ b, c ≤ 1000) — the number of registered users, the required minimum number of users with the same contribution, time needed to read and upvote a blog, and time needed to read and upvote a comment, respectively.
The second line contains n integers t1, t2, ..., tn (|ti| ≤ 109) where ti denotes contribution of the i-th registered user.
Output
Print the minimum number of minutes Limak will spend to get a tie between at least k registered users.
Examples
Input
4 3 100 30
12 2 6 1
Output
220
Input
4 3 30 100
12 2 6 1
Output
190
Input
6 2 987 789
-8 42 -4 -65 -8 -8
Output
0
Note
In the first sample, there are 4 registered users and Limak wants a tie between at least 3 of them. Limak should behave as follows.
* He spends 100 minutes to read one blog of the 4-th user and increase his contribution from 1 to 6.
* Then he spends 4·30 = 120 minutes to read four comments of the 2-nd user and increase his contribution from 2 to 6 (four times it was increaded by 1).
In the given scenario, Limak spends 100 + 4·30 = 220 minutes and after that each of users 2, 3, 4 has contribution 6.
In the second sample, Limak needs 30 minutes to read a blog and 100 minutes to read a comment. This time he can get 3 users with contribution equal to 12 by spending 100 + 3·30 = 190 minutes:
* Spend 2·30 = 60 minutes to read two blogs of the 1-st user to increase his contribution from 2 to 12.
* Spend 30 + 100 minutes to read one blog and one comment of the 3-rd user. His contribution will change from 6 to 6 + 5 + 1 = 12.
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx")
using namespace std;
int a, b, c, d, n, m, k;
int mas[200002];
pair<int, int> fx[200002];
long long solve(int md) {
multiset<long long> s1, s2;
long long sum = 0;
long long add1 = 0, add2 = 0;
for (int _n((n)-1), i(0); i <= _n; i++) {
int t = mas[i] % 5;
fx[i].first = mas[i];
fx[i].second = 0;
while (t != md) {
++t;
if (t == 5) t = 0;
++fx[i].first;
fx[i].second += c;
}
fx[i].first /= 5;
}
auto upd = [&]() {
while ((int)s1.size() > k) {
long long t = *s1.rbegin() + add1;
s1.erase(--s1.end());
s2.insert(t - add2);
sum -= t;
}
while (1) {
if (s2.empty()) break;
long long mn2 = *s2.begin() + add2;
long long mx1 = *s1.rbegin() + add1;
if (mn2 < mx1) {
sum -= mx1;
sum += mn2;
s1.erase(--s1.end());
s2.erase(s2.begin());
s1.insert(mn2 + add1);
s2.insert(mx1 + add2);
} else
break;
}
};
long long ans = 8LL * 1000000000 * 1000000000;
for (int _n((n)-1), i(0); i <= _n; i++) {
s1.insert(fx[i].second - add1);
sum += fx[i].second;
upd();
if (s1.size() == k && sum < ans) {
ans = sum;
}
if (i == n - 1) break;
long long delta = (long long)fx[i + 1].first - (long long)fx[i].first;
add1 += (long long)delta * b;
add2 += (long long)delta * b;
sum += (long long)s1.size() * delta * b;
}
return ans;
}
int main() {
scanf("%d%d%d%d", &n, &k, &b, &c);
b = min(b, c * 5);
for (int _n((n)-1), i(0); i <= _n; i++) {
scanf("%d", &mas[i]);
}
sort(mas, mas + n);
int mn = mas[0];
for (int _n((n)-1), i(0); i <= _n; i++) {
mas[i] -= mn;
}
long long ans = 8LL * 1000000000 * 1000000000;
for (int _n((5) - 1), md(0); md <= _n; md++) {
long long cur = solve(md);
if (cur < ans) ans = cur;
}
cout << ans << endl;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Vasya has a multiset s consisting of n integer numbers. Vasya calls some number x nice if it appears in the multiset exactly once. For example, multiset \{1, 1, 2, 3, 3, 3, 4\} contains nice numbers 2 and 4.
Vasya wants to split multiset s into two multisets a and b (one of which may be empty) in such a way that the quantity of nice numbers in multiset a would be the same as the quantity of nice numbers in multiset b (the quantity of numbers to appear exactly once in multiset a and the quantity of numbers to appear exactly once in multiset b).
Input
The first line contains a single integer n~(2 ≤ n ≤ 100).
The second line contains n integers s_1, s_2, ... s_n~(1 ≤ s_i ≤ 100) — the multiset s.
Output
If there exists no split of s to satisfy the given requirements, then print "NO" in the first line.
Otherwise print "YES" in the first line.
The second line should contain a string, consisting of n characters. i-th character should be equal to 'A' if the i-th element of multiset s goes to multiset a and 'B' if if the i-th element of multiset s goes to multiset b. Elements are numbered from 1 to n in the order they are given in the input.
If there exist multiple solutions, then print any of them.
Examples
Input
4
3 5 7 1
Output
YES
BABA
Input
3
3 5 1
Output
NO
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int inf = 1e9 + 7;
inline void rvi(vector<int>& v, int n) {
int temp;
for (int i = 0; i < n; i++) {
cin >> temp;
v.push_back(temp);
}
}
inline void rvll(vector<long long int>& v, int n) {
long long int temp;
for (int i = 0; i < n; i++) {
cin >> temp;
v.push_back(temp);
}
}
inline void prvi(vector<int>& a) {
for (int i = 0; i < a.size(); i++) {
cout << a[i] << " ";
}
cout << endl;
}
inline void prvll(vector<long long int>& a) {
for (int i = 0; i < a.size(); i++) {
cout << a[i] << " ";
}
cout << endl;
}
inline void prmii(map<int, int>& m) {
for (auto x : m) {
cout << x.first << " " << x.second << endl;
}
}
inline vector<long long int> prefixsum(vector<int>& a) {
vector<long long int> b;
b.push_back(a[0]);
for (int i = 1; i < a.size(); i++) {
b.push_back(a[i] + b[i - 1]);
}
return b;
}
inline vector<long long int> suffixsum(vector<int>& a) {
vector<long long int> b((a.size()));
b[(a.size()) - 1] = a[(a.size()) - 1];
for (int i = (a.size()) - 1 - 1; i >= 0; i--) {
b[i] = a[i] + b[i + 1];
}
return b;
}
inline vector<long long int> prefixsum(vector<long long int>& a) {
vector<long long int> b;
b.push_back(a[0]);
for (int i = 1; i < a.size(); i++) {
b.push_back(a[i] + b[i - 1]);
}
return b;
}
inline vector<long long int> suffixsum(vector<long long int>& a) {
vector<long long int> b((a.size()));
b[(a.size()) - 1] = a[(a.size()) - 1];
for (int i = (a.size()) - 1 - 1; i >= 0; i--) {
b[i] = a[i] + b[i + 1];
}
return b;
}
void solve();
int main() {
std::ios::sync_with_stdio(false);
cin.tie(NULL);
solve();
return 0;
}
void solve() {
int n;
cin >> n;
vector<int> a(n);
vector<char> b(n);
map<int, int> mp;
for (int i = 0; i < n; i++) {
cin >> a[i];
mp[a[i]]++;
}
int count = 0;
int flag = 0;
for (auto x : mp) {
if (x.second == 1) {
count++;
} else if ((x.second) >= 3) {
flag = 1;
} else {
;
}
}
if ((count % 2) != 0 && flag == 0) {
cout << "NO" << endl;
} else if (mp.size() == 1) {
if (((mp[a[0]])) == 1) {
cout << "NO" << endl;
} else {
cout << "YES" << endl;
for (int i = 0; i < n; i++) {
if ((i & 1) == 0) {
b[i] = 'A';
} else {
b[i] = 'A';
}
}
for (int i = 0; i < n; i++) {
cout << b[i];
}
cout << endl;
return;
}
} else {
cout << "YES" << endl;
if (flag == 0 || (count % 2) == 0) {
int check = 0;
for (int i = 0; i < n; i++) {
if (mp[a[i]] == 1) {
if ((check & 1) == 0) {
b[i] = 'A';
check++;
} else {
b[i] = 'B';
check++;
}
} else {
b[i] = 'A';
}
}
} else {
int check = 0;
for (int i = 0; i < n; i++) {
if (mp[a[i]] == 1) {
if ((check & 1) == 0) {
b[i] = 'A';
check++;
} else {
b[i] = 'B';
check++;
}
} else {
b[i] = 'A';
}
}
int val;
for (auto x : mp) {
if ((x.second >= 3)) {
val = x.first;
break;
}
}
for (int i = 0; i < n; i++) {
if (a[i] == val) {
b[i] = 'B';
break;
}
}
}
for (int i = 0; i < n; i++) {
cout << b[i];
}
cout << endl;
}
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Little Victor adores the sets theory. Let us remind you that a set is a group of numbers where all numbers are pairwise distinct. Today Victor wants to find a set of integers S that has the following properties:
* for all x <image> the following inequality holds l ≤ x ≤ r;
* 1 ≤ |S| ≤ k;
* lets denote the i-th element of the set S as si; value <image> must be as small as possible.
Help Victor find the described set.
Input
The first line contains three space-separated integers l, r, k (1 ≤ l ≤ r ≤ 1012; 1 ≤ k ≤ min(106, r - l + 1)).
Output
Print the minimum possible value of f(S). Then print the cardinality of set |S|. Then print the elements of the set in any order.
If there are multiple optimal sets, you can print any of them.
Examples
Input
8 15 3
Output
1
2
10 11
Input
8 30 7
Output
0
5
14 9 28 11 16
Note
Operation <image> represents the operation of bitwise exclusive OR. In other words, it is the XOR operation.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long l, r, k;
long long a[1000010];
int d1;
struct node {
long long w;
long long b[5];
int cnt;
};
node b[20];
long long c[5];
bool cmp(node a, node b) { return a.w < b.w; }
void dfs(long long l, long long r, int cent, long long v) {
if (l > r) {
if (!cent) return;
b[d1].cnt = cent;
for (int i = 0; i < cent; i++) b[d1].b[i] = c[i];
b[d1++].w = v;
return;
}
c[cent] = l;
dfs(l + 1, r, cent + 1, v ^ l);
dfs(l + 1, r, cent, v);
}
int main() {
while (cin >> l >> r >> k) {
long long ans, x;
int d = 0, i, j;
if (k == 1) {
ans = l;
a[d++] = l;
} else {
if (r - l < 4) {
d1 = 0;
dfs(l, r, 0, 0);
sort(b, b + d1, cmp);
for (i = 0; i < d1; i++)
if (b[i].cnt <= k) {
ans = b[i].w;
for (j = 0; j < b[i].cnt; j++) a[d++] = b[i].b[j];
break;
}
} else {
if (k == 2) {
for (x = l; x <= r; x++)
if (x % 2 == 0) break;
ans = 1;
a[d++] = x;
a[d++] = x + 1;
} else if (k >= 4) {
for (x = l; x <= r; x++)
if (x % 2 == 0) break;
ans = 0;
a[d++] = x;
a[d++] = x + 1;
a[d++] = x + 2;
a[d++] = x + 3;
} else {
long long now = l;
int bi = 0;
while (now) {
now >>= 1;
bi++;
}
now = 3;
while (--bi) now <<= 1;
if (now <= r) {
ans = 0;
a[d++] = now;
a[d++] = now ^ l;
a[d++] = l;
} else {
for (x = l; x <= r; x++)
if (x % 2 == 0) break;
ans = 1;
a[d++] = x;
a[d++] = x + 1;
}
}
}
}
cout << ans << endl << d << endl;
for (i = 0; i < d - 1; i++) cout << a[i] << ' ';
cout << a[i] << endl;
}
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
There are M chairs arranged in a line. The coordinate of the i-th chair (1 ≤ i ≤ M) is i.
N people of the Takahashi clan played too much games, and they are all suffering from backaches. They need to sit in chairs and rest, but they are particular about which chairs they sit in. Specifically, the i-th person wishes to sit in a chair whose coordinate is not greater than L_i, or not less than R_i. Naturally, only one person can sit in the same chair.
It may not be possible for all of them to sit in their favorite chairs, if nothing is done. Aoki, who cares for the health of the people of the Takahashi clan, decides to provide additional chairs so that all of them can sit in chairs at their favorite positions.
Additional chairs can be placed at arbitrary real coordinates. Find the minimum required number of additional chairs.
Constraints
* 1 ≤ N,M ≤ 2 × 10^5
* 0 ≤ L_i < R_i ≤ M + 1(1 ≤ i ≤ N)
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M
L_1 R_1
:
L_N R_N
Output
Print the minimum required number of additional chairs.
Examples
Input
4 4
0 3
2 3
1 3
3 4
Output
0
Input
7 6
0 7
1 5
3 6
2 7
1 6
2 6
3 7
Output
2
Input
3 1
1 2
1 2
1 2
Output
2
Input
6 6
1 6
1 6
1 5
1 5
2 6
2 6
Output
2
### Response
```cpp
#include <iostream>
#include <vector>
#include <functional>
#include <queue>
using namespace std;
int N, M, L[200009], R[200009];
vector<int>vec[200009];
priority_queue<int, vector<int>, greater<int>>Q;
int main() {
cin >> N >> M; M++;
for (int i = 1; i <= N; i++) {
cin >> L[i] >> R[i]; vec[L[i]].push_back(R[i]);
}
for (int i = M; i > N; i--) {
for (int j : vec[i]) Q.push(M - j);
}
int P = M - 1;
for (int i = N; i >= 1; i--) {
for (int j : vec[i]) Q.push(M - j);
if (!Q.empty()) { Q.pop(); P--; }
}
for (int j : vec[0]) Q.push(M - j);
vector<int>v; while (!Q.empty()) { v.push_back(Q.top()); Q.pop(); }
int B = 1, cnt = v.size();
for (int i = 0; i < v.size(); i++) {
if (B > P) break;
if (B <= v[i]) { B++; cnt--; }
}
cout << cnt << endl;
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
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;
long long i, n, x, m, k, ans;
int main() {
cin >> n;
x = n;
while (x) {
x /= 10;
m++;
}
ans = n * m + m - 1;
k = 1;
for (i = 0; i < m - 1; i++) {
k *= 10;
ans -= k;
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.
All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.
Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.
The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
Output
The first line must contain the minimum possible total cost of delaying the flights.
The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
Example
Input
5 2
4 2 1 10 2
Output
20
3 6 7 4 5
Note
Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles.
However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline void read(T& x) {
x = 0;
char c = getchar();
while (c < '0' || c > '9') c = getchar();
while (c >= '0' && c <= '9') {
x *= 10;
x += c - '0';
c = getchar();
}
}
inline void reads(string& s) {
char c = getchar();
while (c < 'a' || c > 'z') c = getchar();
while (c >= 'a' && c <= 'z') {
s += c;
c = getchar();
}
}
const string YES = "YES";
const string NO = "NO";
void out(int x) {
if (x == 0) {
cout << NO << endl;
exit(0);
}
if (x == 1) {
cout << YES << endl;
exit(0);
}
}
const int N = 300300;
int c[N];
int ans[N];
priority_queue<pair<int, int>> st;
int main() {
ios_base::sync_with_stdio(0);
int n, k;
cin >> n >> k;
for (int i = 0; i < n; i++) cin >> c[i];
for (int i = 0; i < k; i++) st.push({c[i], -i});
int ans[n];
long long sum = 0;
for (int j = k; j < k + n; j++) {
if (j < n) {
st.push({c[j], -j});
}
if (st.size() == 0) {
while (true) {
}
}
auto it = st.top();
st.pop();
auto cur = it;
cur.second *= -1;
ans[cur.second] = j + 1;
sum += 1ll * cur.first * (j - cur.second);
}
cout << sum << endl;
for (int i = 0; i < n; i++) cout << ans[i] << ' ';
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 ≤ x ≤ m.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 ≤ ai ≤ 104) — elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 — the binary representation of number m. Number m equals <image>.
Output
Print a single integer — the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }
long long lcm(int a, int b) { return a / gcd(a, b) * b; }
int num[N], s[N];
char b[N];
int main() {
int n;
cin >> n;
int i, j;
for (i = 0; i < n; ++i) {
cin >> num[i];
if (i == 0)
s[i] = num[i];
else
s[i] = s[i - 1] + num[i];
}
cin >> b;
int ans = -1, sum = 0;
for (i = n - 1; i >= 0; --i) {
if (b[i] == '1') {
ans = max(ans, sum + (i == 0 ? 0 : s[i - 1]));
sum += num[i];
}
}
cout << max(ans, sum) << endl;
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long fp(long long n, long long p) {
if (p == 0) return 1;
if (p == 1) return n;
long long res;
res = fp(n, p / 2);
res = (res * res);
if (p % 2) res = (res * n);
return res;
}
bool comp(pair<long long, long long> a, pair<long long, long long> b) {
if (a.first != b.first)
return (a.first < b.first);
else
return (a.second < b.second);
}
bool comp2(pair<long long, long long> a, pair<long long, long long> b) {
return (a.second < b.second);
}
long long n, m, a, b, ans = 0;
pair<long long, long long> arr[200001];
int main() {
ios::sync_with_stdio(0);
ios_base::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n;
for (int i = 0; i < n; i++) {
cin >> arr[i].first >> arr[i].second;
}
sort(arr, arr + n, comp2);
a = 0;
while (a < n) {
long long l = a, cur = arr[a].second;
while (a < n) {
if (arr[a].second == cur)
a++;
else
break;
}
long long t = a - l;
ans += t * (t - 1) / 2;
}
sort(arr, arr + n, comp);
a = 0;
while (a < n) {
long long l = a, cur = arr[a].first;
while (a < n) {
if (arr[a].first == cur)
a++;
else
break;
}
long long t = a - l;
ans += t * (t - 1) / 2;
}
a = 0;
while (a < n) {
int l = a, cux = arr[a].first, cuy = arr[a].second;
while (a < n) {
if (cux == arr[a].first && cuy == arr[a].second)
a++;
else
break;
}
long long q = a - l;
ans -= q * (q - 1) / 2;
}
cout << ans << '\n';
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
There is a flat island whose shape is a perfect square. On this island, there are three habitants whose names are IC, PC, and ACM Every day, one jewel is dropped from the heaven. Just as the jewel touches the ground, IC, PC, and ACM leave their houses simultaneously, run with the same speed, and then a person who first touched the jewel can get the jewel. Hence, the person whose house is nearest to the location of the jewel is the winner of that day.
They always have a quarrel with each other, and therefore their houses are located at distinct places. The locations of their houses are fixed. This jewel falls at a random point on the island, that is, all points on the island have even chance.
When three are two or more persons whose houses are simultaneously nearest, the last person in the order of
IC, PC, ACM
obtains the jewel.
Our interest is to know the probability for IC to get the jewel under this situation.
Input
The input describes one problem instance per line. Each line contains the x- and y-coordinates of IC's home, those of PC's, and those of ACM's in this order. Note that the houses of IC, PC and ACM are located at distinct places. The end of the input is indicated by a line with six zeros.
The coordinates of the whole island are given by (0, 10000) × (0, 10000) and coordinates of houses are given in integer numbers between 1 and 9999, inclusive. It should be noted that the locations of the jewels are arbitrary places on the island and their coordinate values are not necessarily integers.
Output
For each input line, your program should output its sequence number starting from 1, and the probability for the instance. The computed probability values should have errors less than 10-5.
The sequence number and the probability should be printed on the same line. The two numbers should be separated by a space.
Example
Input
2000 2000 8000 8000 9000 9500
2500 2500 7500 2500 2500 7500
0 0 0 0 0 0
Output
1 0.50000
2 0.25000
### Response
```cpp
#include<iostream>
#include<cfloat>
#include<cassert>
#include<cmath>
#include<vector>
using namespace std;
#define EPS (1e-10)
#define equals(a, b) (fabs((a) - (b)) < EPS )
#define dle(a, b) (equals(a, b) || a < b )
static const double PI = acos(-1);
class Point{
public:
double x, y;
Point ( double x = 0, double y = 0): x(x), y(y){}
Point operator + ( Point p ){ return Point(x + p.x, y + p.y); }
Point operator - ( Point p ){ return Point(x - p.x, y - p.y); }
Point operator * ( double a ){ return Point(x*a, y*a); }
Point operator / ( double a ){ return Point(x/a, y/a); }
double abs() { return sqrt(norm());}
double norm() { return x*x + y*y; }
bool operator < ( const Point &p ) const {
return x != p.x ? x < p.x : y < p.y;
}
bool operator == ( const Point &p ) const {
return fabs(x-p.x) < EPS && fabs(y-p.y) < EPS;
}
};
typedef Point Vector;
class Segment{
public:
Point p1, p2;
Segment(Point s = Point(), Point t = Point()): p1(s), p2(t){}
};
typedef Segment Line;
typedef vector<Point> Polygon;
double norm( Vector a ){ return a.x*a.x + a.y*a.y; }
double abs( Vector a ){ return sqrt(norm(a)); }
Point polar( double a, double r ){ return Point(cos(r)*a, sin(r)*a);}
double getDistance( Vector a, Vector b ){ return abs(a - b); }
double dot( Vector a, Vector b ){ return a.x*b.x + a.y*b.y; }
double cross( Vector a, Vector b ){ return a.x*b.y - a.y*b.x; }
double arg(Vector p){
return atan2(p.y, p.x);
}
static const int COUNTER_CLOCKWISE = 1;
static const int CLOCKWISE = -1;
static const int ONLINE_BACK = 2;
static const int ONLINE_FRONT = -2;
static const int ON_SEGMENT = 0;
int ccw( Point p0, Point p1, Point p2 ){
Vector a = p1 - p0;
Vector b = p2 - p0;
if ( cross(a, b) > EPS ) return COUNTER_CLOCKWISE;
if ( cross(a, b) < -EPS ) return CLOCKWISE;
if ( dot(a, b) < -EPS ) return ONLINE_BACK;
if ( norm(a) < norm(b) ) return ONLINE_FRONT;
return ON_SEGMENT;
}
Point getCrossPointLines( Line s1, Line s2){
Vector a = s1.p2 - s1.p1;
Vector base = s2.p2 - s2.p1;
return s1.p1 + a * cross(base, s2.p1 - s1.p1)/cross(base, a);
}
double getAngleTheta(Point p){
double polar = atan2(p.y, p.x);
double rad = (dle(0, polar))? polar : 2*acos(-1)+polar;
return rad*180.0/acos(-1);
}
double getAngle(Point p){
double polar = atan2(p.y, p.x);
return (dle(0, polar))? polar : 2*acos(-1)+polar;
}
Polygon cutPolygon( Polygon P, Line l ){
Polygon u;
for ( int i = 0; i < P.size(); i++ ){
Point a = P[i], b = P[(i+1)%P.size()];
if ( ccw(l.p1, l.p2, a) != CLOCKWISE ) u.push_back(a);
if ( ccw(l.p1, l.p2, a) * ccw(l.p1, l.p2, b) == -1 ){
u.push_back(getCrossPointLines(Segment(a, b), l));
}
}
return u;
}
Line getCutLine( Point p1, Point p2 ){
Vector v = p2 - p1;
v = polar(abs(v), arg(v)+PI/2.0);
double dx = (p2.x + p1.x)/2.0;
double dy = (p2.y + p1.y)/2.0;
return Line(Point(dx, dy), Point(v.x+dx, v.y+dy));
}
double getArea(Polygon p){
double sum = 0.0;
for(int i = 0; i < p.size(); i++){
sum += cross(p[i], p[(i+1)%p.size()]);
}
return abs(sum/2);
}
int main(){
double x1, y1, x2, y2, x3, y3;
Point P[3];
Polygon B;
int tcase = 1;
while(1){
cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;
if ( x1 == 0 && y1 == 0 && x2 == 0 && y2 == 0 && x3 == 0 && y3 == 0 ) break;
P[0] = Point(x1, y1);
P[1] = Point(x2, y2);
P[2] = Point(x3, y3);
B.clear();
B.push_back(Point(0, 0));
B.push_back(Point(10000, 0));
B.push_back(Point(10000, 10000));
B.push_back(Point(0, 10000));
B = cutPolygon(B, getCutLine(P[0], P[1]));
B = cutPolygon(B, getCutLine(P[0], P[2]));
printf("%d %.12lf\n", tcase++, getArea(B)/(100000000));
}
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
It has been noted that if some ants are put in the junctions of the graphene integer lattice then they will act in the following fashion: every minute at each junction (x, y) containing at least four ants a group of four ants will be formed, and these four ants will scatter to the neighbouring junctions (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1) — one ant in each direction. No other ant movements will happen. Ants never interfere with each other.
Scientists have put a colony of n ants into the junction (0, 0) and now they wish to know how many ants will there be at some given junctions, when the movement of the ants stops.
Input
First input line contains integers n (0 ≤ n ≤ 30000) and t (1 ≤ t ≤ 50000), where n is the number of ants in the colony and t is the number of queries. Each of the next t lines contains coordinates of a query junction: integers xi, yi ( - 109 ≤ xi, yi ≤ 109). Queries may coincide.
It is guaranteed that there will be a certain moment of time when no possible movements can happen (in other words, the process will eventually end).
Output
Print t integers, one per line — the number of ants at the corresponding junctions when the movement of the ants stops.
Examples
Input
1 3
0 1
0 0
0 -1
Output
0
1
0
Input
6 5
0 -2
0 -1
0 0
0 1
0 2
Output
0
1
2
1
0
Note
In the first sample the colony consists of the one ant, so nothing happens at all.
In the second sample the colony consists of 6 ants. At the first minute 4 ants scatter from (0, 0) to the neighbouring junctions. After that the process stops.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000, mi = 500;
const int dx[] = {1, 0, -1, 0};
const int dy[] = {0, 1, 0, -1};
int n, m, v[maxn][maxn];
void dfs(const int x, const int y) {
int w = v[x][y] >> 2;
v[x][y] &= 3;
if (w == 0) return;
for (int i = 0; i < 4; ++i) {
int a = x + dx[i];
int b = y + dy[i];
v[a][b] += w;
if (v[a][b] >= 4) dfs(a, b);
}
}
int main() {
while (scanf("%d%d", &n, &m) != EOF) {
v[mi][mi] = n;
dfs(mi, mi);
int x, y;
for (int i = 0; i < m; ++i) {
scanf("%d%d", &x, &y);
x += mi;
y += mi;
if (x >= 0 && x < maxn && y >= 0 && y < maxn)
printf("%d\n", v[x][y]);
else
printf("0\n");
}
}
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.
Input
The first line contains one positive integer n — the number of operations, that have been made by Vasya (1 ≤ n ≤ 100).
The next line contains the string s, consisting of n symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on i-th operation, s_i is equal to "-" (without quotes), if added, s_i is equal to "+" (without quotes).
Output
Print one integer — the minimal possible number of stones that can be in the pile after these n operations.
Examples
Input
3
---
Output
0
Input
4
++++
Output
4
Input
2
-+
Output
1
Input
5
++-++
Output
3
Note
In the first test, if Vasya had 3 stones in the pile at the beginning, after making operations the number of stones will be equal to 0. It is impossible to have less number of piles, so the answer is 0. Please notice, that the number of stones at the beginning can't be less, than 3, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).
In the second test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 4. It is impossible to have less number of piles because after making 4 operations the number of stones in the pile increases on 4 stones. So, the answer is 4.
In the third test, if Vasya had 1 stone in the pile at the beginning, after making operations the number of stones will be equal to 1. It can be proved, that it is impossible to have less number of stones after making the operations.
In the fourth test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n;
string s;
int main(void) {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> s;
int m = 0;
int a = 0;
for (int i = n - 1; i >= 0; i--) {
if (s[i] == '+')
m++;
else
m--;
a = max(a, m);
}
cout << a;
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Amr lives in Lala Land. Lala Land is a very beautiful country that is located on a coordinate line. Lala Land is famous with its apple trees growing everywhere.
Lala Land has exactly n apple trees. Tree number i is located in a position xi and has ai apples growing on it. Amr wants to collect apples from the apple trees. Amr currently stands in x = 0 position. At the beginning, he can choose whether to go right or left. He'll continue in his direction until he meets an apple tree he didn't visit before. He'll take all of its apples and then reverse his direction, continue walking in this direction until he meets another apple tree he didn't visit before and so on. In the other words, Amr reverses his direction when visiting each new apple tree. Amr will stop collecting apples when there are no more trees he didn't visit in the direction he is facing.
What is the maximum number of apples he can collect?
Input
The first line contains one number n (1 ≤ n ≤ 100), the number of apple trees in Lala Land.
The following n lines contains two integers each xi, ai ( - 105 ≤ xi ≤ 105, xi ≠ 0, 1 ≤ ai ≤ 105), representing the position of the i-th tree and number of apples on it.
It's guaranteed that there is at most one apple tree at each coordinate. It's guaranteed that no tree grows in point 0.
Output
Output the maximum number of apples Amr can collect.
Examples
Input
2
-1 5
1 5
Output
10
Input
3
-2 2
1 4
-1 3
Output
9
Input
3
1 9
3 5
7 10
Output
9
Note
In the first sample test it doesn't matter if Amr chose at first to go left or right. In both cases he'll get all the apples.
In the second sample test the optimal solution is to go left to x = - 1, collect apples from there, then the direction will be reversed, Amr has to go to x = 1, collect apples from there, then the direction will be reversed and Amr goes to the final tree x = - 2.
In the third sample test the optimal solution is to go right to x = 1, collect apples from there, then the direction will be reversed and Amr will not be able to collect anymore apples because there are no apple trees to his left.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
int getint() {
int t = 0, flag = 1;
char c = getchar();
while (c < '0' || c > '9' || c == '-') {
if (c == '-') flag = -1;
c = getchar();
}
while (c >= '0' && c <= '9') t = t * 10 + c - '0', c = getchar();
return t * flag;
}
int GCD(int m, int n) { return !m ? n : GCD(n % m, m); }
template <typename T>
string to_string(T value) {
ostringstream os;
os << value;
return os.str();
}
long long MultMod(long long a, long long b, long long MOD) {
a %= MOD;
b %= MOD;
long long ret = 0;
while (b) {
if (b & 1) {
ret += a;
if (ret >= MOD) ret -= MOD;
}
a = a << 1;
if (a >= MOD) a -= MOD;
b = b >> 1;
}
return ret;
}
int x, a, n, t, m;
vector<pair<int, int> > vp, vn;
int main() {
while (cin >> n) {
vp.clear(), vn.clear();
for (int i = 0; i < n; i++) {
cin >> x >> a;
if (x > 0)
vp.push_back({x, a});
else
vn.push_back({-x, a});
}
sort(vp.begin(), vp.end());
sort(vn.begin(), vn.end());
int ans = 0;
if (vp.size() == vn.size()) {
for (int i = 0; i < vp.size(); i++) ans += vp[i].second + vn[i].second;
} else {
int minsize = min(vp.size(), vn.size());
for (int i = 0; i < minsize; i++) ans += vp[i].second + vn[i].second;
if (vp.size() > vn.size())
ans += vp[minsize].second;
else
ans += vn[minsize].second;
}
cout << ans << endl;
}
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Vasya is developing his own programming language VPL (Vasya Programming Language). Right now he is busy making the system of exceptions. He thinks that the system of exceptions must function like that.
The exceptions are processed by try-catch-blocks. There are two operators that work with the blocks:
1. The try operator. It opens a new try-catch-block.
2. The catch(<exception_type>, <message>) operator. It closes the try-catch-block that was started last and haven't yet been closed. This block can be activated only via exception of type <exception_type>. When we activate this block, the screen displays the <message>. If at the given moment there is no open try-catch-block, then we can't use the catch operator.
The exceptions can occur in the program in only one case: when we use the throw operator. The throw(<exception_type>) operator creates the exception of the given type.
Let's suggest that as a result of using some throw operator the program created an exception of type a. In this case a try-catch-block is activated, such that this block's try operator was described in the program earlier than the used throw operator. Also, this block's catch operator was given an exception type a as a parameter and this block's catch operator is described later that the used throw operator. If there are several such try-catch-blocks, then the system activates the block whose catch operator occurs earlier than others. If no try-catch-block was activated, then the screen displays message "Unhandled Exception".
To test the system, Vasya wrote a program that contains only try, catch and throw operators, one line contains no more than one operator, the whole program contains exactly one throw operator.
Your task is: given a program in VPL, determine, what message will be displayed on the screen.
Input
The first line contains a single integer: n (1 ≤ n ≤ 105) the number of lines in the program. Next n lines contain the program in language VPL. Each line contains no more than one operator. It means that input file can contain empty lines and lines, consisting only of spaces.
The program contains only operators try, catch and throw. It is guaranteed that the program is correct. It means that each started try-catch-block was closed, the catch operators aren't used unless there is an open try-catch-block. The program has exactly one throw operator. The program may have spaces at the beginning of a line, at the end of a line, before and after a bracket, a comma or a quote mark.
The exception type is a nonempty string, that consists only of upper and lower case english letters. The length of the string does not exceed 20 symbols. Message is a nonempty string, that consists only of upper and lower case english letters, digits and spaces. Message is surrounded with quote marks. Quote marks shouldn't be printed. The length of the string does not exceed 20 symbols.
Length of any line in the input file does not exceed 50 symbols.
Output
Print the message the screen will show after the given program is executed.
Examples
Input
8
try
try
throw ( AE )
catch ( BE, "BE in line 3")
try
catch(AE, "AE in line 5")
catch(AE,"AE somewhere")
Output
AE somewhere
Input
8
try
try
throw ( AE )
catch ( AE, "AE in line 3")
try
catch(BE, "BE in line 5")
catch(AE,"AE somewhere")
Output
AE in line 3
Input
8
try
try
throw ( CE )
catch ( BE, "BE in line 3")
try
catch(AE, "AE in line 5")
catch(AE,"AE somewhere")
Output
Unhandled Exception
Note
In the first sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(BE,"BE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so the second block will be activated, because operator catch(AE,"AE somewhere") has exception type AE as parameter and operator catch(BE,"BE in line 3") has exception type BE.
In the second sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(AE,"AE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so both blocks can be activated, but only the first one will be activated, because operator catch(AE,"AE in line 3") is described earlier than catch(AE,"AE somewhere")
In the third sample there is no blocks that can be activated by an exception of type CE.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, l1, c1 = 0, k;
string z[100010], z1 = "", z2 = "", z3 = "";
bool v;
cin >> n;
cin.ignore();
for (int i = 0; i < n; i++) getline(cin, z[i]);
for (int i = 0; i < n; i++) {
l1 = z[i].length();
for (int j = 0; j <= l1 - 3; j++)
if (z[i][j] == 't' && z[i][j + 1] == 'r' && z[i][j + 2] == 'y')
c1++;
else if (z[i][j] >= 'a' && z[i][j] <= 'z')
break;
for (int j = 0; j <= l1 - 5; j++)
if (z[i][j] == 'c' && z[i][j + 1] == 'a' && z[i][j + 2] == 't' &&
z[i][j + 3] == 'c' && z[i][j + 4] == 'h')
c1--;
else if (z[i][j] >= 'a' && z[i][j] <= 'z')
break;
v = false;
for (int j = 0; j <= l1 - 5; j++) {
if (z[i][j] == 't' && z[i][j + 1] == 'h' && z[i][j + 2] == 'r' &&
z[i][j + 3] == 'o' && z[i][j + 4] == 'w') {
k = j + 5;
z1 = "";
while (!((z[i][k] >= 'a' && z[i][k] <= 'z') ||
(z[i][k] >= 'A' && z[i][k] <= 'Z')))
k++;
while (((z[i][k] >= 'a' && z[i][k] <= 'z') ||
(z[i][k] >= 'A' && z[i][k] <= 'Z'))) {
z1 += z[i][k];
k++;
}
k = i + 1;
v = true;
break;
} else if (z[i][j] >= 'a' && z[i][j] <= 'z')
break;
}
if (v) break;
}
v = false;
c1 = 0;
int f = 0;
for (int i = k; i < n; i++) {
for (int j = 0; j <= l1 - 3; j++)
if (z[i][j] == 't' && z[i][j + 1] == 'r' && z[i][j + 2] == 'y')
c1++;
else if (z[i][j] >= 'a' && z[i][j] <= 'z')
break;
for (int j = 0; j <= l1 - 5; j++)
if (z[i][j] == 'c' && z[i][j + 1] == 'a' && z[i][j + 2] == 't' &&
z[i][j + 3] == 'c' && z[i][j + 4] == 'h') {
if (c1 == 0) {
f = j + 5;
while (z[i][f] == '(' || z[i][f] == ' ') f++;
z2 = "";
while (z[i][f] != ' ' && z[i][f] != ',') {
z2 += z[i][f];
f++;
}
if (z1 == z2) {
v = true;
while (z[i][f] != '"') f++;
f++;
z3 = "";
while (z[i][f] != '"') {
z3 += z[i][f];
f++;
}
break;
}
} else
c1--;
} else if (z[i][j] >= 'a' && z[i][j] <= 'z')
break;
if (v) {
cout << z3;
return 0;
}
}
cout << "Unhandled Exception";
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a person to the chat ('Add' command).
* Remove a person from the chat ('Remove' command).
* Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
* +<name> for 'Add' command.
* -<name> for 'Remove' command.
* <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number — answer to the problem.
Examples
Input
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate
Output
9
Input
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate
Output
14
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string com;
map<string, bool> mp;
int ans = 0;
while (getline(cin, com)) {
if (com[0] == '+') {
com.erase(com.begin(), com.begin() + 1);
mp[com] = 1;
} else if (com[0] == '-') {
com.erase(com.begin(), com.begin() + 1);
mp[com] = 0;
} else {
int len = com.size() - com.find(':') - 1, cnt = 0;
for (map<string, bool>::iterator it = mp.begin(); it != mp.end(); it++) {
if (it->second) cnt++;
}
ans += cnt * len;
}
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that multiple elements can have equivalent keys.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print all values with the specified $key$.
* delete($key$): Delete all elements with the specified $key$.
* dump($L$, $R$): Print all elements formed by a pair of the key and the value such that the key is greater than or equal to $L$ and less than or equal to $R$ in lexicographic order.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consists of lower-case letters
* $L \leq R$ in lexicographic order
* The total number of elements printed by get operations does not exceed $500,000$
* The total number of elements printed by dump operations does not exceed $500,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
or
2 $key$
or
3 $L$ $R$
where the first digits 0, 1, 2 and 3 represent insert, get, delete and dump operations.
Output
For each get operation, print the corresponding values in the order of insertions.
For each dump operation, print the corresponding elements formed by a pair of the key and the value. For the dump operation, print the elements in ascending order of the keys, in case of a tie, in the order of insertions.
Example
Input
10
0 blue 6
0 red 1
0 blue 4
0 white 5
1 red
1 blue
2 red
1 black
1 red
3 w z
Output
1
6
4
white 5
### Response
```cpp
#include <iostream>
#include <map>
#include <set>
#include <string>
#define int long long
using namespace std;
multimap<string, int>m;
set<string>s;
signed main() {
int q; cin >> q;
for (int i = 0; i < q; i++) {
int p; string k, l, r;
cin >> p;
if (p == 0) {
cin >> k >> p;
s.insert(k); m.insert(make_pair(k, p));
}
else if (p == 1) {
cin >> k;
for (auto i = m.lower_bound(k); i != m.upper_bound(k); i++) cout << i -> second << endl;
}
else if (p == 2) {
cin >> k;
s.erase(k);
m.erase(m.equal_range(k).first, m.equal_range(k).second);
}
else {
cin >> l >> r;
for (auto i = m.lower_bound(l); i != m.upper_bound(r); i++)cout << i -> first << ' ' << i -> second << endl;
}
}
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.
Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy:
* Each piece should contain at least l numbers.
* The difference between the maximal and the minimal number on the piece should be at most s.
Please help Alexandra to find the minimal number of pieces meeting the condition above.
Input
The first line contains three space-separated integers n, s, l (1 ≤ n ≤ 105, 0 ≤ s ≤ 109, 1 ≤ l ≤ 105).
The second line contains n integers ai separated by spaces ( - 109 ≤ ai ≤ 109).
Output
Output the minimal number of strip pieces.
If there are no ways to split the strip, output -1.
Examples
Input
7 2 2
1 3 1 2 4 1 2
Output
3
Input
7 2 2
1 100 1 100 1 100 1
Output
-1
Note
For the first sample, we can split the strip into 3 pieces: [1, 3, 1], [2, 4], [1, 2].
For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = int(1e5) + 100;
int lmin, lmax, rmin, rmax, stmin[maxn], stmax[maxn], posmin[maxn],
posmax[maxn], f[maxn];
int n, s, l;
void ad(int i, int x) {
while (rmin > lmin && stmin[rmin - 1] >= x) rmin--;
rmin++;
stmin[rmin - 1] = x;
posmin[rmin - 1] = i;
while (rmax > lmax && stmax[rmax - 1] <= x) rmax--;
rmax++;
stmax[rmax - 1] = x;
posmax[rmax - 1] = i;
}
void update(int &v, int i) {
while ((stmax[lmax] - stmin[lmin] > s || f[v - 1] == -1) && (v <= i)) {
v++;
if (posmax[lmax] < v) lmax++;
if (posmin[lmin] < v) lmin++;
}
}
int main() {
cin >> n >> s >> l;
int v = 1;
for (int i = 1; i <= n; i++) f[i] = -1;
for (int i = 1; i <= n; i++) {
int x;
cin >> x;
ad(i, x);
update(v, i);
if (i - v + 1 >= l) f[i] = f[v - 1] + 1;
}
cout << f[n];
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
You are given a string A. Find a string B, where B is a palindrome and A is a subsequence of B.
A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "contest".
A palindrome is a string that reads the same forward or backward.
The length of string B should be at most 104. It is guaranteed that there always exists such string.
You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104.
Input
First line contains a string A (1 ≤ |A| ≤ 103) consisting of lowercase Latin letters, where |A| is a length of A.
Output
Output single line containing B consisting of only lowercase Latin letters. You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104. If there are many possible B, print any of them.
Examples
Input
aba
Output
aba
Input
ab
Output
aabaa
Note
In the first example, "aba" is a subsequence of "aba" which is a palindrome.
In the second example, "ab" is a subsequence of "aabaa" which is a palindrome.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int inf = INT_MAX;
const long long int infl = LLONG_MAX;
int main() {
std::ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
string s;
cin >> s;
cout << s;
int n = s.length();
for (int i = n - 1; i >= 0; i--) {
cout << s[i];
}
cout << endl;
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from 1 to n and then 3n times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements 7n+1 times instead of 3n times. Because it is more random, OK?!
You somehow get a test from one of these problems and now you want to know from which one.
Input
In the first line of input there is one integer n (10^{3} ≤ n ≤ 10^{6}).
In the second line there are n distinct integers between 1 and n — the permutation of size n from the test.
It is guaranteed that all tests except for sample are generated this way: First we choose n — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
Output
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
Example
Input
5
2 4 5 1 3
Output
Petr
Note
Please note that the sample is not a valid test (because of limitations for n) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.
Due to randomness of input hacks in this problem are forbidden.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[1000006];
int main() {
int n;
while (~scanf("%d", &n)) {
int cnt = 0;
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
}
for (int i = 1; i <= n; i++) {
if (a[i] == i) continue;
while (a[i] != i) {
cnt++;
swap(a[i], a[a[i]]);
}
}
if ((cnt % 2) == (n % 2))
puts("Petr");
else
puts("Um_nik");
}
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
A new set of desks just arrived, and it's about time! Things were getting quite cramped in the office. You've been put in charge of creating a new seating chart for the engineers. The desks are numbered, and you sent out a survey to the engineering team asking each engineer the number of the desk they currently sit at, and the number of the desk they would like to sit at (which may be the same as their current desk). Each engineer must either remain where they sit, or move to the desired seat they indicated in the survey. No two engineers currently sit at the same desk, nor may any two engineers sit at the same desk in the new seating arrangement.
How many seating arrangements can you create that meet the specified requirements? The answer may be very large, so compute it modulo 1000000007 = 109 + 7.
Input
Input will begin with a line containing N (1 ≤ N ≤ 100000), the number of engineers.
N lines follow, each containing exactly two integers. The i-th line contains the number of the current desk of the i-th engineer and the number of the desk the i-th engineer wants to move to. Desks are numbered from 1 to 2·N. It is guaranteed that no two engineers sit at the same desk.
Output
Print the number of possible assignments, modulo 1000000007 = 109 + 7.
Examples
Input
4
1 5
5 2
3 7
7 3
Output
6
Input
5
1 10
2 10
3 10
4 10
5 5
Output
5
Note
These are the possible assignments for the first example:
* 1 5 3 7
* 1 2 3 7
* 5 2 3 7
* 1 5 7 3
* 1 2 7 3
* 5 2 7 3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -f;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;
}
template <typename T>
inline void Max(T &a, T &b) {
if (a < b) a = b;
}
template <typename T>
inline void Min(T &a, T &b) {
if (a > b) a = b;
}
const double pi = (double)acos(-1.0);
const double eps = (double)1e-10;
const int INF = (int)0x3f3f3f3f;
const int MOD = (int)1e9 + 7;
const int MAXN = (int)2e5 + 10;
const int MAXM = (int)1e5 + 10;
int n;
int p[MAXN];
int cnt[MAXN];
int mark[MAXN];
int Find(int x) { return x == p[x] ? x : p[x] = Find(p[x]); }
void work() {
scanf("%d", &n);
for (int i = 1; i <= n * 2; i++) p[i] = i;
for (int i = 1; i <= n; i++) {
int x, y, u, v;
u = read();
v = read();
x = Find(u);
y = Find(v);
if (u == v) {
mark[x] = 1;
} else if (x == y) {
mark[x] = 2;
} else {
p[x] = y;
}
}
for (int i = 1; i <= n * 2; i++) {
if (mark[i] == 1) mark[Find(i)] = cnt[Find(i)] = 1;
if (mark[i] == 2) mark[Find(i)] = cnt[Find(i)] = 2;
}
for (int i = 1; i <= 2 * n; i++) {
int x = Find(i);
if (mark[x]) continue;
cnt[x]++;
}
long long ans = 1;
for (int i = 1; i <= n * 2; i++)
if (p[i] == i) {
ans = ans * cnt[i] % MOD;
}
printf("%I64d\n", ans);
}
int main() {
work();
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Amr bought a new video game "Guess Your Way Out! II". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.
Let's index all the nodes of the tree such that
* The root is number 1
* Each internal node i (i ≤ 2h - 1 - 1) will have a left child with index = 2i and a right child with index = 2i + 1
The level of a node is defined as 1 for a root, or 1 + level of parent of the node otherwise. The vertices of the level h are called leaves. The exit to the maze is located at some leaf node n, the player doesn't know where the exit is so he has to guess his way out!
In the new version of the game the player is allowed to ask questions on the format "Does the ancestor(exit, i) node number belong to the range [L, R]?". Here ancestor(v, i) is the ancestor of a node v that located in the level i. The game will answer with "Yes" or "No" only. The game is designed such that it doesn't always answer correctly, and sometimes it cheats to confuse the player!.
Amr asked a lot of questions and got confused by all these answers, so he asked you to help him. Given the questions and its answers, can you identify whether the game is telling contradictory information or not? If the information is not contradictory and the exit node can be determined uniquely, output its number. If the information is not contradictory, but the exit node isn't defined uniquely, output that the number of questions is not sufficient. Otherwise output that the information is contradictory.
Input
The first line contains two integers h, q (1 ≤ h ≤ 50, 0 ≤ q ≤ 105), the height of the tree and the number of questions respectively.
The next q lines will contain four integers each i, L, R, ans (1 ≤ i ≤ h, 2i - 1 ≤ L ≤ R ≤ 2i - 1, <image>), representing a question as described in the statement with its answer (ans = 1 if the answer is "Yes" and ans = 0 if the answer is "No").
Output
If the information provided by the game is contradictory output "Game cheated!" without the quotes.
Else if you can uniquely identify the exit to the maze output its index.
Otherwise output "Data not sufficient!" without the quotes.
Examples
Input
3 1
3 4 6 0
Output
7
Input
4 3
4 10 14 1
3 6 6 0
2 3 3 1
Output
14
Input
4 2
3 4 6 1
4 12 15 1
Output
Data not sufficient!
Input
4 2
3 4 5 1
2 3 3 1
Output
Game cheated!
Note
Node u is an ancestor of node v if and only if
* u is the same node as v,
* u is the parent of node v,
* or u is an ancestor of the parent of node v.
In the first sample test there are 4 leaf nodes 4, 5, 6, 7. The first question says that the node isn't in the range [4, 6] so the exit is node number 7.
In the second sample test there are 8 leaf nodes. After the first question the exit is in the range [10, 14]. After the second and the third questions only node number 14 is correct. Check the picture below to fully understand.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long h, q, a, l1, r1, x, f[51], M, lm, rm, s, lh, rh, mm;
pair<long long, long long> t, k[100010], t1;
vector<pair<long long, long long> > w, la;
int main() {
cin >> h >> q;
f[0] = 1;
for (long long i = 1; i <= h; i++) {
f[i] = f[i - 1] * 2;
}
M = f[h] + 1;
lm = f[h - 1];
rm = f[h] - 1;
s = 0;
for (long long i = 1; i <= q; i++) {
cin >> a >> l1 >> r1 >> x;
long long ll, rr;
ll = l1 * f[h - a];
rr = ll + (r1 - l1 + 1) * f[h - a] - 1;
if ((ll > rm || rr < lm) && x == 1) {
cout << "Game cheated!";
return 0;
}
if (x == 1) {
lm = max(ll, lm);
rm = min(rm, rr);
}
if (x == 0) {
s++;
k[s] = make_pair(ll, rr);
}
}
lh = lm;
rh = rm;
for (long long i = 1; i <= s; i++) {
w.push_back(make_pair(k[i].first, -1 * i));
w.push_back(make_pair(k[i].second, i));
if (k[i].first < lm && k[i].second > rm) {
cout << "Game cheated!";
return 0;
}
}
long long cd = lm, cc = rm, s1 = 0, s2 = 0, e = -1;
mm = 0;
if (!w.empty()) {
sort(w.begin(), w.end());
la.push_back(make_pair(lm - 1, 1));
la.push_back(make_pair(rm + 1, -1));
for (long long i = 0; i <= w.size() - 1; i++) {
if (w[i].second < 0) {
e = k[-1 * w[i].second].second;
if (w[i].first >= lm && w[i].first <= rm)
la.push_back(make_pair(w[i].first, -1));
while (true) {
if (w[i].first == e && w[i].second > 0) break;
i++;
if (w[i].second < 0) {
long long kx = k[-1 * w[i].second].second;
if (kx <= rm) e = max(e, kx);
}
}
if (e >= lm && e <= rm) la.push_back(make_pair(e, 1));
}
}
sort(la.begin(), la.end());
for (long long i = 1; i < la.size(); i++) {
if (la[i].second == -1 && la[i - 1].second == 1) {
if (la[i].first - 1 >= la[i - 1].first + 1) {
cd = la[i - 1].first + 1;
cc = la[i].first - 1;
mm += cc - cd + 1;
}
}
}
} else {
mm += cc - cd + 1;
}
if (mm == 0)
cout << "Game cheated!";
else if (mm > 1)
cout << "Data not sufficient!";
else
cout << cd;
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
The research center Q has developed a new multi-core processor. The processor consists of n cores and has k cells of cache memory. Consider the work of this processor.
At each cycle each core of the processor gets one instruction: either do nothing, or the number of the memory cell (the core will write an information to the cell). After receiving the command, the core executes it immediately. Sometimes it happens that at one cycle, multiple cores try to write the information into a single cell. Unfortunately, the developers did not foresee the possibility of resolving conflicts between cores, so in this case there is a deadlock: all these cores and the corresponding memory cell are locked forever. Each of the locked cores ignores all further commands, and no core in the future will be able to record an information into the locked cell. If any of the cores tries to write an information into some locked cell, it is immediately locked.
The development team wants to explore the deadlock situation. Therefore, they need a program that will simulate the processor for a given set of instructions for each core within m cycles . You're lucky, this interesting work is entrusted to you. According to the instructions, during the m cycles define for each core the number of the cycle, during which it will become locked. It is believed that initially all cores and all memory cells are not locked.
Input
The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 100). Then follow n lines describing instructions. The i-th line contains m integers: xi1, xi2, ..., xim (0 ≤ xij ≤ k), where xij is the instruction that must be executed by the i-th core at the j-th cycle. If xij equals 0, then the corresponding instruction is «do nothing». But if xij is a number from 1 to k, then the corresponding instruction is «write information to the memory cell number xij».
We assume that the cores are numbered from 1 to n, the work cycles are numbered from 1 to m and the memory cells are numbered from 1 to k.
Output
Print n lines. In the i-th line print integer ti. This number should be equal to 0 if the i-th core won't be locked, or it should be equal to the number of the cycle when this core will be locked.
Examples
Input
4 3 5
1 0 0
1 0 2
2 3 1
3 2 0
Output
1
1
3
0
Input
3 2 2
1 2
1 2
2 2
Output
1
1
0
Input
1 1 1
0
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int ta[1000], ya[1000], t[1000], n, m, k, a[1000][1000];
int main() {
cin >> n >> m >> k;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
}
}
for (int j = 1; j <= m; j++) {
for (int i = 0; i <= k; i++) {
t[i] = 0;
}
for (int i = 1; i <= n; i++) {
if (ya[i] == 0) {
if (ta[a[i][j]] == 0) {
t[a[i][j]]++;
} else {
ya[i] = j;
}
}
}
for (int i = 1; i <= k; i++) {
if (t[i] > 1) {
ta[i] = 1;
for (int l = 1; l <= n; l++) {
if (a[l][j] == i && ya[l] == 0) {
ya[l] = j;
}
}
}
}
}
for (int i = 1; i <= n; i++) {
cout << ya[i] << endl;
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
At school Vasya got an impressive list of summer reading books. Unlike other modern schoolchildren, Vasya loves reading, so he read some book each day of the summer.
As Vasya was reading books, he was making notes in the Reader's Diary. Each day he wrote the orderal number of the book he was reading. The books in the list are numbered starting from 1 and Vasya was reading them in the order they go in the list. Vasya never reads a new book until he finishes reading the previous one. Unfortunately, Vasya wasn't accurate and some days he forgot to note the number of the book and the notes for those days remained empty.
As Vasya knows that the literature teacher will want to check the Reader's Diary, so he needs to restore the lost records. Help him do it and fill all the blanks. Vasya is sure that he spends at least two and at most five days for each book. Vasya finished reading all the books he had started. Assume that the reading list contained many books. So many, in fact, that it is impossible to read all of them in a summer. If there are multiple valid ways to restore the diary records, Vasya prefers the one that shows the maximum number of read books.
Input
The first line contains integer n — the number of summer days (2 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ... an — the records in the diary in the order they were written (0 ≤ ai ≤ 105). If Vasya forgot to write the number of the book on the i-th day, then ai equals 0.
Output
If it is impossible to correctly fill the blanks in the diary (the diary may contain mistakes initially), print "-1".
Otherwise, print in the first line the maximum number of books Vasya could have read in the summer if we stick to the diary. In the second line print n integers — the diary with correctly inserted records. If there are multiple optimal solutions, you can print any of them.
Examples
Input
7
0 1 0 0 0 3 0
Output
3
1 1 2 2 3 3 3
Input
8
0 0 0 0 0 0 0 0
Output
4
1 1 2 2 3 3 4 4
Input
4
0 0 1 0
Output
1
1 1 1 1
Input
4
0 0 0 3
Output
-1
### 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;
}
int ok(int l, int r, int a, int b) {
if (l > r) {
if ((a + 1) == b) return 1;
return 0;
}
int gap = r - l + 1;
int lage = b - a - 1;
if (5 * lage < gap) return 0;
if ((2 * lage) > gap) return 0;
return 1;
}
int a[400007];
int n;
int dp[400007][7];
int P[400007];
int N[400007];
int ar[400007];
int lol(int p, int pv) {
if (p == (n + 1)) {
int vl = a[P[p]];
int lstend = P[p] + ar[P[p]] + pv;
if (P[p] == 0) lstend++;
int gap = p - lstend;
if (gap == 1) return -2000000000;
return vl + (gap / 2);
}
int &res = dp[p][pv];
if (res != -1) return res;
res = -2000000000;
int lstend = P[p] + ar[P[p]] + pv;
if (P[p] == 0) lstend++;
for (int bac = 0; bac < 5; bac++) {
for (int fr = 0; fr < 5; fr++) {
if ((bac + fr + 1) > 5) continue;
if ((bac + fr + 1) < 2) continue;
if ((p - bac) < lstend) continue;
if ((p + fr) >= N[p]) continue;
if ((p + fr) < (p + ar[p] - 1)) continue;
int tp = ok(lstend, p - bac - 1, a[P[p]], a[p]);
if (tp) {
res = max(res, lol(N[p], (p + fr - (p + ar[p] - 1))));
}
}
}
return res;
}
void Fill(int l, int r, int st, int ed) {
if (l > r) return;
int gap = r - l + 1;
int vl = ed - st + 1;
int mid = gap / vl;
int rm = gap % vl;
for (int i = l; i <= r; i += mid) {
for (int j = i; j < i + mid; j++) {
a[j] = st;
}
if (rm) {
rm--;
a[i + mid] = st;
i++;
}
st++;
}
}
void path(int p, int pv) {
if (p == (n + 1)) {
int vl = a[P[p]];
int lstend = P[p] + ar[P[p]] + pv;
if (P[p] == 0) lstend++;
int gap = p - lstend;
Fill(lstend, p - 1, vl + 1, vl + (gap / 2));
return;
}
int res = lol(p, pv);
int lstend = P[p] + ar[P[p]] + pv;
if (P[p] == 0) lstend++;
int f = 0;
for (int bac = 0; bac < 5; bac++) {
for (int fr = 0; fr < 5; fr++) {
if ((bac + fr + 1) > 5) continue;
if ((bac + fr + 1) < 2) continue;
if ((p - bac) < lstend) continue;
if ((p + fr) >= N[p]) continue;
if ((p + fr) < (p + ar[p] - 1)) continue;
int tp = ok(lstend, p - bac - 1, a[P[p]], a[p]);
if (tp) {
int kk = lol(N[p], (p + fr - (p + ar[p] - 1)));
if (kk == res) {
f = 1;
for (int i = p; i >= p - bac; i--) a[i] = a[p];
for (int i = p; i <= p + fr; i++) a[i] = a[p];
Fill(lstend, p - bac - 1, a[P[p]] + 1, a[p] - 1);
path(N[p], (p + fr - (p + ar[p] - 1)));
break;
}
}
}
if (f) break;
}
return;
}
int Nxt(int p) {
int tot = 0;
while (a[p] == a[p + tot]) {
tot++;
}
return tot;
}
int Next(int p) {
int tot = 0;
while ((p + tot) <= n && (a[p] == a[p + tot] || !a[p + tot])) {
tot++;
}
return p + tot;
}
int main() {
n = in<int>();
for (int i = 1; i < n + 1; i++) {
a[i] = in<int>();
}
int pv = -1;
int lst = 0;
for (int i = 1; i <= n; i++) {
if (a[i]) {
if (a[i] == pv) {
for (int j = lst + 1; j < i + 1; j++) a[j] = a[i];
}
lst = i;
pv = a[i];
}
}
int f = 0;
int fs = -1;
for (int i = 1; i <= n;) {
if (a[i]) {
int tp = Nxt(i);
if (tp > 5) {
printf("-1\n");
exit(0);
}
int tp1 = tp;
ar[i] = tp;
tp = Next(i);
N[i] = tp;
P[tp] = i;
f = 1;
if (fs == -1) {
fs = i;
}
i += tp1;
} else
i++;
}
if (fs == -1) fs = n + 1;
memset(dp, -1, sizeof(dp));
int ans = lol(fs, 0);
if (ans <= -2000000000) ans = -1;
cout << ans << endl;
if (ans == -1) exit(0);
path(fs, 0);
for (int i = 1; i < n + 1; i++) {
printf("%d ", a[i]);
}
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
There are n segments [l_i, r_i] for 1 ≤ i ≤ n. You should divide all segments into two non-empty groups in such way that there is no pair of segments from different groups which have at least one common point, or say that it's impossible to do it. Each segment should belong to exactly one group.
To optimize testing process you will be given multitest.
Input
The first line contains one integer T (1 ≤ T ≤ 50000) — the number of queries. Each query contains description of the set of segments. Queries are independent.
First line of each query contains single integer n (2 ≤ n ≤ 10^5) — number of segments. It is guaranteed that ∑{n} over all queries does not exceed 10^5.
The next n lines contains two integers l_i, r_i per line (1 ≤ l_i ≤ r_i ≤ 2 ⋅ 10^5) — the i-th segment.
Output
For each query print n integers t_1, t_2, ..., t_n (t_i ∈ \{1, 2\}) — for each segment (in the same order as in the input) t_i equals 1 if the i-th segment will belongs to the first group and 2 otherwise.
If there are multiple answers, you can print any of them. If there is no answer, print -1.
Example
Input
3
2
5 5
2 3
3
3 5
2 3
2 3
3
3 3
4 4
5 5
Output
2 1
-1
1 1 2
Note
In the first query the first and the second segments should be in different groups, but exact numbers don't matter.
In the second query the third segment intersects with the first and the second segments, so they should be in the same group, but then the other group becomes empty, so answer is -1.
In the third query we can distribute segments in any way that makes groups non-empty, so any answer of 6 possible is correct.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
unsigned long long t;
cin >> t;
while (t--) {
int n;
cin >> n;
map<int, vector<int>> mp;
vector<pair<int, pair<int, int>>> vv;
vector<int> ans(n, 0);
for (unsigned long long i = 0; i < n; i++) {
int l, r;
cin >> l >> r;
vv.push_back({l, {r, i}});
}
sort(vv.begin(), vv.end());
for (unsigned long long i = 0; i < n; i++) {
int l = vv[i].first, r = vv[i].second.first;
int idx = vv[i].second.second;
mp[l].push_back(idx);
mp[r + 1].push_back(-1);
}
int cn = 0;
int change = 1;
int once = 0;
for (auto i : mp) {
for (auto j : i.second) {
if (j == -1)
cn--;
else
ans[j] = change, once = 1, cn++;
if (once == 1 && cn == 0) change = 2;
}
}
int theek = 0;
for (unsigned long long i = 0; i < n; i++) {
if (ans[i] == 2) theek++;
}
if (theek == 0) {
cout << -1 << endl;
} else {
for (int i = 0; i < ans.size(); i++) cout << ans[i] << " ";
cout << endl;
}
}
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Qingshan and Daniel are going to play a card game. But it will be so boring if only two persons play this. So they will make n robots in total to play this game automatically. Robots made by Qingshan belong to the team 1, and robots made by Daniel belong to the team 2. Robot i belongs to team t_i. Before the game starts, a_i cards are given for robot i.
The rules for this card game are simple:
* Before the start, the robots are arranged in a circle in the order or their indices. The robots will discard cards in some order, in each step one robot discards a single card. When the game starts, robot 1 will discard one of its cards. After that, robots will follow the following rules:
* If robot i discards the card last, the nearest robot whose team is opposite from i's will discard the card next. In another word j will discard a card right after i, if and only if among all j that satisfy t_i≠ t_j, dist(i,j) (definition is below) is minimum.
* The robot who has no cards should quit the game immediately. This robot won't be considered in the next steps.
* When no robot can discard the card next, the game ends.
We define the distance from robot x to robot y as dist(x,y)=(y-x+n)mod n. It is similar to the oriented distance on the circle.
For example, when n=5, the distance from 1 to 3 is dist(1,3)=(3-1+5)mod 5=2, the distance from 3 to 1 is dist(3,1)=(1-3+5)mod 5 =3.
Later, Qingshan finds out that it will take so much time to see how robots play. She wants to know the result as quickly as possible. You, as Qingshan's fan, are asked to calculate an array [ans_1,ans_2,…,ans_n] — ans_i is equal to the number of cards, that i-th robot will discard during the game. You need to hurry!
To avoid the large size of the input, the team and the number of cards of each robot will be generated in your code with some auxiliary arrays.
Input
The first line contains one integer n (1 ≤ n ≤ 5⋅ 10^6) — the number of robots playing this game.
The second line contains one integer m (1 ≤ m ≤ min(n,200 000)).
Each of the next m line contains four integers p_i, k_i, b_i, w_i (1 ≤ p_i ≤ n, 1 ≤ k_i ≤ 10^9+7, 0 ≤ b_i ,w_i< k_i). It's guaranteed that p_m=n and p_{j-1}<p_{j} (2 ≤ j ≤ m).
Arrays a_j and t_j should be generated by the following pseudo code:
seed = 0
base = 0
function rnd():
ret = seed
seed = (seed * base + 233) mod 1000000007
return ret
p[0] = 0
for i = 1 to m:
seed = b[i]
base = w[i]
for j = p[i - 1] + 1 to p[i]:
t[j] = (rnd() mod 2) + 1
a[j] = (rnd() mod k[i]) + 1
Output
Print a single integer \left( ∏_{i=1}^{n} ((ans_i ⊕ i^2)+1)\right) mod 10^9+7, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Examples
Input
3
3
1 5 2 3
2 7 1 2
3 2 1 1
Output
100
Input
5000000
2
1919810 998244353 114514 19260817
5000000 233333333 623532 7175
Output
800210675
Input
1
1
1 1 0 0
Output
1
Note
In the first test case a=[5,5,1] and t=[1,2,2].
The robot 1 discards the card first.
Then robot 2 discards the card next. Robot 3 doesn't discard the card next because dist(1,2)<dist(1,3).
Then robot 1 discards the card next. Robot 3 doesn't discard the card next because t_2=t_3.
If we write down the index of the robot who discards a card in time order, it will be the sequence [1,2,1,2,1,2,1,2]. So robots 1, 2 and 3 discard 5, 5 and 0 cards, respectively. And the answer is (((5 ⊕ 1^2)+1)×((5 ⊕ 2^2)+1)×((0 ⊕ 3^2)+1)) mod 10^9+7=(5× 2 × 10)mod 10^9+7=100.
### Response
```cpp
#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 1000000007
#define LL long long
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=5e6+11;
const int MAXM=2e5+11;
int col[MAXN],ret,seed,base,A[MAXN],B[MAXN],N,M,p[MAXM],k[MAXM],b[MAXM],w[MAXM];
int rnd(){
ret=seed,seed=(LL)((LL)seed*base+233)%mod; return ret;
}
signed main(){
//freopen("A.in","r",stdin);
N=read(),M=read(); for(int i=1;i<=M;i++) p[i]=read(),k[i]=read(),b[i]=read(),w[i]=read();
p[0]=0; for(int i=1;i<=M;i++){seed=b[i],base=w[i];for(int j=p[i-1]+1;j<=p[i];j++) col[j]=(rnd()%2)+1,B[j]=A[j]=(rnd()%k[i])+1;}
int res1=0,res2=0;
for(int i=1;i<=N;i++) if(col[i]==1) res1+=A[i];else res2+=A[i];
int ps=0; if(res1!=res2){
if(res1<res2) ps=1; else ps=2;
}else ps=col[1];
int be=0,res=(ps==1)?res1:res2;
//for(int i=1;i<=N;i++) cerr<<col[i]<<" ";cerr<<endl;
//for(int i=1;i<=N;i++) cerr<<A[i]<<" ";cerr<<endl;
int cnt=0;
if(col[1]==ps) be=1;
else {A[1]--; for(int i=1;i<=N;i++) if(col[i]==ps){be=i;break;}}
//for(int i=1;i<=N;i++) cerr<<A[i]<<" ";cerr<<endl;
while(res||cnt){
if(A[be]){
if(col[be]==ps){cnt+=A[be];res-=A[be];A[be]=0;}
else{
int w=min(A[be],cnt); A[be]-=w;
cnt-=w;
}
} be++; if(be==N+1) be=1;
}
LL Ans=1;
//for(int i=1;i<=N;i++) cerr<<B[i]-A[i]<<" ";cerr<<"\n";
for(int i=1;i<=N;i++) Ans*=(LL)((LL)((B[i]-A[i])^(LL)(i*i))+1)%mod,Ans%=mod;
printf("%lld\n",Ans); return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Write a program which reads a $n \times m$ matrix $A$ and a $m \times l$ matrix $B$, and prints their product, a $n \times l$ matrix $C$. An element of matrix $C$ is obtained by the following formula:
\\[ c_{ij} = \sum_{k=1}^m a_{ik}b_{kj} \\]
where $a_{ij}$, $b_{ij}$ and $c_{ij}$ are elements of $A$, $B$ and $C$ respectively.
Note
解説
Constraints
* $1 \leq n, m, l \leq 100$
* $0 \leq a_{ij}, b_{ij} \leq 10000$
Input
In the first line, three integers $n$, $m$ and $l$ are given separated by space characters
In the following lines, the $n \times m$ matrix $A$ and the $m \times l$ matrix $B$ are given.
Output
Print elements of the $n \times l$ matrix $C$ ($c_{ij}$). Print a single space character between adjacent elements.
Example
Input
3 2 3
1 2
0 3
4 5
1 2 1
0 3 2
Output
1 8 5
0 9 6
4 23 14
### Response
```cpp
#include <iostream>
using namespace std;
int main()
{
int n = 0, m = 0, l = 0, a[100][100] = { 0 }, b[100][100] = { 0 };
cin >> n >> m >> l;
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++)
cin >> a[i][j];
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < l; j++)
cin >> b[i][j];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < l; j++) {
long t = 0;
if (j > 0)
cout << " ";
for (int k = 0; k < m; k++)
t += a[i][k] * b[k][j];
cout << t;
}
cout << endl;
}
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Carol is currently curling.
She has n disks each with radius r on the 2D plane.
Initially she has all these disks above the line y = 10100.
She then will slide the disks towards the line y = 0 one by one in order from 1 to n.
When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk.
Compute the y-coordinates of centers of all the disks after all disks have been pushed.
Input
The first line will contain two integers n and r (1 ≤ n, r ≤ 1 000), the number of disks, and the radius of the disks, respectively.
The next line will contain n integers x1, x2, ..., xn (1 ≤ xi ≤ 1 000) — the x-coordinates of the disks.
Output
Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6.
Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates.
Example
Input
6 2
5 5 6 8 3 12
Output
2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613
Note
The final positions of the disks will look as follows:
<image>
In particular, note the position of the last disk.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
double r;
cin >> n >> r;
vector<double> x(n);
for (int i = 0; i < (int)(n); ++i) cin >> x[i];
vector<double> y(n, 0);
for (int i = 0; i < (int)(n); ++i) {
y[i] = r;
for (int j = 0; j < (int)(i); ++j) {
if (abs(x[i] - x[j]) - 0.000000000001 < 2.0 * r) {
y[i] = max(y[i], y[j] + sqrt(4.0 * r * r -
abs(x[i] - x[j]) * abs(x[i] - x[j])));
}
}
}
for (int i = 0; i < (int)(n); ++i) {
if (i) printf(" ");
printf("%.9f", y[i]);
}
printf("\n");
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Let's call an array consisting of n integer numbers a1, a2, ..., an, beautiful if it has the following property:
* consider all pairs of numbers x, y (x ≠ y), such that number x occurs in the array a and number y occurs in the array a;
* for each pair x, y must exist some position j (1 ≤ j < n), such that at least one of the two conditions are met, either aj = x, aj + 1 = y, or aj = y, aj + 1 = x.
Sereja wants to build a beautiful array a, consisting of n integers. But not everything is so easy, Sereja's friend Dima has m coupons, each contains two integers qi, wi. Coupon i costs wi and allows you to use as many numbers qi as you want when constructing the array a. Values qi are distinct. Sereja has no coupons, so Dima and Sereja have made the following deal. Dima builds some beautiful array a of n elements. After that he takes wi rubles from Sereja for each qi, which occurs in the array a. Sereja believed his friend and agreed to the contract, and now he is wondering, what is the maximum amount of money he can pay.
Help Sereja, find the maximum amount of money he can pay to Dima.
Input
The first line contains two integers n and m (1 ≤ n ≤ 2·106, 1 ≤ m ≤ 105). Next m lines contain pairs of integers. The i-th line contains numbers qi, wi (1 ≤ qi, wi ≤ 105).
It is guaranteed that all qi are distinct.
Output
In a single line print maximum amount of money (in rubles) Sereja can pay.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5 2
1 2
2 3
Output
5
Input
100 3
1 2
2 1
3 1
Output
4
Input
1 2
1 1
2 100
Output
100
Note
In the first sample Sereja can pay 5 rubles, for example, if Dima constructs the following array: [1, 2, 1, 2, 2]. There are another optimal arrays for this test.
In the third sample Sereja can pay 100 rubles, if Dima constructs the following array: [2].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
const double eps = 1e-8;
long long cont(long long n) {
long long ans = (n - 1);
ans = ans * (n / 2);
ans += ((n + 1) / 2);
return ans;
}
long long solve(long long aval, long long mx) {
long long lo = 1, hi = mx;
for (long long i = mx; i >= 1; i--)
if (cont(i) <= aval) return i;
return lo;
}
vector<long long> tp;
int main() {
ios_base::sync_with_stdio(0);
long long aval, m;
cin >> aval >> m;
tp.resize(m);
int a;
for (int i = 0; i < m; i++) {
cin >> a >> tp[i];
}
sort(tp.begin(), tp.end());
reverse(tp.begin(), tp.end());
long long can = solve(aval, m);
long long ans = 0;
for (int i = 0; i < can; i++) ans += tp[i];
cout << ans << endl;
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, <image>) — the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
### Response
```cpp
#include <bits/stdc++.h>
#pragma comment(linker, ”/ STACK : 38777216“
using namespace std;
const int N = 150005;
const int inf = 1000 * 1000 * 1000;
const int mod = 1000 * 1000 * 1000 + 7;
int n, m;
long long q, M;
vector<int> g[N];
bool used[N];
void dfs(int v) {
q++;
used[v] = true;
for (int i = 0; i < g[v].size(); i++) {
int to = g[v][i];
if (used[to]) continue;
dfs(to);
}
}
int main() {
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int a, b;
scanf("%d%d", &a, &b);
g[a].push_back(b);
g[b].push_back(a);
}
for (int i = 1; i <= n; i++) {
if (used[i]) continue;
q = 0;
dfs(i);
M += (q * (q - 1)) / (2ll);
}
if (M == (long long)m)
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
Input
The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.
Output
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
Examples
Input
6
549871
Output
54-98-71
Input
7
1198733
Output
11-987-33
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, i, j;
char str[105];
cin >> n;
cin >> str;
i = 0;
while (i < n - 1) {
if ((n - 1) - (i) == 2) {
cout << str[i] << str[i + 1] << str[i + 2];
i = i + 3;
} else {
cout << str[i] << str[i + 1];
i = i + 2;
}
if (i < n - 1) cout << "-";
}
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 × n grid where each row is a permutation of the numbers 1,2,3,…,n.
The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column.
Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo 10^9+7.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains a single integer n (2 ≤ n ≤ 4 ⋅ 10^5).
The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers 1,2,3,…,n and the numbers in each column and row will be pairwise distinct.
It is guaranteed that the sum of n over all test cases does not exceed 4 ⋅ 10^5.
Output
For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo 10^9+7.
The answer for each test case should be on a separate line.
Example
Input
2
4
1 4 2 3
3 2 1 4
8
2 6 5 1 4 3 7 8
3 8 7 5 1 2 4 6
Output
2
8
Note
The two possible puzzle configurations for example 1 are:
* [1,4,2,3] in the first row and [3,2,1,4] in the second;
* [3,2,1,4] in the first row and [1,4,2,3] in the second.
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
#define peace ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define ll long long
#define endl "\n"
#define fl(i,a,b) for(int i=a;i<b;i++)
#define rfl(i,a,b) for(int i=a;i>b;i--)
#define cases() ll t;cin>>t; while(t--)
#define sz(x) ((ll)(x).size())
#define all(v) v.begin(),v.end()
#define get(a,n) fl(i,0,n) cin>>a[i];
#define pr(a,n,st) fl(i,st,n) cout<<a[i]<<" "; cout<<endl;
#define prt(a,n,m) fl(i,0,n) fl(j,0,m) cout<<a[i][j]<<" \n"[j==m-1];
#define pb push_back
#define ff first
#define ss second
#define nl cout<<endl;
typedef pair<int,int>pairs;
#define de(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
cout << *it << " = " << a << endl;
err(++it, args...);
}
const int MOD=1e9+7, N=4e5+5, B = 32;
ll modExp(ll b, ll p) {
ll res = 1;
while(p > 0) {
if(p & 1) res = (res * b) % MOD;
b = (b * b) % MOD, p >>= 1;
}
return res;
}
int par[N], rk[N];
void init(int v) {
par[v] = v;
rk[v] = 1;
}
int find(int v) {
return v == par[v] ? v : par[v] = find(par[v]);
}
void join(int u, int v) {
u = find(u), v = find(v);
if(u != v) {
if(rk[u] < rk[v]) swap(u, v);
par[v] = u;
rk[u] += rk[v];
}
}
void solve() {
int n; cin >> n;
fl(i, 1, n + 1) init(i);
int a[2][n];
fl(i, 0, 2) {
fl(j, 0, n) {
cin >> a[i][j];
}
}
fl(i, 0, n) {
join(a[0][i], a[1][i]);
}
set<int> st;
fl(i, 0, n) {
st.insert(find(a[0][i]));
}
cout << modExp(2ll, sz(st)) << endl;
}
int main() {
peace;
#ifndef ONLINE_JUDGE
freopen("inputf.in", "r", stdin); freopen("outputf.in", "w", stdout);
#endif
cases()
solve();
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
It's that time of the year when the Russians flood their countryside summer cottages (dachas) and the bus stop has a lot of people. People rarely go to the dacha on their own, it's usually a group, so the people stand in queue by groups.
The bus stop queue has n groups of people. The i-th group from the beginning has ai people. Every 30 minutes an empty bus arrives at the bus stop, it can carry at most m people. Naturally, the people from the first group enter the bus first. Then go the people from the second group and so on. Note that the order of groups in the queue never changes. Moreover, if some group cannot fit all of its members into the current bus, it waits for the next bus together with other groups standing after it in the queue.
Your task is to determine how many buses is needed to transport all n groups to the dacha countryside.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 100). The next line contains n integers: a1, a2, ..., an (1 ≤ ai ≤ m).
Output
Print a single integer — the number of buses that is needed to transport all n groups to the dacha countryside.
Examples
Input
4 3
2 3 2 1
Output
3
Input
3 4
1 2 1
Output
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void cp() {
ios ::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
}
int main() {
cp();
long long n;
cin >> n;
;
long long m;
cin >> m;
;
long long a[n];
for (long long i = 0; i < n; i++) cin >> a[i];
long long ans = 1;
long long ca = 0;
for (long long i = 0; i < n; i++) {
ca += (a[i]);
if (ca > m) {
ca = a[i];
ans++;
}
}
cout << ans << endl;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
You are given the array of integer numbers a0, a1, ..., an - 1. For each element find the distance to the nearest zero (to the element which equals to zero). There is at least one zero element in the given array.
Input
The first line contains integer n (1 ≤ n ≤ 2·105) — length of the array a. The second line contains integer elements of the array separated by single spaces ( - 109 ≤ ai ≤ 109).
Output
Print the sequence d0, d1, ..., dn - 1, where di is the difference of indices between i and nearest j such that aj = 0. It is possible that i = j.
Examples
Input
9
2 1 0 3 0 0 3 2 4
Output
2 1 0 1 0 0 1 2 3
Input
5
0 1 2 3 4
Output
0 1 2 3 4
Input
7
5 6 0 1 -2 3 4
Output
2 1 0 1 2 3 4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<int> zeroes;
int binarySearch(int p, int low, int high) {
int ans = INT_MAX;
while (low <= high) {
int mid = (low + high) >> 1;
ans = min(ans, abs(p - zeroes[mid]));
if (zeroes[mid] > p) {
high = mid - 1;
} else if (zeroes[mid] < p) {
low = mid + 1;
}
}
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
vector<long long int> v(n), result(n);
for (int i = 0; i < n; i++) {
cin >> v[i];
if (v[i] == 0) {
zeroes.emplace_back(i);
result[i] = 0;
} else {
result[i] = -1;
}
}
sort((zeroes).begin(), (zeroes).end());
int len = (int)zeroes.size();
for (int i = 0; i < n; i++) {
if (result[i] == -1) {
result[i] = binarySearch(i, 0, len - 1);
}
}
for (int x : result) {
cout << x << " ";
}
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell <image>. The following condition is satisfied for the vector: <image>, where <image> is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited.
Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
Input
The first line contains integers n, m, dx, dy(1 ≤ n ≤ 106, 1 ≤ m ≤ 105, 1 ≤ dx, dy ≤ n) — the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≤ xi, yi ≤ n - 1) — the coordinates of apples. One cell may contain multiple apple trees.
Output
Print two space-separated numbers — the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
Examples
Input
5 5 2 3
0 0
1 2
1 3
2 4
3 1
Output
1 3
Input
2 3 1 1
0 0
0 1
1 1
Output
0 0
Note
In the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)
In the second sample: (0, 0) - (1, 1) - (0, 0)
### Response
```cpp
#include <bits/stdc++.h>
long long n, m, dx, dy, ansx, ansy, x, y, z, sum[1000010], f[1000010], tmp, ti,
i, ans;
int main() {
scanf("%lld%lld%lld%lld", &n, &m, &dx, &dy);
do {
f[tmp] = ti;
tmp = (tmp + dx) % n;
ti++;
} while (tmp);
for (i = 1; i <= m; i++) {
scanf("%lld%lld", &x, &y);
z = (y - f[x] * dy) % n + n;
sum[z % n]++;
if (sum[z % n] > ans) {
ans = sum[z % n];
ansx = x;
ansy = y;
}
}
printf("%lld %lld", ansx, ansy);
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Example
Input
anagram
grandmother
Output
4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string s, t;
cin >> s >> t;
vector<vector<short> > vec(t.size() + 1, vector<short>(26));
for (int i = 1; i <= t.size(); i++) {
vec[i][t[i-1] - 'a']++;
for (int j = 0; j < 26; j++) {
vec[i][j] += vec[i-1][j];
}
}
vector<vector<short> > v(s.size() + 1, vector<short>(26));
for (int i = 1; i <= s.size(); i++) {
v[i][s[i-1] - 'a']++;
for (int j = 0; j < 26; j++) {
v[i][j] += v[i-1][j];
}
}
for (int i = s.size(); i > 0; i--) {
set<vector<short>> sv;
for (int j = 0; j + i < vec.size(); j++) {
vector<short> sub(26);
for (int k = 0; k < 26; k++) {
sub[k] += vec[i + j][k] - vec[j][k];
}
sv.insert(sub);
}
for (int j = 0; j + i < v.size(); j++) {
vector<short> sub(26);
for (int k = 0; k < 26; k++) {
sub[k] = v[i + j][k] - v[j][k];
}
if (sv.find(sub) != sv.end()) {
cout << i << endl;
return 0;
}
}
}
cout << 0 << endl;
return 0;
}
``` |
### Prompt
Create a solution in cpp for 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>B
C<B
A>C
Output
CBA
Input
A<B
B>C
C>A
Output
ACB
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[3] = {0};
string str;
for (int i = 0; i < 3; i++) {
cin >> str;
if (str[1] == '>')
arr[str[0] - 'A']++;
else
arr[str[2] - 'A']++;
}
if (arr[0] == 3 || arr[1] == 3 || arr[2] == 3 ||
(arr[0] == 1 && arr[1] == 1 && arr[2] == 1))
cout << "Impossible\n";
else {
if (arr[0] == 0)
cout << "A";
else if (arr[1] == 0)
cout << "B";
else if (arr[2] == 0)
cout << "C";
if (arr[0] == 1)
cout << "A";
else if (arr[1] == 1)
cout << "B";
else if (arr[2] == 1)
cout << "C";
if (arr[0] == 2)
cout << "A";
else if (arr[1] == 2)
cout << "B";
else if (arr[2] == 2)
cout << "C";
}
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Treeland is a country in which there are n towns connected by n - 1 two-way road such that it's possible to get from any town to any other town.
In Treeland there are 2k universities which are located in different towns.
Recently, the president signed the decree to connect universities by high-speed network.The Ministry of Education understood the decree in its own way and decided that it was enough to connect each university with another one by using a cable. Formally, the decree will be done!
To have the maximum sum in the budget, the Ministry decided to divide universities into pairs so that the total length of the required cable will be maximum. In other words, the total distance between universities in k pairs should be as large as possible.
Help the Ministry to find the maximum total distance. Of course, each university should be present in only one pair. Consider that all roads have the same length which is equal to 1.
Input
The first line of the input contains two integers n and k (2 ≤ n ≤ 200 000, 1 ≤ k ≤ n / 2) — the number of towns in Treeland and the number of university pairs. Consider that towns are numbered from 1 to n.
The second line contains 2k distinct integers u1, u2, ..., u2k (1 ≤ ui ≤ n) — indices of towns in which universities are located.
The next n - 1 line contains the description of roads. Each line contains the pair of integers xj and yj (1 ≤ xj, yj ≤ n), which means that the j-th road connects towns xj and yj. All of them are two-way roads. You can move from any town to any other using only these roads.
Output
Print the maximum possible sum of distances in the division of universities into k pairs.
Examples
Input
7 2
1 5 6 2
1 3
3 2
4 5
3 7
4 3
4 6
Output
6
Input
9 3
3 2 1 6 5 9
8 9
3 2
2 7
3 4
7 6
4 5
2 1
2 8
Output
9
Note
The figure below shows one of possible division into pairs in the first test. If you connect universities number 1 and 6 (marked in red) and universities number 2 and 5 (marked in blue) by using the cable, the total distance will equal 6 which will be the maximum sum in this example.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100 * 100 * 10 * 3 + 10;
bool mark[MAXN], mark2[MAXN];
long long n, k;
long long ans = 0, dp[MAXN];
vector<int> a[MAXN];
void dfs(int v) {
mark2[v] = 1;
for (int i = 0; i < a[v].size(); i++) {
if (mark2[a[v][i]] == false) {
dfs(a[v][i]);
dp[v] += dp[a[v][i]];
ans += min(dp[a[v][i]], 2 * k - dp[a[v][i]]);
}
}
if (mark[v]) dp[v]++;
}
int main() {
ios ::sync_with_stdio(false);
cin.tie(0);
int x, y;
cin >> n >> k;
for (int i = 0; i < 2 * k; i++) cin >> x, mark[x] = 1;
for (int i = 0; i < n - 1; i++) {
cin >> x >> y;
a[x].push_back(y);
a[y].push_back(x);
}
dfs(1);
cout << ans << endl;
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Little Petya loves looking for numbers' divisors. One day Petya came across the following problem:
You are given n queries in the form "xi yi". For each query Petya should count how many divisors of number xi divide none of the numbers xi - yi, xi - yi + 1, ..., xi - 1. Help him.
Input
The first line contains an integer n (1 ≤ n ≤ 105). Each of the following n lines contain two space-separated integers xi and yi (1 ≤ xi ≤ 105, 0 ≤ yi ≤ i - 1, where i is the query's ordinal number; the numeration starts with 1).
If yi = 0 for the query, then the answer to the query will be the number of divisors of the number xi. In this case you do not need to take the previous numbers x into consideration.
Output
For each query print the answer on a single line: the number of positive integers k such that <image>
Examples
Input
6
4 0
3 1
5 2
6 2
18 4
10000 3
Output
3
1
1
2
2
22
Note
Let's write out the divisors that give answers for the first 5 queries:
1) 1, 2, 4
2) 3
3) 5
4) 2, 6
5) 9, 18
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<long long> fact(10, 1);
long long gcd(long long n1, long long n2) {
long long maxm = max(n1, n2);
long long minm = min(n1, n2);
if ((maxm % minm) == 0)
return minm;
else
return gcd(minm, maxm % minm);
}
long long power(long long x, long long y) {
long long temp;
if (y == 0) return 1;
temp = power(x, y / 2) % 1000000007;
if (y % 2 == 0)
return temp * temp % 1000000007;
else
return (x * temp % 1000000007) * temp % 1000000007;
}
long long ifact(long long k) {
return power(fact[k], 1000000007 - 2) % 1000000007;
}
long long ncr(long long n, long long r) {
if (n < r) return 0;
long long num = 1;
long long den = 1;
long long g;
for (long long i = 1; i < r + 1; i++) {
num = num * (n - i + 1);
den = den * (i);
g = gcd(num, den);
num = num / g;
den = den / g;
}
return num;
}
vector<long long> factors(100001, -1);
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t = 1;
while (t--) {
long long n, x, y;
cin >> n;
for (long long i = 0; i < n; i++) {
long long ans = 0;
cin >> x >> y;
for (long long j = 1; j < sqrt(x); j++) {
if (x % j == 0) {
if (factors[j] == -1 || factors[j] < i - y) ans++;
factors[j] = i;
if (factors[x / j] == -1 || factors[x / j] < i - y) ans++;
factors[x / j] = i;
}
}
long long sq = sqrt(x);
if (sq * sq == x) {
if (factors[sq] == -1 || factors[sq] < i - y) ans++;
factors[sq] = i;
}
cout << ans << endl;
}
}
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
There are N barbecue restaurants along a street. The restaurants are numbered 1 through N from west to east, and the distance between restaurant i and restaurant i+1 is A_i.
Joisino has M tickets, numbered 1 through M. Every barbecue restaurant offers barbecue meals in exchange for these tickets. Restaurant i offers a meal of deliciousness B_{i,j} in exchange for ticket j. Each ticket can only be used once, but any number of tickets can be used at a restaurant.
Joisino wants to have M barbecue meals by starting from a restaurant of her choice, then repeatedly traveling to another barbecue restaurant and using unused tickets at the restaurant at her current location. Her eventual happiness is calculated by the following formula: "(The total deliciousness of the meals eaten) - (The total distance traveled)". Find her maximum possible eventual happiness.
Constraints
* All input values are integers.
* 2≤N≤5×10^3
* 1≤M≤200
* 1≤A_i≤10^9
* 1≤B_{i,j}≤10^9
Input
The input is given from Standard Input in the following format:
N M
A_1 A_2 ... A_{N-1}
B_{1,1} B_{1,2} ... B_{1,M}
B_{2,1} B_{2,2} ... B_{2,M}
:
B_{N,1} B_{N,2} ... B_{N,M}
Output
Print Joisino's maximum possible eventual happiness.
Examples
Input
3 4
1 4
2 2 5 1
1 3 3 2
2 2 5 1
Output
11
Input
5 3
1 2 3 4
10 1 1
1 1 1
1 10 1
1 1 1
1 1 10
Output
20
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
char gc(){
static const int L=(1<<19)+1;
static char ibuf[L],*iS,*iT;
if(iS==iT){
iT=(iS=ibuf)+fread(ibuf,1,L,stdin);
return iS==iT?EOF:*iS++;
}
return*iS++;
}
template<class I>void gi(I&x){
static char c;static int f;
for(f=1,c=gc();c<'0'||c>'9';c=gc())if(c=='-')f=-1;
for(x=0;c<='9'&&c>='0';c=gc())x=x*10+(c&15);x*=f;
}
const int N=5005,M=205,K=13;
const ll inf=1e14;
int n,m,st[K][N][M],lg2[N];
ll D[N],ans;
inline void Max(int*a,int*b,int*c){for(int i=1;i<=m;i++)c[i]=max(a[i],b[i]);}
inline ll Sum(int*a,int*b){ll s=0;for(int i=1;i<=m;i++)s+=max(a[i],b[i]);return s;}
inline ll Get(int l,int r){int t=lg2[r-l+1];return Sum(st[t][l],st[t][r-(1<<t)+1]);}
void solve(int l,int r,int s,int t){
if(l>r)return;
int m=(l+r)>>1;
ll best=-inf;int p;
for(int i=s;i<=m&&i<=t;i++){
ll cur=Get(i,m)-D[m]+D[i];
if(cur>best)best=cur,p=i;
}
ans=max(ans,best);
solve(l,m-1,s,p),solve(m+1,r,p,t);
}
int main(){
gi(n),gi(m);
for(int i=2;i<=n;i++)gi(D[i]),D[i]+=D[i-1];
for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)gi(st[0][i][j]);
for(int i=2;i<=n;i++)lg2[i]=lg2[i-1]+!(i&(i-1));
for(int i=1,l=2;l<=n;i++,l<<=1)for(int j=1;j+l-1<=n;j++)Max(st[i-1][j],st[i-1][j+(l>>1)],st[i][j]);
solve(1,n,1,n);
printf("%lld\n",ans);
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
A tennis tournament with n participants is running. The participants are playing by an olympic system, so the winners move on and the losers drop out.
The tournament takes place in the following way (below, m is the number of the participants of the current round):
* let k be the maximal power of the number 2 such that k ≤ m,
* k participants compete in the current round and a half of them passes to the next round, the other m - k participants pass to the next round directly,
* when only one participant remains, the tournament finishes.
Each match requires b bottles of water for each participant and one bottle for the judge. Besides p towels are given to each participant for the whole tournament.
Find the number of bottles and towels needed for the tournament.
Note that it's a tennis tournament so in each match two participants compete (one of them will win and the other will lose).
Input
The only line contains three integers n, b, p (1 ≤ n, b, p ≤ 500) — the number of participants and the parameters described in the problem statement.
Output
Print two integers x and y — the number of bottles and towels need for the tournament.
Examples
Input
5 2 3
Output
20 15
Input
8 2 4
Output
35 32
Note
In the first example will be three rounds:
1. in the first round will be two matches and for each match 5 bottles of water are needed (two for each of the participants and one for the judge),
2. in the second round will be only one match, so we need another 5 bottles of water,
3. in the third round will also be only one match, so we need another 5 bottles of water.
So in total we need 20 bottles of water.
In the second example no participant will move on to some round directly.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long M = 3e5 + 7, N = 500, mod = 1000000007;
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
;
{
long long n, a, b;
cin >> n >> a >> b;
long long ans1 = 0, ans2 = n * b;
while (n > 1) {
long long lim = 0;
for (long long i = 1; i <= n; i *= 2) {
if (i > n) break;
lim = i;
}
long long ex = n - lim;
ans1 += (lim * a) + lim / 2;
n = lim / 2 + ex;
}
cout << ans1 << " " << ans2 << '\n';
}
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Mishka received a gift of multicolored pencils for his birthday! Unfortunately he lives in a monochrome world, where everything is of the same color and only saturation differs. This pack can be represented as a sequence a1, a2, ..., an of n integer numbers — saturation of the color of each pencil. Now Mishka wants to put all the mess in the pack in order. He has an infinite number of empty boxes to do this. He would like to fill some boxes in such a way that:
* Each pencil belongs to exactly one box;
* Each non-empty box has at least k pencils in it;
* If pencils i and j belong to the same box, then |ai - aj| ≤ d, where |x| means absolute value of x. Note that the opposite is optional, there can be pencils i and j such that |ai - aj| ≤ d and they belong to different boxes.
Help Mishka to determine if it's possible to distribute all the pencils into boxes. Print "YES" if there exists such a distribution. Otherwise print "NO".
Input
The first line contains three integer numbers n, k and d (1 ≤ k ≤ n ≤ 5·105, 0 ≤ d ≤ 109) — the number of pencils, minimal size of any non-empty box and maximal difference in saturation between any pair of pencils in the same box, respectively.
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109) — saturation of color of each pencil.
Output
Print "YES" if it's possible to distribute all the pencils into boxes and satisfy all the conditions. Otherwise print "NO".
Examples
Input
6 3 10
7 2 7 7 4 2
Output
YES
Input
6 2 3
4 5 3 13 4 10
Output
YES
Input
3 2 5
10 16 22
Output
NO
Note
In the first example it is possible to distribute pencils into 2 boxes with 3 pencils in each with any distribution. And you also can put all the pencils into the same box, difference of any pair in it won't exceed 10.
In the second example you can split pencils of saturations [4, 5, 3, 4] into 2 boxes of size 2 and put the remaining ones into another box.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = int(5e5) + 10;
const int K = int(2e6) + 10;
const int MOD = int(1e9) + 7;
const int INF = int(1e9) + 5;
const long long INF64 = 1e18;
int a[N], dp[N], l[N];
void solve() {
int n, k, d;
cin >> n >> k >> d;
for (int i = 1; i <= n; i++) cin >> a[i];
sort(a + 1, a + 1 + n);
dp[0] = 1;
for (int i = k; i <= n; i++) {
int x = l[i - k];
if (a[i] - a[x + 1] <= d) {
dp[i] = 1;
}
if (dp[i])
l[i] = i;
else
l[i] = l[i - 1];
}
if (dp[n])
cout << "YES" << '\n';
else
cout << "NO" << '\n';
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
t = 1;
while (t--) {
solve();
}
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Snuke can change a string t of length N into a string t' of length N - 1 under the following rule:
* For each i (1 ≤ i ≤ N - 1), the i-th character of t' must be either the i-th or (i + 1)-th character of t.
There is a string s consisting of lowercase English letters. Snuke's objective is to apply the above operation to s repeatedly so that all the characters in s are the same. Find the minimum necessary number of operations.
Constraints
* 1 ≤ |s| ≤ 100
* s consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
Output
Print the minimum necessary number of operations to achieve the objective.
Examples
Input
serval
Output
3
Input
jackal
Output
2
Input
zzz
Output
0
Input
whbrjpjyhsrywlqjxdbrbaomnw
Output
8
### Response
```cpp
#include <iostream>
using namespace std;
const int kInf = 1e9;
void Solve() {
string s;
cin >> s;
int ans = kInf;
for (char c = 'a'; c <= 'z'; ++c) {
int tans = 0;
int last = s.length();
for (int j = s.length() - 1; j >= 0; --j) {
if (s[j] == c) {
tans = max(tans, last - j - 1);
last = j;
}
}
tans = max(tans, last);
ans = min(ans, tans);
}
cout << ans << "\n";
}
int main() {
int tests = 1;
for (;tests; --tests) {
Solve();
}
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Takahashi and Aoki are playing a stone-taking game. Initially, there are N piles of stones, and the i-th pile contains A_i stones and has an associated integer K_i.
Starting from Takahashi, Takahashi and Aoki take alternate turns to perform the following operation:
* Choose a pile. If the i-th pile is selected and there are X stones left in the pile, remove some number of stones between 1 and floor(X/K_i) (inclusive) from the pile.
The player who first becomes unable to perform the operation loses the game. Assuming that both players play optimally, determine the winner of the game. Here, floor(x) represents the largest integer not greater than x.
Constraints
* 1 \leq N \leq 200
* 1 \leq A_i,K_i \leq 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 K_1
:
A_N K_N
Output
If Takahashi will win, print `Takahashi`; if Aoki will win, print `Aoki`.
Examples
Input
2
5 2
3 3
Output
Aoki
Input
3
3 2
4 3
5 1
Output
Takahashi
Input
3
28 3
16 4
19 2
Output
Aoki
Input
4
3141 59
26535 897
93 23
8462 64
Output
Takahashi
### Response
```cpp
#include <bits/stdc++.h>
int cal(int n,int k)
{
while(n>=k&&n%k!=0) {
int div = n/k+1;
n -= ((n-1)%k/div+1)*div;
}
return n/k;
}
int n;
int main()
{
scanf("%d",&n);
int val = 0;
for(int i = 0;i < n;++i) {
int a,b;
scanf("%d%d",&a,&b);
val ^= cal(a,b);
}
if(val > 0) {
printf("Takahashi\n");
} else {
printf("Aoki\n");
}
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
A fraction whose numerator is 1 and whose denominator is a positive integer is called a unit fraction. A representation of a positive rational number p/q as the sum of finitely many unit fractions is called a partition of p/q into unit fractions. For example, 1/2 + 1/6 is a partition of 2/3 into unit fractions. The difference in the order of addition is disregarded. For example, we do not distinguish 1/6 + 1/2 from 1/2 + 1/6.
For given four positive integers p, q, a, and n, count the number of partitions of p/q into unit fractions satisfying the following two conditions.
* The partition is the sum of at most n many unit fractions.
* The product of the denominators of the unit fractions in the partition is less than or equal to a.
For example, if (p,q,a,n) = (2,3,120,3), you should report 4 since
2/3 = 1/3 + 1/3 = 1/2 + 1/6 = 1/4 + 1/4 + 1/6 = 1/3 + 1/6 + 1/6
enumerates all of the valid partitions.
Input
The input is a sequence of at most 1000 data sets followed by a terminator.
A data set is a line containing four positive integers p, q, a, and n satisfying p,q <= 800, a <= 12000 and n <= 7. The integers are separated by a space.
The terminator is composed of just one line which contains four zeros separated by a space. It is not a part of the input data but a mark for the end of the input.
Output
The output should be composed of lines each of which contains a single integer. No other characters should appear in the output.
The output integer corresponding to a data set p, q, a, n should be the number of all partitions of p/q into at most n many unit fractions such that the product of the denominators of the unit fractions is less than or equal to a.
Example
Input
2 3 120 3
2 3 300 3
2 3 299 3
2 3 12 3
2 3 12000 7
54 795 12000 7
2 3 300 1
2 1 200 5
2 4 54 2
0 0 0 0
Output
4
7
6
2
42
1
0
9
3
### Response
```cpp
#include <iostream>
using namespace std;
int n, p, q, a;
int dfs(int i, int last, int prod, int c, int d){
int count = 0;
if (c * q == d * p) {
return 1;
}
if (i >= n) {
return 0;
}
for (int j = last; j * prod <= a; j++) {
if (q * (c * j + d) <= (p * j * d)){
count += dfs(i+1, j, j*prod, c*j+d, d*j);
}
}
return count;
}
int main()
{
while (true) {
cin >> p >> q >> a >> n;
if (p == 0) {
break;
}
cout << dfs(0, 1, 1, 0, 1) << endl;
}
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
problem
Given a sequence of n integers a1, a2, ..., an and a positive integer k (1 ≤ k ≤ n), then the sum of k consecutive integers Si = ai + ai + Create a program that outputs the maximum value of 1 + ... + ai + k-1 (1 ≤ i ≤ n --k + 1).
input
The input consists of multiple datasets. Each dataset is given in the following format. The input ends on a line containing two zeros.
On the first line, the positive integer n (1 ≤ n ≤ 100000) and the positive integer k (1 ≤ k ≤ n) are written in this order, separated by blanks. The first + i lines after the second line. (1 ≤ i ≤ n) contains the i-th term ai (-10000 ≤ ai ≤ 10000) in the sequence. Of the scoring data, 60% of the points are n ≤ 5000, k ≤ 1000. Meet.
The number of datasets does not exceed 5.
output
The maximum value of Si is output to one line for each data set.
Examples
Input
5 3
2
5
-4
10
3
0 0
Output
11
Input
None
Output
None
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, k;
while (cin >> n >> k, n || k){
int a[100010], num;
for (int i = 0; i < n; i++){
cin >> num;
if (i == 0) a[i] = num;
else a[i] = a[i - 1] + num;
}
int res = 0;
for (int i = k; i < n; i++){
res = max(res, a[i] - a[i - k]);
}
cout << res << '\n';
}
}
``` |
### Prompt
Create a solution in cpp for the following problem:
The king of Berland organizes a ball! n pair are invited to the ball, they are numbered from 1 to n. Each pair consists of one man and one woman. Each dancer (either man or woman) has a monochrome costume. The color of each costume is represented by an integer from 1 to k, inclusive.
Let b_i be the color of the man's costume and g_i be the color of the woman's costume in the i-th pair. You have to choose a color for each dancer's costume (i.e. values b_1, b_2, ..., b_n and g_1, g_2, ... g_n) in such a way that:
1. for every i: b_i and g_i are integers between 1 and k, inclusive;
2. there are no two completely identical pairs, i.e. no two indices i, j (i ≠ j) such that b_i = b_j and g_i = g_j at the same time;
3. there is no pair such that the color of the man's costume is the same as the color of the woman's costume in this pair, i.e. b_i ≠ g_i for every i;
4. for each two consecutive (adjacent) pairs both man's costume colors and woman's costume colors differ, i.e. for every i from 1 to n-1 the conditions b_i ≠ b_{i + 1} and g_i ≠ g_{i + 1} hold.
Let's take a look at the examples of bad and good color choosing (for n=4 and k=3, man is the first in a pair and woman is the second):
Bad color choosing:
* (1, 2), (2, 3), (3, 2), (1, 2) — contradiction with the second rule (there are equal pairs);
* (2, 3), (1, 1), (3, 2), (1, 3) — contradiction with the third rule (there is a pair with costumes of the same color);
* (1, 2), (2, 3), (1, 3), (2, 1) — contradiction with the fourth rule (there are two consecutive pairs such that colors of costumes of men/women are the same).
Good color choosing:
* (1, 2), (2, 1), (1, 3), (3, 1);
* (1, 2), (3, 1), (2, 3), (3, 2);
* (3, 1), (1, 2), (2, 3), (3, 2).
You have to find any suitable color choosing or say that no suitable choosing exists.
Input
The only line of the input contains two integers n and k (2 ≤ n, k ≤ 2 ⋅ 10^5) — the number of pairs and the number of colors.
Output
If it is impossible to find any suitable colors choosing, print "NO".
Otherwise print "YES" and then the colors of the costumes of pairs in the next n lines. The i-th line should contain two integers b_i and g_i — colors of costumes of man and woman in the i-th pair, respectively.
You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
Examples
Input
4 3
Output
YES
3 1
1 3
3 2
2 3
Input
10 4
Output
YES
2 1
1 3
4 2
3 4
4 3
3 2
2 4
4 1
1 4
3 1
Input
13 4
Output
NO
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int prime_table[] = {1009L, 10007L, 100003L, 1000003L,
10000019L, 100000007L, 1000000007L};
const long long int maxn_1 = 3.1e1;
const long long int maxn_2 = 3.1e2;
const long long int maxn_3 = 3.1e3;
const long long int maxn_4 = 3.1e4;
const long long int maxn_5 = 3.1e5;
const long long int maxn_6 = 3.1e6;
signed main() {
{
ios::sync_with_stdio(0);
cin.tie(0);
};
long long int n, k;
cin >> n >> k;
long long int shang, remain;
shang = n / k;
remain = n % k;
if (remain != 0) {
shang++;
}
if (shang >= k) {
(cout << "NO" << endl);
} else {
(cout << "YES" << endl);
vector<pair<long long int, long long int> > re;
re.resize(n + 1);
re[0].first = re[0].second = -1;
for (long long int i = 0; i < n; i += 1) {
re[i + 1].first = (i % k) + 1;
}
long long int start = 1;
long long int pos = 1;
for (long long int i = 0; i < shang; i += 1) {
for (long long int j = 0; j < k; j += 1) {
re[pos].second = (start + j) % k + 1;
pos++;
if (pos > n) {
break;
}
}
if (pos > n) {
break;
}
start++;
}
for (long long int i = 1; i < n + 1; i += 1) {
cout << re[i].first << " " << re[i].second << endl;
}
}
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Write a program of a Merge Sort algorithm implemented by the following pseudocode. You should also report the number of comparisons in the Merge function.
Merge(A, left, mid, right)
n1 = mid - left;
n2 = right - mid;
create array L[0...n1], R[0...n2]
for i = 0 to n1-1
do L[i] = A[left + i]
for i = 0 to n2-1
do R[i] = A[mid + i]
L[n1] = SENTINEL
R[n2] = SENTINEL
i = 0;
j = 0;
for k = left to right-1
if L[i] <= R[j]
then A[k] = L[i]
i = i + 1
else A[k] = R[j]
j = j + 1
Merge-Sort(A, left, right){
if left+1 < right
then mid = (left + right)/2;
call Merge-Sort(A, left, mid)
call Merge-Sort(A, mid, right)
call Merge(A, left, mid, right)
Notes
Constraints
* n ≤ 500000
* 0 ≤ an element in S ≤ 109
Input
In the first line n is given. In the second line, n integers are given.
Output
In the first line, print the sequence S. Two consequtive elements should be separated by a space character.
In the second line, print the number of comparisons.
Example
Input
10
8 5 9 2 6 3 7 1 10 4
Output
1 2 3 4 5 6 7 8 9 10
34
### Response
```cpp
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=1e6;
int a[maxn];
int b[maxn];
int cnt;
void merge(int l,int mid,int r)
{
int p1=l,p2=mid+1;//双指针
int pos=l;//当前位置
while(p1<=mid&&p2<=r){
cnt++;
if(a[p1]<a[p2]){
b[pos++]=a[p1++];
}else{
b[pos++]=a[p2++];
}
}
while(p1<=mid){
cnt++;
b[pos++]=a[p1++];
}
while(p2<=r){
cnt++;
b[pos++]=a[p2++];
}
for(int i=l;i<=r;i++)a[i]=b[i];
}
void merge_sort(int l,int r)
{
if(l<r){
int mid=(l+r)/2;
merge_sort(l,mid);
merge_sort(mid+1,r);
merge(l,mid,r);
}
}
int main()
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
int n;
cin>>n;
cnt=0;
for(int i=1;i<=n;i++)cin>>a[i];
merge_sort(1,n);
for(int i=1;i<=n;i++){
if(i>1)cout<<" ";
cout<<a[i];
}
cout<<endl;
cout<<cnt<<endl;
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Homer has two friends Alice and Bob. Both of them are string fans.
One day, Alice and Bob decide to play a game on a string s = s_1 s_2 ... s_n of length n consisting of lowercase English letters. They move in turns alternatively and Alice makes the first move.
In a move, a player must choose an index i (1 ≤ i ≤ n) that has not been chosen before, and change s_i to any other lowercase English letter c that c ≠ s_i.
When all indices have been chosen, the game ends.
The goal of Alice is to make the final string lexicographically as small as possible, while the goal of Bob is to make the final string lexicographically as large as possible. Both of them are game experts, so they always play games optimally. Homer is not a game expert, so he wonders what the final string will be.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
Each test contains multiple test cases. The first line contains t (1 ≤ t ≤ 1000) — the number of test cases. Description of the test cases follows.
The only line of each test case contains a single string s (1 ≤ |s| ≤ 50) consisting of lowercase English letters.
Output
For each test case, print the final string in a single line.
Example
Input
3
a
bbbb
az
Output
b
azaz
by
Note
In the first test case: Alice makes the first move and must change the only letter to a different one, so she changes it to 'b'.
In the second test case: Alice changes the first letter to 'a', then Bob changes the second letter to 'z', Alice changes the third letter to 'a' and then Bob changes the fourth letter to 'z'.
In the third test case: Alice changes the first letter to 'b', and then Bob changes the second letter to 'y'.
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
char alice(char c){
if(c=='a') return 'b';
return 'a';
}
char bob(char c){
if(c=='z') return 'y';
return 'z';
}
int main()
{
int t;
cin>>t;
while(t--){
string s;
cin>>s;
unordered_map<char, vector<int>> m;
vector<char> v;
bool turn=1;
for(int i =0;i<s.size();i++){
char c=s[i];
if(turn){
s[i]=alice(c);
}
else{
s[i]=bob(c);
}
turn=!turn;
}
cout<<s<<"\n";
}
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
In this task you have to write a program dealing with nonograms on fields no larger than 5 × 20.
Simplified nonogram is a task where you have to build such field (each cell is either white or black) that satisfies the given information about rows and columns. For each row and each column the number of contiguous black segments is specified.
For example if size of the field is n = 3, m = 5, аnd numbers of contiguous black segments in rows are: [2, 3, 2] and in columns are: [1, 0, 1, 2, 1] then the solution may look like:
<image>
It is guaranteed that on each test in the testset there exists at least one solution.
Input
In the first line there follow two integers n, m (1 ≤ n ≤ 5, 1 ≤ m ≤ 20) — number of rows and number of columns respectively.
Second line contains n integers a1, a2, ..., an where ai is the number of contiguous black segments in i-th row of the field.
Similarly, third line contains m integers b1, b2, ..., bm where bi is the number of contiguous black segments in the i-th column of the field.
It is guaranteed that there exists at least one solution.
Output
Output any possible solution. Output should consist of n lines each containing m characters. Denote white cell as "." and black cell as "*".
Examples
Input
3 5
2 3 2
1 0 1 2 1
Output
*.**.
*.*.*
*..**
Input
3 3
2 1 2
2 1 2
Output
*.*
.*.
*.*
Input
3 3
1 0 1
2 2 2
Output
***
...
***
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool vis[20][32][11][11][11][11][11];
bool dp[20][32][11][11][11][11][11];
int r[25], c[25], R, C;
bool dp_func(int row, int prv, int col1, int col2, int col3, int col4,
int col5);
inline bool check(int mask, int pos) { return (bool)(mask & (1 << pos)); }
int ou[25];
bool rec(int row, int prv, int col1, int col2, int col3, int col4, int col5,
int pos, int ager, int seg) {
if (seg > r[row]) return 0;
if (pos == C) {
if (seg == r[row])
return dp_func(row + 1, prv, col1, col2, col3, col4, col5);
return 0;
}
int tmp[] = {col1, col2, col3, col4, col5};
int ret = 0;
if (check(prv, pos)) {
ret |= rec(row, prv, tmp[0], tmp[1], tmp[2], tmp[3], tmp[4], pos + 1, 1,
seg + (ager == 0));
if (ret) return 1;
ret |= rec(row, prv ^ (1 << pos), tmp[0], tmp[1], tmp[2], tmp[3], tmp[4],
pos + 1, 0, seg);
return ret;
}
ret |= rec(row, prv, tmp[0], tmp[1], tmp[2], tmp[3], tmp[4], pos + 1, 0, seg);
if (ret) return 1;
if (c[pos] == tmp[pos]) return 0;
tmp[pos]++;
ret |= rec(row, prv | (1 << pos), tmp[0], tmp[1], tmp[2], tmp[3], tmp[4],
pos + 1, 1, seg + (ager == 0));
return ret;
}
bool dp_func(int row, int prv, int col1, int col2, int col3, int col4,
int col5) {
if (row == R) {
if (col1 == c[0] && col2 == c[1] && col3 == c[2] && col4 == c[3] &&
col5 == c[4])
return 1;
return 0;
}
if (vis[row][prv][col1][col2][col3][col4][col5])
return dp[row][prv][col1][col2][col3][col4][col5];
vis[row][prv][col1][col2][col3][col4][col5] = 1;
bool d = rec(row, prv, col1, col2, col3, col4, col5, 0, 0, 0);
return dp[row][prv][col1][col2][col3][col4][col5] = d;
}
void path(int row, int prv, int col1, int col2, int col3, int col4, int col5,
int pos, int ager, int seg) {
if (seg > r[row]) assert(0);
if (row == R) return;
if (pos == C) {
if (seg == r[row] && dp_func(row + 1, prv, col1, col2, col3, col4, col5)) {
path(row + 1, prv, col1, col2, col3, col4, col5, 0, 0, 0);
ou[row] |= prv;
return;
}
assert(0);
}
int tmp[] = {col1, col2, col3, col4, col5};
int ret = 0;
if ((bool)(prv & (1 << pos))) {
ret |= rec(row, prv, tmp[0], tmp[1], tmp[2], tmp[3], tmp[4], pos + 1, 1,
seg + (ager == 0));
if (ret == 1) {
path(row, prv, tmp[0], tmp[1], tmp[2], tmp[3], tmp[4], pos + 1, 1,
seg + (ager == 0));
return;
}
path(row, prv ^ (1 << pos), tmp[0], tmp[1], tmp[2], tmp[3], tmp[4], pos + 1,
0, seg);
return;
}
ret |= rec(row, prv, tmp[0], tmp[1], tmp[2], tmp[3], tmp[4], pos + 1, 0, seg);
if (ret) {
path(row, prv, tmp[0], tmp[1], tmp[2], tmp[3], tmp[4], pos + 1, 0, seg);
return;
}
tmp[pos]++;
path(row, prv | (1 << pos), tmp[0], tmp[1], tmp[2], tmp[3], tmp[4], pos + 1,
1, seg + (ager == 0));
}
int main() {
int i, j, k, l, m, n;
scanf("%d%d", &R, &C);
swap(R, C);
for (int i = 0; i < C; i++) scanf("%d", &c[i]);
for (int i = 0; i < R; i++) scanf("%d", &r[i]);
int d = dp_func(0, 0, 0, 0, 0, 0, 0);
path(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
for (int i = 0; i < C; i++) {
for (int j = 0; j < R; j++) {
if (check(ou[j], i))
printf("*");
else
printf(".");
}
printf("\n");
}
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
This is an interactive problem.
Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≤ i ≤ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice.
As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and <image> sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists.
You can ask questions of form «which number was received by student i?», and the goal is to determine whether the desired pair exists in no more than 60 questions.
Input
At the beginning the even integer n (2 ≤ n ≤ 100 000) is given — the total number of students.
You are allowed to ask no more than 60 questions.
Output
To ask the question about the student i (1 ≤ i ≤ n), you should print «? i». Then from standard output you can read the number ai received by student i ( - 109 ≤ ai ≤ 109).
When you find the desired pair, you should print «! i», where i is any student who belongs to the pair (1 ≤ i ≤ n). If you determined that such pair doesn't exist, you should output «! -1». In both cases you should immediately terminate the program.
The query that contains your answer is not counted towards the limit of 60 queries.
Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language.
Hacking
Use the following format for hacking:
In the first line, print one even integer n (2 ≤ n ≤ 100 000) — the total number of students.
In the second line print n integers ai ( - 109 ≤ ai ≤ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or - 1.
The hacked solution will not have direct access to the sequence ai.
Examples
Input
8
<span class="tex-span"></span>
2
<span class="tex-span"></span>
2
Output
<span class="tex-span"></span>
? 4
<span class="tex-span"></span>
? 8
<span class="tex-span"></span>
! 4
Input
6
<span class="tex-span"></span>
1
<span class="tex-span"></span>
2
<span class="tex-span"></span>
3
<span class="tex-span"></span>
2
<span class="tex-span"></span>
1
<span class="tex-span"></span>
0
Output
<span class="tex-span"></span>
? 1
<span class="tex-span"></span>
? 2
<span class="tex-span"></span>
? 3
<span class="tex-span"></span>
? 4
<span class="tex-span"></span>
? 5
<span class="tex-span"></span>
? 6
<span class="tex-span"></span>
! -1
Note
Input-output in statements illustrates example interaction.
In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2
In the second sample the selection sequence is 1, 2, 3, 2, 1, 0.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
if (n % 4 != 0) {
cout << "! -1\n";
return 0;
}
int l = 1, r = 1 + n / 2, x, y, cur;
cout << "? " << 1 << endl;
cin >> x;
cout << "? " << 1 + n / 2 << endl;
cin >> y;
if (x == y) {
cout << "! " << 1 << endl;
return 0;
}
bool f = (x < y);
while (1) {
cur = (l + r) / 2;
cout << "? " << cur << endl;
cin >> x;
cout << "? " << cur + n / 2 << endl;
cin >> y;
if (x == y) {
cout << "! " << cur << endl;
return 0;
}
if ((x < y) == f)
l = cur;
else
r = cur;
}
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
There is a bookshelf which can fit n books. The i-th position of bookshelf is a_i = 1 if there is a book on this position and a_i = 0 otherwise. It is guaranteed that there is at least one book on the bookshelf.
In one move, you can choose some contiguous segment [l; r] consisting of books (i.e. for each i from l to r the condition a_i = 1 holds) and:
* Shift it to the right by 1: move the book at index i to i + 1 for all l ≤ i ≤ r. This move can be done only if r+1 ≤ n and there is no book at the position r+1.
* Shift it to the left by 1: move the book at index i to i-1 for all l ≤ i ≤ r. This move can be done only if l-1 ≥ 1 and there is no book at the position l-1.
Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).
For example, for a = [0, 0, 1, 0, 1] there is a gap between books (a_4 = 0 when a_3 = 1 and a_5 = 1), for a = [1, 1, 0] there are no gaps between books and for a = [0, 0,0] there are also no gaps between books.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 200) — 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 places on a bookshelf. The second line of the test case contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 1), where a_i is 1 if there is a book at this position and 0 otherwise. It is guaranteed that there is at least one book on the bookshelf.
Output
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).
Example
Input
5
7
0 0 1 0 1 0 1
3
1 0 0
5
1 1 0 0 1
6
1 0 0 0 0 1
5
1 1 0 1 1
Output
2
0
2
4
1
Note
In the first test case of the example, you can shift the segment [3; 3] to the right and the segment [4; 5] to the right. After all moves, the books form the contiguous segment [5; 7]. So the answer is 2.
In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.
In the third test case of the example, you can shift the segment [5; 5] to the left and then the segment [4; 4] to the left again. After all moves, the books form the contiguous segment [1; 3]. So the answer is 2.
In the fourth test case of the example, you can shift the segment [1; 1] to the right, the segment [2; 2] to the right, the segment [6; 6] to the left and then the segment [5; 5] to the left. After all moves, the books form the contiguous segment [3; 4]. So the answer is 4.
In the fifth test case of the example, you can shift the segment [1; 2] to the right. After all moves, the books form the contiguous segment [2; 5]. So the answer is 1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int T, a[55], n;
int main() {
scanf("%d", &T);
while (T--) {
memset(a, 0, sizeof a);
scanf("%d", &n);
int ans = 0;
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
}
int first, last;
for (int i = 1; i <= n; ++i)
if (a[i] == 1) {
first = i;
break;
}
for (int i = n; i >= 1; --i)
if (a[i] == 1) {
last = i;
break;
}
for (int i = first; i <= last; ++i) {
if (a[i] == 0) ans++;
}
printf("%d\n", ans);
}
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Determine if we can choose K different integers between 1 and N (inclusive) so that no two of them differ by 1.
Constraints
* 1\leq N,K\leq 100
* N and K are integers.
Input
Input is given from Standard Input in the following format:
N K
Output
If we can choose K integers as above, print `YES`; otherwise, print `NO`.
Examples
Input
3 2
Output
YES
Input
5 5
Output
NO
Input
31 10
Output
YES
Input
10 90
Output
NO
### Response
```cpp
#include <bits/stdc++.h>
int n, k;
int main()
{
std::cin >> n >> k;
std::cout << ((n + 1) / 2 >= k ? "YES" : "NO");
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
problem
Given a sequence of n integers a1, a2, ..., an and a positive integer k (1 ≤ k ≤ n), then the sum of k consecutive integers Si = ai + ai + Create a program that outputs the maximum value of 1 + ... + ai + k-1 (1 ≤ i ≤ n --k + 1).
input
The input consists of multiple datasets. Each dataset is given in the following format. The input ends on a line containing two zeros.
On the first line, the positive integer n (1 ≤ n ≤ 100000) and the positive integer k (1 ≤ k ≤ n) are written in this order, separated by blanks. The first + i lines after the second line. (1 ≤ i ≤ n) contains the i-th term ai (-10000 ≤ ai ≤ 10000) in the sequence. Of the scoring data, 60% of the points are n ≤ 5000, k ≤ 1000. Meet.
The number of datasets does not exceed 5.
output
The maximum value of Si is output to one line for each data set.
Examples
Input
5 3
2
5
-4
10
3
0 0
Output
11
Input
None
Output
None
### Response
```cpp
#include<iostream>
using namespace std;
int main(){
while(1){
int a[100000+2],n,k,ans=0,sum=0;
scanf("%d%d",&n,&k);
if(n==0&&k==0)break;
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
for(int i=0;i<k;i++){
sum+=a[i];
}
ans=sum;
for(int i=k;i<n;i++){
sum+=a[i]-a[i-k];
if(ans<sum)ans=sum;
}
printf("%d\n",ans);
}
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Edo has got a collection of n refrigerator magnets!
He decided to buy a refrigerator and hang the magnets on the door. The shop can make the refrigerator with any size of the door that meets the following restrictions: the refrigerator door must be rectangle, and both the length and the width of the door must be positive integers.
Edo figured out how he wants to place the magnets on the refrigerator. He introduced a system of coordinates on the plane, where each magnet is represented as a rectangle with sides parallel to the coordinate axes.
Now he wants to remove no more than k magnets (he may choose to keep all of them) and attach all remaining magnets to the refrigerator door, and the area of the door should be as small as possible. A magnet is considered to be attached to the refrigerator door if its center lies on the door or on its boundary. The relative positions of all the remaining magnets must correspond to the plan.
Let us explain the last two sentences. Let's suppose we want to hang two magnets on the refrigerator. If the magnet in the plan has coordinates of the lower left corner (x1, y1) and the upper right corner (x2, y2), then its center is located at (<image>, <image>) (may not be integers). By saying the relative position should correspond to the plan we mean that the only available operation is translation, i.e. the vector connecting the centers of two magnets in the original plan, must be equal to the vector connecting the centers of these two magnets on the refrigerator.
The sides of the refrigerator door must also be parallel to coordinate axes.
Input
The first line contains two integers n and k (1 ≤ n ≤ 100 000, 0 ≤ k ≤ min(10, n - 1)) — the number of magnets that Edo has and the maximum number of magnets Edo may not place on the refrigerator.
Next n lines describe the initial plan of placing magnets. Each line contains four integers x1, y1, x2, y2 (1 ≤ x1 < x2 ≤ 109, 1 ≤ y1 < y2 ≤ 109) — the coordinates of the lower left and upper right corners of the current magnet. The magnets can partially overlap or even fully coincide.
Output
Print a single integer — the minimum area of the door of refrigerator, which can be used to place at least n - k magnets, preserving the relative positions.
Examples
Input
3 1
1 1 2 2
2 2 3 3
3 3 4 4
Output
1
Input
4 1
1 1 2 2
1 9 2 10
9 9 10 10
9 1 10 2
Output
64
Input
3 0
1 1 2 2
1 1 1000000000 1000000000
1 3 8 12
Output
249999999000000001
Note
In the first test sample it is optimal to remove either the first or the third magnet. If we remove the first magnet, the centers of two others will lie at points (2.5, 2.5) and (3.5, 3.5). Thus, it is enough to buy a fridge with door width 1 and door height 1, the area of the door also equals one, correspondingly.
In the second test sample it doesn't matter which magnet to remove, the answer will not change — we need a fridge with door width 8 and door height 8.
In the third sample you cannot remove anything as k = 0.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
const int maxm = maxn * 4 + 10;
const int inf = 1e9;
const long long mod = 1e9 + 7;
int getint() {
char c;
while ((c = getchar()) && !(c >= '0' && c <= '9') && c != '-')
;
int ret = c - '0', sgn = 0;
if (c == '-') sgn = 1, ret = 0;
while ((c = getchar()) && c >= '0' && c <= '9') ret = ret * 10 + c - '0';
if (sgn) ret = -ret;
return ret;
}
multiset<pair<long long, long long> > st1, st2;
multiset<pair<long long, long long> >::iterator it;
vector<pair<long long, long long> > g;
int main() {
int n, m;
while (scanf("%d%d", &n, &m) == 2) {
int i;
st1.clear();
st2.clear();
for (i = 1; i <= n; i++) {
long long x1, y1, x2, y2;
scanf("%I64d%I64d%I64d%I64d", &x1, &y1, &x2, &y2);
x1 *= 2, y1 *= 2, x2 *= 2, y2 *= 2;
st1.insert(make_pair((x1 + x2) / 2, (y1 + y2) / 2));
st2.insert(make_pair((y1 + y2) / 2, (x1 + x2) / 2));
}
long long ans = 1e18 + 10;
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= m; j++) {
for (int k = 0; k <= m; k++) {
for (int l = 0; l <= m; l++) {
if (i + j + k + l > m) continue;
g.clear();
int cnt = 0;
while (cnt < i && (st1.size())) {
it = st1.begin();
int xx = (*it).first, yy = (*it).second;
g.push_back(make_pair(xx, yy));
st1.erase(it);
it = st2.find(make_pair(yy, xx));
st2.erase(it);
cnt++;
}
cnt = 0;
while (cnt < j && (st1.size())) {
it = st1.end();
it--;
int xx = (*it).first, yy = (*it).second;
g.push_back(make_pair(xx, yy));
st1.erase(it);
it = st2.find(make_pair(yy, xx));
st2.erase(it);
cnt++;
}
cnt = 0;
while (cnt < k && (st2.size())) {
it = st2.begin();
int xx = (*it).first, yy = (*it).second;
g.push_back(make_pair(yy, xx));
st2.erase(it);
it = st1.find(make_pair(yy, xx));
st1.erase(it);
cnt++;
}
cnt = 0;
while (cnt < l && (st2.size())) {
it = st2.end();
it--;
int xx = (*it).first, yy = (*it).second;
g.push_back(make_pair(yy, xx));
st2.erase(it);
it = st1.find(make_pair(yy, xx));
st1.erase(it);
cnt++;
}
long long x, y, t1, t2;
if (st1.size() == 0) {
ans = 0;
continue;
}
it = st1.begin();
x = (*it).first;
it = st1.end();
it--;
y = (*it).first;
t1 = (y - x) / 2;
t1 = max(t1, (long long)1);
it = st2.begin();
x = (*it).first;
it = st2.end();
it--;
y = (*it).first;
t2 = (y - x) / 2;
t2 = max(t2, (long long)1);
ans = min(ans, t1 * t2);
int len = g.size();
for (int c = 0; c < len; c++) {
st1.insert(g[c]);
st2.insert(make_pair(g[c].second, g[c].first));
}
}
}
}
}
cout << ans << endl;
}
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Reforms continue entering Berland. For example, during yesterday sitting the Berland Parliament approved as much as n laws (each law has been assigned a unique number from 1 to n). Today all these laws were put on the table of the President of Berland, G.W. Boosch, to be signed.
This time mr. Boosch plans to sign 2k laws. He decided to choose exactly two non-intersecting segments of integers from 1 to n of length k and sign all laws, whose numbers fall into these segments. More formally, mr. Boosch is going to choose two integers a, b (1 ≤ a ≤ b ≤ n - k + 1, b - a ≥ k) and sign all laws with numbers lying in the segments [a; a + k - 1] and [b; b + k - 1] (borders are included).
As mr. Boosch chooses the laws to sign, he of course considers the public opinion. Allberland Public Opinion Study Centre (APOSC) conducted opinion polls among the citizens, processed the results into a report and gave it to the president. The report contains the absurdity value for each law, in the public opinion. As mr. Boosch is a real patriot, he is keen on signing the laws with the maximum total absurdity. Help him.
Input
The first line contains two integers n and k (2 ≤ n ≤ 2·105, 0 < 2k ≤ n) — the number of laws accepted by the parliament and the length of one segment in the law list, correspondingly. The next line contains n integers x1, x2, ..., xn — the absurdity of each law (1 ≤ xi ≤ 109).
Output
Print two integers a, b — the beginning of segments that mr. Boosch should choose. That means that the president signs laws with numbers from segments [a; a + k - 1] and [b; b + k - 1]. If there are multiple solutions, print the one with the minimum number a. If there still are multiple solutions, print the one with the minimum b.
Examples
Input
5 2
3 6 1 1 6
Output
1 4
Input
6 2
1 1 1 1 1 1
Output
1 3
Note
In the first sample mr. Boosch signs laws with numbers from segments [1;2] and [4;5]. The total absurdity of the signed laws equals 3 + 6 + 1 + 6 = 16.
In the second sample mr. Boosch signs laws with numbers from segments [1;2] and [3;4]. The total absurdity of the signed laws equals 1 + 1 + 1 + 1 = 4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long INF = (long long)(1e18);
const int maxn = 200010;
struct node {
long long sum;
int id;
node(long long s = 0, int i = -1) {
sum = s;
id = i;
}
bool operator>(const node& b) const {
if (sum == b.sum) return id < b.id;
return sum > b.sum;
}
bool operator<(const node& b) const {
if (sum == b.sum) return id > b.id;
return sum < b.sum;
}
} t[maxn << 2];
long long a[maxn], b[maxn];
int n, k;
void build(int v, int tl, int tr) {
if (tl == tr) {
t[v] = node(a[tl], tl);
} else {
int tm = (tl + tr) >> 1;
int next = v << 1;
build(next, tl, tm);
build(next + 1, tm + 1, tr);
t[v] = max(t[next], t[next + 1]);
}
}
node query(int v, int tl, int tr, int l, int r) {
if (l > tr || r < tl) return node(-INF, int(1e9));
if (l <= tl && tr <= r) return t[v];
int tm = (tl + tr) >> 1;
int next = v << 1;
node left_max = query(next, tl, tm, l, r);
node right_max = query(next + 1, tm + 1, tr, l, r);
return max(left_max, right_max);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> k;
for (int i = 0; i < n; i++) {
cin >> b[i];
if (i > 0) b[i] += b[i - 1];
a[i] = -INF;
}
for (int i = 0; i + k - 1 < n; i++) {
a[i] = b[i + k - 1];
if (i > 0) a[i] -= b[i - 1];
}
build(1, 0, n);
int aa, bb;
long long best = -INF;
for (int i = 0; i + k + k - 1 < n; i++) {
node m = query(1, 0, n, i + k, n);
long long curr = a[i] + m.sum;
if (curr > best) {
aa = i + 1;
bb = m.id + 1;
best = curr;
}
}
cout << aa << " " << bb << endl;
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Imagine that you are in a building that has exactly n floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to n. Now you're on the floor number a. You are very bored, so you want to take the lift. Floor number b has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make k consecutive trips in the lift.
Let us suppose that at the moment you are on the floor number x (initially, you were on floor a). For another trip between floors you choose some floor with number y (y ≠ x) and the lift travels to this floor. As you cannot visit floor b with the secret lab, you decided that the distance from the current floor x to the chosen y must be strictly less than the distance from the current floor x to floor b with the secret lab. Formally, it means that the following inequation must fulfill: |x - y| < |x - b|. After the lift successfully transports you to floor y, you write down number y in your notepad.
Your task is to find the number of distinct number sequences that you could have written in the notebook as the result of k trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by 1000000007 (109 + 7).
Input
The first line of the input contains four space-separated integers n, a, b, k (2 ≤ n ≤ 5000, 1 ≤ k ≤ 5000, 1 ≤ a, b ≤ n, a ≠ b).
Output
Print a single integer — the remainder after dividing the sought number of sequences by 1000000007 (109 + 7).
Examples
Input
5 2 4 1
Output
2
Input
5 2 4 2
Output
2
Input
5 3 4 1
Output
0
Note
Two sequences p1, p2, ..., pk and q1, q2, ..., qk are distinct, if there is such integer j (1 ≤ j ≤ k), that pj ≠ qj.
Notes to the samples:
1. In the first sample after the first trip you are either on floor 1, or on floor 3, because |1 - 2| < |2 - 4| and |3 - 2| < |2 - 4|.
2. In the second sample there are two possible sequences: (1, 2); (1, 3). You cannot choose floor 3 for the first trip because in this case no floor can be the floor for the second trip.
3. In the third sample there are no sought sequences, because you cannot choose the floor for the first trip.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
const long long maxn = 5005;
const long long inf = 1ll << 50;
long long dp[maxn][maxn];
long long psum[maxn];
inline long long get_sum(long long a, long long b) {
return (psum[b] - psum[a - 1] + mod) % mod;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long n, a, b, k;
cin >> n >> a >> b >> k;
dp[0][a] = 1;
for (int i = 1; i <= k; i++) {
for (int j = 1; j <= n; j++) {
psum[j] = psum[j - 1] + dp[i - 1][j];
psum[j] %= mod;
}
for (int j = 1; j < b; j++) {
dp[i][j] = get_sum(1, (b + j - 1) >> 1) - dp[i - 1][j] + mod;
dp[i][j] %= mod;
}
for (int j = b + 1; j <= n; j++) {
dp[i][j] = get_sum(((b + j) >> 1) + 1, n) - dp[i - 1][j] + mod;
dp[i][j] %= mod;
}
}
long long ans = 0;
for (int i = 1; i <= n; i++) {
ans += dp[k][i];
ans %= mod;
}
cout << ans << "\n";
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
You've got a string a_1, a_2, ..., a_n, consisting of zeros and ones.
Let's call a sequence of consecutive elements a_i, a_{i + 1}, …, a_j (1≤ i≤ j≤ n) a substring of string a.
You can apply the following operations any number of times:
* Choose some substring of string a (for example, you can choose entire string) and reverse it, paying x coins for it (for example, «0101101» → «0111001»);
* Choose some substring of string a (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones — by zeros), paying y coins for it (for example, «0101101» → «0110001»).
You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.
What is the minimum number of coins you need to spend to get a string consisting only of ones?
Input
The first line of input contains integers n, x and y (1 ≤ n ≤ 300 000, 0 ≤ x, y ≤ 10^9) — length of the string, cost of the first operation (substring reverse) and cost of the second operation (inverting all elements of substring).
The second line contains the string a of length n, consisting of zeros and ones.
Output
Print a single integer — the minimum total cost of operations you need to spend to get a string consisting only of ones. Print 0, if you do not need to perform any operations.
Examples
Input
5 1 10
01000
Output
11
Input
5 10 1
01000
Output
2
Input
7 2 3
1111111
Output
0
Note
In the first sample, at first you need to reverse substring [1 ... 2], and then you need to invert substring [2 ... 5].
Then the string was changed as follows:
«01000» → «10000» → «11111».
The total cost of operations is 1 + 10 = 11.
In the second sample, at first you need to invert substring [1 ... 1], and then you need to invert substring [3 ... 5].
Then the string was changed as follows:
«01000» → «11000» → «11111».
The overall cost is 1 + 1 = 2.
In the third example, string already consists only of ones, so the answer is 0.
### Response
```cpp
#include <bits/stdc++.h>
template <class T>
inline bool chmax(T& a, T b) {
if (a < b) {
a = b;
return 1;
}
return 0;
}
template <class T>
inline bool chmin(T& a, T b) {
if (a > b) {
a = b;
return 1;
}
return 0;
}
constexpr long long MAX = 5100000;
constexpr long long INF = 1LL << 60;
constexpr int inf = 1 << 28;
constexpr long long mod = 998244353LL;
using namespace std;
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
long long n, x, y;
cin >> n >> x >> y;
string s;
cin >> s;
s.erase(unique(s.begin(), s.end()), s.end());
n = s.size();
int cnt = 0;
for (int i = 0; i < s.size(); i++) cnt += (s[i] == '0');
long long res = cnt * y;
for (int i = 1; i < cnt; i++) {
chmin(res, i * x + (cnt - i) * y);
}
cout << res << endl;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
There are well-known formulas: <image>, <image>, <image>. Also mathematicians found similar formulas for higher degrees.
Find the value of the sum <image> modulo 109 + 7 (so you should find the remainder after dividing the answer by the value 109 + 7).
Input
The only line contains two integers n, k (1 ≤ n ≤ 109, 0 ≤ k ≤ 106).
Output
Print the only integer a — the remainder after dividing the value of the sum by the value 109 + 7.
Examples
Input
4 1
Output
10
Input
4 2
Output
30
Input
4 3
Output
100
Input
4 0
Output
4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
const int mod = 1e9 + 7;
int pre[N], suf[N], inv[N];
inline int power(int a, int b) {
int res = 1;
for (; b; b >>= 1, a = 1ll * a * a % mod)
if (b & 1) res = 1ll * res * a % mod;
return res;
}
int main() {
int n, m, s = 0, ans = 0;
scanf("%d%d", &n, &m);
if (m == 0) {
printf("%d\n", n);
return 0;
}
inv[1] = 1;
for (int i = 2; i <= m + 1; i++)
inv[i] = 1ll * (mod - mod / i) * inv[mod % i] % mod;
inv[0] = 1;
for (int i = 1; i <= m + 1; i++) inv[i] = 1ll * inv[i] * inv[i - 1] % mod;
pre[0] = n;
for (int i = 1; i <= m + 1; i++) pre[i] = 1ll * pre[i - 1] * (n - i) % mod;
suf[m + 1] = n - (m + 1);
for (int i = m; i >= 0; i--) suf[i] = 1ll * suf[i + 1] * (n - i) % mod;
for (int i = 0; i <= m + 1; i++) {
s = (s + power(i, m)) % mod;
int delta =
1ll * (i == 0 ? 1 : pre[i - 1]) * (i == m + 1 ? 1 : suf[i + 1]) % mod;
delta = 1ll * delta * inv[i] % mod * inv[m + 1 - i] % mod;
if ((m + 1 - i) & 1) delta = mod - delta;
ans = (ans + 1ll * s * delta % mod) % mod;
}
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top.
Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower.
<image>
However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.
Write a program that models the behavior of Ankh-Morpork residents.
Input
The first line contains single integer n (1 ≤ n ≤ 100 000) — the total number of snacks.
The second line contains n integers, the i-th of them equals the size of the snack which fell on the i-th day. Sizes are distinct integers from 1 to n.
Output
Print n lines. On the i-th of them print the sizes of the snacks which the residents placed on the top of the Snacktower on the i-th day in the order they will do that. If no snack is placed on some day, leave the corresponding line empty.
Examples
Input
3
3 1 2
Output
3
2 1
Input
5
4 5 1 2 3
Output
5 4
3 2 1
Note
In the example a snack of size 3 fell on the first day, and the residents immediately placed it. On the second day a snack of size 1 fell, and the residents weren't able to place it because they were missing the snack of size 2. On the third day a snack of size 2 fell, and the residents immediately placed it. Right after that they placed the snack of size 1 which had fallen before.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename Arg1>
void __f(const char* name, Arg1&& arg1) {
cerr << name << " : " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args) {
const char* comma = strchr(names + 1, ',');
cerr.write(names, comma - names) << " : " << arg1 << " | ";
__f(comma + 1, args...);
}
const int N = int(1e5) + 10;
bool vis[N];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
vector<int> v;
int last = n;
for (int i = (int)0; i < (int)n; i++) {
int x;
cin >> x;
vis[x] = 1;
if (x == last) {
while (vis[last]) {
cout << last << " ";
last--;
}
}
cout << endl;
}
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
JOI has a stove in your room. JOI himself is resistant to the cold, so he doesn't need to put on the stove when he is alone in the room, but he needs to put on the stove when there are visitors.
On this day, there are N guests under JOI. The ith (1 \ leq i \ leq N) visitor arrives at time T_i and leaves at time T_i + 1. There can never be more than one visitor at the same time.
JOI can turn the stove on and off at any time. However, each time you turn on the stove, you will consume one match. JOI has only K matches, so he can only stove up to K times. The stove is gone at the beginning of the day.
When the stove is on, fuel is consumed by that amount, so I want to set the time when the stove is on and off and minimize the total time when the stove is on.
Example
Input
3 2
1
3
6
Output
4
### Response
```cpp
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
int n, k; cin >> n >> k;
vector<long long>v;
long long a; cin >> a;
for (int i = 1; i < n; i++) {
long long b; cin >> b;
v.push_back(b - a - 1);
a = b;
}
sort(v.begin(), v.end());
int ans = n;
for (int i = 0; i < n - k; i++)ans += v[i];
cout << ans << endl;
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.
Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
Input
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
Output
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).
If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:
* the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company,
* the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company,
* the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,
Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.
See the samples to better understand the statement.
Examples
Input
5 1 2 5 5 2
Output
5
AAAAA
BBBBB
BBBBB
CCCCC
CCCCC
Input
4 4 2 6 4 2
Output
6
BBBBBB
BBBBBB
AAAACC
AAAACC
AAAACC
AAAACC
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int x[3], y[3], flag[3], ss[3];
int main() {
int a = 0, s = 0;
;
for (int i = 0; i < 3; i++) {
scanf("%d %d", x + i, y + i);
if (x[i] < y[i]) swap(x[i], y[i]);
a = max(a, x[i]);
ss[i] = x[i] * y[i];
s += x[i] * y[i];
}
if (a * a != s) {
printf("-1");
return 0;
}
printf("%d\n", a);
int b = a;
for (int i = 0; i < 3; i++) {
if (x[i] == a) {
for (int j = 0; j < y[i]; j++) {
cout << string(a, 'A' + i);
printf("\n");
}
flag[i] = 1;
b -= y[i];
}
}
for (int i = 0; i < b; i++) {
for (int j = 0; j < 3; j++) {
if (!flag[j]) {
if (x[j] == b)
cout << string(y[j], 'A' + j);
else
cout << string(x[j], 'A' + j);
}
}
printf("\n");
}
}
``` |
### Prompt
Generate a cpp solution to the following problem:
You are given several queries. In the i-th query you are given a single positive integer ni. You are to represent ni as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings.
An integer greater than 1 is composite, if it is not prime, i.e. if it has positive divisors not equal to 1 and the integer itself.
Input
The first line contains single integer q (1 ≤ q ≤ 105) — the number of queries.
q lines follow. The (i + 1)-th line contains single integer ni (1 ≤ ni ≤ 109) — the i-th query.
Output
For each query print the maximum possible number of summands in a valid splitting to composite summands, or -1, if there are no such splittings.
Examples
Input
1
12
Output
3
Input
2
6
8
Output
1
2
Input
3
1
2
3
Output
-1
-1
-1
Note
12 = 4 + 4 + 4 = 4 + 8 = 6 + 6 = 12, but the first splitting has the maximum possible number of summands.
8 = 4 + 4, 6 can't be split into several composite summands.
1, 2, 3 are less than any composite number, so they do not have valid splittings.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename T>
T next_int() {
T x = 0, p = 1;
char ch;
do {
ch = getchar();
} while (ch <= ' ');
if (ch == '-') {
p = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = x * 10 + (ch - '0');
ch = getchar();
}
return p * x;
}
string next_token() {
char ch;
string ans = "";
do {
ch = getchar();
} while (ch <= ' ');
while (ch > ' ') {
ans += ch;
ch = getchar();
}
return ans;
}
const long long INF = (long long)1e18;
const int INFINT = (int)1e9 + 227 + 1;
const int MAXN = (int)1e6 + 227 + 1;
const int MOD = (int)1e9 + 7;
const long double EPS = 1e-9;
long long bin_pow(long long a, long long b) {
if (!b) return 1;
long long ans = bin_pow(a, b / 2);
ans = ans * ans % MOD;
if (b % 2) ans = ans * a % MOD;
return ans;
}
bool used[MAXN];
void build_prime() {
for (int i = 2; i < MAXN; i++) {
if (used[i]) continue;
for (int j = i + i; j < MAXN; j += i) {
used[j] = 1;
}
}
}
bool check(int a) {
if (!a) return 1;
for (int i = 2; i * i <= a; i++)
if (a % i == 0) return 1;
return 0;
}
int dp[MAXN];
int full(int n) {
int ans = n / 4;
while (ans >= 0 && !check(n - ans * 4)) ans--;
if (ans != -1 && ans * 4 != n) ans += dp[n - ans * 4];
return ans;
}
int main() {
build_prime();
for (int i = 0; i * i <= MAXN; i++) dp[i] = -INFINT;
dp[0] = 0;
for (int j = 2; j * j <= MAXN; j++) {
if (!used[j]) continue;
for (int i = 0; i * i <= MAXN; i++) {
dp[i + j] = max(dp[i + j], dp[i] + 1);
}
}
int test;
cin >> test;
while (test--) {
int n = next_int<int>();
cout << full(n) << "\n";
}
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Gaius Julius Caesar, a famous general, loved to line up his soldiers. Overall the army had n1 footmen and n2 horsemen. Caesar thought that an arrangement is not beautiful if somewhere in the line there are strictly more that k1 footmen standing successively one after another, or there are strictly more than k2 horsemen standing successively one after another. Find the number of beautiful arrangements of the soldiers.
Note that all n1 + n2 warriors should be present at each arrangement. All footmen are considered indistinguishable among themselves. Similarly, all horsemen are considered indistinguishable among themselves.
Input
The only line contains four space-separated integers n1, n2, k1, k2 (1 ≤ n1, n2 ≤ 100, 1 ≤ k1, k2 ≤ 10) which represent how many footmen and horsemen there are and the largest acceptable number of footmen and horsemen standing in succession, correspondingly.
Output
Print the number of beautiful arrangements of the army modulo 100000000 (108). That is, print the number of such ways to line up the soldiers, that no more than k1 footmen stand successively, and no more than k2 horsemen stand successively.
Examples
Input
2 1 1 10
Output
1
Input
2 3 1 2
Output
5
Input
2 4 1 1
Output
0
Note
Let's mark a footman as 1, and a horseman as 2.
In the first sample the only beautiful line-up is: 121
In the second sample 5 beautiful line-ups exist: 12122, 12212, 21212, 21221, 22121
### Response
```cpp
#include <bits/stdc++.h>
int dp[213][213][2][13];
int n1, n2, k1, k2;
int main() {
scanf("%d%d%d%d", &n1, &n2, &k1, &k2);
dp[1][0][0][1] = dp[0][1][1][1] = 1;
dp[0][1][0][1] = dp[1][0][1][1] = 0;
for (int i = 0; i <= n1; i++) {
for (int j = 0; j <= n2; j++) {
if (i > 0)
for (int k = 2; k <= k1; k++) {
dp[i][j][0][k] = dp[i - 1][j][0][k - 1];
}
if (j > 0)
for (int k = 2; k <= k2; k++) {
dp[i][j][1][k] = dp[i][j - 1][1][k - 1];
}
if (i + j != 1) dp[i][j][1][1] = dp[i][j][0][1] = 0;
if (i > 0) {
for (int k = 1; k <= k2; k++) {
dp[i][j][0][1] += dp[i - 1][j][1][k];
}
dp[i][j][0][1] %= 100000000;
}
if (j > 0) {
for (int k = 1; k <= k1; k++) {
dp[i][j][1][1] += dp[i][j - 1][0][k];
}
dp[i][j][1][1] %= 100000000;
}
}
}
int ans = 0;
for (int i = 1; i <= k1; i++) {
ans += dp[n1][n2][0][i];
ans %= 100000000;
}
for (int i = 1; i <= k2; i++) {
ans += dp[n1][n2][1][i];
ans %= 100000000;
}
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Alice and Bob begin their day with a quick game. They first choose a starting number X0 ≥ 3 and try to reach one million by the process described below.
Alice goes first and then they take alternating turns. In the i-th turn, the player whose turn it is selects a prime number smaller than the current number, and announces the smallest multiple of this prime number that is not smaller than the current number.
Formally, he or she selects a prime p < Xi - 1 and then finds the minimum Xi ≥ Xi - 1 such that p divides Xi. Note that if the selected prime p already divides Xi - 1, then the number does not change.
Eve has witnessed the state of the game after two turns. Given X2, help her determine what is the smallest possible starting number X0. Note that the players don't necessarily play optimally. You should consider all possible game evolutions.
Input
The input contains a single integer X2 (4 ≤ X2 ≤ 106). It is guaranteed that the integer X2 is composite, that is, is not prime.
Output
Output a single integer — the minimum possible X0.
Examples
Input
14
Output
6
Input
20
Output
15
Input
8192
Output
8191
Note
In the first test, the smallest possible starting number is X0 = 6. One possible course of the game is as follows:
* Alice picks prime 5 and announces X1 = 10
* Bob picks prime 7 and announces X2 = 14.
In the second case, let X0 = 15.
* Alice picks prime 2 and announces X1 = 16
* Bob picks prime 5 and announces X2 = 20.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int x2, t[1010000];
int mx, x1, MIN;
vector<int> s;
int main() {
t[1] = 1;
for (int i = 2; i <= 1000010; i++) {
if (!t[i]) {
for (int j = 2 * i; j <= 1000010; j += i) t[j] = 1;
}
}
scanf("%d", &x2);
for (int i = 1; i * i <= x2; i++) {
if (x2 % i == 0) {
s.push_back(i);
s.push_back(x2 / i);
}
}
sort(s.begin(), s.end());
for (int i = (int)s.size() - 1; i >= 0; i--) {
if (!t[s[i]]) {
mx = s[i];
break;
}
}
MIN = 1e9;
for (int x1 = x2 - mx + 1; x1 <= x2; x1++) {
for (int i = 2; i * i <= x1; i++) {
if (x1 % i == 0) {
if (!t[x1 / i]) MIN = min(MIN, x1 - x1 / i + 1);
if (!t[i]) MIN = min(MIN, x1 - i + 1);
}
}
}
printf("%d\n", MIN);
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Ivan has an array consisting of n different integers. He decided to reorder all elements in increasing order. Ivan loves merge sort so he decided to represent his array with one or several increasing sequences which he then plans to merge into one sorted array.
Ivan represent his array with increasing sequences with help of the following algorithm.
While there is at least one unused number in array Ivan repeats the following procedure:
* iterate through array from the left to the right;
* Ivan only looks at unused numbers on current iteration;
* if current number is the first unused number on this iteration or this number is greater than previous unused number on current iteration, then Ivan marks the number as used and writes it down.
For example, if Ivan's array looks like [1, 3, 2, 5, 4] then he will perform two iterations. On first iteration Ivan will use and write numbers [1, 3, 5], and on second one — [2, 4].
Write a program which helps Ivan and finds representation of the given array with one or several increasing sequences in accordance with algorithm described above.
Input
The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of elements in Ivan's array.
The second line contains a sequence consisting of distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — Ivan's array.
Output
Print representation of the given array in the form of one or more increasing sequences in accordance with the algorithm described above. Each sequence must be printed on a new line.
Examples
Input
5
1 3 2 5 4
Output
1 3 5
2 4
Input
4
4 3 2 1
Output
4
3
2
1
Input
4
10 30 50 101
Output
10 30 50 101
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int n = 0, c = 0, m;
while (!isdigit(c)) m = c - 45 ? 1 : -1, c = getchar();
while (isdigit(c)) n = n * 10 + c - 48, c = getchar();
return m * n;
}
const int N = 200001;
vector<int> ans[N];
int a[N];
int t[4 * N];
void update(int v, int tl, int tr, int id, int x) {
if (tl == tr) {
t[v] = x;
return;
}
int tm = (tl + tr) >> 1;
if (id <= tm) {
update(2 * v, tl, tm, id, x);
} else
update(2 * v + 1, tm + 1, tr, id, x);
t[v] = min(t[2 * v], t[2 * v + 1]);
}
int get_min(int v, int tl, int tr, int l, int r) {
if (l == tl && r == tr) {
return t[v];
}
int tm = (tl + tr) >> 1;
if (r <= tm)
return get_min(2 * v, tl, tm, l, r);
else if (l > tm)
return get_min(2 * v + 1, tm + 1, tr, l, r);
return min(get_min(2 * v, tl, tm, l, tm),
get_min(2 * v + 1, tm + 1, tr, tm + 1, r));
}
int us[N];
int main() {
map<int, int> mp;
int n = read();
for (int i = 1; i <= n; i++) {
a[i] = read();
mp[a[i]];
}
int cnt = 0;
for (auto i : mp) {
mp[i.first] = ++cnt;
}
for (int i = 1; i < 4 * N; i++) t[i] = 1e9;
int l = 0;
for (int i = 1; i <= n; i++) {
int t = mp[a[i]];
us[t] = a[i];
int g = get_min(1, 1, n, 1, t);
if (g == 1e9) {
++l;
g = l;
ans[g].push_back(t);
} else {
int u = ans[g][ans[g].size() - 1];
update(1, 1, n, u, 1e9);
ans[g].push_back(t);
}
update(1, 1, n, t, g);
}
for (int i = 1; i <= l; i++) {
for (int j : ans[i]) cout << us[j] << " ";
cout << "\n";
}
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
You are given an array a consisting of n integers, and additionally an integer m. You have to choose some sequence of indices b1, b2, ..., bk (1 ≤ b1 < b2 < ... < bk ≤ n) in such a way that the value of <image> is maximized. Chosen sequence can be empty.
Print the maximum possible value of <image>.
Input
The first line contains two integers n and m (1 ≤ n ≤ 35, 1 ≤ m ≤ 109).
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Output
Print the maximum possible value of <image>.
Examples
Input
4 4
5 2 4 1
Output
3
Input
3 20
199 41 299
Output
19
Note
In the first example you can choose a sequence b = {1, 2}, so the sum <image> is equal to 7 (and that's 3 after taking it modulo 4).
In the second example you can choose a sequence b = {3}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long n, m;
cin >> n >> m;
long long a[n];
for (long long i = 0; i < n; i++) cin >> a[i], a[i] %= m;
vector<long long> w;
long long kol = 1 << (n / 2), r = n / 2;
for (long long mask = 0; mask < kol; ++mask) {
long long sum = 0;
for (long long i = 0; i < r; ++i)
if ((1 << i) & mask) sum += a[i];
w.emplace_back(sum % m);
}
sort((w).begin(), (w).end());
long long ans = 0, r1 = r;
kol = 1 << (n - r), r = n - r;
for (long long mask = 0; mask < kol; ++mask) {
long long sum = 0;
for (long long i = 0; i < r; ++i)
if ((1 << i) & mask) sum += a[i + r1];
sum %= m;
auto q = lower_bound((w).begin(), (w).end(), m - sum);
if (q != w.begin()) q--;
long long q1 = *q;
ans = max(ans, (sum + q1) % m);
}
cout << ans << '\n';
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
You are given an array a consisting of n integers.
You can remove at most one element from this array. Thus, the final length of the array is n-1 or n.
Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.
Recall that the contiguous subarray a with indices from l to r is a[l ... r] = a_l, a_{l + 1}, ..., a_r. The subarray a[l ... r] is called strictly increasing if a_l < a_{l+1} < ... < a_r.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array a after removing at most one element.
Examples
Input
5
1 2 5 3 4
Output
4
Input
2
1 2
Output
2
Input
7
6 5 4 3 2 4 3
Output
2
Note
In the first example, you can delete a_3=5. Then the resulting array will be equal to [1, 2, 3, 4] and the length of its largest increasing subarray will be equal to 4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int inf = 1000000005;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
vector<int> v(n + 2);
for (int i = 1; i <= n; i++) {
cin >> v[i];
}
v[0] = inf;
v[n + 1] = -1;
vector<int> l(n + 2, 1);
vector<int> r(n + 2, 1);
for (int i = 1; i <= n; i++) {
if (v[i] > v[i - 1]) {
l[i] = l[i - 1] + 1;
}
}
for (int i = n; i >= 1; i--) {
if (v[i] < v[i + 1]) {
r[i] = r[i + 1] + 1;
}
}
int best = 0;
for (int i = 1; i <= n; i++) {
best = max({best, l[i], r[i]});
if (v[i - 1] < v[i + 1]) {
best = max(best, l[i - 1] + r[i + 1]);
}
}
cout << best << endl;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Once Petya read a problem about a bracket sequence. He gave it much thought but didn't find a solution. Today you will face it.
You are given string s. It represents a correct bracket sequence. A correct bracket sequence is the sequence of opening ("(") and closing (")") brackets, such that it is possible to obtain a correct mathematical expression from it, inserting numbers and operators between the brackets. For example, such sequences as "(())()" and "()" are correct bracket sequences and such sequences as ")()" and "(()" are not.
In a correct bracket sequence each bracket corresponds to the matching bracket (an opening bracket corresponds to the matching closing bracket and vice versa). For example, in a bracket sequence shown of the figure below, the third bracket corresponds to the matching sixth one and the fifth bracket corresponds to the fourth one.
<image>
You are allowed to color some brackets in the bracket sequence so as all three conditions are fulfilled:
* Each bracket is either not colored any color, or is colored red, or is colored blue.
* For any pair of matching brackets exactly one of them is colored. In other words, for any bracket the following is true: either it or the matching bracket that corresponds to it is colored.
* No two neighboring colored brackets have the same color.
Find the number of different ways to color the bracket sequence. The ways should meet the above-given conditions. Two ways of coloring are considered different if they differ in the color of at least one bracket. As the result can be quite large, print it modulo 1000000007 (109 + 7).
Input
The first line contains the single string s (2 ≤ |s| ≤ 700) which represents a correct bracket sequence.
Output
Print the only number — the number of ways to color the bracket sequence that meet the above given conditions modulo 1000000007 (109 + 7).
Examples
Input
(())
Output
12
Input
(()())
Output
40
Input
()
Output
4
Note
Let's consider the first sample test. The bracket sequence from the sample can be colored, for example, as is shown on two figures below.
<image> <image>
The two ways of coloring shown below are incorrect.
<image> <image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 800;
const int mod = 1e9 + 7;
int dp[N][N][3][3];
string s;
stack<int> st;
int p[N], fp[N];
bool judge(int c1, int c2) { return c1 == 0 || c2 == 0 || c1 != c2; }
long long dfs(int l, int r, int lc, int rc) {
if (dp[l][r][lc][rc] != -1) return dp[l][r][lc][rc];
if (l + 1 > r) return dp[l][r][lc][rc] = 0;
if (l == r) return dp[l][r][lc][rc] = 1LL;
long long ans = 0;
int k = p[l];
if (k == r) {
if ((lc == 0 && rc) || (lc && rc == 0)) {
if (l + 1 == r) return dp[l][r][lc][rc] = 1LL;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (judge(lc, i) && judge(j, rc)) {
ans = (ans + dfs(l + 1, r - 1, i, j)) % mod;
}
}
}
}
} else if (k < r) {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (judge(i, j))
ans = (ans + dfs(l, k, lc, i) * dfs(k + 1, r, j, rc) % mod) % mod;
}
}
}
return dp[l][r][lc][rc] = ans % mod;
}
int main() {
cin >> s;
memset(p, -1, sizeof p);
memset(fp, -1, sizeof fp);
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '(')
st.push(i);
else {
int pos = st.top();
st.pop();
p[pos] = i;
fp[i] = pos;
}
}
memset(dp, -1, sizeof dp);
long long ans = 0;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
ans = (ans + dfs(0, s.size() - 1, i, j)) % mod;
}
}
cout << ans;
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
You are given two non-negative integers L and R. We will choose two integers i and j such that L \leq i < j \leq R. Find the minimum possible value of (i \times j) \mbox{ mod } 2019.
Constraints
* All values in input are integers.
* 0 \leq L < R \leq 2 \times 10^9
Input
Input is given from Standard Input in the following format:
L R
Output
Print the minimum possible value of (i \times j) \mbox{ mod } 2019 when i and j are chosen under the given condition.
Examples
Input
2020 2040
Output
2
Input
4 5
Output
20
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
long long a,b;
cin>>a>>b;
if(fabs(a-b)>2018){
cout<<0<<endl;
return 0;
}
ll mi=10000;
for(ll i=a;i<=b;i++){
for(ll j=i+1;j<=b;j++){
if(i*j%2019<mi){
mi=i*j%2019;
}
}
}
cout<<mi<<endl;
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had c pages.
At first day Mister B read v0 pages, but after that he started to speed up. Every day, starting from the second, he read a pages more than on the previous day (at first day he read v0 pages, at second — v0 + a pages, at third — v0 + 2a pages, and so on). But Mister B is just a human, so he physically wasn't able to read more than v1 pages per day.
Also, to refresh his memory, every day, starting from the second, Mister B had to reread last l pages he read on the previous day. Mister B finished the book when he read the last page for the first time.
Help Mister B to calculate how many days he needed to finish the book.
Input
First and only line contains five space-separated integers: c, v0, v1, a and l (1 ≤ c ≤ 1000, 0 ≤ l < v0 ≤ v1 ≤ 1000, 0 ≤ a ≤ 1000) — the length of the book in pages, the initial reading speed, the maximum reading speed, the acceleration in reading speed and the number of pages for rereading.
Output
Print one integer — the number of days Mister B needed to finish the book.
Examples
Input
5 5 10 5 4
Output
1
Input
12 4 12 4 1
Output
3
Input
15 1 100 0 0
Output
15
Note
In the first sample test the book contains 5 pages, so Mister B read it right at the first day.
In the second sample test at first day Mister B read pages number 1 - 4, at second day — 4 - 11, at third day — 11 - 12 and finished the book.
In third sample test every day Mister B read 1 page of the book, so he finished in 15 days.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long N = 2e5 + 5;
const long long mod = 1e9 + 7;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long c, v0, v1, a, l, ans = 0;
cin >> c >> v0 >> v1 >> a >> l;
long long tot = 0;
while (tot < c) {
long long add = v0 - l * (ans > 0);
tot = tot + add;
v0 = min(v0 + a, v1);
ans++;
}
cout << ans;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Mad scientist Mike has constructed a rooted tree, which consists of n vertices. Each vertex is a reservoir which can be either empty or filled with water.
The vertices of the tree are numbered from 1 to n with the root at vertex 1. For each vertex, the reservoirs of its children are located below the reservoir of this vertex, and the vertex is connected with each of the children by a pipe through which water can flow downwards.
Mike wants to do the following operations with the tree:
1. Fill vertex v with water. Then v and all its children are filled with water.
2. Empty vertex v. Then v and all its ancestors are emptied.
3. Determine whether vertex v is filled with water at the moment.
Initially all vertices of the tree are empty.
Mike has already compiled a full list of operations that he wants to perform in order. Before experimenting with the tree Mike decided to run the list through a simulation. Help Mike determine what results will he get after performing all the operations.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 500000) — the number of vertices in the tree. Each of the following n - 1 lines contains two space-separated numbers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the edges of the tree.
The next line contains a number q (1 ≤ q ≤ 500000) — the number of operations to perform. Each of the following q lines contains two space-separated numbers ci (1 ≤ ci ≤ 3), vi (1 ≤ vi ≤ n), where ci is the operation type (according to the numbering given in the statement), and vi is the vertex on which the operation is performed.
It is guaranteed that the given graph is a tree.
Output
For each type 3 operation print 1 on a separate line if the vertex is full, and 0 if the vertex is empty. Print the answers to queries in the order in which the queries are given in the input.
Examples
Input
5
1 2
5 1
2 3
4 2
12
1 1
2 3
3 1
3 2
3 3
3 4
1 2
2 4
3 1
3 3
3 4
3 5
Output
0
0
0
1
0
1
0
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 500005;
struct IntervalTree {
void init(int N) {
this->N = N;
it.resize(4 * N + 1, 0);
lazy.resize(4 * N + 1, -1);
}
void lazyUpdate(int p, int L, int R) {
if (lazy[p] != -1) {
if (lazy[p] == 0)
it[p] = 0;
else
it[p] = R - L + 1;
if (L != R) {
lazy[p * 2] = lazy[p * 2 + 1] = lazy[p];
}
lazy[p] = -1;
}
}
void update(int p, int L, int R, int u, int v, int val) {
lazyUpdate(p, L, R);
if (R < u || L > v) return;
if (L >= u && R <= v) {
lazy[p] = val;
lazyUpdate(p, L, R);
return;
}
int M = (L + R) >> 1;
update(p * 2, L, M, u, v, val);
update(p * 2 + 1, M + 1, R, u, v, val);
it[p] = it[p * 2] + it[p * 2 + 1];
}
int query(int p, int L, int R, int u, int v) {
lazyUpdate(p, L, R);
if (R < u || L > v) return -1;
if (L >= u && R <= v) return it[p];
int M = (L + R) >> 1;
int p1 = query(p * 2, L, M, u, v);
int p2 = query(p * 2 + 1, M + 1, R, u, v);
if (p1 == -1) return p2;
if (p2 == -1) return p1;
return p1 + p2;
}
int N;
vector<int> it, lazy;
};
int L[MAXN], R[MAXN], p[MAXN];
vector<int> adj[MAXN];
int n, m;
void dfs(int u, int pa) {
L[u] = ++m;
for (int i = 0; i < int(adj[u].size()); i++) {
int v = adj[u][i];
if (v == pa) continue;
p[v] = u;
dfs(v, u);
}
R[u] = m;
}
int main() {
ios::sync_with_stdio(0);
cin >> n;
for (int i = 1; i < n; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs(1, 0);
IntervalTree it;
it.init(n);
int q;
cin >> q;
while (q--) {
int c, v;
cin >> c >> v;
if (c == 1) {
int x = R[v] - L[v] + 1 - it.query(1, 1, n, L[v], R[v]);
it.update(1, 1, n, L[v], R[v], 1);
if (x > 0 && v != 1) it.update(1, 1, n, L[p[v]], L[p[v]], 0);
} else if (c == 2) {
it.update(1, 1, n, L[v], L[v], 0);
} else {
int x = R[v] - L[v] + 1 - it.query(1, 1, n, L[v], R[v]);
if (x > 0)
cout << "0\n";
else
cout << "1\n";
}
}
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
Maksim has n objects and m boxes, each box has size exactly k. Objects are numbered from 1 to n in order from left to right, the size of the i-th object is a_i.
Maksim wants to pack his objects into the boxes and he will pack objects by the following algorithm: he takes one of the empty boxes he has, goes from left to right through the objects, and if the i-th object fits in the current box (the remaining size of the box is greater than or equal to a_i), he puts it in the box, and the remaining size of the box decreases by a_i. Otherwise he takes the new empty box and continues the process above. If he has no empty boxes and there is at least one object not in some box then Maksim cannot pack the chosen set of objects.
Maksim wants to know the maximum number of objects he can pack by the algorithm above. To reach this target, he will throw out the leftmost object from the set until the remaining set of objects can be packed in boxes he has. Your task is to say the maximum number of objects Maksim can pack in boxes he has.
Each time when Maksim tries to pack the objects into the boxes, he will make empty all the boxes he has before do it (and the relative order of the remaining set of objects will not change).
Input
The first line of the input contains three integers n, m, k (1 ≤ n, m ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 10^9) — the number of objects, the number of boxes and the size of each box.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the size of the i-th object.
Output
Print the maximum number of objects Maksim can pack using the algorithm described in the problem statement.
Examples
Input
5 2 6
5 2 1 4 2
Output
4
Input
5 1 4
4 2 3 4 1
Output
1
Input
5 3 3
1 2 3 1 1
Output
5
Note
In the first example Maksim can pack only 4 objects. Firstly, he tries to pack all the 5 objects. Distribution of objects will be [5], [2, 1]. Maxim cannot pack the next object in the second box and he has no more empty boxes at all. Next he will throw out the first object and the objects distribution will be [2, 1], [4, 2]. So the answer is 4.
In the second example it is obvious that Maksim cannot pack all the objects starting from first, second, third and fourth (in all these cases the distribution of objects is [4]), but he can pack the last object ([1]).
In the third example Maksim can pack all the objects he has. The distribution will be [1, 2], [3], [1, 1].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int mod1 = 998244353;
long long int mod = 1e9 + 7;
bool comp(long long int x, long long int y) {
if (x > y) return true;
return false;
}
long long int INF = 1e18;
long long int a[200005];
void solve() {
long long int n, m, k;
cin >> n >> m >> k;
for (int i = 0; i < n; ++i) cin >> a[i];
long long int cnt = 1;
long long int i = n - 1;
while (cnt <= m && i >= 0) {
long long int sum = a[i];
while (i - 1 >= 0 && a[i - 1] + sum <= k) {
sum += a[i - 1];
--i;
}
++cnt;
--i;
}
cout << n - i - 1;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long int t = 1;
while (t--) {
solve();
cout << "\n";
}
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Roma found a new character in the game "World of Darkraft - 2". In this game the character fights monsters, finds the more and more advanced stuff that lets him fight stronger monsters.
The character can equip himself with k distinct types of items. Power of each item depends on its level (positive integer number). Initially the character has one 1-level item of each of the k types.
After the victory over the monster the character finds exactly one new randomly generated item. The generation process looks as follows. Firstly the type of the item is defined; each of the k types has the same probability. Then the level of the new item is defined. Let's assume that the level of player's item of the chosen type is equal to t at the moment. Level of the new item will be chosen uniformly among integers from segment [1; t + 1].
From the new item and the current player's item of the same type Roma chooses the best one (i.e. the one with greater level) and equips it (if both of them has the same level Roma choses any). The remaining item is sold for coins. Roma sells an item of level x of any type for x coins.
Help Roma determine the expected number of earned coins after the victory over n monsters.
Input
The first line contains two integers, n and k (1 ≤ n ≤ 105; 1 ≤ k ≤ 100).
Output
Print a real number — expected number of earned coins after victory over n monsters. The answer is considered correct if its relative or absolute error doesn't exceed 10 - 9.
Examples
Input
1 3
Output
1.0000000000
Input
2 1
Output
2.3333333333
Input
10 2
Output
15.9380768924
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, k;
double f[2][1010];
int main() {
scanf("%d%d", &n, &k);
int now = 1;
int t = min(n, 1000);
for (int i = 1; i <= n; i++, now ^= 1) {
for (int j = t; j; j--) {
f[now][j] = ((f[now ^ 1][j + 1] + j) / (j + 1.0) +
j * (f[now ^ 1][j] + (j + 1.0) / 2.0) / (j + 1.0)) /
(k * 1.0) +
(k - 1) * f[now ^ 1][j] / (k * 1.0);
}
}
printf("%.10lf", f[now ^ 1][1] * k);
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Nikola owns a large warehouse which is illuminated by N light bulbs, numbered 1 to N. At the exit of the warehouse, there are S light switches, numbered 1 to S. Each switch swaps the on/off state for some light bulbs, so if a light bulb is off, flipping the switch turns it on, and if the light bulb is on, flipping the switch turns it off.
At the end of the day, Nikola wants to turn all the lights off. To achieve this, he will flip some of the light switches at the exit of the warehouse, but since Nikola is lazy, he wants to flip the _minimum_ number of switches required to turn all the lights off. Since Nikola was not able to calculate the minimum number of switches, he asked you to help him. During a period of D days, Nikola noted which light bulbs were off and which were on at the end of each day. He wants you to tell him the minimum number of switches he needed to flip to turn all the lights off for each of the D days or tell him that it's impossible.
Input
First line contains three integers, N, S and D (1 ≤ N ≤ 10^3, 1 ≤ S ≤ 30, 1 ≤ D ≤ 10^3) – representing number of light bulbs, the number of light switches, and the number of days respectively.
The next S lines contain the description of each light switch as follows: The first number in the line, C_i (1 ≤ C_i ≤ N), represents the number of light bulbs for which the on/off state is swapped by light switch i, the next C_i numbers (sorted in increasing order) represent the indices of those light bulbs.
The next D lines contain the description of light bulbs for each day as follows: The first number in the line, T_i (1 ≤ T_i ≤ N), represents the number of light bulbs which are on at the end of day i, the next T_i numbers (sorted in increasing order) represent the indices of those light bulbs.
Output
Print D lines, one for each day. In the i^{th} line, print the minimum number of switches that need to be flipped on day i, or -1 if it's impossible to turn all the lights off.
Example
Input
4 3 4
2 1 2
2 2 3
1 2
1 1
2 1 3
3 1 2 3
3 1 2 4
Output
2
2
3
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 7;
const long long mod = 998244353;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
int n, s, d;
unsigned long long ok[N];
unsigned long long d1[(1 << 20)], d2[(1 << 10)], a[N];
unordered_map<unsigned long long, int> m;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
for (int i = 0; i < N; i++) ok[i] = rng();
cin >> n >> s >> d;
for (int i = 0; i < s; i++) {
int len;
cin >> len;
for (int j = 1; j <= len; j++) {
int x;
cin >> x;
a[i] ^= ok[x];
}
}
int c = min(20, s);
for (int i = 0; i < c; i++) {
for (int j = 0; j < (1 << i); j++) {
d1[(1 << i) + j] = (d1[j] ^ a[i]);
}
}
for (int i = 0; i < s - c; i++) {
for (int j = 0; j < (1 << i); j++) {
d2[j + (1 << i)] = (d2[j] ^ a[i + c]);
}
}
for (int i = 0; i < (1 << c); i++) {
unsigned long long res = d1[i];
if (m.find(res) == m.end()) {
m[res] = __builtin_popcount(i);
} else {
m[res] = min(m[res], __builtin_popcount(i));
}
}
for (int i = 1; i <= d; i++) {
int len;
cin >> len;
unsigned long long a = 0;
for (int j = 1; j <= len; j++) {
int x;
cin >> x;
a ^= ok[x];
}
int ans = 1e9;
for (int j = 0; j < (1 << s - c); j++) {
auto c = (a ^ d2[j]);
if (m.find(c) != m.end()) {
ans = min(ans, m[c] + __builtin_popcount(j));
}
}
cout << (ans == 1e9 ? -1 : ans) << "\n";
}
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
A long time ago there was a land called Dudeland. Dudeland consisted of n towns connected with n - 1 bidirectonal roads. The towns are indexed from 1 to n and one can reach any city from any other city if he moves along the roads of the country. There are m monasteries in Dudeland located in m different towns. In each monastery lives a pilgrim.
At the beginning of the year, each pilgrim writes down which monastery is the farthest from the monastery he is living in. If there is more than one farthest monastery, he lists all of them. On the Big Lebowski day each pilgrim picks one town from his paper at random and starts walking to that town.
Walter hates pilgrims and wants to make as many of them unhappy as possible by preventing them from finishing their journey. He plans to destroy exactly one town that does not contain a monastery. A pilgrim becomes unhappy if all monasteries in his list become unreachable from the monastery he is living in.
You need to find the maximum number of pilgrims Walter can make unhappy. Also find the number of ways he can make this maximal number of pilgrims unhappy: the number of possible towns he can destroy.
Input
The first line contains two integers n (3 ≤ n ≤ 105) and m (2 ≤ m < n). The next line contains m distinct integers representing indices of towns that contain monasteries.
Next n - 1 lines contain three integers each, ai, bi, ci, indicating that there is an edge between towns ai and bi of length ci (1 ≤ ai, bi ≤ n, 1 ≤ ci ≤ 1000, ai ≠ bi).
Output
Output two integers: the maximum number of pilgrims Walter can make unhappy and the number of ways in which he can make his plan come true.
Examples
Input
8 5
7 2 5 4 8
1 2 1
2 3 2
1 4 1
4 5 2
1 6 1
6 7 8
6 8 10
Output
5 1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> path;
bool special[100010];
vector<pair<int, int> > E[100010];
path up[100010];
path down[100010];
int depth[100010];
int par[100010][18];
int add[100010];
int cover[100010];
ostream& operator<<(ostream& out, const pair<int, int>& p) {
return out << "(" << p.first << "," << p.second << ")";
}
path take_better(const path& a, const path& b, int i) {
if (a.first > b.first) return a;
if (a.first < b.first) return b;
return make_pair(a.first, i);
}
void dfs1(int i, int p) {
if (special[i])
down[i] = make_pair(0, i);
else
down[i] = make_pair(-1000000000, i);
par[i][0] = p;
depth[i] = depth[p] + 1;
int numE = E[i].size();
for (int x = 0; x < (numE); ++x) {
int j = E[i][x].first, c = E[i][x].second;
if (j == p) continue;
dfs1(j, i);
path dd = down[j];
dd.first += c;
down[i] = take_better(down[i], dd, i);
}
}
void dfs2(int i, int p, path withoutMe) {
up[i] = withoutMe;
if (special[i]) up[i] = take_better(up[i], make_pair(0, i), i);
int numE = E[i].size();
path best = up[i], second = make_pair(-1000000000, i),
third = make_pair(-1000000000, i);
for (int x = 0; x < (numE); ++x) {
int j = E[i][x].first, c = E[i][x].second;
if (j == p) continue;
path here = down[j];
here.first += c;
if (here >= best) {
third = second;
second = best;
best = here;
} else if (here >= second) {
third = second;
second = here;
} else if (here >= third) {
third = here;
}
}
for (int x = 0; x < (numE); ++x) {
int j = E[i][x].first, c = E[i][x].second;
if (j == p) continue;
path withoutHim;
path goHere = down[j];
goHere.first += c;
if (goHere == best)
withoutHim = take_better(second, third, i);
else if (goHere == second)
withoutHim = take_better(best, third, i);
else
withoutHim = take_better(best, second, i);
withoutHim.first += c;
dfs2(j, i, withoutHim);
}
}
int nth(int a, int n) {
assert(n >= 0);
for (int k = 0; n; n >>= 1, ++k)
if (n & 1) a = par[a][k];
return a;
}
int lca(int a, int b) {
if (depth[a] < depth[b]) swap(a, b);
a = nth(a, depth[a] - depth[b]);
assert(depth[a] == depth[b]);
for (int k = 18 - 1; k >= 0; --k)
if (par[a][k] != par[b][k]) a = par[a][k], b = par[b][k];
if (a != b) a = b = par[a][0];
return a;
}
bool is_ancestor(int a, int b) { return lca(a, b) == a; }
void update(int i, int v) { add[i] += v; }
void add_path(int i, int j) {
if (is_ancestor(i, j)) {
update(j, 1);
update(par[i][0], -1);
} else if (is_ancestor(j, i)) {
update(i, 1);
update(par[j][0], -1);
} else {
int k = lca(i, j);
update(i, 1);
update(j, 1);
update(k, -1);
update(par[k][0], -1);
}
}
void setup(int N) {
for (int k = (1); k <= (18 - 1); ++k)
for (int i = (1); i <= (N); ++i) par[i][k] = par[par[i][k - 1]][k - 1];
for (int i = (1); i <= (N); ++i) {
if (!special[i]) continue;
path p = take_better(up[i], down[i], i);
int j = p.second;
add_path(i, j);
}
}
int dfs3(int i, int p) {
int sum = add[i];
int numE = E[i].size();
for (int x = 0; x < (numE); ++x) {
int j = E[i][x].first;
if (j == p) continue;
sum += dfs3(j, i);
}
assert(sum >= 0);
cover[i] = sum;
return sum;
}
int main() {
srand(time(NULL));
int N, M, a, b, c;
cin >> N >> M;
for (int i = (1); i <= (M); ++i) {
scanf("%d", &a);
special[a] = true;
}
for (int i = (1); i <= (N - 1); ++i) {
scanf("%d%d%d", &a, &b, &c);
E[a].push_back(make_pair(b, c));
E[b].push_back(make_pair(a, c));
}
path init(-1000000000, 1);
dfs1(1, 0);
dfs2(1, 0, init);
setup(N);
dfs3(1, 0);
int mx = 0;
int cnt = 0;
for (int i = (1); i <= (N); ++i) {
if (special[i]) continue;
if (cover[i] == mx) {
cnt++;
} else if (cover[i] > mx) {
mx = cover[i];
cnt = 1;
}
}
cout << mx << " " << cnt << endl;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Dima loves representing an odd number as the sum of multiple primes, and Lisa loves it when there are at most three primes. Help them to represent the given number as the sum of at most than three primes.
More formally, you are given an odd numer n. Find a set of numbers pi (1 ≤ i ≤ k), such that
1. 1 ≤ k ≤ 3
2. pi is a prime
3. <image>
The numbers pi do not necessarily have to be distinct. It is guaranteed that at least one possible solution exists.
Input
The single line contains an odd number n (3 ≤ n < 109).
Output
In the first line print k (1 ≤ k ≤ 3), showing how many numbers are in the representation you found.
In the second line print numbers pi in any order. If there are multiple possible solutions, you can print any of them.
Examples
Input
27
Output
3
5 11 11
Note
A prime is an integer strictly larger than one that is divisible only by one and by itself.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool check_prime(long long k) {
for (long long i = 2; i * i <= k; i++) {
if (k % i == 0) return 0;
}
return 1;
}
int32_t main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
long long n;
cin >> n;
vector<long long> ans;
if (check_prime(n))
ans.push_back(n);
else {
for (long long i = n - 2;; i--) {
if (check_prime(i)) {
ans.push_back(i);
n -= i;
break;
}
}
if (check_prime(n))
ans.push_back(n);
else {
for (long long i = 2; i <= n; i++) {
if (check_prime(i) && check_prime(n - i)) {
ans.push_back(i);
ans.push_back(n - i);
break;
}
}
}
}
cout << ans.size() << "\n";
for (auto it : ans) cout << it << " ";
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Rick and Morty are playing their own version of Berzerk (which has nothing in common with the famous Berzerk game). This game needs a huge space, so they play it with a computer.
In this game there are n objects numbered from 1 to n arranged in a circle (in clockwise order). Object number 1 is a black hole and the others are planets. There's a monster in one of the planet. Rick and Morty don't know on which one yet, only that he's not initially in the black hole, but Unity will inform them before the game starts. But for now, they want to be prepared for every possible scenario.
<image>
Each one of them has a set of numbers between 1 and n - 1 (inclusive). Rick's set is s1 with k1 elements and Morty's is s2 with k2 elements. One of them goes first and the player changes alternatively. In each player's turn, he should choose an arbitrary number like x from his set and the monster will move to his x-th next object from its current position (clockwise). If after his move the monster gets to the black hole he wins.
Your task is that for each of monster's initial positions and who plays first determine if the starter wins, loses, or the game will stuck in an infinite loop. In case when player can lose or make game infinity, it more profitable to choose infinity game.
Input
The first line of input contains a single integer n (2 ≤ n ≤ 7000) — number of objects in game.
The second line contains integer k1 followed by k1 distinct integers s1, 1, s1, 2, ..., s1, k1 — Rick's set.
The third line contains integer k2 followed by k2 distinct integers s2, 1, s2, 2, ..., s2, k2 — Morty's set
1 ≤ ki ≤ n - 1 and 1 ≤ si, 1, si, 2, ..., si, ki ≤ n - 1 for 1 ≤ i ≤ 2.
Output
In the first line print n - 1 words separated by spaces where i-th word is "Win" (without quotations) if in the scenario that Rick plays first and monster is initially in object number i + 1 he wins, "Lose" if he loses and "Loop" if the game will never end.
Similarly, in the second line print n - 1 words separated by spaces where i-th word is "Win" (without quotations) if in the scenario that Morty plays first and monster is initially in object number i + 1 he wins, "Lose" if he loses and "Loop" if the game will never end.
Examples
Input
5
2 3 2
3 1 2 3
Output
Lose Win Win Loop
Loop Win Win Win
Input
8
4 6 2 3 4
2 3 6
Output
Win Win Win Win Win Win Win
Lose Win Lose Lose Win Lose Lose
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct l {
int i;
int type;
};
vector<int> dp1, st1, dp2, st2, lk1, lk2;
queue<l> q;
int main() {
int n, k1, k2;
cin >> n;
cin >> k1;
for (int i = 0; i < k1; i++) {
int a;
cin >> a;
lk1.push_back(a);
}
cin >> k2;
for (int i = 0; i < k2; i++) {
int a;
cin >> a;
lk2.push_back(a);
}
dp1.resize(n, k1);
st1.resize(n, 0);
dp2.resize(n, k2);
st2.resize(n, 0);
st1[0] = 2;
st2[0] = 2;
q.push({0, 1});
q.push({0, 2});
while (q.size() > 0) {
l b = q.front();
q.pop();
if (b.type == 1) {
if (st1[b.i] == 1) {
for (auto i : lk2) {
int pos = (n + b.i - i) % n;
dp2[pos]--;
if (dp2[pos] == 0 && st2[pos] == 0) {
q.push({pos, 2});
st2[pos] = 2;
}
}
} else if (st1[b.i] == 2) {
for (auto i : lk2) {
int pos = (n + b.i - i) % n;
if (st2[pos] == 0) {
q.push({pos, 2});
st2[pos] = 1;
}
}
}
} else {
if (st2[b.i] == 1) {
for (auto i : lk1) {
int pos = (n + b.i - i) % n;
dp1[pos]--;
if (dp1[pos] == 0 && st1[pos] == 0) {
q.push({pos, 1});
st1[pos] = 2;
}
}
} else if (st2[b.i] == 2) {
for (auto i : lk1) {
int pos = (n + b.i - i) % n;
if (st1[pos] == 0) {
q.push({pos, 1});
st1[pos] = 1;
}
}
}
}
}
for (int i = 1; i < n; i++) {
if (st1[i] == 2) {
cout << "Lose ";
} else if (st1[i] == 0) {
cout << "Loop ";
} else {
cout << "Win ";
}
}
cout << "\n";
for (int i = 1; i < n; i++) {
if (st2[i] == 2) {
cout << "Lose ";
} else if (st2[i] == 0) {
cout << "Loop ";
} else {
cout << "Win ";
}
}
cout << "\n";
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Tonight, in your favourite cinema they are giving the movie Joker and all seats are occupied. In the cinema there are N rows with N seats each, forming an N\times N square. We denote with 1, 2,\dots, N the viewers in the first row (from left to right); with N+1, \dots, 2N the viewers in the second row (from left to right); and so on until the last row, whose viewers are denoted by N^2-N+1,\dots, N^2.
At the end of the movie, the viewers go out of the cinema in a certain order: the i-th viewer leaving her seat is the one denoted by the number P_i. The viewer P_{i+1} waits until viewer P_i has left the cinema before leaving her seat. To exit from the cinema, a viewer must move from seat to seat until she exits the square of seats (any side of the square is a valid exit). A viewer can move from a seat to one of its 4 adjacent seats (same row or same column). While leaving the cinema, it might be that a certain viewer x goes through a seat currently occupied by viewer y; in that case viewer y will hate viewer x forever. Each viewer chooses the way that minimizes the number of viewers that will hate her forever.
Compute the number of pairs of viewers (x, y) such that y will hate x forever.
Constraints
* 2 \le N \le 500
* The sequence P_1, P_2, \dots, P_{N^2} is a permutation of \\{1, 2, \dots, N^2\\}.
Input
The input is given from Standard Input in the format
N
P_1 P_2 \cdots P_{N^2}
Output
If ans is the number of pairs of viewers described in the statement, you should print on Standard Output
ans
Output
If ans is the number of pairs of viewers described in the statement, you should print on Standard Output
ans
Examples
Input
3
1 3 7 9 5 4 8 6 2
Output
1
Input
4
6 7 1 4 13 16 10 9 5 11 12 14 15 2 3 8
Output
3
Input
6
11 21 35 22 7 36 27 34 8 20 15 13 16 1 24 3 2 17 26 9 18 32 31 23 19 14 4 25 10 29 28 33 12 6 5 30
Output
11
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int n;
long long int ans=0;
int dist[500][500],vis[500][500];
bool in(int x,int y){
return x>=0&&x<n&&y>=0&&y<n;
}
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
void dfs(int x,int y){
for(int i=0;i<4;i++){
int nx=x+dx[i],ny=y+dy[i];
if(in(nx,ny)){
if(!vis[x][y]){
if(dist[nx][ny]>dist[x][y]+1)
dist[nx][ny]=dist[x][y]+1,dfs(nx,ny);
}
else{
if(dist[nx][ny]>dist[x][y])
dist[nx][ny]=dist[x][y],dfs(nx,ny);
}
}
}
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cin>>n;
for(int i=0;i<n*n;i++){
int x=i/n,y=i%n;
dist[x][y]=min({x,n-1-x,y,n-1-y});
}
for(int i=1,x;i<=n*n;i++){
cin>>x;
x--;
ans+=dist[x/n][x%n];
vis[x/n][x%n]=true;
dfs(x/n,x%n);
}
cout<<ans<<endl;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
You have an array of positive integers a[1], a[2], ..., a[n] and a set of bad prime numbers b1, b2, ..., bm. The prime numbers that do not occur in the set b are considered good. The beauty of array a is the sum <image>, where function f(s) is determined as follows:
* f(1) = 0;
* Let's assume that p is the minimum prime divisor of s. If p is a good prime, then <image>, otherwise <image>.
You are allowed to perform an arbitrary (probably zero) number of operations to improve array a. The operation of improvement is the following sequence of actions:
* Choose some number r (1 ≤ r ≤ n) and calculate the value g = GCD(a[1], a[2], ..., a[r]).
* Apply the assignments: <image>, <image>, ..., <image>.
What is the maximum beauty of the array you can get?
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 5000) showing how many numbers are in the array and how many bad prime numbers there are.
The second line contains n space-separated integers a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109) — array a. The third line contains m space-separated integers b1, b2, ..., bm (2 ≤ b1 < b2 < ... < bm ≤ 109) — the set of bad prime numbers.
Output
Print a single integer — the answer to the problem.
Examples
Input
5 2
4 20 34 10 10
2 5
Output
-2
Input
4 5
2 4 8 16
3 5 7 11 17
Output
10
Note
Note that the answer to the problem can be negative.
The GCD(x1, x2, ..., xk) is the maximum positive integer that divides each xi.
### Response
```cpp
#include <bits/stdc++.h>
int prims[10010];
bool sito[100010];
int prims_c = 0;
bool is_bad[10010];
std::set<int> bad;
char rozklad[5010][10010];
char _GCD[5010][10010];
char (*GCD)[10010] = _GCD + 1;
char GCD_r[10010];
int tab[5010];
int main() {
for (int i = 2; i < 100000; i++)
if (!sito[i]) {
for (int j = i * 2; j < 100000; j += i) sito[j] = 1;
prims[prims_c++] = i;
}
int n, m;
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++) scanf("%d", tab + i);
int index = 0;
for (int i = 0; i < m; i++) {
int x;
scanf("%d", &x);
if (x < 100000) {
while (prims[index] < x) index++;
is_bad[index] = 1;
} else
bad.insert(x);
}
memset(GCD[-1], 120, sizeof(GCD[-1]));
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < prims_c && tab[i] > 1; j++)
while (tab[i] % prims[j] == 0) {
rozklad[i][j]++;
if (GCD[i - 1][j] > GCD[i][j]) GCD[i][j]++;
if (is_bad[j])
res--;
else
res++;
tab[i] /= prims[j];
}
if (i == 0)
GCD_r[0] = tab[i];
else if (GCD_r[i - 1] == tab[i])
GCD_r[i] = tab[i];
else
GCD_r[i] = 1;
if (bad.end() != bad.find(tab[i]))
res--;
else if (tab[i] > 1)
res++;
}
int last_change = 0;
for (int i = n - 1; i >= 0; i--) {
int val = 0;
for (int j = 0; j < 10010; j++)
if (is_bad[j])
val -= GCD[i][j];
else
val += GCD[i][j];
if (GCD_r[i] > 1)
if (bad.end() != bad.find(GCD_r[i]))
val--;
else
val++;
if (val < last_change) {
res -= (val - last_change) * (i + 1);
last_change = val;
}
}
printf("%d\n", res);
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
You are given a rooted tree with n nodes, labeled from 1 to n. The tree is rooted at node 1. The parent of the i-th node is p_i. A leaf is node with no children. For a given set of leaves L, let f(L) denote the smallest connected subgraph that contains all leaves L.
You would like to partition the leaves such that for any two different sets x, y of the partition, f(x) and f(y) are disjoint.
Count the number of ways to partition the leaves, modulo 998244353. Two ways are different if there are two leaves such that they are in the same set in one way but in different sets in the other.
Input
The first line contains an integer n (2 ≤ n ≤ 200 000) — the number of nodes in the tree.
The next line contains n-1 integers p_2, p_3, …, p_n (1 ≤ p_i < i).
Output
Print a single integer, the number of ways to partition the leaves, modulo 998244353.
Examples
Input
5
1 1 1 1
Output
12
Input
10
1 2 3 4 5 6 7 8 9
Output
1
Note
In the first example, the leaf nodes are 2,3,4,5. The ways to partition the leaves are in the following image <image>
In the second example, the only leaf is node 10 so there is only one partition. Note that node 1 is not a leaf.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e5 + 5;
const int MOD = 998244353;
int dp[MAXN][3];
vector<int> E[MAXN];
void dfs(int now) {
if (E[now].size() == 0) {
dp[now][2] = 1;
return;
}
int sz = E[now].size();
dp[now][0] = 1;
for (int v : E[now]) {
dfs(v);
dp[now][2] = (1LL * dp[now][2] *
(1LL * dp[v][0] + dp[v][2] + dp[v][2] + dp[v][1]) % MOD +
1LL * dp[now][1] * (dp[v][1] + dp[v][2]) % MOD) %
MOD;
dp[now][1] = (1LL * dp[now][1] * (dp[v][0] + dp[v][2]) % MOD +
1LL * dp[now][0] * (dp[v][2] + dp[v][1]) % MOD) %
MOD;
dp[now][0] = 1LL * dp[now][0] * (dp[v][0] + dp[v][2]) % MOD;
}
}
int main() {
int n;
scanf("%d", &n);
for (int i = 2; i <= n; i++) {
int x;
scanf("%d", &x);
E[x].push_back(i);
}
dfs(1);
long long ans = (dp[1][0] + dp[1][2]) % MOD;
printf("%lld\n", ans);
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.
A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.
You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.
Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively.
Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v).
You may assume that there is at most one railway connecting any two towns.
Output
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1.
Examples
Input
4 2
1 3
3 4
Output
2
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Input
5 5
4 2
3 5
4 5
5 1
1 2
Output
3
Note
In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time.
In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int map1[410][410], map2[410][410];
int n, m;
void dijkstra(int map[][410]) {
int res[410];
int vis[410];
int v, min;
for (int i = 1; i <= n; i++) {
vis[i] = 0;
res[i] = map[1][i];
}
for (int i = 1; i <= n; i++) {
min = 1 << 29;
for (int j = 1; j <= n; j++) {
if (vis[j] == 0 && res[j] < min) {
v = j;
min = res[j];
}
}
vis[v] = 1;
for (int j = 1; j <= n; j++) {
if (vis[j] == 0 && res[j] > map[v][j] + res[v]) {
res[j] = map[v][j] + res[v];
}
}
}
if (res[n] == 1 << 29) {
printf("-1\n");
return;
} else
printf("%d\n", res[n]);
}
int main() {
while (~scanf("%d%d", &n, &m)) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i == j) {
map1[i][j] = 0;
map1[i][j] = 0;
} else {
map1[i][j] = map1[j][i] = 1 << 29;
map2[i][j] = map2[j][i] = 1 << 29;
}
}
}
int flag = 0;
for (int i = 0; i < m; i++) {
int a, b;
scanf("%d%d", &a, &b);
if ((a == 1 && b == n) || (a == n && b == 1)) {
flag = 1;
}
map1[a][b] = 1;
map1[b][a] = 1;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (map1[i][j] == 1 << 29 || map1[i][j] == 0) {
map2[i][j] = 1;
map2[j][i] = 1;
}
}
}
if (m == n * (n - 1) / 2) {
printf("-1\n");
continue;
}
if (flag == 1) {
dijkstra(map2);
} else if (flag == 0) {
dijkstra(map1);
}
}
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Let N be a positive integer. You are given a string s of length N - 1, consisting of `<` and `>`.
Find the number of permutations (p_1, p_2, \ldots, p_N) of (1, 2, \ldots, N) that satisfy the following condition, modulo 10^9 + 7:
* For each i (1 \leq i \leq N - 1), p_i < p_{i + 1} if the i-th character in s is `<`, and p_i > p_{i + 1} if the i-th character in s is `>`.
Constraints
* N is an integer.
* 2 \leq N \leq 3000
* s is a string of length N - 1.
* s consists of `<` and `>`.
Input
Input is given from Standard Input in the following format:
N
s
Output
Print the number of permutations that satisfy the condition, modulo 10^9 + 7.
Examples
Input
4
<><
Output
5
Input
5
<<<<
Output
1
Input
20
>>>><>>><>><>>><<>>
Output
217136290
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll md = 1e9+7;
int main()
{
int n;
string s;
cin >> n >> s;
ll dp[n+1][n+1];
dp[1][1] = 1;
for (int q = 2; q <= n; q++)
{
if (s[q-2] == '>')
{
dp[q][q] = 0;
for (int w = q-1; w >= 1; w--)
{
dp[q][w] = (dp[q][w+1] + dp[q-1][w]) % md;
}
}
else
{
dp[q][1] = 0;
for (int w = 2; w <= q; w++)
{
dp[q][w] = (dp[q][w-1] + dp[q-1][w-1]) % md;
}
}
}
ll tot = 0;
for (int q = 1; q <= n; q++)
{
tot = (tot + dp[n][q]) % md;
}
cout << tot <<"\n";
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7.
The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string.
Input
The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106.
Output
Print the minimum number of steps modulo 109 + 7.
Examples
Input
ab
Output
1
Input
aab
Output
3
Note
The first example: "ab" → "bba".
The second example: "aab" → "abba" → "bbaba" → "bbbbaa".
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx")
using namespace std;
bool is_prime(int n) {
for (int i = 2; i * i <= n; ++i) {
if (n % i == 0) {
return false;
}
}
return true;
}
inline long long getPow(long long a, long long b) {
long long res = 1, tp = a;
while (b) {
if (b & 1ll) {
res *= tp;
}
tp *= tp;
b >>= 1ll;
}
return res;
}
inline long long to_ll(string s) {
long long cur = 0;
for (int i = 0; i < s.size(); i++) {
cur = cur * 10 + s[i] - '0';
}
return cur;
}
inline string to_str(long long x) {
string s = "";
while (x) {
s += char(x % 10 + '0');
x /= 10;
}
reverse(s.begin(), s.end());
return s;
}
inline long long nxt() {
long long x;
scanf("%lld", &x);
return x;
}
void ok() {
puts("YES");
exit(0);
}
void no() {
puts("NO");
exit(0);
}
bool check(long long a, long long b1, long long b2, long long A, long long B) {
if (b1 + b2 <= B && a <= A) {
return true;
} else
return false;
}
int main() {
string s;
cin >> s;
reverse(s.begin(), s.end());
long long ans = 0;
long long ct = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == 'b') {
ct++;
} else {
ans += ct;
ct *= 2;
ans %= 1000000007;
ct %= 1000000007;
}
}
cout << ans;
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Bomboslav set up a branding agency and now helps companies to create new logos and advertising slogans. In term of this problems, slogan of the company should be a non-empty substring of its name. For example, if the company name is "hornsandhoofs", then substrings "sand" and "hor" could be its slogans, while strings "e" and "hornss" can not.
Sometimes the company performs rebranding and changes its slogan. Slogan A is considered to be cooler than slogan B if B appears in A as a substring at least twice (this occurrences are allowed to overlap). For example, slogan A = "abacaba" is cooler than slogan B = "ba", slogan A = "abcbcbe" is cooler than slogan B = "bcb", but slogan A = "aaaaaa" is not cooler than slogan B = "aba".
You are given the company name w and your task is to help Bomboslav determine the length of the longest sequence of slogans s1, s2, ..., sk, such that any slogan in the sequence is cooler than the previous one.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the length of the company name that asks Bomboslav to help. The second line contains the string w of length n, that consists of lowercase English letters.
Output
Print a single integer — the maximum possible length of the sequence of slogans of the company named w, such that any slogan in the sequence (except the first one) is cooler than the previous
Examples
Input
3
abc
Output
1
Input
5
ddddd
Output
5
Input
11
abracadabra
Output
3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 444444, mod = 998244353;
inline long long read() {
char ch = getchar();
long long x = 0, f = 0;
while (ch < '0' || ch > '9') f |= ch == '-', ch = getchar();
while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
return f ? -x : x;
}
int n, cnt, lst, fa[maxn], ch[maxn][26], len[maxn], el, head[maxn], to[maxn],
nxt[maxn], rt[maxn], tot, ls[maxn * 33], rs[maxn * 33], ans, pos[maxn],
f[maxn], tr[maxn];
char s[maxn];
inline void add(int u, int v) {
to[++el] = v;
nxt[el] = head[u];
head[u] = el;
}
inline void init() { fa[0] = -1; }
void update(int &x, int l, int r, int p) {
if (!x) x = ++tot;
if (l == r) return;
int mid = (l + r) >> 1;
if (mid >= p)
update(ls[x], l, mid, p);
else
update(rs[x], mid + 1, r, p);
}
int merge(int x, int y) {
if (!x || !y) return x + y;
int now = ++tot;
ls[now] = merge(ls[x], ls[y]);
rs[now] = merge(rs[x], rs[y]);
return now;
}
bool query(int x, int l, int r, int ql, int qr) {
if (!x) return false;
if (l >= ql && r <= qr) return true;
int mid = (l + r) >> 1;
if (mid < ql) return query(rs[x], mid + 1, r, ql, qr);
if (mid >= qr) return query(ls[x], l, mid, ql, qr);
return query(ls[x], l, mid, ql, qr) || query(rs[x], mid + 1, r, ql, qr);
}
void extend(int id, int c) {
int now = ++cnt;
pos[now] = id;
len[now] = len[lst] + 1;
int p = lst;
lst = now;
for (; ~p && !ch[p][c]; p = fa[p]) ch[p][c] = now;
if (~p) {
int q = ch[p][c];
if (len[p] + 1 == len[q])
fa[now] = q;
else {
int cl = ++cnt;
len[cl] = len[p] + 1;
fa[cl] = fa[q];
pos[cl] = pos[q];
fa[q] = fa[now] = cl;
for (int i = (0); i <= (25); i++) ch[cl][i] = ch[q][i];
for (; ~p && ch[p][c] == q; p = fa[p]) ch[p][c] = cl;
}
}
}
void dfs(int u) {
update(rt[u], 1, n, pos[u]);
for (int i = head[u]; i; i = nxt[i]) {
int v = to[i];
dfs(v);
rt[u] = merge(rt[u], rt[v]);
}
}
void dfs2(int u) {
if (u) {
if (!fa[u])
tr[u] = u, f[u] = 1;
else {
int tmp = tr[fa[u]];
if (query(rt[tmp], 1, n, pos[u] - len[u] + len[tmp], pos[u] - 1))
tr[u] = u, f[u] = f[fa[u]] + 1;
else
tr[u] = tmp, f[u] = f[fa[u]];
}
}
ans = max(ans, f[u]);
for (int i = head[u]; i; i = nxt[i]) {
int v = to[i];
dfs2(v);
}
}
int main() {
n = read();
scanf("%s", s + 1);
init();
for (int i = (1); i <= (n); i++) extend(i, s[i] - 'a');
for (int i = (1); i <= (cnt); i++) add(fa[i], i);
dfs(0);
dfs2(0);
printf("%d\n", ans);
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
One day Om Nom found a thread with n beads of different colors. He decided to cut the first several beads from this thread to make a bead necklace and present it to his girlfriend Om Nelly.
<image>
Om Nom knows that his girlfriend loves beautiful patterns. That's why he wants the beads on the necklace to form a regular pattern. A sequence of beads S is regular if it can be represented as S = A + B + A + B + A + ... + A + B + A, where A and B are some bead sequences, " + " is the concatenation of sequences, there are exactly 2k + 1 summands in this sum, among which there are k + 1 "A" summands and k "B" summands that follow in alternating order. Om Nelly knows that her friend is an eager mathematician, so she doesn't mind if A or B is an empty sequence.
Help Om Nom determine in which ways he can cut off the first several beads from the found thread (at least one; probably, all) so that they form a regular pattern. When Om Nom cuts off the beads, he doesn't change their order.
Input
The first line contains two integers n, k (1 ≤ n, k ≤ 1 000 000) — the number of beads on the thread that Om Nom found and number k from the definition of the regular sequence above.
The second line contains the sequence of n lowercase Latin letters that represent the colors of the beads. Each color corresponds to a single letter.
Output
Print a string consisting of n zeroes and ones. Position i (1 ≤ i ≤ n) must contain either number one if the first i beads on the thread form a regular sequence, or a zero otherwise.
Examples
Input
7 2
bcabcab
Output
0000011
Input
21 2
ababaababaababaababaa
Output
000110000111111000011
Note
In the first sample test a regular sequence is both a sequence of the first 6 beads (we can take A = "", B = "bca"), and a sequence of the first 7 beads (we can take A = "b", B = "ca").
In the second sample test, for example, a sequence of the first 13 beads is regular, if we take A = "aba", B = "ba".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
const int64_t MOD = 1000051373LL;
const int64_t BASE = 100;
const int64_t BASE_MODULAR_INVERSE = 630032365;
string s;
int n, k, max_packet[N], f[N];
int64_t phash[N], BMI[N];
bool ans[N], ask[N];
void hash_preproc();
int64_t get_hash(int, int);
int64_t _sum(int64_t, int64_t);
int64_t _mul(int64_t, int64_t);
int32_t main() {
cin >> n >> k >> s;
hash_preproc();
for (int len = 1; len * k <= n; len++) {
vector<int64_t> sh;
for (int i = 0; i < k; i++) sh.push_back(get_hash(i * len, (i + 1) * len));
sh.resize(unique(sh.begin(), sh.end()) - sh.begin());
if (sh.size() == 1) ask[len * k - 1] = true;
}
int p = 0;
for (int i = 1; i < n; i++) {
while (s[i] != s[p] and p > 0) p = f[p];
if (s[i] == s[p]) p++;
f[i + 1] = p;
}
p = 0;
for (int i = 1; i < n; i++) {
while (s[i] != s[p] and p > 0) p = f[p];
if (s[i] == s[p]) p++;
while ((!ask[i - p] or (i - p + 1) / k < p) and p > 0) p = f[p];
if (ask[i - p] and (i - p + 1) / k >= p) ans[i + 1] = true;
}
ans[1] = (k == 1);
for (int i = 1; i <= n; i++) cout << ans[i];
cout << endl;
}
void hash_preproc() {
int64_t cur_base = 1;
for (int i = 1; i <= n; i++) {
phash[i] = _sum(phash[i - 1], _mul(cur_base, int(s[i - 1] - 'a' + 1)));
cur_base = _mul(cur_base, BASE);
}
BMI[0] = 1;
for (int i = 1; i <= n; i++) BMI[i] = _mul(BMI[i - 1], BASE_MODULAR_INVERSE);
}
int64_t get_hash(int l, int r) {
int64_t res = _sum(phash[r], MOD - phash[l]);
res = _mul(res, BMI[l]);
return res;
}
int64_t _sum(int64_t a, int64_t b) {
a += b;
if (a >= MOD) a -= MOD;
return a;
}
int64_t _mul(int64_t a, int64_t b) { return 1LL * a * b % MOD; }
``` |
### Prompt
Generate a Cpp solution to the following problem:
The Smart Beaver from ABBYY came up with another splendid problem for the ABBYY Cup participants! This time the Beaver invites the contest participants to check out a problem on sorting documents by their subjects. Let's describe the problem:
You've got some training set of documents. For each document you know its subject. The subject in this problem is an integer from 1 to 3. Each of these numbers has a physical meaning. For instance, all documents with subject 3 are about trade.
You can download the training set of documents at the following link: http://download4.abbyy.com/a2/X2RZ2ZWXBG5VYWAL61H76ZQM/train.zip. The archive contains three directories with names "1", "2", "3". Directory named "1" contains documents on the 1-st subject, directory "2" contains documents on the 2-nd subject, and directory "3" contains documents on the 3-rd subject. Each document corresponds to exactly one file from some directory.
All documents have the following format: the first line contains the document identifier, the second line contains the name of the document, all subsequent lines contain the text of the document. The document identifier is used to make installing the problem more convenient and has no useful information for the participants.
You need to write a program that should indicate the subject for a given document. It is guaranteed that all documents given as input to your program correspond to one of the three subjects of the training set.
Input
The first line contains integer id (0 ≤ id ≤ 106) — the document identifier. The second line contains the name of the document. The third and the subsequent lines contain the text of the document. It is guaranteed that the size of any given document will not exceed 10 kilobytes.
The tests for this problem are divided into 10 groups. Documents of groups 1 and 2 are taken from the training set, but their identifiers will not match the identifiers specified in the training set. Groups from the 3-rd to the 10-th are roughly sorted by the author in ascending order of difficulty (these groups contain documents which aren't present in the training set).
Output
Print an integer from 1 to 3, inclusive — the number of the subject the given document corresponds to.
Examples
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#pragma comment(linker, "/STACK:200000000")
const double EPS = 1E-9;
const int INF = 1000000000;
const long long INF64 = (long long)1E18;
const double PI = 3.1415926535897932384626433832795;
string tr[3][50] = {{"BRITISH, FRENCH MINISTERS DISCUSS PUBLIC SPENDING",
"FORMER HERSTATT DEALER CAN BE SUED, COURT RULES",
"U.K. MONEY MARKET DEFICIT FORECAST AT 700 MLN STG",
"BANK OF SPAIN SUSPENDS ASSISTANCE",
"U.K. MONEY MARKET GIVEN 265 MLN STG ASSISTANCE",
"BANK OF FRANCE AGAIN BUYING DOLLARS, SOURCES SAY",
"BUNDESBANK BOUGHT DOLLARS AGAINST YEN, DEALERS SAY",
"U.K. MONEY MARKET GIVEN FURTHER 663 MLN STG HELP",
"AUSTRIA DOES NOT INTERVENE TO SUPPORT DOLLAR",
"TAIWAN TO STUDY SUSPENDING FOREX CONTROLS",
"OFFICIAL WANTS ARAB FUND TO HELP LEBANESE POUND",
"CHINA POSTPONES PLAN TO SCRAP PARALLEL CURRENCY",
"ARAB BANKER SAYS TOO SOON FOR SINGLE CURRENCY",
"ARAB FOREX ASSOCIATION ELECTS NEW CHAIRMAN",
"JAPAN CAREFULLY CONSIDERING MONEY POLICY -- SUMITA",
"BAHRAIN INTRODUCES NEW MONEY MARKET REGIME",
"BANK OF ENGLAND FORECASTS SURPLUS IN MONEY MARKET",
"PHILADELPHIA EXCHANGE TO EXTEND HOURS FOR ASIA",
"JAPAN CONDUCTS CURRENCY SURVEY OF BIG INVESTORS",
"BANK OF ENGLAND DOES NOT OPERATE IN MONEY MARKET",
"ASIAN DOLLAR MARKET ASSETS FALL IN JANUARY",
"PHILADELPHIA EXCHANGE TO EXTEND HOURS FOR ASIA",
"JAPAN CAREFULLY CONSIDERING MONEY POLICY - SUMITA",
"U.K. MONEY MARKET GIVEN 129 MLN STG ASSISTANCE",
"JAPAN CONDUCTS CURRENCY SURVEY OF BIG INVESTORS",
"JAPANESE SEEN LIGHTENING U.S. BOND HOLDINGS",
"FED ADDS RESERVES VIA CUSTOMER REPURCHASES",
"FORMER TREASURY OFFICIAL URGES CURRENCY REFORMS",
"FED WILL BUY BILLS FOR CUSTOMER AFTER AUCTION",
"TREASURY BALANCES AT FED FELL ON MARCH 27",
"U.S. CREDIT MARKETS END UNDER EXTREME PRESSURE",
"U.K. MONEY MARKET OFFERED EARLY ASSISTANCE",
"UK MONEY MARKET GIVEN FURTHER 570 MLN STG HELP",
"CALL MONEY PRESSURE FROM LARGE GERMAN BANKS",
"U.K. MONEY MARKET SHORTAGE FORECAST REVISED UP",
"U.K. MONEY MARKET GIVEN 215 MLN STG LATE HELP",
"U.S. TREASURY'S BAKER SEES RATE STABILITY",
"TREASURY'S BAKER SAYS COOPERATION WORKING",
"TREASURY'S BAKER SAYS U.S. BACKS STABILITY",
"BANGEMANN CALLS FOR CURRENCY CALM",
"TREASURY'S BAKER PURSUING S. ASIAN REVALUATIONS",
"TREASURY'S BAKER PURSUING S. ASIAN REVALUATIONS",
"CURRENCY FUTURES CLIMB LIKELY TO BE CHECKED",
"U.S. FED EXPLORES COMMODITY BASKET INDEX",
"U.K. MONEY MARKET OFFERED EARLY ASSISTANCE",
"U.K. MONEY MARKET GIVEN 689 MLN STG EARLY HELP",
"U.K. MONEY MARKET SHORTAGE FORECAST REVISED UP",
"U.K. MONEY MARKET DEFICIT REVISED DOWNWARDS",
"FED BUYS ONE BILLION DLRS OF BILLS FOR CUSTOMER",
"FED BUYS ONE BILLION DLRS OF BILLS FOR CUSTOMER"},
{"N.Z. TRADING BANK DEPOSIT GROWTH RISES SLIGHTLY",
"NEW YORK BUSINESS LOANS FALL 222 MLN DLRS",
"U.S. M-1 MONEY SUPPLY RISES 1.2 BILLION DLR",
"CANADIAN MONEY SUPPLY FALLS IN WEEK",
"DUTCH MONEY SUPPLY HARDLY CHANGED IN DECEMBER",
"U.K. CONFIRMS FEBRUARY STERLING M3 RISE",
"SINGAPORE M-1 MONEY SUPPLY 2.7 PCT UP IN JANUARY",
"SINGAPORE BANK CREDIT RISES IN JANUARY",
"H.K. M3 MONEY SUPPLY RISES 1.4 PCT IN FEBRUARY",
"U.S. BANK DISCOUNT BORROWINGS 310 MLN DLRS",
"U.S. M-1 MONEY SUPPLY ROSE 2.1 BILLION DLRS",
"AUSTRALIAN BROAD MONEY GROWTH 10.3 PCT IN FEBRUARY",
"TAIWAN ISSUES MORE CERTIFICATES OF DEPOSIT",
"SOUTH KOREAN MONEY SUPPLY FALLS IN MARCH",
"BELGIAN MONEY SUPPLY RISES IN FOURTH QUARTER 1986",
"CANADIAN MONEY SUPPLY FALLS IN WEEK",
"TREASURY BALANCES AT FED ROSE ON FEB 27",
"FEBRUARY FOMC VOTES UNCHANGED MONETARY POLICY",
"U.S. BUSINESS LOANS FELL 822 MLN DLRS",
"GERMAN CAPITAL ACCOUNT IN DEFICIT IN FEBRUARY",
"TREASURY BALANCES AT FED ROSE ON APRIL 6",
"TAIWAN ISSUES MORE CDS TO CURB MONEY SUPPLY GROWTH",
"SOUTH KOREAN MONEY SUPPLY RISES IN FEBRUARY",
"SPAIN RAISES BANKS' RESERVE REQUIREMENT",
"N.Z. MONEY SUPPLY RISES 3.6 PCT IN DECEMBER",
"FED DATA SUGGEST STABLE U.S. MONETARY POLICY",
"N.Z. CENTRAL BANK SEES SLOWER MONEY, CREDIT GROWTH",
"U.S. M-1 MONEY SUPPLY RISES 1.9 BILLION DLRS",
"U.S. MONEY GROWTH SLOWS SHARPLY, ECONOMISTS SAY",
"CANADIAN MONEY SUPPLY RISES IN WEEK",
"TREASURY BALANCES AT FED FELL ON MARCH 5",
"U.S. BUSINESS LOANS FALL 618 MLN DLRS",
"SINGAPORE M-1 MONEY SUPPLY UP 3.7 PCT IN DECEMBER",
"FRENCH JANUARY M-3 MONEY SUPPLY RISES ONE PCT",
"U.K. CONFIRMS JANUARY STERLING M3 RISE",
"TREASURY BALANCES AT FED ROSE ON MARCH 6",
"SPAIN'S MONEY SUPPLY GROWTH DOUBLES IN FEBRUARY",
"TREASURY BALANCES AT FED FELL ON MARCH 10",
"NEW YORK BUSINESS LOANS FALL 718 MLN DLRS",
"U.S. M-1 MONEY SUPPLY FALLS 600 MLN DLRS",
"JAPAN PERSONAL SAVINGS SOAR IN 1986",
"CANADIAN MONEY SUPPLY RISES IN WEEK",
"U.S. BUSINESS LOANS RISE 377 MLN DLRS",
"BANGLADESH MONEY SUPPLY RISES IN DECEMBER",
"GERMAN FEBRUARY CENTRAL BANK MONEY GROWTH STEADY",
"THAI M-1 MONEY SUPPLY RISES IN JANUARY",
"JAPAN FEBRUARY MONEY SUPPLY RISES 8.8 PCT",
"ASSETS OF U.S. MONEY FUNDS ROSE IN WEEK",
"ITALY M-2 UP 2.8 PCT IN 3 MONTHS TO END JANUARY",
"PHILIPPINES' LIQUIDITY RISES, LOAN DEMAND FALLS"},
{"WHITE HOUSE UNIT DECIDES ON SEMICONDUCTORS",
"CHINA CALLS FOR BETTER TRADE DEAL WITH U.S.",
"GATT WARNS U.S. ON FEDERAL BUDGET, PROTECTIONISM",
"WHITE HOUSE PANEL SAID URGING JAPAN RETALIATION",
"NAKASONE TO VISIT WASHINGTON IN LATE APRIL",
"WORLD BANK CHIEF URGES MORE JAPANESE INVESTMENT",
"NAKASONE TO VISIT WASHINGTON IN LATE APRIL",
"NAKASONE HARD-PRESSED TO SOOTHE U.S ANGER ON TRADE",
"INDIA STEPS UP COUNTERTRADE DEALS TO CUT TRADE GAP",
"UK MAY REVOKE JAPANESE FINANCIAL LICENSES",
"REAGAN READY TO IMPOSE TRADE CURBS AGAINST JAPAN",
"JAPAN'S CHIP MAKERS ANGERED BY U.S. SANCTION PLANS",
"NAKASONE SOUNDS CONCILIATORY NOTE IN CHIP DISPUTE",
"ISLAMIC BANKS ESTABLISH 50 MLN DLR TRADE PORTFOLIO",
"TOKYO BIDS TO STOP CHIP ROW TURNING INTO TRADE WAR",
"BALDRIGE PREDICTS END OF U.S.-JAPAN TRADE DISPUTE",
"JAPAN HAS LITTLE NEW TO OFFER IN MICROCHIP DISPUTE",
"NAKASONE SOUNDS CONCILIATORY NOTE IN CHIP DISPUTE",
"TOKYO BIDS TO STOP CHIP ROW BECOMING TRADE WAR",
"BALDRIGE PREDICTS END OF U.S.-JAPAN TRADE DISPUTE",
"YUGOSLAV TRADE FALLS SHARPLY STATISTICS SHOW",
"ECONOMIC SPOTLIGHT - U.S. CONGRESS RAPS JAPAN",
"U.S. TRADE OFFICIAL SAYS JAPAN ACTION FOOLISH",
"EUROPEAN COMMUNITY TO SET UP OFFICE IN PEKING",
"TRADE FRICTION THREATENS TO TOPPLE NAKASONE",
" EUROPE ON SIDELINES IN U.S-JAPAN MICROCHIP ROW",
"THATCHER SAYS TRADE TARGETS SET WITH MOSCOW",
"JAPAN TO CUT MICROCHIP OUTPUT, BOOST IMPORTS",
"JAPAN WILL ASK COMPANIES TO BOOST IMPORTS",
"U.S./JAPAN TRADE WAR NOT IN UK'S INTEREST - LAWSON",
"EC APPROVES MEDITERRANEAN FINANCIAL PACKAGES",
"SOVIET UNION SEEN WATCHING CHINA GATT APPLICATION",
"U.S. SENATE LEADERS SEE NO TRADE WAR BREWING",
"U.S. STOCK MARKET OVERREACTS TO TARIFFS - YEUTTER",
"ENVOY ADVISES NAKASONE TO PREPARE FOR U.S. VISIT",
"TREASURY'S BAKER SEES SMALLER TRADE DEFICIT",
"TREASURY'S BAKER NOT CONCERNED BY BOND DECLINES",
"U.S.-JAPAN NOT IN TRADE WAR, YEUTTER SAYS",
"CHIRAC, REAGAN DISCUSS ARMS CONTROL, TRADE",
"TRADE WAR FEARS MAY PROMPT STOCK MARKETS' DOWNTURN",
"WHITE HOUSE DISCOUNTS THREAT OF TRADE WAR",
"BALDRIGE SAYS U.S. TO IMPOSE JAPANESE SANCTIONS",
"SENIOR U.S. OFFICIAL TO VISIT JAPAN AS TRADE ROW GROWS",
"BROADER U.S. EEP SOUGHT BY REPUBLICAN LAWMAKERS",
"U.S. OFFICIAL TO VISIT JAPAN AS TRADE ROW GROWS",
"U.S. OFFICIAL SEES EVIDENCE OF EXPORT GROWTH",
"TAIWAN'S SECOND QUARTER IMPORTS SEEN RISING",
"BELGIAN SAYS EC WOULD REACT TO TEXTILE BILL",
"ROSTENKOWSKI OPPOSES PROTECTIONIST TRADE BILL",
"U.K. EXPORTS BODY GETS NEW EXECUTIVE DIRECTOR"}};
char buf[1100000];
string trim(string s) {
string res;
for (int i = 0; i < (int)(s.size()); i++)
if (isalpha(s[i]) || isdigit(s[i])) res += s[i];
return res;
}
bool match(string s1, string s2) { return trim(s1) == trim(s2); }
int main() {
gets(buf);
string text;
while (gets(buf)) {
text += buf;
break;
}
for (int i = 0; i < (int)(3); i++)
for (int j = 0; j < (int)(i); j++)
for (int a = 0; a < (int)(50); a++)
for (int b = 0; b < (int)(50); b++)
if (match(tr[i][a], tr[j][b])) throw;
for (int i = 0; i < (int)(3); i++)
for (int j = 0; j < (int)(50); j++)
if (match(text, tr[i][j])) {
printf("%d\n", i + 1);
return 0;
}
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
The Committee for Research on Binary Viruses discovered a method of replication for a large family of viruses whose genetic codes are sequences of zeros and ones. Each virus originates from a single gene; for simplicity genes are denoted by integers from 0 to G - 1. At each moment in time a virus is a sequence of genes. When mutation occurs, one of the genes from the sequence is replaced by a certain sequence of genes, according to the mutation table. The virus stops mutating when it consists only of genes 0 and 1.
For instance, for the following mutation table: $$$ 2 → ⟨ 0\ 1 ⟩ \\\ 3 → ⟨ 2\ 0\ 0⟩\\\ 3 → ⟨ 1\ 3⟩\\\ 4 → ⟨ 0\ 3\ 1\ 2⟩\\\ 5 → ⟨ 2\ 1⟩\\\ 5 → ⟨ 5⟩ a virus that initially consisted of a single gene 4, could have mutated as follows: ⟨ 4 ⟩ → ⟨ \underline{0\ 3\ 1\ 2} ⟩ → ⟨ 0\ \underline{2\ 0\ 0}\ 1\ 2 ⟩ → ⟨ 0\ \underline{0\ 1}\ 0\ 0\ 1\ 2 ⟩ → ⟨ 0\ 0\ 1\ 0\ 0\ 1\ \underline{0\ 1} ⟩ or in another way: ⟨ 4 ⟩ → ⟨ \underline{0\ 3\ 1\ 2} ⟩ → ⟨ 0\ \underline{1\ 3}\ 1\ 2 ⟩ → ⟨ 0\ 1\ 3\ 1\ \underline{0\ 1} ⟩ → ⟨ 0\ 1\ \underline{2\ 0\ 0}\ 1\ 0\ 1 ⟩ → ⟨ 0\ 1\ \underline{0\ 1}\ 0\ 0\ 1\ 0\ 1 ⟩ $$$
Viruses are detected by antibodies that identify the presence of specific continuous fragments of zeros and ones in the viruses' codes. For example, an antibody reacting to a fragment ⟨ 0\ 0\ 1\ 0\ 0 ⟩ will detect a virus ⟨ 0\ 0\ 1\ 0\ 0\ 1\ 0\ 1 ⟩, but it will not detect a virus ⟨ 0\ 1\ 0\ 1\ 0\ 0\ 1\ 0\ 1 ⟩.
For each gene from 2 to G-1, the scientists are wondering whether a given set of antibodies is enough to detect all viruses that can emerge through mutations from this gene. If not, they want to know the length of the shortest virus that cannot be detected.
It may happen that sometimes scientists don't have any antibodies. Then of course no virus can be detected, so the scientists are only interested in the length of the shortest possible virus that can emerge from the gene mutations.
Input
The first line of the input will contain three integers G, N and M (G > 2, N ≥ G - 2, M ≥ 0) specifying the number of genes, the number of rows in the mutation table, and the number of antibodies.
The following N lines contain descriptions of rows of the mutation table; each line begins with two integers a and k (2 ≤ a < G, k ≥ 1), followed by a sequence of k integers b_1, b_2, …, b_k (0 ≤ b_i < G), that encode the row $$$ a → ⟨ b_1\ b_2\ …\ b_k ⟩ $$$
The sum of all values k does not exceed 100. Every integer from 2 to G - 1 appears in the table as a at least once.
The next M lines contain descriptions of the antibodies; each such line begins with an integer ℓ (ℓ ≥ 1), followed by a sequence of ℓ integers c_1, c_2, …, c_ℓ (0 ≤ c_i ≤ 1), describing the antibody. The sum of all values ℓ does not exceed 50.
Output
Your program needs to output exactly G - 2 lines, containing the answers for the subsequent genes from 2 to G - 1.
If all viruses that can mutate from this single gene can be detected by the given set of antibodies, you need to print the word "YES". You also need to print this if there are no viruses that could originate from this gene (it can happen when the sequences never stop mutating).
Otherwise you need to print the word "NO", followed by an integer denoting the minimal length of the undetectable virus. You can assume that for all the prepared input data this value will be smaller than 2^{63}.
Scoring
Subtasks:
1. (11 points) No antibodies (M = 0)
2. (14 points) N = G - 2
3. (25 points) One antibody (M = 1)
4. (32 points) The sum of all values ℓ does not exceed 10
5. (18 points) No further constraints
Example
Input
6 6 2
2 2 0 1
3 3 2 0 0
3 2 1 3
4 4 0 3 1 2
5 2 2 1
5 1 5
2 1 1
5 0 0 1 0 0
Output
NO 2
NO 4
NO 9
YES
### Response
```cpp
#include <bits/stdc++.h>
namespace IAKIOI {
const long long L = 1 << 20 | 1;
char buffer[L], *S, *TT;
inline void read(long long &x) {
x = 0;
long long f = 1;
char s =
((S == TT && (TT = (S = buffer) + fread(buffer, 1, L, stdin), S == TT))
? EOF
: *S++);
while (s < '0' || s > '9') {
if (s == '-') f = -1;
s = ((S == TT && (TT = (S = buffer) + fread(buffer, 1, L, stdin), S == TT))
? EOF
: *S++);
}
while (s >= '0' && s <= '9') {
x = x * 10 + s - '0';
s = ((S == TT && (TT = (S = buffer) + fread(buffer, 1, L, stdin), S == TT))
? EOF
: *S++);
}
x *= f;
}
inline void write(long long x) {
if (x < 0) {
putchar('-');
x = -x;
}
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
} // namespace IAKIOI
using namespace IAKIOI;
const unsigned long long oo = 1ull << 63;
unsigned long long f[205][52][52];
long long G, N, M, n, m, b[55], ty[205], v[205][55][55];
std::vector<std::pair<long long, long long>> out[205];
long long ch[55][2], fail[55], ok[55], rt = 1, tot = 1;
inline void insert(long long *a, long long len) {
long long nw = rt;
for (long long i = 1; i <= len; i++) {
if (!ch[nw][a[i]]) ch[nw][a[i]] = ++tot;
nw = ch[nw][a[i]];
}
ok[nw] = 1;
}
std::queue<long long> Q;
inline void getfail() {
for (long long i = 0; i <= 1; i++)
if (ch[rt][i])
fail[ch[rt][i]] = rt, Q.push(ch[rt][i]);
else
ch[rt][i] = rt;
while (Q.size()) {
long long u = Q.front();
Q.pop();
for (long long i = 0; i <= 1; i++)
if (ch[u][i]) {
fail[ch[u][i]] = ch[fail[u]][i];
ok[ch[u][i]] |= ok[fail[ch[u][i]]];
Q.push(ch[u][i]);
} else
ch[u][i] = ch[fail[u]][i];
}
}
long long id[55], num[55];
struct node {
long long x, fr, ed;
unsigned long long num;
node(long long _x = 0, long long _fr = 0, long long _ed = 0,
unsigned long long _num = 0) {
x = _x;
fr = _fr;
ed = _ed;
num = _num;
}
friend bool operator<(node a, node b) { return a.num > b.num; }
};
std::priority_queue<node> Heap;
signed main() {
read(G), G--;
read(N), read(M), n = G;
for (long long i = 1, a = 0, k = 0; i <= N; i++, n += k) {
read(a), read(k);
for (long long j = 1; j <= k; j++) read(b[j]), ty[n + j] = 1;
for (long long j = 2; j <= k; j++) {
out[n + j].push_back(std::make_pair(n + j - 1, b[j - 1]));
out[b[j - 1]].push_back(std::make_pair(n + j - 1, n + j));
}
out[b[k]].push_back(std::make_pair(n + k, -1));
out[n + 1].push_back(std::make_pair(a, -1));
}
for (long long i = 1, len; i <= M; i++) {
read(len);
for (long long j = 1; j <= len; j++) read(b[j]);
insert(b, len);
}
getfail();
long long cnt = 0;
for (long long i = 1; i <= tot; i++)
if (!ok[i]) id[i] = ++cnt, num[cnt] = i;
for (long long i = 0; i <= n; i++)
for (long long j = 1; j <= cnt; j++)
for (long long k = 1; k <= cnt; k++) f[i][j][k] = oo;
for (long long i = 1; i <= cnt; i++) {
long long x = num[i];
if (id[ch[x][0]]) {
f[0][i][id[ch[x][0]]] = 1;
Heap.push(node(0, i, id[ch[x][0]], 1));
}
if (id[ch[x][1]]) {
f[1][i][id[ch[x][1]]] = 1;
Heap.push(node(1, i, id[ch[x][1]], 1));
}
}
while (Heap.size()) {
node tmp = Heap.top();
Heap.pop();
long long x = tmp.x, fr = tmp.fr, ed = tmp.ed;
unsigned long long val = tmp.num;
if (v[x][fr][ed]) continue;
v[x][fr][ed] = 1;
for (std::pair<long long, long long> u : out[x]) {
long long y = u.first, w = u.second;
if (w == -1) {
if (f[y][fr][ed] > val) {
f[y][fr][ed] = val;
Heap.push(node(y, fr, ed, f[y][fr][ed]));
}
} else {
if (!ty[x]) {
for (long long j = 1; j <= cnt; j++)
if (f[y][fr][j] > val + f[w][ed][j]) {
f[y][fr][j] = val + f[w][ed][j];
Heap.push(node(y, fr, j, f[y][fr][j]));
}
} else {
for (long long j = 1; j <= cnt; j++)
if (f[y][j][ed] > val + f[w][j][fr]) {
f[y][j][ed] = val + f[w][j][fr];
Heap.push(node(y, j, ed, f[y][j][ed]));
}
}
}
}
}
for (long long i = 2; i <= G; i++) {
unsigned long long ans = oo;
for (long long j = 1; j <= cnt; j++) ans = std::min(ans, f[i][1][j]);
(ans == oo) ? puts("YES") : printf("NO %lld\n", ans);
}
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Gerald has n younger brothers and their number happens to be even. One day he bought n2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer k from 1 to n2 he has exactly one bag with k candies.
Help him give n bags of candies to each brother so that all brothers got the same number of candies.
Input
The single line contains a single integer n (n is even, 2 ≤ n ≤ 100) — the number of Gerald's brothers.
Output
Let's assume that Gerald indexes his brothers with numbers from 1 to n. You need to print n lines, on the i-th line print n integers — the numbers of candies in the bags for the i-th brother. Naturally, all these numbers should be distinct and be within limits from 1 to n2. You can print the numbers in the lines in any order.
It is guaranteed that the solution exists at the given limits.
Examples
Input
2
Output
1 4
2 3
Note
The sample shows Gerald's actions if he has two brothers. In this case, his bags contain 1, 2, 3 and 4 candies. He can give the bags with 1 and 4 candies to one brother and the bags with 2 and 3 to the other brother.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int s[11000];
int main(int argc, char *argv[]) {
int n = 0;
cin >> n;
int i = 0;
for (i = 0; i < 10001; i++) {
s[i] = i + 1;
}
int j = 0;
int step = 0;
int k = 0;
for (i = 0; i < n; i++) {
for (j = step; j < step + n / 2; j++) {
cout << s[j] << ' ';
}
for (k = n * n - step - n / 2; k < n * n - step; k++) {
cout << s[k] << ' ';
}
cout << endl;
step = step + n / 2;
}
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
We have N balance beams numbered 1 to N. The length of each beam is 1 meters. Snuke walks on Beam i at a speed of 1/A_i meters per second, and Ringo walks on Beam i at a speed of 1/B_i meters per second.
Snuke and Ringo will play the following game:
* First, Snuke connects the N beams in any order of his choice and makes a long beam of length N meters.
* Then, Snuke starts at the left end of the long beam. At the same time, Ringo starts at a point chosen uniformly at random on the long beam. Both of them walk to the right end of the long beam.
* Snuke wins if and only if he catches up to Ringo before Ringo reaches the right end of the long beam. That is, Snuke wins if there is a moment when Snuke and Ringo stand at the same position, and Ringo wins otherwise.
Find the probability that Snuke wins when Snuke arranges the N beams so that the probability of his winning is maximized.
This probability is a rational number, so we ask you to represent it as an irreducible fraction P/Q (to represent 0, use P=0, Q=1).
Constraints
* 1 \leq N \leq 10^5
* 1 \leq A_i,B_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 B_1
A_2 B_2
\vdots
A_N B_N
Output
Print the numerator and denominator of the irreducible fraction that represents the maximum probability of Snuke's winning.
Examples
Input
2
3 2
1 2
Output
1 4
Input
4
1 5
4 7
2 1
8 4
Output
1 2
Input
3
4 1
5 2
6 3
Output
0 1
Input
10
866111664 178537096
705445072 318106937
472381277 579910117
353498483 865935868
383133839 231371336
378371075 681212831
304570952 16537461
955719384 267238505
844917655 218662351
550309930 62731178
Output
697461712 2899550585
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int a[200010],b[200010],n,val[200010],l,r,mid,ans,fp,nwp;
long long nw,sum[200010],nww,fa,fb,nwa,nwb;
long long gcd(long long a,long long b) {return (!b)?a:gcd(b,a%b);}
int main()
{
scanf("%d",&n);
for (int i=1; i<=n; i++) scanf("%d%d",&a[i],&b[i]),val[i]=max(a[i],b[i]),nw+=min(a[i]-b[i],0);
sort(val+1,val+1+n),sum[0]=0,fp=0,fa=0,fb=1;
for (int i=1; i<=n; i++) sum[i]=sum[i-1]+val[i];
for (int i=1; i<=n; i++)
{
l=1,r=n,ans=0,nww=(a[i]<b[i]?nw:nw+a[i]-b[i]);
while (l<=r)
{
mid=(l+r)>>1;
if (sum[mid]-(max(a[i],b[i])<=val[mid]?max(a[i],b[i]):0)+nww<=0) ans=mid,l=mid+1; else r=mid-1;
}
nww=nww-(a[i]-b[i])+sum[ans]-(max(a[i],b[i])<=val[ans]?max(a[i],b[i]):0);
nwp=ans-(max(a[i],b[i])<=val[ans]);
nwa=b[i]-(a[i]+nww),nwb=b[i];
if (nwp>fp||nwp==fp&&nwa*fb>nwb*fa) fp=nwp,fa=nwa,fb=nwb;
}
fa+=fp*fb,fb*=n;
long long g=gcd(fa,fb);
printf("%lld %lld\n",fa/g,fb/g);
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Nikita has a stack. A stack in this problem is a data structure that supports two operations. Operation push(x) puts an integer x on the top of the stack, and operation pop() deletes the top integer from the stack, i. e. the last added. If the stack is empty, then the operation pop() does nothing.
Nikita made m operations with the stack but forgot them. Now Nikita wants to remember them. He remembers them one by one, on the i-th step he remembers an operation he made pi-th. In other words, he remembers the operations in order of some permutation p1, p2, ..., pm. After each step Nikita wants to know what is the integer on the top of the stack after performing the operations he have already remembered, in the corresponding order. Help him!
Input
The first line contains the integer m (1 ≤ m ≤ 105) — the number of operations Nikita made.
The next m lines contain the operations Nikita remembers. The i-th line starts with two integers pi and ti (1 ≤ pi ≤ m, ti = 0 or ti = 1) — the index of operation he remembers on the step i, and the type of the operation. ti equals 0, if the operation is pop(), and 1, is the operation is push(x). If the operation is push(x), the line also contains the integer xi (1 ≤ xi ≤ 106) — the integer added to the stack.
It is guaranteed that each integer from 1 to m is present exactly once among integers pi.
Output
Print m integers. The integer i should equal the number on the top of the stack after performing all the operations Nikita remembered on the steps from 1 to i. If the stack is empty after performing all these operations, print -1.
Examples
Input
2
2 1 2
1 0
Output
2
2
Input
3
1 1 2
2 1 3
3 0
Output
2
3
2
Input
5
5 0
4 0
3 1 1
2 1 1
1 1 2
Output
-1
-1
-1
-1
2
Note
In the first example, after Nikita remembers the operation on the first step, the operation push(2) is the only operation, so the answer is 2. After he remembers the operation pop() which was done before push(2), answer stays the same.
In the second example, the operations are push(2), push(3) and pop(). Nikita remembers them in the order they were performed.
In the third example Nikita remembers the operations in the reversed order.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int GLL(long long& x) { return scanf("%lld", &x); }
int GI(int& x) { return scanf("%d", &x); }
const int MAXRT = 333;
const int MAXM = MAXRT * MAXRT;
pair<int, int> actions[MAXM];
int pops[MAXRT];
vector<int> pushes[MAXRT];
int m, p, t, x;
void buildBlock(int b) {
pops[b] = 0;
pushes[b] = vector<int>();
for (int i = b * MAXRT; i < (b + 1) * MAXRT; i++) {
if (actions[i].first == 0) {
if (pushes[b].size() > 0) {
pushes[b].pop_back();
} else {
pops[b]++;
}
} else if (actions[i].first == 1) {
pushes[b].push_back(actions[i].second);
}
}
}
vector<pair<int, int> > state;
int combineBlocks() {
state = vector<pair<int, int> >();
for (int i = 0; i < (int)(MAXRT); i++) {
int pop = pops[i];
while (pop > 0 && state.size() > 0) {
if (state[state.size() - 1].second <= pop) {
pop -= state[state.size() - 1].second;
state.pop_back();
} else {
state[state.size() - 1].second -= pop;
pop = 0;
}
}
state.push_back(make_pair(i, pushes[i].size()));
}
while (state.size() > 0 && state[state.size() - 1].second == 0) {
state.pop_back();
}
if (state.size() == 0) {
return -1;
} else {
return pushes[state[state.size() - 1].first]
[state[state.size() - 1].second - 1];
}
}
int main() {
for (int i = 0; i < (int)(MAXM); i++) actions[i] = make_pair(-1, -1);
memset(pops, 0, sizeof pops);
GI(m);
for (int i = 0; i < (int)(m); i++) {
GI(p);
GI(t);
if (t == 1) GI(x);
actions[p] = make_pair(t, x);
buildBlock(p / MAXRT);
printf("%d\n", combineBlocks());
}
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?
Input
The first line contains number n (1 ≤ n ≤ 1000) — the number of values of the banknotes that used in Geraldion.
The second line contains n distinct space-separated numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the values of the banknotes.
Output
Print a single line — the minimum unfortunate sum. If there are no unfortunate sums, print - 1.
Examples
Input
5
1 2 3 4 5
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int i, n, a[1000];
cin >> n;
for (i = 0; i < n; i++) {
cin >> a[i];
}
sort(a, a + n);
if (a[0] == 1)
cout << "-1";
else {
cout << "1";
}
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.
New parliament assembly hall is a rectangle consisting of a × b chairs — a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hall
We know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.
Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.
Input
The first line of the input contains three integers n, a and b (1 ≤ n ≤ 10 000, 1 ≤ a, b ≤ 100) — the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.
Output
If there is no way to assigns seats to parliamentarians in a proper way print -1.
Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.
Examples
Input
3 2 2
Output
0 3
1 2
Input
8 4 3
Output
7 8 3
0 1 4
6 0 5
0 2 0
Input
10 2 2
Output
-1
Note
In the first sample there are many other possible solutions. For example,
3 2
0 1
and
2 1
3 0
The following assignment
3 2
1 0
is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int p, n, m;
cin >> p >> n >> m;
if (p > n * m)
cout << "-1\n";
else {
for (int i = 0; i < n; i++) {
int s, e;
s = i * m + 1;
e = (i + 1) * m;
if (i % 2 == 0 || (m % 2 == 1)) {
for (int j = s; j <= e; j++)
if (j <= p)
cout << j << ' ';
else
cout << "0 ";
cout << '\n';
} else {
for (int j = e; j >= s; j--)
if (j <= p)
cout << j << ' ';
else
cout << "0 ";
cout << '\n';
}
}
}
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
After observing the results of Spy Syndrome, Yash realised the errors of his ways. He now believes that a super spy such as Siddhant can't use a cipher as basic and ancient as Caesar cipher. After many weeks of observation of Siddhant’s sentences, Yash determined a new cipher technique.
For a given sentence, the cipher is processed as:
1. Convert all letters of the sentence to lowercase.
2. Reverse each of the words of the sentence individually.
3. Remove all the spaces in the sentence.
For example, when this cipher is applied to the sentence
Kira is childish and he hates losing
the resulting string is
ariksihsidlihcdnaehsetahgnisol
Now Yash is given some ciphered string and a list of words. Help him to find out any original sentence composed using only words from the list. Note, that any of the given words could be used in the sentence multiple times.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 10 000) — the length of the ciphered text. The second line consists of n lowercase English letters — the ciphered text t.
The third line contains a single integer m (1 ≤ m ≤ 100 000) — the number of words which will be considered while deciphering the text. Each of the next m lines contains a non-empty word wi (|wi| ≤ 1 000) consisting of uppercase and lowercase English letters only. It's guaranteed that the total length of all words doesn't exceed 1 000 000.
Output
Print one line — the original sentence. It is guaranteed that at least one solution exists. If there are multiple solutions, you may output any of those.
Examples
Input
30
ariksihsidlihcdnaehsetahgnisol
10
Kira
hates
is
he
losing
death
childish
L
and
Note
Output
Kira is childish and he hates losing
Input
12
iherehtolleh
5
HI
Ho
there
HeLLo
hello
Output
HI there HeLLo
Note
In sample case 2 there may be multiple accepted outputs, "HI there HeLLo" and "HI there hello" you may output any of them.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int mod = 1000000009;
const long long b = 29;
const int N = 100002;
int dp[10003], sa[10003], n, m;
string v[N], s;
unordered_map<long long, int> p;
int main() {
cin.tie(0);
ios_base::sync_with_stdio(0);
cin >> n >> s >> m;
for (int i = 0; i < m; ++i) {
cin >> v[i];
long long h = 0ll;
for (int j = v[i].size() - 1; j >= 0; j--) {
long long ch = v[i][j] - 'a' + 1;
if (ch <= 0) ch = v[i][j] - 'A' + 1;
h = (h * b + ch) % mod;
}
p[h] = i + 1;
}
int len = s.size() - 1;
dp[len + 1] = n;
for (int i = len; i >= 0; --i) {
long long h = 0ll;
for (int j = i; j <= len; ++j) {
long long ch = s[j] - 'a' + 1;
h = ((h * b) + ch) % mod;
if (dp[j + 1] and p.find(h) != p.end()) {
dp[i] = j + 1;
sa[i] = p[h];
break;
}
}
}
for (int i = 0; i <= len; i = dp[i]) {
cout << v[sa[i] - 1] << " ";
if (i >= dp[i]) break;
}
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Our old friend Alexey has finally entered the University of City N — the Berland capital. Alexey expected his father to get him a place to live in but his father said it was high time for Alexey to practice some financial independence. So, Alexey is living in a dorm.
The dorm has exactly one straight dryer — a 100 centimeter long rope to hang clothes on. The dryer has got a coordinate system installed: the leftmost end of the dryer has coordinate 0, and the opposite end has coordinate 100. Overall, the university has n students. Dean's office allows i-th student to use the segment (li, ri) of the dryer. However, the dean's office actions are contradictory and now one part of the dryer can belong to multiple students!
Alexey don't like when someone touch his clothes. That's why he want make it impossible to someone clothes touch his ones. So Alexey wonders: what is the total length of the parts of the dryer that he may use in a such way that clothes of the others (n - 1) students aren't drying there. Help him! Note that Alexey, as the most respected student, has number 1.
Input
The first line contains a positive integer n (1 ≤ n ≤ 100). The (i + 1)-th line contains integers li and ri (0 ≤ li < ri ≤ 100) — the endpoints of the corresponding segment for the i-th student.
Output
On a single line print a single number k, equal to the sum of lengths of the parts of the dryer which are inside Alexey's segment and are outside all other segments.
Examples
Input
3
0 5
2 8
1 6
Output
1
Input
3
0 10
1 5
7 15
Output
3
Note
Note that it's not important are clothes drying on the touching segments (e.g. (0, 1) and (1, 2)) considered to be touching or not because you need to find the length of segments.
In the first test sample Alexey may use the only segment (0, 1). In such case his clothes will not touch clothes on the segments (1, 6) and (2, 8). The length of segment (0, 1) is 1.
In the second test sample Alexey may dry his clothes on segments (0, 1) and (5, 7). Overall length of these segments is 3.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int A[1000];
int n, r1, l1, r, l, i, j;
int s = 0;
int main() {
scanf("%d%d%d", &n, &r1, &l1);
for (i = 0; i <= 101; i++) {
A[i] = 0;
}
for (i = 2; i <= n; i++) {
scanf("%d%d", &r, &l);
for (j = r + 1; j <= l; j++) A[j] = 1;
}
for (i = r1 + 1; i <= l1; i++) {
if (A[i] == 0) {
s++;
}
}
printf("%d\n", s);
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix a with n lines and m columns. Let number a[i][j] represents the calories burned by performing workout at the cell of gym in the i-th line and the j-th column.
Iahub starts with workout located at line 1 and column 1. He needs to finish with workout a[n][m]. After finishing workout a[i][j], he can go to workout a[i + 1][j] or a[i][j + 1]. Similarly, Iahubina starts with workout a[n][1] and she needs to finish with workout a[1][m]. After finishing workout from cell a[i][j], she goes to either a[i][j + 1] or a[i - 1][j].
There is one additional condition for their training. They have to meet in exactly one cell of gym. At that cell, none of them will work out. They will talk about fast exponentiation (pretty odd small talk) and then both of them will move to the next workout.
If a workout was done by either Iahub or Iahubina, it counts as total gain. Please plan a workout for Iahub and Iahubina such as total gain to be as big as possible. Note, that Iahub and Iahubina can perform workouts with different speed, so the number of cells that they use to reach meet cell may differs.
Input
The first line of the input contains two integers n and m (3 ≤ n, m ≤ 1000). Each of the next n lines contains m integers: j-th number from i-th line denotes element a[i][j] (0 ≤ a[i][j] ≤ 105).
Output
The output contains a single number — the maximum total gain possible.
Examples
Input
3 3
100 100 100
100 1 100
100 100 100
Output
800
Note
Iahub will choose exercises a[1][1] → a[1][2] → a[2][2] → a[3][2] → a[3][3]. Iahubina will choose exercises a[3][1] → a[2][1] → a[2][2] → a[2][3] → a[1][3].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m;
int a[1010][1010] = {0};
int dp00[1010][1010] = {0}, dp01[1010][1010] = {0}, dp10[1010][1010] = {0},
dp11[1010][1010] = {0};
int ans = 0;
int ans1 = 0, ans2 = 0;
void init() {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
dp00[i][j] = max(dp00[i - 1][j], dp00[i][j - 1]) + a[i][j];
}
}
for (int i = 1; i <= n; i++) {
for (int j = m; j >= 1; j--) {
dp01[i][j] = max(dp01[i - 1][j], dp01[i][j + 1]) + a[i][j];
}
}
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= m; j++) {
dp10[i][j] = max(dp10[i + 1][j], dp10[i][j - 1]) + a[i][j];
}
}
for (int i = n; i >= 1; i--) {
for (int j = m; j >= 1; j--) {
dp11[i][j] = max(dp11[i + 1][j], dp11[i][j + 1]) + a[i][j];
}
}
}
void solve() {
for (int i = 2; i <= n - 1; i++) {
for (int j = 2; j <= m - 1; j++) {
ans = max(ans, dp00[i][j - 1] + dp01[i - 1][j] + dp10[i + 1][j] +
dp11[i][j + 1]);
ans = max(ans, dp00[i - 1][j] + dp01[i][j + 1] + dp10[i][j - 1] +
dp11[i + 1][j]);
}
}
cout << ans;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
}
}
init();
solve();
}
``` |
### Prompt
Create a solution in CPP for the following problem:
We have a string s consisting of lowercase English letters. Snuke can perform the following operation repeatedly:
* Insert a letter `x` to any position in s of his choice, including the beginning and end of s.
Snuke's objective is to turn s into a palindrome. Determine whether the objective is achievable. If it is achievable, find the minimum number of operations required.
Constraints
* 1 \leq |s| \leq 10^5
* s consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
Output
If the objective is achievable, print the number of operations required. If it is not, print `-1` instead.
Examples
Input
xabxa
Output
2
Input
ab
Output
-1
Input
a
Output
0
Input
oxxx
Output
3
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
int ans=0;
cin>>s;
int n=s.size();
int l=0; int r=n-1;
while(l<=r)
{
if(s[l]==s[r])
{
l++; r--;
continue;
}
if(s[l]!='x' && s[r]!='x')
{
cout<<-1<<endl;
return 0;
}
if(s[l]=='x')
{
l++;
ans++;
continue;
}
if(s[r]=='x')
{
r--;;
ans++;
continue;
}
}
cout<<ans<<endl;
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
problem
AOR Ika is a monster buster.
One day, as I was walking down the road, I met a sleeping monster.
AOR Ika, who has a strong fighting spirit, decides to hit the monster with a wake-up blow. However, the current attack power of AOR Ika is $ 0 $, and she cannot make a decent attack as it is.
AOR Ika-chan, who is devoting himself to the monster buster, was actually entrusted with a special whistle by his master. When he plays a specific song with this whistle, his attack power increases for a certain period of time.
Trained AOR Ika can play $ N $ songs. The $ i $ th song takes $ R_i $ seconds to play, and the attack power increases by $ A_i $ after the performance ends. After $ T_i $ seconds, the effect of this performance will be cut off and the attack power will return to that before the performance.
Also, AOR Ika-chan can play over and over. If you finish playing the same song during the effect time of the performance, the attack power will increase by $ W_i $ instead of $ A_i $. The time is not extended. Therefore, when the first effect of the $ i $ th song currently in effect expires, all the effects of the layered performance also expire.
Output the maximum attack power of AOR Ika-chan. No matter how much you play, no monster will occur, and AOR Ika-chan can attack in $ 0.5 $ seconds.
output
Output the maximum value of AOR Ika-chan's attack power. Also, output a line break at the end.
Example
Input
2
5 10 5 5
4 4 2 2
Output
14
### Response
```cpp
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int N;
long long dp[2][2020];
vector<pair<pair<long long,long long>,pair<long long,long long> > >E;
int main()
{
cin>>N;
for(int i=0;i<=2000;i++)dp[0][i]=-1e18;
for(int i=0;i<N;i++)
{
long long R,A,W,T;
cin>>R>>A>>W>>T;
T--;
E.push_back({{T,R},{A,W}});
}
sort(E.begin(),E.end(),[](
pair<pair<long long,long long>,pair<long long,long long> >a,
pair<pair<long long,long long>,pair<long long,long long> >b
){return a.first.first+a.first.second>b.first.first+b.first.second;}
);
for(int i=0;i<N;i++)
{
long long R,A,W,T;
R=E[i].first.second;
A=E[i].second.first;
W=E[i].second.second;
T=E[i].first.first;
for(int j=0;j<=2000;j++)dp[1][j]=-1e18;
for(int j=R;j<=2000;j++)
{
dp[1][min(T,j-R)]=max(dp[1][min(T,j-R)],dp[0][j]+A);
}
dp[1][T]=max(dp[1][T],A);
for(int j=T;j>=R;j--)
{
dp[1][j-R]=max(dp[1][j-R],dp[1][j]+W);
}
for(int j=0;j<=2000;j++)dp[0][j]=max(dp[0][j],dp[1][j]);
}
long long ans=0;
for(int j=0;j<=2000;j++)ans=max(ans,dp[0][j]);
cout<<ans<<endl;
}
``` |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.