text
stringlengths 424
69.5k
|
---|
### Prompt
Create a solution in CPP for the following problem:
Meanwhile, the kingdom of K is getting ready for the marriage of the King's daughter. However, in order not to lose face in front of the relatives, the King should first finish reforms in his kingdom. As the King can not wait for his daughter's marriage, reforms must be finished as soon as possible.
The kingdom currently consists of n cities. Cities are connected by n - 1 bidirectional road, such that one can get from any city to any other city. As the King had to save a lot, there is only one path between any two cities.
What is the point of the reform? The key ministries of the state should be relocated to distinct cities (we call such cities important). However, due to the fact that there is a high risk of an attack by barbarians it must be done carefully. The King has made several plans, each of which is described by a set of important cities, and now wonders what is the best plan.
Barbarians can capture some of the cities that are not important (the important ones will have enough protection for sure), after that the captured city becomes impassable. In particular, an interesting feature of the plan is the minimum number of cities that the barbarians need to capture in order to make all the important cities isolated, that is, from all important cities it would be impossible to reach any other important city.
Help the King to calculate this characteristic for each of his plan.
Input
The first line of the input contains integer n (1 β€ n β€ 100 000) β the number of cities in the kingdom.
Each of the next n - 1 lines contains two distinct integers ui, vi (1 β€ ui, vi β€ n) β the indices of the cities connected by the i-th road. It is guaranteed that you can get from any city to any other one moving only along the existing roads.
The next line contains a single integer q (1 β€ q β€ 100 000) β the number of King's plans.
Each of the next q lines looks as follows: first goes number ki β the number of important cities in the King's plan, (1 β€ ki β€ n), then follow exactly ki space-separated pairwise distinct numbers from 1 to n β the numbers of important cities in this plan.
The sum of all ki's does't exceed 100 000.
Output
For each plan print a single integer β the minimum number of cities that the barbarians need to capture, or print - 1 if all the barbarians' attempts to isolate important cities will not be effective.
Examples
Input
4
1 3
2 3
4 3
4
2 1 2
3 2 3 4
3 1 2 4
4 1 2 3 4
Output
1
-1
1
-1
Input
7
1 2
2 3
3 4
1 5
5 6
5 7
1
4 2 4 6 7
Output
2
Note
In the first sample, in the first and the third King's plan barbarians can capture the city 3, and that will be enough. In the second and the fourth plans all their attempts will not be effective.
In the second sample the cities to capture are 3 and 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#pragma GCC target("avx2")
#pragma GCC optimization("O3")
#pragma GCC optimization("unroll-loops")
struct greateri {
template <class T>
bool operator()(T const &a, T const &b) const {
return a > b;
}
};
void setIO(string s) {
ios_base::sync_with_stdio(0);
cin.tie(0);
freopen((s + ".in").c_str(), "r", stdin);
freopen((s + ".out").c_str(), "w", stdout);
}
vector<long long> trt[100001], tree[100001];
long long tin[100001], tout[100001], impo[100001], dep[100001];
long long par[100001][37];
long long n, in, l;
void dfs(long long node, long long p, long long d) {
tin[node] = in++;
par[node][0] = p;
dep[node] = d;
for (long long i = 1; i <= l; ++i) {
par[node][i] = par[par[node][i - 1]][i - 1];
}
for (auto it : tree[node]) {
if (it != p) {
dfs(it, node, d + 1);
}
}
tout[node] = in++;
}
bool up(long long u, long long v) {
return tin[u] <= tin[v] && tout[u] >= tout[v];
}
long long lca(long long u, long long v) {
if (up(u, v)) return u;
if (up(v, u)) return v;
for (long long i = l; i >= 0; --i) {
if (!up(par[u][i], v)) u = par[u][i];
}
return par[u][0];
}
bool ka = true;
pair<long long, long long> solve(long long node, long long p) {
pair<long long, long long> ans;
ans.first = 0;
ans.second = 0;
long long counti = 0;
long long cna = 0;
for (auto it : trt[node]) {
if (it != p) {
long long len = dep[it] - dep[node];
if (impo[node]) {
if (impo[it] && len == 1) ka = false;
auto v = solve(it, node);
ans.first += v.first;
if ((v.second) != 0) counti++;
} else {
auto v = solve(it, node);
ans.first += v.first;
if ((v.second) != 0) cna++;
}
}
}
if (impo[node]) {
ans.first += counti;
ans.second = 1;
} else {
if (cna <= 1) {
ans.second += cna;
} else {
ans.first++;
ans.second = 0;
}
}
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
l = log2(n);
for (long long i = 0; i < n - 1; ++i) {
long long x, y;
cin >> x >> y;
x--, y--;
tree[x].push_back(y);
tree[y].push_back(x);
}
dfs(0, 0, 0);
long long q;
cin >> q;
while (q--) {
ka = true;
long long k;
cin >> k;
vector<pair<long long, long long> > imp;
set<pair<long long, long long> > cum;
for (long long i = 0; i < k; ++i) {
long long yo;
cin >> yo;
yo--;
impo[yo]++;
imp.push_back({tin[yo], yo});
cum.insert({tin[yo], yo});
}
sort((imp).begin(), (imp).end());
for (long long i = 0; i < k - 1; ++i) {
long long k = lca(imp[i].second, imp[i + 1].second);
cum.insert({tin[k], k});
}
imp.clear();
for (auto it : cum) {
imp.push_back(it);
}
vector<long long> yom;
yom.push_back(imp[0].second);
for (long long i = 1; i < (long long)imp.size(); ++i) {
long long cur = imp[i].second;
while ((long long)yom.size() >= 2 &&
!up(yom[(long long)yom.size() - 1], cur)) {
trt[yom[(long long)yom.size() - 2]].push_back(yom.back());
yom.pop_back();
}
yom.push_back(cur);
}
while ((long long)yom.size() >= 2) {
trt[yom[(long long)yom.size() - 2]].push_back(yom.back());
yom.pop_back();
}
auto ans = solve(yom[0], -1);
if (ka)
cout << ans.first << '\n';
else
cout << -1 << '\n';
for (long long i = 0; i < imp.size(); ++i) {
trt[imp[i].second].clear();
if (impo[imp[i].second]) impo[imp[i].second]--;
}
imp.clear();
}
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Vasya has a sequence of cubes and exactly one integer is written on each cube. Vasya exhibited all his cubes in a row. So the sequence of numbers written on the cubes in the order from the left to the right equals to a1, a2, ..., an.
While Vasya was walking, his little brother Stepan played with Vasya's cubes and changed their order, so now the sequence of numbers written on the cubes became equal to b1, b2, ..., bn.
Stepan said that he swapped only cubes which where on the positions between l and r, inclusive, and did not remove or add any other cubes (i. e. he said that he reordered cubes between positions l and r, inclusive, in some way).
Your task is to determine if it is possible that Stepan said the truth, or it is guaranteed that Stepan deceived his brother.
Input
The first line contains three integers n, l, r (1 β€ n β€ 105, 1 β€ l β€ r β€ n) β the number of Vasya's cubes and the positions told by Stepan.
The second line contains the sequence a1, a2, ..., an (1 β€ ai β€ n) β the sequence of integers written on cubes in the Vasya's order.
The third line contains the sequence b1, b2, ..., bn (1 β€ bi β€ n) β the sequence of integers written on cubes after Stepan rearranged their order.
It is guaranteed that Stepan did not remove or add other cubes, he only rearranged Vasya's cubes.
Output
Print "LIE" (without quotes) if it is guaranteed that Stepan deceived his brother. In the other case, print "TRUTH" (without quotes).
Examples
Input
5 2 4
3 4 2 3 1
3 2 3 4 1
Output
TRUTH
Input
3 1 2
1 2 3
3 1 2
Output
LIE
Input
4 2 4
1 1 1 1
1 1 1 1
Output
TRUTH
Note
In the first example there is a situation when Stepan said the truth. Initially the sequence of integers on the cubes was equal to [3, 4, 2, 3, 1]. Stepan could at first swap cubes on positions 2 and 3 (after that the sequence of integers on cubes became equal to [3, 2, 4, 3, 1]), and then swap cubes in positions 3 and 4 (after that the sequence of integers on cubes became equal to [3, 2, 3, 4, 1]).
In the second example it is not possible that Stepan said truth because he said that he swapped cubes only between positions 1 and 2, but we can see that it is guaranteed that he changed the position of the cube which was on the position 3 at first. So it is guaranteed that Stepan deceived his brother.
In the third example for any values l and r there is a situation when Stepan said the truth.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int mod = 1000000007;
long long int POWER[65];
void precompute() {
POWER[0] = 1;
for (int i = 1; i < 31; i++) POWER[i] = POWER[i - 1] << 1LL;
}
long long int power(long long int x, long long int y, long long int mod) {
long long int res = 1;
x %= mod;
while (y) {
if (y & 1) res = (res * x) % mod;
y >>= 1;
x = (x * x) % mod;
}
return res;
}
int main() {
long long int n, l, r;
cin >> n >> l >> r;
long long int a[n];
long long int b[n];
map<long long int, long long int> ma, mb;
for (long long int i = 0; i < n; i++) {
cin >> a[i];
}
for (long long int i = 0; i < n; i++) {
cin >> b[i];
}
for (long long int i = l - 1; i < r; i++) {
ma[a[i]]++;
mb[b[i]]++;
}
for (long long int i = l - 1; i < r; i++) {
if (ma[a[i]] != mb[a[i]]) {
cout << "LIE";
return 0;
}
}
for (long long int i = 0; i < l - 1; i++) {
if (a[i] != b[i]) {
cout << "LIE";
return 0;
}
}
for (long long int i = r + 2; i < n; i++) {
if (a[i] != b[i]) {
cout << "LIE";
return 0;
}
}
cout << "TRUTH";
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Chef Monocarp has just put n dishes into an oven. He knows that the i-th dish has its optimal cooking time equal to t_i minutes.
At any positive integer minute T Monocarp can put no more than one dish out of the oven. If the i-th dish is put out at some minute T, then its unpleasant value is |T - t_i| β the absolute difference between T and t_i. Once the dish is out of the oven, it can't go back in.
Monocarp should put all the dishes out of the oven. What is the minimum total unpleasant value Monocarp can obtain?
Input
The first line contains a single integer q (1 β€ q β€ 200) β the number of testcases.
Then q testcases follow.
The first line of the testcase contains a single integer n (1 β€ n β€ 200) β the number of dishes in the oven.
The second line of the testcase contains n integers t_1, t_2, ..., t_n (1 β€ t_i β€ n) β the optimal cooking time for each dish.
The sum of n over all q testcases doesn't exceed 200.
Output
Print a single integer for each testcase β the minimum total unpleasant value Monocarp can obtain when he puts out all the dishes out of the oven. Remember that Monocarp can only put the dishes out at positive integer minutes and no more than one dish at any minute.
Example
Input
6
6
4 2 4 4 5 2
7
7 7 7 7 7 7 7
1
1
5
5 1 2 4 3
4
1 4 4 4
21
21 8 1 4 1 5 21 1 8 21 11 21 11 3 12 8 19 15 9 11 13
Output
4
12
0
0
2
21
Note
In the first example Monocarp can put out the dishes at minutes 3, 1, 5, 4, 6, 2. That way the total unpleasant value will be |4 - 3| + |2 - 1| + |4 - 5| + |4 - 4| + |6 - 5| + |2 - 2| = 4.
In the second example Monocarp can put out the dishes at minutes 4, 5, 6, 7, 8, 9, 10.
In the third example Monocarp can put out the dish at minute 1.
In the fourth example Monocarp can put out the dishes at minutes 5, 1, 2, 4, 3.
In the fifth example Monocarp can put out the dishes at minutes 1, 3, 4, 5.
### Response
```cpp
#include <bits/stdc++.h>
int main() {
int time;
scanf("%d", &time);
while (time--) {
int n;
scanf("%d", &n);
int a[300];
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
int z = -1;
for (int i = n; i > 1; i--) {
for (int j = 1; j < i; j++) {
if (a[j] > a[j + 1]) {
z = a[j];
a[j] = a[j + 1];
a[j + 1] = z;
}
}
}
int b[300][500];
for (int i = 0; i <= n; i++)
for (int j = 0; j <= n * 2; j++) b[i][j] = 2000000000;
for (int j = 0; j <= n * 2; j++) b[0][j] = 0;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n * 2; j++)
b[i][j] = (((b[i][j - 1]) > (b[i - 1][j - 1] + abs(j - a[i])))
? (b[i - 1][j - 1] + abs(j - a[i]))
: (b[i][j - 1]));
printf("%d\n", b[n][n * 2]);
}
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row β the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column β the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 Γ 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 β€ aij β€ 100) separated by single spaces β the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 β€ n β€ 5
The input limitations for getting 100 points are:
* 1 β€ n β€ 101
Output
Print a single integer β the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int a[n][n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cin >> a[i][j];
}
}
int s = 0;
for (int i = 0; i < n; ++i) {
s += a[i][i];
if (i != n / 2) {
s += a[i][n - 1 - i] + a[i][n / 2] + a[n / 2][i];
}
}
cout << s << endl;
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
You are given a set of n elements indexed from 1 to n. The weight of i-th element is wi. The weight of some subset of a given set is denoted as <image>. The weight of some partition R of a given set into k subsets is <image> (recall that a partition of a given set is a set of its subsets such that every element of the given set belongs to exactly one subset in partition).
Calculate the sum of weights of all partitions of a given set into exactly k non-empty subsets, and print it modulo 109 + 7. Two partitions are considered different iff there exist two elements x and y such that they belong to the same set in one of the partitions, and to different sets in another partition.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2Β·105) β the number of elements and the number of subsets in each partition, respectively.
The second line contains n integers wi (1 β€ wi β€ 109)β weights of elements of the set.
Output
Print one integer β the sum of weights of all partitions of a given set into k non-empty subsets, taken modulo 109 + 7.
Examples
Input
4 2
2 3 2 3
Output
160
Input
5 2
1 2 3 4 5
Output
645
Note
Possible partitions in the first sample:
1. {{1, 2, 3}, {4}}, W(R) = 3Β·(w1 + w2 + w3) + 1Β·w4 = 24;
2. {{1, 2, 4}, {3}}, W(R) = 26;
3. {{1, 3, 4}, {2}}, W(R) = 24;
4. {{1, 2}, {3, 4}}, W(R) = 2Β·(w1 + w2) + 2Β·(w3 + w4) = 20;
5. {{1, 3}, {2, 4}}, W(R) = 20;
6. {{1, 4}, {2, 3}}, W(R) = 20;
7. {{1}, {2, 3, 4}}, W(R) = 26;
Possible partitions in the second sample:
1. {{1, 2, 3, 4}, {5}}, W(R) = 45;
2. {{1, 2, 3, 5}, {4}}, W(R) = 48;
3. {{1, 2, 4, 5}, {3}}, W(R) = 51;
4. {{1, 3, 4, 5}, {2}}, W(R) = 54;
5. {{2, 3, 4, 5}, {1}}, W(R) = 57;
6. {{1, 2, 3}, {4, 5}}, W(R) = 36;
7. {{1, 2, 4}, {3, 5}}, W(R) = 37;
8. {{1, 2, 5}, {3, 4}}, W(R) = 38;
9. {{1, 3, 4}, {2, 5}}, W(R) = 38;
10. {{1, 3, 5}, {2, 4}}, W(R) = 39;
11. {{1, 4, 5}, {2, 3}}, W(R) = 40;
12. {{2, 3, 4}, {1, 5}}, W(R) = 39;
13. {{2, 3, 5}, {1, 4}}, W(R) = 40;
14. {{2, 4, 5}, {1, 3}}, W(R) = 41;
15. {{3, 4, 5}, {1, 2}}, W(R) = 42.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n;
long long k;
long long a[200005];
long long s1;
long long s2;
long long inv[200005];
long long p;
long long ans;
long long quick_pow(long long x, long long n) {
long long res = 1;
while (n) {
if (n & 1) res = res * x % 1000000007;
x = x * x % 1000000007;
n >>= 1;
}
return res;
}
int main() {
scanf("%lld %lld", &n, &k);
inv[1] = inv[0] = 1LL;
for (long long i = 2; i <= n; i++)
inv[i] = (1000000007 - 1000000007 / i) * inv[1000000007 % i] % 1000000007;
for (long long i = 1; i <= n; ++i) inv[i] = inv[i - 1] * inv[i] % 1000000007;
for (long long i = 1; i <= n; ++i) scanf("%lld", a + i);
for (long long i = 0; i <= k; ++i) {
long long fg = 1;
if (i & 1) fg = -1;
(s1 += fg * inv[i] * inv[k - i] % 1000000007 * quick_pow(k - i, n) %
1000000007) %= 1000000007;
(s2 += fg * inv[i] * inv[k - i] % 1000000007 * quick_pow(k - i, n - 1) %
1000000007) %= 1000000007;
}
p = (s1 + s2 * (n - 1) % 1000000007) % 1000000007;
p = (p + 1000000007) % 1000000007;
for (long long i = 1; i <= n; ++i)
ans = (ans + a[i] * p % 1000000007) % 1000000007;
printf("%lld\n", ans);
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Vasily the bear has got a large square white table of n rows and n columns. The table has got a black border around this table.
<image> The example of the initial table at n = 5.
Vasily the bear wants to paint his square table in exactly k moves. Each move is sequence of actions:
1. The bear chooses some square inside his table. At that the square must have a black border painted around it. Also, the square shouldn't contain a black cell. The number of cells in the square shouldn't be less than 2.
2. The bear chooses some row and some column inside the chosen square. Then he paints each cell of this row and this column inside the chosen square. After that the rectangles, formed by the square's border and the newly painted cells, must be squares of a non-zero area.
<image> An example of correct painting at n = 7 ΠΈ k = 2.
The bear already knows numbers n and k. Help him β find the number of ways to paint the square in exactly k moves. Two ways to paint are called distinct if the resulting tables will differ in at least one cell. As the answer can be rather large, print the remainder after dividing it by 7340033.
Input
The first line contains integer q (1 β€ q β€ 105) β the number of test data.
Each of the following q lines contains two integers n and k (1 β€ n β€ 109, 0 β€ k β€ 1000) β the size of the initial table and the number of moves for the corresponding test.
Output
For each test from the input print the answer to the problem modulo 7340033. Print the answers to the tests in the order in which the tests are given in the input.
Examples
Input
8
1 0
1 1
3 0
3 1
2 0
2 1
3 2
7 2
Output
1
0
1
1
1
0
0
4
Note
All possible painting ways for the test n = 7 and k = 2 are:
<image>
### Response
```cpp
#include <bits/stdc++.h>
const long long delta = 7340033;
long long n, q, k;
using namespace std;
long long dp[35][1001], tmp[1000];
long long cut(long long x) {
if (x & 1) return cut(x / 2) + 1;
return 0;
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> q;
for (long long i = 0; i < 35; i++) dp[i][0] = 1;
for (long long i = 1; i < 35; i++) dp[i][1] = 1;
for (long long i = 1; i < 34; i++)
for (long long c = 0; c < 4; c++) {
for (long long k = 0; k < 1001; k++) tmp[k] = 0;
for (long long j = 1; j < 1001; j++)
for (long long aj = j + 1; aj < 1001; aj++) {
tmp[aj] += (dp[i + 1][aj - j] * dp[i][j]) % delta;
tmp[aj] %= delta;
}
for (long long k = 1; k < 1001; k++) {
dp[i + 1][k] += tmp[k];
dp[i + 1][k] %= delta;
}
}
dp[0][0] = 1;
while (q--) {
cin >> n >> k;
if ((1 << (cut(n))) > n)
cout << dp[cut(n) - 1][k] << endl;
else
cout << dp[cut(n)][k] << endl;
}
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Little Janet likes playing with cubes. Actually, she likes to play with anything whatsoever, cubes or tesseracts, as long as they are multicolored. Each cube is described by two parameters β color ci and size si. A Zebra Tower is a tower that consists of cubes of exactly two colors. Besides, the colors of the cubes in the tower must alternate (colors of adjacent cubes must differ). The Zebra Tower should have at least two cubes. There are no other limitations. The figure below shows an example of a Zebra Tower.
<image>
A Zebra Tower's height is the sum of sizes of all cubes that form the tower. Help little Janet build the Zebra Tower of the maximum possible height, using the available cubes.
Input
The first line contains an integer n (2 β€ n β€ 105) β the number of cubes. Next n lines contain the descriptions of the cubes, one description per line. A cube description consists of two space-separated integers ci and si (1 β€ ci, si β€ 109) β the i-th cube's color and size, correspondingly. It is guaranteed that there are at least two cubes of different colors.
Output
Print the description of the Zebra Tower of the maximum height in the following form. In the first line print the tower's height, in the second line print the number of cubes that form the tower, and in the third line print the space-separated indices of cubes in the order in which they follow in the tower from the bottom to the top. Assume that the cubes are numbered from 1 to n in the order in which they were given in the input.
If there are several existing Zebra Towers with maximum heights, it is allowed to print any of them.
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
4
1 2
1 3
2 4
3 3
Output
9
3
2 3 1
Input
2
1 1
2 1
Output
2
2
2 1
### Response
```cpp
#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:64000000")
using namespace std;
const long long inf = (long long)1e17;
long long ans = 0, c1 = 0, c2 = 0, cnt1 = 0, cnt2 = 0;
long long b[100005][2][2] = {}, mx, n, cnt;
long long max(long long a, long long b) {
if (a > b) return a;
return b;
}
void f(long long c, long long cnt) {
long long cu = b[cnt][c][0], cc = b[cnt][c][1];
if (b[cnt][c ^ 1][1] != cc) {
if (ans < cu + b[cnt][c ^ 1][0]) {
ans = cu + b[cnt][c ^ 1][0];
cnt1 = cnt2 = cnt;
c1 = c;
c2 = c ^ 1;
}
}
if (cnt > 1) {
if (b[cnt - 1][c][1] != cc) {
if (b[cnt - 1][c][0] + cu > ans) {
ans = b[cnt - 1][c][0] + cu;
cnt1 = cnt;
cnt2 = cnt - 1;
c1 = c2 = c;
}
}
if (b[cnt - 1][c ^ 1][1] != cc) {
if (b[cnt - 1][c ^ 1][0] + cu > ans) {
ans = b[cnt - 1][c ^ 1][0] + cu;
cnt1 = cnt;
cnt2 = cnt - 1;
c1 = c;
c2 = c ^ 1;
}
}
}
if (b[cnt + 1][c][1] != cc) {
if (b[cnt + 1][c][0] + cu > ans) {
ans = b[cnt + 1][c][0] + cu;
cnt1 = cnt;
cnt2 = cnt + 1;
c1 = c2 = c;
}
}
if (b[cnt + 1][c ^ 1][1] != cc) {
if (b[cnt + 1][c ^ 1][0] + cu > ans) {
ans = b[cnt + 1][c ^ 1][0] + cu;
cnt1 = cnt;
cnt2 = cnt + 1;
c1 = c;
c2 = c ^ 1;
}
}
}
struct cube {
long long c, w, num;
};
struct cmp {
bool operator()(const cube& a, const cube& b) {
return (a.c < b.c || (a.c == b.c && a.w > b.w));
}
};
int main() {
cin >> n;
for (int i = 0; i < 100005; ++i)
for (int j = 0; j < 2; ++j)
for (int k = 0; k < 2; ++k) b[i][j][k] = -inf;
vector<cube> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i].c >> a[i].w;
a[i].num = i;
}
sort(a.begin(), a.end(), cmp());
for (int i = 0, j; i < n; ++i) {
for (j = i; j < n && a[j].c == a[i].c; ++j)
;
mx = 0, cnt = 0;
for (int k = i; k < j; ++k) {
mx += a[k].w;
++cnt;
if (mx >= b[cnt][0][0]) {
b[cnt][1][0] = b[cnt][0][0];
b[cnt][1][1] = b[cnt][0][1];
b[cnt][0][0] = mx;
b[cnt][0][1] = a[i].c;
} else if (mx > b[cnt][1][0]) {
b[cnt][1][0] = mx;
b[cnt][1][1] = a[i].c;
}
}
i = j - 1;
}
for (int i = 1; i <= n; ++i) {
f(0, i);
f(1, i);
}
cout << ans << '\n' << cnt1 + cnt2 << '\n';
vector<int> help1, help2;
for (int i = 0; i < n; ++i)
if (a[i].c == b[cnt1][c1][1] && cnt1 > help1.size())
help1.push_back(a[i].num);
for (int i = 0; i < n; ++i)
if (a[i].c == b[cnt2][c2][1] && cnt2 > help2.size())
help2.push_back(a[i].num);
if (cnt2 > cnt1) swap(help1, help2);
while (help2.size() != 0) {
cout << help1.back() + 1 << ' ' << help2.back() + 1 << ' ';
help1.pop_back();
help2.pop_back();
}
if (help1.size() != 0)
cout << help1.back() + 1 << '\n';
else
cout << '\n';
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Theseus has just arrived to Crete to fight Minotaur. He found a labyrinth that has a form of a rectangular field of size n Γ m and consists of blocks of size 1 Γ 1.
Each block of the labyrinth has a button that rotates all blocks 90 degrees clockwise. Each block rotates around its center and doesn't change its position in the labyrinth. Also, each block has some number of doors (possibly none). In one minute, Theseus can either push the button in order to rotate all the blocks 90 degrees clockwise or pass to the neighbouring block. Theseus can go from block A to some neighbouring block B only if block A has a door that leads to block B and block B has a door that leads to block A.
Theseus found an entrance to labyrinth and is now located in block (xT, yT) β the block in the row xT and column yT. Theseus know that the Minotaur is hiding in block (xM, yM) and wants to know the minimum number of minutes required to get there.
Theseus is a hero, not a programmer, so he asks you to help him.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 1000) β the number of rows and the number of columns in labyrinth, respectively.
Each of the following n lines contains m characters, describing the blocks of the labyrinth. The possible characters are:
* Β«+Β» means this block has 4 doors (one door to each neighbouring block);
* Β«-Β» means this block has 2 doors β to the left and to the right neighbours;
* Β«|Β» means this block has 2 doors β to the top and to the bottom neighbours;
* Β«^Β» means this block has 1 door β to the top neighbour;
* Β«>Β» means this block has 1 door β to the right neighbour;
* Β«<Β» means this block has 1 door β to the left neighbour;
* Β«vΒ» means this block has 1 door β to the bottom neighbour;
* Β«LΒ» means this block has 3 doors β to all neighbours except left one;
* Β«RΒ» means this block has 3 doors β to all neighbours except right one;
* Β«UΒ» means this block has 3 doors β to all neighbours except top one;
* Β«DΒ» means this block has 3 doors β to all neighbours except bottom one;
* Β«*Β» means this block is a wall and has no doors.
Left, right, top and bottom are defined from representing labyrinth as a table, where rows are numbered from 1 to n from top to bottom and columns are numbered from 1 to m from left to right.
Next line contains two integers β coordinates of the block (xT, yT) (1 β€ xT β€ n, 1 β€ yT β€ m), where Theseus is initially located.
Last line contains two integers β coordinates of the block (xM, yM) (1 β€ xM β€ n, 1 β€ yM β€ m), where Minotaur hides.
It's guaranteed that both the block where Theseus starts and the block where Minotaur is hiding have at least one door. Theseus and Minotaur may be initially located at the same block.
Output
If Theseus is not able to get to Minotaur, then print -1 in the only line of the output. Otherwise, print the minimum number of minutes required to get to the block where Minotaur is hiding.
Examples
Input
2 2
+*
*U
1 1
2 2
Output
-1
Input
2 3
<><
><>
1 1
2 1
Output
4
Note
Assume that Theseus starts at the block (xT, yT) at the moment 0.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int ps, n, m, a[4000005], nm, nm2, nm3, s, xt, yt, xm, ym, q[4000005],
ans = 1000000007;
vector<int> v[4000005];
void addup(int x, int y, int s) {
if (x > 1) v[s].push_back(s - m);
if (y < m) v[s + nm].push_back(s + nm + 1);
if (x < n) v[s + nm2].push_back(s + nm2 + m);
if (y > 1) v[s + nm3].push_back(s + nm3 - 1);
}
void addright(int x, int y, int s) {
if (x > 1) v[s + nm3].push_back(s + nm3 - m);
if (y < m) v[s].push_back(s + 1);
if (x < n) v[s + nm].push_back(s + nm + m);
if (y > 1) v[s + nm2].push_back(s + nm2 - 1);
}
void adddown(int x, int y, int s) {
if (x > 1) v[s + nm2].push_back(s + nm2 - m);
if (y < m) v[s + nm3].push_back(s + nm3 + 1);
if (x < n) v[s].push_back(s + m);
if (y > 1) v[s + nm].push_back(s + nm - 1);
}
void addleft(int x, int y, int s) {
if (x > 1) v[s + nm].push_back(s + nm - m);
if (y < m) v[s + nm2].push_back(s + nm2 + 1);
if (x < n) v[s + nm3].push_back(s + nm3 + m);
if (y > 1) v[s].push_back(s - 1);
}
int main() {
scanf("%d%d", &n, &m);
nm = n * m, nm2 = nm << 1, nm3 = nm2 + nm;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
s++;
char c;
scanf(" %c", &c);
v[s].push_back(s + nm);
v[s + nm].push_back(s + nm2);
v[s + nm2].push_back(s + nm3);
v[s + nm3].push_back(s);
if (c == '*') continue;
if (c == '+' || c == '|' || c == '^' || c == 'L' || c == 'R' || c == 'D')
addup(i, j, s);
if (c == '+' || c == '-' || c == '>' || c == 'L' || c == 'U' || c == 'D')
addright(i, j, s);
if (c == '+' || c == '|' || c == 'v' || c == 'L' || c == 'R' || c == 'U')
adddown(i, j, s);
if (c == '+' || c == '-' || c == '<' || c == 'U' || c == 'R' || c == 'D')
addleft(i, j, s);
}
}
scanf("%d%d%d%d", &xt, &yt, &xm, &ym);
int start = (xt - 1) * m + yt, end = (xm - 1) * m + ym, qs = 1, qe = 0;
a[start] = 1, q[1] = start;
while (qs != qe) {
int o = q[++qe], z = a[o] + 1;
if (o % nm == end) break;
for (int i = 0; i < v[o].size(); i++) {
if (!a[v[o][i]]) {
bool b = (v[o][i] == o + nm) || (v[o][i] + nm3 == o);
for (int j = 0; j < v[v[o][i]].size(); j++)
if (v[v[o][i]][j] == o) b = 1;
if (b) a[v[o][i]] = z, q[++qs] = v[o][i];
}
}
}
if (a[end]) ans = min(ans, a[end]);
if (a[end + nm]) ans = min(ans, a[end + nm]);
if (a[end + nm2]) ans = min(ans, a[end + nm2]);
if (a[end + nm3]) ans = min(ans, a[end + nm3]);
if (ans == 1000000007) ans = 0;
ans--;
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Ahmed and Mostafa used to compete together in many programming contests for several years. Their coach Fegla asked them to solve one challenging problem, of course Ahmed was able to solve it but Mostafa couldn't.
This problem is similar to a standard problem but it has a different format and constraints.
In the standard problem you are given an array of integers, and you have to find one or more consecutive elements in this array where their sum is the maximum possible sum.
But in this problem you are given n small arrays, and you will create one big array from the concatenation of one or more instances of the small arrays (each small array could occur more than once). The big array will be given as an array of indexes (1-based) of the small arrays, and the concatenation should be done in the same order as in this array. Then you should apply the standard problem mentioned above on the resulting big array.
For example let's suppose that the small arrays are {1, 6, -2}, {3, 3} and {-5, 1}. And the indexes in the big array are {2, 3, 1, 3}. So the actual values in the big array after formatting it as concatenation of the small arrays will be {3, 3, -5, 1, 1, 6, -2, -5, 1}. In this example the maximum sum is 9.
Can you help Mostafa solve this problem?
Input
The first line contains two integers n and m, n is the number of the small arrays (1 β€ n β€ 50), and m is the number of indexes in the big array (1 β€ m β€ 250000). Then follow n lines, the i-th line starts with one integer l which is the size of the i-th array (1 β€ l β€ 5000), followed by l integers each one will be greater than or equal -1000 and less than or equal 1000. The last line contains m integers which are the indexes in the big array, and you should concatenate the small arrays in the same order, and each index will be greater than or equal to 1 and less than or equal to n.
The small arrays are numbered from 1 to n in the same order as given in the input. Some of the given small arrays may not be used in big array.
Note, that the array is very big. So if you try to build it straightforwardly, you will probably get time or/and memory limit exceeded.
Output
Print one line containing the maximum sum in the big array after formatting it as described above. You must choose at least one element for the sum, i. e. it cannot be empty.
Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d).
Examples
Input
3 4
3 1 6 -2
2 3 3
2 -5 1
2 3 1 3
Output
9
Input
6 1
4 0 8 -3 -10
8 3 -2 -5 10 8 -9 -5 -4
1 0
1 -3
3 -8 5 6
2 9 6
1
Output
8
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n, m, l, ans, c, cc, mx, a[55][5005], b[250005], best_prefix[55],
best_suffix[55], best_mid[55], sum[55], mem[250005][3];
bool flag;
long long solve(long long p = 0, bool token = 0) {
if (p == m) return -1e18;
if (mem[p][token] > -1e18) return mem[p][token];
if (token)
mem[p][token] = max(best_prefix[b[p]], sum[b[p]] + solve(p + 1, 1));
else
mem[p][token] =
max(best_mid[b[p]],
max(solve(p + 1, 0), best_suffix[b[p]] + solve(p + 1, 1)));
return mem[p][token];
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m;
for (long long i = 0; i < n; i++) {
cin >> l;
c = cc = 0;
flag = 0;
mx = -1e18;
for (long long j = 0; j < l; j++) {
cin >> a[i][j];
mx = max(mx, a[i][j]);
c += a[i][j];
if (c > -1)
flag = 1;
else
c = 0;
cc = max(cc, c);
}
if (!flag) cc = mx;
best_mid[i] = cc;
c = 0;
best_prefix[i] = 0;
flag = 0;
for (long long j = 0; j < l; j++) {
c += a[i][j];
if (c >= best_prefix[i]) {
best_prefix[i] = c;
flag = 1;
}
}
sum[i] = c;
if (!flag) best_prefix[i] = -1e14;
c = 0;
best_suffix[i] = 0;
flag = 0;
for (long long j = l - 1; ~j; j--) {
c += a[i][j];
if (c >= best_suffix[i]) {
best_suffix[i] = c;
flag = 1;
}
}
if (!flag) best_suffix[i] = -1e14;
}
for (long long i = 0; i < m; i++) {
cin >> b[i];
b[i]--;
}
for (long long i = 0; i < 250005; i++)
for (long long j = 0; j < 3; j++) mem[i][j] = -1e18;
cout << solve();
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
There are N rabbits on a number line. The rabbits are conveniently numbered 1 through N. The coordinate of the initial position of rabbit i is x_i.
The rabbits will now take exercise on the number line, by performing sets described below. A set consists of M jumps. The j-th jump of a set is performed by rabbit a_j (2β€a_jβ€N-1). For this jump, either rabbit a_j-1 or rabbit a_j+1 is chosen with equal probability (let the chosen rabbit be rabbit x), then rabbit a_j will jump to the symmetric point of its current position with respect to rabbit x.
The rabbits will perform K sets in succession. For each rabbit, find the expected value of the coordinate of its eventual position after K sets are performed.
Constraints
* 3β€Nβ€10^5
* x_i is an integer.
* |x_i|β€10^9
* 1β€Mβ€10^5
* 2β€a_jβ€N-1
* 1β€Kβ€10^{18}
Input
The input is given from Standard Input in the following format:
N
x_1 x_2 ... x_N
M K
a_1 a_2 ... a_M
Output
Print N lines. The i-th line should contain the expected value of the coordinate of the eventual position of rabbit i after K sets are performed. The output is considered correct if the absolute or relative error is at most 10^{-9}.
Examples
Input
3
-1 0 2
1 1
2
Output
-1.0
1.0
2.0
Input
3
1 -1 1
2 2
2 2
Output
1.0
-1.0
1.0
Input
5
0 1 3 6 10
3 10
2 3 4
Output
0.0
3.0
7.0
8.0
10.0
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int N,M;long long K;
long long X[100005],D[100005];
int P[61][100005];
int ans[100005];
int main(){
scanf("%d",&N);
for(int i=1;i<=N;i++) scanf("%lld",&X[i]),D[i]=X[i]-X[i-1],P[0][i]=i;
scanf("%d%lld",&M,&K);
while(M--){
int x;scanf("%d",&x);
swap(P[0][x],P[0][x+1]);
}
for(int i=1;i<=60;i++)
for(int j=1;j<=N;j++)
P[i][j]=P[i-1][P[i-1][j]];
for(int j=1;j<=N;j++) ans[j]=j;
for(int i=60;~i;i--)if((K>>i)&1)
for(int j=1;j<=N;j++)
ans[j]=P[i][ans[j]];
for(int i=1;i<=N;i++) printf("%lld\n",X[i]=X[i-1]+D[ans[i]]);
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
You came to a local shop and want to buy some chocolate bars. There are n bars in the shop, i-th of them costs a_i coins (and you want to buy all of them).
You have m different coupons that allow you to buy chocolate bars. i-th coupon allows you to buy q_i chocolate bars while you have to pay only for the q_i - 1 most expensive ones (so, the cheapest bar of those q_i bars is for free).
You can use only one coupon; if you use coupon i, you have to choose q_i bars and buy them using the coupon, and buy all the remaining n - q_i bars without any discounts.
To decide which coupon to choose, you want to know what will be the minimum total amount of money you have to pay if you use one of the coupons optimally.
Input
The first line contains one integer n (2 β€ n β€ 3 β
10^5) β the number of chocolate bars in the shop.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the cost of i-th chocolate bar.
The third line contains one integer m (1 β€ m β€ n - 1) β the number of coupons you have.
The fourth line contains m integers q_1, q_2, ..., q_m (2 β€ q_i β€ n), where q_i is the number of chocolate bars you have to buy using i-th coupon so that the least expensive of them will be for free. All values of q_i are pairwise distinct.
Output
Print m integers, i-th of them should be the minimum amount of money you have to pay if you buy q_i bars with i-th coupon, and all the remaining bars one by one for their full price.
Example
Input
7
7 1 3 1 4 10 8
2
3 4
Output
27
30
Note
Consider the first example.
If we use the first coupon, we may choose chocolate bars having indices 1, 6 and 7, and we pay 18 coins for them and 9 coins for all other bars.
If we use the second coupon, we may choose chocolate bars having indices 1, 5, 6 and 7, and we pay 25 coins for them and 5 coins for all other bars.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m, a[300005];
cin >> n;
long long s = 0;
for (int i = 0; i < n; i++) {
cin >> a[i];
s += a[i];
}
sort(a, a + n);
reverse(a, a + n);
cin >> m;
for (int i = 0; i < m; i++) {
int r;
cin >> r;
cout << s - a[r - 1] << endl;
}
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
What are you doing at the end of the world? Are you busy? Will you save us?
<image>
Nephren is playing a game with little leprechauns.
She gives them an infinite array of strings, f0... β.
f0 is "What are you doing at the end of the world? Are you busy? Will you save us?".
She wants to let more people know about it, so she defines fi = "What are you doing while sending "fi - 1"? Are you busy? Will you send "fi - 1"?" for all i β₯ 1.
For example, f1 is
"What are you doing while sending "What are you doing at the end of the world? Are you busy? Will you save us?"? Are you busy? Will you send "What are you doing at the end of the world? Are you busy? Will you save us?"?". Note that the quotes in the very beginning and in the very end are for clarity and are not a part of f1.
It can be seen that the characters in fi are letters, question marks, (possibly) quotation marks and spaces.
Nephren will ask the little leprechauns q times. Each time she will let them find the k-th character of fn. The characters are indexed starting from 1. If fn consists of less than k characters, output '.' (without quotes).
Can you answer her queries?
Input
The first line contains one integer q (1 β€ q β€ 10) β the number of Nephren's questions.
Each of the next q lines describes Nephren's question and contains two integers n and k (0 β€ n β€ 105, 1 β€ k β€ 1018).
Output
One line containing q characters. The i-th character in it should be the answer for the i-th query.
Examples
Input
3
1 1
1 2
1 111111111111
Output
Wh.
Input
5
0 69
1 194
1 139
0 47
1 66
Output
abdef
Input
10
4 1825
3 75
3 530
4 1829
4 1651
3 187
4 584
4 255
4 774
2 474
Output
Areyoubusy
Note
For the first two examples, refer to f0 and f1 given in the legend.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long numc[100001];
string s1 =
"What are you doing at the end of the world? Are you busy? Will you save "
"us?";
string s2 =
"What are you doing while sending \"\"? Are you busy? Will you send \"\"?";
string s3 = "What are you doing while sending \"";
string s4 = "\"? Are you busy? Will you send \"";
string s5 = "\"?";
int main() {
long long q, n, k;
long long i;
numc[0] = s1.length();
for (i = 1; i <= 54; i++) {
numc[i] = 2 * numc[i - 1] + s2.length();
}
for (i = 55; i <= 100000; i++) numc[i] = numc[54];
cin >> q;
for (i = 1; i <= q; i++) {
cin >> n >> k;
if (n == 0 && k <= numc[0]) {
cout << s1[k - 1];
continue;
}
if (k > numc[n]) {
cout << ".";
continue;
}
long long level = n;
while (1 == 1) {
if (level == 0) {
cout << s1[k - 1];
break;
}
if (k <= s3.length()) {
cout << s3[k - 1];
break;
}
if (k > s3.length() + numc[level - 1] &&
k <= s4.length() + s3.length() + numc[level - 1]) {
cout << s4[k - 1 - s3.length() - numc[level - 1]];
break;
}
if (k > s4.length() + s3.length() + numc[level - 1] + numc[level - 1]) {
cout << s5[k - 1 - 2 * numc[level - 1] - s3.length() - s4.length()];
break;
}
if (k <= numc[level - 1] + s3.length())
k -= s3.length();
else
k -= (s3.length() + s4.length() + numc[level - 1]);
level--;
}
}
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
Oleg the bank client solves an interesting chess problem: place on n Γ n chessboard the maximum number of rooks so that they don't beat each other. Of course, no two rooks can share the same cell.
Remind that a rook standing in the cell (a, b) beats a rook standing in the cell (x, y) if and only if a = x or b = y.
Unfortunately (of fortunately?) for Oleg the answer in this problem was always n, so the task bored Oleg soon. He decided to make it more difficult by removing some cells from the board. If a cell is deleted, Oleg can't put a rook there, but rooks do beat each other "through" deleted cells.
Oleg deletes the cells in groups, namely, he repeatedly choose a rectangle with sides parallel to the board sides and deletes all the cells inside the rectangle. Formally, if he chooses a rectangle, lower left cell of which has coordinates (x1, y1), and upper right cell of which has coordinates (x2, y2), then he deletes all such cells with coordinates (x, y) that x1 β€ x β€ x2 and y1 β€ y β€ y2. It is guaranteed that no cell is deleted twice, i.e. the chosen rectangles do not intersect.
This version of the problem Oleg can't solve, and his friend Igor is busy at a conference, so he can't help Oleg.
You are the last hope for Oleg! Help him: given the size of the board and the deleted rectangles find the maximum possible number of rooks that could be placed on the board so that no two rooks beat each other.
Input
The first line contains single integer n (1 β€ n β€ 10000) β the size of the board.
The second line contains single integer q (0 β€ q β€ 10000) β the number of deleted rectangles.
The next q lines contain the information about the deleted rectangles.
Each of these lines contains four integers x1, y1, x2 and y2 (1 β€ x1 β€ x2 β€ n, 1 β€ y1 β€ y2 β€ n) β the coordinates of the lower left and the upper right cells of a deleted rectangle.
If is guaranteed that the rectangles do not intersect.
Output
In the only line print the maximum number of rooks Oleg can place on the board so that no two rooks beat each other.
Examples
Input
5
5
1 1 2 1
1 3 1 5
4 1 5 5
2 5 2 5
3 2 3 5
Output
3
Input
8
4
2 2 4 6
1 8 1 8
7 1 8 2
5 4 6 8
Output
8
Note
Here is the board and the example of rooks placement in the first example:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline bool chkmin(T &a, const T &b) {
return a > b ? a = b, 1 : 0;
}
template <typename T>
inline bool chkmax(T &a, const T &b) {
return a < b ? a = b, 1 : 0;
}
const int oo = 0x3f3f3f3f;
namespace network_flow {
const int max0 = 3000000, max1 = 10000000;
struct edge {
int id, g, nxt;
edge() {}
edge(int _id, int _g, int _nxt) : id(_id), g(_g), nxt(_nxt) {}
};
int st[max0 + 5], en = 0;
edge e[max1 + 5];
inline void add_edge(int first, int second, int z) {
e[en] = edge(second, z, st[first]), st[first] = en++;
}
inline void add_biedge(int first, int second, int z) {
add_edge(first, second, z), add_edge(second, first, 0);
}
int S, T, N;
int dis[max0 + 5];
inline bool bfs() {
static int q[max0 + 5];
static bool vis[max0 + 5];
int head = 0, rear = 0;
memset(dis, -1, sizeof(dis[0]) * N);
memset(vis, 0, sizeof(vis[0]) * N);
vis[q[rear++] = S] = 1;
dis[S] = 0;
while (head != rear) {
int first = q[head++];
for (int i = st[first]; i != -1; i = e[i].nxt) {
if (!e[i].g) continue;
int second = e[i].id;
if (!vis[second]) {
dis[second] = dis[first] + 1;
if (second == T) return 1;
q[rear++] = second;
vis[second] = 1;
}
}
}
return 0;
}
int cur[max0 + 5];
inline int dfs(int first, int flow) {
if (first == T) return flow;
int res = flow;
for (int &i = cur[first]; i != -1; i = e[i].nxt) {
if (!e[i].g) continue;
int second = e[i].id;
if (dis[second] == dis[first] + 1) {
int F = dfs(second, min(e[i].g, res));
res -= F;
e[i].g -= F;
e[i ^ 1].g += F;
if (res <= 0) return flow;
}
}
dis[first] = -1;
return flow - res;
}
inline int work() {
if (S == T) return oo;
int ret = 0;
for (; bfs();) {
for (int i = (0), i_end_ = (N); i < i_end_; ++i) cur[i] = st[i];
ret += dfs(S, oo);
}
return ret;
}
} // namespace network_flow
using network_flow::add_biedge;
using network_flow::add_edge;
using network_flow::en;
using network_flow::N;
using network_flow::S;
using network_flow::st;
using network_flow::T;
using network_flow::work;
const int maxn = 10100;
int n, qn;
struct node;
node *newnode();
node *copy(node *first);
struct node {
int id;
int link;
node *c[2];
bool has, con;
node() : has(0), con(0) { memset(c, 0, sizeof c); }
void update() {
has = con;
for (int i = (0), i_end_ = (2); i < i_end_; ++i)
if (c[i] && c[i]->has) has = 1;
}
void flag_label() {
if (!con) add_biedge(id, link, oo);
has = con = 1;
}
};
const int max0 = 100000;
node *nd_pool;
int nd_res = 0;
inline node *newnode() {
if (!nd_res) nd_pool = new node[max0], nd_res = max0;
node *ret = nd_pool + (--nd_res);
ret->id = N++;
return ret;
}
inline node *copy(node *first) {
node *tmp = newnode();
int tmpid = tmp->id;
*tmp = *first;
tmp->id = tmpid;
return tmp;
}
void build(node *&rt, int l, int r) {
if (!rt) {
rt = newnode();
rt->link = N++;
}
if (r - l <= 1) {
add_biedge(rt->link, T, 1);
return;
}
int mid = (l + r) >> 1;
build(rt->c[0], l, mid);
build(rt->c[1], mid, r);
for (int i = (0), i_end_ = (2); i < i_end_; ++i)
add_biedge(rt->link, rt->c[i]->link, oo);
}
int seg_x, seg_y, seg_ty;
void clear(node *&rt) {
if (!rt->has) return;
rt = copy(rt);
if (rt->con) rt->con = 0;
rt->update();
if (rt->has)
for (int i = (0), i_end_ = (2); i < i_end_; ++i)
if (rt->c[i]) clear(rt->c[i]);
rt->update();
for (int i = (0), i_end_ = (2); i < i_end_; ++i)
if (rt->c[i]) add_biedge(rt->id, rt->c[i]->id, oo);
}
void add(node *&rt, int l, int r) {
if (seg_x <= l && r <= seg_y) {
if (!seg_ty) {
clear(rt);
} else
rt = copy(rt), rt->flag_label();
return;
}
rt = copy(rt);
int mid = (l + r) >> 1;
if (rt->con) {
for (int i = (0), i_end_ = (2); i < i_end_; ++i)
if (rt->c[i]) {
rt->c[i] = copy(rt->c[i]);
rt->c[i]->flag_label();
}
rt->con = 0;
}
if (seg_x < mid) add(rt->c[0], l, mid);
if (seg_y > mid) add(rt->c[1], mid, r);
rt->update();
for (int i = (0), i_end_ = (2); i < i_end_; ++i)
if (rt->c[i]) add_biedge(rt->id, rt->c[i]->id, oo);
}
vector<pair<int, pair<int, int> > > all[maxn + 5];
node *rt;
int main() {
memset(st, -1, sizeof st);
S = N++, T = N++;
scanf("%d", &n);
scanf("%d", &qn);
build(rt, 0, n);
rt->flag_label();
for (int i = (0), i_end_ = (qn); i < i_end_; ++i) {
int ux, uy, vx, vy;
scanf("%d%d%d%d", &ux, &uy, &vx, &vy), --ux, --uy;
all[ux].push_back(make_pair(0, make_pair(uy, vy)));
all[vx].push_back(make_pair(1, make_pair(uy, vy)));
}
for (int i = (0), i_end_ = (n); i < i_end_; ++i) {
sort((all[i]).begin(), (all[i]).end());
reverse((all[i]).begin(), (all[i]).end());
for (auto u : all[i]) {
seg_x = u.second.first, seg_y = u.second.second, seg_ty = u.first;
add(rt, 0, n);
}
add_biedge(S, rt->id, 1);
}
printf("%d\n", work());
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Rick is in love with Unity. But Mr. Meeseeks also love Unity, so Rick and Mr. Meeseeks are "love rivals".
Unity loves rap, so it decided that they have to compete in a rap game (battle) in order to choose the best. Rick is too nerds, so instead he's gonna make his verse with running his original algorithm on lyrics "Rap God" song.
<image>
His algorithm is a little bit complicated. He's made a tree with n vertices numbered from 1 to n and there's a lowercase english letter written on each edge. He denotes str(a, b) to be the string made by writing characters on edges on the shortest path from a to b one by one (a string of length equal to distance of a to b). Note that str(a, b) is reverse of str(b, a) and str(a, a) is empty.
In order to make the best verse he can, he needs to answer some queries, but he's not a computer scientist and is not able to answer those queries, so he asked you to help him. Each query is characterized by two vertices x and y (x β y). Answer to this query is the number of vertices like z such that z β x, z β y and str(x, y) is lexicographically larger than str(x, z).
String x = x1x2...x|x| is lexicographically larger than string y = y1y2...y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ..., x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ..., xr = yr and xr + 1 > yr + 1. Characters are compared like their ASCII codes (or alphabetic order).
Help Rick get the girl (or whatever gender Unity has).
Input
The first line of input contain two integers n and q (2 β€ n β€ 20000, 1 β€ q β€ 20000) β number of vertices in tree and number of queries respectively.
The next n - 1 lines contain the edges. Each line contains two integers v and u (endpoints of the edge) followed by an English lowercase letter c (1 β€ v, u β€ n, v β u).
The next q line contain the queries. Each line contains two integers x and y (1 β€ x, y β€ n, x β y).
Output
Print the answer for each query in one line.
Examples
Input
4 3
4 1 t
3 2 p
1 2 s
3 2
1 3
2 1
Output
0
1
1
Input
8 4
4 6 p
3 7 o
7 8 p
4 5 d
1 3 o
4 3 p
3 2 e
8 6
3 7
8 1
4 3
Output
6
1
3
1
Note
Here's the tree of first sample testcase:
<image>
Here's the tree of second sample testcase:
<image>
In this test:
* str(8, 1) = poo
* str(8, 2) = poe
* str(8, 3) = po
* str(8, 4) = pop
* str(8, 5) = popd
* str(8, 6) = popp
* str(8, 7) = p
So, for the first query, <image> and for the third query <image> is the answer.
### Response
```cpp
#include <bits/stdc++.h>
const int N = 20054, M = N * 2;
struct edge {
int u, v;
char w;
edge(int u0 = 0, int v0 = 0, char w0 = 0) : u(u0), v(v0), w(w0) {}
} e[M];
int n, q, E = 0;
int first[N], next[M];
int p[N], dep[N], status[N];
int cnt = 0, o[N];
int stamp = 0, tag[N], L[N];
char s[M], pst[N];
inline int cmp(const char x, const char y) { return x < y ? -1 : x > y; }
inline void addedge(int u, int v, char w) {
e[++E] = edge(u, v, w), next[E] = first[u], first[u] = E;
e[++E] = edge(v, u, w), next[E] = first[v], first[v] = E;
}
void dfs(int x) {
int i, y;
o[++cnt] = x;
for (i = first[x]; i; i = next[i])
if ((y = e[i].v) != p[x])
p[y] = x, pst[y] = e[i].w, dep[y] = dep[x] + 1, dfs(y);
}
int genstr(int x, int y) {
char *_beg = s, *_end = s + M;
for (; x != y; dep[x] < dep[y] ? (*--_end = pst[y], y = p[y])
: (*_beg++ = pst[x], x = p[x]))
;
return memcpy(_beg, _end, s + M - _end), M - (_end - _beg);
}
int main() {
int i, u, v, x, l;
char w[3];
scanf("%d%d", &n, &q);
for (i = 1; i < n; ++i) scanf("%d%d%s", &u, &v, w), addedge(u, v, *w);
for (dfs(1); q; --q) {
scanf("%d%d", &u, &v), l = genstr(u, v), --s[l - 1], s[l] = 127;
status[u] = L[u] = 0, tag[u] = ++stamp;
for (x = u; p[x]; x = p[x])
tag[p[x]] = stamp, L[p[x]] = L[x] + 1,
status[p[x]] = (status[x] ? status[x] : cmp(pst[x], s[L[x]]));
for (i = 2; i <= n; ++i)
if (tag[x = o[i]] != stamp)
L[x] = L[p[x]] + 1,
status[x] = (status[p[x]] ? status[p[x]] : cmp(pst[x], s[L[p[x]]]));
printf("%d\n", int(n - 1 - std::count(status + 1, status + (n + 1), 1)));
}
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalizationΒ» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
Input
The first line contains an integer n (1 β€ n β€ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
Output
Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.
Examples
Input
4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis
Output
word
l10n
i18n
p43s
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
string tmp;
cin >> n;
while (n--) {
cin >> tmp;
if (tmp.length() <= 10)
cout << tmp << endl;
else {
cout << tmp[0] << tmp.length() - 2 << tmp[tmp.length() - 1] << endl;
}
}
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3.
m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj.
A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served.
You are to compute the prices each buyer will pay for t-shirts.
Input
The first line contains single integer n (1 β€ n β€ 200 000) β the number of t-shirts.
The following line contains sequence of integers p1, p2, ..., pn (1 β€ pi β€ 1 000 000 000), where pi equals to the price of the i-th t-shirt.
The following line contains sequence of integers a1, a2, ..., an (1 β€ ai β€ 3), where ai equals to the front color of the i-th t-shirt.
The following line contains sequence of integers b1, b2, ..., bn (1 β€ bi β€ 3), where bi equals to the back color of the i-th t-shirt.
The next line contains single integer m (1 β€ m β€ 200 000) β the number of buyers.
The following line contains sequence c1, c2, ..., cm (1 β€ cj β€ 3), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served.
Output
Print to the first line m integers β the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1.
Examples
Input
5
300 200 400 500 911
1 2 1 2 3
2 1 3 2 1
6
2 3 1 2 1 1
Output
200 400 300 500 911 -1
Input
2
1000000000 1
1 1
1 2
2
2 1
Output
1 1000000000
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long N = 2e5 + 5;
long long t, n, m, x, ans[N], p[N];
vector<pair<long long, long long> > v1, v2, v3;
bool f[N];
int main() {
t = 1;
while (t--) {
scanf("%lld", &n);
for (long long i = 0; i < n; i++) {
scanf("%lld", &x);
p[i] = x;
}
for (long long i = 0; i < n; i++) {
scanf("%lld", &x);
if (x == 1) v1.push_back({p[i], i});
if (x == 2) v2.push_back({p[i], i});
if (x == 3) v3.push_back({p[i], i});
}
for (long long i = 0; i < n; i++) {
scanf("%lld", &x);
if (x == 1) v1.push_back({p[i], i});
if (x == 2) v2.push_back({p[i], i});
if (x == 3) v3.push_back({p[i], i});
}
sort(v1.begin(), v1.end());
sort(v2.begin(), v2.end());
sort(v3.begin(), v3.end());
long long q = 0, i1 = 0, i2 = 0, i3 = 0;
scanf("%lld", &m);
while (m--) {
scanf("%lld", &x);
if (x == 1 && i1 < v1.size()) {
while (i1 < v1.size() && f[v1[i1].second]) i1++;
if (i1 < v1.size() && !f[v1[i1].second]) {
ans[q] = v1[i1].first;
f[v1[i1].second] = 1;
i1++;
} else
ans[q] = -1;
} else if (x == 2 && i2 < v2.size()) {
while (i2 < v2.size() && f[v2[i2].second]) i2++;
if (i2 < v2.size() && !f[v2[i2].second]) {
ans[q] = v2[i2].first;
f[v2[i2].second] = 1;
i2++;
} else
ans[q] = -1;
} else if (x == 3 && i3 < v3.size()) {
while (i3 < v3.size() && f[v3[i3].second]) i3++;
if (i3 < v3.size() && !f[v3[i3].second]) {
ans[q] = v3[i3].first;
f[v3[i3].second] = 1;
i3++;
} else
ans[q] = -1;
} else
ans[q] = -1;
q++;
}
for (long long i = 0; i < q; i++) {
printf("%d ", ans[i]);
}
puts("");
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
A 3Γ3 grid with a integer written in each square, is called a magic square if and only if the integers in each row, the integers in each column, and the integers in each diagonal (from the top left corner to the bottom right corner, and from the top right corner to the bottom left corner), all add up to the same sum.
You are given the integers written in the following three squares in a magic square:
* The integer A at the upper row and left column
* The integer B at the upper row and middle column
* The integer C at the middle row and middle column
Determine the integers written in the remaining squares in the magic square.
It can be shown that there exists a unique magic square consistent with the given information.
Constraints
* 0 \leq A, B, C \leq 100
Input
The input is given from Standard Input in the following format:
A
B
C
Output
Output the integers written in the magic square, in the following format:
X_{1,1} X_{1,2} X_{1,3}
X_{2,1} X_{2,2} X_{2,3}
X_{3,1} X_{3,2} X_{3,3}
where X_{i,j} is the integer written in the square at the i-th row and j-th column.
Examples
Input
8
3
5
Output
8 3 4
1 5 9
6 7 2
Input
1
1
1
Output
1 1 1
1 1 1
1 1 1
### Response
```cpp
#include<iostream>
using namespace std ;
int main()
{
int a,b,c;
cin>>a>>b>>c;
cout<<a<<" "<<b<<" "<<3*c-a-b<<" "<<endl;
cout<<4*c-2*a-b<<" "<<c<<" "<<2*a+b-2*c<<" "<<endl;
cout<<a+b-c<<" "<<2*c-b<<" "<<2*c-a<<" "<<endl;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Ralph has a magic field which is divided into n Γ m blocks. That is to say, there are n rows and m columns on the field. Ralph can put an integer in each block. However, the magic field doesn't always work properly. It works only if the product of integers in each row and each column equals to k, where k is either 1 or -1.
Now Ralph wants you to figure out the number of ways to put numbers in each block in such a way that the magic field works properly. Two ways are considered different if and only if there exists at least one block where the numbers in the first way and in the second way are different. You are asked to output the answer modulo 1000000007 = 109 + 7.
Note that there is no range of the numbers to put in the blocks, but we can prove that the answer is not infinity.
Input
The only line contains three integers n, m and k (1 β€ n, m β€ 1018, k is either 1 or -1).
Output
Print a single number denoting the answer modulo 1000000007.
Examples
Input
1 1 -1
Output
1
Input
1 3 1
Output
1
Input
3 3 -1
Output
16
Note
In the first example the only way is to put -1 into the only block.
In the second example the only way is to put 1 into every block.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int k;
long long n, m, x, y;
const int MO = 1000000007;
long long powmod(long long n, long long m) {
if (m == 0) return 1;
if (m == 1)
return n % MO;
else
return ((powmod(n, m / 2) * powmod(n, m / 2)) % MO * powmod(n, m % 2)) % MO;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m >> k;
if (k == -1 && abs(n - m) % 2 == 1)
cout << 0;
else {
x = powmod(2, n - 1);
y = powmod(x, m - 1);
cout << y;
}
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Ann and Borya have n piles with candies and n is even number. There are ai candies in pile with number i.
Ann likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer. During one move guys can select some pile with candies and add one candy to it (this candy is new and doesn't belong to any other pile) or remove one candy (if there is at least one candy in this pile).
Find out minimal number of moves that is required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer.
Input
First line contains one even integer n (2 β€ n β€ 200 000) β number of piles with candies.
Second line contains sequence of integers a1, a2, ..., an (0 β€ ai β€ 109) β amounts of candies in each pile.
Output
Output minimal number of steps required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer. If condition is already satisfied output 0.
Examples
Input
4
12 14 30 4
Output
2
Input
6
0 0 0 0 0 0
Output
6
Input
6
120 110 23 34 25 45
Output
3
Input
10
121 56 78 81 45 100 1 0 54 78
Output
0
Note
In first example you can satisfy condition in two moves. During each move you should add one candy to second pile. After it size of second pile becomes 16. After that Borya and Ann will have two piles with number of candies which is a square of integer (second and fourth pile) and two piles with number of candies which is not a square of any integer (first and third pile).
In second example you should add two candies to any three piles.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n;
long long a[200001];
int main() {
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i];
priority_queue<long long, vector<long long>, greater<long long> > differences;
priority_queue<long long, vector<long long>, greater<long long> >
differences_2;
int square_counter = 0;
for (int i = 0; i < n; i++) {
long long number = a[i];
long long square_root = (long long)sqrt(number);
if (square_root * square_root == number) {
square_counter++;
differences_2.push(number == 0 ? 2 : 1);
} else {
differences.push(min(number - square_root * square_root,
(square_root + 1) * (square_root + 1) - number));
}
}
long long moves = 0;
while (square_counter < n / 2) {
square_counter++;
moves += differences.top();
differences.pop();
}
while (square_counter > n / 2) {
square_counter--;
moves += differences_2.top();
differences_2.pop();
}
cout << moves << endl;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
You are given two arithmetic progressions: a1k + b1 and a2l + b2. Find the number of integers x such that L β€ x β€ R and x = a1k' + b1 = a2l' + b2, for some integers k', l' β₯ 0.
Input
The only line contains six integers a1, b1, a2, b2, L, R (0 < a1, a2 β€ 2Β·109, - 2Β·109 β€ b1, b2, L, R β€ 2Β·109, L β€ R).
Output
Print the desired number of integers x.
Examples
Input
2 0 3 3 5 21
Output
3
Input
2 4 3 0 6 17
Output
2
### Response
```cpp
#include <bits/stdc++.h>
template <class T>
inline void chkmax(T &x, const T &y) {
if (x < y) x = y;
}
template <class T>
inline void chkmin(T &x, const T &y) {
if (y < x) x = y;
}
template <class T>
inline void read(T &x) {
char c;
int f = 1;
x = 0;
while (((c = getchar()) < '0' || c > '9') && c != '-')
;
if (c == '-')
f = -1;
else
x = c - '0';
while ((c = getchar()) >= '0' && c <= '9') x = x * 10 + c - '0';
x *= f;
}
long long extgcd(long long a, long long b, long long &x, long long &y) {
if (!b) {
x = 1, y = 0;
return a;
}
long long ret = extgcd(b, a % b, y, x);
y -= a / b * x;
return ret;
}
long long ceil(long long u, long long v) {
long long t = u / v;
if (t * v < u) ++t;
return t;
}
long long floor(long long u, long long v) {
long long t = u / v;
if (t * v > u) --t;
return t;
}
long long fmm(long long a, long long b, long long mod) {
long long ret = 0;
while (b) {
if (b & 1) (ret += a) %= mod;
(a += a) %= mod, b >>= 1;
}
return ret;
}
int main() {
long long a1, b1, a2, b2, L, R;
read(a1), read(b1), read(a2), read(b2), read(L), read(R);
if (b2 < b1) std::swap(a1, a2), std::swap(b1, b2);
long long x, y, gcd = extgcd(a1, a2, x, y);
if ((b2 - b1) % gcd)
puts("0");
else {
long long t = (b2 - b1) / gcd;
x *= t, y *= t;
long long u = a1 * a2 / gcd, v = fmm((x % u + u) % u, a1, u) + b1;
long long l = ceil(L - v, u), r = floor(R - v, u);
chkmax(l, std::max(ceil(b1 - v, u), ceil(b2 - v, u)));
if (l > r)
puts("0");
else
std::cout << r - l + 1 << std::endl;
}
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
A balancing network is an abstract device built up of N wires, thought of as running from left to right, and M balancers that connect pairs of wires. The wires are numbered from 1 to N from top to bottom, and the balancers are numbered from 1 to M from left to right. Balancer i connects wires x_i and y_i (x_i < y_i).
pic1-small-2acea94b.png
Each balancer must be in one of two states: up or down.
Consider a token that starts moving to the right along some wire at a point to the left of all balancers. During the process, the token passes through each balancer exactly once. Whenever the token encounters balancer i, the following happens:
* If the token is moving along wire x_i and balancer i is in the down state, the token moves down to wire y_i and continues moving to the right.
* If the token is moving along wire y_i and balancer i is in the up state, the token moves up to wire x_i and continues moving to the right.
* Otherwise, the token doesn't change the wire it's moving along.
Let a state of the balancing network be a string of length M, describing the states of all balancers. The i-th character is `^` if balancer i is in the up state, and `v` if balancer i is in the down state.
A state of the balancing network is called uniforming if a wire w exists such that, regardless of the starting wire, the token will always end up at wire w and run to infinity along it. Any other state is called non-uniforming.
You are given an integer T (1 \le T \le 2). Answer the following question:
* If T = 1, find any uniforming state of the network or determine that it doesn't exist.
* If T = 2, find any non-uniforming state of the network or determine that it doesn't exist.
Note that if you answer just one kind of questions correctly, you can get partial score.
Constraints
* 2 \leq N \leq 50000
* 1 \leq M \leq 100000
* 1 \leq T \leq 2
* 1 \leq x_i < y_i \leq N
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M T
x_1 y_1
x_2 y_2
:
x_M y_M
Output
Print any uniforming state of the given network if T = 1, or any non-uniforming state if T = 2. If the required state doesn't exist, output `-1`.
Examples
Input
4 5 1
1 3
2 4
1 2
3 4
2 3
Output
^^^^^
Input
4 5 2
1 3
2 4
1 2
3 4
2 3
Output
v^^^^
Input
3 1 1
1 2
Output
-1
Input
2 1 2
1 2
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
//#define cerr if (false) cerr
#define db(x) cerr << #x << "=" << x << endl
#define db2(x, y) cerr << #x << "=" << x << "," << #y << "=" << y << endl
#define db3(x, y, z) cerr << #x << "=" << x << "," << #y << "=" << y << "," << #z << "=" << z << endl
#define dbv(v) cerr << #v << "="; for (auto _x : v) cerr << _x << ", "; cerr << endl
#define dba(a, n) cerr << #a << "="; for (int _i = 0; _i < (n); ++_i) cerr << a[_i] << ", "; cerr << endl
template <typename A, typename B>
ostream& operator<<(ostream& os, const pair<A, B>& x) {
return os << "(" << x.first << "," << x.second << ")";
}
typedef long long ll;
typedef long double ld;
bitset<50001> B[50005];
int main() {
int n, m, t;
scanf("%d%d%d", &n, &m, &t);
vector<int> x(m), y(m);
for (int i = 0; i < m; ++i) scanf("%d%d", &x[i], &y[i]);
if (t == 2) {
if (n < 3) {
printf("-1\n");
return 0;
}
auto dir = [](int a, int b) {
return a > b ? '^' : 'v';
};
vector<pair<char, int>> p;
int a = 1, b = 2, c = 3;
int ab = -1, ac = -1;
for (int i = 0; i < m; ++i) {
if (y[i] == a) swap(x[i], y[i]);
if (x[i] == a && y[i] == b) {
p.emplace_back(dir(a, b), ac); // b-c
p.emplace_back(dir(b, a), ac); // a-c
swap(a, c);
} else if (x[i] == a && y[i] == c) {
p.emplace_back(dir(c, a), ab); // a-b
p.emplace_back(dir(a, c), ab); // c-b
swap(a, b);
} else {
// a-b
p.emplace_back((y[i] == a || y[i] == b) ? dir(x[i], y[i]) : dir(y[i], x[i]), ab);
// a-c
p.emplace_back((y[i] == a || y[i] == c) ? dir(x[i], y[i]) : dir(y[i], x[i]), ac);
}
ab = p.size() - 2;
ac = p.size() - 1;
}
string ans;
for (; ab != -1;) {
ans += p[ab].first;
ab = p[ab].second;
}
reverse(ans.begin(), ans.end());
printf("%s\n", ans.c_str());
return 0;
}
for (int i = 1; i <= n; ++i) B[i][i] = 1;
for (int i = m - 1; i >= 0; --i) {
B[x[i]] |= B[y[i]];
B[y[i]] = B[x[i]];
}
auto sum = B[1];
for (int i = 2; i <= n; ++i) {
sum &= B[i];
}
int take = -1;
for (int i = 1; i <= n; ++i) {
if (sum[i] == 1) {
take = i;
break;
}
}
if (take == -1) printf("-1\n");
else {
auto b = sum;
b.reset();
b[take] = 1;
string ans;
for (int i = m - 1; i >= 0; --i) {
if (b[x[i]] == 1) {
b[y[i]] = 1;
ans += '^';
} else if (b[y[i]] == 1) {
b[x[i]] = 1;
ans += 'v';
} else {
ans += '^';
}
}
reverse(ans.begin(), ans.end());
printf("%s\n", ans.c_str());
}
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads.
Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they canβt see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities.
Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>.
Input
The first line contains a single integer n (1 β€ n β€ 100000) β number of cities.
Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi) β the cities connected by the i-th road.
It is guaranteed that one can reach any city from any other by the roads.
Output
Print a number β the expected length of their journey. The journey starts in the city 1.
Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>.
Examples
Input
4
1 2
1 3
2 4
Output
1.500000000000000
Input
5
1 2
1 3
3 4
2 5
Output
2.000000000000000
Note
In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5.
In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100000;
int N;
double answer = 0;
vector<int> adjacency[MAXN];
void dfs(int current_node, int parent, double probability, int depth) {
int num_children = 0;
for (auto i : adjacency[current_node]) {
if (i != parent) {
num_children++;
}
}
for (auto i : adjacency[current_node]) {
if (i != parent) {
dfs(i, current_node, double(probability / num_children), depth + 1);
}
}
if (num_children == 0) {
answer += probability * depth;
}
}
int main() {
cin >> N;
for (int i = 0; i < N - 1; i++) {
int u, v;
cin >> u >> v;
u--;
v--;
adjacency[u].push_back(v);
adjacency[v].push_back(u);
}
dfs(0, 0, 1.0, 0);
cout << fixed << setprecision(7) << answer << endl;
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
There are n knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood.
Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes.
A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated.
On a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood.
<image>
King Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not.
Input
The first line contains number n, which is the number of knights at the round table (3 β€ n β€ 105). The second line contains space-separated moods of all the n knights in the order of passing them around the table. "1" means that the knight is in a good mood an "0" means that he is in a bad mood.
Output
Print "YES" without the quotes if the following month will turn out to be lucky. Otherwise, print "NO".
Examples
Input
3
1 1 1
Output
YES
Input
6
1 0 1 1 1 0
Output
YES
Input
6
1 0 0 1 0 1
Output
NO
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long const M = 1000000007;
double const pi = acos(-1);
long long const inf = 2e18;
long long const N = 200001;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long i, j, t, n, k;
cin >> n;
vector<long long> a(n);
bool ok = false;
for (i = 0; i < n; i++) cin >> a[i];
for (i = 2; i * i <= n; i++) {
if (n % i == 0) {
long long counter = n / i, mxi = 0;
vector<long long> dp(n, 0);
if (i != 2) {
for (j = 0; j < n; j++) {
if (a[j] == 1) {
dp[j] = 1;
if (j - counter >= 0) dp[j] += dp[j - counter];
}
mxi = max(mxi, dp[j]);
}
}
if (mxi >= i) ok = true;
counter = i, mxi = 0;
for (j = 0; j < n; j++) dp[i] = 0;
for (j = 0; j < n; j++) {
if (a[j] == 1) {
dp[j] = 1;
if (j - counter >= 0) dp[j] += dp[j - counter];
}
mxi = max(mxi, dp[j]);
}
if (mxi >= (n / i) && (n / i != 2)) ok = true;
}
if (ok) break;
}
long long cnt = 0;
for (i = 0; i < n; i++)
if (a[i] == 1) cnt++;
if (cnt == n) ok = true;
if (ok)
cout << "YES"
<< "\n";
else
cout << "NO"
<< "\n";
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
A non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, "abcba", "a", and "abba" are palindromes, while "abab" and "xy" are not.
A string is called a substring of another string, if it can be obtained from that string by dropping some (possibly zero) number of characters from the beginning and from the end of it. For example, "abc", "ab", and "c" are substrings of the string "abc", while "ac" and "d" are not.
Let's define a palindromic count of the string as the number of its substrings that are palindromes. For example, the palindromic count of the string "aaa" is 6 because all its substrings are palindromes, and the palindromic count of the string "abc" is 3 because only its substrings of length 1 are palindromes.
You are given a string s. You can arbitrarily rearrange its characters. You goal is to obtain a string with the maximum possible value of palindromic count.
Input
The first line contains an integer n (1 β€ n β€ 100 000) β the length of string s.
The second line contains string s that consists of exactly n lowercase characters of Latin alphabet.
Output
Print string t, which consists of the same set of characters (and each characters appears exactly the same number of times) as string s. Moreover, t should have the maximum possible value of palindromic count among all such strings strings.
If there are multiple such strings, print any of them.
Examples
Input
5
oolol
Output
ololo
Input
16
gagadbcgghhchbdf
Output
abccbaghghghgdfd
Note
In the first example, string "ololo" has 9 palindromic substrings: "o", "l", "o", "l", "o", "olo", "lol", "olo", "ololo". Note, that even though some substrings coincide, they are counted as many times as they appear in the resulting string.
In the second example, the palindromic count of string "abccbaghghghgdfd" is 29.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
string s;
cin >> n >> s;
sort(s.begin(), s.end());
cout << s << '\n';
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Sereja has two sequences a1, a2, ..., an and b1, b2, ..., bm, consisting of integers. One day Sereja got bored and he decided two play with them. The rules of the game was very simple. Sereja makes several moves, in one move he can perform one of the following actions:
1. Choose several (at least one) first elements of sequence a (non-empty prefix of a), choose several (at least one) first elements of sequence b (non-empty prefix of b); the element of sequence a with the maximum index among the chosen ones must be equal to the element of sequence b with the maximum index among the chosen ones; remove the chosen elements from the sequences.
2. Remove all elements of both sequences.
The first action is worth e energy units and adds one dollar to Sereja's electronic account. The second action is worth the number of energy units equal to the number of elements Sereja removed from the sequences before performing this action. After Sereja performed the second action, he gets all the money that he earned on his electronic account during the game.
Initially Sereja has s energy units and no money on his account. What maximum number of money can Sereja get? Note, the amount of Seraja's energy mustn't be negative at any time moment.
Input
The first line contains integers n, m, s, e (1 β€ n, m β€ 105; 1 β€ s β€ 3Β·105; 103 β€ e β€ 104). The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 105). The third line contains m integers b1, b2, ..., bm (1 β€ bi β€ 105).
Output
Print a single integer β maximum number of money in dollars that Sereja can get.
Examples
Input
5 5 100000 1000
1 2 3 4 5
3 2 4 5 1
Output
3
Input
3 4 3006 1000
1 2 3
1 2 4 3
Output
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int INF = 1000 * 1000 * 1000;
const int maxn = 1000 * 100 + 50;
int a[maxn], b[maxn], n, m, s, e, dp[maxn][300 + 20];
vector<int> v[maxn];
int main() {
cin >> n >> m >> s >> e;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = 0; i < m; i++) {
cin >> b[i];
v[b[i]].push_back(i);
}
for (int i = 0; i < maxn; i++) {
for (int j = 0; j < 310; j++) {
dp[i][j] = INF;
}
}
int ans = 0;
for (int i = 0; i < n; i++) {
dp[i][0] = 0;
for (int j = 1; j <= min(i + 1, 300); j++) {
int help = 0;
if (i > 0) {
dp[i][j] = dp[i - 1][j];
help = dp[i - 1][j - 1];
} else {
dp[i][j] = INF;
}
if (v[a[i]].size() == 0) {
continue;
}
int hh =
lower_bound(v[a[i]].begin(), v[a[i]].end(), help) - v[a[i]].begin();
if (hh == v[a[i]].size()) {
continue;
}
dp[i][j] = min(dp[i][j], v[a[i]][hh] + 1);
if (j * e + (i + 1 + dp[i][j]) <= s) {
ans = max(ans, j);
}
}
}
cout << ans;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
PMP is getting a warrior. He is practicing a lot, but the results are not acceptable yet. This time instead of programming contests, he decided to compete in a car racing to increase the spirit of victory. He decides to choose a competition that also exhibits algorithmic features.
AlgoRace is a special league of car racing where different teams compete in a country of n cities. Cities are numbered 1 through n. Every two distinct cities in the country are connected with one bidirectional road. Each competing team should introduce one driver and a set of cars.
The competition is held in r rounds. In i-th round, drivers will start at city si and finish at city ti. Drivers are allowed to change their cars at most ki times. Changing cars can take place in any city in no time. One car can be used multiple times in one round, but total number of changes should not exceed ki. Drivers can freely choose their path to destination.
PMP has prepared m type of purpose-built cars. Beside for PMPβs driving skills, depending on properties of the car and the road, a car traverses each road in each direction in different times.
PMP Warriors wants to devise best strategies of choosing car and roads in each round to maximize the chance of winning the cup. For each round they want to find the minimum time required to finish it.
Input
The first line contains three space-separated integers n, m, r (2 β€ n β€ 60, 1 β€ m β€ 60, 1 β€ r β€ 105) β the number of cities, the number of different types of cars and the number of rounds in the competition, correspondingly.
Next m sets of n Γ n matrices of integers between 0 to 106 (inclusive) will follow β describing the time one car requires to traverse different roads. The k-th integer in j-th line of the i-th set is the time that i-th car requires to traverse the road from j-th city to k-th city. These matrices are not necessarily symmetric, but their diagonal is always zero.
Next r lines contain description of the rounds. The i-th of these lines contains space-separated integers si, ti, ki (1 β€ si, ti β€ n, si β ti, 0 β€ ki β€ 1000) β the number of starting city, finishing city and the number of possible car changes in i-th round, correspondingly.
Output
For each round you should print the minimum required time to complete the round in a single line.
Examples
Input
4 2 3
0 1 5 6
2 0 3 6
1 3 0 1
6 6 7 0
0 3 5 6
2 0 1 6
1 3 0 2
6 6 7 0
1 4 2
1 4 1
1 4 3
Output
3
4
3
Input
4 2 3
0 7 3 3
8 0 10 5
1 1 0 4
8 9 2 0
0 3 3 9
7 0 4 9
3 8 0 4
4 8 9 0
2 3 3
2 1 3
1 2 2
Output
4
5
3
Note
In the first sample, in all rounds PMP goes from city #1 to city #2, then city #3 and finally city #4. But the sequences of types of the cars he uses are (1, 2, 1) in the first round and (1, 2, 2) in the second round. In the third round, although he can change his car three times, he uses the same strategy as the first round which only needs two car changes.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int inf = 1000000000;
int d[70][70][70];
int dp[70][70][1010];
int r, s, k, n, m, t;
void floyd(int x) {
for (int k = 1; k <= n; k++)
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
d[x][i][j] = min(d[x][i][j], d[x][i][k] + d[x][k][j]);
}
int main() {
scanf("%d%d%d", &n, &m, &r);
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
for (int w = 1; w <= n; w++) scanf("%d", &d[i][j][w]);
for (int i = 1; i <= m; i++) floyd(i);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
for (int w = 0; w <= 1000; w++) dp[i][j][w] = inf;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
for (int w = 1; w <= m; w++) dp[i][j][0] = min(dp[i][j][0], d[w][i][j]);
for (int l = 1; l <= 300; l++)
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
for (int w = 1; w <= n; w++)
dp[i][j][l] = min(dp[i][j][l], dp[i][w][l - 1] + dp[w][j][0]);
while (r--) {
scanf("%d%d%d", &s, &t, &k);
if (k > 300) k = 300;
printf("%d\n", dp[s][t][k]);
}
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.
Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.
Note that all computations should be done in base 10. You should find the result as an irreducible fraction, written in base 10.
Input
Input contains one integer number A (3 β€ A β€ 1000).
Output
Output should contain required average value in format Β«X/YΒ», where X is the numerator and Y is the denominator.
Examples
Input
5
Output
7/3
Input
3
Output
2/1
Note
In the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a;
unsigned long long int sum = 0;
cin >> a;
int array2[a];
for (int i = 2; i < a; i++) {
for (int n = 0; n < a; n++) array2[n] = 0;
for (int j = 0, k = a; k != 0; j++) {
array2[j] = k % i;
k /= i;
}
for (int c = 0; c < a; c++) sum += array2[c];
}
int k = a - 2;
unsigned long long int m = sum;
for (int i = 2; i < sum; i++)
while (1) {
if (k % i == 0 && m % i == 0) {
k /= i;
m /= i;
} else
break;
}
cout << m << "/" << k << endl;
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Welcome! Everything is fine.
You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.
You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.
Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.
The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses.
As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are:
* The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other;
* The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other.
What are the values of G and B?
Input
The first line of input contains a single integer t (1 β€ t β€ 500) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer k denoting the number of pairs of people (1 β€ k β€ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 β€ a_i, b_i β€ 2k, a_i β b_i, 1 β€ t_i β€ 10^6). It is guaranteed that the given roads define a tree structure.
It is guaranteed that the sum of the k in a single file is at most 3 β
10^5.
Output
For each test case, output a single line containing two space-separated integers G and B.
Example
Input
2
3
1 2 3
3 2 4
2 4 3
4 5 6
5 6 5
2
1 2 1
1 3 2
1 4 3
Output
15 33
6 6
Note
For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5;
* The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6;
* The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4.
Note that the sum of the f(i) is 5 + 6 + 4 = 15.
We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6;
* The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14;
* The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13.
Note that the sum of the f(i) is 6 + 14 + 13 = 33.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n;
struct Edge {
long long to, nxt, w;
} e[300005 << 1];
long long head[300005], tot;
void add(long long u, long long v, long long w) {
e[tot].to = v;
e[tot].w = w;
e[tot].nxt = head[u];
head[u] = tot++;
}
long long size[300005], val[300005];
void getsize(int u, int fa) {
size[u] = 1;
for (int i = head[u]; i != -1; i = e[i].nxt) {
int v = e[i].to;
if (v == fa) continue;
val[v] = e[i].w;
getsize(v, u);
size[u] += size[v];
}
}
long long ans1, ans2;
void dfs1(int u, int fa) {
if (size[u] % 2) ans1 += val[u];
for (int i = head[u]; i != -1; i = e[i].nxt) {
int v = e[i].to;
if (v == fa) continue;
dfs1(v, u);
}
}
void dfs2(int u, int fa) {
long long tmp = min(size[u], n - size[u]);
ans2 += tmp * val[u];
for (int i = head[u]; i != -1; i = e[i].nxt) {
int v = e[i].to;
if (v == fa) continue;
dfs2(v, u);
}
}
void init() {
memset(head, -1, sizeof head);
tot = 0;
ans1 = ans2 = 0;
}
int main() {
int t;
cin >> t;
while (t--) {
init();
scanf("%d", &n);
n <<= 1;
for (int i = 1; i <= n - 1; i++) {
long long u, v, w;
scanf("%lld%lld%lld", &u, &v, &w);
add(u, v, w);
add(v, u, w);
}
getsize(1, 1);
dfs1(1, 1);
dfs2(1, 1);
cout << ans1 << " " << ans2 << '\n';
}
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
This morning, Roman woke up and opened the browser with n opened tabs numbered from 1 to n. There are two kinds of tabs: those with the information required for the test and those with social network sites. Roman decided that there are too many tabs open so he wants to close some of them.
He decided to accomplish this by closing every k-th (2 β€ k β€ n - 1) tab. Only then he will decide whether he wants to study for the test or to chat on the social networks. Formally, Roman will choose one tab (let its number be b) and then close all tabs with numbers c = b + i β
k that satisfy the following condition: 1 β€ c β€ n and i is an integer (it may be positive, negative or zero).
For example, if k = 3, n = 14 and Roman chooses b = 8, then he will close tabs with numbers 2, 5, 8, 11 and 14.
After closing the tabs Roman will calculate the amount of remaining tabs with the information for the test (let's denote it e) and the amount of remaining social network tabs (s). Help Roman to calculate the maximal absolute value of the difference of those values |e - s| so that it would be easy to decide what to do next.
Input
The first line contains two integers n and k (2 β€ k < n β€ 100) β the amount of tabs opened currently and the distance between the tabs closed.
The second line consists of n integers, each of them equal either to 1 or to -1. The i-th integer denotes the type of the i-th tab: if it is equal to 1, this tab contains information for the test, and if it is equal to -1, it's a social network tab.
Output
Output a single integer β the maximum absolute difference between the amounts of remaining tabs of different types |e - s|.
Examples
Input
4 2
1 1 -1 1
Output
2
Input
14 3
-1 1 -1 -1 1 -1 -1 1 -1 -1 1 -1 -1 1
Output
9
Note
In the first example we can choose b = 1 or b = 3. We will delete then one tab of each type and the remaining tabs are then all contain test information. Thus, e = 2 and s = 0 and |e - s| = 2.
In the second example, on the contrary, we can leave opened only tabs that have social networks opened in them.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k, x, dem = 0, dem1 = 0, a[150], out = 0;
cin >> n >> k;
for (int i = 1; i <= n; i++) {
cin >> a[i];
if (a[i] == 1)
dem++;
else
dem1++;
}
for (int i = 0; i < k; i++) {
int x = dem, y = dem1;
for (int j = i; j <= n; j += k) {
if (a[j] == 1) x--;
if (a[j] == -1) y--;
}
out = max(out, abs(x - y));
}
cout << out;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
One day a well-known sponsor of a well-known contest decided to give every participant of the contest a T-shirt as a present. A natural problem occurred: on the one hand, it is not clear how many T-shirts of what sizes should be ordered, and on the other hand, one doesn't want to order too many T-shirts (and we do not exactly paper the walls with the oversupply). After considerable brain racking and some pre-estimating, the sponsor representatives ordered a certain number of T-shirts of sizes S, M, L, XL and XXL. The T-shirts turned out to bring good luck, that's why on the contest day there built up a line of K participants willing to get one. Every contestant is characterized by his/her desired T-shirt size (so it happens that for all the participants it is also one of the sizes S, M, L, XL and XXL). The participants come up to get a T-shirt one by one and try to choose the most suitable one, choosing it like this. If there is still a T-shirt of the optimal size left, that he/she takes it without further ado. Otherwise the contestant would prefer to choose a T-shirt with the size as close to the optimal one as possible (the distance between neighboring sizes is considered equal to one). If the variant of choice is not unique, the contestant will take a T-shirt of a bigger size (in case he/she grows more). For example, for a person whose optimal size is L the preference list looks like this: L, XL, M, XXL, S. Using the data on how many T-shirts of every size had been ordered by the organizers, on the size of contestants in the line determine who got a T-shirt of what size.
Input
The first line contains five non-negative integers NS, NM, NL, NXL, NXXL not exceeding 1000 which represent the number of T-shirts of the corresponding sizes. The second line contains an integer K (1 β€ K β€ 1000) which represents the number of participants. The next K lines contain the optimal T-shirt sizes for the contestants. The sizes are given in the order in which the participants stand in the line. It is guaranteed that NS + NM + NL + NXL + NXXL β₯ K.
Output
For each contestant, print a line containing the size of the T-shirt he/she got.
Examples
Input
1 0 2 0 1
3
XL
XXL
M
Output
XXL
L
L
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a[5];
for (int i = 0; i < 5; ++i) cin >> a[i];
int count;
cin >> count;
string tmp;
string prS;
for (int i = 0; i < count; ++i) {
cin >> tmp;
int size;
if (tmp == "S" || tmp == "s")
size = 0;
else if (tmp == "M" || tmp == "m")
size = 1;
else if (tmp == "L" || tmp == "l")
size = 2;
else if (tmp == "XL" || tmp == "xl")
size = 3;
else
size = 4;
int pSize;
if (a[size] > 0) {
a[size]--;
pSize = size;
} else
for (int k = 1; k < 5; ++k) {
if (size + k < 5 && a[size + k] > 0) {
a[size + k]--;
pSize = size + k;
break;
} else if (size - k >= 0 && a[size - k] > 0) {
a[size - k]--;
pSize = size - k;
break;
}
}
if (pSize == 0)
prS += "S\n";
else if (pSize == 1)
prS += "M\n";
else if (pSize == 2)
prS += "L\n";
else if (pSize == 3)
prS += "XL\n";
else if (pSize == 4)
prS += "XXL\n";
}
cout << prS;
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l, r (l β€ r) such that a_l + a_{l+1} + ... + a_{r-1} + a_r < t.
Input
The first line contains two integers n and t (1 β€ n β€ 200 000, |t| β€ 2β
10^{14}).
The second line contains a sequence of integers a_1, a_2, ..., a_n (|a_{i}| β€ 10^{9}) β the description of Petya's array. Note that there might be negative, zero and positive elements.
Output
Print the number of segments in Petya's array with the sum of elements less than t.
Examples
Input
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
Note
In the first example the following segments have sum less than 4:
* [2, 2], sum of elements is -1
* [2, 3], sum of elements is 2
* [3, 3], sum of elements is 3
* [4, 5], sum of elements is 3
* [5, 5], sum of elements is -1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline long long read() {
long long x = 0;
char c = getchar();
bool f = 0;
for (; c > '9' || c < '0'; f = c == '-', c = getchar())
;
for (; c >= '0' && c <= '9'; x = (x << 1) + (x << 3) + c - '0', c = getchar())
;
return f ? -x : x;
}
inline void write(long long x) {
if (x < 0) putchar('-'), x = -x;
if (x >= 10) write(x / 10);
putchar(x % 10 + 48);
}
const int N = 200000 + 10;
long long has[N], sum[N], a[N], t, ans;
int n, c[N];
void modify(int x, int v) {
for (; x <= *has; x += x & -x) c[x] += v;
}
int query(int x) {
int res = 0;
for (; x; x -= x & -x) res += c[x];
return res;
}
int solve(long long x) {
if (has[1] >= x) return 0;
int pos =
has[*has] < x ? *has : lower_bound(has + 1, has + *has + 1, x) - has - 1;
return query(pos);
}
int main() {
n = read(), t = read();
for (int i = 1; i <= n; ++i) {
a[i] = read();
sum[i] = sum[i - 1] + a[i];
has[i] = sum[i];
}
sort(has + 1, has + n + 1);
*has = unique(has + 1, has + n + 1) - has - 1;
for (int i = 1; i <= n; ++i) {
int x = lower_bound(has + 1, has + *has + 1, sum[i]) - has;
modify(x, 1);
}
for (int i = 0; i < n; ++i) {
ans += solve(t + sum[i]);
int x = lower_bound(has + 1, has + *has + 1, sum[i + 1]) - has;
modify(x, -1);
}
write(ans);
puts("");
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Write a program of the Bubble Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:
BubbleSort(A)
1 for i = 0 to A.length-1
2 for j = A.length-1 downto i+1
3 if A[j] < A[j-1]
4 swap A[j] and A[j-1]
Note that, indices for array elements are based on 0-origin.
Your program should also print the number of swap operations defined in line 4 of the pseudocode.
Constraints
1 β€ N β€ 100
Input
The first line of the input includes an integer N, the number of elements in the sequence.
In the second line, N elements of the sequence are given separated by spaces characters.
Output
The output consists of 2 lines.
In the first line, please print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.
In the second line, please print the number of swap operations.
Examples
Input
5
5 3 2 4 1
Output
1 2 3 4 5
8
Input
6
5 2 4 6 1 3
Output
1 2 3 4 5 6
9
### Response
```cpp
#include<iostream>
using namespace std;
void bubblesort(int A[100], int N){
int cnt=0;
for(int i=0;i<N;i++){
for(int j=N-1;j>i;j--){
if(A[j]<A[j-1]){
swap(A[j],A[j-1]);
cnt++;}
}
}
for(int k=0;k<N-1;k++)cout <<A[k]<<" ";
cout <<A[N-1]<<endl;
cout <<cnt<<endl;}
int main(){
int N,A[100];
cin>>N;
for(int i=0;i<N;i++)cin>>A[i];
bubblesort(A,N);
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Valera is a coder. Recently he wrote a funny program. The pseudo code for this program is given below:
//input: integers x, k, p
a = x;
for(step = 1; step <= k; step = step + 1){
rnd = [random integer from 1 to 100];
if(rnd <= p)
a = a * 2;
else
a = a + 1;
}
s = 0;
while(remainder after dividing a by 2 equals 0){
a = a / 2;
s = s + 1;
}
Now Valera wonders: given the values x, k and p, what is the expected value of the resulting number s?
Input
The first line of the input contains three integers x, k, p (1 β€ x β€ 109; 1 β€ k β€ 200; 0 β€ p β€ 100).
Output
Print the required expected value. Your answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
Examples
Input
1 1 50
Output
1.0000000000000
Input
5 3 0
Output
3.0000000000000
Input
5 3 25
Output
1.9218750000000
Note
If the concept of expected value is new to you, you can read about it by the link:
http://en.wikipedia.org/wiki/Expected_value
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const double eps(1e-8);
int x, k, p;
double dp[2][210];
int main() {
scanf("%d %d %d", &x, &k, &p);
double P = p / 100.;
for (int i = 0; i <= k + 1; i++) {
int tmp = x + i;
while (!(tmp & 1)) tmp >>= 1, dp[0][i] += 1.;
}
int now = 0;
for (int i = 0; i < k; i++) {
memset(dp[now ^ 1], 0, sizeof(dp[now ^ 1]));
for (int j = 0; j <= k; j++) {
dp[now ^ 1][j << 1] += (dp[now][j] + 1) * P;
dp[now ^ 1][j] += dp[now][j + 1] * (1 - P);
}
now ^= 1;
}
printf("%.10f\n", dp[now][0]);
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Bees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes, shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature β color, number, shape, and shading β the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.
<image>
Polina came up with a new game called "Hyperset". In her game, there are n cards with k features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k = 4.
Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.
Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.
Input
The first line of each test contains two integers n and k (1 β€ n β€ 1500, 1 β€ k β€ 30) β number of cards and number of features.
Each of the following n lines contains a card description: a string consisting of k letters "S", "E", "T". The i-th character of this string decribes the i-th feature of that card. All cards are distinct.
Output
Output a single integer β the number of ways to choose three cards that form a set.
Examples
Input
3 3
SET
ETS
TSE
Output
1
Input
3 4
SETE
ETSE
TSES
Output
0
Input
5 4
SETT
TEST
EEET
ESTE
STES
Output
2
Note
In the third example test, these two triples of cards are sets:
1. "SETT", "TEST", "EEET"
2. "TEST", "ESTE", "STES"
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<string> str(1500);
map<string, int> mp;
map<string, int>::iterator it;
string word;
void call(string ff, string ss, long long sz) {
for (long long i = 0; i < sz; i++) {
if (ff[i] == ss[i])
word += ff[i];
else
word += 'S' + 'E' + 'T' - ff[i] - ss[i];
}
}
int main() {
long long n, i, j, k, cnt;
cin >> n >> k;
for (i = 0; i < n; i++) {
cin >> str[i];
mp.insert({str[i], 0});
}
for (i = 0, cnt = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (i != j) {
call(str[i], str[j], k);
it = mp.find(word);
if (it != mp.end()) cnt++;
word.clear();
}
}
}
cout << cnt / 3 << endl;
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Jeff loves regular bracket sequences.
Today Jeff is going to take a piece of paper and write out the regular bracket sequence, consisting of nm brackets. Let's number all brackets of this sequence from 0 to nm - 1 from left to right. Jeff knows that he is going to spend ai mod n liters of ink on the i-th bracket of the sequence if he paints it opened and bi mod n liters if he paints it closed.
You've got sequences a, b and numbers n, m. What minimum amount of ink will Jeff need to paint a regular bracket sequence of length nm?
Operation x mod y means taking the remainder after dividing number x by number y.
Input
The first line contains two integers n and m (1 β€ n β€ 20; 1 β€ m β€ 107; m is even). The next line contains n integers: a0, a1, ..., an - 1 (1 β€ ai β€ 10). The next line contains n integers: b0, b1, ..., bn - 1 (1 β€ bi β€ 10). The numbers are separated by spaces.
Output
In a single line print the answer to the problem β the minimum required amount of ink in liters.
Examples
Input
2 6
1 2
2 1
Output
12
Input
1 10000000
2
3
Output
25000000
Note
In the first test the optimal sequence is: ()()()()()(), the required number of ink liters is 12.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long INF = 0x3f3f3f3f3f3f3f3fLL;
int n, m;
long long a[25], b[25];
long long A[25][25], B[25][25], f[25][25];
void init(long long a[25][25]) {
memset(a, 0x3f, sizeof(A));
for (int i = 0; i <= n; i++) a[i][i] = 0;
}
void mul(long long a[][25], long long b[][25], long long c[][25]) {
static long long tmp[25][25];
memset(tmp, 0x3f, sizeof(A));
for (int i = 0; i <= n; i++)
for (int j = 0; j <= n; j++)
for (int k = 0; k <= n; k++)
tmp[i][j] = min(tmp[i][j], a[i][k] + b[k][j]);
memcpy(c, tmp, sizeof(tmp));
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= n; i++) cin >> b[i];
init(A), init(f);
for (int k = 1; k <= n; k++) {
init(B);
for (int i = 0; i <= n; i++)
for (int j = 0; j <= n; j++)
i + 1 == j ? B[j][i] = a[k]
: j + 1 == i ? B[j][i] = b[k]
: B[j][i] = INF;
mul(B, A, A);
}
for (; m; m >>= 1, mul(A, A, A))
if (m & 1) mul(f, A, f);
cout << f[0][0] << endl;
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
You are a student looking for a job. Today you had an employment examination for an IT company. They asked you to write an efficient program to perform several operations. First, they showed you an N \times N square matrix and a list of operations. All operations but one modify the matrix, and the last operation outputs the character in a specified cell. Please remember that you need to output the final matrix after you finish all the operations.
Followings are the detail of the operations:
WR r c v
(Write operation) write a integer v into the cell (r,c) (1 \leq v \leq 1,000,000)
CP r1 c1 r2 c2
(Copy operation) copy a character in the cell (r1,c1) into the cell (r2,c2)
SR r1 r2
(Swap Row operation) swap the r1-th row and r2-th row
SC c1 c2
(Swap Column operation) swap the c1-th column and c2-th column
RL
(Rotate Left operation) rotate the whole matrix in counter-clockwise direction by 90 degrees
RR
(Rotate Right operation) rotate the whole matrix in clockwise direction by 90 degrees
RH
(Reflect Horizontal operation) reverse the order of the rows
RV
(Reflect Vertical operation) reverse the order of the columns
Input
First line of each testcase contains nine integers. First two integers in the line, N and Q, indicate the size of matrix and the number of queries, respectively (1 \leq N,Q \leq 40,000). Next three integers, A B, and C, are coefficients to calculate values in initial matrix (1 \leq A,B,C \leq 1,000,000), and they are used as follows: A_{r,c} = (r * A + c * B) mod C where r and c are row and column indices, respectively (1\leq r,c\leq N). Last four integers, D, E, F, and G, are coefficients to compute the final hash value mentioned in the next section (1 \leq D \leq E \leq N, 1 \leq F \leq G \leq N, E - D \leq 1,000, G - F \leq 1,000). Each of next Q lines contains one operation in the format as described above.
Output
Output a hash value h computed from the final matrix B by using following pseudo source code.
h <- 314159265
for r = D...E
for c = F...G
h <- (31 * h + B_{r,c}) mod 1,000,000,007
where "<-" is a destructive assignment operator, "for i = S...T" indicates a loop for i from S to T (both inclusive), and "mod" is a remainder operation.
Examples
Input
2 1 3 6 12 1 2 1 2
WR 1 1 1
Output
676573821
Input
2 1 3 6 12 1 2 1 2
RL
Output
676636559
Input
2 1 3 6 12 1 2 1 2
RH
Output
676547189
Input
39989 6 999983 999979 999961 1 1000 1 1000
SR 1 39989
SC 1 39989
RL
RH
RR
RV
Output
458797120
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
constexpr int mod = 1e9 + 7;
constexpr int rev_tbl[2][4][2] = { // [mir][rot][row/col]
{{0, 0}, {1, 0}, {1, 1}, {0, 1}},
{{0, 1}, {1, 1}, {1, 0}, {0, 0}}
};
int main() {
ll n, q, A, B, C, D, E, F, G;
cin >> n >> q >> A >> B >> C >> D >> E >> F >> G;
vector<string> op(q);
vector<int> w(q), x(q), y(q), z(q);
for(int i = 0; i < q; ++i) {
cin >> op[i];
if(op[i] == "WR") cin >> w[i] >> x[i] >> y[i];
else if(op[i] == "CP") cin >> w[i] >> x[i] >> y[i] >> z[i];
else if(op[i] == "SR") cin >> w[i] >> x[i];
else if(op[i] == "SC") cin >> w[i] >> x[i];
}
int mir = 0, rot = 0;
vector<int> ridx(n), cidx(n);
iota(begin(ridx), end(ridx), 1);
iota(begin(cidx), end(cidx), 1);
auto get_r_idx = [&] (int r) -> int& {
const int i = (rev_tbl[mir][rot][0] ? n - r : r - 1);
return rot & 1 ? cidx[i] : ridx[i];
};
auto get_c_idx = [&] (int c) -> int& {
const int i = (rev_tbl[mir][rot][1] ? n - c : c - 1);
return rot & 1 ? ridx[i] : cidx[i];
};
auto get_orig_pos = [&] (int r, int c) {
if(rot & 1) return make_pair(get_c_idx(c), get_r_idx(r));
else return make_pair(get_r_idx(r), get_c_idx(c));
};
map<pii, int> v;
for(int i = 0; i < q; ++i) {
if(op[i] == "WR") {
int r, c; tie(r, c) = get_orig_pos(w[i], x[i]);
v[{r, c}] = y[i];
} else if(op[i] == "CP") {
int r1, c1, r2, c2;
tie(r1, c1) = get_orig_pos(w[i], x[i]);
tie(r2, c2) = get_orig_pos(y[i], z[i]);
if(v.count({r1, c1})) {
v[{r2, c2}] = v[{r1, c1}];
} else {
v[{r2, c2}] = (r1 * A + c1 * B) % C;
}
} else if(op[i] == "SR") {
swap(get_r_idx(w[i]), get_r_idx(x[i]));
} else if(op[i] == "SC") {
swap(get_c_idx(w[i]), get_c_idx(x[i]));
} else if(op[i] == "RL") {
if(mir) rot = (rot + 3) % 4;
else rot = (rot + 1) % 4;
} else if(op[i] == "RR") {
if(mir) rot = (rot + 1) % 4;
else rot = (rot + 3) % 4;
} else if(op[i] == "RH") {
mir = !mir;
rot = (rot + 2) % 4;
} else if(op[i] == "RV") {
mir = !mir;
}
}
ll h = 314159265;
for(int r = D; r <= E; ++r) {
for(int c = F; c <= G; ++c) {
int rr, cc; tie(rr, cc) = get_orig_pos(r, c);
const ll val = v.count({rr, cc}) ? v[{rr, cc}] : (rr * A + cc * B) % C;
h = (h * 31 + val) % mod;
}
}
cout << h << endl;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
You are involved in the development of a certain game. The game is for players to explore randomly generated dungeons. As a specification of the game, I want to show the player the danger level of the dungeon in advance and select whether to search for the generated dungeon or to regenerate a new dungeon.
There are n rooms in the dungeon generated by this game, and they are numbered from 0 to n-1. The rooms are connected by a passage. There are a total of n-1 passages connecting rooms. The passage can go in either direction. In addition, a distance is set between the rooms. In the generated dungeon, it is possible to go from one room to all other rooms via several passages. Then, when the player plays the game, two different rooms are selected as the start point and the goal point.
You decide to decide how to evaluate the risk in order to evaluate the dungeon. First, the risk level when moving from one room to another is set to the value of the most costly passage among the passages used to move between rooms in the shortest time. Then, we decided to set the risk level of the dungeon as the sum of the risk levels when moving between a pair of rooms where i <j.
A randomly generated dungeon is given as input. First, calculate the risk of moving for all room pairs where i <j. Then output the sum as the answer to the problem.
Input
The input is given in the following format.
n
a1 b1 c1
..
..
..
an-1 bn-1 cn-1
ai bi ci means that the distance of the passage connecting the rooms ai and bi is ci.
Input meets the following constraints
2 β€ n β€ 200,000
0 β€ ai, bi <n
0 β€ ci β€ 100,000
Output
Print the answer value on one line
Examples
Input
4
0 1 3
1 2 5
1 3 2
Output
23
Input
6
0 2 5
2 1 1
2 3 10
3 5 4
3 4 2
Output
111
### Response
```cpp
#include<iostream>
#include<vector>
#include<algorithm>
#include<tuple>
using namespace std;
class QuickUnionFind {
private:
int size_; std::vector<int> g; std::vector<std::vector<int> > v;
public:
QuickUnionFind() : size_(0), g(std::vector<int>()), v(std::vector<std::vector<int> >()) {};
QuickUnionFind(int size__) : size_(size__) {
g.resize(size_); v.resize(size_);
for (int i = 0; i < size_; i++) g[i] = i, v[i] = { i };
};
int size() { return size_; }
int root(int x) { return g[x]; }
int size(int x) { return v[x].size(); }
bool same(int x, int y) { return g[x] == g[y]; }
void unite(int x, int y) {
x = g[x], y = g[y];
if (x == y) return;
if (v[x].size() < v[y].size()) std::swap(x, y);
v[x].insert(v[x].end(), v[y].begin(), v[y].end());
for (auto &e : v[y]) g[e] = x;
v[y].clear();
}
std::vector<int> connected(int x) { return v[g[x]]; }
bool operator==(const QuickUnionFind& u) { return g == u.g; }
bool operator!=(const QuickUnionFind& u) { return g != u.g; }
};
long long n, a[2000000], b[200000], c[200000], ret;
vector<tuple<int, int, int>>tup;
int main() {
cin >> n; for (int i = 0; i < n - 1; i++) { cin >> a[i] >> b[i] >> c[i]; tup.push_back(make_tuple(c[i], a[i], b[i])); }
sort(tup.begin(), tup.end()); QuickUnionFind UF(n);
for (int i = 0; i < tup.size(); i++) {
long long a1 = get<0>(tup[i]), a2 = get<1>(tup[i]), a3 = get<2>(tup[i]);
ret += 1LL * a1*UF.size(UF.root(a2))*UF.size(UF.root(a3)); UF.unite(a2, a3);
}
cout << ret << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
N persons are standing in a row. The height of the i-th person from the front is A_i.
We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:
Condition: Nobody in front of the person is taller than the person. Here, the height of a person includes the stool.
Find the minimum total height of the stools needed to meet this goal.
Constraints
* 1 \leq N \leq 2\times 10^5
* 1 \leq A_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 \ldots A_N
Output
Print the minimum total height of the stools needed to meet the goal.
Examples
Input
5
2 1 5 4 3
Output
4
Input
5
3 3 3 3 3
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a,n,maxL=0; cin>>n>>maxL;
long long sum=0;
for(int i=0;i<n-1;i++){
cin>>a;
if(maxL>a) sum+=maxL-a;
else maxL=a;
}
cout<<sum;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Mike is trying rock climbing but he is awful at it.
There are n holds on the wall, i-th hold is at height ai off the ground. Besides, let the sequence ai increase, that is, ai < ai + 1 for all i from 1 to n - 1; we will call such sequence a track. Mike thinks that the track a1, ..., an has difficulty <image>. In other words, difficulty equals the maximum distance between two holds that are adjacent in height.
Today Mike decided to cover the track with holds hanging on heights a1, ..., an. To make the problem harder, Mike decided to remove one hold, that is, remove one element of the sequence (for example, if we take the sequence (1, 2, 3, 4, 5) and remove the third element from it, we obtain the sequence (1, 2, 4, 5)). However, as Mike is awful at climbing, he wants the final difficulty (i.e. the maximum difference of heights between adjacent holds after removing the hold) to be as small as possible among all possible options of removing a hold. The first and last holds must stay at their positions.
Help Mike determine the minimum difficulty of the track after removing one hold.
Input
The first line contains a single integer n (3 β€ n β€ 100) β the number of holds.
The next line contains n space-separated integers ai (1 β€ ai β€ 1000), where ai is the height where the hold number i hangs. The sequence ai is increasing (i.e. each element except for the first one is strictly larger than the previous one).
Output
Print a single number β the minimum difficulty of the track after removing a single hold.
Examples
Input
3
1 4 6
Output
5
Input
5
1 2 3 4 5
Output
2
Input
5
1 2 3 7 8
Output
4
Note
In the first sample you can remove only the second hold, then the sequence looks like (1, 6), the maximum difference of the neighboring elements equals 5.
In the second test after removing every hold the difficulty equals 2.
In the third test you can obtain sequences (1, 3, 7, 8), (1, 2, 7, 8), (1, 2, 3, 8), for which the difficulty is 4, 5 and 5, respectively. Thus, after removing the second element we obtain the optimal answer β 4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[100005];
int n, k;
map<int, int> m;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
ios_base::sync_with_stdio(0);
int n;
cin >> n;
vector<int> v(n);
for (int i = 0; i < n; i++) {
cin >> v[i];
}
int maxx = 0, ans = 1e8;
for (int i = 1; i < n - 1; i++) {
maxx = 0;
for (int j = 1; j < n; j++) {
if (j == i) {
j++;
maxx = max(maxx, v[j] - v[j - 2]);
} else {
maxx = max(maxx, v[j] - v[j - 1]);
}
}
ans = min(ans, maxx);
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?
There are n students living in a building, and for each of them the favorite drink a_i is known. So you know n integers a_1, a_2, ..., a_n, where a_i (1 β€ a_i β€ k) is the type of the favorite drink of the i-th student. The drink types are numbered from 1 to k.
There are infinite number of drink sets. Each set consists of exactly two portions of the same drink. In other words, there are k types of drink sets, the j-th type contains two portions of the drink j. The available number of sets of each of the k types is infinite.
You know that students will receive the minimum possible number of sets to give all students exactly one drink. Obviously, the number of sets will be exactly β n/2 β, where β x β is x rounded up.
After students receive the sets, they will distribute their portions by their choice: each student will get exactly one portion. Note, that if n is odd then one portion will remain unused and the students' teacher will drink it.
What is the maximum number of students that can get their favorite drink if β n/2 β sets will be chosen optimally and students will distribute portions between themselves optimally?
Input
The first line of the input contains two integers n and k (1 β€ n, k β€ 1 000) β the number of students in the building and the number of different drinks.
The next n lines contain student's favorite drinks. The i-th line contains a single integer from 1 to k β the type of the favorite drink of the i-th student.
Output
Print exactly one integer β the maximum number of students that can get a favorite drink.
Examples
Input
5 3
1
3
1
1
2
Output
4
Input
10 3
2
1
3
2
3
3
1
3
1
2
Output
9
Note
In the first example, students could choose three sets with drinks 1, 1 and 2 (so they will have two sets with two drinks of the type 1 each and one set with two drinks of the type 2, so portions will be 1, 1, 1, 1, 2, 2). This way all students except the second one will get their favorite drinks.
Another possible answer is sets with drinks 1, 2 and 3. In this case the portions will be 1, 1, 2, 2, 3, 3. Then all the students except one will gain their favorite drinks. The only student that will not gain the favorite drink will be a student with a_i = 1 (i.e. the first, the third or the fourth).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a, b, c, l, r, x[2000000], y, z, man, mix, d[2000000], ans, ans1;
vector<long long> v1, v;
int main() {
cin >> a >> b;
for (int i = 0; i < a; i++) {
cin >> d[i];
x[d[i]]++;
}
ans1 = (a + 1) / 2;
for (int i = 1; i <= b; i++) {
if (x[i] % 2 == 0) {
ans += x[i];
ans1 -= x[i] / 2;
}
}
for (int i = 1; i <= b; i++) {
if (x[i] % 2 == 1) {
ans1 -= x[i] / 2;
ans += x[i] - 1;
}
}
cout << ans + ans1;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Nastya likes reading and even spends whole days in a library sometimes. Today she found a chronicle of Byteland in the library, and it stated that there lived shamans long time ago. It is known that at every moment there was exactly one shaman in Byteland, and there were n shamans in total enumerated with integers from 1 to n in the order they lived. Also, each shaman had a magic power which can now be expressed as an integer.
The chronicle includes a list of powers of the n shamans. Also, some shamans can be king-shamans, if they gathered all the power of their predecessors, i.e. their power is exactly the sum of powers of all previous shamans. Nastya is interested in whether there was at least one king-shaman in Byteland.
Unfortunately many of the powers are unreadable in the list, so Nastya is doing the following:
* Initially she supposes some power for each shaman.
* After that she changes the power of some shaman q times (the shamans can differ) and after that wants to check if there is at least one king-shaman in the list. If yes, she wants to know the index of any king-shaman.
Unfortunately the list is too large and Nastya wants you to help her.
Input
The first line contains two integers n and q (1 β€ n, q β€ 2Β·105).
The second line contains n integers a1, ..., an (0 β€ ai β€ 109), where ai is the magic power of the i-th shaman.
After that q lines follow, the i-th of them contains two integers pi and xi (1 β€ pi β€ n, 0 β€ xi β€ 109) that mean that the new power of the pi-th shaman is xi.
Output
Print q lines, the i-th of them should contain - 1, if after the i-th change there are no shaman-kings, and otherwise a single integer j, where j is an index of some king-shaman after the i-th change.
If there are multiple king-shamans after each change, print the index of any of them.
Examples
Input
2 1
1 3
1 2
Output
-1
Input
3 4
2 2 3
1 1
1 2
2 4
3 6
Output
3
2
-1
3
Input
10 7
0 3 1 4 6 2 7 8 10 1
2 5
1 3
9 36
4 10
4 9
1 2
1 0
Output
1
-1
9
-1
4
-1
1
Note
In the first example powers of shamans after the first change are equal to (2, 3). The answer equals - 1, because the sum of powers of shamans before the first shaman is equal to 0, and before the second is equal to 2.
In the second example after the first change the powers are equal to (1, 2, 3). The answer is equal to 3, because the power of the third shaman is equal to 3, and the sum of powers of the first and the second shaman is also 1 + 2 = 3. After the second change the powers become equal to (2, 2, 3), where the answer equals 2. After the third change the powers become equal to (2, 4, 3), where the answer equals - 1. After the fourth change the powers become equal to (2, 4, 6), where the answer equals 3.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
using vvi = vector<vi>;
using vll = vector<ll>;
using vvll = vector<vll>;
using vb = vector<bool>;
using vd = vector<double>;
using vs = vector<string>;
template <typename T>
void ckmin(T& a, const T& b) {
a = min(a, b);
}
template <typename T>
void ckmax(T& a, const T& b) {
a = max(a, b);
}
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
template <typename T>
struct binary_indexed_tree {
int S;
vector<T> table;
binary_indexed_tree<T>(int _S = 0) : S(_S) { table.resize(S + 1); }
void add(int i, T v) {
for (i++; i <= S; i += i & -i) table[i] = table[i] + v;
}
T sum(int i) const {
T res = T();
for (; i; i -= i & -i) res = res + table[i];
return res;
}
T sum(int l, int r) const { return sum(r) - sum(l); }
int lower_bound(const function<bool(T)>& comp) const {
int inx = 0;
T cur = T();
for (int i = 31 - __builtin_clz(S); i >= 0; i--) {
int nxt = inx + (1 << i);
if (nxt <= S && !comp(cur + table[nxt])) {
inx = nxt;
cur = cur + table[nxt];
}
}
return inx < S ? inx + 1 : -1;
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int N, Q;
cin >> N >> Q;
binary_indexed_tree<ll> sh(N);
vi pow(N);
for (int i = 0; i < N; i++) {
cin >> pow[i];
sh.add(i, pow[i]);
}
for (int q = 0, i, v; q < Q; q++) {
cin >> i >> v;
--i;
sh.add(i, v - pow[i]);
pow[i] = v;
int used = 1;
ll sum = sh.sum(used);
while (true) {
if (2 * pow[used - 1] == sum) {
cout << used << "\n";
break;
}
int jump = sh.lower_bound([&sum](ll tot) { return tot >= 2 * sum; });
if (jump == -1) {
cout << "-1\n";
break;
}
used = jump;
sum = sh.sum(used);
}
}
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Mr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to n (n β₯ 2) burles and the amount of tax he has to pay is calculated as the maximum divisor of n (not equal to n, of course). For example, if n = 6 then Funt has to pay 3 burles, while for n = 25 he needs to pay 5 and if n = 2 he pays only 1 burle.
As mr. Funt is a very opportunistic person he wants to cheat a bit. In particular, he wants to split the initial n in several parts n1 + n2 + ... + nk = n (here k is arbitrary, even k = 1 is allowed) and pay the taxes for each part separately. He can't make some part equal to 1 because it will reveal him. So, the condition ni β₯ 2 should hold for all i from 1 to k.
Ostap Bender wonders, how many money Funt has to pay (i.e. minimal) if he chooses and optimal way to split n in parts.
Input
The first line of the input contains a single integer n (2 β€ n β€ 2Β·109) β the total year income of mr. Funt.
Output
Print one integer β minimum possible number of burles that mr. Funt has to pay as a tax.
Examples
Input
4
Output
2
Input
27
Output
3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool check(long long n) {
bool is = true;
for (long long i = 2; i * i <= n; i++) {
if (n % i == 0) {
is = false;
break;
}
}
return is;
}
int main() {
long long n;
scanf("%I64d", &n);
bool is = check(n);
int ans;
if (is)
ans = 1;
else {
if (n % 2 == 0)
ans = 2;
else {
ans = 3;
if (check(n - 2)) ans = 2;
}
}
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
You are given an array a, consisting of n integers.
Each position i (1 β€ i β€ n) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.
For example, let a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}], the underlined positions are locked. You can obtain the following arrays:
* [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}];
* [-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}];
* [1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}];
* [1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}];
* and some others.
Let p be a sequence of prefix sums of the array a after the rearrangement. So p_1 = a_1, p_2 = a_1 + a_2, p_3 = a_1 + a_2 + a_3, ..., p_n = a_1 + a_2 + ... + a_n.
Let k be the maximum j (1 β€ j β€ n) such that p_j < 0. If there are no j such that p_j < 0, then k = 0.
Your goal is to rearrange the values in such a way that k is minimum possible.
Output the array a after the rearrangement such that the value k for it is minimum possible. If there are multiple answers then print any of them.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then t testcases follow.
The first line of each testcase contains a single integer n (1 β€ n β€ 100) β the number of elements in the array a.
The second line of each testcase contains n integers a_1, a_2, ..., a_n (-10^5 β€ a_i β€ 10^5) β the initial array a.
The third line of each testcase contains n integers l_1, l_2, ..., l_n (0 β€ l_i β€ 1), where l_i = 0 means that the position i is unlocked and l_i = 1 means that the position i is locked.
Output
Print n integers β the array a after the rearrangement. Value k (the maximum j such that p_j < 0 (or 0 if there are no such j)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones.
If there are multiple answers then print any of them.
Example
Input
5
3
1 3 2
0 0 0
4
2 -3 4 -1
1 1 1 1
7
-8 4 -2 -6 4 7 1
1 0 0 0 1 1 0
5
0 1 -4 6 3
0 0 0 1 1
6
-1 7 10 4 -8 -1
1 0 0 0 0 1
Output
1 2 3
2 -3 4 -1
-8 -6 1 4 4 7 -2
-4 0 1 6 3
-1 4 7 -8 10 -1
Note
In the first testcase you can rearrange all values however you want but any arrangement will result in k = 0. For example, for an arrangement [1, 2, 3], p=[1, 3, 6], so there are no j such that p_j < 0. Thus, k = 0.
In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.
In the third testcase the prefix sums for the printed array are p = [-8, -14, -13, -9, -5, 2, 0]. The maximum j is 5, thus k = 5. There are no arrangements such that k < 5.
In the fourth testcase p = [-4, -4, -3, 3, 6].
In the fifth testcase p = [-1, 3, 10, 2, 12, 11].
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
long long power(long long base, long long exp);
void solve() {
long long n;
cin >> n;
vector<long long> arr(n, 0);
for (long long i = 0; i < n; i++) {
cin >> arr[i];
}
vector<long long> temp(n, 0);
for (long long i = 0; i < n; i++) {
cin >> temp[i];
}
vector<long long> z;
long long sum = 0;
for (long long i = 0; i < n; i++) {
if (temp[i] == 0) {
z.push_back(arr[i]);
}
}
sort((z).begin(), (z).end(), greater<long long>());
long long x = 0;
for (long long i = 0; i < n; i++) {
if (temp[i] == 0) {
arr[i] = z[x++];
}
}
for (long long i = 0; i < n; i++) cout << arr[i] << " ";
cout << "\n";
}
int32_t main() {
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
srand(chrono::high_resolution_clock::now().time_since_epoch().count());
long long t = 1;
cin >> t;
while (t--) {
solve();
}
return 0;
}
long long power(long long base, long long exp) {
base %= 1000000007;
long long result = 1;
while (exp > 0) {
if (exp & 1) result = ((long long)result * base) % 1000000007;
base = ((long long)base * base) % 1000000007;
exp >>= 1;
}
return result;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Pasha has a wooden stick of some positive integer length n. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be n.
Pasha likes rectangles but hates squares, so he wonders, how many ways are there to split a stick into four parts so that it's possible to form a rectangle using these parts, but is impossible to form a square.
Your task is to help Pasha and count the number of such ways. Two ways to cut the stick are considered distinct if there exists some integer x, such that the number of parts of length x in the first way differ from the number of parts of length x in the second way.
Input
The first line of the input contains a positive integer n (1 β€ n β€ 2Β·109) β the length of Pasha's stick.
Output
The output should contain a single integer β the number of ways to split Pasha's stick into four parts of positive integer length so that it's possible to make a rectangle by connecting the ends of these parts, but is impossible to form a square.
Examples
Input
6
Output
1
Input
20
Output
4
Note
There is only one way to divide the stick in the first sample {1, 1, 2, 2}.
Four ways to divide the stick in the second sample are {1, 1, 9, 9}, {2, 2, 8, 8}, {3, 3, 7, 7} and {4, 4, 6, 6}. Note that {5, 5, 5, 5} doesn't work.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
if (n & 1) {
cout << "0";
return 0;
}
n >>= 1;
int x = (n >> 1);
if ((n & 1) == 0) --x;
cout << x;
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Bike is a smart boy who loves math very much. He invented a number called "Rotatable Number" inspired by 142857.
As you can see, 142857 is a magic number because any of its rotatings can be got by multiplying that number by 1, 2, ..., 6 (numbers from one to number's length). Rotating a number means putting its last several digit into first. For example, by rotating number 12345 you can obtain any numbers: 12345, 51234, 45123, 34512, 23451. It's worth mentioning that leading-zeroes are allowed. So both 4500123 and 0123450 can be obtained by rotating 0012345. You can see why 142857 satisfies the condition. All of the 6 equations are under base 10.
* 142857Β·1 = 142857;
* 142857Β·2 = 285714;
* 142857Β·3 = 428571;
* 142857Β·4 = 571428;
* 142857Β·5 = 714285;
* 142857Β·6 = 857142.
Now, Bike has a problem. He extends "Rotatable Number" under any base b. As is mentioned above, 142857 is a "Rotatable Number" under base 10. Another example is 0011 under base 2. All of the 4 equations are under base 2.
* 0011Β·1 = 0011;
* 0011Β·10 = 0110;
* 0011Β·11 = 1001;
* 0011Β·100 = 1100.
So, he wants to find the largest b (1 < b < x) so that there is a positive "Rotatable Number" (leading-zeroes allowed) of length n under base b.
Note that any time you multiply a rotatable number by numbers from 1 to its length you should get a rotating of that number.
Input
The only line contains two space-separated integers n, x (1 β€ n β€ 5Β·106, 2 β€ x β€ 109).
Output
Print a single integer β the largest b you found. If no such b exists, print -1 instead.
Examples
Input
6 11
Output
10
Input
5 8
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
const int N = 5e6 + 6;
int n, x, a[N], len;
inline int pow(int x, int k, int mod) {
long long res = 1, r = x % mod;
for (; k; k >>= 1, r = r * r % mod)
if (k & 1) res = res * r % mod;
return res;
}
int main() {
scanf("%d%d", &n, &x);
if (n == 1 && x <= 2) {
puts("-1");
return 0;
}
for (int i = 2; i * i <= n + 1; ++i)
if ((n + 1) % i == 0) {
puts("-1");
return 0;
}
for (int i = 1; i * i <= n; ++i)
if (n % i == 0) a[++len] = i, a[++len] = n / i;
if (a[len] == a[len - 1]) --len;
for (int i = x - 1; i >= 1; --i) {
bool flag = true;
for (int k = 1; k <= len; ++k)
if (a[k] != n && pow(i, a[k], n + 1) == 1) {
flag = false;
break;
}
if (flag) {
printf("%d\n", i);
return 0;
}
}
puts("-1");
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Little Vasya has received a young builderβs kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same.
Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible.
Input
The first line contains an integer N (1 β€ N β€ 1000) β the number of bars at Vasyaβs disposal. The second line contains N space-separated integers li β the lengths of the bars. All the lengths are natural numbers not exceeding 1000.
Output
In one line output two numbers β the height of the largest tower and their total number. Remember that Vasya should use all the bars.
Examples
Input
3
1 2 3
Output
1 3
Input
4
6 5 6 7
Output
2 3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int max, n, l, s, N, i;
int a[1001];
cin >> N;
max = -1;
s = 0;
for (i = 1; i <= 1000; i++) {
a[i] = 0;
}
for (i = 1; i <= N; i++) {
cin >> l;
a[l]++;
if (a[l] > max) max = a[l];
}
for (i = 1; i <= 1000; i++) {
if (a[i] != 0) s++;
}
cout << max << " " << s;
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him.
<image>
The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 β€ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads.
<image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights.
Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe.
He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.
Input
The first line contains integer n (1 β€ n β€ 10) β the number of roads on the path from the entrance to any exit.
The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 β the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100.
Output
Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe.
Examples
Input
2
1 2 3 4 5 6
Output
5
Note
Picture for the sample test. Green color denotes the additional street lights.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m = 0, k, ans = 0, a[1000000], b[1000000], x, y, z = 1, MAX, MIN;
string str, str1, str2;
char C;
bool flag = false;
int main() {
cin >> n;
k = pow(2, float(n - 1));
n = pow(2, (float)(n + 1)) - 1;
for (int i = 2; i <= n; i++) {
cin >> a[i];
}
n--;
for (int i = n; i >= 2; i -= 2) {
a[i / 2] += max(a[i], a[i + 1]), ans += (abs(a[i] - a[i + 1]));
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution 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;
int main() {
string a;
cin >> a;
cout << a;
int n = a.size();
for (int i = n - 1; i >= 0; i--) {
cout << a[i];
}
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
You are given integer n. You have to arrange numbers from 1 to 2n, using each of them exactly once, on the circle, so that the following condition would be satisfied:
For every n consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard 2n numbers differ not more than by 1.
For example, choose n = 3. On the left you can see an example of a valid arrangement: 1 + 4 + 5 = 10, 4 + 5 + 2 = 11, 5 + 2 + 3 = 10, 2 + 3 + 6 = 11, 3 + 6 + 1 = 10, 6 + 1 + 4 = 11, any two numbers differ by at most 1. On the right you can see an invalid arrangement: for example, 5 + 1 + 6 = 12, and 3 + 2 + 4 = 9, 9 and 12 differ more than by 1.
<image>
Input
The first and the only line contain one integer n (1 β€ n β€ 10^5).
Output
If there is no solution, output "NO" in the first line.
If there is a solution, output "YES" in the first line. In the second line output 2n numbers β numbers from 1 to 2n in the order they will stay in the circle. Each number should appear only once. If there are several solutions, you can output any of them.
Examples
Input
3
Output
YES
1 4 5 2 3 6
Input
4
Output
NO
Note
Example from the statement is shown for the first example.
It can be proved that there is no solution in the second example.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<pair<long long, long long> > vp;
vector<long long> v;
set<long long> st;
long long ara[500005];
map<long long, long long> mp;
long long Set(long long N, long long pos) { return N = N | (1LL << pos); }
long long reset(long long N, long long pos) { return N = N & ~(1LL << pos); }
bool check(long long N, long long pos) { return (bool)(N & (1LL << pos)); }
vector<long long> e, o;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long n, i, j, p;
cin >> n;
if (n % 2 == 0)
cout << "NO\n";
else {
cout << "YES\n";
p = 1;
for (i = 0; i < 2 * n; i += 2) {
ara[i] = p;
p += 2;
}
p = 2;
for (i = n; i < 2 * n; i += 2) {
ara[i] = p;
p += 2;
}
for (i = 1; i < n; i += 2) {
ara[i] = p;
p += 2;
}
for (i = 0; i < 2 * n; i++) cout << ara[i] << " ";
cout << '\n';
}
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute:
* move north from cell (i, j) to (i, j + 1);
* move east from cell (i, j) to (i + 1, j);
* move south from cell (i, j) to (i, j - 1);
* move west from cell (i, j) to (i - 1, j);
* stay in cell (i, j).
The robot wants to reach cell (x, y) in as few commands as possible. However, he can't execute the same command two or more times in a row.
What is the minimum number of commands required to reach (x, y) from (0, 0)?
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of testcases.
Each of the next t lines contains two integers x and y (0 β€ x, y β€ 10^4) β the destination coordinates of the robot.
Output
For each testcase print a single integer β the minimum number of commands required for the robot to reach (x, y) from (0, 0) if no command is allowed to be executed two or more times in a row.
Example
Input
5
5 5
3 4
7 1
0 0
2 0
Output
10
7
13
0
3
Note
The explanations for the example test:
We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.
In the first test case, the robot can use the following sequence: NENENENENE.
In the second test case, the robot can use the following sequence: NENENEN.
In the third test case, the robot can use the following sequence: ESENENE0ENESE.
In the fourth test case, the robot doesn't need to go anywhere at all.
In the fifth test case, the robot can use the following sequence: E0E.
### Response
```cpp
#pragma GCC optimize("Ofast") //Comment optimisations for interactive problems (use endl)
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization ("unroll-loops")
#include<bits/stdc++.h>
using namespace std;
#define fastio ios:: sync_with_stdio(0);cin.tie(0);cout.tie(0);cout<<fixed;cout<<setprecision(10);
#define randomINIT mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
#define all(x) (x).begin(),(x).end()
#define mset(x,val) memset(x,val,sizeof(x))
#define endl "\n"
#define pb push_back
#define sym(s) s="#"+s+"#";
#define mp make_pair
#define s second
#define f first
#define dline cerr<<"///REACHED///\n";
#define debv(a) for(auto it: a)cout<<it<<" ";cout<<endl;
#define deb1(a) cout<<a<<endl;
#define deb2(a,b) cout<<a<<" "<<b<<endl;
#define deb3(a,b,c) cout<<a<<" "<<b<<" "<<c<<endl;
#define deb4(a,b,c,d) cout<<a<<" "<<b<<" "<<c<<" "<<d<<endl;
#define uniq(a) a.resize(unique(a.begin(), a.end()) - a.begin());
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<ll,ll> pll;
typedef vector<ll> vll;
typedef vector<pll> vpll;
const ll MOD = 1e+9+7;
const ll INF = 0x7f7f7f7f7f7f7f7f;
const int INFi = 0x7f7f7f7f;
const ll N = 3e+5+7;
vll adj[N];ll vis[N]={};
int dx8[]={0,1,1,1,0,-1,-1,-1}, dy8[]={1,1,0,-1,-1,-1,0,1};
int dx4[]={0,1,0,-1}, dy4[]={1,0,-1,0};
//<<-----Declare Variable Here------->>//
int t=1;
ll x,y;
//<<-----Implement Functions Here---->>//
//<<-----Start of Main--------------->>//
void MAIN(){
cin>>x>>y;if(x>y)swap(x,y);
if(x==y)cout<<2*x<<endl;
else cout<<2*y-1<<endl;
}
int main(){
fastio;randomINIT;
cin>>t;
while(t--){
MAIN();
}
#ifndef ONLINE_JUDGE
cout<<"\nTime Elapsed: " << 1.0*clock() / CLOCKS_PER_SEC << " sec\n";
#endif
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Snuke is going to open a contest named "AtCoder s Contest". Here, s is a string of length 1 or greater, where the first character is an uppercase English letter, and the second and subsequent characters are lowercase English letters.
Snuke has decided to abbreviate the name of the contest as "AxC". Here, x is the uppercase English letter at the beginning of s.
Given the name of the contest, print the abbreviation of the name.
Constraints
* The length of s is between 1 and 100, inclusive.
* The first character in s is an uppercase English letter.
* The second and subsequent characters in s are lowercase English letters.
Input
The input is given from Standard Input in the following format:
AtCoder s Contest
Output
Print the abbreviation of the name of the contest.
Examples
Input
AtCoder Beginner Contest
Output
ABC
Input
AtCoder Snuke Contest
Output
ASC
Input
AtCoder X Contest
Output
AXC
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
string a;
int main(){
cin>>a>>a;
cout<<'A'<<a[0]<<'C'<<endl;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string β concatenation of letters, which correspond to the stages.
There are n stages available. The rocket must contain exactly k of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' β 26 tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
Input
The first line of input contains two integers β n and k (1 β€ k β€ n β€ 50) β the number of available stages and the number of stages to use in the rocket.
The second line contains string s, which consists of exactly n lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.
Output
Print a single integer β the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.
Examples
Input
5 3
xyabd
Output
29
Input
7 4
problem
Output
34
Input
2 2
ab
Output
-1
Input
12 1
abaabbaaabbb
Output
1
Note
In the first example, the following rockets satisfy the condition:
* "adx" (weight is 1+4+24=29);
* "ady" (weight is 1+4+25=30);
* "bdx" (weight is 2+4+24=30);
* "bdy" (weight is 2+4+25=31).
Rocket "adx" has the minimal weight, so the answer is 29.
In the second example, target rocket is "belo". Its weight is 2+5+12+15=34.
In the third example, n=k=2, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
string s;
cin >> s;
vector<int> arr;
for (int i = 0; i < n; i++) {
int temp = s[i] - 96;
arr.push_back(temp);
}
sort(arr.begin(), arr.end());
int ctr = 1;
int sum = arr[0];
int t = 0;
for (int i = 1; i < n && ctr < k; i++) {
if (arr[i] - arr[t] >= 2) {
ctr++;
sum += arr[i];
t = i;
}
}
if (ctr != k)
cout << "-1";
else
cout << sum;
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
This is an interactive problem.
You are the head coach of a chess club. The club has 2n players, each player has some strength which can be represented by a number, and all those numbers are distinct. The strengths of the players are not known to you.
You need to select n players who would represent your club in the upcoming championship. Naturally, you want to select n players with the highest strengths.
You can organize matches between the players to do that. In every match, you pick two players, they play some games, and you learn which one of the two has higher strength. You can wait for the outcome of a match before deciding who will participate in the next one.
However, you do not want to know exactly how those n players compare between themselves, as that would make the championship itself less intriguing. More formally, you must reach a state where there is exactly one way to choose n players with the highest strengths that is consistent with the outcomes of the matches you organized, but there must be at least two possible orderings of those n players by strength that are consistent with the outcomes of the matches you organized.
Interaction
Your program has to process multiple test cases in one run. First, it should read the integer t (t β₯ 1) β the number of test cases. Then, it should process the test cases one by one.
In each test case, your program should start by reading the integer n (3 β€ n β€ 100) β the number of players to select out of 2n players. The sum of squares of the values of n over all test cases does not exceed 10 000.
Then your program can organize matches zero or more times. To organize a match, your program should print a match description formatted as ? i j β a question mark followed by two distinct numbers of players participating in the match. The players are numbered from 1 to 2n, inclusive. Remember to flush the output after printing the match description. Then your program should read the match outcome β it will be either the greater-than character (>), if the first player in the match description has higher strength, or the less-than character (<), if the second player in the match description has higher strength.
Your program can organize at most 4n^2 matches. After it is done organizing matches, it should print the exclamation mark (!) and continue to the next test case, or exit gracefully if this was the last test case. Remember to flush the output after printing the exclamation mark.
There must be exactly one way to choose n players with the highest strength that is consistent with the outcomes of the matches you organized, but there must be at least two possible orderings of those n players by their strength that are consistent with the outcomes of the matches you organized.
The judging program picks some distinct numbers as the strengths of all players before your program starts organizing matches and uses them to answer the requests.
Example
Input
2
3
>
<
>
<
>
>
3
<
<
<
>
>
Output
? 1 3
? 4 2
? 4 5
? 6 5
? 3 4
? 5 6
!
? 3 4
? 4 2
? 5 3
? 6 4
? 3 1
!
Note
In the example, the players in the first test case are sorted by strength in decreasing order. From the matches in the example output, we can deduce that players 1, 2, and 3 have the highest strength, but we do not know how the player 1 compares to the player 2.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using vi = std::vector<int>;
using vvi = std::vector<vi>;
using pii = std::pair<int, int>;
using vpii = std::vector<pii>;
struct Jury {
vi perm;
vpii edges;
int getN() { return ((int)(perm).size() - 1) / 2; }
Jury(int n) : perm(1 + 2 * n, 0) {
for (int i = 1; i <= 2 * n; i++) perm[i] = i;
}
char ask(int a, int b) {
if (perm[a] < perm[b]) {
edges.emplace_back(a, b);
return '<';
}
assert(perm[a] > perm[b]);
edges.emplace_back(b, a);
return '>';
}
bool next() {
edges.clear();
return std::next_permutation(perm.begin() + 1, perm.end());
}
bool check() {
int n = ((int)(perm).size() - 1) / 2;
vi a{0}, ind{0};
for (int i = n + 1; i <= 2 * n; i++) {
a.push_back(i);
}
for (int i = 1; i <= 2 * n; i++) {
if (perm[i] > n) ind.push_back(i);
}
std::sort((a).begin(), (a).end());
vvi answers;
vi backup = perm;
do {
vi save = perm;
for (int i = 1; i <= n; i++) {
perm[ind[i]] = a[i];
}
bool ok = true;
for (auto &[a, b] : edges) {
ok &= perm[a] < perm[b];
}
if (ok) {
answers.push_back(perm);
}
perm = save;
} while (std::next_permutation(a.begin() + 1, a.end()));
perm = backup;
if ((int)(answers).size() == 1) {
std::cout << "Wrong Answer on testcase";
for (int i = 1; i <= 2 * n; i++) {
std::cout << ' ' << perm[i];
}
std::cout << std::endl;
std::cout << "order of indexes";
for (int i = 1; i <= n; i++) {
std::cout << ' ' << ind[i];
}
std::cout << " is strictly defined!" << std::endl;
std::cout << "you determined that these condition holds:" << std::endl;
perm = answers.back();
for (auto &[a, b] : edges) {
std::cout << a << '<' << b << "( means p[" << a << "]=" << perm[a]
<< " < "
<< "p[" << b << "] = " << perm[b] << std::endl;
}
return false;
} else {
assert((int)(answers).size() > 1);
for (int i = 1; i <= 2 * n; i++) {
if (i > 1) std::cout << ' ';
std::cout << perm[i];
}
std::cout << ": OK" << std::endl;
return true;
}
}
} jury(3);
bool test;
int getN() {
if (test) return jury.getN();
int n;
cin >> n;
return n;
}
char ask(int a, int b) {
if (test) return jury.ask(a, b);
cout << "? " << a << ' ' << b << endl;
char res;
cin >> res;
return res;
}
void checkAnsw() {
if (test) {
if (jury.check()) {
if (!jury.next()) {
std::exit(0);
}
} else {
getchar();
getchar();
std::exit(0);
}
} else
cout << '!' << endl;
}
void bfs(vector<vector<int>> &g, vector<pii> &arr, int start, int less_ind) {
int n = g.size();
queue<int> q;
q.push(start);
while (!q.empty()) {
int cur = q.front();
q.pop();
if (!g[cur][less_ind]) {
++arr[cur].first;
++arr[less_ind].second;
g[less_ind][cur] = -1;
g[cur][less_ind] = 1;
for (int i = 0; i < n; ++i)
if (g[cur][i] == -1) q.push(i);
}
}
}
int32_t main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
test = false;
int t;
if (test)
t = 2e9;
else
cin >> t;
while (t--) {
int hn = getN();
int n = hn << 1;
vector<vector<int>> g(n, vector<int>(n));
vector<pii> arr;
vector<int> losers;
arr.reserve(n);
losers.reserve(hn);
for (int i = 1; i < n; i += 2) {
pii a = {1, 0}, b = {1, 0};
char res = ask(i, i + 1);
if (res == '<') {
losers.push_back(i);
++b.first;
++a.second;
g[i - 1][i] = -1;
g[i][i - 1] = 1;
} else {
losers.push_back(i + 1);
++a.first;
++b.second;
g[i][i - 1] = -1;
g[i - 1][i] = 1;
}
arr.push_back(a);
arr.push_back(b);
}
for (int i = 0; i < hn; ++i)
for (int j = i + 1; j < hn; ++j) {
int ind = losers[i];
int jnd = losers[j];
if (!g[ind - 1][jnd - 1]) {
char res = ask(ind, jnd);
int less_ind = ind - 1, start = jnd - 1;
if (res == '>') swap(less_ind, start);
bfs(g, arr, start, less_ind);
}
}
int found = 0;
while (found < hn) {
pii mina = {2e9, 2e9}, minb = {2e9, 2e9};
int mini = -1, minj = -1;
for (int i = 0; i < n; ++i) {
if (arr[i] < mina) {
swap(mina, minb);
swap(mini, minj);
mina = arr[i];
mini = i;
} else if (arr[i] < minb) {
minb = arr[i];
minj = i;
}
}
if (mina.first < minb.first) {
arr[mini] = {2e9, 2e9};
++found;
} else {
char res = ask(mini + 1, minj + 1);
int less_ind = mini, start = minj;
if (res == '>') swap(less_ind, start);
bfs(g, arr, start, less_ind);
}
}
checkAnsw();
}
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Vasya has recently found out what a digital root of a number is and he decided to share his knowledge with you.
Let's assume that S(n) is the sum of digits of number n, for example, S(4098) = 4 + 0 + 9 + 8 = 21. Then the digital root of number n equals to:
1. dr(n) = S(n), if S(n) < 10;
2. dr(n) = dr( S(n) ), if S(n) β₯ 10.
For example, dr(4098) = dr(21) = 3.
Vasya is afraid of large numbers, so the numbers he works with are at most 101000. For all such numbers, he has proved that dr(n) = S( S( S( S(n) ) ) ) (n β€ 101000).
Now Vasya wants to quickly find numbers with the given digital root. The problem is, he hasn't learned how to do that and he asked you to help him. You task is, given numbers k and d, find the number consisting of exactly k digits (the leading zeroes are not allowed), with digital root equal to d, or else state that such number does not exist.
Input
The first line contains two integers k and d (1 β€ k β€ 1000; 0 β€ d β€ 9).
Output
In a single line print either any number that meets the requirements (without the leading zeroes) or "No solution" (without the quotes), if the corresponding number does not exist.
The chosen number must consist of exactly k digits. We assume that number 0 doesn't contain any leading zeroes.
Examples
Input
4 4
Output
5881
Input
5 1
Output
36172
Input
1 0
Output
0
Note
For the first test sample dr(5881) = dr(22) = 4.
For the second test sample dr(36172) = dr(19) = dr(10) = 1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int k, d;
cin >> k >> d;
if (d == 0 && k != 1)
cout << "No solution";
else {
cout << d;
for (int i = 0; i < k - 1; i++) cout << "0";
}
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Yet another education system reform has been carried out in Berland recently. The innovations are as follows:
An academic year now consists of n days. Each day pupils study exactly one of m subjects, besides, each subject is studied for no more than one day. After the lessons of the i-th subject pupils get the home task that contains no less than ai and no more than bi exercises. Besides, each subject has a special attribute, the complexity (ci). A school can make its own timetable, considering the following conditions are satisfied:
* the timetable should contain the subjects in the order of the complexity's strict increasing;
* each day, except for the first one, the task should contain either k times more exercises, or more by k compared to the previous day (more formally: let's call the number of home task exercises in the i-th day as xi, then for each i (1 < i β€ n): either xi = k + xi - 1 or xi = kΒ·xi - 1 must be true);
* the total number of exercises in all home tasks should be maximal possible.
All limitations are separately set for each school.
It turned out that in many cases ai and bi reach 1016 (however, as the Berland Minister of Education is famous for his love to half-measures, the value of bi - ai doesn't exceed 100). That also happened in the Berland School β256. Nevertheless, you as the school's principal still have to work out the timetable for the next academic year...
Input
The first line contains three integers n, m, k (1 β€ n β€ m β€ 50, 1 β€ k β€ 100) which represent the number of days in an academic year, the number of subjects and the k parameter correspondingly. Each of the following m lines contains the description of a subject as three integers ai, bi, ci (1 β€ ai β€ bi β€ 1016, bi - ai β€ 100, 1 β€ ci β€ 100) β two limitations to the number of exercises on the i-th subject and the complexity of the i-th subject, correspondingly. Distinct subjects can have the same complexity. The subjects are numbered with integers from 1 to m.
Please do not use the %lld specificator to read or write 64-bit numbers in Π‘++. It is preferred to use the cin stream or the %I64d specificator.
Output
If no valid solution exists, print the single word "NO" (without the quotes). Otherwise, the first line should contain the word "YES" (without the quotes) and the next n lines should contain any timetable that satisfies all the conditions. The i + 1-th line should contain two positive integers: the number of the subject to study on the i-th day and the number of home task exercises given for this subject. The timetable should contain exactly n subjects.
Examples
Input
4 5 2
1 10 1
1 10 2
1 10 3
1 20 4
1 100 5
Output
YES
2 8
3 10
4 20
5 40
Input
3 4 3
1 3 1
2 4 4
2 3 3
2 2 2
Output
NO
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long INF = 0x3f3f3f3f;
void Open() {}
long long n, m, k;
long long dp[55][55][55][110];
struct info {
long long a, b, c, id;
bool operator<(const info& o) const { return c < o.c; }
} sub[110];
int paidx[110][110][110][3];
long long pat[110][110];
long long ansidx[110];
long long anst[110];
int main() {
Open();
memset(paidx, -1, sizeof paidx);
scanf("%I64d%I64d%I64d", &n, &m, &k);
for (long long i = 0; i < m; i++)
scanf("%I64d%I64d%I64d", &sub[(i)].a, &sub[(i)].b, &sub[(i)].c),
sub[(i)].b -= sub[(i)].a, sub[(i)].id = i;
sort(sub, sub + m);
for (long long i = 0; i <= sub[(0)].b; i++) dp[0][1][0][i] = i + sub[(0)].a;
for (long long i = 1; i < m; i++)
for (long long j = 1; j <= min(i + 1, n); j++) {
for (long long s = j - 1; s < i; s++)
for (long long t = 0; t <= sub[(s)].b; t++)
dp[i][j][s][t] = dp[i - 1][j][s][t];
if (j == 1) {
for (long long t = 0; t <= sub[(i)].b; t++)
dp[i][j][i][t] = t + sub[(i)].a;
continue;
}
for (long long t = 0; t <= sub[(i)].b; t++)
for (long long s = j - 2; s < i; s++) {
if (sub[(s)].c >= sub[(i)].c) continue;
if (sub[(i)].a + t - sub[(s)].a - k >= 0 &&
sub[(i)].a + t - sub[(s)].a - k <= sub[(s)].b &&
dp[i][j][i][t] <
dp[i - 1][j - 1][s][sub[(i)].a + t - sub[(s)].a - k] +
sub[(i)].a + t &&
dp[i - 1][j - 1][s][sub[(i)].a + t - sub[(s)].a - k] != 0) {
dp[i][j][i][t] =
dp[i - 1][j - 1][s][sub[(i)].a + t - sub[(s)].a - k] +
sub[(i)].a + t;
paidx[i][j][t][0] = j - 1;
paidx[i][j][t][1] = s;
paidx[i][j][t][2] = sub[(i)].a + t - sub[(s)].a - k;
}
if ((sub[(i)].a + t) % k == 0 &&
(sub[(i)].a + t) / k - sub[(s)].a >= 0 &&
(sub[(i)].a + t) / k - sub[(s)].a <= sub[(s)].b &&
dp[i][j][i][t] <
dp[i - 1][j - 1][s][(sub[(i)].a + t) / k - sub[(s)].a] +
sub[(i)].a + t &&
dp[i - 1][j - 1][s][(sub[(i)].a + t) / k - sub[(s)].a] != 0) {
dp[i][j][i][t] =
dp[i - 1][j - 1][s][(sub[(i)].a + t) / k - sub[(s)].a] +
sub[(i)].a + t;
paidx[i][j][t][0] = j - 1;
paidx[i][j][t][1] = s;
paidx[i][j][t][2] = (sub[(i)].a + t) / k - sub[(s)].a;
}
}
}
long long ans = 0;
long long tmp = n, preidx, preans;
pair<long long, long long> pre;
for (long long i = 0; i < m; i++)
for (long long j = 0; j <= sub[(i)].b; j++)
if (ans < dp[m - 1][n][i][j])
ans = dp[m - 1][n][i][j], pre = pair<long long, long long>(i, j),
preidx = n, preans = j + sub[(i)].a;
if (ans == 0) {
cout << "NO" << endl;
return 0;
}
cout << "YES" << endl;
while (pre != pair<long long, long long>(-1, -1)) {
ansidx[--tmp] = pre.first;
anst[tmp] = pre.second + sub[(pre.first)].a;
pair<long long, long long> pretmp = pre;
int tmppreidx = preidx;
preidx = paidx[pretmp.first][tmppreidx][pretmp.second][0];
pre.first = paidx[pretmp.first][tmppreidx][pretmp.second][1];
pre.second = paidx[pretmp.first][tmppreidx][pretmp.second][2];
}
for (long long i = 0; i < n; i++)
printf("%I64d %I64d\n", sub[(ansidx[i])].id + 1, anst[i]);
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Curry making
As the ACM-ICPC domestic qualifying is approaching, you who wanted to put more effort into practice decided to participate in a competitive programming camp held at a friend's house. Participants decided to prepare their own meals.
On the first night of the training camp, the participants finished the day's practice and began preparing dinner. Not only in competitive programming, but also in self-catering, you are often said to be a "professional", and you have spared time because you have finished making the menu for your charge in a blink of an eye. Therefore, I decided to help other people make curry.
Now, there is a curry made by mixing R0 [g] roux with W0 [L] water. There is one type of roux used this time, and each roux is R [g]. Ru has a sufficient stockpile. When you use this roux, you think that the curry with a concentration of C [g / L] is the most delicious, so add some roux and water to this curry appropriately to make the concentration C [g / L]. I want to. Here, the concentration of curry in which roux R0 [g] is dissolved in water W0 [L] is R0 / W0 [g / L], and X roux of R [g] and water Y [L] are added to this curry. ] Is added, the concentration becomes (R0 + XR) / (W0 + Y) [g / L]. Although there are a lot of roux, you thought that it was not good to use too much, so you decided to make a curry with a concentration of C [g / L] by reducing the number of roux to be added as much as possible.
When making a curry with a concentration of C [g / L] by properly adding either roux, water, or both to a curry with a concentration of R0 / W0 [g / L], the number of roux X to be added Find the minimum value.
However, please note the following points regarding the curry making this time.
* Number of roux to be added The value of X must be an integer greater than or equal to 0. In other words, it is not possible to add only 1/3 of the roux.
* The value of the volume Y of water to be added can be a real number greater than or equal to 0, and does not have to be an integer.
* In some cases, it is possible to make curry with a concentration of C without adding either roux, water, or both.
* Since a sufficient amount of roux and water is secured, it is good that the situation that the curry with concentration C cannot be made due to lack of roux and water does not occur.
Input
The input consists of multiple datasets. Each dataset consists of one line and is expressed in the following format.
> R0 W0 C R
Here, R0, W0, C, and R are the mass of roux already dissolved in the curry that is being made [g], the volume of water contained in the curry [L], and the concentration of the curry you want to make [g / L]. , Represents the mass [g] per roux. All of these values ββare integers between 1 and 100. The end of the input is indicated by a line of four zeros separated by blanks.
Output
For each dataset, one line is the minimum number of roux that needs to be added to make a curry with a concentration of C from a fake curry that is a mixture of W0 [L] water and R0 [g] roux. To output. Do not output the amount of water to add.
Note that due to input constraints, the minimum number of roux that is the answer for each dataset is guaranteed to be within the range represented by a 32-bit signed integer.
Sample Input
10 5 3 4
2 5 2 3
91 13 7 62
10 1 3 5
20 100 2 20
2 14 7 1
0 0 0 0
Output for Sample Input
2
3
0
0
9
96
Example
Input
10 5 3 4
2 5 2 3
91 13 7 62
10 1 3 5
20 100 2 20
2 14 7 1
0 0 0 0
Output
2
3
0
0
9
96
### Response
```cpp
#include <iostream>
#define llint long long
using namespace std;
llint r0, w0, c, r;
int main(void)
{
while(1){
cin >> r0 >> w0 >> c >> r;
if(r0 == 0 && w0 == 0 && c == 0 && r == 0) break;
if(c*w0-r0+r-1 <= 0) cout << 0 << endl;
else cout << (c*w0-r0+r-1)/r << endl;
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the photos in the booklet in order. He now wants to sell some "special edition" photobooks, each with one extra photo inserted anywhere in the book. He wants to make as many distinct photobooks as possible, so he can make more money. He asks Haruhi, how many distinct photobooks can he make by inserting one extra photo into the photobook he already has?
Please help Haruhi solve this problem.
Input
The first line of input will be a single string s (1 β€ |s| β€ 20). String s consists only of lowercase English letters.
Output
Output a single integer equal to the number of distinct photobooks Kyoya Ootori can make.
Examples
Input
a
Output
51
Input
hi
Output
76
Note
In the first case, we can make 'ab','ac',...,'az','ba','ca',...,'za', and 'aa', producing a total of 51 distinct photo booklets.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
#pragma comment(linker, "/STACK:268435456")
#pragma warning(disable : 4996)
int n, i, j, a[1111];
char c[28];
string s, d, e;
map<string, int> m;
scanf("%d", &n);
gets(c);
gets(c);
s = c;
for (i = 0; i < s.length(); i++) {
for (j = 0; j <= i; j++) {
d.push_back(s[j]);
}
for (j = int('a'); j <= int('z'); j++) {
e += d;
e.push_back(char(j));
for (int k = i + 1; k < s.length(); k++) e.push_back(s[k]);
m[e] = 1;
e.clear();
}
d.clear();
}
for (j = int('a'); j <= int('z'); j++) {
e.push_back(char(j));
e += s;
m[e] = 1;
e.clear();
}
printf("%d", m.size());
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
A frog is about to return to the burrow. The burrow is D centimeters ahead of the frog, and the frog goes straight toward the burrow. There are only two actions that a frog can do:
* Large jump (go forward L centimeters)
* Small jump (go 1 cm forward)
The frog aims to just land in the burrow without jumping over it.
Create a program that asks how many times a frog needs to jump to return to its burrow.
Input
The input is given in the following format.
DL
The input is one line, given the distance D (1 β€ D β€ 10000) to the burrow and the distance L (2 β€ L β€ 10000) for the frog to travel on a large jump.
Output
Print on one line how many times the frog needs to jump.
Examples
Input
10 5
Output
2
Input
7 4
Output
4
### Response
```cpp
#include <iostream>
#include <vector>
using namespace std;
int main(void){
int d,l;
cin>>d>>l;
cout<<d/l+d%l<<endl;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
In the game Lizard Era: Beginning the protagonist will travel with three companions: Lynn, Meliana and Worrigan. Overall the game has n mandatory quests. To perform each of them, you need to take exactly two companions.
The attitude of each of the companions to the hero is an integer. Initially, the attitude of each of them to the hero of neutral and equal to 0. As the hero completes quests, he makes actions that change the attitude of the companions, whom he took to perform this task, in positive or negative direction.
Tell us what companions the hero needs to choose to make their attitude equal after completing all the quests. If this can be done in several ways, choose the one in which the value of resulting attitude is greatest possible.
Input
The first line contains positive integer n (1 β€ n β€ 25) β the number of important tasks.
Next n lines contain the descriptions of the tasks β the i-th line contains three integers li, mi, wi β the values by which the attitude of Lynn, Meliana and Worrigan respectively will change towards the hero if the hero takes them on the i-th task. All the numbers in the input are integers and do not exceed 107 in absolute value.
Output
If there is no solution, print in the first line "Impossible".
Otherwise, print n lines, two characters is each line β in the i-th line print the first letters of the companions' names that hero should take to complete the i-th task ('L' for Lynn, 'M' for Meliana, 'W' for Worrigan). Print the letters in any order, if there are multiple solutions, print any of them.
Examples
Input
3
1 0 0
0 1 0
0 0 1
Output
LM
MW
MW
Input
7
0 8 9
5 9 -2
6 -8 -7
9 4 5
-4 -9 9
-4 5 2
-6 8 -7
Output
LM
MW
LM
LW
MW
LM
LW
Input
2
1 0 0
1 1 0
Output
Impossible
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 25;
const int maxhfsize = 1600000;
struct Result {
int d[2];
int mask;
};
inline bool operator<(const Result& a, const Result& b) {
return a.d[0] == b.d[0] ? a.d[1] < b.d[1] : a.d[0] < b.d[0];
}
inline bool operator==(const Result& a, const Result& b) {
return a.d[0] == b.d[0] && a.d[1] == b.d[1];
}
int deltas[maxn][3];
int firstSize, secondSize;
Result firstHalf[maxhfsize], secondHalf[maxhfsize];
void makeHalf(Result* out, int& sz, int begin, int end) {
int k = end - begin;
int maxMask = 1;
for (int i = 0; i < k; ++i) maxMask *= 3;
sz = 0;
for (int mask = 0; mask < maxMask; ++mask) {
Result& here = out[sz++];
here.mask = mask;
int t = mask;
for (int i = begin; i < end; ++i) {
int bit = t % 3;
t /= 3;
if (bit != 0) {
here.d[0] -= deltas[i][0];
here.d[1] -= deltas[i][0];
}
if (bit != 1) here.d[0] += deltas[i][1];
if (bit != 2) here.d[1] += deltas[i][2];
}
}
sort(out, out + sz);
sz = unique(out, out + sz) - out;
}
int n;
int score(int begin, int end, int mask) {
int ret = 0;
for (int i = begin; i < end; ++i) {
int bit = mask % 3;
mask /= 3;
if (bit) ret += deltas[i][0];
}
return ret;
}
void out(int begin, int end, int mask) {
int sum[3] = {0, 0, 0};
for (int i = begin; i < end; ++i) {
int bit = mask % 3;
mask /= 3;
for (int j = 0; j < 3; ++j)
if (j != bit) {
sum[j] += deltas[i][j];
cout << "LMW"[j];
}
cout << '\n';
}
42;
}
int main() {
ios_base::sync_with_stdio(false);
cin >> n;
for (int i = 0; i < n; ++i)
for (int j = 0; j < 3; ++j) cin >> deltas[i][j];
int pivot = n / 2;
makeHalf(firstHalf, firstSize, 0, pivot);
makeHalf(secondHalf, secondSize, pivot, n);
int notMuch = -100000000;
int ansF = -1, ansS = -1, ans = notMuch;
for (int i = 0; i < secondSize; ++i) {
Result a = secondHalf[i];
Result need;
need.d[0] = -a.d[0];
need.d[1] = -a.d[1];
int fst = -1;
if (pivot != 0 || need.d[0] || need.d[1]) {
auto it = lower_bound(firstHalf, firstHalf + firstSize, need);
if (it == firstHalf + firstSize || !(*it == need)) continue;
fst = it->mask;
}
int here = score(0, pivot, fst) + score(pivot, n, a.mask);
if (here > ans) {
ans = here;
ansF = fst;
ansS = a.mask;
}
}
if (ans == notMuch)
cout << "Impossible\n";
else {
out(0, pivot, ansF);
out(pivot, n, ansS);
}
42;
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
At University A, there were many mistakes in entering IDs.
Therefore, University A decided to issue a new ID to prevent typos.
There is a way to check if the new ID is correct to prevent typos.
γ» Calculate the sum of all digits.
γ» However, the number of even-numbered digits is doubled, with the rightmost digit as the first digit.
-When the number becomes 10 or more by doubling, the number obtained by adding the 1st digit and the 10th digit is used as the digit number.
γ» If the sum is divisible by 10, the ID is correct, otherwise it is incorrect.
As an example, check the ID 53579.
Since the sum of all digits is calculated,
5 + 3 + 5 + 7 + 9
However, since the number of even-numbered digits is doubled,
5 + 6 + 5 + 14 + 9
When the number becomes 10 or more by doubling, the number obtained by adding the ones digit and the tens digit is the digit number.
5 + 6 + 5 + (1 + 4) + 9
From the above, the total sum is 30. Since 30 is divisible by 10, 53579 is the correct ID.
Mr. B is a college student at University A and was issued a new ID, but he forgot some digits of the ID.
However, I succeeded in narrowing down some candidates as to what kind of numbers will be included in the forgotten part.
Your job is to find out how many correct combinations of B's ββIDs are available.
Input
The input is given in the following format.
n
ID
m
a0 a1 ... am-1
n is the number of digits in the ID.
Each digit of the ID contains a number from 0 to 9 or the letter'*' to indicate that it is a forgotten digit.
m is the number of candidate numbers in the'*'.
ai is a candidate for numbers in'*'.
Input meets the following constraints
1 β€ n β€ 100,000
1 β€ m β€ 10
0 β€ ai β€ 9
Number of 1 β€'*' β€ 7
Output
Output the answer value on one line
Examples
Input
5
5*57*
2
3 9
Output
1
Input
15
2***9*2*6*1199*
9
0 1 2 3 4 6 7 8 9
Output
478297
### Response
```cpp
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <ctime>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <cstring>
#include <numeric>
#include <cassert>
using namespace std;
static const double EPS = 1e-10;
typedef long long ll;
#define rep(i,n) for(int i=0;i<n;i++)
#define rev(i,n) for(int i=n-1;i>=0;i--)
#define all(a) a.begin(),a.end()
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)
#define SS stringstream
#define DBG1(a) rep(_X,sz(a)){printf("%d ",a[_X]);}puts("");
#define DBG2(a) rep(_X,sz(a)){rep(_Y,sz(a[_X]))printf("%d ",a[_X][_Y]);puts("");}
#define bitcount(b) __builtin_popcount(b)
#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define delete(a,n) a.erase(remove(all(a),n),a.end())
template<typename T, typename S> vector<T>& operator<<(vector<T>& a, S b) { a.push_back(b); return a; }
template<typename T> void operator>>(vector<T>& a, int b) {while(b--)if(!a.empty())a.pop_back();}
bool isprime(int n){ if(n<2)return false; for(int i=2;i*i<=n;i++)if(n%i==0)return false; return true;}
ll b_pow(ll x,ll n){return n ? b_pow(x*x,n/2)*(n%2?x:1) : 1ll;}
string itos(int n){stringstream ss;ss << n;return ss.str();}
vector<int> pos;
vector<int> item;
int anss = 0;
string s;
long long dp[100010][10];
int cost(int a,int b){
return !b ? a : (a*2) / 10 + (a*2)%10;
}
int main(){
int n,m;
cin >> n;
cin >> s;
reverse(s.begin(),s.end());
cin >> m;
for(int i = 0 ; i < m ; i++){
int a;
cin >> a;
item.push_back(a);
}
dp[0][0] = 1;
for(int i = 0 ; i < n ; i++){
for(int j = 0 ; j < 10 ; j++){
if( s[i] == '*' ){
for(int k = 0 ; k < item.size() ; k++)
dp[i+1][(j+cost(item[k],i%2))%10] += dp[i][j];
}else{
dp[i+1][(j+cost(s[i]-'0',i%2))%10] += dp[i][j];
}
}
}
cout << dp[n][0] << endl;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an nΓ m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1β€ n,mβ€ 1000) β the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
### Response
```cpp
#include <bits/stdc++.h>
int n, m, t, la, ans = 0;
bool ok, hori_ok = 0, vert_ok = 0;
int dx[4] = {-1, 0, 0, 1}, dy[4] = {0, -1, 1, 0};
char ch[1002][1002];
bool vis[1002][1002] = {};
template <class T>
void read(T &x) {
x = 0;
int f = 0;
char ch = getchar();
while (ch < '0' || ch > '9') f |= (ch == '-'), ch = getchar();
while (ch >= '0' && ch <= '9')
x = (x << 3) + (x << 1) + (ch ^ 48), ch = getchar();
x = f ? -x : x;
return;
}
inline bool check_hori() {
for (int i = 1; i <= n; ++i) {
t = 0, ok = 0;
for (int j = 1; j <= m; ++j)
if (ch[i][j] == '#') {
ok = 1, la = j;
break;
}
if (!ok) hori_ok = 1;
for (int j = la; j <= m; ++j)
if (ch[i][j] == '#') {
++t;
if (t > 1) {
printf("-1");
return 1;
}
while (j < m && ch[i][j + 1] == '#') ++j;
}
}
return 0;
}
inline bool check_vert() {
for (int j = 1; j <= m; ++j) {
t = 0, ok = 0;
for (int i = 1; i <= n; ++i)
if (ch[i][j] == '#') {
ok = 1, la = i;
break;
}
if (!ok) vert_ok = 1;
for (int i = la; i <= n; ++i)
if (ch[i][j] == '#') {
++t;
if (t > 1) {
printf("-1");
return 1;
}
while (i < n && ch[i + 1][j] == '#') ++i;
}
}
return 0;
}
inline void dfs(int x, int y) {
vis[x][y] = 1;
for (int i = 0, x1, y1; i < 4; ++i) {
x1 = x + dx[i], y1 = y + dy[i];
if (ch[x1][y1] == '#' && !vis[x1][y1]) dfs(x1, y1);
}
}
int main() {
read(n), read(m);
for (int i = 1; i <= n; ++i) scanf("%s", ch[i] + 1);
if (check_hori()) return 0;
if (check_vert()) return 0;
if ((hori_ok && !vert_ok) || (!hori_ok && vert_ok)) {
printf("-1");
return 0;
}
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j)
if (ch[i][j] == '#' && !vis[i][j]) ++ans, dfs(i, j);
printf("%d", ans);
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
A new innovative ticketing systems for public transport is introduced in Bytesburg. Now there is a single travel card for all transport. To make a trip a passenger scan his card and then he is charged according to the fare.
The fare is constructed in the following manner. There are three types of tickets:
1. a ticket for one trip costs 20 byteland rubles,
2. a ticket for 90 minutes costs 50 byteland rubles,
3. a ticket for one day (1440 minutes) costs 120 byteland rubles.
Note that a ticket for x minutes activated at time t can be used for trips started in time range from t to t + x - 1, inclusive. Assume that all trips take exactly one minute.
To simplify the choice for the passenger, the system automatically chooses the optimal tickets. After each trip starts, the system analyses all the previous trips and the current trip and chooses a set of tickets for these trips with a minimum total cost. Let the minimum total cost of tickets to cover all trips from the first to the current is a, and the total sum charged before is b. Then the system charges the passenger the sum a - b.
You have to write a program that, for given trips made by a passenger, calculates the sum the passenger is charged after each trip.
Input
The first line of input contains integer number n (1 β€ n β€ 105) β the number of trips made by passenger.
Each of the following n lines contains the time of trip ti (0 β€ ti β€ 109), measured in minutes from the time of starting the system. All ti are different, given in ascending order, i. e. ti + 1 > ti holds for all 1 β€ i < n.
Output
Output n integers. For each trip, print the sum the passenger is charged after it.
Examples
Input
3
10
20
30
Output
20
20
10
Input
10
13
45
46
60
103
115
126
150
256
516
Output
20
20
10
0
20
0
0
20
20
10
Note
In the first example, the system works as follows: for the first and second trips it is cheaper to pay for two one-trip tickets, so each time 20 rubles is charged, after the third trip the system understands that it would be cheaper to buy a ticket for 90 minutes. This ticket costs 50 rubles, and the passenger had already paid 40 rubles, so it is necessary to charge 10 rubles only.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, k, a, b, i = 2, m[200005];
set<pair<int, int> > s;
pair<int, int> p;
int main() {
ios::sync_with_stdio(0);
cin >> n >> a;
s.insert({a, 1});
m[1] = 20;
s.insert({10e9 + 1, 0});
cout << 20 << "\n";
while (i <= n) {
cin >> a;
m[i] = m[i - 1] + 20;
p = *--s.lower_bound({a - 89, 0});
m[i] = min(m[i], m[p.second] + 50);
p = *--s.lower_bound({a - 1439, 0});
m[i] = min(m[i], m[p.second] + 120);
cout << m[i] - m[i - 1] << "\n";
s.insert({a, i});
i++;
}
i = 0;
cout << endl;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
I have a sequence defined as follows:
* All even-numbered terms are equal to the previous term multiplied by 2.
* All odd-numbered terms are equal to the previous term divided by 3.
Create a program that reads the first term a of this sequence and outputs the sum s (10) from the first term to the tenth term.
Input
The input consists of multiple test cases. For each test case, a real number a (1.0 β€ a β€ 10.0) representing the first term of the sequence is given in one row.
The number of test cases does not exceed 50.
Output
Print s (10) on one line for each test case.
The output may contain an error of 0.000001 or less.
Example
Input
1.0
2.0
3.0
Output
7.81481481
15.62962963
23.44444444
### Response
```cpp
#include<iostream>
#include <iomanip>
using namespace std;
int main()
{
double s;
for(;cin>>s;)
{
double sum=s;
for(int i=2;i<=10;i++)
{
if(i%2==0)
s*=2;
else
s/=3;
sum+=s;
}
cout<< fixed << setprecision(8)<<sum<<endl;
}
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left).
<image>
Alice and Bob play dice. Alice has built a tower from n dice. We know that in this tower the adjacent dice contact with faces with distinct numbers. Bob wants to uniquely identify the numbers written on the faces of all dice, from which the tower is built. Unfortunately, Bob is looking at the tower from the face, and so he does not see all the numbers on the faces. Bob sees the number on the top of the tower and the numbers on the two adjacent sides (on the right side of the picture shown what Bob sees).
Help Bob, tell whether it is possible to uniquely identify the numbers on the faces of all the dice in the tower, or not.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of dice in the tower.
The second line contains an integer x (1 β€ x β€ 6) β the number Bob sees at the top of the tower. Next n lines contain two space-separated integers each: the i-th line contains numbers ai, bi (1 β€ ai, bi β€ 6; ai β bi) β the numbers Bob sees on the two sidelong faces of the i-th dice in the tower.
Consider the dice in the tower indexed from top to bottom from 1 to n. That is, the topmost dice has index 1 (the dice whose top face Bob can see). It is guaranteed that it is possible to make a dice tower that will look as described in the input.
Output
Print "YES" (without the quotes), if it is possible to to uniquely identify the numbers on the faces of all the dice in the tower. If it is impossible, print "NO" (without the quotes).
Examples
Input
3
6
3 2
5 4
2 4
Output
YES
Input
3
3
2 6
4 1
5 3
Output
NO
### Response
```cpp
#include <bits/stdc++.h>
int main() {
int n, x;
scanf("%d\n%d\n", &n, &x);
int temp1, temp2;
for (int i = 0; i < n; ++i) {
scanf("%d%d", &temp1, &temp2);
if (temp1 == x || temp1 == 7 - x) {
puts("NO");
return 0;
}
if (temp2 == x || temp2 == 7 - x) {
puts("NO");
return 0;
}
}
puts("YES");
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
This is the hard version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.
You are given a binary table of size n Γ m. This table consists of symbols 0 and 1.
You can make such operation: select 3 different cells that belong to one 2 Γ 2 square and change the symbols in these cells (change 0 to 1 and 1 to 0).
Your task is to make all symbols in the table equal to 0. You are allowed to make at most nm operations. You don't need to minimize the number of operations.
It can be proved, that it is always possible.
Input
The first line contains a single integer t (1 β€ t β€ 5000) β the number of test cases. The next lines contain descriptions of test cases.
The first line of the description of each test case contains two integers n, m (2 β€ n, m β€ 100).
Each of the next n lines contains a binary string of length m, describing the symbols of the next row of the table.
It is guaranteed, that the sum of nm for all test cases does not exceed 20000.
Output
For each test case print the integer k (0 β€ k β€ nm) β the number of operations.
In the each of the next k lines print 6 integers x_1, y_1, x_2, y_2, x_3, y_3 (1 β€ x_1, x_2, x_3 β€ n, 1 β€ y_1, y_2, y_3 β€ m) describing the next operation. This operation will be made with three cells (x_1, y_1), (x_2, y_2), (x_3, y_3). These three cells should be different. These three cells should belong to some 2 Γ 2 square.
Example
Input
5
2 2
10
11
3 3
011
101
110
4 4
1111
0110
0110
1111
5 5
01011
11001
00010
11011
10000
2 3
011
101
Output
1
1 1 2 1 2 2
2
2 1 3 1 3 2
1 2 1 3 2 3
4
1 1 1 2 2 2
1 3 1 4 2 3
3 2 4 1 4 2
3 3 4 3 4 4
4
1 2 2 1 2 2
1 4 1 5 2 5
4 1 4 2 5 1
4 4 4 5 3 4
2
1 3 2 2 2 3
1 2 2 1 2 2
Note
In the first test case, it is possible to make only one operation with cells (1, 1), (2, 1), (2, 2). After that, all symbols will be equal to 0.
In the second test case:
* operation with cells (2, 1), (3, 1), (3, 2). After it the table will be:
011
001
000
* operation with cells (1, 2), (1, 3), (2, 3). After it the table will be:
000
000
000
In the fifth test case:
* operation with cells (1, 3), (2, 2), (2, 3). After it the table will be:
010
110
* operation with cells (1, 2), (2, 1), (2, 2). After it the table will be:
000
000
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 105;
char s[N];
int T, n, m, a[N][N];
vector<pair<int, int>> ans;
inline void flip(int x, int y) {
ans.push_back(make_pair(x, y));
a[x][y] = (a[x][y] + 1) % 2;
}
void solve2m2() {
int _a[3][3];
vector<pair<int, int>> w;
w.push_back(make_pair(1, 1));
w.push_back(make_pair(1, 2));
w.push_back(make_pair(2, 1));
w.push_back(make_pair(1, 2));
w.push_back(make_pair(1, 1));
w.push_back(make_pair(2, 2));
w.push_back(make_pair(2, 1));
w.push_back(make_pair(1, 1));
w.push_back(make_pair(2, 2));
w.push_back(make_pair(2, 2));
w.push_back(make_pair(1, 2));
w.push_back(make_pair(2, 1));
for (int i = 1; i <= 2; ++i)
for (int j = 1; j <= 2; ++j) _a[i][j] = a[n + i - 2][m + j - 2];
auto fp = [&](int x, int y) { _a[x][y] = (_a[x][y] + 1) % 2; };
auto ck = [&]() {
for (int i = 1; i <= 2; ++i) {
for (int j = 1; j <= 2; ++j) {
if (_a[i][j]) return false;
}
}
return true;
};
for (int i = 0; i < (1 << 4); ++i) {
for (int j = 0; j < 4; ++j) {
if (i & (1 << j)) {
fp(w[j * 3].first, w[j * 3].second);
fp(w[j * 3 + 1].first, w[j * 3 + 1].second);
fp(w[j * 3 + 2].first, w[j * 3 + 2].second);
}
}
if (ck()) {
for (int j = 0; j < 4; ++j) {
if (i & (1 << j)) {
flip(w[j * 3].first + n - 2, w[j * 3].second + m - 2);
flip(w[j * 3 + 1].first + n - 2, w[j * 3 + 1].second + m - 2);
flip(w[j * 3 + 2].first + n - 2, w[j * 3 + 2].second + m - 2);
}
}
return;
}
for (int j = 0; j < 4; ++j) {
if (i & (1 << j)) {
fp(w[j * 3].first, w[j * 3].second);
fp(w[j * 3 + 1].first, w[j * 3 + 1].second);
fp(w[j * 3 + 2].first, w[j * 3 + 2].second);
}
}
}
}
int main() {
scanf("%d", &T);
while (T--) {
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; ++i) {
scanf("%s", s + 1);
for (int j = 1; j <= m; ++j) a[i][j] = s[j] - '0';
}
vector<pair<int, int>>().swap(ans);
for (int i = 1; i <= n - 2; ++i) {
for (int j = 1; j <= m; ++j) {
if (j == m) {
if (a[i][j]) flip(i, j), flip(i + 1, j), flip(i + 1, j - 1);
} else {
if (a[i][j]) flip(i, j), flip(i + 1, j), flip(i, j + 1);
}
}
}
for (int j = 1; j <= m - 2; ++j) {
if (a[n - 1][j]) flip(n - 1, j), flip(n - 1, j + 1), flip(n, j + 1);
if (a[n][j]) flip(n, j), flip(n, j + 1), flip(n - 1, j + 1);
}
solve2m2();
printf("%d\n", ans.size() / 3);
for (int i = 0; i < ans.size(); ++i) {
printf("%d %d\n", ans[i].first, ans[i].second);
}
}
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Ksenia has ordinary pan scales and several weights of an equal mass. Ksenia has already put some weights on the scales, while other weights are untouched. Ksenia is now wondering whether it is possible to put all the remaining weights on the scales so that the scales were in equilibrium.
The scales is in equilibrium if the total sum of weights on the left pan is equal to the total sum of weights on the right pan.
Input
The first line has a non-empty sequence of characters describing the scales. In this sequence, an uppercase English letter indicates a weight, and the symbol "|" indicates the delimiter (the character occurs in the sequence exactly once). All weights that are recorded in the sequence before the delimiter are initially on the left pan of the scale. All weights that are recorded in the sequence after the delimiter are initially on the right pan of the scale.
The second line contains a non-empty sequence containing uppercase English letters. Each letter indicates a weight which is not used yet.
It is guaranteed that all the English letters in the input data are different. It is guaranteed that the input does not contain any extra characters.
Output
If you cannot put all the weights on the scales so that the scales were in equilibrium, print string "Impossible". Otherwise, print the description of the resulting scales, copy the format of the input.
If there are multiple answers, print any of them.
Examples
Input
AC|T
L
Output
AC|TL
Input
|ABC
XYZ
Output
XYZ|ABC
Input
W|T
F
Output
Impossible
Input
ABC|
D
Output
Impossible
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string s1 = "", s2 = "", s;
long long i, found = 0;
cin >> s;
for (i = 0; i < s.length(); i++) {
if (s[i] == '|')
found = 1;
else {
if (found)
s2 += s[i];
else
s1 += s[i];
}
}
cin >> s;
for (i = 0; i < s.length(); i++) {
if (s1.length() < s2.length()) {
s1 += s[i];
} else
s2 += s[i];
}
if (s1.length() != s2.length())
cout << "Impossible\n";
else {
cout << s1 << "|" << s2 << "\n";
}
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor.
There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest's 1 coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in k days. He decided to spend these last days with helping poor people.
After taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too.
Your task is to find the difference between richest and poorest persons wealth after k days. Note that the choosing at random among richest and poorest doesn't affect the answer.
Input
The first line of the input contains two integers n and k (1 β€ n β€ 500 000, 0 β€ k β€ 109) β the number of citizens in Kekoland and the number of days left till Robin Hood's retirement.
The second line contains n integers, the i-th of them is ci (1 β€ ci β€ 109) β initial wealth of the i-th person.
Output
Print a single line containing the difference between richest and poorest peoples wealth.
Examples
Input
4 1
1 1 4 2
Output
2
Input
3 1
2 2 2
Output
0
Note
Lets look at how wealth changes through day in the first sample.
1. [1, 1, 4, 2]
2. [2, 1, 3, 2] or [1, 2, 3, 2]
So the answer is 3 - 1 = 2
In second sample wealth will remain the same for each person.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long v[500100];
int main() {
ios::sync_with_stdio(false);
long long n, k;
cin >> n >> k;
long long sum = 0;
for (int i = 1; i <= n; i++) {
cin >> v[i];
sum += v[i];
}
sort(v + 1, v + n + 1);
long long left = 1, right = n;
long long nr1 = 0, nr2 = 0;
while (v[left] == v[1]) {
nr1++;
left++;
}
left--;
while (v[right] == v[n]) {
nr2++;
right--;
}
right++;
long long need1 = (v[left + 1] - v[left]) * nr1;
long long need2 = (v[right] - v[right - 1]) * nr2;
long long v1 = 0, v2 = 0;
if (k == 0) {
cout << v[n] - v[1] << '\n';
return 0;
}
if (v[left] == v[right]) {
cout << "0\n";
return 0;
}
int maxx = 1;
if (sum % n == 0) maxx = 0;
while (1) {
if (left == right - 1 || (k < need1 - v1 && k < need2 - v2)) {
cout << max((long long)maxx,
(v[right] - (k + v2) / nr2) - (v[left] + (k + v1) / nr1));
return 0;
} else {
if (need1 - v1 < need2 - v2) {
v2 += (need1 - v1);
left++;
nr1++;
while (v[left + 1] == v[left]) {
left++;
nr1++;
}
k -= (need1 - v1);
need1 = (v[left + 1] - v[left]) * nr1;
if (v2 == need2 && left != right - 1) {
right--;
nr2++;
while (v[right - 1] == v[right]) {
right--;
nr2++;
}
need2 = (v[right] - v[right - 1]) * nr2;
if (left == right) right++;
if (left + 1 != right) v2 = 0;
}
v1 = 0;
} else {
v1 += (need2 - v2);
right--;
nr2++;
while (v[right - 1] == v[right] && right - 1 > left) {
right--;
nr2++;
}
k -= (need2 - v2);
need2 = (v[right] - v[right - 1]) * nr2;
if (v1 == need1 && left != right - 1) {
left++;
nr1++;
while (v[left + 1] == v[left] && left + 1 < right) {
left++;
nr1++;
}
need1 = (v[left + 1] - v[left]) * nr1;
if (left == right) left--;
if (left + 1 != right) v1 = 0;
}
v2 = 0;
}
}
}
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Consider the following equation:
<image> where sign [a] represents the integer part of number a.
Let's find all integer z (z > 0), for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers x and y (x, y > 0), for which the given above equation holds.
Let's write out all such z in the increasing order: z1, z2, z3, and so on (zi < zi + 1). Your task is: given the number n, find the number zn.
Input
The first line contains a single integer n (1 β€ n β€ 40).
Output
Print a single integer β the number zn modulo 1000000007 (109 + 7). It is guaranteed that the answer exists.
Examples
Input
1
Output
1
Input
2
Output
3
Input
3
Output
15
### Response
```cpp
#include <bits/stdc++.h>
inline unsigned int getuint() {
char w = getchar();
while (w < '0' || '9' < w) w = getchar();
unsigned int ans = 0;
for (; '0' <= w && w <= '9'; w = getchar()) ans = ans * 10 + w - '0';
return ans;
}
const int mod = 1000000007;
inline long long bin(int y) {
long long x = 2, ans = 1;
for (; y; y >>= 1, x = x * x % mod)
if (y & 1) ans = ans * x % mod;
return ans;
}
const int a[] = {
233, 2, 3, 5, 7, 13, 17, 19,
31, 61, 89, 107, 127, 521, 607, 1279,
2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213,
19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091,
756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917,
20996011, 24036583, 25964951, 30402457, 32582657};
int main() {
int n = getuint();
printf("%I64d\n", (bin(a[n] - 1) + mod - 1) % mod);
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
This morning, Roman woke up and opened the browser with n opened tabs numbered from 1 to n. There are two kinds of tabs: those with the information required for the test and those with social network sites. Roman decided that there are too many tabs open so he wants to close some of them.
He decided to accomplish this by closing every k-th (2 β€ k β€ n - 1) tab. Only then he will decide whether he wants to study for the test or to chat on the social networks. Formally, Roman will choose one tab (let its number be b) and then close all tabs with numbers c = b + i β
k that satisfy the following condition: 1 β€ c β€ n and i is an integer (it may be positive, negative or zero).
For example, if k = 3, n = 14 and Roman chooses b = 8, then he will close tabs with numbers 2, 5, 8, 11 and 14.
After closing the tabs Roman will calculate the amount of remaining tabs with the information for the test (let's denote it e) and the amount of remaining social network tabs (s). Help Roman to calculate the maximal absolute value of the difference of those values |e - s| so that it would be easy to decide what to do next.
Input
The first line contains two integers n and k (2 β€ k < n β€ 100) β the amount of tabs opened currently and the distance between the tabs closed.
The second line consists of n integers, each of them equal either to 1 or to -1. The i-th integer denotes the type of the i-th tab: if it is equal to 1, this tab contains information for the test, and if it is equal to -1, it's a social network tab.
Output
Output a single integer β the maximum absolute difference between the amounts of remaining tabs of different types |e - s|.
Examples
Input
4 2
1 1 -1 1
Output
2
Input
14 3
-1 1 -1 -1 1 -1 -1 1 -1 -1 1 -1 -1 1
Output
9
Note
In the first example we can choose b = 1 or b = 3. We will delete then one tab of each type and the remaining tabs are then all contain test information. Thus, e = 2 and s = 0 and |e - s| = 2.
In the second example, on the contrary, we can leave opened only tabs that have social networks opened in them.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long fastPow(long long b, long long p) {
if (p == 0) return 1;
long long st = fastPow(b, p / 2);
st *= st;
if (p % 2 == 1) {
st *= b;
}
return st;
}
bool isPrime(long long n) {
if (n < 2) return false;
if (n % 2 == 0) return false;
for (long long i = 3; i * i <= n; i += 2) {
if (n % i == 0) return false;
}
return true;
}
long long gcd(long long a, long long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
int main() {
long long n, k;
cin >> n >> k;
long long arr[n];
long long test = 0;
long long social = 0;
for (long long i = 0; i < n; i++) {
cin >> arr[i];
if (arr[i] == -1)
social++;
else
test++;
}
long long res = 0;
bool del[n];
memset(del, true, sizeof del);
for (long long i = 0; i < n; i++) {
social = test = 0;
for (long long j = i; j < n; j += k) {
del[j] = false;
}
for (long long j = i; j >= 0; j -= k) {
del[j] = false;
}
for (long long j = 0; j < n; j++) {
if (del[j]) {
if (arr[j] == -1)
social++;
else
test++;
}
}
res = max(res, abs(social - test));
memset(del, true, sizeof del);
}
cout << res;
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
You are given an array a_1, a_2, ..., a_n where all a_i are integers and greater than 0.
In one operation, you can choose two different indices i and j (1 β€ i, j β€ n). If gcd(a_i, a_j) is equal to the minimum element of the whole array a, you can swap a_i and a_j. gcd(x, y) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x and y.
Now you'd like to make a non-decreasing using the operation any number of times (possibly zero). Determine if you can do this.
An array a is non-decreasing if and only if a_1 β€ a_2 β€ β¦ β€ a_n.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains one integer n (1 β€ n β€ 10^5) β the length of array a.
The second line of each test case contains n positive integers a_1, a_2, β¦ a_n (1 β€ a_i β€ 10^9) β the array itself.
It is guaranteed that the sum of n over all test cases doesn't exceed 10^5.
Output
For each test case, output "YES" if it is possible to make the array a non-decreasing using the described operation, or "NO" if it is impossible to do so.
Example
Input
4
1
8
6
4 3 6 6 2 9
4
4 5 6 7
5
7 5 2 2 4
Output
YES
YES
YES
NO
Note
In the first and third sample, the array is already non-decreasing.
In the second sample, we can swap a_1 and a_3 first, and swap a_1 and a_5 second to make the array non-decreasing.
In the forth sample, we cannot the array non-decreasing using the operation.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[100002];
int b[100002];
int main() {
int t;
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> t;
while (t--) {
int n;
cin >> n;
int mn = INT_MAX;
for (int i = 0; i < n; i++) {
cin >> a[i];
b[i] = a[i];
if (mn > a[i]) {
mn = a[i];
}
}
sort(b, b + n);
bool is = true;
for (int i = 0; i < n; i++) {
if (a[i] != b[i] and a[i] % mn == 0 and b[i] % mn == 0)
continue;
else if (a[i] != b[i]) {
is = false;
break;
}
}
if (is)
puts("YES");
else
puts("NO");
}
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Breaking news from zombie neurology! It turns out that β contrary to previous beliefs β every zombie is born with a single brain, and only later it evolves into a complicated brain structure. In fact, whenever a zombie consumes a brain, a new brain appears in its nervous system and gets immediately connected to one of the already existing brains using a single brain connector. Researchers are now interested in monitoring the brain latency of a zombie. Your task is to write a program which, given a history of evolution of a zombie's nervous system, computes its brain latency at every stage.
Input
The first line of the input contains one number n β the number of brains in the final nervous system (2 β€ n β€ 200000). In the second line a history of zombie's nervous system evolution is given. For convenience, we number all the brains by 1, 2, ..., n in the same order as they appear in the nervous system (the zombie is born with a single brain, number 1, and subsequently brains 2, 3, ..., n are added). The second line contains n - 1 space-separated numbers p2, p3, ..., pn, meaning that after a new brain k is added to the system, it gets connected to a parent-brain <image>.
Output
Output n - 1 space-separated numbers β the brain latencies after the brain number k is added, for k = 2, 3, ..., n.
Example
Input
6
1
2
2
1
5
Output
1 2 2 3 4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using namespace std;
const int rmax = 20;
vector<vector<int> > g;
vector<vector<int> > parent;
vector<int> t_in, t_out;
int timer;
void dfs(int v) {
t_in[v] = timer++;
for (int to : g[v]) {
dfs(to);
}
t_out[v] = timer++;
}
bool ancestor(int u, int v) {
return t_in[u] <= t_in[v] && t_out[u] >= t_out[v];
}
int help(int u, int w) {
if (u == w) {
return 0;
}
int ans = 0;
for (int r = rmax - 1; r >= 0; --r) {
if (!ancestor(parent[u][r], w)) {
ans += (1 << r);
u = parent[u][r];
}
}
return ans + 1;
}
int path_len(int u, int v) {
if (ancestor(u, v)) {
return help(v, u);
}
int old_u = u;
for (int r = rmax - 1; r >= 0; --r) {
if (!ancestor(parent[u][r], v)) {
u = parent[u][r];
}
}
int w = parent[u][0];
return help(old_u, w) + help(v, w);
}
int main() {
int n;
cin >> n;
g.resize(n);
parent.resize(n);
t_in.resize(n), t_out.resize(n);
for (int i = 0; i < n; ++i) {
parent[i].resize(rmax);
}
parent[0][0] = 0;
for (int i = 1; i < n; ++i) {
int p;
cin >> p;
--p;
g[p].push_back(i);
parent[i][0] = p;
}
dfs(0);
for (int r = 1; r < rmax; ++r) {
for (int i = 0; i < n; ++i) {
int t = parent[i][r - 1];
parent[i][r] = parent[t][r - 1];
}
}
int u = 0, v = 1;
cout << "1 ";
int diam = 1;
for (int i = 2; i < n; ++i) {
int x = path_len(i, u);
int y = path_len(i, v);
if (x > diam) {
diam = x;
v = i;
}
if (y > diam) {
diam = y;
u = i;
}
cout << diam << " ";
}
cout << "\n";
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
Polycarpus enjoys studying Berland hieroglyphs. Once Polycarp got hold of two ancient Berland pictures, on each of which was drawn a circle of hieroglyphs. We know that no hieroglyph occurs twice in either the first or the second circle (but in can occur once in each of them).
Polycarpus wants to save these pictures on his laptop, but the problem is, laptops do not allow to write hieroglyphs circles. So Polycarp had to break each circle and write down all of its hieroglyphs in a clockwise order in one line. A line obtained from the first circle will be called a, and the line obtained from the second one will be called b.
There are quite many ways to break hieroglyphic circles, so Polycarpus chooses the method, that makes the length of the largest substring of string a, which occurs as a subsequence in string b, maximum.
Help Polycarpus β find the maximum possible length of the desired substring (subsequence) if the first and the second circles are broken optimally.
The length of string s is the number of characters in it. If we denote the length of string s as |s|, we can write the string as s = s1s2... s|s|.
A substring of s is a non-empty string x = s[a... b] = sasa + 1... sb (1 β€ a β€ b β€ |s|). For example, "code" and "force" are substrings of "codeforces", while "coders" is not.
A subsequence of s is a non-empty string y = s[p1p2... p|y|] = sp1sp2... sp|y| (1 β€ p1 < p2 < ... < p|y| β€ |s|). For example, "coders" is a subsequence of "codeforces".
Input
The first line contains two integers la and lb (1 β€ la, lb β€ 1000000) β the number of hieroglyphs in the first and second circles, respectively.
Below, due to difficulties with encoding of Berland hieroglyphs, they are given as integers from 1 to 106.
The second line contains la integers β the hieroglyphs in the first picture, in the clockwise order, starting with one of them.
The third line contains lb integers β the hieroglyphs in the second picture, in the clockwise order, starting with one of them.
It is guaranteed that the first circle doesn't contain a hieroglyph, which occurs twice. The second circle also has this property.
Output
Print a single number β the maximum length of the common substring and subsequence. If at any way of breaking the circles it does not exist, print 0.
Examples
Input
5 4
1 2 3 4 5
1 3 5 6
Output
2
Input
4 6
1 3 5 2
1 2 3 4 5 6
Output
3
Input
3 3
1 2 3
3 2 1
Output
2
Note
In the first test Polycarpus picks a string that consists of hieroglyphs 5 and 1, and in the second sample β from hieroglyphs 1, 3 and 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000002;
int a[maxn * 2], v[maxn];
int main() {
int n, m, tmp;
scanf("%d %d", &n, &m);
for (int i = 0; i < n; ++i) scanf("%d", &a[i]), a[i + n] = a[i];
for (int i = 0; i < m; ++i) scanf("%d", &tmp), v[tmp] = i + 1;
int p = 0, t = 0, ans = 0;
for (int i = 0; i < n; ++i) {
if (p <= i || i >= t) p = i, t = 0;
if (t == 0) {
while (p - i + 1 <= n && v[a[p + 1]] > v[a[p]] &&
v[a[p + 1]] - v[a[i]] + 1 <= m)
++p;
if (p - i + 1 <= n && v[a[p + 1]] > 0 && v[a[p + 1]] < v[a[p]] &&
v[a[p + 1]] - v[a[i]] + 1 <= 0)
t = p + 1, p++;
}
if (t > 0) {
while (p - i + 1 <= n && v[a[p + 1]] > v[a[p]] &&
v[a[p + 1]] - v[a[i]] + 1 <= 0)
++p;
}
if (v[a[i]] > 0) ans = max(ans, p - i + 1);
}
cout << ans;
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?
You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.
Each digit is allowed to occur in the number the same number of times it occurs in the set.
Input
A single line contains a single integer n (1 β€ n β€ 100000) β the number of digits in the set. The second line contains n digits, the digits are separated by a single space.
Output
On a single line print the answer to the problem. If such number does not exist, then you should print -1.
Examples
Input
1
0
Output
0
Input
11
3 4 5 4 5 3 5 3 4 4 0
Output
5554443330
Input
8
3 2 5 1 5 2 2 3
Output
-1
Note
In the first sample there is only one number you can make β 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
static const int maxn = 100010;
int n;
int digit[10];
int main() {
while (~scanf("%d", &n)) {
memset(digit, false, sizeof digit);
int sum = 0;
for (int i = 0; i < n; ++i) {
int t;
scanf("%d", &t);
sum += t;
digit[t]++;
}
if (digit[0] == 0) {
printf("-1\n");
continue;
}
if (sum == 0) {
printf("0\n");
continue;
}
int r = sum % 3;
if (!r) {
for (int i = 9; i >= 0; --i) {
for (int j = 0; j < digit[i]; ++j) {
printf("%d", i);
}
}
printf("\n");
continue;
}
bool solved = false;
int ind = -1;
for (int i = 0; i < 9; ++i) {
if (i % 3 == r && digit[i]) {
digit[i]--;
sum -= i;
ind = i;
solved = true;
break;
}
}
if (solved) {
if (sum == 0) {
printf("0\n");
} else {
for (int i = 9; i >= 0; --i) {
for (int j = 0; j < digit[i]; ++j) {
printf("%d", i);
}
}
printf("\n");
}
continue;
}
r = r == 1 ? 2 : 1;
int cnt = 0;
for (int i = 0; i < 9; ++i) {
if (i % 3 == r && digit[i]) {
digit[i]--;
sum -= i;
ind = i;
cnt++;
break;
}
}
for (int i = 0; i < 9; ++i) {
if (i % 3 == r && digit[i]) {
digit[i]--;
sum -= i;
ind = i;
cnt++;
break;
}
}
if (cnt == 2) {
solved = true;
}
if (solved) {
if (sum == 0) {
printf("0\n");
} else {
for (int i = 9; i >= 0; --i) {
for (int j = 0; j < digit[i]; ++j) {
printf("%d", i);
}
}
printf("\n");
}
} else {
printf("0\n");
}
}
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Find places where a string P is found within a text T. Print all indices of T where P found. The indices of T start with 0.
Constraints
* 1 β€ length of T β€ 1000
* 1 β€ length of P β€ 1000
* The input consists of alphabetical characters and digits
Input
In the first line, a text T is given. In the second line, a string P is given.
Examples
Input
aabaaa
aa
Output
0
3
4
Input
xyzz
yz
Output
1
Input
abc
xyz
Output
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string t, p; cin >> t >> p;
int ans = -1;
while (true) {
ans = t.find(p, ans + 1);
if (ans == -1) break;
cout << ans << endl;
}
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Write a program which reads an integer n and prints the factorial of n. You can assume that n β€ 20.
Input
An integer n (1 β€ n β€ 20) in a line.
Output
Print the factorial of n in a line.
Example
Input
5
Output
120
### Response
```cpp
#include <iostream>
using namespace std;
int main() {
int n;
long long ans=1;
cin >> n;
for(int i=2; i<=n; i++) ans*=i;
cout << ans <<endl;
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
You are given a sequence of n integers a1, a2, ..., an.
Determine a real number x such that the weakness of the sequence a1 - x, a2 - x, ..., an - x is as small as possible.
The weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) of a sequence.
The poorness of a segment is defined as the absolute value of sum of the elements of segment.
Input
The first line contains one integer n (1 β€ n β€ 200 000), the length of a sequence.
The second line contains n integers a1, a2, ..., an (|ai| β€ 10 000).
Output
Output a real number denoting the minimum possible weakness of a1 - x, a2 - x, ..., an - x. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6.
Examples
Input
3
1 2 3
Output
1.000000000000000
Input
4
1 2 3 4
Output
2.000000000000000
Input
10
1 10 2 9 3 8 4 7 5 6
Output
4.500000000000000
Note
For the first case, the optimal value of x is 2 so the sequence becomes - 1, 0, 1 and the max poorness occurs at the segment "-1" or segment "1". The poorness value (answer) equals to 1 in this case.
For the second sample the optimal value of x is 2.5 so the sequence becomes - 1.5, - 0.5, 0.5, 1.5 and the max poorness occurs on segment "-1.5 -0.5" or "0.5 1.5". The poorness value (answer) equals to 2 in this case.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void Rd(int &res) {
res = 0;
char p;
int k = 1;
while (p = getchar(), !(p >= '0' && p <= '9') && p != '-')
;
if (p == '-') k = -1, p = getchar();
do {
res = (res << 1) + (res << 3) + (p ^ 48);
} while (p = getchar(), p >= '0');
res *= k;
}
int a[200005], n;
bool gre(double a, double b) { return a - b > 0.0000000001; }
double calc(double pl) {
double Mx = 0, Mi = 0, Mxsum = 0, Misum = 0, bas = 0;
for (int i = 1; i <= n; i++) {
if (gre(bas, Mxsum)) Mxsum = bas;
if (gre(bas, Misum)) Misum = bas;
Mxsum += a[i] - pl;
Misum -= a[i] - pl;
if (gre(Mxsum, Mx)) Mx = Mxsum;
if (gre(Misum, Mi)) Mi = Misum;
}
if (gre(Mi, Mx))
return -1;
else
return Mx;
}
int main() {
Rd(n);
for (int i = 1; i <= n; i++) Rd(a[i]);
double l = -10000, r = 10000, ans = 0;
for (int i = 1; i <= 100; i++) {
double mid = (l + r) / 2;
double lp = calc(mid);
if (gre(lp, 0))
ans = lp, l = mid;
else
r = mid;
}
printf("%.15lf\n", ans);
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.
According to the schedule, a student can take the exam for the i-th subject on the day number ai. However, Valera has made an arrangement with each teacher and the teacher of the i-th subject allowed him to take an exam before the schedule time on day bi (bi < ai). Thus, Valera can take an exam for the i-th subject either on day ai, or on day bi. All the teachers put the record of the exam in the student's record book on the day of the actual exam and write down the date of the mark as number ai.
Valera believes that it would be rather strange if the entries in the record book did not go in the order of non-decreasing date. Therefore Valera asks you to help him. Find the minimum possible value of the day when Valera can take the final exam if he takes exams so that all the records in his record book go in the order of non-decreasing date.
Input
The first line contains a single positive integer n (1 β€ n β€ 5000) β the number of exams Valera will take.
Each of the next n lines contains two positive space-separated integers ai and bi (1 β€ bi < ai β€ 109) β the date of the exam in the schedule and the early date of passing the i-th exam, correspondingly.
Output
Print a single integer β the minimum possible number of the day when Valera can take the last exam if he takes all the exams so that all the records in his record book go in the order of non-decreasing date.
Examples
Input
3
5 2
3 1
4 2
Output
2
Input
3
6 1
5 2
4 3
Output
6
Note
In the first sample Valera first takes an exam in the second subject on the first day (the teacher writes down the schedule date that is 3). On the next day he takes an exam in the third subject (the teacher writes down the schedule date, 4), then he takes an exam in the first subject (the teacher writes down the mark with date 5). Thus, Valera takes the last exam on the second day and the dates will go in the non-decreasing order: 3, 4, 5.
In the second sample Valera first takes an exam in the third subject on the fourth day. Then he takes an exam in the second subject on the fifth day. After that on the sixth day Valera takes an exam in the first subject.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool isprime(long long int x) {
bool is = true;
for (long long int i = 2; i <= (long long int)sqrt(x) + 1; i++) {
if (x % i == 0 && i != x) {
is = false;
break;
}
}
return is;
}
void solve();
int sum(long long int n) {
long long int s = 0, d;
while (n != 0) {
d = n % 10;
s += d;
n /= 10;
}
return s;
}
long long int adt(long long int x) {
long long int f = 1;
while (x != 0) {
f *= x;
x--;
}
return f;
}
bool comp(char s1, char s2) { return s1 > s2; }
bool distinct(long long int x) {
set<int> s;
int d = 0;
while (x != 0) {
d++;
s.insert(x % 10);
x = x / 10;
}
return (d == (int)s.size());
}
long long int add(long long int x) {
long long int d = 13, e = -1;
while (x != 0) {
d = min(d, x % 10);
e = max(e, x % 10);
x = x / 10;
}
return d * e;
}
int main() {
cout << fixed;
int t = 1;
while (t--) solve();
return 0;
}
long long int f(long long int x) { return (3 * x * x + x) / 2; }
long long int solve(long long int st, long long int l, long long int r) {
long long int guess = (l + r) / 2;
if (f(guess) <= st && f(guess + 1) > st) return guess;
if (f(guess) <= st) return solve(st, guess + 1, r);
if (f(guess) > st) return solve(st, l, guess - 1);
return 0;
}
struct info {
long long int act;
long long int bon;
};
bool compo(info a, info b) {
if (a.act < b.act)
return true;
else {
if (a.act > b.act)
return false;
else
return (a.bon < b.bon);
}
}
void solve() {
long long int n, i;
cin >> n;
info arr[n];
for (i = 0; i < n; i++) cin >> arr[i].act >> arr[i].bon;
sort(arr, arr + n, compo);
long long int prev = arr[0].bon;
for (i = 1; i < n; i++) {
if (arr[i].bon >= prev)
prev = arr[i].bon;
else
prev = arr[i].act;
}
cout << prev << endl;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
You are given a rectangular grid with n rows and m columns. The cell located on the i-th row from the top and the j-th column from the left has a value a_{ij} written in it.
You can perform the following operation any number of times (possibly zero):
* Choose any two adjacent cells and multiply the values in them by -1. Two cells are called adjacent if they share a side.
Note that you can use a cell more than once in different operations.
You are interested in X, the sum of all the numbers in the grid.
What is the maximum X you can achieve with these operations?
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 100). Description of the test cases follows.
The first line of each test case contains two integers n,m (2 β€ n, m β€ 10).
The following n lines contain m integers each, the j-th element in the i-th line is a_{ij} (-100β€ a_{ij}β€ 100).
Output
For each testcase, print one integer X, the maximum possible sum of all the values in the grid after applying the operation as many times as you want.
Example
Input
2
2 2
-1 1
1 1
3 4
0 -1 -2 -3
-1 -2 -3 -4
-2 -3 -4 -5
Output
2
30
Note
In the first test case, there will always be at least one -1, so the answer is 2.
In the second test case, we can use the operation six times to elements adjacent horizontally and get all numbers to be non-negative. So the answer is: 2Γ 1 + 3Γ2 + 3Γ 3 + 2Γ 4 + 1Γ 5 = 30.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long int mod = 1e9 + 7;
const long long int inf = 2e9 + 5;
double PI = 3.14159265358979323846;
void solve() {
int n, m;
cin >> n >> m;
int a[n][m];
int cnt = 0;
int sum = 0;
int minElement = inf;
vector<int> v;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> a[i][j];
minElement = min(minElement, abs(a[i][j]));
v.push_back(abs(a[i][j]));
if (a[i][j] < 0) cnt++;
}
}
sort((v).begin(), (v).end());
if (cnt & 1) v[0] = -v[0];
sum = accumulate((v).begin(), (v).end(), 0);
cout << sum << "\n";
}
int32_t main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T;
cin >> T;
while (T--) solve();
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Haiku is a genre of Japanese traditional poetry.
A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syllables). A haiku masterpiece contains a description of a moment in those three phrases. Every word is important in a small poem, which is why haiku are rich with symbols. Each word has a special meaning, a special role. The main principle of haiku is to say much using a few words.
To simplify the matter, in the given problem we will consider that the number of syllable in the phrase is equal to the number of vowel letters there. Only the following letters are regarded as vowel letters: "a", "e", "i", "o" and "u".
Three phases from a certain poem are given. Determine whether it is haiku or not.
Input
The input data consists of three lines. The length of each line is between 1 and 100, inclusive. The i-th line contains the i-th phrase of the poem. Each phrase consists of one or more words, which are separated by one or more spaces. A word is a non-empty sequence of lowercase Latin letters. Leading and/or trailing spaces in phrases are allowed. Every phrase has at least one non-space character. See the example for clarification.
Output
Print "YES" (without the quotes) if the poem is a haiku. Otherwise, print "NO" (also without the quotes).
Examples
Input
on codeforces
beta round is running
a rustling of keys
Output
YES
Input
how many gallons
of edo s rain did you drink
cuckoo
Output
NO
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 2;
const int M = 1e5 + 2;
const int mod = 1e9 + 7;
const int inf = 1e9;
const long long INF = 1e16;
void data() {}
template <typename T>
void scerr(T nums) {
for (auto it : nums) cerr << it << " | ";
cerr << "\n";
}
int n, ans, f = 1;
string s1, s2, s3;
int main() {
data();
scanf("%d", &n);
getline(cin, s1);
getline(cin, s2);
getline(cin, s3);
for (auto l : s1)
if (l == 'a' || l == 'e' || l == 'i' || l == 'o' || l == 'u') ans++;
if (ans != 5) f = 0;
ans = 0;
for (auto l : s2)
if (l == 'a' || l == 'e' || l == 'i' || l == 'o' || l == 'u') ans++;
if (ans != 7) f = 0;
ans = 0;
for (auto l : s3)
if (l == 'a' || l == 'e' || l == 'i' || l == 'o' || l == 'u') ans++;
if (ans != 5) f = 0;
if (f)
printf("YES");
else
printf("NO");
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them.
Constraints
* $1 \leq n \leq 100,000$
* $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$
* Two parallel segments never overlap or touch.
* The number of intersections $\leq 1,000,000$
Input
In the first line, the number of segments $n$ is given. In the following $n$ lines, the $i$-th segment is given by coordinates of its end points in the following format:
$x_1 \; y_1 \; x_2 \; y_2$
The coordinates are given in integers.
Output
Print the number of intersections in a line.
Example
Input
6
2 2 2 5
1 3 5 3
4 1 4 4
5 2 7 2
6 1 6 3
6 5 6 7
Output
3
### Response
```cpp
#include<bits/stdc++.h>
#define rep(i,n)for(int i=0;i<(n);i++)
using namespace std;
int bit[200000];
vector<int>v;
void add(int k, int x) {
while (k <= v.size()) {
bit[k] += x;
k += k&-k;
}
}
int sum(int k) {
int res = 0;
while (k) {
res += bit[k];
k -= k&-k;
}
return res;
}
int a[100000], b[100000], c[100000], d[100000];
struct st {
int y, t, id;
};
int main() {
int n; scanf("%d", &n);
vector<st>xs;
rep(i, n) {
scanf("%d%d%d%d", &a[i], &b[i], &c[i], &d[i]);
if (a[i] > c[i])swap(a[i], c[i]);
if (b[i] > d[i])swap(b[i], d[i]);
v.push_back(a[i]); v.push_back(c[i]);
if (a[i] == c[i]) {
xs.push_back({ b[i],0,i });
xs.push_back({ d[i],2,i });
}
else xs.push_back({ b[i],1,i });
}
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
sort(xs.begin(), xs.end(), [](st&a, st&b) {
if (a.y == b.y)return a.t < b.t;
return a.y < b.y;
});
rep(i, n) {
a[i] = lower_bound(v.begin(), v.end(), a[i]) - v.begin() + 1;
c[i] = lower_bound(v.begin(), v.end(), c[i]) - v.begin() + 1;
}
int ans = 0;
for (st&p : xs) {
if (p.t == 0)add(a[p.id], 1);
else if (p.t == 1) {
ans += sum(c[p.id]);
if (a[p.id])ans -= sum(a[p.id] - 1);
}
else add(a[p.id], -1);
}
printf("%d\n", ans);
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Andrewid the Android is a galaxy-known detective. Now he is preparing a defense against a possible attack by hackers on a major computer network.
In this network are n vertices, some pairs of vertices are connected by m undirected channels. It is planned to transfer q important messages via this network, the i-th of which must be sent from vertex si to vertex di via one or more channels, perhaps through some intermediate vertices.
To protect against attacks a special algorithm was developed. Unfortunately it can be applied only to the network containing directed channels. Therefore, as new channels can't be created, it was decided for each of the existing undirected channels to enable them to transmit data only in one of the two directions.
Your task is to determine whether it is possible so to choose the direction for each channel so that each of the q messages could be successfully transmitted.
Input
The first line contains three integers n, m and q (1 β€ n, m, q β€ 2Β·105) β the number of nodes, channels and important messages.
Next m lines contain two integers each, vi and ui (1 β€ vi, ui β€ n, vi β ui), that means that between nodes vi and ui is a channel. Between a pair of nodes can exist more than one channel.
Next q lines contain two integers si and di (1 β€ si, di β€ n, si β di) β the numbers of the nodes of the source and destination of the corresponding message.
It is not guaranteed that in it initially possible to transmit all the messages.
Output
If a solution exists, print on a single line "Yes" (without the quotes). Otherwise, print "No" (without the quotes).
Examples
Input
4 4 2
1 2
1 3
2 3
3 4
1 3
4 2
Output
Yes
Input
3 2 2
1 2
3 2
1 3
2 1
Output
No
Input
3 3 2
1 2
1 2
3 2
1 3
2 1
Output
Yes
Note
In the first sample test you can assign directions, for example, as follows: 1 β 2, 1 β 3, 3 β 2, 4 β 3. Then the path for for the first message will be 1 β 3, and for the second one β 4 β 3 β 2.
In the third sample test you can assign directions, for example, as follows: 1 β 2, 2 β 1, 2 β 3. Then the path for the first message will be 1 β 2 β 3, and for the second one β 2 β 1.
### Response
```cpp
#include <bits/stdc++.h>
using std::min;
int n, m, q;
int h[(200000 + 5)], nh[(200000 + 5)], tot = 1;
struct Edge {
int to, next;
} e[(200000 + 5) * 4];
int dfn[(200000 + 5)], low[(200000 + 5)], cnt;
bool bri[(200000 + 5) * 2];
int bel[(200000 + 5)], dcc;
struct Node {
int fa, dep, size, son, top, cnt0, cnt1;
} a[(200000 + 5)];
template <typename T>
void Read(T &x) {
x = 0;
char ch = getchar();
while (!isdigit(ch)) ch = getchar();
while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
}
void Add_Edge(int u, int v) { e[++tot].to = v, e[tot].next = h[u], h[u] = tot; }
void Add_New_Edge(int u, int v) {
e[++tot].to = v, e[tot].next = nh[u], nh[u] = tot;
}
void Tarjan(int u, int ed) {
dfn[u] = low[u] = ++cnt;
for (int i = h[u], v = e[i].to; i; i = e[i].next, v = e[i].to) {
if (!dfn[v]) {
Tarjan(v, i ^ 1);
low[u] = min(low[u], low[v]);
if (dfn[u] < low[v]) bri[i] = bri[i ^ 1] = 1;
} else if (i != ed)
low[u] = min(low[u], dfn[v]);
}
}
void DFS1(int u) {
for (int i = h[u], v = e[i].to; i; i = e[i].next, v = e[i].to)
if (!bri[i] && !bel[v]) bel[v] = dcc, DFS1(v);
}
void DFS2(int u) {
a[u].size = 1;
for (int i = nh[u], v = e[i].to; i; i = e[i].next, v = e[i].to) {
if (v == a[u].fa) continue;
a[v].fa = u;
a[v].dep = a[u].dep + 1;
DFS2(v);
a[u].size += a[v].size;
if (a[a[u].son].size < a[v].size) a[u].son = v;
}
}
void DFS3(int u, int tp) {
a[u].top = tp;
if (!a[u].son) return;
DFS3(a[u].son, tp);
for (int i = nh[u], v = e[i].to; i; i = e[i].next, v = e[i].to)
if (v != a[u].fa && v != a[u].son) DFS3(v, v);
}
int LCA(int u, int v) {
while (a[u].top != a[v].top && u && v) {
if (a[a[u].top].dep > a[a[v].top].dep)
u = a[a[u].top].fa;
else
v = a[a[v].top].fa;
}
if (!u || !v) return 0;
if (a[u].dep < a[v].dep) return u;
return v;
}
void DFS4(int u) {
for (int i = nh[u], v = e[i].to; i; i = e[i].next, v = e[i].to)
if (v != a[u].fa) DFS4(v), a[u].cnt0 += a[v].cnt0, a[u].cnt1 += a[v].cnt1;
}
int main() {
Read(n), Read(m), Read(q);
int u, v;
for (int i = 1; i <= m; ++i) {
Read(u), Read(v);
Add_Edge(u, v), Add_Edge(v, u);
}
for (int i = 1; i <= n; ++i)
if (!dfn[i]) Tarjan(i, 0);
for (int i = 1; i <= n; ++i)
if (!bel[i]) bel[i] = ++dcc, DFS1(i);
for (int u = 1; u <= n; ++u)
for (int i = h[u], v = e[i].to; i; i = e[i].next, v = e[i].to)
if (bel[u] != bel[v]) Add_New_Edge(bel[u], bel[v]);
for (int i = 1; i <= dcc; ++i)
if (!a[i].fa) DFS2(i), DFS3(i, i);
int lca;
while (q--) {
Read(u), Read(v);
u = bel[u], v = bel[v];
lca = LCA(u, v);
if (!lca) return printf("No"), 0;
++a[u].cnt0, --a[lca].cnt0, ++a[v].cnt1, --a[lca].cnt1;
}
for (int i = 1; i <= dcc; ++i)
if (!a[i].fa) DFS4(i);
for (int i = 1; i <= dcc; ++i)
if (a[i].cnt0 && a[i].cnt1) return printf("NO"), 0;
printf("Yes");
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to <image>. Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it.
He painted a few lines, parallel to the sides of the hexagon. The lines split the hexagon into regular triangles with sides of 1 centimeter. Now Gerald wonders how many triangles he has got. But there were so many of them that Gerald lost the track of his counting. Help the boy count the triangles.
Input
The first and the single line of the input contains 6 space-separated integers a1, a2, a3, a4, a5 and a6 (1 β€ ai β€ 1000) β the lengths of the sides of the hexagons in centimeters in the clockwise order. It is guaranteed that the hexagon with the indicated properties and the exactly such sides exists.
Output
Print a single integer β the number of triangles with the sides of one 1 centimeter, into which the hexagon is split.
Examples
Input
1 1 1 1 1 1
Output
6
Input
1 2 1 2 1 2
Output
13
Note
This is what Gerald's hexagon looks like in the first sample:
<image>
And that's what it looks like in the second sample:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int Nmax = 2e5 + 17;
inline int sqr(int x) { return x * x; }
int main(void) {
int a[6];
for (int i = 0; i < 6; i++) cin >> a[i];
cout << sqr(a[0] + a[1] + a[2]) - sqr(a[0]) - sqr(a[2]) - sqr(a[4]);
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Yes, that's another problem with definition of "beautiful" numbers.
Let's call a positive integer x beautiful if its decimal representation without leading zeroes contains even number of digits, and there exists a permutation of this representation which is palindromic. For example, 4242 is a beautiful number, since it contains 4 digits, and there exists a palindromic permutation 2442.
Given a positive integer s, find the largest beautiful number which is less than s.
Input
The first line contains one integer t (1 β€ t β€ 105) β the number of testcases you have to solve.
Then t lines follow, each representing one testcase and containing one string which is the decimal representation of number s. It is guaranteed that this string has even length, contains no leading zeroes, and there exists at least one beautiful number less than s.
The sum of lengths of s over all testcases doesn't exceed 2Β·105.
Output
For each testcase print one line containing the largest beautiful number which is less than s (it is guaranteed that the answer exists).
Example
Input
4
89
88
1000
28923845
Output
88
77
99
28923839
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = (int)1e6 + 100;
const int mod = (int)1e9 + 7;
const long long BIG = (long long)1e18 + 14;
int t, n, cnt[29];
string second, ans;
int main() {
cin >> t;
for (int tt = (1); tt <= (t); ++tt) {
cin >> second;
ans = "";
n = ((int)(second).size());
second = '+' + second;
memset(cnt, 0, sizeof(cnt));
for (auto c : second) cnt[c - '0']++;
for (int i = (n); i >= (1); --i) {
if (((int)(ans).size())) break;
cnt[second[i] - '0']--;
char ch = second[i];
for (int cur = (ch - '0' - 1); cur >= (0); --cur) {
if (i == 1 && !cur) break;
cnt[cur]++;
second[i] = char(cur + '0');
vector<int> add;
int del = n - i;
for (int dig = (0); dig <= (9); ++dig)
if (cnt[dig] % 2) add.push_back(dig);
if (((int)(add).size()) <= del &&
(del - ((int)(add).size())) % 2 == 0) {
int cnt9 = del - ((int)(add).size()), pos = 0;
for (int j = (n); j >= (i + 1); --j) {
if (pos < ((int)(add).size()))
second[j] = char(add[pos++] + '0');
else
second[j] = '9';
}
ans = second;
break;
}
cnt[cur]--;
}
second[i] = ch;
}
if (!((int)(ans).size()))
for (int i = (1); i <= (n - 1); ++i) ans += '9';
ans.erase(ans.begin());
cout << ans << endl;
}
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l β€ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
Input
The first line of input contains two integers n and k (1 β€ n β€ 100, 1 β€ k β€ 109). The next line contains n integers p1, p2, ..., pn β the given permutation. All pi are different and in range from 1 to n.
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem G1 (3 points), the constraints 1 β€ n β€ 6, 1 β€ k β€ 4 will hold.
* In subproblem G2 (5 points), the constraints 1 β€ n β€ 30, 1 β€ k β€ 200 will hold.
* In subproblem G3 (16 points), the constraints 1 β€ n β€ 100, 1 β€ k β€ 109 will hold.
Output
Output the answer with absolute or relative error no more than 1e - 9.
Examples
Input
3 1
1 2 3
Output
0.833333333333333
Input
3 4
1 3 2
Output
1.458333333333334
Note
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int p[10];
double ans;
int n, k;
double count(int aft[]) {
double cnt = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++)
if (aft[i] > aft[j]) cnt++;
}
return cnt;
}
double dfs(int cur) {
if (cur == 0) {
return count(p);
}
double ans = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j <= n; j++) {
reverse(p + i, p + j);
ans += dfs(cur - 1);
reverse(p + i, p + j);
}
}
return ans * 1 / ((1.0 + n) * n / 2.0);
}
int main() {
while (scanf("%d %d", &n, &k) != EOF) {
ans = 0;
for (int i = 0; i < n; i++) scanf("%d", &p[i]);
ans = dfs(k);
printf("%.15lf\n", ans);
}
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building.
The slogan of the company consists of n characters, so the decorators hung a large banner, n meters wide and 1 meter high, divided into n equal squares. The first character of the slogan must be in the first square (the leftmost) of the poster, the second character must be in the second square, and so on.
Of course, the R1 programmers want to write the slogan on the poster themselves. To do this, they have a large (and a very heavy) ladder which was put exactly opposite the k-th square of the poster. To draw the i-th character of the slogan on the poster, you need to climb the ladder, standing in front of the i-th square of the poster. This action (along with climbing up and down the ladder) takes one hour for a painter. The painter is not allowed to draw characters in the adjacent squares when the ladder is in front of the i-th square because the uncomfortable position of the ladder may make the characters untidy. Besides, the programmers can move the ladder. In one hour, they can move the ladder either a meter to the right or a meter to the left.
Drawing characters and moving the ladder is very tiring, so the programmers want to finish the job in as little time as possible. Develop for them an optimal poster painting plan!
Input
The first line contains two integers, n and k (1 β€ k β€ n β€ 100) β the number of characters in the slogan and the initial position of the ladder, correspondingly. The next line contains the slogan as n characters written without spaces. Each character of the slogan is either a large English letter, or digit, or one of the characters: '.', '!', ',', '?'.
Output
In t lines, print the actions the programmers need to make. In the i-th line print:
* "LEFT" (without the quotes), if the i-th action was "move the ladder to the left";
* "RIGHT" (without the quotes), if the i-th action was "move the ladder to the right";
* "PRINT x" (without the quotes), if the i-th action was to "go up the ladder, paint character x, go down the ladder".
The painting time (variable t) must be minimum possible. If there are multiple optimal painting plans, you can print any of them.
Examples
Input
2 2
R1
Output
PRINT 1
LEFT
PRINT R
Input
2 1
R1
Output
PRINT R
RIGHT
PRINT 1
Input
6 4
GO?GO!
Output
RIGHT
RIGHT
PRINT !
LEFT
PRINT O
LEFT
PRINT G
LEFT
PRINT ?
LEFT
PRINT O
LEFT
PRINT G
Note
Note that the ladder cannot be shifted by less than one meter. The ladder can only stand in front of some square of the poster. For example, you cannot shift a ladder by half a meter and position it between two squares. Then go up and paint the first character and the second character.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 200;
char sign[MAXN];
int main() {
ios_base::sync_with_stdio(false);
int n, k;
cin >> n >> k >> sign;
if (n - k > k - 1) {
for (int i = k - 1; i > 0; i--) cout << "LEFT" << endl;
for (int i = 0; i < n; i++) {
cout << "PRINT " << sign[i] << endl;
if (i < n - 1) cout << "RIGHT" << endl;
}
} else {
for (int i = k - 1; i < n - 1; i++) cout << "RIGHT" << endl;
for (int i = n - 1; i >= 0; i--) {
cout << "PRINT " << sign[i] << endl;
;
if (i > 0) cout << "LEFT" << endl;
}
}
return 0;
}
``` |
### Prompt
Generate 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;
template <class T>
inline bool chmax(T &a, T b) {
if (a < b) {
a = b;
return true;
}
return false;
}
template <class T>
inline bool chmin(T &a, T b) {
if (a > b) {
a = b;
return true;
}
return false;
}
const long long INF = 1e18;
int dp[2][8000];
int num[2][8000];
vector<long long> s[2];
long long k[2];
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int N;
cin >> N;
for (int i = 0; i < 2; i++) {
cin >> k[i];
for (int j = 0; j < k[i]; j++) {
long long a;
cin >> a;
s[i].push_back(a);
}
}
queue<pair<int, int> > que;
dp[0][0] = -1;
dp[1][0] = -1;
que.push({0, 0});
que.push({1, 0});
while (!que.empty()) {
auto from = que.front();
que.pop();
int person = from.first;
int pos = from.second;
for (auto delta : s[1 - person]) {
int nowperson = 1 - person;
int nowpos = (pos + N - delta) % N;
if (dp[nowperson][nowpos] != 0) continue;
if (dp[person][pos] == -1) {
dp[nowperson][nowpos] = 1;
que.push({nowperson, nowpos});
} else {
num[nowperson][nowpos]++;
if (num[nowperson][nowpos] == k[nowperson]) {
dp[nowperson][nowpos] = -1;
que.push({nowperson, nowpos});
}
}
}
}
for (int i = 0; i < 2; i++) {
for (int j = 1; j < N; j++) {
if (j != 1) cout << " ";
if (dp[i][j] == 1) cout << "Win";
if (dp[i][j] == 0) cout << "Loop";
if (dp[i][j] == -1) cout << "Lose";
}
cout << "\n";
}
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Your task is to calculate the distance between two $n$ dimensional vectors $x = \\{x_1, x_2, ..., x_n\\}$ and $y = \\{y_1, y_2, ..., y_n\\}$.
The Minkowski's distance defined below is a metric which is a generalization of both the Manhattan distance and the Euclidean distance.
\\[ D_{xy} = (\sum_{i=1}^n |x_i - y_i|^p)^{\frac{1}{p}} \\]
It can be the Manhattan distance
\\[ D_{xy} = |x_1 - y_1| + |x_2 - y_2| + ... + |x_n - y_n| \\]
where $p = 1 $.
It can be the Euclidean distance
\\[ D_{xy} = \sqrt{(|x_1 - y_1|)^{2} + (|x_2 - y_2|)^{2} + ... + (|x_n - y_n|)^{2}} \\]
where $p = 2 $.
Also, it can be the Chebyshev distance
\\[ D_{xy} = max_{i=1}^n (|x_i - y_i|) \\]
where $p = \infty$
Write a program which reads two $n$ dimensional vectors $x$ and $y$, and calculates Minkowski's distance where $p = 1, 2, 3, \infty$ respectively.
Constraints
* $1 \leq n \leq 100$
* $0 \leq x_i, y_i \leq 1000$
Input
In the first line, an integer $n$ is given. In the second and third line, $x = \\{x_1, x_2, ... x_n\\}$ and $y = \\{y_1, y_2, ... y_n\\}$ are given respectively. The elements in $x$ and $y$ are given in integers.
Output
Print the distance where $p = 1, 2, 3$ and $\infty$ in a line respectively. The output should not contain an absolute error greater than 10-5.
Example
Input
3
1 2 3
2 0 4
Output
4.000000
2.449490
2.154435
2.000000
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, x[100], y[100];
cin >> n;
for (int i = 0; i < n; i++) cin >> x[i];
for (int i = 0; i < n; i++) cin >> y[i];
double d[4] = {};
for (int p = 1; p <= 3; p++) {
for (int i = 0; i < n; i++) {
d[p] += pow(fabs(x[i] - y[i]), p);
}
d[p] = pow(d[p], 1.0/p);
}
for (int i = 0; i < n; i++){
d[0] = (d[0] < fabs(x[i] - y[i])?fabs(x[i] - y[i]):d[0]);
}
printf("%lf\n%lf\n%lf\n%lf\n", d[1], d[2], d[3], d[0]);
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Taro is very good at 8 puzzles and always has his friends sort them out during breaks. At that time, my friend asked me, "Can you solve more complicated puzzles?", But I have never done other puzzles. Apparently the friend made 11 puzzles by himself. The puzzle has the following shape.
<image>
11 The puzzle is done using 11 square cards and a frame shaped as shown in Figure 1. First, put 11 cards in the frame. This will create two empty spaces, and you can move cards adjacent to these empty spaces. The goal of the 11 puzzle is to repeat this process and align the cards neatly into the finished product shown in Figure 2.
Taro decided to try this puzzle. However, Taro solved this 11 puzzle very easily. So my friend said unreasonably, "Please solve with the least number of movements!" Taro doesn't know the answer, so I decided to ask you, who can program, to create a program that gives you the minimum number of steps to solve 11 puzzles. At this time, there are two places that can be moved, but let's consider moving one number by one space as one step.
Create a program that takes the initial state of the 11 puzzle as input and outputs the minimum number of steps to solve the 11 puzzle. However, if the minimum number of steps to solve the puzzle is more than 20 steps, output "NA". The state of the puzzle is assumed to be entered in order from the information on the first line, and the number 0 represents free space. For example, the input that represents the state in Figure 1 is:
6
2 1 3
10 5 7 0 8
9 4 11
0
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by -1 line. Each dataset is given in the following format:
p1
p2 p3 p4
p5 p6 p7 p8 p9
p10 p11 p12
p13
Line i gives the puzzle line i information pi (0 β€ pi β€ 11), separated by blanks.
The number of datasets does not exceed 100.
Output
Outputs the minimum number of steps or NA on one line for each dataset.
Example
Input
2
1 0 3
4 5 6 7 8
9 0 11
10
0
1 2 3
4 5 6 7 8
9 10 11
0
0
11 10 9
8 7 6 5 4
3 2 1
0
-1
Output
2
0
NA
### Response
```cpp
#include <iostream>
#include <stdlib.h>
using namespace std;
int p[5][5],x[11]={1,2,3,0,1,2,3,4,1,2,3},y[11]={1,1,1,2,2,2,2,2,3,3,3},s,sx[2],sy[2]
,mx[4]={1,0,-1,0},my[4]={0,-1,0,1},lt;
int search(int t,int mx2,int my2,int mc) {
int a,i,j,x2,y2,s2;
if (s==0) { if (lt>t) lt=t; return 1;}
for (i=0;i<2;i++) for (j=0;j<4;j++) {
x2=sx[i]+mx[j]; y2=sy[i]+my[j];
if (x2<0 || x2>4 || y2<0 || y2>4) continue;
if (p[y2][x2]<1 || ( mc==i && mx2==-mx[j] && my2==-my[j])) continue;
s2=abs(sx[i]-x[p[y2][x2]-1])+abs(sy[i]-y[p[y2][x2]-1])-(abs(x2-x[p[y2][x2]-1])+abs(y2-y[p[y2][x2]-1]));
if (s+s2>lt-t) continue;
p[sy[i]][sx[i]]=p[y2][x2]; p[y2][x2]=0; s+=s2;
sx[i]=x2; sy[i]=y2;
a=search(t+1,mx[j],my[j],i);
sx[i]=x2-mx[j]; sy[i]=y2-my[j];
p[y2][x2]=p[sy[i]][sx[i]]; p[sy[i]][sx[i]]=0; s-=s2;
if (a==1) return 0;
}
return 0;
}
int main() {
int i,j,k;
for (i=0;i<5;i++) for (j=0;j<5;j++) p[i][j]=-1;
while (cin >> p[0][2] && p[0][2]!=-1) {
cin >> p[1][1] >> p[1][2] >> p[1][3];
cin >> p[2][0] >> p[2][1] >> p[2][2] >> p[2][3] >> p[2][4];
cin >> p[3][1] >> p[3][2] >> p[3][3];
cin >> p[4][2]; k=0; s=0;
for (i=0;i<5;i++) for (j=0;j<5;j++) {
if (p[i][j]==0) { sx[k]=j; sy[k]=i; k++;}
if (p[i][j]>0) s+=abs(j-x[p[i][j]-1])+abs(i-y[p[i][j]-1]);
}
lt=21;
search(0,0,0,0);
if (lt==21) cout << "NA" << endl; else cout << lt << endl;
}
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Phoenix has a string s consisting of lowercase Latin letters. He wants to distribute all the letters of his string into k non-empty strings a_1, a_2, ..., a_k such that every letter of s goes to exactly one of the strings a_i. The strings a_i do not need to be substrings of s. Phoenix can distribute letters of s and rearrange the letters within each string a_i however he wants.
For example, if s = baba and k=2, Phoenix may distribute the letters of his string in many ways, such as:
* ba and ba
* a and abb
* ab and ab
* aa and bb
But these ways are invalid:
* baa and ba
* b and ba
* baba and empty string (a_i should be non-empty)
Phoenix wants to distribute the letters of his string s into k strings a_1, a_2, ..., a_k to minimize the lexicographically maximum string among them, i. e. minimize max(a_1, a_2, ..., a_k). Help him find the optimal distribution and print the minimal possible value of max(a_1, a_2, ..., a_k).
String x is lexicographically less than string y if either x is a prefix of y and x β y, or there exists an index i (1 β€ i β€ min(|x|, |y|)) such that x_i < y_i and for every j (1 β€ j < i) x_j = y_j. Here |x| denotes the length of the string x.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases. Each test case consists of two lines.
The first line of each test case consists of two integers n and k (1 β€ k β€ n β€ 10^5) β the length of string s and the number of non-empty strings, into which Phoenix wants to distribute letters of s, respectively.
The second line of each test case contains a string s of length n consisting only of lowercase Latin letters.
It is guaranteed that the sum of n over all test cases is β€ 10^5.
Output
Print t answers β one per test case. The i-th answer should be the minimal possible value of max(a_1, a_2, ..., a_k) in the i-th test case.
Example
Input
6
4 2
baba
5 2
baacb
5 3
baacb
5 3
aaaaa
6 4
aaxxzz
7 1
phoenix
Output
ab
abbc
b
aa
x
ehinopx
Note
In the first test case, one optimal solution is to distribute baba into ab and ab.
In the second test case, one optimal solution is to distribute baacb into abbc and a.
In the third test case, one optimal solution is to distribute baacb into ac, ab, and b.
In the fourth test case, one optimal solution is to distribute aaaaa into aa, aa, and a.
In the fifth test case, one optimal solution is to distribute aaxxzz into az, az, x, and x.
In the sixth test case, one optimal solution is to distribute phoenix into ehinopx.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long cl(long long n, long long m) {
if (n % m)
return n / m + 1;
else
return n / m;
}
long long pw(long long a, long long b, long long M) {
a %= M;
long long r = 1;
while (b > 0) {
if (b & 1) r = r * a % M;
a = a * a % M;
b >>= 1;
}
return r;
}
const long long N = 1e6 + 5;
signed main() {
long long TT;
cin >> TT;
while (TT--) {
long long n, k;
map<long long, long long> m;
cin >> n >> k;
string s;
cin >> s;
long long mx = 0;
for (long long i = 0; i < s.size(); i++)
m[s[i] - 'a']++, mx = max(mx, m[s[i] - 'a']);
string st[k];
for (long long i = 0; i <= k - 1; i++) st[i] = "";
long long t = 0;
long long cnt = 0;
for (long long i = 0; i < k; i++) {
if (m[t] > 0)
st[i] += (char)(t + 'a'), m[t]--;
else {
while (m[t] == 0) {
t++;
if (t == 26) {
goto bahr;
}
}
i--;
continue;
}
}
bahr : {}
for (long long i = 0; i < 26; i++) {
if (m[i] > 0) cnt++;
}
if (st[0] != st[k - 1]) {
cout << st[k - 1] << endl;
continue;
}
if (cnt > 1) {
cout << st[0];
for (long long i = 0; i < 26; i++) {
while (m[i] > 0) {
cout << (char)(i + 'a');
m[i]--;
}
}
cout << endl;
} else if (cnt == 1) {
long long mx = 0;
for (long long i = 0; i < 26; i++) {
if (m[i] > 0) mx = i, cnt = m[i];
}
cout << st[0];
for (long long i = 0; i < cl(cnt, k); i++) {
cout << (char)(mx + 'a');
}
cout << endl;
} else {
cout << st[0] << endl;
}
}
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Mr. Kitayuta has kindly given you a string s consisting of lowercase English letters. You are asked to insert exactly n lowercase English letters into s to make it a palindrome. (A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" and "kitayuta" are not.) You can choose any n lowercase English letters, and insert each of them to any position of s, possibly to the beginning or the end of s. You have to insert exactly n letters even if it is possible to turn s into a palindrome by inserting less than n letters.
Find the number of the palindromes that can be obtained in this way, modulo 10007.
Input
The first line contains a string s (1 β€ |s| β€ 200). Each character in s is a lowercase English letter.
The second line contains an integer n (1 β€ n β€ 109).
Output
Print the number of the palindromes that can be obtained, modulo 10007.
Examples
Input
revive
1
Output
1
Input
add
2
Output
28
Note
For the first sample, you can obtain the palindrome "reviver" by inserting 'r' to the end of "revive".
For the second sample, the following 28 palindromes can be obtained: "adada", "adbda", ..., "adzda", "dadad" and "ddadd".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int mod = 1e4 + 7;
inline int read() {
int kkk = 0, x = 1;
char c = getchar();
while ((c < '0' || c > '9') && c != '-') c = getchar();
if (c == '-') c = getchar(), x = -1;
while (c >= '0' && c <= '9')
kkk = (kkk << 3) + (kkk << 1) + (c - '0'), c = getchar();
return kkk * x;
}
int n, len, CNT[210][210][210], line[210], ANS;
char s[210];
struct data {
int A[410][410], n, m;
} change, ans;
data mul(data x, data y) {
data z;
memset(z.A, 0, sizeof(z.A));
z.n = x.n, z.m = y.m;
for (int i = 0; i <= x.n; ++i)
for (int j = 0; j <= x.m; ++j)
for (int k = 0; k <= y.m; ++k)
(z.A[i][k] += x.A[i][j] * y.A[j][k]) %= mod;
return z;
}
void init() {
change.n = change.m = ans.m = len + (len + 1) / 2 + 1, ans.A[0][0] = 1;
for (int i = 0; i < len; ++i) {
change.A[i][i + 1] = 1;
change.A[i + 1][i + 1] = 24;
}
for (int i = len + 1; i < ans.m; ++i) {
change.A[i][i + 1] = 1;
change.A[i][i] = 25;
}
change.A[len][ans.m] = 1;
change.A[ans.m][ans.m] = 26;
for (int x = 0; x <= len; ++x) {
int y = (len - x + 1) / 2;
change.A[x][ans.m - y] = line[x];
}
}
void out_change() {
cout << "0 " << len << " " << len + 1 << " " << ans.m - 1 << " " << ans.m
<< endl;
cout << setw(4) << 0;
for (int i = 0; i <= ans.m; ++i) cout << setw(4) << i;
cout << endl;
for (int i = 0; i <= ans.m; ++i) {
cout << setw(4) << i;
for (int j = 0; j <= ans.m; ++j) cout << setw(4) << change.A[i][j];
cout << endl;
}
}
int main() {
scanf("%s", s);
n = read();
len = strlen(s);
CNT[0][len - 1][s[0] != s[len - 1]] = 1;
for (int i = len; i >= 2; --i)
for (int l = 0; l + i - 1 < len; ++l) {
int r = l + i - 1;
for (int k = 0; k <= len; ++k)
if (s[l] == s[r])
(CNT[l + 1][r - 1][k + (s[l + 1] != s[r - 1])] += CNT[l][r][k]) %=
mod;
else {
(CNT[l + 1][r][k + (s[l + 1] != s[r])] += CNT[l][r][k]) %= mod;
(CNT[l][r - 1][k + (s[l] != s[r - 1])] += CNT[l][r][k]) %= mod;
}
}
for (int i = 2; i >= 1; --i)
for (int l = 0; l + i - 1 < len; ++l) {
int r = l + i - 1;
for (int k = 0; k <= len; ++k)
if (s[l] == s[r]) (line[k] += CNT[l][r][k]) %= mod;
}
init();
int Time = (n + len + 1) / 2 + 1;
while (Time) {
if (Time % 2) ans = mul(ans, change);
change = mul(change, change);
Time /= 2;
}
ANS = ans.A[0][ans.m];
if ((n + len) % 2 == 0) {
printf("%d\n", ANS);
return 0;
}
for (int i = 0; i < len; ++i)
for (int k = 0; k <= len; ++k)
line[k] = (line[k] - CNT[i][i][k] + mod) % mod;
memset(ans.A, 0, sizeof(ans.A));
memset(change.A, 0, sizeof(change.A));
init();
change.A[ans.m][ans.m] = 0;
Time = (n + len + 1) / 2 + 1;
while (Time) {
if (Time % 2) ans = mul(ans, change);
change = mul(change, change);
Time /= 2;
}
printf("%d\n", (ANS - ans.A[0][ans.m] + mod) % mod);
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
A sequence of non-negative integers a_1, a_2, ..., a_n is called growing if for all i from 1 to n - 1 all ones (of binary representation) in a_i are in the places of ones (of binary representation) in a_{i + 1} (in other words, a_i \:\&\: a_{i + 1} = a_i, where \& denotes [bitwise AND](http://tiny.cc/xpy9uz)). If n = 1 then the sequence is considered growing as well.
For example, the following four sequences are growing:
* [2, 3, 15, 175] β in binary it's [10_2, 11_2, 1111_2, 10101111_2];
* [5] β in binary it's [101_2];
* [1, 3, 7, 15] β in binary it's [1_2, 11_2, 111_2, 1111_2];
* [0, 0, 0] β in binary it's [0_2, 0_2, 0_2].
The following three sequences are non-growing:
* [3, 4, 5] β in binary it's [11_2, 100_2, 101_2];
* [5, 4, 3] β in binary it's [101_2, 100_2, 011_2];
* [1, 2, 4, 8] β in binary it's [0001_2, 0010_2, 0100_2, 1000_2].
Consider two sequences of non-negative integers x_1, x_2, ..., x_n and y_1, y_2, ..., y_n. Let's call this pair of sequences co-growing if the sequence x_1 β y_1, x_2 β y_2, ..., x_n β y_n is growing where β denotes [bitwise XOR](http://tiny.cc/bry9uz).
You are given a sequence of integers x_1, x_2, ..., x_n. Find the lexicographically minimal sequence y_1, y_2, ..., y_n such that sequences x_i and y_i are co-growing.
The sequence a_1, a_2, ..., a_n is lexicographically smaller than the sequence b_1, b_2, ..., b_n if there exists 1 β€ k β€ n such that a_i = b_i for any 1 β€ i < k but a_k < b_k.
Input
The first line contains an integer t (1 β€ t β€ 10^4). Then t test cases follow.
The first line of each test case contains an integer n (1 β€ n β€ 2 β
10^5) β length of the sequence x_i.
The second line contains n integers x_1, x_2, ..., x_n (0 β€ x_i < 2^{30}) β elements of the sequence x_i.
It is guaranteed that the sum of n overall all test cases doesn't exceed 2 β
10^5.
Output
For each test case, print n integers y_1, y_2, ..., y_n (0 β€ y_i < 2^{30}) β lexicographically minimal sequence such that such that it's co-growing with given sequence x_i.
Example
Input
5
4
1 3 7 15
4
1 2 4 8
5
1 2 3 4 5
4
11 13 15 1
1
0
Output
0 0 0 0
0 1 3 7
0 1 0 3 2
0 2 0 14
0
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define int long long
void problem_solver() {
int n;
cin >> n;
vector<int> arr(n);
for(int i=0; i<n; i++) cin >> arr[i];
vector<int> ans;
ans.push_back(0);
for(int i=1; i<n; i++) {
int val = arr[i] & arr[i-1];
val ^= arr[i-1];
ans.push_back(val);
arr[i] += val;
}
for(int i : ans) cout << i << " ";
}
int32_t main() {
int t = 1;
cin >> t;
while(t--) {
problem_solver();
cout << "\n";
}
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
Mayor of Yusland just won the lottery and decided to spent money on something good for town. For example, repair all the roads in the town.
Yusland consists of n intersections connected by n - 1 bidirectional roads. One can travel from any intersection to any other intersection using only these roads.
There is only one road repairing company in town, named "RC company". Company's center is located at the intersection 1. RC company doesn't repair roads you tell them. Instead, they have workers at some intersections, who can repair only some specific paths. The i-th worker can be paid ci coins and then he repairs all roads on a path from ui to some vi that lies on the path from ui to intersection 1.
Mayor asks you to choose the cheapest way to hire some subset of workers in order to repair all the roads in Yusland. It's allowed that some roads will be repaired more than once.
If it's impossible to repair all roads print - 1.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 300 000) β the number of cities in Yusland and the number of workers respectively.
Then follow nβ1 line, each of them contains two integers xi and yi (1 β€ xi, yi β€ n) β indices of intersections connected by the i-th road.
Last m lines provide the description of workers, each line containing three integers ui, vi and ci (1 β€ ui, vi β€ n, 1 β€ ci β€ 109). This means that the i-th worker can repair all roads on the path from vi to ui for ci coins. It's guaranteed that vi lies on the path from ui to 1. Note that vi and ui may coincide.
Output
If it's impossible to repair all roads then print - 1. Otherwise print a single integer β minimum cost required to repair all roads using "RC company" workers.
Example
Input
6 5
1 2
1 3
3 4
4 5
4 6
2 1 2
3 1 4
4 1 3
5 3 1
6 3 2
Output
8
Note
In the first sample, we should choose workers with indices 1, 3, 4 and 5, some roads will be repaired more than once but it is OK. The cost will be equal to 2 + 3 + 1 + 2 = 8 coins.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 3e5 + 10;
const long long MX = 1e18;
long long n, m, maper, dp[MAXN], seg[4 * MAXN], lazy[4 * MAXN];
long long heavy[MAXN], l_[MAXN], r_[MAXN];
struct worker {
long long w = 0, id = 0;
worker(int c) { w = c; }
};
vector<worker> workers;
vector<int> be[MAXN], en[MAXN];
vector<int> adj[MAXN];
void dfs(int v, int par = 0) {
int local = -1;
l_[v] = m + 10;
for (auto i : adj[v])
if (i != par) {
dfs(i, v);
l_[v] = min(l_[v], l_[i]);
}
l_[v] = min(l_[v], maper + 1);
for (auto i : be[v]) workers[i].id = ++maper;
r_[v] = maper;
}
void add(int s, int e, long long val, int l = 1, int r = maper + 1,
int id = 1) {
if (l >= e || r <= s) return;
if (l >= s && r <= e) {
lazy[id] += val;
seg[id] += val;
lazy[id] = min(lazy[id], MX);
seg[id] = min(seg[id], MX);
return;
}
int mid = l + r >> 1;
add(s, e, val, l, mid, id << 1);
add(s, e, val, mid, r, id << 1 | 1);
seg[id] = min(seg[id << 1], seg[id << 1 | 1]);
seg[id] += lazy[id];
seg[id] = min(MX, seg[id]);
}
void change(int s, int e, long long val, int l = 1, int r = maper + 1,
int id = 1) {
if (l >= e || r <= s) return;
if (l >= s && r <= e) {
lazy[id] = val;
seg[id] = val;
return;
}
int mid = l + r >> 1;
change(s, e, val, l, mid, id << 1);
change(s, e, val, mid, r, id << 1 | 1);
seg[id] = min(seg[id << 1], seg[id << 1 | 1]);
seg[id] += lazy[id];
seg[id] = min(MX, seg[id]);
}
long long get(int s, int e, int l = 1, int r = maper + 1, int id = 1) {
if (l >= e || r <= s) return MX;
if (l >= s && r <= e) return seg[id];
int mid = l + r >> 1;
long long mn = MX;
mn = min(mn, get(s, e, l, mid, id << 1));
mn = min(mn, get(s, e, mid, r, id << 1 | 1));
mn += lazy[id];
mn = min(mn, MX);
return mn;
}
void solve(int v, int par = 0) {
if (!(adj[v].size() - 1 + (!par))) {
long long mini = MX;
dp[v] = MX;
for (auto i : be[v]) mini = min(mini, workers[i].w);
for (auto i : be[v]) change(workers[i].id, workers[i].id + 1, workers[i].w);
dp[v] = mini;
return;
}
for (auto i : adj[v])
if (i != par) solve(i, v);
long long pre = 0;
for (auto i : adj[v])
if (i != par) {
add(l_[i], r_[i] + 1, pre);
pre += dp[i];
pre = min(pre, MX);
}
pre = 0;
reverse(adj[v].begin(), adj[v].end());
for (auto i : adj[v])
if (i != par) {
add(l_[i], r_[i] + 1, pre);
pre += dp[i];
pre = min(pre, MX);
}
long long mini = MX;
dp[v] = MX;
if (!par) {
mini = 0;
dp[v] = pre;
}
for (auto i : be[v]) mini = min(mini, (long long)workers[i].w);
dp[v] = min(dp[v], mini + get(l_[v], r_[v] + 1));
for (auto i : en[v]) change(workers[i].id, workers[i].id + 1, MX);
dp[v] = min(dp[v], get(l_[v], r_[v] + 1));
for (auto i : be[v])
change(workers[i].id, workers[i].id + 1, pre + workers[i].w);
return;
}
int main() {
ios::sync_with_stdio(0);
cin >> n >> m;
if (n == 1) return cout << 0 << endl, 0;
for (int i = 1; i < n; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
for (int i = 0; i < m; i++) {
int u, v, c;
cin >> u >> v >> c;
workers.push_back(worker(c));
if (u != v) {
en[v].push_back(i);
be[u].push_back(i);
}
}
for (int i = 1; i < 4 * MAXN; i++) seg[i] = MX;
dfs(1);
solve(1);
if (dp[1] == MX) dp[1] = -1;
cout << dp[1] << endl;
cin >> n;
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Initially, each edge is painted blue. Takahashi will convert this blue tree into a red tree, by performing the following operation N-1 times:
* Select a simple path that consists of only blue edges, and remove one of those edges.
* Then, span a new red edge between the two endpoints of the selected path.
His objective is to obtain a tree that has a red edge connecting vertices c_i and d_i, for each i.
Determine whether this is achievable.
Constraints
* 2 β€ N β€ 10^5
* 1 β€ a_i,b_i,c_i,d_i β€ N
* a_i β b_i
* c_i β d_i
* Both input graphs are trees.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 d_1
:
c_{N-1} d_{N-1}
Output
Print `YES` if the objective is achievable; print `NO` otherwise.
Examples
Input
3
1 2
2 3
1 3
3 2
Output
YES
Input
5
1 2
2 3
3 4
4 5
3 4
2 4
1 4
1 5
Output
YES
Input
6
1 2
3 5
4 6
1 6
5 1
5 3
1 4
2 6
4 3
5 6
Output
NO
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
#define N 111116
typedef pair<int,int> edge;
int n,f[N];
multiset<int> s[N];
map<edge,int> h;
queue<edge> q;
edge make(int x,int y){
if (x>y) swap(x,y);
return edge(x,y);
}
int find(int x){
if (f[x]==x) return x;
return f[x]=find(f[x]);
}
int read(){
int x=0,f=1;char ch=getchar();
for (;!isdigit(ch);ch=getchar()) if (ch=='-') f=-f;
for (;isdigit(ch);ch=getchar()) x=x*10+ch-'0';
return x*f;
}
int main(){
n=read();
for (int i=1;i<=2*n-2;i++){
int x=read(),y=read();edge e=make(x,y);
s[x].insert(y);s[y].insert(x);
if (++h[e]==2) q.push(e);
}
for (int i=1;i<=n;i++) f[i]=i;
for (int i=1;i<=n-1;i++){
int x=0,y=0;
while (x==y){
if (q.empty()) {printf("NO\n");return 0;};
x=find(q.front().first);y=find(q.front().second);q.pop();
}
if (s[x].size()>s[y].size()) swap(x,y);f[x]=y;
for (set<int>::iterator i=s[x].begin();i!=s[x].end();i++){
int z=find(*i);edge e=make(y,z);
if (y==z) continue;
s[y].insert(z);s[z].insert(y);
if (++h[e]==2) q.push(e);
s[z].erase(s[z].find(x));
}
s[y].erase(s[y].find(x));s[x].clear();
}
printf("YES\n");return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Hit n nails one by one at the coordinates P1 (x1, y1), P2 (x2, y2), P3 (x3, y3), ..., Pn (xn, yn) on the flat plate, and put them on the rubber band ring. Surround it with a single rubber band so that all the nails fit inside. At this time, the rubber bands must not intersect.
Create a program that reads the coordinates of the nails and outputs the number of nails that are not in contact with the rubber band when the nail is surrounded by the rubber band as described above. The rubber band shall expand and contract sufficiently. You may not hit more than one nail at the same coordinates. In addition, it is assumed that the nails covered with rubber bands are connected by a straight line, and that no more than three nails are lined up on the straight line. For example, there can be no input as shown in Figure 1. As shown in Figure 2, it is possible for nails without rubber bands to line up in a straight line.
<image> | <image>
--- | ---
Figure 1 | Figure 2
However, each coordinate value is a real number between -1000.0 and 1000.0. Also, n is an integer between 3 and 100.
Hint
Below is a diagram for the second sample input.
<image>
---
Input
Given multiple datasets. Each dataset is given in the following format:
n
x1, y1
x2, y2
...
...
xn, yn
When n is 0, it indicates the end of input. The number of datasets does not exceed 50.
Output
For each dataset, output the number of nails that are not in contact with the rubber. For example, if there is an input representing the four nails shown in Fig. 3, it will be surrounded as shown in Fig. 4, so the number of nails that are not in contact with the rubber band is one.
<image> | <image>
--- | ---
Figure 3 | Figure 4
Example
Input
4
1.0,0.0
0.0,1.0
2.0,1.0
1.0,2.0
9
-509.94,892.63
567.62,639.99
-859.32,-64.84
-445.99,383.69
667.54,430.49
551.12,828.21
-940.2,-877.2
-361.62,-970
-125.42,-178.48
0
Output
0
3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using uint=unsigned;
using ll=long long;
using ull=unsigned long long;
#define int ll
#define rng(i,a,b) for(int i=int(a);i<int(b);i++)
#define rep(i,b) rng(i,0,b)
#define gnr(i,a,b) for(int i=int(b)-1;i>=a;i--)
#define per(i,b) gnr(i,0,b)
#define mp make_pair
#define mt make_tuple
#define pb push_back
#define eb emplace_back
#define fs first
#define sc second
#define bg begin()
#define ed end()
#define all(x) x.bg,x.ed
#ifdef LOCAL
#define dmp(x) cerr<<__LINE__<<" "<<#x<<" "<<x<<endl
#else
#define dmp(x) void(0)
#endif
#define tmp template<class t>
tmp void chmax(t&a,t b){if(a<b)a=b;}
tmp void chmin(t&a,t b){if(a>b)a=b;}
tmp using vc=vector<t>;
tmp using vvc=vc<vc<t>>;
using pi=pair<int,int>;
using vi=vc<int>;
template<class t,class u>
ostream& operator<<(ostream& os,const pair<t,u>& p){
return os<<"{"<<p.fs<<","<<p.sc<<"}";
}
tmp ostream& operator<<(ostream& os,const vc<t>& v){
os<<"{";
for(auto e:v)os<<e<<",";
return os<<"}";
}
constexpr ll ten(int n){
return n==0?1:ten(n-1)*10;
}
tmp void mkuni(vc<t>&v){
sort(all(v));
v.erase(unique(all(v)),v.ed);
}
ll read(){ll i;cin>>i;return i;}
using ld=long double;
using cm=complex<ld>;
#define x real()
#define y imag()
const ld eps=1e-7;
int sgn(ld a){return a<-eps?-1:(a>eps?1:0);}
auto cmcmp=[](const cm&a,const cm&b){
if(sgn(a.x-b.x))return a.x<b.x;
else return sgn(a.y-b.y)<0;
};
ld dot(cm a,cm b){return a.x*b.x+a.y*b.y;}
ld crs(cm a,cm b){return a.x*b.y-a.y*b.x;}
int ccw(cm a,cm b){return sgn(crs(a,b));}
int ccw(cm a,cm b,cm c){return ccw(b-a,c-a);}
//(-2)[a,-1](0)[b,1](2)
int bet(cm a,cm b,cm c){
cm d=b-a;
ld e=dot(d,c-a);
if(sgn(e)<=0)return sgn(e)-1;
return sgn(e-norm(d))+1;
}
ld tri2(cm a,cm b,cm c){
return crs(b-a,c-a);
}
//0-no,1-edge,2-in
int cont(cm a,cm b,cm c,cm d){
if(ccw(a,b,c)==-1)
swap(b,c);
return min({ccw(a,b,d),ccw(b,c,d),ccw(c,a,d)})+1;
}
//no point in edges
vc<cm> convex(vc<cm> s){
swap(s[0],*min_element(all(s),cmcmp));
sort(s.bg+1,s.ed,[&](cm a,cm b){
int c=ccw(s[0],a,b);
if(c)return c==1;
else return bet(s[0],a,b)==2;
});
vc<cm> t;
rep(i,s.size()){
int ss;
while((ss=t.size())>=2){
cm a=t[ss-2];
cm b=t[ss-1];
cm c=s[i];
if(ccw(a,b,c)>0)
break;
t.pop_back();
}
t.pb(s[i]);
}
return t;
}
cm readcm(){
ld a,b;
char c;
cin>>a>>c>>b;
return cm(a,b);
}
ld readld(){
ld a;
cin>>a;
return a;
}
signed main(){
cin.tie(nullptr);
ios::sync_with_stdio(false);
cout<<fixed<<setprecision(20);
while(1){
int n=read();
if(n==0)break;
vc<cm> s(n);
rep(i,n)
s[i]=readcm();
cout<<n-convex(s).size()<<endl;
}
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
The athletics competition 200M semi-final three races were held. Eight players (24 players in total) will participate in each group. A total of eight players, including the top two players in each group and the top two players from all the players in each group who are third or lower, will advance to the final.
Create a program that inputs the player numbers and times and outputs the numbers and times of the eight finalists.
Input
The input is given in the following format:
p1 t1
p2 t2
::
p24 t24
Lines 1-8, 1st set player number pi (integer, 1 β€ pi β€ 10000) and time ti (real number measured to 1/100, 1 β€ ti β€ 100), lines 9-16 Is given the player number pi and time ti of the second group, and the player number pi and time ti of the third group on the 17th to 24th lines. It is assumed that there are no players with the same player number or the same time.
Output
In the following order, please output the player numbers and times of the finalists on one line, separated by blanks.
1st place player in the 1st group
2nd place player in the 1st group
1st place player in the 2nd group
2nd place player in the 2nd group
1st place player in the 3rd group
Second place player in the third group
The player with the fastest time among the players who are 3rd or lower in each group
The player with the second fastest time among the players who are third or lower in each group
Example
Input
18 25.46
16 26.23
3 23.00
10 24.79
5 22.88
11 23.87
19 23.90
1 25.11
23 23.88
4 23.46
7 24.12
12 22.91
13 21.99
14 22.86
21 23.12
9 24.09
17 22.51
22 23.49
6 23.02
20 22.23
24 21.89
15 24.14
8 23.77
2 23.42
Output
5 22.88
3 23.00
13 21.99
14 22.86
24 21.89
20 22.23
17 22.51
12 22.91
### Response
```cpp
#include <bits/stdc++.h>
#define f first
#define s second
using namespace std;
typedef pair<double,int> P;
int main(){
P a[3][8];
vector <P> b,ans;
for(int i=0;i<3;i++){
for(int j=0;j<8;j++) cin>>a[i][j].s>>a[i][j].f;
sort(a[i],a[i]+8);
ans.push_back(a[i][0]);
ans.push_back(a[i][1]);
for(int j=2;j<8;j++) b.push_back(a[i][j]);
}
sort(b.begin(),b.end());
ans.push_back(b[0]);
ans.push_back(b[1]);
for(int i=0;i<8;i++) cout <<ans[i].s<<" "<<ans[i].f<<endl;
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Today is Matvey's birthday. He never knows what to ask as a present so friends gave him a string s of length n. This string consists of only first eight English letters: 'a', 'b', ..., 'h'.
First question that comes to mind is: who might ever need some string? Matvey is a special boy so he instantly found what to do with this string. He used it to build an undirected graph where vertices correspond to position in the string and there is an edge between distinct positions a and b (1 β€ a, b β€ n) if at least one of the following conditions hold:
1. a and b are neighbouring, i.e. |a - b| = 1.
2. Positions a and b contain equal characters, i.e. sa = sb.
Then Matvey decided to find the diameter of this graph. Diameter is a maximum distance (length of the shortest path) among all pairs of vertices. Also, Matvey wants to find the number of pairs of vertices such that the distance between them is equal to the diameter of the graph. As he is very cool and experienced programmer he managed to solve this problem very fast. Will you do the same?
Input
The first line of the input contains a single integer n (2 β€ n β€ 100 000) β the length of the string.
The second line contains the string s itself. It's guaranteed that s consists of only first eight letters of English alphabet.
Output
Print two integers β the diameter of the graph and the number of pairs of positions with the distance equal to the diameter.
Examples
Input
3
abc
Output
2 1
Input
7
aaabaaa
Output
2 4
Note
Consider the second sample.
The maximum distance is 2. It's obtained for pairs (1, 4), (2, 4), (4, 6) and (4, 7).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int gi() {
int res = 0, s = 1;
char ch;
for (ch = getchar(); (ch < '0' || ch > '9') && ch != '-'; ch = getchar())
;
if (ch == '-') s = -1, ch = getchar();
for (; ch >= '0' && ch <= '9'; ch = getchar()) res = res * 10 + ch - 48;
return res * s;
}
int n, m, dis[100010][9], d[9][9], last[9], c[100010], que[100010 << 2], h, t,
mask[100010], tong[9][280];
long long sum[20];
char str[100010];
void init() {
memset(dis, 0x3f3f3f3f, sizeof(dis));
memset(d, 0x3f3f3f3f, sizeof(d));
memset(tong, 0, sizeof(tong));
memset(mask, 0, sizeof(mask));
memset(sum, 0, sizeof(sum));
}
int main() {
n = gi();
m = 8;
scanf("%s", str + 1);
for (int i = 1; i <= n; ++i) c[i] = str[i] - 'a' + 1;
init();
for (int i = 1; i <= m; ++i) {
que[h = t = n + m] = n + i, d[i][i] = 0;
while (h <= t) {
int p = que[h];
h++;
if (p > n) {
for (int j = 1; j <= n; ++j)
if (c[j] == p - n && dis[j][i] > d[p - n][i])
dis[j][i] = d[p - n][i], que[--h] = j;
} else {
if (p > 1 && dis[p - 1][i] > dis[p][i] + 1)
dis[p - 1][i] = dis[p][i] + 1, que[++t] = p - 1;
if (p < n && dis[p + 1][i] > dis[p][i] + 1)
dis[p + 1][i] = dis[p][i] + 1, que[++t] = p + 1;
if (d[c[p]][i] > dis[p][i] + 1)
d[c[p]][i] = dis[p][i] + 1, que[++t] = c[p] + n;
}
}
}
for (int i = 1; i <= m; ++i) {
d[i][i] = 0;
for (int j = 1; j <= m; ++j)
if (i != j) d[i][j]--;
}
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j)
if (dis[i][j] > d[c[i]][j]) mask[i] |= (1 << (j - 1));
for (int i = 1; i <= n; ++i) {
if (i > 2 * m) {
for (int sub = mask[i - 2 * m]; sub; sub = (sub - 1) & mask[i - 2 * m])
tong[c[i - 2 * m]][sub]++;
tong[c[i - 2 * m]][0]++;
}
for (int j = 1; j <= 2 * m - 1 && j < i; ++j) {
int ds = j;
for (int trans = 1; trans <= m; ++trans)
ds = min(ds, dis[i - j][trans] + dis[i][trans] + 1);
sum[ds]++;
}
for (int to = 1; to <= m; ++to) {
int ds = 0x3f3f3f3f, sub = 0;
for (int trans = 1; trans <= m; ++trans)
ds = min(ds, dis[i][trans] + d[trans][to] + 1);
if (ds > 2 * m - 1) continue;
for (int trans = 1; trans <= m; ++trans)
if (dis[i][trans] + d[trans][to] + 1 == ds) sub |= (1 << (trans - 1));
sum[ds] += tong[to][0] - tong[to][sub];
sum[ds + 1] += tong[to][sub];
}
}
for (int i = 2 * m - 1; i >= 0; --i)
if (sum[i] > 0) {
printf("%d %I64d\n", i, sum[i]);
break;
}
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
You are the God of Wind.
By moving a big cloud around, you can decide the weather: it invariably rains under the cloud, and the sun shines everywhere else.
But you are a benign God: your goal is to give enough rain to every field in the countryside, and sun to markets and festivals. Small humans, in their poor vocabulary, only describe this as βweather forecastβ.
You are in charge of a small country, called Paccimc. This country is constituted of 4 Γ 4 square areas, denoted by their numbers.
<image>
Your cloud is of size 2 Γ 2, and may not cross the borders of the country.
You are given the schedule of markets and festivals in each area for a period of time.
On the first day of the period, it is raining in the central areas (6-7-10-11), independently of the schedule.
On each of the following days, you may move your cloud by 1 or 2 squares in one of the four cardinal directions (North, West, South, and East), or leave it in the same position. Diagonal moves are not allowed. All moves occur at the beginning of the day.
You should not leave an area without rain for a full week (that is, you are allowed at most 6 consecutive days without rain). You donβt have to care about rain on days outside the period you were given: i.e. you can assume it rains on the whole country the day before the period, and the day after it finishes.
Input
The input is a sequence of data sets, followed by a terminating line containing only a zero.
A data set gives the number N of days (no more than 365) in the period on a single line, followed by N lines giving the schedule for markets and festivals. The i-th line gives the schedule for the i-th day. It is composed of 16 numbers, either 0 or 1, 0 standing for a normal day, and 1 a market or festival day. The numbers are separated by one or more spaces.
Output
The answer is a 0 or 1 on a single line for each data set, 1 if you can satisfy everybody, 0 if there is no way to do it.
Example
Input
1
0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
7
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 1 0 0 0 0 1 1 0 0 1
0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 1
0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0
0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0
1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0
7
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0
0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0
0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
15
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0 1 0 0 1 0 0
0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0
1 0 0 1 1 0 0 0 0 1 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 1 0 1 0 1 0 0 0 0 0 0
0
Output
0
1
0
1
### Response
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
struct info{
int n,w,s,e,p;
info(int n, int w, int s, int e, int p):n(n), w(w), s(s), e(e), p(p){}
info(){}
void decrease(){
n--; w--; s--; e--;
}
bool isvalid(){
return n>0 && w>0 && s>0 && e>0;
}
bool operator < (const info &a) const{
return (n +(w<<3) +(s<<6) +(e<<9) +(p<<12)) < (a.n +(a.w<<3) +(a.s<<6) +(a.e<<9) +(a.p<<12));
}
};
int main(){
while(1){
int n;
cin >> n;
if(n==0) break;
vector<vector<int> > w(n, vector<int>(17));
for(int i=0; i<n; i++){
for(int j=1; j<=16; j++){
cin >> w[i][j];
}
}
set<info> s;
if(w[0][6] +w[0][7] +w[0][10] +w[0][11] == 0){
s.insert(info(6, 6, 6, 6, 6));
}
for(int i=1; i<n; i++){
set<info> ns;
for(set<info>::iterator itr=s.begin(); itr != s.end(); itr++){
info e = *itr;
int x = (e.p -1) %4;
int y = (e.p -1) /4;
e.decrease();
for(int d=0; d<4; d++){
for(int t=(d==0)?0:1; t<=2; t++){
int nx = x +t*dx[d];
int ny = y +t*dy[d];
info ni = e;
ni.p = 4*ny +nx +1;
if(nx<0 || nx>2 || ny<0 || ny>2) break;
if(w[i][ni.p] +w[i][ni.p+1] +w[i][ni.p+4] +w[i][ni.p+5] > 0) continue;
if(ni.p == 1) ni.n = 7;
if(ni.p == 3) ni.w = 7;
if(ni.p == 9) ni.s = 7;
if(ni.p == 11) ni.e = 7;
if(ni.isvalid()) ns.insert(ni);
}
}
}
s = ns;
}
if(s.size()!=0){
cout << 1 << endl;
}else{
cout << 0 << endl;
}
}
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
For given three points p1, p2, p, find the reflection point x of p onto p1p2.
<image>
Constraints
* 1 β€ q β€ 1000
* -10000 β€ xi, yi β€ 10000
* p1 and p2 are not identical.
Input
xp1 yp1 xp2 yp2
q
xp0 yp0
xp1 yp1
...
xpqβ1 ypqβ1
In the first line, integer coordinates of p1 and p2 are given. Then, q queries are given for integer coordinates of p.
Output
For each query, print the coordinate of the reflection point x. The output values should be in a decimal fraction with an error less than 0.00000001.
Examples
Input
0 0 2 0
3
-1 1
0 1
1 1
Output
-1.0000000000 -1.0000000000
0.0000000000 -1.0000000000
1.0000000000 -1.0000000000
Input
0 0 3 4
3
2 5
1 4
0 3
Output
4.2400000000 3.3200000000
3.5600000000 2.0800000000
2.8800000000 0.8400000000
### Response
```cpp
#include<stdio.h>
#include<math.h>
using namespace std;
int main(){
const double dTolerance = 1.0e-10;
double x1, x2, y1, y2;
scanf("%lf %lf %lf %lf", &x1, &y1, &x2, &y2);
int q;
scanf("%d", &q);
for (int i = 0; i < q; i++){
double x, y;
scanf("%lf %lf", &x, &y);
if (fabs(x1 - x2) < dTolerance) {
printf("%.10lf %.10lf\n", 2 * x1 - x, y);
} else if (fabs(y1 - y2) < dTolerance){
printf("%.10lf %.10lf\n", x, 2 * y1 - y);
} else {
double dt = ((x2 - x1) * (x2 - x) + (y2 - y1) * (y2 - y)) / ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
double ds = ((x2 - x1) * (x - x1) + (y2 - y1) * (y - y1)) / ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
printf("%.10lf %.10lf\n", 2 * (dt * x1 + ds * x2) - x, 2 * (dt * y1 + ds * y2) - y);
}
}
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
The subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You are given an integer n.
You have to find a sequence s consisting of digits \{1, 3, 7\} such that it has exactly n subsequences equal to 1337.
For example, sequence 337133377 has 6 subsequences equal to 1337:
1. 337\underline{1}3\underline{3}\underline{3}7\underline{7} (you can remove the second and fifth characters);
2. 337\underline{1}\underline{3}3\underline{3}7\underline{7} (you can remove the third and fifth characters);
3. 337\underline{1}\underline{3}\underline{3}37\underline{7} (you can remove the fourth and fifth characters);
4. 337\underline{1}3\underline{3}\underline{3}\underline{7}7 (you can remove the second and sixth characters);
5. 337\underline{1}\underline{3}3\underline{3}\underline{7}7 (you can remove the third and sixth characters);
6. 337\underline{1}\underline{3}\underline{3}3\underline{7}7 (you can remove the fourth and sixth characters).
Note that the length of the sequence s must not exceed 10^5.
You have to answer t independent queries.
Input
The first line contains one integer t (1 β€ t β€ 10) β the number of queries.
Next t lines contains a description of queries: the i-th line contains one integer n_i (1 β€ n_i β€ 10^9).
Output
For the i-th query print one string s_i (1 β€ |s_i| β€ 10^5) consisting of digits \{1, 3, 7\}. String s_i must have exactly n_i subsequences 1337. If there are multiple such strings, print any of them.
Example
Input
2
6
1
Output
113337
1337
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int sum = 0, ff = 1;
char ch = getchar();
while (!isdigit(ch)) {
if (ch == '-') ff = -1;
ch = getchar();
}
while (isdigit(ch)) sum = sum * 10 + (ch ^ 48), ch = getchar();
return sum * ff;
}
const int mod = 1e9 + 7;
const int mo = 998244353;
const int N = 1e5 + 5;
int n, Q;
int main() {
Q = read();
for (int q = (1); q <= (Q); q++) {
n = read();
int gs1 = 0, gs7 = 0, gs3 = 0;
int siz = sqrt(2 * n);
for (int i = (siz); i <= (n * 2); i++) {
if (i * (i - 1) > 2 * n) break;
int tmp = i * (i - 1) / 2;
gs7 = n - tmp;
gs3 = i;
}
printf("133");
for (int i = (1); i <= (gs7); i++) putchar('7');
for (int i = (1); i <= (gs3 - 2); i++) putchar('3');
putchar('7');
puts("");
}
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Eshag has an array a consisting of n integers.
Eshag can perform the following operation any number of times: choose some subsequence of a and delete every element from it which is strictly larger than AVG, where AVG is the average of the numbers in the chosen subsequence.
For example, if a = [1 , 4 , 3 , 2 , 4] and Eshag applies the operation to the subsequence containing a_1, a_2, a_4 and a_5, then he will delete those of these 4 elements which are larger than (a_1+a_2+a_4+a_5)/(4) = 11/4, so after the operation, the array a will become a = [1 , 3 , 2].
Your task is to find the maximum number of elements Eshag can delete from the array a by applying the operation described above some number (maybe, zero) times.
A sequence b is a subsequence of an array c if b can be obtained from c by deletion of several (possibly, zero or all) elements.
Input
The first line contains an integer t (1β€ tβ€ 100) β the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer n (1β€ nβ€ 100) β the length of the array a.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (1β€ a_i β€ 100) β the elements of the array a.
Output
For each test case print a single integer β the maximum number of elements Eshag can delete from the array a.
Example
Input
3
6
1 1 1 2 2 3
6
9 9 9 9 9 9
6
6 4 1 1 4 1
Output
3
0
3
Note
Consider the first test case.
Initially a = [1, 1, 1, 2, 2, 3].
In the first operation, Eshag can choose the subsequence containing a_1, a_5 and a_6, their average is equal to (a_1 + a_5 + a_6)/(3) = 6/3 = 2. So a_6 will be deleted.
After this a = [1, 1, 1, 2, 2].
In the second operation, Eshag can choose the subsequence containing the whole array a, the average of all its elements is equal to 7/5. So a_4 and a_5 will be deleted.
After this a = [1, 1, 1].
In the second test case, Eshag can't delete any element.
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin >> t;
while(t--)
{
int n;
cin >> n;
int a, cnt[104]={0}, i, j, k, mx=-5, mn=999;
for(i=0; i<n; i++){
cin >> a;
if(a<mn)
mn = a;
cnt[a]++;
}
cout << (n-cnt[mn]) << endl;
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.