text
stringlengths 424
69.5k
|
---|
### Prompt
Please formulate a CPP solution to the following problem:
In Takahashi Kingdom, which once existed, there are N cities, and some pairs of cities are connected bidirectionally by roads. The following are known about the road network:
* People traveled between cities only through roads. It was possible to reach any city from any other city, via intermediate cities if necessary.
* Different roads may have had different lengths, but all the lengths were positive integers.
Snuke the archeologist found a table with N rows and N columns, A, in the ruin of Takahashi Kingdom. He thought that it represented the shortest distances between the cities along the roads in the kingdom.
Determine whether there exists a road network such that for each u and v, the integer A_{u, v} at the u-th row and v-th column of A is equal to the length of the shortest path from City u to City v. If such a network exist, find the shortest possible total length of the roads.
Constraints
* 1 \leq N \leq 300
* If i β j, 1 \leq A_{i, j} = A_{j, i} \leq 10^9.
* A_{i, i} = 0
Inputs
Input is given from Standard Input in the following format:
N
A_{1, 1} A_{1, 2} ... A_{1, N}
A_{2, 1} A_{2, 2} ... A_{2, N}
...
A_{N, 1} A_{N, 2} ... A_{N, N}
Outputs
If there exists no network that satisfies the condition, print `-1`. If it exists, print the shortest possible total length of the roads.
Examples
Input
3
0 1 3
1 0 2
3 2 0
Output
3
Input
3
0 1 3
1 0 1
3 1 0
Output
-1
Input
5
0 21 18 11 28
21 0 13 10 26
18 13 0 23 13
11 10 23 0 17
28 26 13 17 0
Output
82
Input
3
0 1000000000 1000000000
1000000000 0 1000000000
1000000000 1000000000 0
Output
3000000000
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
long long ans = 0;
vector<vector<long long>> a(n, vector<long long>(n));
for(int i=0;i<n;i++) for(int j=0;j<n;j++) cin >> a[i][j];
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
bool need = true;
for(int k=0;k<n;k++) {
if(k == i || k == j) continue;
if(a[i][j] < a[i][k] + a[k][j]) continue;
else if(a[i][j] == a[i][k] + a[k][j]) need = false;
else {
ans = -1;
break;
}
}
if(ans == -1) break;
if(need) ans += a[i][j];
}
if(ans == -1) break;
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
You are given an array of length n and a number k. Let's pick k non-overlapping non-empty subarrays of the initial array. Let si be the sum of the i-th subarray in order from left to right. Compute the maximum value of the following expression:
|s1 - s2| + |s2 - s3| + ... + |sk - 1 - sk|
Here subarray is a contiguous part of an array.
Input
The first line of input contains two integers n and k. The second line contains n integers β the elements of the array. The absolute values of elements do not exceed 104.
The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem E1 (9 points), constraints 2 β€ n β€ 400, 2 β€ k β€ min(n, 50) will hold.
* In subproblem E2 (12 points), constraints 2 β€ n β€ 30000, 2 β€ k β€ min(n, 200) will hold.
Output
Output a single integer β the maximum possible value.
Examples
Input
5 3
5 2 4 3 1
Output
12
Input
4 2
7 4 3 7
Output
8
Note
Consider the first sample test. The optimal solution is obtained if the first subarray contains the first element only, the second subarray spans the next three elements and the last subarray contains the last element only. The sums of these subarrays are 5, 9 and 1, correspondingly.
Consider the second sample test. In the optimal solution, the first subarray consists of the first two elements and the second subarray consists of the third element only. Note that the last element does not belong to any subarray in this solution.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename T>
void chkmax(T &x, T y) {
x = x > y ? x : y;
}
template <typename T>
void chkmin(T &x, T y) {
x = x > y ? y : x;
}
const int INF = (1ll << 30) - 1;
template <typename T>
void read(T &x) {
x = 0;
bool f = 1;
char ch;
do {
ch = getchar();
if (ch == '-') f = 0;
} while (ch > '9' || ch < '0');
do {
x = x * 10 + ch - '0';
ch = getchar();
} while (ch >= '0' && ch <= '9');
x = f ? x : -x;
}
template <typename T>
void write(T x) {
if (x < 0) x = ~x + 1, putchar('-');
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
const int N = 3e4 + 5;
const int K = 200 + 5;
int n, m, a[N], f[N][K][4];
int main() {
read(n);
read(m);
memset(f, -0x3f, sizeof(f));
for (int i = 1; i <= n; i++) read(a[i]);
for (int i = 0; i <= n; i++)
for (int j = 0; j < 4; j++) f[i][0][j] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
int x = 1 + (j != 1 && j != m);
f[i][j][0] = max(f[i - 1][j][0], f[i - 1][j - 1][3]) + x * a[i];
f[i][j][1] = max(f[i][j][0], f[i - 1][j][1]);
f[i][j][2] = max(f[i - 1][j][2], f[i - 1][j - 1][1]) - x * a[i];
f[i][j][3] = max(f[i][j][2], f[i - 1][j][3]);
if (x == 2) f[i][j][1] = max(f[i][j][1], f[i - 1][j - 1][1]);
if (x == 2) f[i][j][3] = max(f[i][j][3], f[i - 1][j - 1][3]);
}
}
int ans = 0;
for (int i = 0; i < 4; i++) chkmax(ans, f[n][m][i]);
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
We're giving away nice huge bags containing number tiles! A bag we want to present to you contains n tiles. Each of them has a single number written on it β either 1 or 2.
However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in any order you wish. We will then compute the sums of all prefixes in the sequence, and then count how many of these sums are prime numbers. If you want to keep the prize, you will need to maximize the number of primes you get.
Can you win the prize? Hurry up, the bags are waiting!
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of number tiles in the bag. The following line contains n space-separated integers a_1, a_2, ..., a_n (a_i β \{1, 2\}) β the values written on the tiles.
Output
Output a permutation b_1, b_2, ..., b_n of the input sequence (a_1, a_2, ..., a_n) maximizing the number of the prefix sums being prime numbers. If there are multiple optimal permutations, output any.
Examples
Input
5
1 2 1 2 1
Output
1 1 1 2 2
Input
9
1 1 2 1 1 1 2 1 1
Output
1 1 1 2 1 1 1 2 1
Note
The first solution produces the prefix sums 1, \mathbf{\color{blue}{2}}, \mathbf{\color{blue}{3}}, \mathbf{\color{blue}{5}}, \mathbf{\color{blue}{7}} (four primes constructed), while the prefix sums in the second solution are 1, \mathbf{\color{blue}{2}}, \mathbf{\color{blue}{3}}, \mathbf{\color{blue}{5}}, 6, \mathbf{\color{blue}{7}}, 8, 10, \mathbf{\color{blue}{11}} (five primes). Primes are marked bold and blue. In each of these cases, the number of produced primes is maximum possible.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, x, y;
int main() {
int i, a;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &a);
if (a == 1)
x++;
else
y++;
}
if (x == 0) {
for (i = 0; i < y; i++) printf("2 ");
printf("\n");
} else if (y == 0) {
for (i = 0; i < x; i++) printf("1 ");
printf("\n");
} else {
printf("2 1 ");
x--, y--;
for (i = 0; i < y; i++) printf("2 ");
for (i = 0; i < x; i++) printf("1 ");
printf("\n");
}
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Having stayed home alone, Petya decided to watch forbidden films on the Net in secret. "What ungentlemanly behavior!" β you can say that, of course, but don't be too harsh on the kid. In his country films about the Martians and other extraterrestrial civilizations are forbidden. It was very unfair to Petya as he adored adventure stories that featured lasers and robots.
Today Petya is watching a shocking blockbuster about the Martians called "R2:D2". What can "R2:D2" possibly mean? It might be the Martian time represented in the Martian numeral system. Petya knows that time on Mars is counted just like on the Earth (that is, there are 24 hours and each hour has 60 minutes). The time is written as "a:b", where the string a stands for the number of hours (from 0 to 23 inclusive), and string b stands for the number of minutes (from 0 to 59 inclusive). The only thing Petya doesn't know is in what numeral system the Martian time is written.
Your task is to print the radixes of all numeral system which can contain the time "a:b".
Input
The first line contains a single string as "a:b" (without the quotes). There a is a non-empty string, consisting of numbers and uppercase Latin letters. String a shows the number of hours. String b is a non-empty string that consists of numbers and uppercase Latin letters. String b shows the number of minutes. The lengths of strings a and b are from 1 to 5 characters, inclusive. Please note that strings a and b can have leading zeroes that do not influence the result in any way (for example, string "008:1" in decimal notation denotes correctly written time).
We consider characters 0, 1, ..., 9 as denoting the corresponding digits of the number's representation in some numeral system, and characters A, B, ..., Z correspond to numbers 10, 11, ..., 35.
Output
Print the radixes of the numeral systems that can represent the time "a:b" in the increasing order. Separate the numbers with spaces or line breaks. If there is no numeral system that can represent time "a:b", print the single integer 0. If there are infinitely many numeral systems that can represent the time "a:b", print the single integer -1.
Note that on Mars any positional numeral systems with positive radix strictly larger than one are possible.
Examples
Input
11:20
Output
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
Input
2A:13
Output
0
Input
000B:00001
Output
-1
Note
Let's consider the first sample. String "11:20" can be perceived, for example, as time 4:6, represented in the ternary numeral system or as time 17:32 in hexadecimal system.
Let's consider the second sample test. String "2A:13" can't be perceived as correct time in any notation. For example, let's take the base-11 numeral notation. There the given string represents time 32:14 that isn't a correct time.
Let's consider the third sample. String "000B:00001" can be perceived as a correct time in the infinite number of numeral systems. If you need an example, you can take any numeral system with radix no less than 12.
### Response
```cpp
#include <bits/stdc++.h>
int a[5], b[5];
int mu(int a, int n) {
int i, kq = 1;
for (i = 0; i < n; i++) {
kq *= a;
}
return kq;
}
int tinh(int p[], int n, int base) {
int i, sum = 0;
for (i = n - 1; i >= 0; i--) {
sum += p[i] * mu(base, n - i - 1);
}
return sum;
}
int main() {
int i, na, nb, ma = 0, mb = 0, max, check = 0;
char c;
i = 0;
while ((c = getchar()) != EOF) {
if (c >= '0' && c < '9') a[i++] = c - '0';
if (c >= 'A' && c <= 'Z') a[i++] = c - 'A' + 10;
if (a[i - 1] > ma) ma = a[i - 1];
if (c == ':') break;
}
na = i;
i = 0;
while ((c = getchar()) != EOF) {
if (c >= '0' && c < '9') b[i++] = c - '0';
if (c >= 'A' && c <= 'Z') b[i++] = c - 'A' + 10;
if (b[i - 1] > mb) mb = b[i - 1];
if (c == '\n') break;
}
nb = i;
if (ma > mb)
max = ma + 1;
else
max = mb + 1;
if (tinh(a, na, max) > 23 || tinh(b, nb, max) > 59) {
printf("0\n");
return 0;
}
for (i = 0; i < na - 1; i++)
if (a[i] != 0) check = 1;
for (i = 0; i < nb - 1; i++)
if (b[i] != 0) check = 1;
if (check == 0) {
printf("-1\n");
return 0;
}
i = max;
while (tinh(a, na, i) < 24 && tinh(b, nb, i) < 60) {
printf("%d ", i);
i++;
}
printf("\n");
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Everything is great about Ilya's city, except the roads. The thing is, the only ZooVille road is represented as n holes in a row. We will consider the holes numbered from 1 to n, from left to right.
Ilya is really keep on helping his city. So, he wants to fix at least k holes (perharps he can fix more) on a single ZooVille road.
The city has m building companies, the i-th company needs ci money units to fix a road segment containing holes with numbers of at least li and at most ri. The companies in ZooVille are very greedy, so, if they fix a segment containing some already fixed holes, they do not decrease the price for fixing the segment.
Determine the minimum money Ilya will need to fix at least k holes.
Input
The first line contains three integers n, m, k (1 β€ n β€ 300, 1 β€ m β€ 105, 1 β€ k β€ n). The next m lines contain the companies' description. The i-th line contains three integers li, ri, ci (1 β€ li β€ ri β€ n, 1 β€ ci β€ 109).
Output
Print a single integer β the minimum money Ilya needs to fix at least k holes.
If it is impossible to fix at least k holes, print -1.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
10 4 6
7 9 11
6 9 13
7 7 7
3 5 6
Output
17
Input
10 7 1
3 4 15
8 9 8
5 6 8
9 10 6
1 4 2
1 4 10
8 10 13
Output
2
Input
10 1 9
5 10 14
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long cost[303][303], dp[303][303];
int main() {
int n, m, k;
cin >> n >> m >> k;
memset(cost, 0x3f3f3f3f3f3f3f3f, sizeof(cost));
for (int i = 1; i <= m; i++) {
int l, r;
long long c;
cin >> l >> r >> c;
for (int j = l; j <= r; j++) cost[l][j] = min(cost[l][j], c);
}
memset(dp, 0x3f3f3f3f3f3f3f3f, sizeof(dp));
for (int i = 0; i <= n; i++) dp[i][0] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
dp[i][j] = dp[i - 1][j];
for (int k = 1; k <= j; k++)
dp[i][j] = min(dp[i][j], cost[i - k + 1][i] + dp[i - k][j - k]);
}
}
long long result = 0x3f3f3f3f3f3f3f3f;
for (int i = k; i <= n; i++) result = min(result, dp[n][i]);
if (result < 0x3f3f3f3f3f3f3f3f)
cout << result << "\n";
else
cout << "-1\n";
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Mike decided to teach programming to children in an elementary school. He knows that it is not an easy task to interest children in that age to code. That is why he decided to give each child two sweets.
Mike has n sweets with sizes a_1, a_2, β¦, a_n. All his sweets have different sizes. That is, there is no such pair (i, j) (1 β€ i, j β€ n) such that i β j and a_i = a_j.
Since Mike has taught for many years, he knows that if he gives two sweets with sizes a_i and a_j to one child and a_k and a_p to another, where (a_i + a_j) β (a_k + a_p), then a child who has a smaller sum of sizes will be upset. That is, if there are two children who have different sums of sweets, then one of them will be upset. Apparently, Mike does not want somebody to be upset.
Mike wants to invite children giving each of them two sweets. Obviously, he can't give one sweet to two or more children. His goal is to invite as many children as he can.
Since Mike is busy preparing to his first lecture in the elementary school, he is asking you to find the maximum number of children he can invite giving each of them two sweets in such way that nobody will be upset.
Input
The first line contains one integer n (2 β€ n β€ 1 000) β the number of sweets Mike has.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^5) β the sizes of the sweets. It is guaranteed that all integers are distinct.
Output
Print one integer β the maximum number of children Mike can invite giving each of them two sweets in such way that nobody will be upset.
Examples
Input
8
1 8 3 11 4 9 2 7
Output
3
Input
7
3 1 7 11 9 2 12
Output
2
Note
In the first example, Mike can give 9+2=11 to one child, 8+3=11 to another one, and 7+4=11 to the third child. Therefore, Mike can invite three children. Note that it is not the only solution.
In the second example, Mike can give 3+9=12 to one child and 1+11 to another one. Therefore, Mike can invite two children. Note that it is not the only solution.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1005;
const int INF = 0x3f3f3f3f;
int arr[N];
map<int, int> mp;
int main() {
mp.clear();
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
mp[arr[i] + arr[j]]++;
}
}
int ans = 0;
for (pair<int, int> p : mp) {
ans = max(ans, p.second);
}
printf("%d\n", ans);
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Nikita likes tasks on order statistics, for example, he can easily find the k-th number in increasing order on a segment of an array. But now Nikita wonders how many segments of an array there are such that a given number x is the k-th number in increasing order on this segment. In other words, you should find the number of segments of a given array such that there are exactly k numbers of this segment which are less than x.
Nikita wants to get answer for this question for each k from 0 to n, where n is the size of the array.
Input
The first line contains two integers n and x (1 β€ n β€ 2 β
10^5, -10^9 β€ x β€ 10^9).
The second line contains n integers a_1, a_2, β¦, a_n (-10^9 β€ a_i β€ 10^9) β the given array.
Output
Print n+1 integers, where the i-th number is the answer for Nikita's question for k=i-1.
Examples
Input
5 3
1 2 3 4 5
Output
6 5 4 0 0 0
Input
2 6
-5 9
Output
1 2 0
Input
6 99
-1 -1 -1 -1 -1 -1
Output
0 6 5 4 3 2 1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 8e5 + 10;
const long double Pi = 3.141592653589793;
int n, first;
int sum[N], a[N];
int rev[N];
pair<long double, long double> w[N];
pair<long double, long double> operator+(pair<long double, long double> a,
pair<long double, long double> b) {
return make_pair(a.first + b.first, a.second + b.second);
}
pair<long double, long double> operator-(pair<long double, long double> a,
pair<long double, long double> b) {
return make_pair(a.first - b.first, a.second - b.second);
}
pair<long double, long double> operator*(pair<long double, long double> a,
pair<long double, long double> b) {
return make_pair(a.first * b.first - a.second * b.second,
a.first * b.second + a.second * b.first);
}
pair<long double, long double> operator/(pair<long double, long double> a,
long double t) {
return make_pair(a.first / t, a.second / t);
}
void initrev(int n, int &lim) {
lim = 1;
for (; lim < n; lim <<= 1)
;
for (int i = 1; i < lim; i++) {
rev[i] = (rev[i >> 1] >> 1) | ((i & 1) * (lim >> 1));
}
for (int i = 0; i < lim; i++)
w[i] = make_pair(cos(Pi * 2 / lim * i), sin(Pi * 2 / lim * i));
return;
}
void FFT(vector<pair<long double, long double> > &a, int t) {
int lim = a.size();
for (int i = 0; i < lim; i++)
if (i < rev[i]) swap(a[i], a[rev[i]]);
for (int i = 2; i <= lim; i <<= 1) {
for (int j = 0; j < lim; j += i) {
for (int k = 0; k < (i >> 1); k++) {
pair<long double, long double> first = a[j + k],
second =
a[j + k + (i >> 1)] * w[lim / i * k];
a[j + k] = (first + second);
a[j + k + (i >> 1)] = (first - second);
}
}
}
if (t < 0) {
reverse(a.begin() + 1, a.end());
for (int i = 0; i < lim; i++) a[i] = a[i] / lim;
}
return;
}
int main() {
scanf("%d%d", &n, &first);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
sum[i] = sum[i - 1];
if (a[i] < first) sum[i]++;
}
int lim;
initrev(n * 2 + 1, lim);
vector<pair<long double, long double> > f(lim);
for (int i = 0; i <= n; i++) f[sum[i]].first += 1;
vector<pair<long double, long double> > g = f;
reverse(f.begin(), f.begin() + n + 1);
FFT(f, 1), FFT(g, 1);
for (int i = 0; i < lim; i++) f[i] = f[i] * g[i];
FFT(f, -1);
printf("%lld ", (llround(f[n].first) - n - 1) / 2);
for (int i = 1; i <= n; i++) printf("%lld ", llround(f[i + n].first));
printf("\n");
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work.
The girl finds an important permutation for the research. The permutation contains n distinct integers a1, a2, ..., an (1 β€ ai β€ n). She replaces some of permutation elements with -1 value as a revenge.
When Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element ak which has value equal to k (ak = k). Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo 1000000007 (109 + 7).
Input
The first line contains integer n (2 β€ n β€ 2000). On the second line, there are n integers, representing Iahub's important permutation after Iahubina replaces some values with -1.
It's guaranteed that there are no fixed points in the given permutation. Also, the given sequence contains at least two numbers -1 and each positive number occurs in the sequence at most once. It's guaranteed that there is at least one suitable permutation.
Output
Output a single integer, the number of ways Iahub could recover his permutation, modulo 1000000007 (109 + 7).
Examples
Input
5
-1 -1 4 3 -1
Output
2
Note
For the first test example there are two permutations with no fixed points are [2, 5, 4, 3, 1] and [5, 1, 4, 3, 2]. Any other permutation would have at least one fixed point.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long pwr(long long base, long long p, long long mod = (1000000007LL)) {
long long ans = 1;
while (p) {
if (p & 1) ans = (ans * base) % mod;
base = (base * base) % mod;
p /= 2;
}
return ans;
}
long long gcd(long long a, long long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
int n, arr[2002];
bool ele_used[2002], pos_used[2002];
long long DP[2002][2002][2];
long long dp(int rem_ele, int super_pos, bool start_new_chain) {
if (super_pos < 0) return 0;
if (rem_ele == 0) return 1;
long long &ans = DP[rem_ele][super_pos][start_new_chain];
if (ans != -1) return ans;
ans = 0;
if (start_new_chain) {
ans = (ans + (rem_ele - 1) * dp(rem_ele - 1, super_pos + 1, false)) %
(1000000007LL);
ans = (ans + (super_pos)*dp(rem_ele - 1, super_pos, true)) % (1000000007LL);
return ans;
} else {
ans = (ans + (rem_ele - 1) * dp(rem_ele - 1, super_pos, false)) %
(1000000007LL);
ans = (ans + super_pos * dp(rem_ele - 1, super_pos - 1, true)) %
(1000000007LL);
return ans;
}
assert(0);
return 0;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> arr[i];
if (arr[i] != -1) {
ele_used[arr[i]] = pos_used[i] = true;
}
}
int constrained = 0, super_ele = 0, super_pos = 0;
for (int i = 1; i <= n; i++)
if (!ele_used[i] && !pos_used[i])
constrained++;
else if (ele_used[i] && !pos_used[i])
super_pos++;
else if (pos_used[i] && !ele_used[i])
super_ele++;
memset(DP, -1, sizeof(DP));
long long ans = dp(constrained, super_pos, true);
while (super_ele > 0) {
ans = (ans * super_ele) % (1000000007LL);
super_ele--;
}
cout << ans;
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
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;
int main() {
string out[] = {"NO", "YES"};
int a[4] = {};
for (int i = 1; i <= 3; i++) {
string line, se;
getline(cin, line);
stringstream str(line);
while (str >> se) {
for (char c : se) {
a[i] += (set<char>{'a', 'e', 'i', 'o', 'u'}.count(c));
}
}
}
cout << out[a[1] == 5 && a[2] == 7 && a[3] == 5] << '\n';
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
A and B are preparing themselves for programming contests.
To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger.
For each chess piece we know its weight:
* the queen's weight is 9,
* the rook's weight is 5,
* the bishop's weight is 3,
* the knight's weight is 3,
* the pawn's weight is 1,
* the king's weight isn't considered in evaluating position.
The player's weight equals to the sum of weights of all his pieces on the board.
As A doesn't like counting, he asked you to help him determine which player has the larger position weight.
Input
The input contains eight lines, eight characters each β the board's description.
The white pieces on the board are marked with uppercase letters, the black pieces are marked with lowercase letters.
The white pieces are denoted as follows: the queen is represented is 'Q', the rook β as 'R', the bishop β as'B', the knight β as 'N', the pawn β as 'P', the king β as 'K'.
The black pieces are denoted as 'q', 'r', 'b', 'n', 'p', 'k', respectively.
An empty square of the board is marked as '.' (a dot).
It is not guaranteed that the given chess position can be achieved in a real game. Specifically, there can be an arbitrary (possibly zero) number pieces of each type, the king may be under attack and so on.
Output
Print "White" (without quotes) if the weight of the position of the white pieces is more than the weight of the position of the black pieces, print "Black" if the weight of the black pieces is more than the weight of the white pieces and print "Draw" if the weights of the white and black pieces are equal.
Examples
Input
...QK...
........
........
........
........
........
........
...rk...
Output
White
Input
rnbqkbnr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKBNR
Output
Draw
Input
rppppppr
...k....
........
........
........
........
K...Q...
........
Output
Black
Note
In the first test sample the weight of the position of the white pieces equals to 9, the weight of the position of the black pieces equals 5.
In the second test sample the weights of the positions of the black and the white pieces are equal to 39.
In the third test sample the weight of the position of the white pieces equals to 9, the weight of the position of the black pieces equals to 16.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
string c[10];
int main() {
int A = 0, B = 0;
for (int i = 0; i < 8; ++i) cin >> c[i];
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (c[i][j] == 'Q')
A += 9;
else if (c[i][j] == 'R')
A += 5;
else if (c[i][j] == 'B' || c[i][j] == 'N')
A += 3;
else if (c[i][j] == 'P')
A++;
else if (c[i][j] == 'q')
B += 9;
else if (c[i][j] == 'r')
B += 5;
else if (c[i][j] == 'b' || c[i][j] == 'n')
B += 3;
else if (c[i][j] == 'p')
B++;
}
}
if (A > B) {
cout << "White\n";
return 0;
} else if (B > A) {
cout << "Black\n";
return 0;
} else {
cout << "Draw\n";
return 0;
}
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level.
All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases by 1. If he manages to finish the level successfully then the number of clears increases by 1 as well. Note that both of the statistics update at the same time (so if the player finishes the level successfully then the number of plays will increase at the same time as the number of clears).
Polycarp is very excited about his level, so he keeps peeking at the stats to know how hard his level turns out to be.
So he peeked at the stats n times and wrote down n pairs of integers β (p_1, c_1), (p_2, c_2), ..., (p_n, c_n), where p_i is the number of plays at the i-th moment of time and c_i is the number of clears at the same moment of time. The stats are given in chronological order (i.e. the order of given pairs is exactly the same as Polycarp has written down).
Between two consecutive moments of time Polycarp peeked at the stats many players (but possibly zero) could attempt the level.
Finally, Polycarp wonders if he hasn't messed up any records and all the pairs are correct. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then he considers his records correct.
Help him to check the correctness of his records.
For your convenience you have to answer multiple independent test cases.
Input
The first line contains a single integer T (1 β€ T β€ 500) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 100) β the number of moments of time Polycarp peeked at the stats.
Each of the next n lines contains two integers p_i and c_i (0 β€ p_i, c_i β€ 1000) β the number of plays and the number of clears of the level at the i-th moment of time.
Note that the stats are given in chronological order.
Output
For each test case print a single line.
If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then print "YES".
Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
6
3
0 0
1 1
1 2
2
1 0
1000 3
4
10 1
15 2
10 2
15 2
1
765 432
2
4 4
4 3
5
0 0
1 0
1 0
1 0
1 0
Output
NO
YES
NO
YES
NO
YES
Note
In the first test case at the third moment of time the number of clears increased but the number of plays did not, that couldn't have happened.
The second test case is a nice example of a Super Expert level.
In the third test case the number of plays decreased, which is impossible.
The fourth test case is probably an auto level with a single jump over the spike.
In the fifth test case the number of clears decreased, which is also impossible.
Nobody wanted to play the sixth test case; Polycarp's mom attempted it to make him feel better, however, she couldn't clear it.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
int n;
cin >> t;
int arr[107], brr[107];
while (t--) {
cin >> n;
int flag = 0;
for (int i = 0; i < n; i++) {
cin >> arr[i] >> brr[i];
}
if (n == 1) {
if (arr[0] >= brr[0]) {
flag = 1;
cout << "YES" << endl;
continue;
} else {
cout << "NO" << endl;
flag = 1;
continue;
}
}
if (arr[0] < brr[0]) {
cout << "NO" << endl;
flag = 1;
continue;
}
for (int i = 1; i < n; i++) {
if (((arr[i] - arr[i - 1]) < (brr[i] - brr[i - 1])) ||
(arr[i] < arr[i - 1]) || (brr[i] < brr[i - 1])) {
flag = 1;
cout << "NO" << endl;
break;
}
}
if (!flag) cout << "YES" << endl;
}
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Input
The input contains a single integer a (0 β€ a β€ 35).
Output
Output a single integer.
Examples
Input
3
Output
8
Input
10
Output
1024
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int factors[1010 + 10];
int main() {
int n;
cin >> n;
int a[10];
for (int i = 0; i < 6; i++) {
a[i] = n % 2;
n >>= 1;
}
swap(a[0], a[4]);
swap(a[2], a[3]);
int res = 0;
for (int i = 0, pow = 1; i < 6; i++) {
res += a[i] * pow;
pow <<= 1;
}
cout << res << endl;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
There are n players numbered from 0 to n-1 with ranks. The i-th player has rank i.
Players can form teams: the team should consist of three players and no pair of players in the team should have a conflict. The rank of the team is calculated using the following algorithm: let i, j, k be the ranks of players in the team and i < j < k, then the rank of the team is equal to A β
i + B β
j + C β
k.
You are given information about the pairs of players who have a conflict. Calculate the total sum of ranks over all possible valid teams modulo 2^{64}.
Input
The first line contains two space-separated integers n and m (3 β€ n β€ 2 β
10^5, 0 β€ m β€ 2 β
10^5) β the number of players and the number of conflicting pairs.
The second line contains three space-separated integers A, B and C (1 β€ A, B, C β€ 10^6) β coefficients for team rank calculation.
Each of the next m lines contains two space-separated integers u_i and v_i (0 β€ u_i, v_i < n, u_i β v_i) β pair of conflicting players.
It's guaranteed that each unordered pair of players appears in the input file no more than once.
Output
Print single integer β the total sum of ranks over all possible teams modulo 2^{64}.
Examples
Input
4 0
2 3 4
Output
64
Input
4 1
2 3 4
1 0
Output
38
Input
6 4
1 5 3
0 3
3 5
5 4
4 3
Output
164
Note
In the first example all 4 teams are valid, i.e. triples: {0, 1, 2}, {0, 1, 3}, {0, 2, 3} {1, 2, 3}.
In the second example teams are following: {0, 2, 3}, {1, 2, 3}.
In the third example teams are following: {0, 1, 2}, {0, 1, 4}, {0, 1, 5}, {0, 2, 4}, {0, 2, 5}, {1, 2, 3}, {1, 2, 4}, {1, 2, 5}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int n, m, x[N], y[N], l[N], r[N];
unsigned long long A, B, C, ans;
vector<int> L[N], R[N];
set<pair<int, int> > st;
inline unsigned long long sum(int l, int r) {
return (unsigned long long)(l + r) * (r - l + 1) / 2;
}
int main() {
scanf("%d%d%llu%llu%llu", &n, &m, &A, &B, &C);
for (int i = 0; i < m; i++) {
scanf("%d%d", &x[i], &y[i]);
if (x[i] > y[i]) swap(x[i], y[i]);
st.insert(make_pair(x[i], y[i]));
R[x[i]].push_back(y[i]);
L[y[i]].push_back(x[i]);
}
for (int i = 0; i < n; i++)
sort(L[i].begin(), L[i].end()), sort(R[i].begin(), R[i].end());
for (int i = 0; i < n; i++)
ans += (unsigned long long)(n - i - 1) * (n - i - 2) / 2 * A * i;
for (int i = 0; i < n; i++)
ans += (unsigned long long)i * (n - i - 1) * B * i;
for (int i = 0; i < n; i++)
ans += (unsigned long long)i * (i - 1) / 2 * C * i;
for (int i = 0; i < n; i++)
for (int j = 0; j < R[i].size(); j++) {
int k = n - R[i][j] - 1;
if (k < 0) continue;
ans -= A * i * k + B * R[i][j] * k + C * sum(R[i][j] + 1, n - 1);
}
for (int i = 0; i < n; i++)
for (int j = 0; j < R[i].size(); j++) {
int k = i;
if (k < 0) continue;
ans -= B * i * k + C * R[i][j] * k + A * sum(0, i - 1);
}
for (int i = 0; i < n; i++)
for (int j = 0; j < R[i].size(); j++) {
int k = R[i][j] - i - 1;
if (k < 0) continue;
ans -= A * i * k + C * R[i][j] * k + B * sum(i + 1, R[i][j] - 1);
}
for (int i = 0; i < n; i++) {
ans += (unsigned long long)R[i].size() * (R[i].size() - 1) / 2 * A * i;
for (int j = 0; j < R[i].size(); j++)
ans += B * R[i][j] * (R[i].size() - j - 1) + C * R[i][j] * j;
}
for (int i = 0; i < n; i++) {
ans += (unsigned long long)L[i].size() * R[i].size() * B * i;
for (int j = 0; j < L[i].size(); j++) ans += A * L[i][j] * R[i].size();
for (int j = 0; j < R[i].size(); j++) ans += C * R[i][j] * L[i].size();
}
for (int i = 0; i < n; i++) {
ans += (unsigned long long)L[i].size() * (L[i].size() - 1) / 2 * C * i;
for (int j = 0; j < L[i].size(); j++)
ans += B * L[i][j] * j + A * L[i][j] * (L[i].size() - j - 1);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < L[i].size(); j++) l[L[i][j]] = 1;
for (int j = 0; j < R[i].size(); j++) r[R[i][j]] = 1;
if ((unsigned long long)L[i].size() * R[i].size() * 20 <= m) {
for (int j = 0; j < L[i].size(); j++)
for (int k = 0; k < R[i].size(); k++)
if (st.count(make_pair(L[i][j], R[i][k])))
ans -= A * L[i][j] + B * i + C * R[i][k];
} else
for (int j = 0; j < m; j++)
if (l[x[j]] && r[y[j]]) ans -= A * x[j] + B * i + C * y[j];
for (int j = 0; j < L[i].size(); j++) l[L[i][j]] = 0;
for (int j = 0; j < R[i].size(); j++) r[R[i][j]] = 0;
}
printf("%llu\n", ans);
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?
Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.
First, he'll provide you a tree (not 1-tree) with n vertices, then he will ask you q queries. Each query contains 5 integers: x, y, a, b, and k. This means you're asked to determine if there exists a path from vertex a to b that contains exactly k edges after adding a bidirectional edge between vertices x and y. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.
Input
The first line contains an integer n (3 β€ n β€ 10^5), the number of vertices of the tree.
Next n-1 lines contain two integers u and v (1 β€ u,v β€ n, u β v) each, which means there is an edge between vertex u and v. All edges are bidirectional and distinct.
Next line contains an integer q (1 β€ q β€ 10^5), the number of queries Gildong wants to ask.
Next q lines contain five integers x, y, a, b, and k each (1 β€ x,y,a,b β€ n, x β y, 1 β€ k β€ 10^9) β the integers explained in the description. It is guaranteed that the edge between x and y does not exist in the original tree.
Output
For each query, print "YES" if there exists a path that contains exactly k edges from vertex a to b after adding an edge between vertices x and y. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
Output
YES
YES
NO
YES
NO
Note
The image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines).
<image>
Possible paths for the queries with "YES" answers are:
* 1-st query: 1 β 3 β 2
* 2-nd query: 1 β 2 β 3
* 4-th query: 3 β 4 β 2 β 3 β 4 β 2 β 3 β 4 β 2 β 3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct A {
int nod, nvl;
};
queue<int> q;
vector<int> v[100005], rmq[18];
A Repr_Euler[200005];
int nr;
int nivel[100005], prima_aparitie[100005];
void nivelare();
void dfs(int nod);
int distanta(int nod1, int nod2);
int main() {
int n, i, j, q, x, y, a, b, k, D1, D2, D3;
cin >> n;
for (i = 1; i < n; i++) {
cin >> x >> y;
v[x].push_back(y);
v[y].push_back(x);
}
nivelare();
dfs(1);
n = 2 * n - 1;
x = log2(n);
for (i = 1; i <= n; i++) rmq[0].push_back(Repr_Euler[i].nvl);
for (i = 1; i <= x; i++)
for (j = 0; j < n - (1 << i) + 1; j++)
rmq[i].push_back(min(rmq[i - 1][j], rmq[i - 1][j + (1 << (i - 1))]));
cin >> q;
while (q--) {
cin >> x >> y >> a >> b >> k;
D1 = distanta(a, b);
D2 = 1 + distanta(a, x) + distanta(y, b);
D3 = 1 + distanta(a, y) + distanta(x, b);
if (D1 <= k && D1 % 2 == k % 2)
cout << "YES" << '\n';
else if (D2 <= k && D2 % 2 == k % 2)
cout << "YES" << '\n';
else if (D3 <= k && D3 % 2 == k % 2)
cout << "YES" << '\n';
else
cout << "NO" << '\n';
}
return 0;
}
void nivelare() {
int x, i;
nivel[1] = 1;
q.push(1);
while (q.empty() == 0) {
x = q.front();
q.pop();
for (i = 0; i < v[x].size(); i++)
if (nivel[v[x][i]] == 0) {
nivel[v[x][i]] = nivel[x] + 1;
q.push(v[x][i]);
}
}
}
void dfs(int nod) {
int i;
for (i = 0; i < v[nod].size(); i++)
if (nivel[nod] == nivel[v[nod][i]] - 1) {
Repr_Euler[++nr].nod = nod;
Repr_Euler[nr].nvl = nivel[nod];
if (prima_aparitie[nod] == 0) prima_aparitie[nod] = nr;
dfs(v[nod][i]);
}
Repr_Euler[++nr].nod = nod;
Repr_Euler[nr].nvl = nivel[nod];
if (prima_aparitie[nod] == 0) prima_aparitie[nod] = nr;
}
int distanta(int nod1, int nod2) {
int st, dr, x, val, a, b;
st = prima_aparitie[nod1] - 1;
dr = prima_aparitie[nod2] - 1;
if (st > dr) swap(st, dr);
x = log2(dr - st + 1);
a = rmq[x][st];
b = rmq[x][dr - (1 << x) + 1];
val = min(rmq[x][st], rmq[x][dr - (1 << x) + 1]);
return nivel[nod1] + nivel[nod2] - 2 * val;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Vladimir wants to modernize partitions in his office. To make the office more comfortable he decided to remove a partition and plant several bamboos in a row. He thinks it would be nice if there are n bamboos in a row, and the i-th from the left is ai meters high.
Vladimir has just planted n bamboos in a row, each of which has height 0 meters right now, but they grow 1 meter each day. In order to make the partition nice Vladimir can cut each bamboo once at any height (no greater that the height of the bamboo), and then the bamboo will stop growing.
Vladimir wants to check the bamboos each d days (i.e. d days after he planted, then after 2d days and so on), and cut the bamboos that reached the required height. Vladimir wants the total length of bamboo parts he will cut off to be no greater than k meters.
What is the maximum value d he can choose so that he can achieve what he wants without cutting off more than k meters of bamboo?
Input
The first line contains two integers n and k (1 β€ n β€ 100, 1 β€ k β€ 1011) β the number of bamboos and the maximum total length of cut parts, in meters.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) β the required heights of bamboos, in meters.
Output
Print a single integer β the maximum value of d such that Vladimir can reach his goal.
Examples
Input
3 4
1 3 5
Output
3
Input
3 40
10 30 50
Output
32
Note
In the first example Vladimir can check bamboos each 3 days. Then he will cut the first and the second bamboos after 3 days, and the third bamboo after 6 days. The total length of cut parts is 2 + 0 + 1 = 3 meters.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, a[109];
set<int> s;
long long k;
scanf("%d", &n);
scanf("%lld", &k);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
k += a[i];
for (int j = 1; j * j <= a[i]; j++) {
s.insert(j);
s.insert(ceil(a[i] * 1.0 / j));
}
}
long long ans = 1;
for (auto it : s) {
long long sum = 0;
for (int i = 0; i < n; i++) sum += ceil(a[i] * 1.0 / it);
if (it <= k / sum) ans = max(ans, k / sum);
}
printf("%lld\n", ans);
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle.
A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen people be [a_{i_1}, a_{i_2}, ..., a_{i_k}], where k is the number of people you choose. Then the condition |a_{i_j} - a_{i_{j + 1}}| β€ 1 should be satisfied for all j from 1 to k-1 and the condition |a_{i_1} - a_{i_k}| β€ 1 should be also satisfied. |x| means the absolute value of x. It is obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of people.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5), where a_i is the height of the i-th person.
Output
In the first line of the output print k β the number of people in the maximum balanced circle.
In the second line print k integers res_1, res_2, ..., res_k, where res_j is the height of the j-th person in the maximum balanced circle. The condition |res_{j} - res_{j + 1}| β€ 1 should be satisfied for all j from 1 to k-1 and the condition |res_{1} - res_{k}| β€ 1 should be also satisfied.
Examples
Input
7
4 3 5 1 2 2 1
Output
5
2 1 1 2 3
Input
5
3 7 5 1 5
Output
2
5 5
Input
3
5 1 4
Output
2
4 5
Input
7
2 2 3 2 1 2 2
Output
7
1 2 2 2 2 3 2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1 + 2e5;
int n, a[MAXN], f[MAXN], m, ans = 1 + 1e9, cnt, b[MAXN], l = 1, r = 1, lp = 1;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
++f[a[i]];
}
sort(a + 1, a + n + 1);
cnt = 0;
for (int i = 1; i <= n; ++i) {
ans = min(ans, f[a[i]]);
if (a[i] != a[i - 1]) b[++m] = a[i];
}
int j = 1;
l = 1;
r = 1;
lp = 1;
cnt = 0;
while (j <= m + 1) {
if (b[j] - b[j - 1] == 1) {
cnt += f[b[j]];
if (f[b[j]] == 1 && j != lp) {
if (ans <= cnt) {
ans = cnt;
r = j;
l = lp;
}
if (b[j] + 1 == b[j + 1]) {
lp = j;
cnt = f[b[j]];
++j;
} else {
lp = j + 1;
cnt = f[b[j + 1]];
j += 2;
}
} else
++j;
} else {
if (ans <= cnt) {
ans = cnt;
l = lp;
r = j - 1;
}
cnt = f[b[j]];
lp = j;
++j;
}
}
cout << ans << '\n';
for (int i = l; i <= r; ++i) {
cout << b[i] << ' ';
--f[b[i]];
}
for (int i = r; i >= l; --i) {
while (f[b[i]]--) cout << b[i] << ' ';
}
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
You are given an array a of length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 β€ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 β€ a_2 β€ ... β€ a_n) using only allowed swaps.
For example, if a = [3, 2, 1] and p = [1, 2], then we can first swap elements a[2] and a[3] (because position 2 is contained in the given set p). We get the array a = [3, 1, 2]. Then we swap a[1] and a[2] (position 1 is also contained in p). We get the array a = [1, 3, 2]. Finally, we swap a[2] and a[3] again and get the array a = [1, 2, 3], sorted in non-decreasing order.
You can see that if a = [4, 1, 2, 3] and p = [3, 2] then you cannot sort the array.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases.
Then t test cases follow. The first line of each test case contains two integers n and m (1 β€ m < n β€ 100) β the number of elements in a and the number of elements in p. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 100). The third line of the test case contains m integers p_1, p_2, ..., p_m (1 β€ p_i < n, all p_i are distinct) β the set of positions described in the problem statement.
Output
For each test case, print the answer β "YES" (without quotes) if you can sort the initial array in non-decreasing order (a_1 β€ a_2 β€ ... β€ a_n) using only allowed swaps. Otherwise, print "NO".
Example
Input
6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
Output
YES
NO
YES
YES
NO
YES
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 205, M = 1000000007, BIG = 0x3f3f3f3f;
int ct = 0;
int m, n;
int a[N], p[N];
bool Read() {
cin >> n;
if (cin.eof()) return 0;
cin >> m;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= m; i++) cin >> p[i];
return 1;
}
void Process() {
for (int i = 0; i < 10005; i++)
for (int j = 1; j <= m; j++)
if (a[p[j]] > a[p[j] + 1]) swap(a[p[j]], a[p[j] + 1]);
for (int i = 1; i < n; i++)
if (a[i] > a[i + 1]) {
cout << "NO\n";
return;
}
cout << "YES\n";
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T;
cin >> T;
while (T-- && Read()) Process();
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
It has been decided that a programming contest sponsored by company A will be held, so we will post the notice on a bulletin board.
The bulletin board is in the form of a grid with N rows and N columns, and the notice will occupy a rectangular region with H rows and W columns.
How many ways are there to choose where to put the notice so that it completely covers exactly HW squares?
Constraints
* 1 \leq H, W \leq N \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
H
W
Output
Print the answer.
Examples
Input
3
2
3
Output
2
Input
100
1
1
Output
10000
Input
5
4
2
Output
8
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a,b,c;
scanf("%d %d %d ",&a,&b,&c);
printf("%d\n",(a-b+1)*(a-c+1));
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
A and B are preparing themselves for programming contests.
B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.
Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.
However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared β the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.
Can you help B find out exactly what two errors he corrected?
Input
The first line of the input contains integer n (3 β€ n β€ 105) β the initial number of compilation errors.
The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the errors the compiler displayed for the first time.
The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 β the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one.
The fourth line contains n - 2 space-separated integers Ρ1, Ρ2, ..., Ρn - 2 β the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
Output
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
Examples
Input
5
1 5 8 123 7
123 7 5 1
5 1 7
Output
8
123
Input
6
1 4 3 3 5 7
3 7 5 4 3
4 3 7 5
Output
1
3
Note
In the first test sample B first corrects the error number 8, then the error number 123.
In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[100000] = {};
int main() {
long long b = 0, c = 0, d = 0;
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
b += a[i];
}
for (int i = 0; i < n - 1; i++) {
cin >> a[i];
c += a[i];
}
int x = b - c;
for (int i = 0; i < n - 2; i++) {
cin >> a[i];
d += a[i];
}
int y = c - d;
cout << x << '\n' << y;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!
The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).
A subsequence a_{i_1}, a_{i_2}, β¦, a_{i_k} where 1β€ i_1 < i_2 < β¦ < i_kβ€ n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < β¦ < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > β¦ > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.
For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3.
Note, the lengths of LIS and LDS can be different.
So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
Input
The only line contains one integer n (1 β€ n β€ 10^5) β the length of permutation that you need to build.
Output
Print a permutation that gives a minimum sum of lengths of LIS and LDS.
If there are multiple answers, print any.
Examples
Input
4
Output
3 4 1 2
Input
2
Output
2 1
Note
In the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid.
In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid.
### Response
```cpp
#include <bits/stdc++.h>
int main() {
long n;
scanf("%ld", &n);
long t(0);
while (t * t < n) {
++t;
}
while (n) {
long x = ((n - 1) / t) * t;
for (long p = x + 1; p <= n; p++) {
printf("%ld ", p);
}
n = x;
}
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
"Teishi-zushi", a Japanese restaurant, is a plain restaurant with only one round counter. The outer circumference of the counter is C meters. Customers cannot go inside the counter.
Nakahashi entered Teishi-zushi, and he was guided to the counter. Now, there are N pieces of sushi (vinegared rice with seafood and so on) on the counter. The distance measured clockwise from the point where Nakahashi is standing to the point where the i-th sushi is placed, is x_i meters. Also, the i-th sushi has a nutritive value of v_i kilocalories.
Nakahashi can freely walk around the circumference of the counter. When he reach a point where a sushi is placed, he can eat that sushi and take in its nutrition (naturally, the sushi disappears). However, while walking, he consumes 1 kilocalories per meter.
Whenever he is satisfied, he can leave the restaurant from any place (he does not have to return to the initial place). On balance, at most how much nutrition can he take in before he leaves? That is, what is the maximum possible value of the total nutrition taken in minus the total energy consumed? Assume that there are no other customers, and no new sushi will be added to the counter. Also, since Nakahashi has plenty of nutrition in his body, assume that no matter how much he walks and consumes energy, he never dies from hunger.
Constraints
* 1 β€ N β€ 10^5
* 2 β€ C β€ 10^{14}
* 1 β€ x_1 < x_2 < ... < x_N < C
* 1 β€ v_i β€ 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N C
x_1 v_1
x_2 v_2
:
x_N v_N
Output
If Nakahashi can take in at most c kilocalories on balance before he leaves the restaurant, print c.
Examples
Input
3 20
2 80
9 120
16 1
Output
191
Input
3 20
2 80
9 1
16 120
Output
192
Input
1 100000000000000
50000000000000 1
Output
0
Input
15 10000000000
400000000 1000000000
800000000 1000000000
1900000000 1000000000
2400000000 1000000000
2900000000 1000000000
3300000000 1000000000
3700000000 1000000000
3800000000 1000000000
4000000000 1000000000
4100000000 1000000000
5200000000 1000000000
6600000000 1000000000
8000000000 1000000000
9300000000 1000000000
9700000000 1000000000
Output
6500000000
### Response
```cpp
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long LL;
#define N 100000 + 5
int n, V[N];
LL c, ans, Max_1[N], _Max_1[N], Max_2[N], _Max_2[N], X[N], Sum_1[N], Sum_2[N];
int main()
{
scanf("%d%lld", &n, &c);
for (int i = 1; i <= n; i ++)
scanf("%lld%d", X + i, V + i);
for (int i = 1; i <= n; i ++)
{
Sum_1[i] = Sum_1[i - 1] + V[i] - (X[i] - X[i - 1]);
Max_1[i] = max(Max_1[i - 1], Sum_1[i]);
_Max_1[i] = max(_Max_1[i - 1], Sum_1[i] - X[i]);
}
X[n + 1] = c;
for (int i = n; i; i --)
{
Sum_2[i] = Sum_2[i + 1] + V[i] - (X[i + 1] - X[i]);
Max_2[i] = max(Max_2[i + 1], Sum_2[i]);
_Max_2[i] = max(_Max_2[i + 1], Sum_2[i] - (c - X[i]));
}
for (int i = 0; i <= n; i ++)
ans = max(ans, max(Max_1[i] + _Max_2[i + 1], _Max_1[i] + Max_2[i + 1]));//, printf("%lld %lld, %lld %lld\n", Max_1[i], _Max_1[i], Max_2[n - i + 1], _Max_2[n - i + 1]);
printf("%lld\n", ans);
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
The crowdedness of the discotheque would never stop our friends from having fun, but a bit more spaciousness won't hurt, will it?
The discotheque can be seen as an infinite xy-plane, in which there are a total of n dancers. Once someone starts moving around, they will move only inside their own movement range, which is a circular area Ci described by a center (xi, yi) and a radius ri. No two ranges' borders have more than one common point, that is for every pair (i, j) (1 β€ i < j β€ n) either ranges Ci and Cj are disjoint, or one of them is a subset of the other. Note that it's possible that two ranges' borders share a single common point, but no two dancers have exactly the same ranges.
Tsukihi, being one of them, defines the spaciousness to be the area covered by an odd number of movement ranges of dancers who are moving. An example is shown below, with shaded regions representing the spaciousness if everyone moves at the same time.
<image>
But no one keeps moving for the whole night after all, so the whole night's time is divided into two halves β before midnight and after midnight. Every dancer moves around in one half, while sitting down with friends in the other. The spaciousness of two halves are calculated separately and their sum should, of course, be as large as possible. The following figure shows an optimal solution to the example above.
<image>
By different plans of who dances in the first half and who does in the other, different sums of spaciousness over two halves are achieved. You are to find the largest achievable value of this sum.
Input
The first line of input contains a positive integer n (1 β€ n β€ 1 000) β the number of dancers.
The following n lines each describes a dancer: the i-th line among them contains three space-separated integers xi, yi and ri ( - 106 β€ xi, yi β€ 106, 1 β€ ri β€ 106), describing a circular movement range centered at (xi, yi) with radius ri.
Output
Output one decimal number β the largest achievable sum of spaciousness over two halves of the night.
The output is considered correct if it has a relative or absolute error of at most 10 - 9. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if <image>.
Examples
Input
5
2 1 6
0 4 1
2 -1 3
1 -2 1
4 -1 1
Output
138.23007676
Input
8
0 0 1
0 0 2
0 0 3
0 0 4
0 0 5
0 0 6
0 0 7
0 0 8
Output
289.02652413
Note
The first sample corresponds to the illustrations in the legend.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n;
double pi = acos(-1.0);
struct circle {
int r, x, y, cover;
} cir[1001];
int cmp(circle a, circle b) { return a.r > b.r; }
long long dist_sq(circle a, circle b) {
return (long long)(a.x - b.x) * (a.x - b.x) +
(long long)(a.y - b.y) * (a.y - b.y);
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d%d%d", &cir[i].x, &cir[i].y, &cir[i].r);
}
sort(cir + 1, cir + 1 + n, cmp);
cir[1].cover = 0;
for (int i = 2; i <= n; i++) {
for (int j = i - 1; j >= 1; j--) {
if (dist_sq(cir[i], cir[j]) < (long long)cir[j].r * cir[j].r) {
cir[i].cover = cir[j].cover + 1;
break;
}
}
}
long long answer = 0;
for (int i = 1; i <= n; i++) {
if (cir[i].cover == 0) answer += (long long)cir[i].r * cir[i].r;
cir[i].cover--;
}
for (int i = 1; i <= n; i++) {
if (cir[i].cover >= 0) {
if (cir[i].cover & 1)
answer -= (long long)cir[i].r * cir[i].r;
else
answer += (long long)cir[i].r * cir[i].r;
}
}
printf("%.8lf", (double)answer * pi);
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers β one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.
Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
Input
The first line contains a single integer k (1 β€ k β€ 15), the number of boxes.
The i-th of the next k lines first contains a single integer n_i (1 β€ n_i β€ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, β¦, a_{i,n_i} (|a_{i,j}| β€ 10^9), the integers in the i-th box.
It is guaranteed that all a_{i,j} are distinct.
Output
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards.
If there are multiple solutions, output any of those.
You can print each letter in any case (upper or lower).
Examples
Input
4
3 1 7 4
2 3 2
2 8 5
1 10
Output
Yes
7 2
2 3
5 1
10 4
Input
2
2 3 -2
2 -1 5
Output
No
Input
2
2 -10 10
2 0 -20
Output
Yes
-10 2
-20 1
Note
In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10.
In the second sample, it is not possible to pick and redistribute the numbers in the required way.
In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 5e3 + 5;
int k, cnt, tot;
int a[20][N], b[20], tmp[N * 20];
long long sum[20], SS;
map<long long, int> mp;
int id[N * 20], E[1 << 16];
vector<int> G[N * 20], Q[1 << 16];
int vis[N * 20], look[1 << 16], dp[1 << 16];
int pre[1 << 16], l[20], r[20];
void dfs(int x, int statu) {
if (vis[x]) {
int now = 0;
for (int i = tot; i; i--) {
now |= b[id[E[i]] - 1];
if (x == E[i]) break;
}
if (!look[now]) {
look[now] = 1;
for (int i = tot; i; i--) {
Q[now].push_back(E[i]);
if (E[i] == x) break;
}
}
return;
}
if (statu & b[id[x] - 1]) return;
statu |= b[id[x] - 1];
vis[x] = 1;
E[++tot] = x;
for (int i = 0; i < G[x].size(); i++) {
dfs(G[x][i], statu);
}
vis[x] = 0;
--tot;
}
int main() {
b[0] = 1;
for (int i = 1; i <= 16; i++) b[i] = b[i - 1] * 2;
scanf("%d", &k);
for (int i = 1; i <= k; i++) {
scanf("%d", &a[i][0]);
for (int j = 1; j <= a[i][0]; j++) {
scanf("%d", &a[i][j]);
sum[i] += a[i][j];
mp[a[i][j]] = ++cnt;
id[cnt] = i;
tmp[cnt] = a[i][j];
}
SS += sum[i];
}
if (SS % k) {
puts("No");
return 0;
}
SS /= k;
for (int i = 1; i <= k; i++) {
for (int j = 1; j <= a[i][0]; j++) {
if (mp[SS - (sum[i] - a[i][j])]) {
G[mp[a[i][j]]].push_back(mp[SS - (sum[i] - a[i][j])]);
}
}
}
for (int i = 1; i <= cnt; i++) dfs(i, 0);
dp[0] = 1;
for (int i = 0; i < b[k]; i++) {
if (dp[i]) {
int M = i ^ (b[k] - 1);
for (int j = M; j; j = (j - 1) & M) {
if (look[j]) {
dp[i | j] = 1;
pre[i | j] = i;
}
}
}
}
if (!dp[b[k] - 1]) {
puts("No");
return 0;
}
int x = b[k] - 1;
while (x) {
int T = x - pre[x];
for (int i = 0; i < Q[T].size(); i++) {
l[id[mp[SS - sum[id[Q[T][i]]] + tmp[Q[T][i]]]]] =
SS - sum[id[Q[T][i]]] + tmp[Q[T][i]];
r[id[mp[SS - sum[id[Q[T][i]]] + tmp[Q[T][i]]]]] = id[Q[T][i]];
}
x = pre[x];
}
puts("Yes");
for (int i = 1; i <= k; i++) {
printf("%d %d\n", l[i], r[i]);
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
You are given an n Γ m table, consisting of characters Β«AΒ», Β«GΒ», Β«CΒ», Β«TΒ». Let's call a table nice, if every 2 Γ 2 square contains all four distinct characters. Your task is to find a nice table (also consisting of Β«AΒ», Β«GΒ», Β«CΒ», Β«TΒ»), that differs from the given table in the minimum number of characters.
Input
First line contains two positive integers n and m β number of rows and columns in the table you are given (2 β€ n, m, n Γ m β€ 300 000). Then, n lines describing the table follow. Each line contains exactly m characters Β«AΒ», Β«GΒ», Β«CΒ», Β«TΒ».
Output
Output n lines, m characters each. This table must be nice and differ from the input table in the minimum number of characters.
Examples
Input
2 2
AG
CT
Output
AG
CT
Input
3 5
AGCAG
AGCAG
AGCAG
Output
TGCAT
CATGC
TGCAT
Note
In the first sample, the table is already nice. In the second sample, you can change 9 elements to make the table nice.
### Response
```cpp
#include <bits/stdc++.h>
const int ms = 3e5 + 19;
using namespace std;
string per = "ACGT";
int n, m, ans = ms;
string c[ms], cer[ms];
bool w[ms];
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> c[i];
cer[i] = c[i];
}
do {
int cur = 0;
for (int i = 0; i < n; i++) {
int c1 = 0, c2 = 0;
for (int j = 0; j < m; j++) {
c1 += per[(i & 1) * 2 + (j & 1)] != c[i][j];
c2 += per[(i & 1) * 2 + !(j & 1)] != c[i][j];
}
w[i] = c1 < c2;
cur += min(c1, c2);
}
if (cur < ans) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cer[i][j] =
w[i] ? per[(i & 1) * 2 + (j & 1)] : per[(i & 1) * 2 + !(j & 1)];
}
}
ans = cur;
}
cur = 0;
for (int i = 0; i < m; i++) {
int c1 = 0, c2 = 0;
for (int j = 0; j < n; j++) {
c1 += per[(i & 1) * 2 + (j & 1)] != c[j][i];
c2 += per[(i & 1) * 2 + !(j & 1)] != c[j][i];
}
w[i] = c1 < c2;
cur += min(c1, c2);
}
if (cur < ans) {
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
cer[j][i] =
w[i] ? per[(i & 1) * 2 + (j & 1)] : per[(i & 1) * 2 + !(j & 1)];
ans = cur;
}
} while (next_permutation(per.begin(), per.end()));
for (int i = 0; i < n; i++) cout << cer[i] << "\n";
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
The Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail.
We assume that the hash table consists of h cells numbered from 0 to h - 1. Objects are added to and removed from it. Every object has its own unique identifier. In addition, every object has a corresponding hash value β an integer between 0 and h - 1, inclusive. When an object is added to the table, if the cell corresponding to the hash value of the object is free, then this object goes there. If the cell is already occupied by another object, there is a collision. When an object is deleted from the table, the cell which it occupied becomes empty.
The Smart Beaver has recently learned about the method of linear probing to resolve collisions. It is as follows. Let's say that the hash value for the added object equals t and cell t of the table is already occupied. Then we try to add this object to cell (t + m) mod h. If it is also occupied, then we try cell (t + 2Β·m) mod h, then cell (t + 3Β·m) mod h, and so on. Note that in some cases it's possible that the new object can not be added to the table. It is guaranteed that the input for this problem doesn't contain such situations.
The operation a mod b means that we take the remainder of the division of number a by number b.
This technique immediately seemed very inoptimal to the Beaver, and he decided to assess its inefficiency. So, you are given a sequence of operations, each of which is either an addition of an object to the table or a deletion of an object from the table. When adding a new object, a sequence of calls to the table is performed. Calls to occupied cells are called dummy. In other words, if the result of the algorithm described above is the object being added to cell (t + iΒ·m) mod h (i β₯ 0), then exactly i dummy calls have been performed.
Your task is to calculate the total number of dummy calls to the table for the given sequence of additions and deletions. When an object is deleted from the table, assume that no dummy calls are performed. The table is empty before performing the operations, that is, initially it doesn't contain any objects.
Input
The first line of input contains three integers h, m and n (1 β€ m < h), separated by spaces, where h is the size of the hash table, m is the number that is used to resolve collisions, n is the number of operations.
The following n lines contains the descriptions of the operations. Their execution order corresponds to the order in which they appear in the input file. Each operation is described by a single line. The operations are described as follows:
* "+ id hash"
This is the format of the operation that adds an object to the table. The first character is "+" (ASCII 43), followed by a single space, then the object identifier id (0 β€ id β€ 109), then another space, and the hash value of the given object hash (0 β€ hash < h). The object identifier and the hash value of this object are integers.
* "- id"
This is the format of the operation that deletes an object from the table. The first character is "-" (ASCII 45), followed by a single space, then the object identifier id (0 β€ id β€ 109). The object identifier is an integer.
It is guaranteed that for all addition operations the value of id is unique. It is also guaranteed that the initial data is correct, that is, it's always possible to add an object to the hash table and there won't be any deletions of nonexisting objects.
The input limitations for getting 20 points are:
* 1 β€ h β€ 5000
* 1 β€ n β€ 5000
The input limitations for getting 50 points are:
* 1 β€ h β€ 5Β·104
* 1 β€ n β€ 5Β·104
The input limitations for getting 100 points are:
* 1 β€ h β€ 2Β·105
* 1 β€ n β€ 2Β·105
Output
Print a single number β the total number of dummy calls to the hash table.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams and the %I64d specifier.
Examples
Input
10 2 7
+ 11 0
+ 22 2
+ 33 6
+ 44 0
+ 55 0
- 22
+ 66 0
Output
7
Input
5 1 6
+ 123 0
+ 234 1
+ 345 2
- 234
+ 456 0
+ 567 0
Output
4
### Response
```cpp
#include <bits/stdc++.h>
int IntMaxVal = (int)1e20;
int IntMinVal = (int)-1e20;
long long LongMaxVal = (long long)1e20;
long long LongMinVal = (long long)-1e20;
using namespace std;
template <typename T>
struct argument_type;
template <typename T, typename U>
struct argument_type<T(U)> {};
template <typename T1, typename T2>
istream& operator>>(istream& is, pair<T1, T2>& s) {
is >> s.first >> s.second;
return is;
}
class minTree {
int gp2(int n) {
int x = 2;
while (x < n) x *= 2;
return x;
}
vector<int> data;
int n;
public:
void init(int n) {
n = this->n = gp2(n);
data.resize(2 * n);
for (int i = 0; i < n; ++i) data[i + n] = i;
for (int i = n - 1; i >= 1; --i)
data[i] = min(data[2 * i], data[2 * i + 1]);
}
void set(int i, int x) {
i += n;
data[i] = x;
i /= 2;
while (i) {
data[i] = min(data[2 * i], data[2 * i + 1]);
i /= 2;
}
}
int getMin(int l, int r, int i, int fl, int fr) {
if (l == fl && r + 1 == fr) return data[i];
int m = (fl + fr) / 2;
if (l < m && r >= m)
return min(getMin(l, m - 1, 2 * i, fl, m),
getMin(m, r, 2 * i + 1, m, fr));
else if (l < m)
return getMin(l, r, 2 * i, fl, m);
else
return getMin(l, r, 2 * i + 1, m, fr);
}
int getMin(int l, int r) { return getMin(l, r, 1, 0, n); }
};
int main() {
srand(time(NULL));
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int h;
cin >> h;
;
int m;
cin >> m;
;
int n;
cin >> n;
;
int cur = m;
int cycleLength = 1;
while (cur) {
cycleLength++;
cur = (cur + m) % h;
}
int cycles = h / cycleLength;
vector<minTree> trees(cycles);
for (auto& tr : trees) tr.init(cycleLength);
vector<int> treeIndex(h, -1);
vector<int> indexInTree(h);
int nextTree = 0;
for (int i = 0; i < h; ++i)
if (treeIndex[i] == -1) {
treeIndex[i] = nextTree++;
indexInTree[i] = 0;
cur = i;
while (true) {
int then = (cur + m) % h;
if (then == i) break;
indexInTree[then] = indexInTree[cur] + 1;
treeIndex[then] = treeIndex[i];
cur = then;
}
}
map<int, int> position;
long long res = 0;
while (n-- > 0) {
char c;
cin >> c;
;
int id;
cin >> id;
;
if (c == '-') {
int pos = position[id];
trees[treeIndex[pos]].set(indexInTree[pos], indexInTree[pos]);
} else {
int pos;
cin >> pos;
;
int iTree = treeIndex[pos];
int lookupPos = indexInTree[pos];
int actualPos = trees[iTree].getMin(lookupPos, cycleLength - 1);
if (actualPos == IntMaxVal)
actualPos = trees[iTree].getMin(0, lookupPos - 1);
int dist;
if (actualPos >= lookupPos)
dist = actualPos - lookupPos;
else
dist = cycleLength - lookupPos + actualPos;
res += dist;
trees[iTree].set(actualPos, IntMaxVal);
long long longPos = pos + 1LL * dist * m;
longPos %= h;
position[id] = (int)longPos;
}
}
cout << res;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Iahub is playing an uncommon game. Initially, he has n boxes, numbered 1, 2, 3, ..., n. Each box has some number of candies in it, described by a sequence a1, a2, ..., an. The number ak represents the number of candies in box k.
The goal of the game is to move all candies into exactly two boxes. The rest of n - 2 boxes must contain zero candies. Iahub is allowed to do several (possible zero) moves. At each move he chooses two different boxes i and j, such that ai β€ aj. Then, Iahub moves from box j to box i exactly ai candies. Obviously, when two boxes have equal number of candies, box number j becomes empty.
Your task is to give him a set of moves such as Iahub to archive the goal of the game. If Iahub can't win the game for the given configuration of boxes, output -1. Please note that in case there exist a solution, you don't need to print the solution using minimal number of moves.
Input
The first line of the input contains integer n (3 β€ n β€ 1000). The next line contains n non-negative integers: a1, a2, ..., an β sequence elements. It is guaranteed that sum of all numbers in sequence a is up to 106.
Output
In case there exists no solution, output -1. Otherwise, in the first line output integer c (0 β€ c β€ 106), representing number of moves in your solution. Each of the next c lines should contain two integers i and j (1 β€ i, j β€ n, i β j): integers i, j in the kth line mean that at the k-th move you will move candies from the j-th box to the i-th one.
Examples
Input
3
3 6 9
Output
2
2 3
1 3
Input
3
0 1 0
Output
-1
Input
4
0 1 1 0
Output
0
Note
For the first sample, after the first move the boxes will contain 3, 12 and 3 candies. After the second move, the boxes will contain 6, 12 and 0 candies. Now all candies are in exactly 2 boxes.
For the second sample, you can observe that the given configuration is not valid, as all candies are in a single box and they should be in two boxes. Also, any move won't change the configuration, so there exists no solution.
For the third sample, all candies are already in 2 boxes. Hence, no move is needed.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 100005;
pair<int, int> v;
vector<pair<int, int> > ans;
int val[N], b[3], n;
int cmp(int x, int y) { return val[x] < val[y]; }
inline void doit(int x, int y) {
ans.push_back(make_pair(x, y));
val[y] -= val[x];
val[x] <<= 1;
}
inline void solve(int a[3]) {
sort(a, a + 3, cmp);
if (!val[a[0]]) {
v = make_pair(a[1], a[2]);
return;
}
int t = val[a[1]] / val[a[0]];
for (; t; t >>= 1)
if (t & 1)
doit(a[0], a[1]);
else
doit(a[0], a[2]);
solve(a);
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &val[i]);
for (int i = 1; i <= n; i++)
if (val[i]) {
if (!v.first)
v.first = i;
else if (!v.second)
v.second = i;
else
b[0] = v.first, b[1] = v.second, b[2] = i, solve(b);
}
if (!v.second) {
puts("-1");
return 0;
}
printf("%d\n", (int)ans.size());
for (pair<int, int> i : ans) printf("%d %d\n", i.first, i.second);
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
One day Vasya was going home when he saw a box lying on the road. The box can be represented as a rectangular parallelepiped. Vasya needed no time to realize that the box is special, as all its edges are parallel to the coordinate axes, one of its vertices is at point (0, 0, 0), and the opposite one is at point (x1, y1, z1). The six faces of the box contain some numbers a1, a2, ..., a6, exactly one number right in the center of each face.
<image>
The numbers are located on the box like that:
* number a1 is written on the face that lies on the ZOX plane;
* a2 is written on the face, parallel to the plane from the previous point;
* a3 is written on the face that lies on the XOY plane;
* a4 is written on the face, parallel to the plane from the previous point;
* a5 is written on the face that lies on the YOZ plane;
* a6 is written on the face, parallel to the plane from the previous point.
At the moment Vasya is looking at the box from point (x, y, z). Find the sum of numbers that Vasya sees. Note that all faces of the box are not transparent and Vasya can't see the numbers through the box. The picture contains transparent faces just to make it easier to perceive. You can consider that if Vasya is looking from point, lying on the plane of some face, than he can not see the number that is written on this face. It is enough to see the center of a face to see the corresponding number for Vasya. Also note that Vasya always reads correctly the ai numbers that he sees, independently of their rotation, angle and other factors (that is, for example, if Vasya sees some ai = 6, then he can't mistake this number for 9 and so on).
Input
The fist input line contains three space-separated integers x, y and z (|x|, |y|, |z| β€ 106) β the coordinates of Vasya's position in space. The second line contains three space-separated integers x1, y1, z1 (1 β€ x1, y1, z1 β€ 106) β the coordinates of the box's vertex that is opposite to the vertex at point (0, 0, 0). The third line contains six space-separated integers a1, a2, ..., a6 (1 β€ ai β€ 106) β the numbers that are written on the box faces.
It is guaranteed that point (x, y, z) is located strictly outside the box.
Output
Print a single integer β the sum of all numbers on the box faces that Vasya sees.
Examples
Input
2 2 2
1 1 1
1 2 3 4 5 6
Output
12
Input
0 0 10
3 2 3
1 2 3 4 5 6
Output
4
Note
The first sample corresponds to perspective, depicted on the picture. Vasya sees numbers a2 (on the top face that is the darkest), a6 (on the right face that is the lightest) and a4 (on the left visible face).
In the second sample Vasya can only see number a4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int x, y, z;
scanf("%d%d%d", &x, &y, &z);
int x1, y1, z1;
scanf("%d%d%d", &x1, &y1, &z1);
int a[6];
for (int i = 0; i < 6; i++) scanf("%d", &a[i]);
int s = 0;
if (x < 0) s += a[4];
if (x > x1) s += a[5];
if (y < 0) s += a[0];
if (y > y1) s += a[1];
if (z < 0) s += a[2];
if (z > z1) s += a[3];
printf("%d\n", s);
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
You are given n segments on the coordinate axis Ox and the number k. The point is satisfied if it belongs to at least k segments. Find the smallest (by the number of segments) set of segments on the coordinate axis Ox which contains all satisfied points and no others.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 106) β the number of segments and the value of k.
The next n lines contain two integers li, ri ( - 109 β€ li β€ ri β€ 109) each β the endpoints of the i-th segment. The segments can degenerate and intersect each other. The segments are given in arbitrary order.
Output
First line contains integer m β the smallest number of segments.
Next m lines contain two integers aj, bj (aj β€ bj) β the ends of j-th segment in the answer. The segments should be listed in the order from left to right.
Examples
Input
3 2
0 5
-3 2
3 8
Output
2
0 2
3 5
Input
3 2
0 5
-3 3
3 8
Output
1
0 5
### Response
```cpp
#include <bits/stdc++.h>
struct punct {
int x, tip;
inline bool operator<(const punct &b) const {
if (x == b.x) return tip < b.tip;
return x < b.x;
}
};
std::vector<punct> intervale, rasp;
int main() {
int n, k;
scanf("%d %d ", &n, &k);
for (int i = 1; i <= n; i++) {
int st, dr;
scanf("%d %d ", &st, &dr);
punct a;
a.tip = -1;
a.x = st;
intervale.push_back(a);
a.tip = 1;
a.x = dr;
intervale.push_back(a);
}
std::sort(intervale.begin(), intervale.end());
int X = 0;
for (int i = 0; i < intervale.size(); i++) {
int op;
if (X == k - 1 && intervale[i].tip == -1) {
op = intervale[i].x;
}
if (X == k && intervale[i].tip == 1) {
punct a;
a.tip = intervale[i].x;
a.x = op;
rasp.push_back(a);
}
X -= intervale[i].tip;
}
printf("%d\n", rasp.size());
for (int i = 0; i < rasp.size(); i++) {
printf("%d %d\n", rasp[i].x, rasp[i].tip);
}
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows:
There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i β j.
Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections.
* Building a power station in City i will cost c_i yen;
* Making a connection between City i and City j will cost k_i + k_j yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City i and City j are connected by a wire, the wire will go through any shortest path from City i to City j. Thus, the length of the wire if City i and City j are connected is |x_i - x_j| + |y_i - y_j| km.
Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help.
And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made.
If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them.
Input
First line of input contains a single integer n (1 β€ n β€ 2000) β the number of cities.
Then, n lines follow. The i-th line contains two space-separated integers x_i (1 β€ x_i β€ 10^6) and y_i (1 β€ y_i β€ 10^6) β the coordinates of the i-th city.
The next line contains n space-separated integers c_1, c_2, ..., c_n (1 β€ c_i β€ 10^9) β the cost of building a power station in the i-th city.
The last line contains n space-separated integers k_1, k_2, ..., k_n (1 β€ k_i β€ 10^9).
Output
In the first line print a single integer, denoting the minimum amount of yen needed.
Then, print an integer v β the number of power stations to be built.
Next, print v space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from 1 to n and all numbers should be pairwise distinct. You can print the numbers in arbitrary order.
After that, print an integer e β the number of connections to be made.
Finally, print e pairs of integers a and b (1 β€ a, b β€ n, a β b), denoting that a connection between City a and City b will be made. Each unordered pair of cities should be included at most once (for each (a, b) there should be no more (a, b) or (b, a) pairs). You can print the pairs in arbitrary order.
If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them.
Examples
Input
3
2 3
1 1
3 2
3 2 3
3 2 3
Output
8
3
1 2 3
0
Input
3
2 1
1 2
3 3
23 2 23
3 2 3
Output
27
1
2
2
1 2
2 3
Note
For the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red):
<image>
For the first example, the cost of building power stations in all cities is 3 + 2 + 3 = 8. It can be shown that no configuration costs less than 8 yen.
For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is 2 β
(3 + 2) = 10. The cost of connecting City 2 and City 3 is 3 β
(2 + 3) = 15. Thus the total cost is 2 + 10 + 15 = 27. It can be shown that no configuration costs less than 27 yen.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int32_t main() {
int64_t n;
cin >> n;
struct point {
int64_t x, y;
};
vector<point> a(n + 1);
for (int64_t i = 1; i < n + 1; i++) {
cin >> a[i].x >> a[i].y;
}
vector<int64_t> c(n + 1), k(n + 1);
for (int64_t i = 1; i < n + 1; i++) {
cin >> c[i];
}
for (int64_t i = 1; i < n + 1; i++) {
cin >> k[i];
}
vector<vector<int64_t>> d(n + 1, vector<int64_t>(n + 1, INT64_MAX));
for (int64_t i = 1; i < n + 1; i++) {
d[0][i] = c[i];
d[i][0] = c[i];
}
for (int64_t i = 1; i < n + 1; i++) {
for (int64_t j = 1; j < n + 1; j++) {
d[i][j] = d[j][i] =
(k[i] + k[j]) * (abs(a[i].x - a[j].x) + abs(a[i].y - a[j].y));
}
}
int64_t ans = 0;
vector<int64_t> used(n + 1, 0);
vector<int64_t> min_c(n + 1, INT64_MAX), p(n + 1, -1);
vector<pair<int64_t, int64_t>> mst;
min_c[0] = 0;
for (int64_t i = 0; i < n + 1; i++) {
int64_t v = -1;
for (int64_t j = 0; j < n + 1; j++) {
if (!used[j] && (v == -1 || min_c[j] < min_c[v])) {
v = j;
}
}
used[v] = true;
ans += min_c[v];
mst.emplace_back(v, p[v]);
for (int64_t j = 0; j < n + 1; j++) {
if (d[v][j] < min_c[j]) {
min_c[j] = d[v][j];
p[j] = v;
}
}
}
cout << ans << "\n";
vector<int64_t> ans1;
vector<pair<int64_t, int64_t>> ans2;
for (auto it : mst) {
if (it.second == -1) {
continue;
}
if (it.second == 0) {
ans1.push_back(it.first);
} else {
ans2.emplace_back(it.first, it.second);
}
}
cout << ans1.size() << "\n";
for (auto it : ans1) {
cout << it << " ";
}
cout << "\n";
cout << ans2.size() << "\n";
for (auto it : ans2) {
cout << it.first << " " << it.second << "\n";
}
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree β he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree β in this case print "-1".
Input
The first line contains three integers n, d and h (2 β€ n β€ 100 000, 1 β€ h β€ d β€ n - 1) β the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers β indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false), cin.tie(0);
int n, d, h;
cin >> n >> d >> h;
if (d < h || d > h * 2 || d + 1 > n || d == 1 && n > 2) {
cout << -1 << endl;
return 0;
}
vector<vector<int> > adj(n);
for (int i = 0; i < h; i++) adj[i].push_back(i + 1);
if (d > h) {
adj[0].push_back(h + 1);
for (int i = h + 1; i < d; i++) adj[i].push_back(i + 1);
}
if (n > d + 1) {
for (int i = d + 1; i < n; i++)
if (h == 1)
adj[0].push_back(i);
else
adj[1].push_back(i);
}
for (int i = 0; i < n; i++)
for (int j = 0; j < adj[i].size(); j++)
cout << i + 1 << " " << adj[i][j] + 1 << endl;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Each segment has one of two colors: the i-th segment's color is t_i.
Let's call a pair of segments i and j bad if the following two conditions are met:
* t_i β t_j;
* the segments [l_i, r_i] and [l_j, r_j] intersect, embed or touch, i. e. there exists an integer x such that x β [l_i, r_i] and x β [l_j, r_j].
Calculate the maximum number of segments that can be selected from the given ones, so that there is no bad pair among the selected ones.
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β number of segments.
The next n lines contains three integers l_i, r_i, t_i (1 β€ l_i β€ r_i β€ 10^9; t_i β \{1, 2\}) β description of the i-th segment.
Output
Print the maximum number of segments that can be selected, so that there is no bad pair among the selected segments.
Examples
Input
3
1 3 1
4 6 2
2 5 1
Output
2
Input
5
5 8 1
1 3 2
3 4 2
6 6 1
2 10 2
Output
4
Input
7
19 20 1
13 15 2
6 11 2
4 10 1
14 17 1
13 13 2
5 9 1
Output
5
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 4e5 + 7;
struct SegmentTree {
int tr[4 * MAXN];
int lazy[4 * MAXN];
void propagate(int u, int l, int r) {
if (lazy[u]) {
tr[u] += lazy[u];
if (l != r) {
lazy[u * 2] += lazy[u];
lazy[u * 2 + 1] += lazy[u];
}
lazy[u] = 0;
}
}
void build(int u, int l, int r) {
tr[u] = 0;
lazy[u] = 0;
if (l == r) {
return;
}
int mid = (l + r) / 2;
build(u * 2, l, mid);
build(u * 2 + 1, mid + 1, r);
}
void update(int u, int l, int r, int x, int y, int v) {
propagate(u, l, r);
if (r < x || y < l) return;
if (x <= l && r <= y) {
lazy[u] += v;
propagate(u, l, r);
return;
}
int mid = (l + r) / 2;
update(u * 2, l, mid, x, y, v);
update(u * 2 + 1, mid + 1, r, x, y, v);
tr[u] = max(tr[u * 2], tr[u * 2 + 1]);
}
int query(int u, int l, int r, int x, int y) {
propagate(u, l, r);
if (x <= l && r <= y) return tr[u];
int mid = (l + r) / 2;
if (y <= mid) return query(u * 2, l, mid, x, y);
if (mid < x) return query(u * 2 + 1, mid + 1, r, x, y);
return max(query(u * 2, l, mid, x, y), query(u * 2 + 1, mid + 1, r, x, y));
}
};
SegmentTree black, white;
int _l[MAXN], _r[MAXN], _t[MAXN];
vector<int> oc[MAXN];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<int> v;
for (int i = 1; i <= n; i++) {
cin >> _l[i] >> _r[i] >> _t[i];
v.push_back(_l[i]);
v.push_back(_r[i]);
}
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
for (int i = 1; i <= n; i++) {
_l[i] = lower_bound(v.begin(), v.end(), _l[i]) - v.begin();
_r[i] = lower_bound(v.begin(), v.end(), _r[i]) - v.begin();
oc[_l[i]].push_back(i);
}
int m = v.size();
black.build(1, 0, m);
white.build(1, 0, m);
for (int x = m - 1; x >= 0; x--) {
for (int i : oc[x]) {
if (_t[i] == 1) {
white.update(1, 0, m, _r[i] + 1, m, 1);
} else {
black.update(1, 0, m, _r[i] + 1, m, 1);
}
}
black.update(1, 0, m, x, x, white.query(1, 0, m, x + 1, m));
white.update(1, 0, m, x, x, black.query(1, 0, m, x + 1, m));
}
cout << max(black.tr[1], white.tr[1]) << "\n";
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Mishka received a gift of multicolored pencils for his birthday! Unfortunately he lives in a monochrome world, where everything is of the same color and only saturation differs. This pack can be represented as a sequence a1, a2, ..., an of n integer numbers β saturation of the color of each pencil. Now Mishka wants to put all the mess in the pack in order. He has an infinite number of empty boxes to do this. He would like to fill some boxes in such a way that:
* Each pencil belongs to exactly one box;
* Each non-empty box has at least k pencils in it;
* If pencils i and j belong to the same box, then |ai - aj| β€ d, where |x| means absolute value of x. Note that the opposite is optional, there can be pencils i and j such that |ai - aj| β€ d and they belong to different boxes.
Help Mishka to determine if it's possible to distribute all the pencils into boxes. Print "YES" if there exists such a distribution. Otherwise print "NO".
Input
The first line contains three integer numbers n, k and d (1 β€ k β€ n β€ 5Β·105, 0 β€ d β€ 109) β the number of pencils, minimal size of any non-empty box and maximal difference in saturation between any pair of pencils in the same box, respectively.
The second line contains n integer numbers a1, a2, ..., an (1 β€ ai β€ 109) β saturation of color of each pencil.
Output
Print "YES" if it's possible to distribute all the pencils into boxes and satisfy all the conditions. Otherwise print "NO".
Examples
Input
6 3 10
7 2 7 7 4 2
Output
YES
Input
6 2 3
4 5 3 13 4 10
Output
YES
Input
3 2 5
10 16 22
Output
NO
Note
In the first example it is possible to distribute pencils into 2 boxes with 3 pencils in each with any distribution. And you also can put all the pencils into the same box, difference of any pair in it won't exceed 10.
In the second example you can split pencils of saturations [4, 5, 3, 4] into 2 boxes of size 2 and put the remaining ones into another box.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 500 * 1001;
int n, k, d, a[N];
set<int> done;
set<pair<int, int>> remain;
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n >> k >> d;
for (int i = 1; i <= n; i++) cin >> a[i];
sort(a + 1, a + 1 + n);
for (int i = 1; i <= n; i++) remain.insert(make_pair(a[i], i));
done.insert(0);
while (done.size()) {
int dex = *done.begin() + 1;
done.erase(done.begin());
int low = a[dex] + d;
while (remain.upper_bound(make_pair(low, n)) != remain.begin()) {
pair<int, int> p = *(--remain.upper_bound(make_pair(low, n)));
if (p.second - dex + 1 < k) break;
remain.erase(--remain.upper_bound(make_pair(low, n)));
done.insert(p.second);
if (p.second == n) {
cout << "YES";
return 0;
}
}
}
cout << "NO";
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
qd ucyhf yi q fhycu dkcruh mxeiu huluhiu yi q tyvvuhudj fhycu dkcruh. oekh jqia yi je vydt jxu djx ucyhf.
Input
jxu ydfkj sediyiji ev q iydwbu ydjuwuh d (1 β€ d β€ 11184) β jxu edu-rqiut ydtun ev jxu ucyhf je vydt.
Output
ekjfkj q iydwbu dkcruh.
Examples
Input
1
Output
13
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1000001;
bool notp[N];
void sieve() {
notp[0] = notp[1] = 1;
for (int i = 2; i < N; ++i) {
if (notp[i]) continue;
for (int j = i * 2; j < N; j += i) notp[j] = 1;
}
}
int rev(int v) {
int ans = 0;
while (v) {
ans *= 10;
ans += (v % 10);
v /= 10;
}
return ans;
}
int main() {
sieve();
int n;
scanf("%d", &n);
int c = 0;
for (int i = 1; i < N; ++i) {
if (!notp[i] && (!notp[rev(i)] && i != rev(i))) {
++c;
}
if (c == n) {
printf("%d", i);
return 0;
}
}
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Given an integer a as input, print the value a + a^2 + a^3.
Constraints
* 1 \leq a \leq 10
* a is an integer.
Input
Input is given from Standard Input in the following format:
a
Output
Print the value a + a^2 + a^3 as an integer.
Examples
Input
2
Output
14
Input
10
Output
1110
### Response
```cpp
#include <bits/stdc++.h>
int main(){
int a;
std::cin >> a;
std::cout << a+a*a+a*a*a << std::endl;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
problem
You are looking for a constellation in a picture of the starry sky. The photo always contains exactly one figure with the same shape, orientation, and size as the constellation you are looking for. However, there is a possibility that extra stars are shown in the photograph other than the stars that make up the constellation.
For example, the constellations in Figure 1 are included in the photo in Figure 2 (circled). If you translate the coordinates of a star in a given constellation by 2 in the x direction and β3 in the y direction, it will be the position in the photo.
Given the shape of the constellation you want to look for and the position of the star in the picture, write a program that answers the amount to translate to convert the coordinates of the constellation to the coordinates in the picture.
<image> | <image>
--- | ---
Figure 1: The constellation you want to find | Figure 2: Photograph of the starry sky
input
The input consists of multiple datasets. Each dataset is given in the following format.
The first line of the input contains the number of stars m that make up the constellation you want to find. In the following m line, the integers indicating the x and y coordinates of the m stars that make up the constellation you want to search for are written separated by blanks. The number n of stars in the photo is written on the m + 2 line. In the following n lines, the integers indicating the x and y coordinates of the n stars in the photo are written separated by blanks.
The positions of the m stars that make up the constellation are all different. Also, the positions of the n stars in the picture are all different. 1 β€ m β€ 200, 1 β€ n β€ 1000. The x and y coordinates of a star are all 0 or more and 1000000 or less.
When m is 0, it indicates the end of input. The number of datasets does not exceed 5.
output
The output of each dataset consists of one line, with two integers separated by blanks. These show how much the coordinates of the constellation you want to find should be translated to become the coordinates in the photo. The first integer is the amount to translate in the x direction, and the second integer is the amount to translate in the y direction.
Examples
Input
5
8 5
6 4
4 3
7 10
0 10
10
10 5
2 7
9 7
8 10
10 2
1 2
8 1
6 7
6 0
0 9
5
904207 809784
845370 244806
499091 59863
638406 182509
435076 362268
10
757559 866424
114810 239537
519926 989458
461089 424480
674361 448440
81851 150384
459107 795405
299682 6700
254125 362183
50795 541942
0
Output
2 -3
-384281 179674
Input
None
Output
None
### Response
```cpp
#include <stdio.h>
#include <algorithm>
using namespace std;
typedef struct {
int x, y;
} POINT;
bool operator< (const POINT& a, const POINT& b)
{
if (a.x == b.x){
return (a.y < b.y);
}
return (a.x < b.x);
}
int main(void)
{
POINT pat[200];
POINT all[1000];
int allcnt, patcnt;
int i, j;
while (1){
scanf("%d", &patcnt);
if (patcnt == 0){
break;
}
for (int i = 0; i < patcnt; i++){
scanf("%d%d", &pat[i].x, &pat[i].y);
}
scanf("%d", &allcnt);
for (int i = 0; i < allcnt; i++){
scanf("%d%d", &all[i].x, &all[i].y);
}
sort(pat, pat + patcnt);
sort(all, all + allcnt);
for (i = 0; i + patcnt - 1 < allcnt; i++){
int k;
k = 0;
for (j = 0; j < patcnt; j++){
for (int l = 0; l < allcnt; l++){
if (pat[j].x - pat[0].x == all[l].x - all[i].x && pat[j].y - pat[0].y == all[l].y - all[i].y){
k++;
break;
}
}
}
if (k == patcnt){
break;
}
}
printf("%d %d\n", all[i].x - pat[0].x, all[i].y - pat[0].y);
}
return (0);
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.
Max is a young biologist. For n days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer k that if the shark in some day traveled the distance strictly less than k, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to k; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least k.
The shark never returned to the same location after it has moved from it. Thus, in the sequence of n days we can find consecutive nonempty segments when the shark traveled the distance less than k in each of the days: each such segment corresponds to one location. Max wants to choose such k that the lengths of all such segments are equal.
Find such integer k, that the number of locations is as large as possible. If there are several such k, print the smallest one.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of days.
The second line contains n distinct positive integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9) β the distance traveled in each of the day.
Output
Print a single integer k, such that
1. the shark was in each location the same number of days,
2. the number of locations is maximum possible satisfying the first condition,
3. k is smallest possible satisfying the first and second conditions.
Examples
Input
8
1 2 7 3 4 8 5 6
Output
7
Input
6
25 1 2 3 14 36
Output
2
Note
In the first example the shark travels inside a location on days 1 and 2 (first location), then on 4-th and 5-th days (second location), then on 7-th and 8-th days (third location). There are three locations in total.
In the second example the shark only moves inside a location on the 2-nd day, so there is only one location.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long int md = 1e9 + 7;
const long long int N = 100005;
long long int dsu[N], sz[N];
pair<long long int, long long int> a[N];
map<long long int, long long int> m;
long long int root(long long int u) {
while (u != dsu[u]) u = dsu[u];
return u;
}
bool uni(long long int u, long long int v) {
u = root(u), v = root(v);
if (u == v) return 0;
m[sz[u]]--;
if (m[sz[u]] == 0) m.erase(sz[u]);
m[sz[v]]--;
if (m[sz[v]] == 0) m.erase(sz[v]);
m[sz[u] + sz[v]]++;
if (sz[u] > sz[v]) {
dsu[v] = u;
sz[u] += sz[v];
} else {
dsu[u] = v;
sz[v] += sz[u];
}
return 1;
}
bool active[N];
signed main() {
ios::sync_with_stdio(0);
long long int n;
cin >> n;
for (long long int i = 1; i <= n; i++) {
cin >> a[i].first;
a[i].second = i;
dsu[i] = i;
sz[i] = 1;
}
sort(a + 1, a + n + 1);
long long int maxi = 0;
long long int ans = 0;
for (long long int i = 1; i <= n; i++) {
long long int v = a[i].first;
while (a[i].first == v) {
active[a[i].second] = 1;
m[1]++;
if (a[i].second > 1 && active[a[i].second - 1])
uni(a[i].second - 1, a[i].second);
if (a[i].second < n && active[a[i].second + 1])
uni(a[i].second, a[i].second + 1);
i++;
}
i--;
auto it = m.begin();
if (m.size() == 1 && maxi < it->second) {
ans = a[i].first;
maxi = it->second;
}
}
cout << ans + 1;
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Urpal lives in a big city. He has planned to meet his lover tonight.
The city has n junctions numbered from 1 to n. The junctions are connected by m directed streets, all the roads have equal length. Urpal lives in junction a and the date is planned in a restaurant in junction b. He wants to use public transportation to get to junction b. There are k bus transportation companies. At the beginning of every second, a bus from the i-th company chooses a random shortest path between junction si and junction ti and passes through it. There might be no path from si to ti. In that case no bus will leave from si to ti. If a bus passes through a junction where Urpal stands, he can get on the bus. He can also get off the bus at any junction along the path.
Now Urpal wants to know if it's possible to go to the date using public transportation in a finite amount of time (the time of travel is the sum of length of the traveled roads) and what is the minimum number of buses he should take in the worst case.
At any moment Urpal knows only his own position and the place where the date will be. When he gets on the bus he knows only the index of the company of this bus. Of course Urpal knows the city map and the the pairs (si, ti) for each company.
Note that Urpal doesn't know buses velocity.
Input
The first line of the input contains four integers n, m, a, b (2 β€ n β€ 100; 0 β€ m β€ nΒ·(n - 1); 1 β€ a, b β€ n; a β b).
The next m lines contain two integers each ui and vi (1 β€ ui, vi β€ n; ui β vi) describing a directed road from junction ui to junction vi. All roads in the input will be distinct.
The next line contains an integer k (0 β€ k β€ 100). There will be k lines after this, each containing two integers si and ti (1 β€ si, ti β€ n; si β ti) saying there is a bus route starting at si and ending at ti. Please note that there might be no path from si to ti, this case is described in the problem statement.
Output
In the only line of output print the minimum number of buses Urpal should get on on his way in the worst case. If it's not possible to reach the destination in the worst case print -1.
Examples
Input
7 8 1 7
1 2
1 3
2 4
3 4
4 6
4 5
6 7
5 7
3
2 7
1 4
5 7
Output
2
Input
4 4 1 2
1 2
1 3
2 4
3 4
1
1 4
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 105, MOD = 998244353;
inline void ADD(int& x, int y) {
x += y;
if (x >= MOD) x -= MOD;
}
int N, M, K, S, T, G[MAXN][MAXN], s[MAXN], t[MAXN], f[MAXN], dis[MAXN][MAXN],
D[MAXN][MAXN], cnt[MAXN][MAXN];
queue<int> Q;
int main() {
scanf("%d%d%d%d", &N, &M, &S, &T);
int u, v;
while (M--) scanf("%d%d", &u, &v), G[u][v] = 1;
for (int i = 1; i <= N; ++i) {
for (int j = 1; j <= N; ++j) D[i][j] = -1;
D[i][i] = 0, cnt[i][i] = 1, Q.push(i);
while (!Q.empty()) {
int u = Q.front();
Q.pop();
for (int j = 1; j <= N; ++j)
if (G[u][j]) {
if (D[i][j] == -1)
D[i][j] = D[i][u] + 1, Q.push(j), cnt[i][j] = cnt[i][u];
else if (D[i][j] == D[i][u] + 1)
ADD(cnt[i][j], cnt[i][u]);
}
}
}
scanf("%d", &K);
for (int i = 1; i <= K; ++i) scanf("%d%d", &s[i], &t[i]);
f[T] = 1;
for (int turn = 2; turn <= N + 1; ++turn) {
for (int i = 1; i <= N; ++i) {
for (int j = 1; j <= N; ++j) dis[i][j] = -1;
dis[i][i] = 0, Q.push(i);
while (!Q.empty()) {
int u = Q.front();
Q.pop();
for (int j = 1; j <= N; ++j)
if (G[u][j] && !f[j]) {
if (dis[i][j] == -1) dis[i][j] = dis[i][u] + 1, Q.push(j);
}
}
}
int chk = 0;
for (int i = 1; i <= N; ++i)
if (!f[i]) {
for (int j = 1; j <= K; ++j) {
if (D[s[j]][i] + D[i][t[j]] != D[s[j]][t[j]]) continue;
if (1ll * cnt[s[j]][i] * cnt[i][t[j]] % MOD != cnt[s[j]][t[j]])
continue;
if (dis[i][t[j]] != D[i][t[j]]) {
f[i] = turn, ++chk;
break;
}
}
}
if (f[S]) break;
if (!cnt) break;
}
printf("%d\n", f[S] - 1);
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
problem
You are playing with J using the Midakuji. The Amida lottery consists of n vertical bars and m horizontal bars. The vertical bars are numbered from 1 to n in order from the left, and the vertical bar i The positive integer si is written at the bottom of.
<image>
Figure 3-1 Example of Amidakuji (n = 4, m = 5, s1 = 20, s2 = 80, s3 = 100, s4 = 50)
The integer written at the bottom of the vertical bar i, which is reached by following the path from the top of the vertical bar i, is the score when the vertical bar i is selected. For example, in Fig. 3-1 the vertical bar 1 is selected. And the score is 80 points, and if the vertical bar 2 is selected, the score is 100 points.
<image>
Figure 3-2 Example of how to follow the road
Mr. J decides to choose a series of k books from vertical bar 1 to vertical bar k. The total score when selecting those k vertical bars is J's score. However, you are in the Amidakuji You can select one horizontal bar and delete that horizontal bar from the Amidakuji. (You do not have to delete it.) If you delete one horizontal bar, the vertical bar in the deleted Amidakuji will be displayed vertically. J's score is the total of the points when selecting k consecutive vertical bars from bar 1 to vertical bar k.
Given the shape of the Amida lottery and the number of vertical bars k that J chooses as input, create a program that finds the minimum value of J's score.
input
The input consists of multiple datasets. Each dataset is given in the following format.
On the first line, four integers n, m, h, k are written separated by blanks. N (2 β€ n β€ 1000) is the number of vertical bars, and m (1 β€ m β€ 100000) is the horizontal bar. H (2 β€ h β€ 1000) represents the length of the vertical bar, and k (1 β€ k β€ n) represents the number of vertical bars you choose.
The following n lines contain the score written at the bottom of the vertical bar. The first line (1 β€ i β€ n) contains the positive integer si. Also, s1 + s2 + ... + sn β€ 2000000000 = 2 Γ 109.
The following m lines indicate the position of the horizontal bar. The horizontal bars are numbered from 1 to m. The first line (1 β€ i β€ m) is the horizontal bar i. The two integers ai, bi (1 β€ ai β€ n --1, 1 β€ bi β€ h --1) representing the position are separated by blanks, and the horizontal bar i connects the vertical bar ai and the vertical bar ai + 1. , Indicates that the distance from the top edge of the horizontal bar i is bi. However, no two horizontal bars share an endpoint.
Of the scoring data, 20% of the points will have the lowest score for Mr. J if the horizontal bar is not deleted. Also, 30% of the points will satisfy n β€ 20, m β€ 30, h β€ 10. 60% of the points are m β€ 1000.
The end of the input is indicated by a line containing four zeros. The number of datasets does not exceed 10.
output
For each dataset, output the minimum score of Mr. J on one line.
Examples
Input
4 5 7 2
20
80
100
50
1 1
2 6
2 3
1 5
3 1
2 2 5 1
10
20
1 1
1 3
0 0 0 0
Output
100
10
Input
None
Output
None
### Response
```cpp
#include "bits/stdc++.h"
#include<unordered_map>
#include<unordered_set>
#pragma warning(disable:4996)
using namespace std;
using ld = long double;
template<class T>
using Table = vector<vector<T>>;
const ld eps=1e-9;
//// < "D:\D_Download\Visual Studio 2015\Projects\programing_contest_c++\Debug\a.txt" > "D:\D_Download\Visual Studio 2015\Projects\programing_contest_c++\Debug\b.answer"
struct stick{
int h;
int l;
};
int main() {
while (1) {
int N, M, H, K; cin >> N >> M >> H >> K;
if (!N)break;
vector<int>scores(N);
for (int i = 0; i < N; ++i) {
cin >> scores[i];
}
vector<pair<int, int>>ss;
for (int i = 0; i < M; ++i) {
int a, b; cin >> a >> b;
a--;
ss.push_back(make_pair(b, a));
}
sort(ss.begin(), ss.end(),greater<pair<int,int>>());
vector<int>nums(N);
iota(nums.begin(), nums.end(), 0);
vector<pair<int, int>>ps;
for (auto s : ss) {
ps.emplace_back(nums[s.second], nums[s.second + 1]);
swap(nums[s.second], nums[s.second + 1]);
}
int ans = 2e9;
{
int nans = 0;
for (int k = 0; k < K; ++k) {
nans += scores[nums[k]];
}
ans = min(ans, nans);
}
for (int i = 0; i < M; ++i) {
swap(scores[ps[i].first], scores[ps[i].second]);
int nans = 0;
for (int k = 0; k < K; ++k) {
nans += scores[nums[k]];
}
ans = min(ans, nans);
swap(scores[ps[i].first], scores[ps[i].second]);
}
cout << ans << endl;
}
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly greater than a, Vova can just play, and then the charge of his laptop battery will decrease by a;
* if the current charge of his laptop battery is strictly greater than b (b<a), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by b;
* if the current charge of his laptop battery is less than or equal to a and b at the same time then Vova cannot do anything and loses the game.
Regardless of Vova's turns the charge of the laptop battery is always decreases.
Vova wants to complete the game (Vova can complete the game if after each of n turns the charge of the laptop battery is strictly greater than 0). Vova has to play exactly n turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 10^5) β the number of queries. Each query is presented by a single line.
The only line of the query contains four integers k, n, a and b (1 β€ k, n β€ 10^9, 1 β€ b < a β€ 10^9) β the initial charge of Vova's laptop battery, the number of turns in the game and values a and b, correspondingly.
Output
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
Example
Input
6
15 5 3 2
15 5 4 3
15 5 2 1
15 5 5 1
16 7 5 2
20 5 7 3
Output
4
-1
5
2
0
1
Note
In the first example query Vova can just play 4 turns and spend 12 units of charge and then one turn play and charge and spend 2 more units. So the remaining charge of the battery will be 1.
In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be 0 after the last turn.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int inf = 2e9, MX = 1000007;
int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
int lcm(int x, int y) {
x /= gcd(x, y);
return x * y;
}
bool prime[MX], isprime[MX];
vector<int> v;
int cs = 0;
int fx[] = {1, -1, 0, 0, 1, 1, -1, -1};
int fy[] = {0, 0, 1, -1, 1, -1, 1, -1};
void fast() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
}
bool InRng(int i, int j) { return ((i >= 1 && i < 9) && (j >= 1 && j < 9)); }
struct A {
int u, v, id;
A(int a, int b, int c) { u = a, v = b, id = c; }
};
bool operator<(A a, A b) { return a.v > b.v; }
void bs(long long k, long long n, long long a, long long b) {
long long l = 0, r = n + 1, m, ans = 0;
while (l < r) {
m = (l + r) / 2;
if (((m * a) + (n - m) * b) < k) {
l = m + 1;
ans = max(ans, m);
} else
r = m;
}
if (((ans * a) + (n - ans) * b) < k)
cout << ans << endl;
else
cout << -1 << endl;
}
void solve() {
long long k, n, a, b, q;
cin >> q;
while (q--) {
cin >> k >> n >> a >> b;
bs(k, n, a, b);
}
}
int main() {
solve();
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Write a program which judges wheather given length of three side form a right triangle. Print "YES" if the given sides (integers) form a right triangle, "NO" if not so.
Constraints
* 1 β€ length of the side β€ 1,000
* N β€ 1,000
Input
Input consists of several data sets. In the first line, the number of data set, N is given. Then, N lines follow, each line corresponds to a data set. A data set consists of three integers separated by a single space.
Output
For each data set, print "YES" or "NO".
Example
Input
3
4 3 5
4 3 6
8 8 8
Output
YES
NO
NO
### Response
```cpp
#include <cstdio>
int i,a,b,c;
int main()
{
scanf("%d",&i);
while(i!=0)
{
scanf("%d %d %d",&a,&b,&c);
if(a*a+b*b==c*c||b*b+c*c==a*a||c*c+a*a==b*b)
{
printf("YES\n");
}
else printf("NO\n");
i--;
}
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
There are N cities in Republic of AtCoder. The size of the i-th city is A_{i}. Takahashi would like to build N-1 bidirectional roads connecting two cities so that any city can be reached from any other city by using these roads.
Assume that the cost of building a road connecting the i-th city and the j-th city is |i-j| \times D + A_{i} + A_{j}. For Takahashi, find the minimum possible total cost to achieve the objective.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq D \leq 10^9
* 1 \leq A_{i} \leq 10^9
* A_{i} and D are integers.
Input
Input is given from Standard Input in the following format:
N D
A_1 A_2 ... A_N
Output
Print the minimum possible total cost.
Examples
Input
3 1
1 100 1
Output
106
Input
3 1000
1 100 1
Output
2202
Input
6 14
25 171 7 1 17 162
Output
497
Input
12 5
43 94 27 3 69 99 56 25 8 15 46 8
Output
658
### Response
```cpp
#include<bits/stdc++.h>
#define rep(i, n) for(int i = 0; i < n; i++)
using namespace std;
typedef long long ll;
ll qmin(ll a, ll b){
return (a < b) ? a : b;
}
ll n, d;
ll a[200200];
vector< pair< ll, pair<ll, ll> > > edge;
void solve(int l, int r){
if(l >= r) return ;
int mid = (l+r) >> 1;
solve(l, mid);
solve(mid+1, r);
int mnpos1 = l;
for(int i = l; i <= mid; i++){
if(a[i] + (mid - i) * d < a[mnpos1] + (mid - mnpos1) * d) mnpos1 = i;
}
ll mnpos2 = mid+1;
for(int i = mid+1; i <= r; i++){
if(a[i] + (i - mid) * d < a[mnpos2] + (mnpos2 - mid) * d) mnpos2 = i;
}
for(int i = l; i <= mid; i++) edge.push_back(make_pair(a[mnpos2] + a[i] + (mnpos2 - i) * d, make_pair(i, mnpos2)));
for(int i = mid+1; i <= r; i++) edge.push_back(make_pair(a[i] + a[mnpos1] + (i - mnpos1) * d, make_pair(i, mnpos1)));
}
int par[200200];
int get_par(int now){
return par[now] = ((par[now] == now) ? now : get_par(par[now]));
}
void unite(int a, int b){
par[get_par(a)] = get_par(b);
}
ll ans = 0;
int main(){
scanf("%lld%lld", &n, &d);
rep(i, n) par[i] = i;
rep(i, n) scanf("%lld", &a[i]);
solve(0, n-1);
sort(edge.begin(), edge.end());
rep(i, edge.size()){
if(get_par(edge[i].second.first) != get_par(edge[i].second.second)){
ans += edge[i].first;
unite(edge[i].second.first, edge[i].second.second);
}
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
You have written on a piece of paper an array of n positive integers a[1], a[2], ..., a[n] and m good pairs of integers (i1, j1), (i2, j2), ..., (im, jm). Each good pair (ik, jk) meets the following conditions: ik + jk is an odd number and 1 β€ ik < jk β€ n.
In one operation you can perform a sequence of actions:
* take one of the good pairs (ik, jk) and some integer v (v > 1), which divides both numbers a[ik] and a[jk];
* divide both numbers by v, i. e. perform the assignments: <image> and <image>.
Determine the maximum number of operations you can sequentially perform on the given array. Note that one pair may be used several times in the described operations.
Input
The first line contains two space-separated integers n, m (2 β€ n β€ 100, 1 β€ m β€ 100).
The second line contains n space-separated integers a[1], a[2], ..., a[n] (1 β€ a[i] β€ 109) β the description of the array.
The following m lines contain the description of good pairs. The k-th line contains two space-separated integers ik, jk (1 β€ ik < jk β€ n, ik + jk is an odd number).
It is guaranteed that all the good pairs are distinct.
Output
Output the answer for the problem.
Examples
Input
3 2
8 3 8
1 2
2 3
Output
0
Input
3 2
8 12 8
1 2
2 3
Output
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int read() {
int f = 1, x = 0;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;
}
int n, m, T, cnt, ans;
int a[205], u[205], v[205];
int h[205], q[205], last[205], cur[205];
struct edge {
int to, next, v;
} e[200005];
void insert(int u, int v, int w) {
e[++cnt].to = v;
e[cnt].next = last[u];
last[u] = cnt;
e[cnt].v = w;
e[++cnt].to = u;
e[cnt].next = last[v];
last[v] = cnt;
e[cnt].v = 0;
};
bool bfs() {
int head = 0, tail = 1;
for (int i = 0; i <= T; i++) h[i] = -1;
q[0] = 0;
h[0] = 0;
while (head != tail) {
int now = q[head];
head++;
for (int i = last[now]; i; i = e[i].next)
if (h[e[i].to] == -1 && e[i].v) {
h[e[i].to] = h[now] + 1;
q[tail++] = e[i].to;
}
}
return h[T] != -1;
}
int dfs(int x, int f) {
if (x == T) return f;
int w, used = 0;
for (int i = cur[x]; i; i = e[i].next)
if (h[e[i].to] == h[x] + 1) {
w = dfs(e[i].to, min(e[i].v, f - used));
e[i].v -= w;
e[i ^ 1].v += w;
if (e[i].v) cur[x] = i;
used += w;
if (used == f) return f;
}
if (!used) h[x] = -1;
return used;
}
void dinic() {
while (bfs()) {
for (int i = 0; i <= T; i++) cur[i] = last[i];
ans += dfs(0, 1000000000);
}
}
void solve(int x) {
cnt = 1;
memset(last, 0, sizeof(last));
for (int i = 1; i <= n; i++) {
int t = 0;
while (a[i] % x == 0) a[i] /= x, t++;
if (i & 1)
insert(0, i, t);
else
insert(i + n, T, t);
}
for (int i = 1; i <= m; i++) insert(u[i], v[i] + n, 1000000000);
dinic();
}
int main() {
n = read();
m = read();
T = 2 * n + 1;
for (int i = 1; i <= n; i++) a[i] = read();
for (int i = 1; i <= m; i++) {
u[i] = read(), v[i] = read();
if (v[i] & 1) swap(u[i], v[i]);
}
for (int k = 1; k <= n; k++) {
int t = sqrt(a[k]);
for (int i = 2; i <= t; i++)
if (a[k] % i == 0) solve(i);
if (a[k] != 1) solve(a[k]);
}
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Nauuo is a girl who loves playing cards.
One day she was playing cards but found that the cards were mixed with some empty ones.
There are n cards numbered from 1 to n, and they were mixed with another n empty cards. She piled up the 2n cards and drew n of them. The n cards in Nauuo's hands are given. The remaining n cards in the pile are also given in the order from top to bottom.
In one operation she can choose a card in her hands and play it β put it at the bottom of the pile, then draw the top card from the pile.
Nauuo wants to make the n numbered cards piled up in increasing order (the i-th card in the pile from top to bottom is the card i) as quickly as possible. Can you tell her the minimum number of operations?
Input
The first line contains a single integer n (1β€ nβ€ 2β
10^5) β the number of numbered cards.
The second line contains n integers a_1,a_2,β¦,a_n (0β€ a_iβ€ n) β the initial cards in Nauuo's hands. 0 represents an empty card.
The third line contains n integers b_1,b_2,β¦,b_n (0β€ b_iβ€ n) β the initial cards in the pile, given in order from top to bottom. 0 represents an empty card.
It is guaranteed that each number from 1 to n appears exactly once, either in a_{1..n} or b_{1..n}.
Output
The output contains a single integer β the minimum number of operations to make the n numbered cards piled up in increasing order.
Examples
Input
3
0 2 0
3 0 1
Output
2
Input
3
0 2 0
1 0 3
Output
4
Input
11
0 0 0 5 0 0 0 4 0 0 11
9 2 6 0 8 1 7 0 3 0 10
Output
18
Note
Example 1
We can play the card 2 and draw the card 3 in the first operation. After that, we have [0,3,0] in hands and the cards in the pile are [0,1,2] from top to bottom.
Then, we play the card 3 in the second operation. The cards in the pile are [1,2,3], in which the cards are piled up in increasing order.
Example 2
Play an empty card and draw the card 1, then play 1, 2, 3 in order.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n;
int a[200005];
int b[200005];
int c[200005];
int x;
int ans;
int main() {
cin.tie(0);
cout.tie(0);
ios_base::sync_with_stdio(0);
cin >> n;
ans = 2 * n;
int i, j;
for (i = 1; i <= n; i++) {
cin >> a[i];
c[a[i]] = 1;
}
deque<int> Q;
for (i = 1; i <= n; i++) {
cin >> b[i];
Q.push_back(b[i]);
}
int cnt = 0;
while (Q.front() != 1) {
cnt++;
if (c[Q.back() + 1] == 1) {
c[Q.back() + 1] = 0;
Q.push_back(Q.back() + 1);
} else {
break;
}
c[Q.front()] = 1;
Q.pop_front();
}
for (i = 1; i <= n; i++) {
if (Q.front() != i) break;
Q.pop_front();
}
if (i == n + 1) ans = cnt;
int k = n;
for (i = 1; i <= n; i++) {
if (b[i]) k = max(k, i + 1 + n - b[i]);
}
if (k > 0) ans = min(ans, k);
cout << ans;
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
You have an array a_1, a_2, ..., a_n.
Let's call some subarray a_l, a_{l + 1}, ... , a_r of this array a subpermutation if it contains all integers from 1 to r-l+1 exactly once. For example, array a = [2, 2, 1, 3, 2, 3, 1] contains 6 subarrays which are subpermutations: [a_2 ... a_3], [a_2 ... a_4], [a_3 ... a_3], [a_3 ... a_5], [a_5 ... a_7], [a_7 ... a_7].
You are asked to calculate the number of subpermutations.
Input
The first line contains one integer n (1 β€ n β€ 3 β
10^5).
The second line contains n integers a_1, a_2, ... , a_n (1 β€ a_i β€ n).
This array can contain the same integers.
Output
Print the number of subpermutations of the array a.
Examples
Input
8
2 4 1 3 4 2 1 2
Output
7
Input
5
1 1 2 1 2
Output
6
Note
There are 7 subpermutations in the first test case. Their segments of indices are [1, 4], [3, 3], [3, 6], [4, 7], [6, 7], [7, 7] and [7, 8].
In the second test case 6 subpermutations exist: [1, 1], [2, 2], [2, 3], [3, 4], [4, 4] and [4, 5].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, a[300005], fa[300005][20], R[300005], la[300005], lg2[300005];
int get_mx(int l, int r) {
int k = lg2[r - l + 1];
return max(fa[l][k], fa[r - (1 << k) + 1][k]);
}
int main() {
lg2[1] = 0;
scanf("%d", &n);
for (int i = 2; i <= n; i++) lg2[i] = lg2[i >> 1] + 1;
for (int i = 1; i <= n; i++) scanf("%d", &a[i]), fa[i][0] = a[i];
R[n + 1] = n;
for (int i = n; i >= 1; i--) {
if (la[a[i]])
R[i] = min(R[i + 1], la[a[i]] - 1);
else
R[i] = R[i + 1];
la[a[i]] = i;
}
for (int j = 1; j < 20; j++)
for (int i = 1; i + (1 << j - 1) <= n; i++)
fa[i][j] = max(fa[i][j - 1], fa[i + (1 << j - 1)][j - 1]);
long long ans = 0;
for (int i = 1; i <= n; i++) {
int j = i;
while (j <= R[i]) {
int now = get_mx(i, j);
if (now == j - i + 1)
j++, ans++;
else
j = i + now - 1;
}
}
printf("%lld\n", ans);
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Two integers x and y are compatible, if the result of their bitwise "AND" equals zero, that is, a & b = 0. For example, numbers 90 (10110102) and 36 (1001002) are compatible, as 10110102 & 1001002 = 02, and numbers 3 (112) and 6 (1102) are not compatible, as 112 & 1102 = 102.
You are given an array of integers a1, a2, ..., an. Your task is to find the following for each array element: is this element compatible with some other element from the given array? If the answer to this question is positive, then you also should find any suitable element.
Input
The first line contains an integer n (1 β€ n β€ 106) β the number of elements in the given array. The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 4Β·106) β the elements of the given array. The numbers in the array can coincide.
Output
Print n integers ansi. If ai isn't compatible with any other element of the given array a1, a2, ..., an, then ansi should be equal to -1. Otherwise ansi is any such number, that ai & ansi = 0, and also ansi occurs in the array a1, a2, ..., an.
Examples
Input
2
90 36
Output
36 90
Input
4
3 6 3 6
Output
-1 -1 -1 -1
Input
5
10 6 9 8 2
Output
-1 8 2 2 8
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int vis[(1 << 22)];
int pila[(1 << 22)], sz;
void dfs(int x, int valor) {
sz = 0;
pila[sz++] = x;
vis[x] = valor;
while (sz > 0) {
x = pila[sz - 1];
sz--;
for (int i = 0; i < 22; ++i)
if ((x & (1 << i)) && vis[x - (1 << i)] == -1) {
pila[sz++] = x - (1 << i);
vis[x - (1 << i)] = valor;
}
}
}
int a[1000005];
int main() {
memset(vis, -1, sizeof vis);
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
scanf("%d", &a[i]);
dfs((1 << 22) - 1 - a[i], a[i]);
}
for (int i = 0; i < n; ++i) printf("%d ", vis[a[i]]);
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
We will say that two integer sequences of length N, x_1, x_2, ..., x_N and y_1, y_2, ..., y_N, are similar when |x_i - y_i| \leq 1 holds for all i (1 \leq i \leq N).
In particular, any integer sequence is similar to itself.
You are given an integer N and an integer sequence of length N, A_1, A_2, ..., A_N.
How many integer sequences b_1, b_2, ..., b_N are there such that b_1, b_2, ..., b_N is similar to A and the product of all elements, b_1 b_2 ... b_N, is even?
Constraints
* 1 \leq N \leq 10
* 1 \leq A_i \leq 100
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the number of integer sequences that satisfy the condition.
Examples
Input
2
2 3
Output
7
Input
3
3 3 3
Output
26
Input
1
100
Output
1
Input
10
90 52 56 71 44 8 13 30 57 84
Output
58921
### Response
```cpp
#include <iostream>
using namespace std;
int main() {
int N , a[10] , ng = 1 , all = 1;
cin >> N;
for(int i = 0;i < N;i++){
cin >> a[i];
}
for(int i = 0;i < N;i++){
all *= 3;
if(a[i] % 2 == 0) ng *= 2;
}
cout << all - ng << endl;
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most βn/2β vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of queries.
Then t queries follow.
The first line of each query contains two integers n and m (2 β€ n β€ 2 β
10^5, n - 1 β€ m β€ min(2 β
10^5, (n(n-1))/(2))) β the number of vertices and the number of edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 β€ v_i, u_i β€ n, u_i β v_i), which are the indices of vertices connected by the edge.
There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i β u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that β m β€ 2 β
10^5 over all queries.
Output
For each query print two lines.
In the first line print k (1 β€ βn/2β) β the number of chosen vertices.
In the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
Example
Input
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
Output
2
1 3
3
4 3 6
Note
In the first query any vertex or any pair of vertices will suffice.
<image>
Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long power(long long a, long long b) {
long long ans = 1;
while (b > 0) {
if (b % 2 != 0) {
ans = (ans * a) % 1000000007;
}
a = ((a % 1000000007) * (a % 1000000007)) % 1000000007;
b >>= 1;
}
return ans;
}
int main() {
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
;
int t = 1;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
set<int> s1, s2;
vector<int> a[n + 1];
for (int i = 0; i < m; i++) {
int p, q;
cin >> p >> q;
a[p].push_back(q);
a[q].push_back(p);
}
for (int i = 1; i <= n; i++) {
if (s2.count(i)) continue;
s1.insert(i);
for (auto j : a[i]) s2.insert(j);
}
if (s1.size() > n / 2) {
cout << n - s1.size() << '\n';
for (int i = 1; i <= n; i++) {
if (s1.count(i)) continue;
cout << i << " ";
}
} else {
cout << s1.size() << '\n';
for (auto i : s1) cout << i << " ";
}
cout << '\n';
}
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Sereja has an n Γ m rectangular table a, each cell of the table contains a zero or a number one. Sereja wants his table to meet the following requirement: each connected component of the same values forms a rectangle with sides parallel to the sides of the table. Rectangles should be filled with cells, that is, if a component form a rectangle of size h Γ w, then the component must contain exactly hw cells.
A connected component of the same values is a set of cells of the table that meet the following conditions:
* every two cells of the set have the same value;
* the cells of the set form a connected region on the table (two cells are connected if they are adjacent in some row or some column of the table);
* it is impossible to add any cell to the set unless we violate the two previous conditions.
Can Sereja change the values of at most k cells of the table so that the table met the described requirement? What minimum number of table cells should he change in this case?
Input
The first line contains integers n, m and k (1 β€ n, m β€ 100; 1 β€ k β€ 10). Next n lines describe the table a: the i-th of them contains m integers ai1, ai2, ..., aim (0 β€ ai, j β€ 1) β the values in the cells of the i-th row.
Output
Print -1, if it is impossible to meet the requirement. Otherwise, print the minimum number of cells which should be changed.
Examples
Input
5 5 2
1 1 1 1 1
1 1 1 1 1
1 1 0 1 1
1 1 1 1 1
1 1 1 1 1
Output
1
Input
3 4 1
1 0 0 0
0 1 1 1
1 1 1 0
Output
-1
Input
3 4 1
1 0 0 1
0 1 1 0
1 0 0 1
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m, i, j, i1, x1, ans, res, kol, k[2], a[105][105], x[105];
int main() {
ios::sync_with_stdio(false);
cin >> n >> m >> kol;
if (n >= m)
for (i = 0; i < n; i++)
for (j = 0; j < m; j++) cin >> a[i][j];
else {
for (i = 0; i < n; i++)
for (j = 0; j < m; j++) cin >> a[m - j - 1][i];
swap(n, m);
}
ans = 2000000000;
if (n <= kol) {
for (x1 = 0; x1 < (1 << m); x1++) {
i1 = x1;
for (i = 0; i < m; i++) x[i] = i1 & 1, i1 >>= 1;
res = 0;
for (i = 0; i < n; i++) {
k[0] = k[1] = 0;
for (j = 0; j < m; j++) k[a[i][j] == x[j]]++;
res += min(k[0], k[1]);
}
if (res < ans) ans = res;
}
} else {
for (x1 = 0; x1 < n; x1++) {
for (i = 0; i < m; i++) x[i] = a[x1][i];
res = 0;
for (i = 0; i < n; i++) {
k[0] = k[1] = 0;
for (j = 0; j < m; j++) k[a[i][j] == x[j]]++;
res += min(k[0], k[1]);
}
if (res < ans) ans = res;
}
}
if (ans > kol)
cout << -1;
else
cout << ans;
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Student Dima from Kremland has a matrix a of size n Γ m filled with non-negative integers.
He wants to select exactly one integer from each row of the matrix so that the bitwise exclusive OR of the selected integers is strictly greater than zero. Help him!
Formally, he wants to choose an integers sequence c_1, c_2, β¦, c_n (1 β€ c_j β€ m) so that the inequality a_{1, c_1} β a_{2, c_2} β β¦ β a_{n, c_n} > 0 holds, where a_{i, j} is the matrix element from the i-th row and the j-th column.
Here x β y denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of integers x and y.
Input
The first line contains two integers n and m (1 β€ n, m β€ 500) β the number of rows and the number of columns in the matrix a.
Each of the next n lines contains m integers: the j-th integer in the i-th line is the j-th element of the i-th row of the matrix a, i.e. a_{i, j} (0 β€ a_{i, j} β€ 1023).
Output
If there is no way to choose one integer from each row so that their bitwise exclusive OR is strictly greater than zero, print "NIE".
Otherwise print "TAK" in the first line, in the next line print n integers c_1, c_2, β¦ c_n (1 β€ c_j β€ m), so that the inequality a_{1, c_1} β a_{2, c_2} β β¦ β a_{n, c_n} > 0 holds.
If there is more than one possible answer, you may output any.
Examples
Input
3 2
0 0
0 0
0 0
Output
NIE
Input
2 3
7 7 7
7 7 10
Output
TAK
1 3
Note
In the first example, all the numbers in the matrix are 0, so it is impossible to select one number in each row of the table so that their bitwise exclusive OR is strictly greater than zero.
In the second example, the selected numbers are 7 (the first number in the first line) and 10 (the third number in the second line), 7 β 10 = 13, 13 is more than 0, so the answer is found.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename T>
T GCD(T a, T b) {
long long t;
while (a) {
t = a;
a = b % a;
b = t;
}
return b;
}
template <typename T>
string toString(T a) {
return to_string(a);
}
template <typename T>
void toInt(string s, T &x) {
stringstream str(s);
str >> x;
}
inline int add(long long a, long long b) {
a += b;
if (a < 0) a += 1000000007;
return a;
}
inline int sub(long long a, long long b) {
a -= b;
if (a < 0) a += 1000000007;
return a;
}
inline int mul(long long a, long long b) { return (a * 1ll * b) % 1000000007; }
inline int pwr(long long x, long long y) {
int ans = 1 % 1000000007;
while (y) {
if (y & 1) ans = mul(ans, x);
x = mul(x, x);
y >>= 1;
}
return ans;
}
inline int inv(int a) { return pwr(a, 1000000007 - 2); }
vector<int> aa;
int n, m;
vector<vector<int> > vec(501, vector<int>(501));
int dp[501][2000];
int fun(int ind, int cur) {
if (ind == n) {
if (cur > 0) {
cout << "TAK" << '\n';
for (auto it : aa) {
cout << it << " ";
}
cout << '\n';
exit(0);
} else {
return 0;
}
}
if (dp[ind][cur] != -1) {
return dp[ind][cur];
}
int ans = 0;
for (int i = 0; i < m; i++) {
aa.push_back(i + 1);
ans = fun(ind + 1, (cur ^ vec[ind][i]));
aa.pop_back();
}
dp[ind][cur] = 1;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m;
int x = 0, v;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> v;
vec[i][j] = v;
}
}
memset(dp, -1, sizeof(dp));
fun(0, 0);
cout << "NIE" << '\n';
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Takahashi is solving quizzes. He has easily solved all but the last one.
The last quiz has three choices: 1, 2, and 3.
With his supernatural power, Takahashi has found out that the choices A and B are both wrong.
Print the correct choice for this problem.
Constraints
* Each of the numbers A and B is 1, 2, or 3.
* A and B are different.
Input
Input is given from Standard Input in the following format:
A
B
Output
Print the correct choice.
Examples
Input
3
1
Output
2
Input
1
2
Output
3
### Response
```cpp
#include <iostream>
using namespace std;
int main()
{
int i,j,k;
cin>>i>>j;
cout<<6-i-j;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
There are N panels arranged in a row in Takahashi's house, numbered 1 through N. The i-th panel has a number A_i written on it. Takahashi is playing by throwing balls at these panels.
Takahashi threw a ball K times. Let the panel hit by a boll in the i-th throw be panel p_i. He set the score for the i-th throw as i \times A_{p_i}.
He was about to calculate the total score for his throws, when he realized that he forgot the panels hit by balls, p_1,p_2,...,p_K. The only fact he remembers is that for every i (1 β¦ i β¦ K-1), 1 β¦ p_{i+1}-p_i β¦ M holds. Based on this fact, find the maximum possible total score for his throws.
Constraints
* 1 β¦ M β¦ N β¦ 100,000
* 1 β¦ K β¦ min(300,N)
* 1 β¦ A_i β¦ 10^{9}
Input
The input is given from Standard Input in the following format:
N M K
A_1 A_2 β¦ A_N
Output
Print the maximum possible total score for Takahashi's throws.
Examples
Input
5 2 3
10 2 8 10 2
Output
56
Input
5 5 2
5 2 10 5 9
Output
28
Input
10 3 5
3 7 2 6 9 4 8 5 1 1000000000
Output
5000000078
### Response
```cpp
// εΊζ¬γγ³γγ¬γΌγ
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <string>
#include <cstring>
#include <deque>
#include <list>
#include <queue>
#include <stack>
#include <vector>
#include <utility>
#include <algorithm>
#include <map>
#include <set>
#include <complex>
#include <cmath>
#include <limits>
#include <cfloat>
#include <climits>
#include <ctime>
#include <cassert>
#include <numeric>
#include <fstream>
#include <functional>
using namespace std;
#define rep(i,a,n) for(int (i)=(a); (i)<(n); (i)++)
#define repq(i,a,n) for(int (i)=(a); (i)<=(n); (i)++)
#define repr(i,a,n) for(int (i)=(a); (i)>=(n); (i)--)
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define int long long int
template<typename T> void chmax(T &a, T b) {a = max(a, b);}
template<typename T> void chmin(T &a, T b) {a = min(a, b);}
template<typename T> void chadd(T &a, T b) {a = a + b;}
typedef pair<int, int> pii;
typedef long long ll;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
const ll INF = 1001001001001001LL;
const ll MOD = 1000000007LL;
int dp[301][100001];
signed main() {
int N, M, K; cin >> N >> M >> K;
vector<int> A(N);
for(int i=0; i<N; i++) {
cin >> A[i];
dp[1][i] = A[i];
}
for(int k=1; k<K; k++) {
deque< pair<int, int> > deq;
deq.push_back(make_pair(0, -1));
for(int i=k-1; i<N; i++) {
// dp[k-1][i-1] γγ dp[k-1][i-M] γΎγ§γθ¦γ
int num = k + 1;
int prev_max = deq.front().first;
dp[k+1][i] = prev_max + A[i] * num;
// printf("dp[%lld][%lld], assign = %lld\n", k+1, i+1, prev_max);
int lb = i-M+1, val = dp[k][i];
while(deq.size() && deq.back().first <= val) deq.pop_back();
pair<int, int> elem = make_pair(val, i);
deq.push_back(elem);
while(deq.size() && deq.front().second < lb) deq.pop_front();
}
}
cout << *max_element(dp[K], dp[K]+N) << endl;
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
A little boy Gerald entered a clothes shop and found out something very unpleasant: not all clothes turns out to match. For example, Gerald noticed that he looks rather ridiculous in a smoking suit and a baseball cap.
Overall the shop sells n clothing items, and exactly m pairs of clothing items match. Each item has its price, represented by an integer number of rubles. Gerald wants to buy three clothing items so that they matched each other. Besides, he wants to spend as little money as possible. Find the least possible sum he can spend.
Input
The first input file line contains integers n and m β the total number of clothing items in the shop and the total number of matching pairs of clothing items (<image>).
Next line contains n integers ai (1 β€ ai β€ 106) β the prices of the clothing items in rubles.
Next m lines each contain a pair of space-separated integers ui and vi (1 β€ ui, vi β€ n, ui β vi). Each such pair of numbers means that the ui-th and the vi-th clothing items match each other. It is guaranteed that in each pair ui and vi are distinct and all the unordered pairs (ui, vi) are different.
Output
Print the only number β the least possible sum in rubles that Gerald will have to pay in the shop. If the shop has no three clothing items that would match each other, print "-1" (without the quotes).
Examples
Input
3 3
1 2 3
1 2
2 3
3 1
Output
6
Input
3 2
2 3 4
2 3
2 1
Output
-1
Input
4 4
1 1 1 1
1 2
2 3
3 4
4 1
Output
-1
Note
In the first test there only are three pieces of clothing and they all match each other. Thus, there is only one way β to buy the 3 pieces of clothing; in this case he spends 6 roubles.
The second test only has three pieces of clothing as well, yet Gerald can't buy them because the first piece of clothing does not match the third one. Thus, there are no three matching pieces of clothing. The answer is -1.
In the third example there are 4 pieces of clothing, but Gerald can't buy any 3 of them simultaneously. The answer is -1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool A[105][105];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
vector<int> v(n);
for (int i = 0; i < n; i++) cin >> v[i];
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
a--;
b--;
A[a][b] = A[b][a] = true;
}
int solve = -1;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
if (A[i][j] && A[i][k] && A[j][k]) {
int price = v[i] + v[j] + v[k];
if (solve == -1)
solve = price;
else
solve = min(solve, price);
}
}
}
}
cout << solve << '\n';
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
The time is 2020. There is data that saves the qualifying results of PC Koshien 2020. This data stores the reference number and the number of correct answers assigned to each team. Here, the ranking is determined by the number of correct answers, and the ranking is given in descending order of the number of correct answers, such as 1st, 2nd, and so on.
Enter the qualifying result data and reference number from the keyboard, and create a program that outputs the ranking of the team with that number.
Note
In the data of the input example, if the teams are arranged in order of the number of correct answers:
3,30
1,20
2,20
6,20
4,10
5,10
It will be. Here, in order to determine the ranking based on the number of correct answers, the 30-question correct answer team is ranked 1st, the 20-question correct answer team is ranked 2nd, and the 10-question correct answer team is ranked 3rd. Please note that this is different from the usual ranking with the correct team in 5th place).
Input
The input data consists of two parts. The first half is the qualifying result data, and the second half is the inquiry of the team number for which you want to know the ranking. The format of the qualifying result data is as follows.
p1, s1
p2, s2
...
...
0,0
pi (1 β€ pi β€ 100) and si (0 β€ si β€ 30) are integers representing the reference number and the number of correct answers for the i-th team, respectively. It is assumed that the input of this data is completed when both the reference number and the number of correct answers are 0.
Then multiple inquiries in the second half are given. The inquiry format is as follows.
q1
q2
::
Each query is given the reference number qi (1 β€ qi β€ 30) on one line. Please process this until the end of the input. The number of inquiries does not exceed 100.
Output
For each inquiry, print the team ranking on one line.
Example
Input
1,20
2,20
3,30
4,10
5,10
6,20
0,0
1
2
4
5
Output
2
2
3
3
### Response
```cpp
#include <iostream>
#include <map>
#include <set>
using namespace std;
int main(){
int a,b;
char c;
map <int,int>x;
set <int> y;
while (1){
cin>>a>>c>>b;
if (a==0&&b==0) break;
x[a]=b;
y.insert(b);
}
while (cin>>a){
b=1;
set<int>::reverse_iterator it=y.rbegin();
while (*it!=x[a]){
it++;
b++;
}
cout<<b<<endl;
}
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Little boy Igor wants to become a traveller. At first, he decided to visit all the cities of his motherland β Uzhlyandia.
It is widely known that Uzhlyandia has n cities connected with m bidirectional roads. Also, there are no two roads in the country that connect the same pair of cities, but roads starting and ending in the same city can exist. Igor wants to plan his journey beforehand. Boy thinks a path is good if the path goes over m - 2 roads twice, and over the other 2 exactly once. The good path can start and finish in any city of Uzhlyandia.
Now he wants to know how many different good paths are in Uzhlyandia. Two paths are considered different if the sets of roads the paths goes over exactly once differ. Help Igor β calculate the number of good paths.
Input
The first line contains two integers n, m (1 β€ n, m β€ 106) β the number of cities and roads in Uzhlyandia, respectively.
Each of the next m lines contains two integers u and v (1 β€ u, v β€ n) that mean that there is road between cities u and v.
It is guaranteed that no road will be given in the input twice. That also means that for every city there is no more than one road that connects the city to itself.
Output
Print out the only integer β the number of good paths in Uzhlyandia.
Examples
Input
5 4
1 2
1 3
1 4
1 5
Output
6
Input
5 3
1 2
2 3
4 5
Output
0
Input
2 2
1 1
1 2
Output
1
Note
In first sample test case the good paths are:
* 2 β 1 β 3 β 1 β 4 β 1 β 5,
* 2 β 1 β 3 β 1 β 5 β 1 β 4,
* 2 β 1 β 4 β 1 β 5 β 1 β 3,
* 3 β 1 β 2 β 1 β 4 β 1 β 5,
* 3 β 1 β 2 β 1 β 5 β 1 β 4,
* 4 β 1 β 2 β 1 β 3 β 1 β 5.
There are good paths that are same with displayed above, because the sets of roads they pass over once are same:
* 2 β 1 β 4 β 1 β 3 β 1 β 5,
* 2 β 1 β 5 β 1 β 3 β 1 β 4,
* 2 β 1 β 5 β 1 β 4 β 1 β 3,
* 3 β 1 β 4 β 1 β 2 β 1 β 5,
* 3 β 1 β 5 β 1 β 2 β 1 β 4,
* 4 β 1 β 3 β 1 β 2 β 1 β 5,
* and all the paths in the other direction.
Thus, the answer is 6.
In the second test case, Igor simply can not walk by all the roads.
In the third case, Igor walks once over every road.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1E6 + 10;
int n, m;
long long deg[MAXN];
int vis[MAXN], fa[MAXN];
int find(int x) { return x == fa[x] ? x : (fa[x] = find(fa[x])); }
int main() {
scanf("%d%d", &n, &m);
long long self = 0;
for (int i = 1; i <= n; ++i) fa[i] = i;
for (int u, v, i = 0; i < m; ++i) {
scanf("%d%d", &u, &v);
vis[u] = vis[v] = true;
if (u == v) {
++self;
continue;
}
++deg[u], ++deg[v];
u = find(u), v = find(v);
if (u != v) fa[u] = v;
}
int rt = find(find(vis + 1, vis + n + 1, true) - vis);
for (int i = 1; i <= n; ++i)
if (vis[i] && find(rt) != find(i)) {
puts("0");
return 0;
}
long long ans = self * (self - 1) / 2 + self * (m - self);
for (int i = 1; i <= n; ++i) ans += deg[i] * (deg[i] - 1) / 2;
printf("%lld\n", ans);
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
A conglomerate consists of n companies. To make managing easier, their owners have decided to merge all companies into one. By law, it is only possible to merge two companies, so the owners plan to select two companies, merge them into one, and continue doing so until there is only one company left.
But anti-monopoly service forbids to merge companies if they suspect unfriendly absorption. The criterion they use is the difference in maximum salaries between two companies. Merging is allowed only if the maximum salaries are equal.
To fulfill the anti-monopoly requirements, the owners can change salaries in their companies before merging. But the labor union insists on two conditions: it is only allowed to increase salaries, moreover all the employees in one company must get the same increase.
Sure enough, the owners want to minimize the total increase of all salaries in all companies. Help them find the minimal possible increase that will allow them to merge companies into one.
Input
The first line contains a single integer n β the number of companies in the conglomerate (1 β€ n β€ 2 β
10^5). Each of the next n lines describes a company.
A company description start with an integer m_i β the number of its employees (1 β€ m_i β€ 2 β
10^5). Then m_i integers follow: the salaries of the employees. All salaries are positive and do not exceed 10^9.
The total number of employees in all companies does not exceed 2 β
10^5.
Output
Output a single integer β the minimal total increase of all employees that allows to merge all companies.
Example
Input
3
2 4 3
2 2 1
3 1 1 1
Output
13
Note
One of the optimal merging strategies is the following. First increase all salaries in the second company by 2, and merge the first and the second companies. Now the conglomerate consists of two companies with salaries [4, 3, 4, 3] and [1, 1, 1]. To merge them, increase the salaries in the second of those by 3. The total increase is 2 + 2 + 3 + 3 + 3 = 13.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = int(2e5) + 5;
const int inf = (int)1e9 + 7;
int n;
int mx[N], sz[N];
int main() {
scanf("%d", &n);
int gmax = 0;
for (int i = 1; i <= n; ++i) {
scanf("%d", sz + i);
for (int j = 1; j <= sz[i]; ++j) {
int x;
scanf("%d", &x);
mx[i] = max(mx[i], x);
}
gmax = max(gmax, mx[i]);
}
long long ans = 0;
for (int i = 1; i <= n; ++i) {
ans += (gmax - mx[i]) * 1ll * sz[i];
}
printf("%lld\n", ans);
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
You are given a matrix consisting of digits zero and one, its size is n Γ m. You are allowed to rearrange its rows. What is the maximum area of the submatrix that only consists of ones and can be obtained in the given problem by the described operations?
Let's assume that the rows of matrix a are numbered from 1 to n from top to bottom and the columns are numbered from 1 to m from left to right. A matrix cell on the intersection of the i-th row and the j-th column can be represented as (i, j). Formally, a submatrix of matrix a is a group of four integers d, u, l, r (1 β€ d β€ u β€ n; 1 β€ l β€ r β€ m). We will assume that the submatrix contains cells (i, j) (d β€ i β€ u; l β€ j β€ r). The area of the submatrix is the number of cells it contains.
Input
The first line contains two integers n and m (1 β€ n, m β€ 5000). Next n lines contain m characters each β matrix a. Matrix a only contains characters: "0" and "1". Note that the elements of the matrix follow without any spaces in the lines.
Output
Print a single integer β the area of the maximum obtained submatrix. If we cannot obtain a matrix of numbers one, print 0.
Examples
Input
1 1
1
Output
1
Input
2 2
10
11
Output
2
Input
4 3
100
011
000
101
Output
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m, ans, f[5005][5005], a[5005], c[5005];
char g[5005][5005];
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++i) scanf("%s", g[i] + 1);
for (int i = 1; i <= n; ++i) {
for (int j = m; j; --j) f[i][j] = (g[i][j] == '1' ? f[i][j + 1] + 1 : 0);
}
for (int j = 1; j <= m; ++j) {
memset(c, 0, n + 1 << 2);
for (int i = 1; i <= n; ++i) ++c[f[i][j]];
for (int i = 1; i <= n; ++i) c[i] += c[i - 1];
for (int i = n; i; --i) a[c[f[i][j]]--] = f[i][j];
for (int i = 1; i <= n; ++i) ans = max(ans, (n - i + 1) * a[i]);
}
printf("%d\n", ans);
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.
After the contest was over, Valera was interested in results. He found out that:
* each student in the team scored at least l points and at most r points;
* in total, all members of the team scored exactly sall points;
* the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 β₯ a2 β₯ ... β₯ an), then sk = a1 + a2 + ... + ak.
However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
Input
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 β€ n, k, l, r β€ 1000; l β€ r; k β€ n; 1 β€ sk β€ sall β€ 106).
It's guaranteed that the input is such that the answer exists.
Output
Print exactly n integers a1, a2, ..., an β the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
Examples
Input
5 3 1 3 13 9
Output
2 3 2 3 3
Input
5 3 1 3 15 9
Output
3 3 3 3 3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a, s, d, f, g, h, j, k, l, i, n, m;
int main() {
cin >> n >> m >> k >> f >> g >> h;
s = h % m;
for (i = 0; i < m; i++) {
if (i < s)
cout << h / m + 1;
else
cout << h / m;
cout << " ";
}
if (n - m == 0) return 0;
s = (g - h) % (n - m);
for (i = 0; i < n - m; i++) {
if (i < s)
cout << (g - h) / (n - m) + 1;
else
cout << (g - h) / (n - m);
cout << " ";
}
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
There are N balls in a two-dimensional plane. The i-th ball is at coordinates (x_i, y_i).
We will collect all of these balls, by choosing two integers p and q such that p \neq 0 or q \neq 0 and then repeating the following operation:
* Choose a ball remaining in the plane and collect it. Let (a, b) be the coordinates of this ball. If we collected a ball at coordinates (a - p, b - q) in the previous operation, the cost of this operation is 0. Otherwise, including when this is the first time to do this operation, the cost of this operation is 1.
Find the minimum total cost required to collect all the balls when we optimally choose p and q.
Constraints
* 1 \leq N \leq 50
* |x_i|, |y_i| \leq 10^9
* If i \neq j, x_i \neq x_j or y_i \neq y_j.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
:
x_N y_N
Output
Print the minimum total cost required to collect all the balls.
Examples
Input
2
1 1
2 2
Output
1
Input
3
1 4
4 6
7 8
Output
1
Input
4
1 1
1 2
2 1
2 2
Output
2
### Response
```cpp
#include <map>
#include <cstdio>
using namespace std;
int main(){
int n;
scanf("%d", &n);
int x[n], y[n], ans = 0;
for (int i = 0; i < n; i++) scanf("%d %d", &x[i], &y[i]);
map<pair<int, int>, int> m;
for (int i = 0; i < n - 1; i++){
for (int j = i + 1; j < n; j++){
pair<int, int> p = {x[i] - x[j], y[i] - y[j]};
m[p]++;
ans = max(ans, m[p]);
p.first = -p.first;
p.second = -p.second;
m[p]++;
ans = max(ans, m[p]);
}
}
printf("%d\n", n - ans);
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Write a program which converts uppercase/lowercase letters to lowercase/uppercase for a given string.
Constraints
* The length of the input string < 1200
Input
A string is given in a line.
Output
Print the converted string in a line. Note that you do not need to convert any characters other than alphabetical letters.
Example
Input
fAIR, LATER, OCCASIONALLY CLOUDY.
Output
Fair, later, occasionally cloudy.
### Response
```cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
string line;
getline(cin, line);
for (auto &c: line){
if (islower(c)){
putchar(toupper(c));
}else{
putchar(tolower(c));
}
}
cout << endl;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Okabe needs bananas for one of his experiments for some strange reason. So he decides to go to the forest and cut banana trees.
Consider the point (x, y) in the 2D plane such that x and y are integers and 0 β€ x, y. There is a tree in such a point, and it has x + y bananas. There are no trees nor bananas in other points. Now, Okabe draws a line with equation <image>. Okabe can select a single rectangle with axis aligned sides with all points on or under the line and cut all the trees in all points that are inside or on the border of this rectangle and take their bananas. Okabe's rectangle can be degenerate; that is, it can be a line segment or even a point.
Help Okabe and find the maximum number of bananas he can get if he chooses the rectangle wisely.
Okabe is sure that the answer does not exceed 1018. You can trust him.
Input
The first line of input contains two space-separated integers m and b (1 β€ m β€ 1000, 1 β€ b β€ 10000).
Output
Print the maximum number of bananas Okabe can get from the trees he cuts.
Examples
Input
1 5
Output
30
Input
2 3
Output
25
Note
<image>
The graph above corresponds to sample test 1. The optimal rectangle is shown in red and has 30 bananas.
### Response
```cpp
#include <bits/stdc++.h>
int main() {
int m, b;
long long ans = 0;
scanf("%d %d", &m, &b);
for (int i = 0; i <= b; i++) {
long long sum = 0;
sum += (long long)i * (i + 1) / 2 * ((b - i) * m + 1);
sum += (long long)(b - i) * m * ((b - i) * m + 1) / 2 * (i + 1);
if (sum > ans) ans = sum;
}
printf("%lld", ans);
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Recently you've discovered a new shooter. They say it has realistic game mechanics.
Your character has a gun with magazine size equal to k and should exterminate n waves of monsters. The i-th wave consists of a_i monsters and happens from the l_i-th moment of time up to the r_i-th moments of time. All a_i monsters spawn at moment l_i and you have to exterminate all of them before the moment r_i ends (you can kill monsters right at moment r_i). For every two consecutive waves, the second wave starts not earlier than the first wave ends (though the second wave can start at the same moment when the first wave ends) β formally, the condition r_i β€ l_{i + 1} holds. Take a look at the notes for the examples to understand the process better.
You are confident in yours and your character's skills so you can assume that aiming and shooting are instant and you need exactly one bullet to kill one monster. But reloading takes exactly 1 unit of time.
One of the realistic mechanics is a mechanic of reloading: when you reload you throw away the old magazine with all remaining bullets in it. That's why constant reloads may cost you excessive amounts of spent bullets.
You've taken a liking to this mechanic so now you are wondering: what is the minimum possible number of bullets you need to spend (both used and thrown) to exterminate all waves.
Note that you don't throw the remaining bullets away after eradicating all monsters, and you start with a full magazine.
Input
The first line contains two integers n and k (1 β€ n β€ 2000; 1 β€ k β€ 10^9) β the number of waves and magazine size.
The next n lines contain descriptions of waves. The i-th line contains three integers l_i, r_i and a_i (1 β€ l_i β€ r_i β€ 10^9; 1 β€ a_i β€ 10^9) β the period of time when the i-th wave happens and the number of monsters in it.
It's guaranteed that waves don't overlap (but may touch) and are given in the order they occur, i. e. r_i β€ l_{i + 1}.
Output
If there is no way to clear all waves, print -1. Otherwise, print the minimum possible number of bullets you need to spend (both used and thrown) to clear all waves.
Examples
Input
2 3
2 3 6
3 4 3
Output
9
Input
2 5
3 7 11
10 12 15
Output
30
Input
5 42
42 42 42
42 43 42
43 44 42
44 45 42
45 45 1
Output
-1
Input
1 10
100 111 1
Output
1
Note
In the first example:
* At the moment 2, the first wave occurs and 6 monsters spawn. You kill 3 monsters and start reloading.
* At the moment 3, the second wave occurs and 3 more monsters spawn. You kill remaining 3 monsters from the first wave and start reloading.
* At the moment 4, you kill remaining 3 monsters from the second wave.
In total, you'll spend 9 bullets.
In the second example:
* At moment 3, the first wave occurs and 11 monsters spawn. You kill 5 monsters and start reloading.
* At moment 4, you kill 5 more monsters and start reloading.
* At moment 5, you kill the last monster and start reloading throwing away old magazine with 4 bullets.
* At moment 10, the second wave occurs and 15 monsters spawn. You kill 5 monsters and start reloading.
* At moment 11, you kill 5 more monsters and start reloading.
* At moment 12, you kill last 5 monsters.
In total, you'll spend 30 bullets.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("Ofast")
#pragma GCC target("avx")
bool RELAXED = false;
template <int, typename T>
struct MINMAX {
T val;
MINMAX(T val) : val(val) {}
};
template <typename T>
MINMAX<1, T> MAX(T val) {
return MINMAX<1, T>(val);
};
template <typename T>
MINMAX<2, T> MIN(T val) {
return MINMAX<2, T>(val);
};
template <typename T, typename U>
inline T& operator|=(T& lhs, MINMAX<1, U> rhs) {
return lhs = (rhs.val > lhs ? (RELAXED = true, rhs.val)
: (RELAXED = false, lhs));
}
template <typename T, typename U>
inline T& operator|=(T& lhs, MINMAX<2, U> rhs) {
return lhs = (rhs.val < lhs ? (RELAXED = true, rhs.val)
: (RELAXED = false, lhs));
}
template <typename T, typename U>
istream& operator>>(istream& in, pair<T, U>& p) {
in >> p.first >> p.second;
return in;
}
template <typename T>
inline vector<T> READ(int n) {
vector<T> vec(n);
for (int i = 0; i < int(n); i++) cin >> vec[i];
return vec;
}
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T> >;
struct wave {
int start, end, size;
};
int n, k;
vector<wave> W;
bool poss(int rem, int idx) {
if (rem < 0) return false;
if (idx >= n) return true;
int overlapping = idx < n - 1 && (W[idx + 1].start == W[idx].end);
if (W[idx].start == W[idx].end) {
rem -= W[idx].size;
if (rem < 0) return false;
if (idx == n - 1) return true;
if (overlapping)
return poss(rem, idx + 1);
else
return poss(k, idx + 1);
}
signed long long int ts = W[idx].end - W[idx].start - 1;
signed long long int mass = ts * k + rem;
if (mass < W[idx].size) {
int last = W[idx].size - mass;
if (last > k) return false;
if (overlapping) return poss(k - last, idx + 1);
}
return poss(k, idx + 1);
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cout << fixed << setprecision(12);
cin >> n >> k;
signed long long int monster = 0;
for (int i = 0; i < int(n); i++) {
wave w;
cin >> w.start >> w.end >> w.size;
monster += w.size;
W.push_back(w);
}
sort((W).begin(), (W).end(), [](wave l, wave r) {
if (l.start == r.start) return l.end < r.end;
return l.start < r.start;
});
signed long long int mag = k;
signed long long int trash = 0;
for (int i = 0; i < int(n); i++) {
if (!poss(k, i)) {
cerr << "EXIT #" << 115 << endl;
cout << -1 << endl;
exit(0);
};
42;
if (!poss(mag, i)) {
42;
trash += mag;
mag = k;
}
mag -= W[i].size;
mag = (mag % k + k) % k;
}
cout << monster + trash << endl;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Inna loves sleeping very much, so she needs n alarm clocks in total to wake up. Let's suppose that Inna's room is a 100 Γ 100 square with the lower left corner at point (0, 0) and with the upper right corner at point (100, 100). Then the alarm clocks are points with integer coordinates in this square.
The morning has come. All n alarm clocks in Inna's room are ringing, so Inna wants to turn them off. For that Inna has come up with an amusing game:
* First Inna chooses a type of segments that she will use throughout the game. The segments can be either vertical or horizontal.
* Then Inna makes multiple moves. In a single move, Inna can paint a segment of any length on the plane, she chooses its type at the beginning of the game (either vertical or horizontal), then all alarm clocks that are on this segment switch off. The game ends when all the alarm clocks are switched off.
Inna is very sleepy, so she wants to get through the alarm clocks as soon as possible. Help her, find the minimum number of moves in the game that she needs to turn off all the alarm clocks!
Input
The first line of the input contains integer n (1 β€ n β€ 105) β the number of the alarm clocks. The next n lines describe the clocks: the i-th line contains two integers xi, yi β the coordinates of the i-th alarm clock (0 β€ xi, yi β€ 100).
Note that a single point in the room can contain any number of alarm clocks and the alarm clocks can lie on the sides of the square that represents the room.
Output
In a single line print a single integer β the minimum number of segments Inna will have to draw if she acts optimally.
Examples
Input
4
0 0
0 1
0 2
1 0
Output
2
Input
4
0 0
0 1
1 0
1 1
Output
2
Input
4
1 1
1 2
2 3
3 3
Output
3
Note
In the first sample, Inna first chooses type "vertical segments", and then she makes segments with ends at : (0, 0), (0, 2); and, for example, (1, 0), (1, 1). If she paints horizontal segments, she will need at least 3 segments.
In the third sample it is important to note that Inna doesn't have the right to change the type of the segments during the game. That's why she will need 3 horizontal or 3 vertical segments to end the game.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int x, y, n, i, x_state[2019], y_state[2019], ans, sum_x, sum_y;
int main() {
cin >> n;
for (i = 1; i <= n; i++) {
cin >> x >> y;
if (!x_state[x]) sum_x++;
if (!y_state[y]) sum_y++;
x_state[x] = 1, y_state[y] = 1;
}
if (sum_x > sum_y) {
ans = sum_y;
} else
ans = sum_x;
cout << ans;
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Given simple (without self-intersections) n-gon. It is not necessary convex. Also you are given m lines. For each line find the length of common part of the line and the n-gon.
The boundary of n-gon belongs to polygon. It is possible that n-gon contains 180-degree angles.
Input
The first line contains integers n and m (3 β€ n β€ 1000;1 β€ m β€ 100). The following n lines contain coordinates of polygon vertices (in clockwise or counterclockwise direction). All vertices are distinct.
The following m lines contain line descriptions. Each of them contains two distict points of a line by their coordinates.
All given in the input coordinates are real numbers, given with at most two digits after decimal point. They do not exceed 105 by absolute values.
Output
Print m lines, the i-th line should contain the length of common part of the given n-gon and the i-th line. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
Examples
Input
4 3
0 0
1 0
1 1
0 1
0 0 1 1
0 0 0 1
0 0 1 -1
Output
1.41421356237309514547
1.00000000000000000000
0.00000000000000000000
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-6;
double det(complex<double> u, complex<double> v) { return imag(conj(u) * v); }
double dot(complex<double> u, complex<double> v) { return real(conj(u) * v); }
struct Event {
double t;
bool end;
bool operator<(Event e) const { return t < e.t; }
};
const int N = 1000;
int n, m;
complex<double> z[N], p, q;
void normalize() {
vector<complex<double> > p;
for (int i = 0; i < n; i++) {
complex<double> a = z[i];
complex<double> b = z[(i + 1) % n];
complex<double> c = z[(i + 2) % n];
if (abs(det(a - b, c - b)) > EPS) p.push_back(b);
}
n = p.size();
for (int i = 0; i < n; i++) z[i] = p[i];
double area = 0;
for (int i = 0; i < n; i++) {
complex<double> a = z[i], b = z[(i + 1) % n];
area += (imag(a) + imag(b)) * (real(b) - real(a));
}
if (area < 0) reverse(z, z + n);
}
double commonLength() {
vector<Event> event;
for (int i = 0; i < n; i++) {
complex<double> a = z[i];
complex<double> b = z[(i + 1) % n];
double t = (double)det(b - p, b - a) / det(q - p, b - a) * abs(q - p);
if ((det(q - p, a - p)) < -EPS && (det(q - p, b - p)) > EPS)
event.push_back({t, false});
if ((det(q - p, a - p)) > EPS && (det(q - p, b - p)) < -EPS)
event.push_back({t, true});
}
for (int i = 0; i < n; i++) {
complex<double> a = z[i];
complex<double> b = z[(i + 1) % n];
complex<double> c = z[(i + 2) % n];
double t = dot(q - p, b - p) / abs(q - p);
if (abs((det(q - p, b - p))) < EPS) {
if ((det(q - p, a - p)) < -EPS && (det(q - p, c - p)) > EPS)
event.push_back({t, false});
if ((det(q - p, a - p)) > EPS && (det(q - p, c - p)) < -EPS)
event.push_back({t, true});
if (abs((det(q - p, a - p))) < EPS && (det(q - p, c - p)) > EPS &&
(dot(q - p, a - p)) > (dot(q - p, b - p)))
event.push_back({t, false});
if (abs((det(q - p, a - p))) < EPS && (det(q - p, c - p)) < -EPS &&
(dot(q - p, a - p)) < (dot(q - p, b - p)))
event.push_back({t, true});
if (abs((det(q - p, c - p))) < EPS && (det(q - p, a - p)) < -EPS &&
(dot(q - p, c - p)) > (dot(q - p, b - p)))
event.push_back({t, false});
if (abs((det(q - p, c - p))) < EPS && (det(q - p, a - p)) > EPS &&
(dot(q - p, c - p)) < (dot(q - p, b - p)))
event.push_back({t, true});
}
}
sort(event.begin(), event.end());
int c = 0;
double l = 0, t;
for (Event e : event) {
if (c > 0) l += e.t - t;
if (e.end)
c--;
else
c++;
t = e.t;
}
return l;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++) {
double x, y;
scanf("%lf%lf", &x, &y);
z[i] = complex<double>(x, y);
}
normalize();
for (int r = 0; r < m; r++) {
double px, py, qx, qy;
scanf("%lf%lf%lf%lf", &px, &py, &qx, &qy);
p = complex<double>(px, py);
q = complex<double>(qx, qy);
if (real(p) > real(q) || abs(real(p) - real(q)) < EPS && imag(p) > imag(q))
swap(p, q);
printf("%lf\n", commonLength());
}
}
``` |
### Prompt
Generate a CPP solution to the following problem:
ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.
ZS and Chris are good friends. They insist to get a pair of neighbouring empty seats. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit?
Input
The first line of the input contains a single integer n (1 β€ n β€ 1000) β the number of rows of seats in the bus.
Then, n lines follow. Each line contains exactly 5 characters, the first two of them denote the first pair of seats in the row, the third character denotes the walkway (it always equals '|') and the last two of them denote the second pair of seats in the row.
Each character, except the walkway, equals to 'O' or to 'X'. 'O' denotes an empty seat, 'X' denotes an occupied seat. See the sample cases for more details.
Output
If it is possible for Chris and ZS to sit at neighbouring empty seats, print "YES" (without quotes) in the first line. In the next n lines print the bus configuration, where the characters in the pair of seats for Chris and ZS is changed with characters '+'. Thus the configuration should differ from the input one by exactly two charaters (they should be equal to 'O' in the input and to '+' in the output).
If there is no pair of seats for Chris and ZS, print "NO" (without quotes) in a single line.
If there are multiple solutions, you may print any of them.
Examples
Input
6
OO|OX
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX
Output
YES
++|OX
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX
Input
4
XO|OX
XO|XX
OX|OX
XX|OX
Output
NO
Input
5
XX|XX
XX|XX
XO|OX
XO|OO
OX|XO
Output
YES
XX|XX
XX|XX
XO|OX
XO|++
OX|XO
Note
Note that the following is an incorrect configuration for the first sample case because the seats must be in the same pair.
O+|+X
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, i, j, c = 0;
cin >> n;
char s[123][123];
for (i = 0; i < n; i++) {
cin >> s[i];
}
for (i = 0; i < n; i++) {
}
for (i = 0; i < n; i++) {
for (j = 0; j < 5; j++) {
if (s[i][j] == 'O' && s[i][j + 1] == 'O') {
cout << "YES\n";
c = 1;
break;
}
}
if (c == 1) {
break;
}
}
if (c == 0) cout << "NO\n";
int m = 0;
for (i = 0; i < n; i++) {
for (j = 0; j < 5; j++) {
if (s[i][j] == 'O' && s[i][j + 1] == 'O') {
s[i][j] = '+';
s[i][j + 1] = '+';
m = 1;
break;
}
}
if (m == 1) break;
}
if (c == 1) {
for (i = 0; i < n; i++) {
cout << s[i] << endl;
}
}
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Programmers' kids solve this riddle in 5-10 minutes. How fast can you do it?
Input
The input contains a single integer n (0 β€ n β€ 2000000000).
Output
Output a single integer.
Examples
Input
11
Output
2
Input
14
Output
0
Input
61441
Output
2
Input
571576
Output
10
Input
2128506
Output
3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int ans = 0, a[20];
int main() {
long long n;
scanf("%I64d", &n);
a[0] = 1;
a[1] = 0;
a[2] = 0;
a[3] = 0;
a[4] = 1;
a[5] = 0;
a[6] = 1;
a[7] = 0;
a[8] = 2;
a[9] = 1;
a[10] = 1;
a[11] = 2;
a[12] = 0;
a[13] = 1;
a[14] = 0;
a[15] = 0;
do {
ans += a[n % 16];
n /= 16;
} while (n);
printf("%d\n", ans);
}
``` |
### Prompt
Generate a cpp solution to the following problem:
B: Periodic Sequence-
problem
Dr. Period, a professor at H University, is studying a property called the cycle that is supposed to be hidden in all things. As a generally known basic cycle, a cycle hidden in a sequence may be considered. That is, if the sequence S = S_1, S_2, ..., S_N of length N satisfies the following properties, it has a period t (t \ β€ N).
For 1 \ β€ i \ β€ N β t, S_i = S_ {i + t}.
Now, Dr. Period is paying attention to a sequence that can be described more simply using a period. For example, if a sequence of length N has a period t (\ β€ N) and you can write N = kt using an integer k, then that sequence is a sequence of length t S_1, ..., S_t is k. It can be described that the pieces are continuous. When Dr. Period could describe a sequence as an example, he decided to say that the sequence was a k-part.
Dr. Period is interested in the k-part with the largest k. So, as an assistant, you are tasked with writing a program that takes a sequence as input and outputs the largest k when it is a k-part. Create a program that exactly meets Dr. Period's demands.
Input format
N
S_1 ... S_N
The first row is given the integer N, which represents the length of the sequence. In the second row, the integer S_i (1 \ β€ i \ β€ N) representing each element of the sequence of length N is given, separated by blanks. Also, the inputs satisfy 1 \ β€ N \ β€ 200,000 and 1 \ β€ S_i \ β€ 100,000 (1 \ β€ i \ β€ N).
Output format
For a given sequence, output the maximum value of k when it is k-part in one row.
Input example 1
6
1 2 3 1 2 3
Output example 1
2
Input example 2
12
1 2 1 2 1 2 1 2 1 2 1 2
Output example 2
6
Input example 3
6
1 2 3 4 5 6
Output example 3
1
Example
Input
6
1 2 3 1 2 3
Output
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define all(v) begin(v), end(v)
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define reps(i, s, n) for(int i = (int)(s); i < (int)(n); i++)
template<class T1, class T2> void chmin(T1 &a, T2 b){if(a>b)a=b;}
template<class T1, class T2> void chmax(T1 &a, T2 b){if(a<b)a=b;}
using pint = pair<int, int>;
using tint = tuple<int, int, int>;
using vint = vector<int>;
const int inf = 1LL << 55;
const int mod = 1e9 + 7;
signed main()
{
cin.tie(0);
ios_base::sync_with_stdio(0);
cout << fixed << setprecision(12);
int N, S[200002];
cin >> N;
rep(i, N) cin >> S[i];
reps(i, 1, N+1) {
if(N%i) continue;
bool flag = true;
rep(j, N-i) if(S[j] != S[j+i]) flag = false;
if(flag) {
cout << N / i << endl;
return 0;
}
}
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
The range search problem consists of a set of attributed records S to determine which records from S intersect with a given range.
For n points on a plane, report a set of points which are within in a given range. Note that you do not need to consider insert and delete operations for the set.
Constraints
* 0 β€ n β€ 500,000
* 0 β€ q β€ 20,000
* -1,000,000,000 β€ x, y, sx, tx, sy, ty β€ 1,000,000,000
* sx β€ tx
* sy β€ ty
* For each query, the number of points which are within the range is less than or equal to 100.
Input
n
x0 y0
x1 y1
:
xn-1 yn-1
q
sx0 tx0 sy0 ty0
sx1 tx1 sy1 ty1
:
sxq-1 txq-1 syq-1 tyq-1
The first integer n is the number of points. In the following n lines, the coordinate of the i-th point is given by two integers xi and yi.
The next integer q is the number of queries. In the following q lines, each query is given by four integers, sxi, txi, syi, tyi.
Output
For each query, report IDs of points such that sxi β€ x β€ txi and syi β€ y β€ tyi. The IDs should be reported in ascending order. Print an ID in a line, and print a blank line at the end of output for the each query.
Example
Input
6
2 1
2 2
4 2
6 2
3 3
5 4
2
2 4 0 4
4 10 2 5
Output
0
1
2
4
2
3
5
### Response
```cpp
#include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
#define INT(x) int x; scanf("%d",&x)
#define INPUT(x) scanf("%d",&x)
#define REP1(x,n) for(int x = 0; x < n; x++)
#define REP2(x,s,e) for(int x = s; x <= e; x++)
#define BR printf("\n")
#define INF 2000000000
#define NIL -1
int A[500000][3];//x,y,id
void sort_ck(int l,int r,int c){
priority_queue<pair<int,pair<int,int> > > PQ;
int c_ = (c+1)%2;
REP1(i,r-l) PQ.push(make_pair(-A[l+i][c],make_pair(A[l+i][c_],A[l+i][2])));
REP1(i,r-l){
A[i+l][c] = -PQ.top().first;
A[i+l][c_] = PQ.top().second.first;
A[i+l][2] = PQ.top().second.second;
PQ.pop();
}
}
struct Node{
int id,l,r,p,x,y;
};
Node T[500000];
int np = 0;
int make2Dtree(int l,int r,int d){
if (r-l <= 0) return NIL;
int mid = (l+r)/2;
sort_ck(l,r,d);
int t = np++;
T[t].id = A[mid][2];
T[t].x = A[mid][0];
T[t].y = A[mid][1];
int d_ = (d+1)%2;
T[t].l = make2Dtree(l,mid,d_);
T[t].r = make2Dtree(mid+1,r,d_);
return t;
}
vector<int> ans;
void findTree(int i,int xs,int xt,int ys,int yt,int d){
if (d == 0) {
if(xs <= T[i].x && T[i].l != NIL) findTree(T[i].l,xs,xt,ys,yt,1);
if (xs <= T[i].x && T[i].x <= xt && ys <= T[i].y && T[i].y <= yt) ans.push_back(T[i].id);
if(T[i].x <= xt && T[i].r != NIL) findTree(T[i].r,xs,xt,ys,yt,1);
}else{
if(ys <= T[i].y && T[i].l != NIL) findTree(T[i].l,xs,xt,ys,yt,0);
if (xs <= T[i].x && T[i].x <= xt && ys <= T[i].y && T[i].y <= yt) ans.push_back(T[i].id);
if(T[i].y <= yt && T[i].r != NIL) findTree(T[i].r,xs,xt,ys,yt,0);
}
}
void in_order(Node T[],int i){
if (T[i].l != NIL) in_order(T,T[i].l);
printf("%d\n",T[i].id);
if (T[i].r != NIL) in_order(T,T[i].r);
}
int main(){
INT(n);
REP1(i,n){
INT(x);INT(y);
A[i][0] = x;
A[i][1] = y;
A[i][2] = i;
}
make2Dtree(0,n,0);
INT(q);
REP1(i,q){
INT(xs);INT(xt);INT(ys);INT(yt);
findTree(0,xs,xt,ys,yt,0);
sort(ans.begin(),ans.end());
REP1(j,ans.size()) printf("%d\n",ans[j]);
BR;
ans.clear();
}
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
In one of the games Arkady is fond of the game process happens on a rectangular field. In the game process Arkady can buy extensions for his field, each extension enlarges one of the field sizes in a particular number of times. Formally, there are n extensions, the i-th of them multiplies the width or the length (by Arkady's choice) by ai. Each extension can't be used more than once, the extensions can be used in any order.
Now Arkady's field has size h Γ w. He wants to enlarge it so that it is possible to place a rectangle of size a Γ b on it (along the width or along the length, with sides parallel to the field sides). Find the minimum number of extensions needed to reach Arkady's goal.
Input
The first line contains five integers a, b, h, w and n (1 β€ a, b, h, w, n β€ 100 000) β the sizes of the rectangle needed to be placed, the initial sizes of the field and the number of available extensions.
The second line contains n integers a1, a2, ..., an (2 β€ ai β€ 100 000), where ai equals the integer a side multiplies by when the i-th extension is applied.
Output
Print the minimum number of extensions needed to reach Arkady's goal. If it is not possible to place the rectangle on the field with all extensions, print -1. If the rectangle can be placed on the initial field, print 0.
Examples
Input
3 3 2 4 4
2 5 4 10
Output
1
Input
3 3 3 3 5
2 3 5 4 2
Output
0
Input
5 5 1 2 3
2 2 3
Output
-1
Input
3 4 1 1 3
2 3 2
Output
3
Note
In the first example it is enough to use any of the extensions available. For example, we can enlarge h in 5 times using the second extension. Then h becomes equal 10 and it is now possible to place the rectangle on the field.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void read(long long &x) {
x = 0;
long long f = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-') f = -f;
c = getchar();
}
while (c >= '0' && c <= '9') {
x = (x << 1) + (x << 3) + c - '0';
c = getchar();
}
x *= f;
return;
}
long long fs(long long x) { return x < 0 ? -x : x; }
void print(long long x) {
if (x < 10) {
putchar(x + '0');
return;
}
print(x / 10);
putchar(x % 10 + '0');
return;
}
void write(long long x) {
if (x < 0) {
putchar('-');
x = fs(x);
}
print(x);
return;
}
long long mint(long long x, long long y) { return x < y ? x : y; }
long long maxt(long long x, long long y) { return x > y ? x : y; }
pair<long long, long long> r;
queue<pair<long long, long long> > q;
map<pair<long long, long long>, long long> vis;
bool cmp(long long a, long long b) { return a > b; }
long long n, a, b, h, w, ans = 0x3f3f3f3f, v[100005];
int main() {
read(a), read(b), read(h), read(w), read(n);
if (a > b) swap(a, b);
for (int i = 1; i <= n; i++) read(v[i]);
sort(v + 1, v + 1 + n, cmp);
q.push(pair<long long, long long>(mint(h, w), maxt(h, w)));
while (!q.empty()) {
pair<long long, long long> p = q.front();
q.pop();
long long step = vis[p];
if (p.first >= a && p.second >= b) {
printf("%lld\n", step);
return 0;
}
if (step == n) {
continue;
}
r.first = p.first * v[step + 1];
r.second = p.second;
if (r.first > r.second) swap(r.first, r.second);
if (vis[r] == 0) {
vis[r] = step + 1;
q.push(r);
}
r.first = p.first;
r.second = p.second * v[step + 1];
if (vis[r] == 0) {
vis[r] = step + 1;
q.push(r);
}
}
puts("-1");
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Mr. Bender has a digital table of size n Γ n, each cell can be switched on or off. He wants the field to have at least c switched on squares. When this condition is fulfilled, Mr Bender will be happy.
We'll consider the table rows numbered from top to bottom from 1 to n, and the columns β numbered from left to right from 1 to n. Initially there is exactly one switched on cell with coordinates (x, y) (x is the row number, y is the column number), and all other cells are switched off. Then each second we switch on the cells that are off but have the side-adjacent cells that are on.
For a cell with coordinates (x, y) the side-adjacent cells are cells with coordinates (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1).
In how many seconds will Mr. Bender get happy?
Input
The first line contains four space-separated integers n, x, y, c (1 β€ n, c β€ 109; 1 β€ x, y β€ n; c β€ n2).
Output
In a single line print a single integer β the answer to the problem.
Examples
Input
6 4 3 1
Output
0
Input
9 3 8 10
Output
2
Note
Initially the first test has one painted cell, so the answer is 0. In the second test all events will go as is shown on the figure. <image>.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long N;
long long X, Y;
long long C;
long long calcSide(long long l) {
if (l < 0) return 0;
return l * l;
}
long long calcLeft(long long t) { return calcSide(t - Y); }
long long calcRight(long long t) { return calcSide(t - (N - Y) + 1); }
long long calcTop(long long t) { return calcSide(t - X); }
long long calcBottom(long long t) { return calcSide(t - (N - X) + 1); }
long long calcCorner(long long t) {
if (t < 0) return 0;
return t * (t + 1) / 2;
}
long long calcLeftTop(long long t) { return calcCorner(t - X - Y - 1); }
long long calcLeftBottom(long long t) {
return calcCorner(t - (N - 1 - X) - Y - 1);
}
long long calcRightTop(long long t) {
return calcCorner(t - X - (N - 1 - Y) - 1);
}
long long calcRightBottom(long long t) {
return calcCorner(t - (N - 1 - X) - (N - 1 - Y) - 1);
}
long long calc(long long t) {
long long res = t * t + (t + 1) * (t + 1);
res -= calcLeft(t);
res -= calcRight(t);
res -= calcTop(t);
res -= calcBottom(t);
res += calcLeftTop(t);
res += calcLeftBottom(t);
res += calcRightTop(t);
res += calcRightBottom(t);
return res;
}
int main() {
cin >> N >> X >> Y >> C;
X--;
Y--;
long long a = 0;
long long b = 2000000000;
while (b - a > 2) {
long long c = (a + b) / 2;
long long q = calc(c);
if (q >= C)
b = c;
else
a = c;
}
long long res = b;
for (long long i = a; i < b; i++)
if (calc(i) >= C) {
res = i;
break;
}
cout << res << "\n";
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
There is a robot in a warehouse and n packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0, 0). The i-th package is at the point (x_i, y_i). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0, 0) doesn't contain a package.
The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x, y) to the point (x + 1, y) or to the point (x, y + 1).
As we say above, the robot wants to collect all n packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.
The string s of length n is lexicographically less than the string t of length n if there is some index 1 β€ j β€ n that for all i from 1 to j-1 s_i = t_i and s_j < t_j. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
Input
The first line of the input contains an integer t (1 β€ t β€ 100) β the number of test cases. Then test cases follow.
The first line of a test case contains one integer n (1 β€ n β€ 1000) β the number of packages.
The next n lines contain descriptions of packages. The i-th package is given as two integers x_i and y_i (0 β€ x_i, y_i β€ 1000) β the x-coordinate of the package and the y-coordinate of the package.
It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0, 0) doesn't contain a package.
The sum of all values n over test cases in the test doesn't exceed 1000.
Output
Print the answer for each test case.
If it is impossible to collect all n packages in some order starting from (0,0), print "NO" on the first line.
Otherwise, print "YES" in the first line. Then print the shortest path β a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.
Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
Example
Input
3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
Output
YES
RUUURRRRUU
NO
YES
RRRRUUU
Note
For the first test case in the example the optimal path RUUURRRRUU is shown below:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
const long long inf = 1000000000000000000;
int main() {
long long t;
cin >> t;
while (t--) {
long long n;
cin >> n;
vector<pair<long long, long long> > p(n);
for (auto& x : p) cin >> x.first >> x.second;
sort(p.begin(), p.end());
pair<long long, long long> now = {0, 0};
bool f = 1;
string ans = "";
for (int i = 0; i < n; i++) {
if (p[i].first >= now.first && p[i].second >= now.second) {
long long r = p[i].first - now.first, u = p[i].second - now.second;
while (r--) ans += 'R';
while (u--) ans += 'U';
now = p[i];
} else {
f = 0;
break;
}
}
if (f)
cout << "YES\n" << ans << endl;
else
cout << "NO\n";
}
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
To improve the boomerang throwing skills of the animals, Zookeeper has set up an n Γ n grid with some targets, where each row and each column has at most 2 targets each. The rows are numbered from 1 to n from top to bottom, and the columns are numbered from 1 to n from left to right.
For each column, Zookeeper will throw a boomerang from the bottom of the column (below the grid) upwards. When the boomerang hits any target, it will bounce off, make a 90 degree turn to the right and fly off in a straight line in its new direction. The boomerang can hit multiple targets and does not stop until it leaves the grid.
<image>
In the above example, n=6 and the black crosses are the targets. The boomerang in column 1 (blue arrows) bounces 2 times while the boomerang in column 3 (red arrows) bounces 3 times.
The boomerang in column i hits exactly a_i targets before flying out of the grid. It is known that a_i β€ 3.
However, Zookeeper has lost the original positions of the targets. Thus, he asks you to construct a valid configuration of targets that matches the number of hits for each column, or tell him that no such configuration exists. If multiple valid configurations exist, you may print any of them.
Input
The first line contains a single integer n (1 β€ n β€ 10^5).
The next line contains n integers a_1,a_2,β¦,a_n (0 β€ a_i β€ 3).
Output
If no configuration of targets exist, print -1.
Otherwise, on the first line print a single integer t (0 β€ t β€ 2n): the number of targets in your configuration.
Then print t lines with two spaced integers each per line. Each line should contain two integers r and c (1 β€ r,c β€ n), where r is the target's row and c is the target's column. All targets should be different.
Every row and every column in your configuration should have at most two targets each.
Examples
Input
6
2 0 3 0 1 1
Output
5
2 1
2 5
3 3
3 6
5 6
Input
1
0
Output
0
Input
6
3 2 2 2 1 1
Output
-1
Note
For the first test, the answer configuration is the same as in the picture from the statement.
For the second test, the boomerang is not supposed to hit anything, so we can place 0 targets.
For the third test, the following configuration of targets matches the number of hits, but is not allowed as row 3 has 4 targets.
<image>
It can be shown for this test case that no valid configuration of targets will result in the given number of target hits.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cout.tie(0);
cin.tie(0);
int n;
cin >> n;
int tot = n;
vector<int> S[4], A(n + 1);
for (int i = 1; i <= n; ++i) {
cin >> A[i];
S[A[i]].push_back(i);
}
int Max = -1;
if (((int)(S[3]).size())) {
for (int i = S[3].back(); i <= n; ++i)
if (A[i] == 2) {
Max = i;
break;
}
if (Max == -1) {
for (int i = S[3].back(); i <= n; ++i)
if (A[i] == 1) {
Max = i;
break;
}
if (Max == -1) {
cout << -1;
return 0;
}
}
}
vector<pair<int, int>> ans;
for (int i = ((int)(S[1]).size()) - 1; i >= 0; --i) {
int idx1 = S[1][i], idx2;
if (idx1 == Max) continue;
if (((int)(S[2]).size()))
idx2 = S[2].back(), S[2].pop_back();
else
idx2 = 0;
if (idx2) {
if (idx2 > idx1) {
cout << -1;
return 0;
} else {
ans.emplace_back(tot, idx1);
ans.emplace_back(tot, idx2);
--tot;
}
} else {
ans.emplace_back(tot, idx1);
--tot;
}
}
if (((int)(S[2]).size())) {
cout << -1;
return 0;
}
if (Max != -1 && A[Max] == 1) {
ans.emplace_back(tot, Max);
--tot;
}
for (int i = ((int)(S[3]).size()) - 1; i >= 0; --i) {
ans.emplace_back(tot, S[3][i]);
ans.emplace_back(tot, Max);
Max = S[3][i];
--tot;
}
if (tot >= 0) {
cout << ((int)(ans).size()) << '\n';
for (auto [x, y] : ans) cout << x << " " << y << "\n";
} else {
cout << -1;
}
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
M-kun has the following three cards:
* A red card with the integer A.
* A green card with the integer B.
* A blue card with the integer C.
He is a genius magician who can do the following operation at most K times:
* Choose one of the three cards and multiply the written integer by 2.
His magic is successful if both of the following conditions are satisfied after the operations:
* The integer on the green card is strictly greater than the integer on the red card.
* The integer on the blue card is strictly greater than the integer on the green card.
Determine whether the magic can be successful.
Constraints
* 1 \leq A, B, C \leq 7
* 1 \leq K \leq 7
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B C
K
Output
If the magic can be successful, print `Yes`; otherwise, print `No`.
Examples
Input
7 2 5
3
Output
Yes
Input
7 4 2
3
Output
No
### Response
```cpp
#include <iostream>
using namespace std;
int main()
{
int a,b,c,k;
cin>>a>>b>>c>>k;
for(int i=0;i<k;i++)
{
if(a>=b)
b*=2;
else if(b>=c)
c*=2;
}
if(a<b&&b<c) cout<<"Yes";
else cout<<"No";
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
You are given an integer sequence a of length N. How many permutations p of the integers 1 through N satisfy the following condition?
* For each 1 β€ i β€ N, at least one of the following holds: p_i = a_i and p_{p_i} = a_i.
Find the count modulo 10^9 + 7.
Constraints
* 1 β€ N β€ 10^5
* a_i is an integer.
* 1 β€ a_i β€ N
Input
The input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the number of the permutations p that satisfy the condition, modulo 10^9 + 7.
Examples
Input
3
1 2 3
Output
4
Input
2
1 1
Output
1
Input
3
2 1 1
Output
2
Input
3
1 1 1
Output
0
Input
13
2 1 4 3 6 7 5 9 10 8 8 9 11
Output
6
### Response
```cpp
#include<cstdio>
#define maxn 100005
#define mod 1000000007
int n,a[maxn],deg[maxn],pre[maxn],cnt[maxn],f[maxn],ans=1;
bool vis[maxn];
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++) { scanf("%d",&a[i]); deg[a[i]]++; }
for(int i=1;i<=n;i++)
{
if(deg[i]>2) { printf("0\n"); return 0; }
if(deg[i]<2||vis[i]) continue;
int p=i;
do
{
if(vis[p]) { printf("0\n"); return 0; }
vis[p]=true; pre[a[p]]=p,p=a[p];
}while(p!=i);
}
for(int i=1;i<=n;i++)
if(!deg[i])
{
int p=i,l1=0,l2=0;
while(!vis[p]) vis[p]=true,p=a[p],l1++;
do l2++,p=pre[p]; while(deg[p]!=2);
if(l1<l2) ans=ans*2%mod;
else if(l1>l2) { printf("0\n"); return 0; }
}
for(int i=1;i<=n;i++)
if(!vis[i])
{
int p=i,l=0;
do l++,p=a[p],vis[p]=true; while(p!=i);
cnt[l]++;
}
for(int i=1;i<=n;i++)
{
int mul=1;
if(i!=1&&(i&1)) mul++;
f[0]=1,f[1]=mul;
for(int j=2;j<=cnt[i];j++) f[j]=(1ll*f[j-2]*(j-1)%mod*i%mod+1ll*f[j-1]*mul%mod)%mod;
ans=1ll*ans*f[cnt[i]]%mod;
}
printf("%d\n",ans);
}
``` |
### Prompt
Please create a solution in cpp to 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 n, m;
int num(int i, int j, int k) { return k * (n * m) + i * m + j; }
struct room {
bool l = 0, r = 0, u = 0, d = 0;
};
vector<vector<int> > gr;
int bfs(int start, int finish) {
vector<int> distances(4 * n * m, -1);
distances[start] = 0;
queue<int> Q;
Q.push(start);
while (!Q.empty()) {
int v = Q.front();
Q.pop();
for (int nv : gr[v]) {
if (distances[nv] == -1) {
distances[nv] = distances[v] + 1;
Q.push(nv);
}
}
}
return distances[finish];
}
int main() {
cin >> n >> m;
gr.resize(4 * n * m);
vector<vector<vector<room> > > table(
4, vector<vector<room> >(n, vector<room>(m)));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
char x;
cin >> x;
for (int q = 0; q < 4; ++q) {
if (x == '+' || x == '-' || x == '<' || x == 'R' || x == 'U' ||
x == 'D') {
table[q][i][j].l = 1;
}
if (x == '+' || x == '-' || x == '>' || x == 'L' || x == 'U' ||
x == 'D') {
table[q][i][j].r = 1;
}
if (x == '+' || x == '|' || x == '^' || x == 'R' || x == 'L' ||
x == 'D') {
table[q][i][j].u = 1;
}
if (x == '+' || x == '|' || x == 'v' || x == 'R' || x == 'U' ||
x == 'L') {
table[q][i][j].d = 1;
}
if (x == '-') {
x = '|';
} else if (x == '|') {
x = '-';
} else if (x == '^') {
x = '>';
} else if (x == '>') {
x = 'v';
} else if (x == 'v') {
x = '<';
} else if (x == '<') {
x = '^';
} else if (x == 'R') {
x = 'D';
} else if (x == 'D') {
x = 'L';
} else if (x == 'L') {
x = 'U';
} else if (x == 'U') {
x = 'R';
}
}
}
}
for (int q = 0; q < 4; ++q) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (j > 0) {
if (table[q][i][j - 1].r && table[q][i][j].l) {
gr[num(i, j, q)].push_back(num(i, j - 1, q));
}
}
if (j + 1 < m) {
if (table[q][i][j + 1].l && table[q][i][j].r) {
gr[num(i, j, q)].push_back(num(i, j + 1, q));
}
}
if (i > 0) {
if (table[q][i - 1][j].d && table[q][i][j].u) {
gr[num(i, j, q)].push_back(num(i - 1, j, q));
}
}
if (i + 1 < n) {
if (table[q][i + 1][j].u && table[q][i][j].d) {
gr[num(i, j, q)].push_back(num(i + 1, j, q));
gr[num(i + 1, j, q)].push_back(num(i, j, q));
}
}
if (q > 0) {
gr[num(i, j, q - 1)].push_back(num(i, j, q));
}
if (q == 0) {
gr[num(i, j, 3)].push_back(num(i, j, q));
}
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
bool save = table[q][i][j].l;
table[q][i][j].l = table[q][i][j].d;
table[q][i][j].d = table[q][i][j].r;
table[q][i][j].r = table[q][i][j].u;
table[q][i][j].u = save;
}
}
}
int xt, yt, xm, ym;
cin >> xt >> yt >> xm >> ym;
int w1 = bfs(num(xt - 1, yt - 1, 0), num(xm - 1, ym - 1, 0));
int w2 = bfs(num(xt - 1, yt - 1, 0), num(xm - 1, ym - 1, 1));
int w3 = bfs(num(xt - 1, yt - 1, 0), num(xm - 1, ym - 1, 2));
int w4 = bfs(num(xt - 1, yt - 1, 0), num(xm - 1, ym - 1, 3));
int ans = w1;
if (ans == -1 || w2 < ans) {
ans = w2;
}
if (ans == -1 || w3 < ans) {
ans = w3;
}
if (ans == -1 || w4 < ans) {
ans = w4;
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
There is an infinitely large pond, which we consider as a number line. In this pond, there are N lotuses floating at coordinates 0, 1, 2, ..., N-2 and N-1. On the lotus at coordinate i, an integer s_i is written.
You are standing on the lotus at coordinate 0. You will play a game that proceeds as follows:
* 1. Choose positive integers A and B. Your score is initially 0.
* 2. Let x be your current coordinate, and y = x+A. The lotus at coordinate x disappears, and you move to coordinate y.
* If y = N-1, the game ends.
* If y \neq N-1 and there is a lotus floating at coordinate y, your score increases by s_y.
* If y \neq N-1 and there is no lotus floating at coordinate y, you drown. Your score decreases by 10^{100} points, and the game ends.
* 3. Let x be your current coordinate, and y = x-B. The lotus at coordinate x disappears, and you move to coordinate y.
* If y = N-1, the game ends.
* If y \neq N-1 and there is a lotus floating at coordinate y, your score increases by s_y.
* If y \neq N-1 and there is no lotus floating at coordinate y, you drown. Your score decreases by 10^{100} points, and the game ends.
* 4. Go back to step 2.
You want to end the game with as high a score as possible. What is the score obtained by the optimal choice of A and B?
Constraints
* 3 \leq N \leq 10^5
* -10^9 \leq s_i \leq 10^9
* s_0=s_{N-1}=0
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
s_0 s_1 ...... s_{N-1}
Output
Print the score obtained by the optimal choice of A and B.
Examples
Input
5
0 2 5 1 0
Output
3
Input
6
0 10 -7 -4 -13 0
Output
0
Input
11
0 -4 0 -99 31 14 -15 -39 43 18 0
Output
59
### Response
```cpp
#include <bits/stdc++.h>
#define rep(i,n) for (ll i = 0; i < (n); ++i)
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;
int main() {
ll n;
cin>>n;
vector<ll> s(n);
rep(i,n){
cin>>s[i];
}
ll ans=0;
ll l,r,t;
//η΄ζ₯ι£γΆγ¨γοΌ
for(ll c=1;c<n;c++){
l=0;r=n-1;t=0;
if(r%c==0){
while(l<r){
t+=s[l]+s[r];
ans=max(ans,t);
l+=c;r-=c;
}
}
else{
while(r>c){
t+=s[l]+s[r];
ans=max(ans,t);
l+=c;r-=c;
}
}
}
cout<<ans;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Let's define a balanced multiset the following way. Write down the sum of all elements of the multiset in its decimal representation. For each position of that number check if the multiset includes at least one element such that the digit of the element and the digit of the sum at that position are the same. If that holds for every position, then the multiset is balanced. Otherwise it's unbalanced.
For example, multiset \{20, 300, 10001\} is balanced and multiset \{20, 310, 10001\} is unbalanced:
<image>
The red digits mark the elements and the positions for which these elements have the same digit as the sum. The sum of the first multiset is 10321, every position has the digit required. The sum of the second multiset is 10331 and the second-to-last digit doesn't appear in any number, thus making the multiset unbalanced.
You are given an array a_1, a_2, ..., a_n, consisting of n integers.
You are asked to perform some queries on it. The queries can be of two types:
* 1~i~x β replace a_i with the value x;
* 2~l~r β find the unbalanced subset of the multiset of the numbers a_l, a_{l + 1}, ..., a_r with the minimum sum, or report that no unbalanced subset exists.
Note that the empty multiset is balanced.
For each query of the second type print the lowest sum of the unbalanced subset. Print -1 if no unbalanced subset exists.
Input
The first line contains two integers n and m (1 β€ n, m β€ 2 β
10^5) β the number of elements in the array and the number of queries, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i < 10^9).
Each of the following m lines contains a query of one of two types:
* 1~i~x (1 β€ i β€ n, 1 β€ x < 10^9) β replace a_i with the value x;
* 2~l~r (1 β€ l β€ r β€ n) β find the unbalanced subset of the multiset of the numbers a_l, a_{l + 1}, ..., a_r with the lowest sum, or report that no unbalanced subset exists.
It is guaranteed that there is at least one query of the second type.
Output
For each query of the second type print the lowest sum of the unbalanced subset. Print -1 if no unbalanced subset exists.
Example
Input
4 5
300 10001 20 20
2 1 3
1 1 310
2 1 3
2 3 3
2 3 4
Output
-1
330
-1
40
Note
All the subsets of multiset \{20, 300, 10001\} are balanced, thus the answer is -1.
The possible unbalanced subsets in the third query are \{20, 310\} and \{20, 310, 10001\}. The lowest sum one is \{20, 310\}. Note that you are asked to choose a subset, not a subsegment, thus the chosen elements might not be adjancent in the array.
The fourth query includes only the empty subset and subset \{20\}. Both of them are balanced.
The last query includes the empty subset and the subsets \{20\}, \{20\} and \{20, 20\}. Only \{20, 20\} is unbalanced, its sum is 40. Note that you are asked to choose a multiset, thus it might include equal elements.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 100;
const long long inf = 4e9;
long long min_val[maxn << 2][10];
long long ans[maxn << 2];
int a[maxn];
void push_up(int p) {
int lt = p << 1, rt = p << 1 | 1;
ans[p] = inf;
for (int i = 0; i < 10; ++i) {
if (min_val[lt][i] < inf && min_val[rt][i] < inf) {
ans[p] = min(ans[p], min_val[lt][i] + min_val[rt][i]);
}
min_val[p][i] = min(min_val[lt][i], min_val[rt][i]);
}
ans[p] = min(ans[p], min(ans[lt], ans[rt]));
}
void insert(int l, int r, int pos, int p, int val) {
if (l == r) {
long long tmp = val;
for (int i = 0; i < 10; ++i) {
int t = tmp % 10;
if (t) {
min_val[p][i] = val;
} else {
min_val[p][i] = inf;
}
tmp /= 10;
}
ans[p] = inf;
return;
}
int mid = (l + r) / 2;
if (pos <= mid) {
insert(l, mid, pos, p << 1, val);
} else {
insert(mid + 1, r, pos, p << 1 | 1, val);
}
push_up(p);
}
long long res[11];
long long min_ans;
void query(int l, int r, int L, int R, int p) {
if (L <= l && R >= r) {
for (int i = 0; i < 10; ++i) {
if (res[i] < inf && min_val[p][i] < inf) {
min_ans = min(min_ans, res[i] + min_val[p][i]);
}
res[i] = min(res[i], min_val[p][i]);
}
min_ans = min(min_ans, ans[p]);
return;
}
int mid = (l + r) / 2;
if (mid >= L) {
query(l, mid, L, R, p << 1);
}
if (mid < R) {
query(mid + 1, r, L, R, p << 1 | 1);
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
insert(1, n, i, 1, a[i]);
}
int op, a, b;
for (int i = 0; i < m; ++i) {
cin >> op >> a >> b;
if (op == 1) {
insert(1, n, a, 1, b);
} else {
min_ans = inf;
for (int j = 0; j < 10; ++j) res[j] = inf;
query(1, n, a, b, 1);
if (min_ans == inf) {
cout << -1 << endl;
} else {
cout << min_ans << endl;
}
}
}
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is <image> for SmallR while <image> for Zanoes. The one who shoots in the target first should be the winner.
Output the probability that SmallR will win the match.
Input
A single line contains four integers <image>.
Output
Print a single real number, the probability that SmallR will win the match.
The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
Examples
Input
1 2 1 2
Output
0.666666666667
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
float a, b, c, d, l;
cin >> a >> b >> c >> d;
l = (a * d) / ((b * d) - (b - a) * (d - c));
cout << l;
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Mahmoud has an array a consisting of n integers. He asked Ehab to find another array b of the same length such that:
* b is lexicographically greater than or equal to a.
* bi β₯ 2.
* b is pairwise coprime: for every 1 β€ i < j β€ n, bi and bj are coprime, i. e. GCD(bi, bj) = 1, where GCD(w, z) is the greatest common divisor of w and z.
Ehab wants to choose a special array so he wants the lexicographically minimal array between all the variants. Can you find it?
An array x is lexicographically greater than an array y if there exists an index i such than xi > yi and xj = yj for all 1 β€ j < i. An array x is equal to an array y if xi = yi for all 1 β€ i β€ n.
Input
The first line contains an integer n (1 β€ n β€ 105), the number of elements in a and b.
The second line contains n integers a1, a2, ..., an (2 β€ ai β€ 105), the elements of a.
Output
Output n space-separated integers, the i-th of them representing bi.
Examples
Input
5
2 3 5 4 13
Output
2 3 5 7 11
Input
3
10 3 7
Output
10 3 7
Note
Note that in the second sample, the array is already pairwise coprime so we printed it.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int mxP = 3e6;
vector<bool> pos(mxP, 1);
void ridPrime(int p) {
for (int i = p; i < mxP; i += p) {
pos[i] = 0;
}
}
void doStuff(int x) {
set<int> p_f;
for (int i = 2; i * i <= x;) {
if (x % i == 0) {
x /= i;
p_f.insert(i);
} else
++i;
}
if (x > 1) p_f.insert(x);
for (const int &i : p_f) {
ridPrime(i);
}
}
int n, l = 2;
bool g = 0;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for (int i = 0, a; i < n; ++i) {
cin >> a;
if (!g && pos[a]) {
cout << a << ' ';
doStuff(a);
} else if (!g) {
g = 1;
while (pos[a] == 0) ++a;
cout << a << ' ';
doStuff(a);
} else {
assert(l < mxP);
while (pos[l] == 0) ++l;
cout << l << ' ';
doStuff(l);
continue;
}
}
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Greg has an array a = a1, a2, ..., an and m operations. Each operation looks as: li, ri, di, (1 β€ li β€ ri β€ n). To apply operation i to the array means to increase all array elements with numbers li, li + 1, ..., ri by value di.
Greg wrote down k queries on a piece of paper. Each query has the following form: xi, yi, (1 β€ xi β€ yi β€ m). That means that one should apply operations with numbers xi, xi + 1, ..., yi to the array.
Now Greg is wondering, what the array a will be after all the queries are executed. Help Greg.
Input
The first line contains integers n, m, k (1 β€ n, m, k β€ 105). The second line contains n integers: a1, a2, ..., an (0 β€ ai β€ 105) β the initial array.
Next m lines contain operations, the operation number i is written as three integers: li, ri, di, (1 β€ li β€ ri β€ n), (0 β€ di β€ 105).
Next k lines contain the queries, the query number i is written as two integers: xi, yi, (1 β€ xi β€ yi β€ m).
The numbers in the lines are separated by single spaces.
Output
On a single line print n integers a1, a2, ..., an β the array after executing all the queries. Separate the printed numbers by spaces.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
Examples
Input
3 3 3
1 2 3
1 2 1
1 3 2
2 3 4
1 2
1 3
2 3
Output
9 18 17
Input
1 1 1
1
1 1 1
1 1
Output
2
Input
4 3 6
1 2 3 4
1 2 1
2 3 2
3 4 4
1 2
1 3
2 3
1 2
1 3
2 3
Output
5 18 31 20
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long datas[200000];
long long kl[200000][3] = {0};
long long pl[200000] = {0};
long long cl[200000] = {0};
long long m, n, k;
int main() {
ios::sync_with_stdio(false);
cin >> m >> n >> k;
long long a, b;
for (long long i = 0; i < m; i++) {
cin >> datas[i];
}
for (long long i = 0; i < n; i++) {
cin >> kl[i][0] >> kl[i][1] >> kl[i][2];
}
for (long long i = 0; i < k; i++) {
cin >> a >> b;
pl[a - 1]++;
pl[b]--;
}
long long sum = 0;
for (long long i = 0; i < n; i++) {
sum += pl[i];
kl[i][2] *= sum;
}
for (long long i = 0; i < n; i++) {
cl[kl[i][0] - 1] += kl[i][2];
cl[kl[i][1]] -= kl[i][2];
}
sum = 0;
for (long long i = 0; i < m; i++) {
sum += cl[i];
if (i + 1 == m)
cout << sum + datas[i] << endl;
else
cout << sum + datas[i] << ' ';
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Takahashi's office has N rooms. Each room has an ID from 1 to N. There are also N-1 corridors, and the i-th corridor connects Room a_i and Room b_i. It is known that we can travel between any two rooms using only these corridors.
Takahashi has got lost in one of the rooms. Let this room be r. He decides to get back to his room, Room 1, by repeatedly traveling in the following manner:
* Travel to the room with the smallest ID among the rooms that are adjacent to the rooms already visited, but not visited yet.
Let c_r be the number of travels required to get back to Room 1. Find all of c_2,c_3,...,c_N. Note that, no matter how many corridors he passes through in a travel, it still counts as one travel.
Constraints
* 2 \leq N \leq 2\times 10^5
* 1 \leq a_i,b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
Print c_r for each r, in the following format:
c_2 c_3 ... c_N
Output
Print c_r for each r, in the following format:
c_2 c_3 ... c_N
Examples
Input
6
1 5
5 6
6 2
6 3
6 4
Output
5 5 5 1 5
Input
6
1 2
2 3
3 4
4 5
5 6
Output
1 2 3 4 5
Input
10
1 5
5 6
6 10
6 4
10 3
10 8
8 2
4 7
4 9
Output
7 5 3 1 3 4 7 4 5
### Response
```cpp
#include <map>
#include <cstdio>
using namespace std;
const int MAXN = 2e5 + 5;
template<typename _T>
void read( _T &x )
{
x = 0;char s = getchar();int f = 1;
while( s > '9' || s < '0' ){if( s == '-' ) f = -1; s = getchar();}
while( s >= '0' && s <= '9' ){x = ( x << 3 ) + ( x << 1 ) + ( s - '0' ), s = getchar();}
x *= f;
}
template<typename _T>
void write( _T x )
{
if( x < 0 ){ putchar( '-' ); x = ( ~ x ) + 1; }
if( 9 < x ){ write( x / 10 ); }
putchar( x % 10 + '0' );
}
template<typename _T>
_T MAX( const _T a, const _T b )
{
return a > b ? a : b;
}
struct edge
{
int to, nxt;
}Graph[MAXN << 1];
map<int, int> q[MAXN];
int mx[MAXN], c[MAXN];
int head[MAXN];
int N, cnt;
void addEdge( const int from, const int to )
{
Graph[++ cnt].to = to, Graph[cnt].nxt = head[from];
head[from] = cnt;
}
int Q( const int u, const int fa, const int val )
{
if( q[u][val] ) return q[u][val];
q[u][val] = 1;
for( int i = head[u], v ; i ; i = Graph[i].nxt )
if( ( v = Graph[i].to ) ^ fa && v < val )
q[u][val] += Q( v, u, val );
return q[u][val];
}
void DFS( const int u, const int fa )
{
mx[u] = MAX( u, mx[fa] );
for( int i = head[u], v ; i ; i = Graph[i].nxt )
if( ( v = Graph[i].to ) ^ fa )
{
if( mx[u] == u )
{
c[v] = c[u] + Q( v, u, mx[u] );
if( v < mx[fa] ) c[v] -= Q( v, u, mx[fa] );
}
else
{
if( v < mx[u] ) c[v] = c[u];
else c[v] = c[u] + Q( v, u, mx[u] );
}
DFS( v, u );
}
}
int main()
{
read( N );
for( int i = 1, a, b ; i < N ; i ++ )
read( a ), read( b ), addEdge( a, b ), addEdge( b, a );
DFS( 1, 0 );
for( int i = 2 ; i <= N ; i ++ ) write( c[i] ), putchar( i == N ? '\n' : ' ' );
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
You are playing a video game and you have just reached the bonus level, where the only possible goal is to score as many points as possible. Being a perfectionist, you've decided that you won't leave this level until you've gained the maximum possible number of points there.
The bonus level consists of n small platforms placed in a line and numbered from 1 to n from left to right and (n - 1) bridges connecting adjacent platforms. The bridges between the platforms are very fragile, and for each bridge the number of times one can pass this bridge from one of its ends to the other before it collapses forever is known in advance.
The player's actions are as follows. First, he selects one of the platforms to be the starting position for his hero. After that the player can freely move the hero across the platforms moving by the undestroyed bridges. As soon as the hero finds himself on a platform with no undestroyed bridge attached to it, the level is automatically ended. The number of points scored by the player at the end of the level is calculated as the number of transitions made by the hero between the platforms. Note that if the hero started moving by a certain bridge, he has to continue moving in the same direction until he is on a platform.
Find how many points you need to score to be sure that nobody will beat your record, and move to the next level with a quiet heart.
Input
The first line contains a single integer n (2 β€ n β€ 105) β the number of platforms on the bonus level. The second line contains (n - 1) integers ai (1 β€ ai β€ 109, 1 β€ i < n) β the number of transitions from one end to the other that the bridge between platforms i and i + 1 can bear.
Output
Print a single integer β the maximum number of points a player can get on the bonus level.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5
2 1 2 1
Output
5
Note
One possibility of getting 5 points in the sample is starting from platform 3 and consequently moving to platforms 4, 3, 2, 1 and 2. After that the only undestroyed bridge is the bridge between platforms 4 and 5, but this bridge is too far from platform 2 where the hero is located now.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n, ma, a[100100], dp1[100100], dp2[100100], dp3[100100], dp4[100100];
int main() {
ios_base::sync_with_stdio(false);
cin >> n;
for (int i = 1; i <= n - 1; i++) cin >> a[i];
for (int i = 1; i <= n - 1; i++) {
dp2[i] = ((a[i] % 2 == 0) ? a[i] : (a[i] - 1)) + dp2[i - 1];
if (a[i] == 1) dp2[i] = 0;
dp1[i] = max(dp2[i], dp1[i - 1] + ((a[i] & 1) ? a[i] : (a[i] - 1)));
}
for (int i = n - 2; i >= 1; i--) {
dp4[i] = ((a[i + 1] % 2 == 0) ? a[i + 1] : (a[i + 1] - 1)) + dp4[i + 1];
if (a[i + 1] == 1) dp4[i] = 0;
dp3[i] =
max(dp4[i], dp3[i + 1] + ((a[i + 1] & 1) ? a[i + 1] : (a[i + 1] - 1)));
}
for (int i = 1; i <= n - 1; i++)
ma = max(ma, max(dp2[i] + dp3[i], dp1[i] + dp4[i]));
cout << ma;
return -0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
There are n children, who study at the school β41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.
Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other.
You are given the number n, the initial arrangement of children and the number k. You have to find a way for the children to act if they want to finish the process in exactly k seconds. More formally, for each of the k moves, you need to output the numbers of the children who turn left during this move.
For instance, for the configuration shown below and k = 2 children can do the following steps:
<image> At the beginning, two pairs make move: (1, 2) and (3, 4). After that, we receive the following configuration: <image> At the second move pair (2, 3) makes the move. The final configuration is reached. Good job. <image>
It is guaranteed that if the solution exists, it takes not more than n^2 "headturns".
Input
The first line of input contains two integers n and k (2 β€ n β€ 3000, 1 β€ k β€ 3000000) β the number of children and required number of moves.
The next line contains a string of length n and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right.
Output
If there is no solution, print a single line with number -1.
Otherwise, output k lines. Each line has to start with a number n_i (1β€ n_i β€ n/2) β the number of pairs of children, who turn at this move. After that print n_i distinct integers β the numbers of the children who will turn left during this move.
After performing all "headturns", there can't be a pair of two neighboring children looking at each other.
If there are many solutions, print any of them.
Examples
Input
2 1
RL
Output
1 1
Input
2 1
LR
Output
-1
Input
4 2
RLRL
Output
2 1 3
1 2
Note
The first sample contains a pair of children who look at each other. After one move, they can finish the process.
In the second sample, children can't make any move. As a result, they can't end in k>0 moves.
The third configuration is described in the statement.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k, i, cnt = 0;
string s;
cin >> n >> k >> s;
vector<vector<int>> a;
while (1) {
vector<int> temp;
for (i = 0; i < n - 1; i++) {
if (s[i] > s[i + 1]) {
temp.push_back(i);
cnt++;
}
}
if (temp.empty()) break;
for (int j : temp) {
swap(s[j], s[j + 1]);
}
a.push_back(temp);
}
if (k < a.size() || k > cnt) {
cout << -1;
} else {
for (vector<int> &d : a) {
while (d.size() > 1 && k > a.size()) {
cout << "1 " << d.back() + 1 << "\n";
d.pop_back();
k--;
}
cout << d.size();
for (int j = 0; j < d.size(); j++) {
cout << " " << d[j] + 1;
}
cout << "\n";
}
}
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.
Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in circles muttering about how useless her sweetheart is. During that time Dima has time to peacefully complete k - 1 tasks. Then Inna returns and tells Dima off for the next task he does in her presence and goes to another room again. It continues until Dima is through with his tasks.
Overall, Dima has n tasks to do, each task has a unique number from 1 to n. Dima loves order, so he does tasks consecutively, starting from some task. For example, if Dima has 6 tasks to do in total, then, if he starts from the 5-th task, the order is like that: first Dima does the 5-th task, then the 6-th one, then the 1-st one, then the 2-nd one, then the 3-rd one, then the 4-th one.
Inna tells Dima off (only lovingly and appropriately!) so often and systematically that he's very well learned the power with which she tells him off for each task. Help Dima choose the first task so that in total he gets told off with as little power as possible.
Input
The first line of the input contains two integers n, k (1 β€ k β€ n β€ 105). The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 103), where ai is the power Inna tells Dima off with if she is present in the room while he is doing the i-th task.
It is guaranteed that n is divisible by k.
Output
In a single line print the number of the task Dima should start with to get told off with as little power as possible. If there are multiple solutions, print the one with the minimum number of the first task to do.
Examples
Input
6 2
3 2 1 6 5 4
Output
1
Input
10 5
1 3 5 7 9 9 4 1 8 5
Output
3
Note
Explanation of the first example.
If Dima starts from the first task, Inna tells him off with power 3, then Dima can do one more task (as k = 2), then Inna tells him off for the third task with power 1, then she tells him off for the fifth task with power 5. Thus, Dima gets told off with total power 3 + 1 + 5 = 9. If Dima started from the second task, for example, then Inna would tell him off for tasks 2, 4 and 6 with power 2 + 6 + 4 = 12.
Explanation of the second example.
In the second example k = 5, thus, Dima manages to complete 4 tasks in-between the telling off sessions. Thus, Inna tells Dima off for tasks number 1 and 6 (if he starts from 1 or 6), 2 and 7 (if he starts from 2 or 7) and so on. The optimal answer is to start from task 3 or 8, 3 has a smaller number, so the answer is 3.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k, task[100100];
while (scanf("%d%d", &n, &k) != EOF) {
for (int i = 0; i < n; i++) {
scanf("%d", &task[i]);
}
int min = 0x7fffffff, minpos = -1;
for (int i = 0; i < k; i++) {
int sum = task[i];
int j = (i + k) % n;
while (i != j) {
sum += task[j];
j = (j + k) % n;
}
if (sum < min) {
min = sum;
minpos = i;
}
}
cout << minpos + 1 << endl;
}
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Xenia likes puzzles very much. She is especially fond of the puzzles that consist of domino pieces. Look at the picture that shows one of such puzzles.
<image>
A puzzle is a 3 Γ n table with forbidden cells (black squares) containing dominoes (colored rectangles on the picture). A puzzle is called correct if it meets the following conditions:
* each domino occupies exactly two non-forbidden cells of the table;
* no two dominoes occupy the same table cell;
* exactly one non-forbidden cell of the table is unoccupied by any domino (it is marked by a circle in the picture).
To solve the puzzle, you need multiple steps to transport an empty cell from the starting position to some specified position. A move is transporting a domino to the empty cell, provided that the puzzle stays correct. The horizontal dominoes can be moved only horizontally, and vertical dominoes can be moved only vertically. You can't rotate dominoes. The picture shows a probable move.
Xenia has a 3 Γ n table with forbidden cells and a cell marked with a circle. Also, Xenia has very many identical dominoes. Now Xenia is wondering, how many distinct correct puzzles she can make if she puts dominoes on the existing table. Also, Xenia wants the circle-marked cell to be empty in the resulting puzzle. The puzzle must contain at least one move.
Help Xenia, count the described number of puzzles. As the described number can be rather large, print the remainder after dividing it by 1000000007 (109 + 7).
Input
The first line contains integer n (3 β€ n β€ 104) β the puzzle's size. Each of the following three lines contains n characters β the description of the table. The j-th character of the i-th line equals "X" if the corresponding cell is forbidden; it equals ".", if the corresponding cell is non-forbidden and "O", if the corresponding cell is marked with a circle.
It is guaranteed that exactly one cell in the table is marked with a circle. It is guaranteed that all cells of a given table having at least one common point with the marked cell is non-forbidden.
Output
Print a single number β the answer to the problem modulo 1000000007 (109 + 7).
Examples
Input
5
....X
.O...
...X.
Output
1
Input
5
.....
.O...
.....
Output
2
Input
3
...
...
..O
Output
4
Note
Two puzzles are considered distinct if there is a pair of cells that contain one domino in one puzzle and do not contain it in the other one.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <class T>
inline T min(T &a, T &b) {
return a < b ? a : b;
}
template <class T>
inline T max(T &a, T &b) {
return a > b ? a : b;
}
template <class T>
void read(T &x) {
char ch;
while ((ch = getchar()) && !isdigit(ch))
;
x = ch - '0';
while ((ch = getchar()) && isdigit(ch)) x = x * 10 + ch - '0';
}
struct point {
int x, y;
point() {}
point(int _x, int _y) : x(_x), y(_y) {}
};
const int N = 11000, Mod = 1000000007;
int dp[N][8], n, dt[4][N], Ox, Oy, ans, ty[10];
char s[N];
int get() {
memset(dp, 0, sizeof(dp));
;
dp[0][7] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= 7; j++)
for (int k = 0; k <= 7; k++) {
int flag = 0;
for (int l = 0; l <= 2; l++)
if (!(j & (1 << l)) && (!(k & (1 << l)) || dt[l + 1][i])) flag = 1;
for (int l = 0; l <= 2; l++)
if (dt[l + 1][i] && !(k & (1 << l))) flag = 1;
for (int l = 0; l <= 2; l++)
if (!dt[l + 1][i] && (j & (1 << l)) && (k & (1 << l))) flag = 1;
if (flag) continue;
dp[i][k] = (dp[i][k] + dp[i - 1][j]) % Mod;
}
if (dt[1][i] == 0 && dt[2][i] == 0) dp[i][3] = (dp[i][3] + dp[i][0]) % Mod;
if (dt[2][i] == 0 && dt[3][i] == 0) dp[i][6] = (dp[i][6] + dp[i][0]) % Mod;
if (dt[1][i] == 0 && dt[2][i] == 0) dp[i][7] = (dp[i][7] + dp[i][4]) % Mod;
if (dt[2][i] == 0 && dt[3][i] == 0) dp[i][7] = (dp[i][7] + dp[i][1]) % Mod;
}
return dp[n][7];
}
void work(int ty) {
if (ty == 0)
dt[Ox][Oy - 1] ^= 1, dt[Ox][Oy - 2] ^= 1;
else if (ty == 1)
dt[Ox][Oy + 1] ^= 1, dt[Ox][Oy + 2] ^= 1;
else if (ty == 2)
dt[Ox + 1][Oy] ^= 1, dt[Ox + 2][Oy] ^= 1;
else
dt[Ox - 1][Oy] ^= 1, dt[Ox - 2][Oy] ^= 1;
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= 3; i++) {
scanf("%s", s + 1);
for (int j = 1; j <= n; j++) {
if (s[j] != '.') dt[i][j] = 1;
if (s[j] == 'O') Ox = i, Oy = j;
}
}
if (Oy > 2 && !dt[Ox][Oy - 1] && !dt[Ox][Oy - 2]) {
work(0);
ans = (ans + get()) % Mod;
work(0);
ty[0] = 1;
}
if (Oy + 2 <= n && !dt[Ox][Oy + 1] && !dt[Ox][Oy + 2]) {
work(1);
ans = (ans + get()) % Mod;
work(1);
ty[1] = 1;
}
if (Ox == 1 && !dt[Ox + 1][Oy] && !dt[Ox + 2][Oy]) {
work(2);
ans = (ans + get()) % Mod;
work(2);
ty[2] = 1;
}
if (Ox == 3 && !dt[Ox - 1][Oy] && !dt[Ox - 2][Oy]) {
work(3);
ans = (ans + get()) % Mod;
work(3);
ty[3] = 1;
}
for (int i = 0; i <= 3; i++)
for (int j = i + 1; j <= 3; j++)
if (ty[i] && ty[j]) {
work(i);
work(j);
ans = (ans - get()) % Mod;
work(i);
work(j);
}
for (int i = 0; i <= 3; i++)
for (int j = i + 1; j <= 3; j++)
for (int k = j + 1; k <= 3; k++)
if (ty[i] && ty[j] && ty[k]) {
work(i);
work(j);
work(k);
ans = (ans + get()) % Mod;
work(i);
work(j);
work(k);
}
printf("%d\n", (ans + Mod) % Mod);
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Takeshi, who loves hot springs, is planning a trip to a hot spring resort on his next long vacation. I would like to travel by connecting to a long-distance bus and reach my destination with as little money as possible. Takeshi, who has savings but is unwilling to pay, decided to consult with his grandfather. The grandfather, who was impressed by the plan, gave Takeshi a special ticket.
The ticket was that you could ride two consecutive sections of a long-distance bus only once for free. Depending on how you use it, you can expect a considerable reduction in travel costs, but you need to make a solid plan in order to achieve a greater effect.
A total of n departure points, destinations, and relay points, and m lines connecting the two points are given. Each point is assigned a number from 1 to n. The starting point is 1 and the destination is n. Route information is represented by the two points a and b that connect the route and its fare c. Due to the special ticket validity, you can pass two consecutive lines from any point at no charge. However, passing through the destination on the way does not mean that you have reached the destination.
Create a program that outputs the minimum fare by inputting the total number of departure points, destinations, and relay points n, the number of routes m, and the information of each route. However, there must always be a route from the origin to the destination.
input
Given multiple datasets. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
n m
a1 b1 c1
a2 b2 c2
::
am bm cm
The first line gives the total number of origins, destinations, and transit points n (2 β€ n β€ 100) and the number of routes m (1 β€ m β€ 300). The following m lines give information for each line ai, bi, ci (1 β€ ci β€ 1000).
The number of datasets does not exceed 40.
output
Prints the minimum charge on one line for each input dataset.
Example
Input
2 1
1 2 5
3 2
1 2 5
2 3 5
6 9
1 2 7
1 3 9
1 5 14
2 3 10
2 4 15
3 4 11
3 5 2
4 5 9
4 6 8
0 0
Output
5
0
7
### Response
```cpp
#include <vector>
#include <iostream>
#include <utility>
#include <algorithm>
#include <string>
#include <deque>
#include <queue>
#include <tuple>
#include <queue>
#include <functional>
#include <cmath>
#include <iomanip>
#include <map>
#include <set>
#include <numeric>
#include <unordered_map>
#include <unordered_set>
#include <complex>
#include <iterator>
#include <array>
#include <memory>
#include <stack>
#define vi vector<int>
#define vvi vector<vector<int> >
#define ll long long int
#define vl vector<ll>
#define vvl vector<vector<ll>>
#define vb vector<bool>
#define vc vector<char>
#define vs vector<string>
#define ld long double
#define INF 1e9
#define EPS 0.0000000001
#define rep(i,n) for(int i=0;i<n;i++)
#define loop(i,s,n) for(int i=s;i<n;i++)
#define all(in) in.begin(), in.end()
template<class T, class S> void cmin(T &a, const S &b) { if (a > b)a = b; }
template<class T, class S> void cmax(T &a, const S &b) { if (a < b)a = b; }
#define MAX 9999999
using namespace std;
typedef pair<int, int> pii;
typedef pair<double,double>pdd;
typedef pair<ll,ll>pll;
typedef pair<pii,int>piii;
int main(){
int n,m;
while(cin>>n>>m,n+m){
vvi hoge(n+1,vi(n+1,INF));
//edge[index]=(distance,next_vertex)
vector<vector<pii>>edge(n,vector<pii>());
vector<vector<pii>>temp(n,vector<pii>());
rep(i,m){
int a,b,c; cin>>a>>b>>c;
--a,--b;
edge[a].push_back(pii(b,c));
edge[b].push_back(pii(a,c));
}
vvi d(3,vi(n,INF));
d[0][0]=0;
priority_queue<piii,vector<piii>,greater<piii>>que;
que.push(piii(pii(0,0),0));
while(!que.empty()){
piii now=que.top();que.pop();
//cout<<now.first.first<<" "<<now.first.second<<" "<<now.second<<endl;
for(int i=0; i<edge[now.second].size();i++){
pii next=edge[now.second][i];
if(now.first.second==0){
if(now.first.second==0&&d[0][next.first]>d[0][now.second]+next.second){
que.push(piii(pii(d[0][now.second]+next.second,0),next.first));
d[0][next.first]=d[0][now.second]+next.second;
}
if(now.first.second==0&&d[1][next.first]>d[0][now.second]){
d[1][next.first]=d[0][now.second];
que.push(piii(pii(now.first.first,1),next.first));
}
}else if(now.first.second==1){
if(d[2][next.first]>d[1][now.second]){
que.push(piii(pii(d[1][now.second],2),next.first));
d[2][next.first]=d[1][now.second];
}
}else if(now.first.second==2&&d[2][next.first]>d[2][now.second]+next.second){
d[2][next.first]=d[2][now.second]+next.second;
que.push(piii(pii(now.first.first+next.second,2),next.first));
}
}
}
cout<<min(d[0][n-1],d[2][n-1])<<endl;
}
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Osaki
Osaki
English text is not available in this practice contest.
The Yamanote Line is a circular railway line laid in the 23 wards of Tokyo. The total route distance is 34.5km, and one lap takes about one hour. There are 29 stations in total. The line color is Uguisu color. The peak congestion rate exceeds 200%, making it one of the busiest railway lines in Japan. One train runs every three minutes during the busiest hours, and people who come to Tokyo for the first time are amazed at the sight.
Mr. Tetsuko loves the Yamanote Line and loves genuine railways. One day, she came up with the following question while reading her favorite book, the JR timetable. "How many vehicles are used a day on the Yamanote Line?"
She tried to figure out the minimum number of vehicles required for operation from the timetable. However, the number of trains was so large that she couldn't count it by herself. So she turned to you, a good programmer, for help.
Your job is to write a program to find the minimum number of cars required to operate the Yamanote Line from a given timetable. Since the Yamanote Line is a circular line, the timetable is often written with "Osaki Station" as the starting and ending stations for convenience. Therefore, only the departure and arrival times of each train at Osaki Station are recorded in the timetable given by her.
Although this cannot happen on the actual Yamanote Line, in order to simplify the situation setting, we will consider that the train can depart from Osaki Station immediately after it arrives at Osaki Station. In addition, there are cases where the time taken by Mr. Tetsuko is incorrect, or the train added by Mr. Tetsuko's delusion is mixed in the timetable, but you can not see them, so to the last The number must be calculated for the time as written.
If you write a program that works, she may invite you to a date on the train. However, it is up to you to accept or decline the invitation.
Input
The input consists of multiple datasets. Each dataset has the following format.
> n
> hh: mm: ss hh: mm: ss
> hh: mm: ss hh: mm: ss
> ...
> hh: mm: ss hh: mm: ss
The integer n in the first line is the number of trains included in the timetable. This value is guaranteed not to exceed 10,000. The departure time and arrival time of each train at Osaki Station are given in this order on the n lines from the 2nd line to the n + 1st line, and the departure time and arrival time are separated by a single space. Each time is expressed in the format hh: mm: ss, where hh is the hour, mm is the minute, and ss is the second. The range of each value is 0 β€ hh <24, 0 β€ mm <60, 0 β€ ss <60. All of these numbers are prefixed with 0s as needed to be two digits.
Trains that run across 24:00 at night are not included. Therefore, the departure time is always before the arrival time.
The end of input is indicated by n = 0. It is not included in the dataset.
Output
For each dataset, output the minimum number of vehicles required on one line.
Sample Input
3
05:47:15 09:54:40
12:12:59 12:13:00
16:30:20 21:18:53
6
00:00:00 03:00:00
01:00:00 03:00:00
02:00:00 03:00:00
03:00:00 04:00:00
03:00:00 05:00:00
03:00:00 06:00:00
0
Output for the Sample Input
1
3
Example
Input
3
05:47:15 09:54:40
12:12:59 12:13:00
16:30:20 21:18:53
6
00:00:00 03:00:00
01:00:00 03:00:00
02:00:00 03:00:00
03:00:00 04:00:00
03:00:00 05:00:00
03:00:00 06:00:00
0
Output
1
3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef pair<long long, long long> P;
void solve(int n){
vector<int> v;
vector<P> w;
for(int i=0; i<n; ++i){
int a, b, h, m, s;
scanf("%d:%d:%d", &h, &m, &s);
a = 3600*h + 60*m + s;
scanf("%d:%d:%d", &h, &m, &s);
b = 3600*h + 60*m + s;
w.push_back(P(a, b));
}
sort(w.begin(), w.end());
for(int i=0; i<n; ++i){
int a = w[i].first;
int b = w[i].second;
bool f = false;
for(int j=0; j<v.size(); ++j)
if(v[j] <= a){
v[j] = b;
f = true;
break;
}
if(!f) v.push_back(b);
sort(v.begin(), v.end());
}
cout << v.size() << "\n";
}
int main(){
// cin.tie(0);
// ios::sync_with_stdio(false);
while(1){
int n;
cin >> n;
if(n == 0) return 0;
solve(n);
}
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.
Let's index all the leaf nodes from the left to the right from 1 to 2h. The exit is located at some node n where 1 β€ n β€ 2h, the player doesn't know where the exit is so he has to guess his way out!
Amr follows simple algorithm to choose the path. Let's consider infinite command string "LRLRLRLRL..." (consisting of alternating characters 'L' and 'R'). Amr sequentially executes the characters of the string using following rules:
* Character 'L' means "go to the left child of the current node";
* Character 'R' means "go to the right child of the current node";
* If the destination node is already visited, Amr skips current command, otherwise he moves to the destination node;
* If Amr skipped two consecutive commands, he goes back to the parent of the current node before executing next command;
* If he reached a leaf node that is not the exit, he returns to the parent of the current node;
* If he reaches an exit, the game is finished.
Now Amr wonders, if he follows this algorithm, how many nodes he is going to visit before reaching the exit?
Input
Input consists of two integers h, n (1 β€ h β€ 50, 1 β€ n β€ 2h).
Output
Output a single integer representing the number of nodes (excluding the exit node) Amr is going to visit before reaching the exit by following this algorithm.
Examples
Input
1 2
Output
2
Input
2 3
Output
5
Input
3 6
Output
10
Input
10 1024
Output
2046
Note
A perfect binary tree of height h is a binary tree consisting of h + 1 levels. Level 0 consists of a single node called root, level h consists of 2h nodes called leaves. Each node that is not a leaf has exactly two children, left and right one.
Following picture illustrates the sample test number 3. Nodes are labeled according to the order of visit.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int inf = 0x7fffffff;
int main() {
long long h, n;
cin >> h >> n;
long long t = 1;
for (int i = 0; i < h; i++) t *= 2;
long long ans = 0;
int hehe = 1;
for (int i = 0; i < h; i++) {
t /= 2;
if (n > t) {
if (hehe == 1)
ans += t * 2;
else
ans++;
n -= t, hehe = 1;
} else {
if (hehe == 0)
ans += t * 2;
else
ans++;
hehe = 0;
}
}
cout << ans << endl;
;
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
You are given a positive integer n greater or equal to 2. For every pair of integers a and b (2 β€ |a|, |b| β€ n), you can transform a into b if and only if there exists an integer x such that 1 < |x| and (a β
x = b or b β
x = a), where |x| denotes the absolute value of x.
After such a transformation, your score increases by |x| points and you are not allowed to transform a into b nor b into a anymore.
Initially, you have a score of 0. You can start at any integer and transform it as many times as you like. What is the maximum score you can achieve?
Input
A single line contains a single integer n (2 β€ n β€ 100 000) β the given integer described above.
Output
Print an only integer β the maximum score that can be achieved with the transformations. If it is not possible to perform even a single transformation for all possible starting integers, print 0.
Examples
Input
4
Output
8
Input
6
Output
28
Input
2
Output
0
Note
In the first example, the transformations are 2 β 4 β (-2) β (-4) β 2.
In the third example, it is impossible to perform even a single transformation.
### Response
```cpp
#include <bits/stdc++.h>
int main(void) {
int n;
scanf("%d", &n);
long long int ans = 0;
for (int i = 2; i <= n; i++) {
for (int j = 2; i * j <= n; j++) {
ans += j;
}
}
printf("%lld\n", 4 * ans);
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
In Japan, temperature is usually expressed using the Celsius (β) scale. In America, they used the Fahrenheit (β) scale instead. $20$ degrees Celsius is roughly equal to $68$ degrees Fahrenheit. A phrase such as "Todayβs temperature is $68$ degrees" is commonly encountered while you are in America.
A value in Fahrenheit can be converted to Celsius by first subtracting $32$ and then multiplying by $\frac{5}{9}$. A simplified method may be used to produce a rough estimate: first subtract $30$ and then divide by $2$. Using the latter method, $68$ Fahrenheit is converted to $19$ Centigrade, i.e., $\frac{(68-30)}{2}$.
Make a program to convert Fahrenheit to Celsius using the simplified method: $C = \frac{F - 30}{2}$.
Input
The input is given in the following format.
$F$
The input line provides a temperature in Fahrenheit $F$ ($30 \leq F \leq 100$), which is an integer divisible by $2$.
Output
Output the converted Celsius temperature in a line.
Examples
Input
68
Output
19
Input
50
Output
10
### Response
```cpp
#include<iostream>
using namespace std;
int main(){
int f,c;
cin >> f;
c = (f-30)/2;
cout << c << endl;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
A tree is an undirected graph with exactly one simple path between each pair of vertices. We call a set of simple paths k-valid if each vertex of the tree belongs to no more than one of these paths (including endpoints) and each path consists of exactly k vertices.
You are given a tree with n vertices. For each k from 1 to n inclusive find what is the maximum possible size of a k-valid set of simple paths.
Input
The first line of the input contains a single integer n (2 β€ n β€ 100 000) β the number of vertices in the tree.
Then following n - 1 lines describe the tree, each of them contains two integers v, u (1 β€ v, u β€ n) β endpoints of the corresponding edge.
It is guaranteed, that the given graph is a tree.
Output
Output n numbers, the i-th of which is the maximum possible number of paths in an i-valid set of paths.
Examples
Input
7
1 2
2 3
3 4
4 5
5 6
6 7
Output
7
3
2
1
1
1
1
Input
6
1 2
2 3
2 4
1 5
5 6
Output
6
2
2
1
1
0
Note
One way to achieve the optimal number of paths for the second sample is illustrated in the following picture:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long read() {
long long x = 0, f = 1;
char ch = ' ';
while (!isdigit(ch)) {
ch = getchar();
if (ch == '-') f = -1;
}
while (isdigit(ch)) x = (x << 3) + (x << 1) + (ch ^ 48), ch = getchar();
return x * f;
}
int n, ans, tot, h[100003];
vector<int> g[100003];
struct AB {
int a, b, n;
} d[100003];
void charu(int a, int b) {
d[++tot].a = a, d[tot].b = b, d[tot].n = h[a], h[a] = tot;
}
int dfs(int u, int num) {
int first = 0, second = 0;
for (int k = h[u]; k; k = d[k].n) {
int v = d[k].b;
int tmp = dfs(v, num);
if (tmp > first)
second = first, first = tmp;
else if (tmp > second)
second = tmp;
}
if (first + second + 1 >= num) {
ans++;
return 0;
}
return first + 1;
}
void dfs1(int u, int fa) {
for (int v : g[u]) {
if (v == fa) continue;
charu(u, v);
dfs1(v, u);
}
}
int solve(int num) {
ans = 0;
dfs(1, num);
return ans;
}
int main() {
cin >> n;
for (int i = 1; i < n; i++) {
int a = read(), b = read();
g[a].push_back(b);
g[b].push_back(a);
}
dfs1(1, 0);
int p = sqrt(n * (log(n) / log(2)));
;
cout << n << endl;
for (int i = 2; i <= p; i++) {
printf("%d\n", solve(i));
}
int di = solve(p), las = p;
for (int i = di; i >= 0; i--) {
if (solve(las + 1) != i) continue;
int l = las + 1, r = n, mid;
while (l < r) {
mid = (l + r + 1) >> 1;
if (solve(mid) == i)
l = mid;
else
r = mid - 1;
}
for (int j = las + 1; j <= r; j++) printf("%d\n", i);
las = r;
}
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
In BerSoft n programmers work, the programmer i is characterized by a skill r_i.
A programmer a can be a mentor of a programmer b if and only if the skill of the programmer a is strictly greater than the skill of the programmer b (r_a > r_b) and programmers a and b are not in a quarrel.
You are given the skills of each programmers and a list of k pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer i, find the number of programmers, for which the programmer i can be a mentor.
Input
The first line contains two integers n and k (2 β€ n β€ 2 β
10^5, 0 β€ k β€ min(2 β
10^5, (n β
(n - 1))/(2))) β total number of programmers and number of pairs of programmers which are in a quarrel.
The second line contains a sequence of integers r_1, r_2, ..., r_n (1 β€ r_i β€ 10^{9}), where r_i equals to the skill of the i-th programmer.
Each of the following k lines contains two distinct integers x, y (1 β€ x, y β€ n, x β y) β pair of programmers in a quarrel. The pairs are unordered, it means that if x is in a quarrel with y then y is in a quarrel with x. Guaranteed, that for each pair (x, y) there are no other pairs (x, y) and (y, x) in the input.
Output
Print n integers, the i-th number should be equal to the number of programmers, for which the i-th programmer can be a mentor. Programmers are numbered in the same order that their skills are given in the input.
Examples
Input
4 2
10 4 10 15
1 2
4 3
Output
0 0 1 2
Input
10 4
5 4 1 5 4 3 7 1 2 5
4 6
2 1
10 8
3 5
Output
5 4 0 5 3 3 9 0 2 5
Note
In the first example, the first programmer can not be mentor of any other (because only the second programmer has a skill, lower than first programmer skill, but they are in a quarrel). The second programmer can not be mentor of any other programmer, because his skill is minimal among others. The third programmer can be a mentor of the second programmer. The fourth programmer can be a mentor of the first and of the second programmers. He can not be a mentor of the third programmer, because they are in a quarrel.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 2e5 + 5;
vector<int> mp;
int a[MAX_N], ans[MAX_N];
int main() {
int n, m, x, y;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
mp.push_back(a[i]);
}
sort(mp.begin(), mp.end());
for (int i = 1; i <= n; i++) {
ans[i] = lower_bound(mp.begin(), mp.end(), a[i]) - mp.begin();
}
for (int i = 1; i <= m; i++) {
scanf("%d%d", &x, &y);
if (a[x] > a[y]) ans[x]--;
if (a[x] < a[y]) ans[y]--;
}
for (int i = 1; i <= n; i++) printf("%d ", ans[i]);
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.
* For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead").
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the length of showcase string s.
The second line contains string s, consisting of exactly n lowercase Latin letters.
The third line contains one integer m (1 β€ m β€ 5 β
10^4) β the number of friends.
The i-th of the next m lines contains t_i (1 β€ |t_i| β€ 2 β
10^5) β the name of the i-th friend.
It is guaranteed that β _{i=1}^m |t_i| β€ 2 β
10^5.
Output
For each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Example
Input
9
arrayhead
5
arya
harry
ray
r
areahydra
Output
5
6
5
2
9
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool comp(vector<int> &k, vector<int> &kek) {
for (int i = 0; i < 26; i++) {
if (kek[i] < k[i]) return 0;
}
return 1;
}
int main() {
int n;
cin >> n;
string s;
cin >> s;
vector<vector<int> > kek(n + 1, vector<int>(26));
for (int i = 1; i <= n; i++) {
kek[i] = kek[i - 1];
kek[i][s[i - 1] - 'a']++;
}
int t;
cin >> t;
string tt;
while (t--) {
cin >> tt;
vector<int> k(26);
for (auto &i : tt) k[i - 'a']++;
int l = 1, r = n;
while (l < r) {
int mid = (l + r) >> 1;
if (comp(k, kek[mid])) {
r = mid;
} else
l = mid + 1;
}
cout << r << '\n';
}
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.
A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.
A cyclic shift of a permutation (p_1, p_2, β¦, p_n) is a permutation (p_i, p_{i + 1}, β¦, p_{n}, p_1, p_2, β¦, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).
A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, β¦, a_{i_k} for some i_1, i_2, β¦, i_k such that l β€ i_1 < i_2 < β¦ < i_k β€ r.
Input
The first line contains three integers n, m, q (1 β€ n, m, q β€ 2 β
10^5) β the length of the permutation p, the length of the array a and the number of queries.
The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once.
The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a.
The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive.
Output
Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise.
Examples
Input
3 6 3
2 1 3
1 2 3 1 2 3
1 5
2 6
3 5
Output
110
Input
2 4 3
2 1
1 1 2 2
1 2
2 3
3 4
Output
010
Note
In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation.
In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 15;
const int M = 18;
int in[N];
int lastInd[N], len[N];
int per[N], perInd[N];
int jump[N][M];
int minDist[N];
int seg[N * 4];
void init(int pos, int l, int r) {
if (l == r) {
seg[pos] = minDist[l];
return;
}
int mid = (l + r) / 2;
init(pos * 2, l, mid);
init(pos * 2 + 1, mid + 1, r);
seg[pos] = min(seg[pos * 2], seg[pos * 2 + 1]);
}
int query(int pos, int l, int r, int ql, int qr) {
if (r < ql || qr < l) {
return 1e9;
}
if (ql <= l && r <= qr) {
return seg[pos];
}
int mid = (l + r) / 2;
return min(query(pos * 2, l, mid, ql, qr),
query(pos * 2 + 1, mid + 1, r, ql, qr));
}
void solve() {
int n, m, q;
scanf("%d %d %d", &n, &m, &q);
for (int i = 1; i <= n; ++i) {
scanf("%d", &per[i]);
perInd[per[i]] = i;
}
for (int i = 1; i <= m; ++i) {
scanf("%d", &in[i]);
}
memset(lastInd, -1, sizeof(lastInd));
for (int i = m; i >= 1; --i) {
minDist[i] = 1e9;
int curPerInd = perInd[in[i]];
int nextInd = curPerInd + 1;
if (nextInd > n) {
nextInd -= n;
}
nextInd = lastInd[per[nextInd]];
if (nextInd == -1) {
len[i] = 1;
} else {
len[i] = min(n, len[nextInd] + 1);
jump[i][0] = nextInd;
for (int j = 1; j < M; ++j) {
jump[i][j] = jump[jump[i][j - 1]][j - 1];
}
}
if (len[i] == n) {
int cur = i, d = n - 1;
for (int j = 0; j < M; ++j) {
if (d & (1 << j)) {
cur = jump[cur][j];
}
}
minDist[i] = cur;
}
lastInd[in[i]] = i;
}
init(1, 1, m);
for (int i = 0; i < q; ++i) {
int l, r;
scanf("%d %d", &l, &r);
int q = query(1, 1, m, l, r);
if (q <= r) {
printf("1");
} else {
printf("0");
}
}
cout << endl;
}
int main() { solve(); }
``` |
### Prompt
Generate a cpp solution to the following problem:
Your friend has recently learned about coprime numbers. A pair of numbers {a, b} is called coprime if the maximum number that divides both a and b is equal to one.
Your friend often comes up with different statements. He has recently supposed that if the pair (a, b) is coprime and the pair (b, c) is coprime, then the pair (a, c) is coprime.
You want to find a counterexample for your friend's statement. Therefore, your task is to find three distinct numbers (a, b, c), for which the statement is false, and the numbers meet the condition l β€ a < b < c β€ r.
More specifically, you need to find three numbers (a, b, c), such that l β€ a < b < c β€ r, pairs (a, b) and (b, c) are coprime, and pair (a, c) is not coprime.
Input
The single line contains two positive space-separated integers l, r (1 β€ l β€ r β€ 1018; r - l β€ 50).
Output
Print three positive space-separated integers a, b, c β three distinct numbers (a, b, c) that form the counterexample. If there are several solutions, you are allowed to print any of them. The numbers must be printed in ascending order.
If the counterexample does not exist, print the single number -1.
Examples
Input
2 4
Output
2 3 4
Input
10 11
Output
-1
Input
900000000000000009 900000000000000029
Output
900000000000000009 900000000000000010 900000000000000021
Note
In the first sample pair (2, 4) is not coprime and pairs (2, 3) and (3, 4) are.
In the second sample you cannot form a group of three distinct integers, so the answer is -1.
In the third sample it is easy to see that numbers 900000000000000009 and 900000000000000021 are divisible by three.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
int cp(long long a, long long b) {
if (gcd(a, b) == 1) return 1;
return 0;
}
int main() {
long long l, r, t, i, j, a, b, c, n, m, k;
cin >> l >> r;
n = 0;
for (i = l; i <= r; ++i) {
for (j = i + 1; j <= r; ++j) {
for (k = j + 1; k <= r; ++k) {
if (cp(i, k) == 0 && cp(i, j) == 1 && cp(j, k) == 1) {
n = 1;
break;
}
}
if (n == 1) break;
}
if (n == 1) break;
}
if (n == 1)
cout << i << ' ' << j << ' ' << k;
else
cout << "-1";
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
There are an integer sequence A_1,...,A_N consisting of N terms, and N buttons. When the i-th (1 β¦ i β¦ N) button is pressed, the values of the i terms from the first through the i-th are all incremented by 1.
There is also another integer sequence B_1,...,B_N. Takahashi will push the buttons some number of times so that for every i, A_i will be a multiple of B_i.
Find the minimum number of times Takahashi will press the buttons.
Constraints
* All input values are integers.
* 1 β¦ N β¦ 10^5
* 0 β¦ A_i β¦ 10^9(1 β¦ i β¦ N)
* 1 β¦ B_i β¦ 10^9(1 β¦ i β¦ N)
Input
The input is given from Standard Input in the following format:
N
A_1 B_1
:
A_N B_N
Output
Print an integer representing the minimum number of times Takahashi will press the buttons.
Examples
Input
3
3 5
2 7
9 4
Output
7
Input
7
3 1
4 1
5 9
2 6
5 3
5 8
9 7
Output
22
### Response
```cpp
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int N;
cin >> N;
long A[N], B[N];
for(int i = 0; i < N; i++){
cin >> A[i] >> B[i];
}
long plus = 0;
for(int i = N - 1; i >= 0; i--){
plus += B[i] - (A[i] + plus + B[i] - 1) % B[i] - 1;
}
cout << plus << endl;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
There are lots of theories concerning the origin of moon craters. Most scientists stick to the meteorite theory, which says that the craters were formed as a result of celestial bodies colliding with the Moon. The other version is that the craters were parts of volcanoes.
An extraterrestrial intelligence research specialist professor Okulov (the namesake of the Okulov, the author of famous textbooks on programming) put forward an alternate hypothesis. Guess what kind of a hypothesis it was ββ sure, the one including extraterrestrial mind involvement. Now the professor is looking for proofs of his hypothesis.
Professor has data from the moon robot that moves linearly in one direction along the Moon surface. The moon craters are circular in form with integer-valued radii. The moon robot records only the craters whose centers lay on his path and sends to the Earth the information on the distance from the centers of the craters to the initial point of its path and on the radii of the craters.
According to the theory of professor Okulov two craters made by an extraterrestrial intelligence for the aims yet unknown either are fully enclosed one in the other or do not intersect at all. Internal or external tangency is acceptable. However the experimental data from the moon robot do not confirm this theory! Nevertheless, professor Okulov is hopeful. He perfectly understands that to create any logical theory one has to ignore some data that are wrong due to faulty measuring (or skillful disguise by the extraterrestrial intelligence that will be sooner or later found by professor Okulov!) Thatβs why Okulov wants to choose among the available crater descriptions the largest set that would satisfy his theory.
Input
The first line has an integer n (1 β€ n β€ 2000) β the number of discovered craters. The next n lines contain crater descriptions in the "ci ri" format, where ci is the coordinate of the center of the crater on the moon robotβs path, ri is the radius of the crater. All the numbers ci and ri are positive integers not exceeding 109. No two craters coincide.
Output
In the first line output the number of craters in the required largest set. In the next line output space-separated numbers of craters that this set consists of. The craters are numbered from 1 to n in the order in which they were given in the input data. The numbers may be output in any order. If the result is not unique, output any.
Examples
Input
4
1 1
2 2
4 1
5 1
Output
3
1 2 4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2005;
const int INF = 2000000000;
struct Tpair {
int rad, c;
int l() { return c - rad; }
int r() { return c + rad; }
} P[maxn];
int n;
void init() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d%d", &P[i].c, &P[i].rad);
}
int ord[maxn];
int a[maxn];
vector<int> ans[maxn];
bool cmp1(int a, int b) { return P[a].rad < P[b].rad; }
bool cmp2(int a, int b) {
return P[a].r() < P[b].r() || (P[a].r() == P[b].r() && P[a].l() > P[b].l());
}
int cur[maxn];
int f[maxn], lat[maxn], best[maxn];
void work() {
P[0].c = 0, P[0].rad = INF;
for (int i = 0; i <= n; i++) ord[i] = a[i] = i;
sort(ord, ord + n + 1, cmp1);
sort(a, a + n + 1, cmp2);
for (int i = 0; i <= n; i++) {
int u = ord[i], cs = 0;
for (int j = 0; j <= n; j++)
if (a[j] != u && P[a[j]].l() >= P[u].l() && P[a[j]].r() <= P[u].r())
cur[cs++] = a[j];
ans[u].push_back(u);
if (cs) {
for (int j = 0; j < cs; j++) {
int v = cur[j];
if (!j || P[cur[0]].r() > P[v].l()) {
f[j] = ans[v].size();
lat[j] = -1;
} else {
int L = 0, R = j - 1;
while (L < R) {
int mid = (L + R + 1) >> 1;
if (P[cur[mid]].r() <= P[v].l())
L = mid;
else
R = mid - 1;
}
lat[j] = L;
f[j] = ans[v].size() + f[best[lat[j]]];
}
if (j && f[best[j - 1]] > f[j])
best[j] = best[j - 1];
else
best[j] = j;
}
for (int t = cs - 1; t != -1; t = lat[t]) {
t = best[t];
int v = cur[t];
for (int i = 0; i < ans[v].size(); i++) ans[u].push_back(ans[v][i]);
}
}
}
}
void print() {
printf("%d\n", ans[0].size() - 1);
for (int i = 1; i < ans[0].size(); i++) printf("%d ", ans[0][i]);
printf("\n");
}
int main() {
init();
work();
print();
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
The DNA sequence for every living creature in Berland can be represented as a non-empty line consisting of lowercase Latin letters. Berland scientists found out that all the creatures evolve by stages. During one stage exactly one symbol of the DNA line is replaced by exactly two other ones. At that overall there are n permissible substitutions. The substitution ai->bici means that any one symbol ai can be replaced with two symbols bici. Every substitution could happen an unlimited number of times.
They say that two creatures with DNA sequences s1 and s2 can have a common ancestor if there exists such a DNA sequence s3 that throughout evolution it can result in s1 and s2, perhaps after a different number of stages. Your task is to find out by the given s1 and s2 whether the creatures possessing such DNA sequences can have a common ancestor. If the answer is positive, you have to find the length of the shortest sequence of the common ancestorβs DNA.
Input
The first line contains a non-empty DNA sequence s1, the second line contains a non-empty DNA sequence s2. The lengths of these lines do not exceed 50, the lines contain only lowercase Latin letters. The third line contains an integer n (0 β€ n β€ 50) β the number of permissible substitutions. Then follow n lines each of which describes a substitution in the format ai->bici. The characters ai, bi, and ci are lowercase Latin letters. Lines s1 and s2 can coincide, the list of substitutions can contain similar substitutions.
Output
If s1 and s2 cannot have a common ancestor, print -1. Otherwise print the length of the shortest sequence s3, from which s1 and s2 could have evolved.
Examples
Input
ababa
aba
2
c->ba
c->cc
Output
2
Input
ababa
aba
7
c->ba
c->cc
e->ab
z->ea
b->ba
d->dd
d->ab
Output
1
Input
ababa
aba
1
c->ba
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
map<pair<char, char>, char> hash;
char c, x, y, s1[101], s2[101];
int f[101][101];
int a[61][61], b[61][61];
vector<pair<char, char> > p[31];
int n;
int main() {
scanf("%s%s%d", s1, s2, &n);
int l1 = strlen(s1);
int l2 = strlen(s2);
for (int i = 1; i <= n; i++) {
getchar();
c = getchar();
getchar();
getchar();
x = getchar();
y = getchar();
p[c - 'a'].push_back(pair<char, char>(x - 'a', y - 'a'));
}
for (int i = 0; i <= l1 - 1; i++) a[i + 1][i + 1] = 1 << s1[i] - 'a';
for (int i = 0; i <= l2 - 1; i++) b[i + 1][i + 1] = 1 << s2[i] - 'a';
for (int len = 1; len <= l1; len++)
for (int i = 1; i <= l1 - len + 1; i++) {
int j = i + len - 1;
for (int k = 0; k <= 25; k++)
for (int is = 0; is < p[k].size(); is++) {
for (int t = i; t <= j - 1; t++)
if ((a[i][t] & 1 << p[k][is].first) &&
(a[t + 1][j] & 1 << p[k][is].second)) {
a[i][j] |= 1 << k;
break;
}
if (a[i][j] & 1 << k) break;
}
}
for (int len = 1; len <= l2; len++)
for (int i = 1; i <= l2 - len + 1; i++) {
int j = i + len - 1;
for (int k = 0; k <= 25; k++)
for (int is = 0; is < p[k].size(); is++) {
for (int t = i; t <= j - 1; t++)
if ((b[i][t] & 1 << p[k][is].first) &&
(b[t + 1][j] & 1 << p[k][is].second)) {
b[i][j] |= 1 << k;
break;
}
if (b[i][j] & 1 << k) break;
}
}
memset(f, 120, sizeof(f));
f[0][0] = 0;
for (int i = 1; i <= l1; i++)
for (int j = 1; j <= l2; j++)
for (int i1 = 0; i1 <= i - 1; i1++)
for (int j1 = 0; j1 <= j - 1; j1++)
if ((a[i1 + 1][i] & b[j1 + 1][j]) != 0)
f[i][j] = min(f[i][j], f[i1][j1] + 1);
printf("%d\n", f[l1][l2] < 100 ? f[l1][l2] : -1);
fclose(stdin);
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Developing tools for creation of locations maps for turn-based fights in a new game, Petya faced the following problem.
A field map consists of hexagonal cells. Since locations sizes are going to be big, a game designer wants to have a tool for quick filling of a field part with identical enemy units. This action will look like following: a game designer will select a rectangular area on the map, and each cell whose center belongs to the selected rectangle will be filled with the enemy unit.
More formally, if a game designer selected cells having coordinates (x1, y1) and (x2, y2), where x1 β€ x2 and y1 β€ y2, then all cells having center coordinates (x, y) such that x1 β€ x β€ x2 and y1 β€ y β€ y2 will be filled. Orthogonal coordinates system is set up so that one of cell sides is parallel to OX axis, all hexagon centers have integer coordinates and for each integer x there are cells having center with such x coordinate and for each integer y there are cells having center with such y coordinate. It is guaranteed that difference x2 - x1 is divisible by 2.
Working on the problem Petya decided that before painting selected units he wants to output number of units that will be painted on the map.
Help him implement counting of these units before painting.
<image>
Input
The only line of input contains four integers x1, y1, x2, y2 ( - 109 β€ x1 β€ x2 β€ 109, - 109 β€ y1 β€ y2 β€ 109) β the coordinates of the centers of two cells.
Output
Output one integer β the number of cells to be filled.
Examples
Input
1 1 5 5
Output
13
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
cout << (x2 - x1) / 2LL * (y2 - y1 + 1) + (y2 - y1 + 2 - ((x1 ^ x2) & 1)) / 2
<< endl;
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
You are given an undirected graph where each edge has one of two colors: black or red.
Your task is to assign a real number to each node so that:
* for each black edge the sum of values at its endpoints is 1;
* for each red edge the sum of values at its endpoints is 2;
* the sum of the absolute values of all assigned numbers is the smallest possible.
Otherwise, if it is not possible, report that there is no feasible assignment of the numbers.
Input
The first line contains two integers N (1 β€ N β€ 100 000) and M (0 β€ M β€ 200 000): the number of nodes and the number of edges, respectively. The nodes are numbered by consecutive integers: 1, 2, β¦, N.
The next M lines describe the edges. Each line contains three integers a, b and c denoting that there is an edge between nodes a and b (1 β€ a, b β€ N) with color c (1 denotes black, 2 denotes red).
Output
If there is a solution, the first line should contain the word "YES" and the second line should contain N space-separated numbers. For each i (1 β€ i β€ N), the i-th number should be the number assigned to the node i.
Output should be such that:
* the sum of the numbers at the endpoints of each edge differs from the precise value by less than 10^{-6};
* the sum of the absolute values of all assigned numbers differs from the smallest possible by less than 10^{-6}.
If there are several valid solutions, output any of them.
If there is no solution, the only line should contain the word "NO".
Scoring
Subtasks:
1. (5 points) N β€ 5, M β€ 14
2. (12 points) N β€ 100
3. (17 points) N β€ 1000
4. (24 points) N β€ 10 000
5. (42 points) No further constraints
Examples
Input
4 4
1 2 1
2 3 2
1 3 2
3 4 1
Output
YES
0.5 0.5 1.5 -0.5
Input
2 1
1 2 1
Output
YES
0.3 0.7
Input
3 2
1 2 2
2 3 2
Output
YES
0 2 0
Input
3 4
1 2 2
2 2 1
2 1 1
1 2 2
Output
NO
Note
Note that in the second example the solution is not unique.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int N, M;
cin >> N >> M;
vector<vector<pair<int, int>>> adj(N);
for (int i = 0; i < M; i++) {
int u, v, c;
cin >> u >> v >> c;
u--, v--;
adj[u].emplace_back(v, 2 * c);
adj[v].emplace_back(u, 2 * c);
}
const int UNDET = 1e9;
vector<int> ans(N, UNDET);
vector<set<pair<int, int>>> state(N);
vector<int> trial(N, UNDET);
for (int i = 0; i < N; i++) {
if (ans[i] != UNDET) {
continue;
}
static queue<int> q;
static vector<int> vis;
q.emplace(i);
state[i].insert({1, 0});
while (!q.empty()) {
int u = q.front();
vis.emplace_back(u);
q.pop();
for (auto e : adj[u]) {
int v = e.first;
int c = e.second;
for (auto it : state[u]) {
if (state[v].count({-it.first, c - it.second}) == 0) {
state[v].insert({-it.first, c - it.second});
q.emplace(v);
}
}
if (state[v].size() > 2) {
cout << "NO\n";
return 0;
}
}
}
int x = UNDET;
for (auto u : vis) {
if (state[u].size() == 1) {
continue;
}
int a = begin(state[u])->first;
int b = begin(state[u])->second;
int c = next(begin(state[u]))->first;
int d = next(begin(state[u]))->second;
if (a == c && b != d) {
cout << "NO\n";
return 0;
}
x = (d - b) / (a - c);
break;
}
if (x != UNDET) {
for (auto u : vis) {
ans[u] = begin(state[u])->first * x + begin(state[u])->second;
}
for (auto u : vis) {
for (auto e : adj[u]) {
int v = e.first;
int c = e.second;
if (ans[u] + ans[v] != c) {
cout << "NO\n";
return 0;
}
}
}
} else {
auto FindCost = [&](int st) {
for (auto u : vis) {
trial[u] = UNDET;
}
trial[i] = st;
long long cur = 0;
bool can = true;
for (auto u : vis) {
if (!can) {
break;
}
cur += max(trial[u], -trial[u]);
for (auto e : adj[u]) {
int v = e.first;
int c = e.second;
if (trial[v] == UNDET) {
trial[v] = c - trial[u];
}
if (trial[u] + trial[v] != c) {
can = false;
break;
}
}
}
return can ? cur : UNDET;
};
int lo = -1e7, hi = 1e7;
while (lo < hi) {
int md = (lo + hi) >> 1;
if (FindCost(md) < FindCost(md + 1)) {
hi = md;
} else {
lo = md + 1;
}
}
FindCost(lo);
for (auto u : vis) {
ans[u] = trial[u];
}
}
vis.clear();
if (ans[i] == UNDET) {
break;
}
}
if (count(begin(ans), end(ans), UNDET) > 0) {
cout << "NO\n";
} else {
cout << "YES\n";
for (int i = 0; i < N; i++) {
cout << (double)ans[i] / 2 << " ";
}
cout << "\n";
}
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Everyone knows what the Fibonacci sequence is. This sequence can be defined by the recurrence relation:
F1 = 1, F2 = 2, Fi = Fi - 1 + Fi - 2 (i > 2).
We'll define a new number sequence Ai(k) by the formula:
Ai(k) = Fi Γ ik (i β₯ 1).
In this problem, your task is to calculate the following sum: A1(k) + A2(k) + ... + An(k). The answer can be very large, so print it modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers n, k (1 β€ n β€ 1017; 1 β€ k β€ 40).
Output
Print a single integer β the sum of the first n elements of the sequence Ai(k) modulo 1000000007 (109 + 7).
Examples
Input
1 1
Output
1
Input
4 1
Output
34
Input
5 2
Output
316
Input
7 4
Output
73825
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n;
int k, C[50][50], pw[50], p1[50], p2[50];
pair<int, int> fib(long long x) {
if (!x) return make_pair(1, 1);
pair<int, int> ff;
if (x % 2) {
ff = fib((x - 1) / 2);
return make_pair(
(int)(1LL * ff.first * (2ll * ff.second - ff.first) % 1000000007),
(int)(1LL * ff.first * ff.first % 1000000007 +
1ll * ff.second * ff.second % 1000000007) %
1000000007);
} else {
ff = fib((x - 2) / 2);
return make_pair(
(int)(1LL * ff.first * ff.first % 1000000007 +
1ll * ff.second * ff.second % 1000000007) %
1000000007,
(int)(1LL * ff.second * (ff.second + 2ll * ff.first) % 1000000007));
}
}
int calc(long long n, int k) {
int ans[50], f2 = fib(n + 2).first, f1 = fib(n + 1).first;
ans[0] = (f2 - 2) % 1000000007;
for (int i = 1; i <= k; i++) {
ans[i] = (pw[i + 1] - (1ll * p2[i] * f2) % 1000000007) % 1000000007;
for (int j = 1; j <= i; j++) {
ans[i] += (1ll * C[i][j] *
((1ll * ans[i - j] * (pw[j] + 1)) % 1000000007 +
(1ll * p1[i - j] * f1) % 1000000007 - 1)) %
1000000007;
ans[i] %= 1000000007;
}
ans[i] = (-ans[i]) % 1000000007;
}
return (ans[k] + 1000000007) % 1000000007;
}
int main() {
scanf("%I64d %d", &n, &k);
for (int i = 0; i < 50; i++) C[i][0] = 1, C[i][i] = 1;
for (int i = 1; i < 50; i++) {
for (int j = 1; j < i; j++) {
C[i][j] = C[i - 1][j] + C[i - 1][j - 1];
C[i][j] %= 1000000007;
}
}
for (int i = 0; i < 50; i++) {
if (i == 0)
pw[0] = 1, p1[0] = 1, p2[0] = 1;
else
pw[i] = (2ll * pw[i - 1]) % 1000000007,
p1[i] = (1ll * p1[i - 1] * (n % 1000000007 + 1)) % 1000000007,
p2[i] = (1ll * p2[i - 1] * (n % 1000000007 + 2)) % 1000000007;
}
printf("%d\n", calc(n, k));
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.