text
stringlengths 424
69.5k
|
---|
### Prompt
Develop a solution in CPP to the problem described below:
Today is tuesday, that means there is a dispute in JOHNNY SOLVING team again: they try to understand who is Johnny and who is Solving. That's why guys asked Umnik to help them. Umnik gave guys a connected graph with n vertices without loops and multiedges, such that a degree of any vertex is at least 3, and also he gave a number 1 ≤ k ≤ n. Because Johnny is not too smart, he promised to find a simple path with length at least n/k in the graph. In reply, Solving promised to find k simple by vertices cycles with representatives, such that:
* Length of each cycle is at least 3.
* Length of each cycle is not divisible by 3.
* In each cycle must be a representative - vertex, which belongs only to this cycle among all printed cycles.
You need to help guys resolve the dispute, for that you need to find a solution for Johnny: a simple path with length at least n/k (n is not necessarily divided by k), or solution for Solving: k cycles that satisfy all the conditions above. If there is no any solution - print -1.
Input
The first line contains three integers n, m and k (1 ≤ k ≤ n ≤ 2.5 ⋅ 10^5, 1 ≤ m ≤ 5 ⋅ 10^5)
Next m lines describe edges of the graph in format v, u (1 ≤ v, u ≤ n). It's guaranteed that v ≠ u and all m pairs are distinct.
It's guaranteed that a degree of each vertex is at least 3.
Output
Print PATH in the first line, if you solve problem for Johnny. In the second line print the number of vertices in the path c (c ≥ n/k). And in the third line print vertices describing the path in route order.
Print CYCLES in the first line, if you solve problem for Solving. In the following lines describe exactly k cycles in the following format: in the first line print the size of the cycle c (c ≥ 3). In the second line print the cycle in route order. Also, the first vertex in the cycle must be a representative.
Print -1 if there is no any solution. The total amount of printed numbers in the output must be at most 10^6. It's guaranteed, that if exists any solution then there is a correct output satisfies this restriction.
Examples
Input
4 6 2
1 2
1 3
1 4
2 3
2 4
3 4
Output
PATH
4
1 2 3 4
Input
10 18 2
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
2 3
3 4
2 4
5 6
6 7
5 7
8 9
9 10
8 10
Output
CYCLES
4
4 1 2 3
4
7 1 5 6
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
vector<int> deep(n + 1);
vector<vector<int>> E(n + 1);
int u, v;
for (int i = 1; i <= m; i++) {
scanf("%d%d", &u, &v);
E[u].push_back(v);
E[v].push_back(u);
}
bool flag = false;
vector<bool> vis(n + 1);
fill(vis.begin(), vis.end(), false);
vector<int> a(n + 1);
function<void(int)> path_dfs;
path_dfs = [&](int now) {
vis[now] = true;
a[deep[now]] = now;
if (deep[now] == n / k) {
flag = true;
printf("PATH\n%d\n", deep[now] + 1);
for (int i = 0; i <= deep[now]; i++) printf("%d ", a[i]);
printf("\n");
return;
}
for (auto it : E[now]) {
if (vis[it]) continue;
deep[it] = deep[now] + 1;
path_dfs(it);
if (flag) return;
}
};
deep[1] = 0;
path_dfs(1);
if (flag) return 0;
fill(vis.begin(), vis.end(), false);
function<void(int, int)> dfs;
dfs = [&](int now, int fa) {
vis[now] = true;
a[deep[now]] = now;
int cnt = 0;
for (auto it : E[now]) {
if (vis[it]) continue;
cnt++;
dfs(it, now);
if (k == 0) return;
}
if (cnt) return;
k--;
sort(E[now].begin(), E[now].end(),
[&](const int& a, const int& b) { return deep[a] > deep[b]; });
int u = 0, v = 0;
for (auto it : E[now]) {
if (it == fa) continue;
if (!u)
u = it;
else {
v = it;
break;
}
}
if ((deep[now] - deep[u] + 1) % 3) {
printf("%d\n", deep[now] - deep[u] + 1);
printf("%d ", now);
for (int i = deep[u]; i < deep[now]; i++) printf("%d ", a[i]);
} else if ((deep[now] - deep[v] + 1) % 3) {
printf("%d\n", deep[now] - deep[v] + 1);
printf("%d ", now);
for (int i = deep[v]; i < deep[now]; i++) printf("%d ", a[i]);
} else {
printf("%d\n", deep[u] - deep[v] + 2);
printf("%d ", now);
for (int i = deep[v]; i <= deep[u]; i++) printf("%d ", a[i]);
}
printf("\n");
};
printf("CYCLES\n");
dfs(1, 0);
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count.
The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if n = 5, then after the third throw the child number 2 has the ball again. Overall, n - 1 throws are made, and the game ends.
The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.
Input
The first line contains integer n (2 ≤ n ≤ 100) which indicates the number of kids in the circle.
Output
In the single line print n - 1 numbers which are the numbers of children who will get the ball after each throw. Separate the numbers by spaces.
Examples
Input
10
Output
2 4 7 1 6 2 9 7 6
Input
3
Output
2 1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int tab[1001];
int temp[1001];
int main() {
int n;
cin >> n;
int temp = 2;
cout << 2 << " ";
for (long long i = 2; i < n; i++) {
temp += i;
if (temp > n) {
cout << temp - n << " ";
temp -= n;
} else
cout << temp << " ";
}
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.
Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.
Every element of the sequence must appear in exactly one subsequence.
Input
The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence.
The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct.
Output
In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements.
In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence.
Indices could be printed in any order. Every index from 1 to n must appear in output exactly once.
If there are several possible answers, print any of them.
Examples
Input
6
3 2 1 6 5 4
Output
4
2 1 3
1 2
2 4 6
1 5
Input
6
83 -75 -49 11 37 62
Output
1
6 1 2 3 4 5 6
Note
In the first sample output:
After sorting the first subsequence we will get sequence 1 2 3 6 5 4.
Sorting the second subsequence changes nothing.
After sorting the third subsequence we will get sequence 1 2 3 4 5 6.
Sorting the last subsequence changes nothing.
### Response
```cpp
#include <bits/stdc++.h>
const double PI = acos(-1);
using namespace std;
const int MAX = 1 << 20;
int A[MAX], B[MAX], n;
vector<vector<int> > ans;
int vis[MAX];
int main() {
scanf("%d", &n);
for (int i = 0; i < (n); i++) scanf("%d", A + i);
copy(A, A + n, B);
sort(B, B + n);
int m = unique(B, B + n) - B;
for (int i = 0; i < (n); i++) A[i] = lower_bound(B, B + m, A[i]) - B;
for (int i = 0; i < (n); i++)
if (!vis[i]) {
int cur = i;
vector<int> aux;
while (!vis[cur]) {
vis[cur] = 1;
aux.push_back(cur + 1);
cur = A[cur];
}
ans.push_back(aux);
}
printf("%d\n", ((int)ans.size()));
for (auto V : ans) {
printf("%d", ((int)V.size()));
for (int x : V) printf(" %d", x);
puts("");
}
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Let's define the permutation of length n as an array p = [p1, p2, ..., pn] consisting of n distinct integers from range from 1 to n. We say that this permutation maps value 1 into the value p1, value 2 into the value p2 and so on.
Kyota Ootori has just learned about cyclic representation of a permutation. A cycle is a sequence of numbers such that each element of this sequence is being mapped into the next element of this sequence (and the last element of the cycle is being mapped into the first element of the cycle). The cyclic representation is a representation of p as a collection of cycles forming p. For example, permutation p = [4, 1, 6, 2, 5, 3] has a cyclic representation that looks like (142)(36)(5) because 1 is replaced by 4, 4 is replaced by 2, 2 is replaced by 1, 3 and 6 are swapped, and 5 remains in place.
Permutation may have several cyclic representations, so Kyoya defines the standard cyclic representation of a permutation as follows. First, reorder the elements within each cycle so the largest element is first. Then, reorder all of the cycles so they are sorted by their first element. For our example above, the standard cyclic representation of [4, 1, 6, 2, 5, 3] is (421)(5)(63).
Now, Kyoya notices that if we drop the parenthesis in the standard cyclic representation, we get another permutation! For instance, [4, 1, 6, 2, 5, 3] will become [4, 2, 1, 5, 6, 3].
Kyoya notices that some permutations don't change after applying operation described above at all. He wrote all permutations of length n that do not change in a list in lexicographic order. Unfortunately, his friend Tamaki Suoh lost this list. Kyoya wishes to reproduce the list and he needs your help. Given the integers n and k, print the permutation that was k-th on Kyoya's list.
Input
The first line will contain two integers n, k (1 ≤ n ≤ 50, 1 ≤ k ≤ min{1018, l} where l is the length of the Kyoya's list).
Output
Print n space-separated integers, representing the permutation that is the answer for the question.
Examples
Input
4 3
Output
1 3 2 4
Input
10 1
Output
1 2 3 4 5 6 7 8 9 10
Note
The standard cycle representation is (1)(32)(4), which after removing parenthesis gives us the original permutation. The first permutation on the list would be [1, 2, 3, 4], while the second permutation would be [1, 2, 4, 3].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int inf = 1000000000000000001;
long long int fib[51];
int N;
int change[50];
int res[51];
long long int K, M;
long long int mmn(long long int a, long long int b) { return a < b ? a : b; }
void calc_fib() {
fib[0] = 1;
fib[1] = 2;
fib[2] = 3;
for (int i = 3; i <= 50; i++) fib[i] = mmn(inf, fib[i - 1] + fib[i - 2]);
}
long long int get_fib(int i) {
if (i < 0) return 1;
return fib[i];
}
long long int swap(int i, int j) {
int tp = res[i];
res[i] = res[j];
res[j] = tp;
}
int main() {
calc_fib();
scanf("%d %lld ", &N, &K);
for (int i = N; i >= 1; i--) {
res[i] = N - i + 1;
}
int pos = N - 1;
long long int M = K;
while (M > 0) {
int pos = 0;
while (get_fib(pos) < M) pos++;
change[pos] = 1;
M -= get_fib(pos - 1);
}
for (int i = N - 1; i >= 1; i--) {
if (change[i] == 1) {
swap(i + 1, i);
}
}
for (int i = N; i >= 2; i--) {
printf("%d ", res[i]);
}
printf("%d\n", res[1]);
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
problem
Santa Claus came from the sky to JOI town this year as well. Since every house in JOI has children, this Santa Claus must give out presents to every house in JOI. However, this year the reindeer I am carrying is a little deaf and I can only get off the top of the building, so it seems that I have to devise a little route to distribute gifts to all the houses.
JOI Town is divided into north, south, east and west, and each section is a house, a church, or a vacant lot. There is only one church in JOI town. According to the following rules, Santa Claus and reindeer depart from the church, give out one gift to every house, and then return to the church.
* This year's reindeer is a little deaf, so it can only fly straight in either the north, south, east, or west, and cannot change direction in the air.
* You can pass freely over the house where you haven't handed out the presents yet. You can get off at a house that hasn't given out presents yet. Whenever I get home, I give out presents and then take off in either direction of north, south, east or west.
* At the house in JOI town, I spend Christmas night without the fireplace until Santa Claus arrives, but after Santa Claus takes off, I turn on the fireplace. When you turn on the fireplace, smoke comes out of the chimney, so you can't pass over the house where you've finished giving out presents.
* You can pass freely over the church. However, since worship is held in the church, you cannot go down to the church until you have distributed all the presents.
* You can pass freely over the vacant lot, but you cannot get off at the vacant lot.
Create a program that asks how many directions Santa Claus and reindeer can give gifts to, given the structure of the town as input.
input
The input consists of multiple datasets. Each dataset is given in the following format.
Each dataset has n + 1 rows. On the first line, the integer m (1 ≤ m ≤ 10) and the integer n (1 ≤ n ≤ 10) are written separated by a space. In each line from the 2nd line to the n + 1th line, m of 0, 1, or 2 are written, separated by a blank, and each represents the state of each section. If we write the i-th section from the north and the j-th section from the west as (i, j) (1 ≤ i ≤ n, 1 ≤ j ≤ m), the j-th value on the i + 1 line is If the lot (i, j) is a vacant lot, it will be 0, if it is a house, it will be 1, and if it is a church, it will be 2. The number of churches is 1, and the number of houses is 1 or more and 23 or less. However, in the input data for scoring, the number of directions to be distributed does not exceed 2000000.
When both m and n are 0, it indicates the end of input. The number of data sets does not exceed 5.
Input / output example
Input example
3 2
1 0 1
1 0 2
3 3
1 1 1
1 0 1
1 1 2
0 0
Output example
2
6
<image>
Figure: All 6 directions to the second input example (numbers indicate the order of distribution)
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
output
For each dataset, an integer indicating how many directions to distribute gifts is output on one line.
Example
Input
3 2
1 0 1
1 0 2
3 3
1 1 1
1 0 1
1 1 2
0 0
Output
2
6
### Response
```cpp
#include <bits/stdc++.h>
#define rep(i,n)for(int i=0;i<n;i++)
using namespace std;
int H[10][10];
int m, n;
int I, J;
int solve(int i, int j, int k) {
if (!k) {
if (i == I || j == J)return 1;
else return 0;
}
int res = 0;
for (int t = 1; i + t < n; t++) {
if (H[i + t][j] == 1) {
H[i + t][j] = 0;
res += solve(i + t, j, k - 1);
H[i + t][j] = 1;
break;
}
}
for (int t = 1; i - t >= 0; t++) {
if (H[i - t][j] == 1) {
H[i - t][j] = 0;
res += solve(i - t, j, k - 1);
H[i - t][j] = 1;
break;
}
}
for (int t = 1; j + t < m; j++) {
if (H[i][j + t] == 1) {
H[i][j + t] = 0;
res += solve(i, j + t, k - 1);
H[i][j + t] = 1;
break;
}
}
for (int t = 1; j - t >= 0; t++) {
if (H[i][j - t] == 1) {
H[i][j - t] = 0;
res += solve(i, j - t, k - 1);
H[i][j - t] = 1;
break;
}
}
return res;
}
int main() {
while (scanf("%d%d", &m, &n), m) {
int cnt = 0;
rep(i, n) {
rep(j, m) {
scanf("%d", &H[i][j]);
if (H[i][j] == 1)cnt++;
if (H[i][j] == 2) { I = i; J = j; }
}
}
printf("%d\n", solve(I, J, cnt));
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Your program fails again. This time it gets "Wrong answer on test 233"
.
This is the easier version of the problem. In this version 1 ≤ n ≤ 2000. You can hack this problem only if you solve and lock both problems.
The problem is about a test containing n one-choice-questions. Each of the questions contains k options, and only one of them is correct. The answer to the i-th question is h_{i}, and if your answer of the question i is h_{i}, you earn 1 point, otherwise, you earn 0 points for this question. The values h_1, h_2, ..., h_n are known to you in this problem.
However, you have a mistake in your program. It moves the answer clockwise! Consider all the n answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically.
Formally, the mistake moves the answer for the question i to the question i mod n + 1. So it moves the answer for the question 1 to question 2, the answer for the question 2 to the question 3, ..., the answer for the question n to the question 1.
We call all the n answers together an answer suit. There are k^n possible answer suits in total.
You're wondering, how many answer suits satisfy the following condition: after moving clockwise by 1, the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo 998 244 353.
For example, if n = 5, and your answer suit is a=[1,2,3,4,5], it will submitted as a'=[5,1,2,3,4] because of a mistake. If the correct answer suit is h=[5,2,2,3,4], the answer suit a earns 1 point and the answer suite a' earns 4 points. Since 4 > 1, the answer suit a=[1,2,3,4,5] should be counted.
Input
The first line contains two integers n, k (1 ≤ n ≤ 2000, 1 ≤ k ≤ 10^9) — the number of questions and the number of possible answers to each question.
The following line contains n integers h_1, h_2, ..., h_n, (1 ≤ h_{i} ≤ k) — answers to the questions.
Output
Output one integer: the number of answers suits satisfying the given condition, modulo 998 244 353.
Examples
Input
3 3
1 3 1
Output
9
Input
5 5
1 1 4 2 2
Output
1000
Note
For the first example, valid answer suits are [2,1,1], [2,1,2], [2,1,3], [3,1,1], [3,1,2], [3,1,3], [3,2,1], [3,2,2], [3,2,3].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long M = 998244353;
const int N = 2001;
int n;
long long k;
long long h[N];
int diff = 0;
long long dp[N][2 * N];
long long res = 0;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> k;
for (int i = 0; i < n; i++) cin >> h[i];
for (int i = 0; i < n; i++)
if (h[i] != h[(i - 1 + n) % n]) diff++;
dp[0][diff] = 1;
for (int i = 1; i <= diff; i++) {
for (int j = 0; j <= 2 * diff; j++) {
dp[i][j] += dp[i - 1][j - 1] + dp[i - 1][j + 1] + dp[i - 1][j] * (k - 2);
dp[i][j] %= M;
}
}
for (int i = 1; i <= diff; i++) {
res += dp[diff][i + diff];
res %= M;
}
for (int i = diff + 1; i <= n; i++) {
res *= k;
res %= M;
}
cout << res << endl;
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Find the number of the possible tuples of sequences (A_0,A_1,...,A_N) that satisfy all of the following conditions, modulo M:
* For every i (0\leq i\leq N), A_i is a sequence of length i consisting of integers between 1 and K (inclusive);
* For every i (1\leq i\leq N), A_{i-1} is a subsequence of A_i, that is, there exists 1\leq x_i\leq i such that the removal of the x_i-th element of A_i would result in a sequence equal to A_{i-1};
* For every i (1\leq i\leq N), A_i is lexicographically larger than A_{i-1}.
Constraints
* 1 \leq N,K \leq 300
* 2 \leq M \leq 10^9
* N, K and M are integers.
Input
Input is given from Standard Input in the following format:
N K M
Output
Print the number of the possible tuples of sequences (A_0,A_1,...,A_N), modulo M.
Examples
Input
2 2 100
Output
5
Input
4 3 999999999
Output
358
Input
150 150 998244353
Output
186248260
### Response
```cpp
/*
读题不规范,爆零两行泪。
数据不清空,爆零两行泪。
多测不读完,爆零两行泪。
边界不特判,爆零两行泪。
贪心不证明,爆零两行泪。
D P 顺序错,爆零两行泪。
大小少等号,爆零两行泪。
变量不统一,爆零两行泪。
越界不判断,爆零两行泪。
调试不注释,爆零两行泪。
溢出不 l l,爆零两行泪。
*/
#include<bits/stdc++.h>
using namespace std;
const int N=300,M=300;
int n,m,mod;
int comb[N+1][N+1];
int dp[N+1][M+2];
int Sum[N+1][M+2];
int main(){
cin>>n>>m>>mod;
comb[0][0]=1;
for(int i=1;i<=n;i++)for(int j=0;j<=i;j++)comb[i][j]=((j?comb[i-1][j-1]:0)+(j<i?comb[i-1][j]:0))%mod;
for(int i=1;i<=m+1;i++)Sum[0][i]=(Sum[0][i-1]+(dp[0][i]=1))%mod;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
for(int k=1;k<=i;k++)(dp[i][j]+=1ll*dp[i-k][j]*comb[i-1][k-1]%mod*(Sum[k-1][m+1]-Sum[k-1][j])%mod)%=mod;
Sum[i][j]=(Sum[i][j-1]+dp[i][j])%mod;
// printf("dp[%d][%d]=%d\n",i,j,dp[i][j]);
}
Sum[i][m+1]=Sum[i][m];
}
cout<<(dp[n][1]+mod)%mod;
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.
For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 100 000).
The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part.
Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query.
Output
Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7.
Examples
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
Note
In the first example:
* For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2.
* For query 2: Both 3, 4 and 4, 3 ordering give the same answer.
In the second example, any order of eating parts leads to the same answer.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int M1 = 1000000007;
const int M2 = 998244353;
const int N = 100005;
int ones[N];
template <typename T>
T modpow(T base, T exp, T modulus) {
base %= modulus;
T result = 1;
while (exp > 0) {
if (exp & 1) result = (result * base) % modulus;
base = (base * base) % modulus;
exp >>= 1;
}
return result;
}
long long int GPmodM(long long int a, long long int r, long long int n) {
return (a * (modpow(r, n, M1) - 1) * modpow(r - 1, M1 - 2, M1)) % M1;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
;
int n, m, q, a, b, temp;
cin >> n >> q;
string s;
cin >> s;
for (int i = 0; i < n; i++) {
if (s[i] == '1') {
ones[i + 1] = ones[i] + 1;
} else {
ones[i + 1] = ones[i];
}
}
for (int i = 0; i < q; i++) {
cin >> a >> b;
int length = b - a + 1;
int one = ones[b] - ones[a - 1];
int zero = length - one;
if (zero == length) {
cout << 0 << "\n";
} else {
long long int ans = modpow(2 * 1LL, 1LL * one, M1) - 1;
ans += GPmodM(ans, 1LL * 2, zero);
cout << ans % M1 << "\n";
}
}
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Gildong is playing a video game called Block Adventure. In Block Adventure, there are n columns of blocks in a row, and the columns are numbered from 1 to n. All blocks have equal heights. The height of the i-th column is represented as h_i, which is the number of blocks stacked in the i-th column.
Gildong plays the game as a character that can stand only on the top of the columns. At the beginning, the character is standing on the top of the 1-st column. The goal of the game is to move the character to the top of the n-th column.
The character also has a bag that can hold infinitely many blocks. When the character is on the top of the i-th column, Gildong can take one of the following three actions as many times as he wants:
* if there is at least one block on the column, remove one block from the top of the i-th column and put it in the bag;
* if there is at least one block in the bag, take one block out of the bag and place it on the top of the i-th column;
* if i < n and |h_i - h_{i+1}| ≤ k, move the character to the top of the i+1-st column. k is a non-negative integer given at the beginning of the game. Note that it is only possible to move to the next column.
In actions of the first two types the character remains in the i-th column, and the value h_i changes.
The character initially has m blocks in the bag. Gildong wants to know if it is possible to win the game. Help Gildong find the answer to his question.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000). Description of the test cases follows.
The first line of each test case contains three integers n, m, and k (1 ≤ n ≤ 100, 0 ≤ m ≤ 10^6, 0 ≤ k ≤ 10^6) — the number of columns in the game, the number of blocks in the character's bag at the beginning, and the non-negative integer k described in the statement.
The second line of each test case contains n integers. The i-th integer is h_i (0 ≤ h_i ≤ 10^6), the initial height of the i-th column.
Output
For each test case, print "YES" if it is possible to win the game. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
5
3 0 1
4 3 5
3 1 2
1 4 7
4 10 0
10 20 10 20
2 5 5
0 11
1 9 9
99
Output
YES
NO
YES
NO
YES
Note
In the first case, Gildong can take one block from the 1-st column, move to the 2-nd column, put the block on the 2-nd column, then move to the 3-rd column.
In the second case, Gildong has to put the block in his bag on the 1-st column to get to the 2-nd column. But it is impossible to get to the 3-rd column because |h_2 - h_3| = 3 > k and there is no way to decrease the gap.
In the fifth case, the character is already on the n-th column from the start so the game is won instantly.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n, m, k;
cin >> n >> m >> k;
vector<int> h(n);
for (int& i : h) cin >> i;
for (int i = 0; i < n - 1; ++i) {
m += h[i] - max(0, h[i + 1] - k);
if (m < 0) {
cout << "NO" << '\n';
return;
}
}
cout << "YES" << '\n';
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) solve();
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
You're given a string of lower-case Latin letters. Your task is to find the length of its longest substring that can be met in the string at least twice. These occurrences can overlap (see sample test 2).
Input
The first input line contains the string. It's guaranteed, that the string is non-empty, consists of lower-case Latin letters, and its length doesn't exceed 100.
Output
Output one number — length of the longest substring that can be met in the string at least twice.
Examples
Input
abcd
Output
0
Input
ababa
Output
3
Input
zzz
Output
2
### Response
```cpp
#include <bits/stdc++.h>
int main() {
char str[101];
char buf[101];
gets(str);
int len = strlen(str);
int i, j, flag = 0;
for (i = len - 1; i > 0; --i) {
j = 0;
while (i <= len - j - 1) {
memset(buf, 0, 101);
strncpy(buf, str + j, i);
if (strstr(str + j + 1, buf) != NULL) {
flag = 1;
break;
}
j++;
}
if (flag) break;
}
printf("%d", i);
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
You are given an array with n integers ai and m queries. Each query is described by two integers (lj, rj).
Let's define the function <image>. The function is defined for only u ≤ v.
For each query print the maximal value of the function f(ax, ay) over all lj ≤ x, y ≤ rj, ax ≤ ay.
Input
The first line contains two integers n, m (1 ≤ n ≤ 5·104, 1 ≤ m ≤ 5·103) — the size of the array and the number of the queries.
The second line contains n integers ai (1 ≤ ai ≤ 106) — the elements of the array a.
Each of the next m lines contains two integers lj, rj (1 ≤ lj ≤ rj ≤ n) – the parameters of the j-th query.
Output
For each query print the value aj on a separate line — the maximal value of the function f(ax, ay) over all lj ≤ x, y ≤ rj, ax ≤ ay.
Examples
Input
6 3
1 2 3 4 5 6
1 6
2 5
3 4
Output
7
7
7
Input
1 1
1
1 1
Output
1
Input
6 20
10 21312 2314 214 1 322
1 1
1 2
1 3
1 4
1 5
1 6
2 2
2 3
2 4
2 5
2 6
3 4
3 5
3 6
4 4
4 5
4 6
5 5
5 6
6 6
Output
10
21313
21313
21313
21313
21313
21312
21313
21313
21313
21313
2314
2315
2315
214
215
323
1
323
322
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int quick_pow(int a, int b, int MOD) {
a %= MOD;
int res = 1;
while (b) {
if (b & 1) res = (res * a) % MOD;
b /= 2;
a = (a * a) % MOD;
}
return res;
}
const int maxn = 50000 + 10;
int a[maxn], b[maxn], res[maxn], x[maxn], y[maxn], sum[1000005], f[1000005];
int main() {
int i, j, n, m;
sum[0] = 0;
for (i = 1; i <= 1000000; i++) sum[i] = (sum[i - 1] ^ i);
while (scanf("%d%d", &n, &m) != EOF) {
for (i = 1; i <= n; i++) {
scanf("%d", &a[i]);
f[i] = sum[a[i]];
}
for (i = 1; i <= m; i++) {
scanf("%d%d", &x[i], &y[i]);
res[i] = -1;
}
for (i = 1; i <= n; i++) {
b[i - 1] = 0;
for (j = i; j <= n; j++) {
b[j] = max(b[j - 1], f[i] ^ f[j] ^ (a[i] < a[j] ? a[i] : a[j]));
}
for (j = 1; j <= m; j++) {
if (x[j] <= i && y[j] >= i) {
res[j] = max(res[j], b[y[j]]);
}
}
}
for (i = 1; i <= m; i++) printf("%d\n", res[i]);
}
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Kevin Sun has just finished competing in Codeforces Round #334! The round was 120 minutes long and featured five problems with maximum point values of 500, 1000, 1500, 2000, and 2500, respectively. Despite the challenging tasks, Kevin was uncowed and bulldozed through all of them, distinguishing himself from the herd as the best cowmputer scientist in all of Bovinia. Kevin knows his submission time for each problem, the number of wrong submissions that he made on each problem, and his total numbers of successful and unsuccessful hacks. Because Codeforces scoring is complicated, Kevin wants you to write a program to compute his final score.
Codeforces scores are computed as follows: If the maximum point value of a problem is x, and Kevin submitted correctly at minute m but made w wrong submissions, then his score on that problem is <image>. His total score is equal to the sum of his scores for each problem. In addition, Kevin's total score gets increased by 100 points for each successful hack, but gets decreased by 50 points for each unsuccessful hack.
All arithmetic operations are performed with absolute precision and no rounding. It is guaranteed that Kevin's final score is an integer.
Input
The first line of the input contains five space-separated integers m1, m2, m3, m4, m5, where mi (0 ≤ mi ≤ 119) is the time of Kevin's last submission for problem i. His last submission is always correct and gets accepted.
The second line contains five space-separated integers w1, w2, w3, w4, w5, where wi (0 ≤ wi ≤ 10) is Kevin's number of wrong submissions on problem i.
The last line contains two space-separated integers hs and hu (0 ≤ hs, hu ≤ 20), denoting the Kevin's numbers of successful and unsuccessful hacks, respectively.
Output
Print a single integer, the value of Kevin's final score.
Examples
Input
20 40 60 80 100
0 1 2 3 4
1 0
Output
4900
Input
119 119 119 119 119
0 0 0 0 0
10 0
Output
4930
Note
In the second sample, Kevin takes 119 minutes on all of the problems. Therefore, he gets <image> of the points on each problem. So his score from solving problems is <image>. Adding in 10·100 = 1000 points from hacks, his total score becomes 3930 + 1000 = 4930.
### Response
```cpp
#include <bits/stdc++.h>
namespace chtholly {
inline int read() {
int x = 0, f = 1;
char c = getchar();
for (; !isdigit(c); c = getchar()) f ^= c == '-';
for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + (c ^ '0');
return f ? x : -x;
}
template <typename mitsuha>
inline bool read(mitsuha &x) {
x = 0;
int f = 1;
char c = getchar();
for (; !isdigit(c) && ~c; c = getchar()) f ^= c == '-';
if (!~c) return 0;
for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + (c ^ '0');
return x = f ? x : -x, 1;
}
template <typename mitsuha>
inline int write(mitsuha x) {
if (!x) return 0 & putchar(48);
if (x < 0) x = -x, putchar('-');
int bit[20], i, p = 0;
for (; x; x /= 10) bit[++p] = x % 10;
for (i = p; i; --i) putchar(bit[i] + 48);
return 0;
}
inline char fuhao() {
char c = getchar();
for (; isspace(c); c = getchar())
;
return c;
}
} // namespace chtholly
using namespace chtholly;
using namespace std;
int suan(int x, int m, int w) {
return max(x * 3 / 10, x - x * m / 250 - 50 * w);
}
int main() {
int m1, m2, m3, m4, m5;
cin >> m1 >> m2 >> m3 >> m4 >> m5;
int w1, w2, w3, w4, w5, ans = 0;
cin >> w1 >> w2 >> w3 >> w4 >> w5;
ans += suan(500, m1, w1) + suan(1000, m2, w2) + suan(1500, m3, w3) +
suan(2000, m4, w4) + suan(2500, m5, w5);
int hs, hu;
cin >> hs >> hu;
cout << ans + hs * 100 - hu * 50;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Tavas lives in Kansas. Kansas has n cities numbered from 1 to n connected with m bidirectional roads. We can travel from any city to any other city via these roads. Kansas is as strange as Tavas. So there may be a road between a city and itself or more than one road between two cities.
Tavas invented a game and called it "Dashti". He wants to play Dashti with his girlfriends, Nafas.
In this game, they assign an arbitrary integer value to each city of Kansas. The value of i-th city equals to pi.
During the game, Tavas is in city s and Nafas is in city t. They play in turn and Tavas goes first. A player in his/her turn, must choose a non-negative integer x and his/her score increases by the sum of values of all cities with (shortest) distance no more than x from his/her city. Each city may be used once, or in the other words, after first time a player gets score from a city, city score becomes zero.
There is an additional rule: the player must choose x such that he/she gets the point of at least one city that was not used before. Note that city may initially have value 0, such city isn't considered as been used at the beginning of the game, i. e. each player may use it to fullfill this rule.
The game ends when nobody can make a move.
A player's score is the sum of the points he/she earned during the game. The winner is the player with greater score, or there is a draw if players score the same value. Both players start game with zero points.
<image>
If Tavas wins, he'll break his girlfriend's heart, and if Nafas wins, Tavas will cry. But if their scores are equal, they'll be happy and Tavas will give Nafas flowers.
They're not too emotional after all, so they'll play optimally. Your task is to tell Tavas what's going to happen after the game ends.
Input
The first line of input contains two integers n and m (2 ≤ n ≤ 2000, n - 1 ≤ m ≤ 105).
The second line of input contains two integers s and t (1 ≤ s, t ≤ n, s ≠ t).
The next line contains n integers p1, p2, ..., pn separated by spaces (|pi| ≤ 109).
The next m lines contain the roads. Each line contains three integers v, u, w and it means that there's an road with length w between cities v and u (1 ≤ u, v ≤ n and 0 ≤ w ≤ 109). The road may lead from the city to itself, there may be several roads between each pair of cities.
Output
If Tavas wins, print "Break a heart". If Nafas wins print "Cry" and if nobody wins (i. e. the game ended with draw) print "Flowers".
Examples
Input
4 4
1 2
3 2 5 -11
1 4 2
3 4 2
3 1 5
3 2 1
Output
Cry
Input
5 4
1 2
2 2 -5 -4 6
1 2 4
2 3 5
2 4 2
4 5 2
Output
Break a heart
Input
2 1
1 2
-5 -5
1 2 10
Output
Flowers
### Response
```cpp
#include <bits/stdc++.h>
int h[2010], nxt[2 * 101000], to[2 * 101000], cost[2 * 101000], K = 0;
long long v[2010][2010][2], f[2010][2010][2];
int w[2010];
long long d[2][2010];
bool used[2010];
long long b[2][2010];
int n, m, s, t;
void ins(int u, int v, int c) {
nxt[++K] = h[u];
h[u] = K;
to[K] = v;
cost[K] = c;
}
void dij(long long *d, int S) {
memset(used, 0, sizeof(used));
d[S] = 0;
for (int T = 1; T <= n; T++) {
int u = 0;
for (int i = 1; i <= n; i++)
if (!used[i] && (u == 0 || d[i] < d[u])) u = i;
used[u] = 1;
for (int i = h[u]; i; i = nxt[i])
d[to[i]] = std::min(d[to[i]], d[u] + cost[i]);
}
}
int main() {
memset(d, 0x3f, sizeof(d));
memset(v, 0x3f, sizeof(v));
long long inf = v[0][0][0];
memset(f, 0, sizeof(f));
scanf("%d%d%d%d", &n, &m, &s, &t);
for (int i = 1; i <= n; i++) scanf("%d", &w[i]);
for (int i = 1; i <= m; i++) {
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
ins(u, v, w);
ins(v, u, w);
}
dij(d[0], s);
dij(d[1], t);
memcpy(b, d, sizeof(d));
int N[2];
for (int i = 0; i < 2; i++) {
std::sort(b[i] + 1, b[i] + n + 1);
N[i] = std::unique(b[i] + 1, b[i] + n + 1) - b[i] - 1;
for (int j = 1; j <= n; j++)
d[i][j] = std::lower_bound(b[i] + 1, b[i] + N[i] + 1, d[i][j]) - b[i];
}
for (int j = 0; j <= N[1]; j++)
for (int i = 1; i <= n; i++) {
if (d[1][i] > j) {
if (v[d[0][i]][j][0] == inf) v[d[0][i]][j][0] = 0;
v[d[0][i]][j][0] += w[i];
}
}
for (int j = 0; j <= N[0]; j++)
for (int i = 1; i <= n; i++) {
if (d[0][i] > j) {
if (v[j][d[1][i]][1] == inf) v[j][d[1][i]][1] = 0;
v[j][d[1][i]][1] += w[i];
}
}
for (int i = N[0]; i >= 0; i--)
for (int j = N[1]; j >= 0; j--) {
if (v[i + 1][j][0] == inf)
f[i][j][0] = f[i + 1][j][0];
else
f[i][j][0] = std::max(f[i + 1][j][0], f[i + 1][j][1]) + v[i + 1][j][0];
if (v[i][j + 1][1] == inf)
f[i][j][1] = f[i][j + 1][1];
else
f[i][j][1] = std::min(f[i][j + 1][1], f[i][j + 1][0]) - v[i][j + 1][1];
}
if (f[0][0][0] > 0) puts("Break a heart");
if (f[0][0][0] == 0) puts("Flowers");
if (f[0][0][0] < 0) puts("Cry");
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
Input
The input contains three positive integer numbers in the first line: n, m and a (1 ≤ n, m, a ≤ 109).
Output
Write the needed number of flagstones.
Examples
Input
6 6 4
Output
4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n, m, a;
cin >> n >> m >> a;
long long x = ceil((double)n / a), y = ceil((double)m / a);
cout << x * y << endl;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.
New parliament assembly hall is a rectangle consisting of a × b chairs — a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hall
We know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.
Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.
Input
The first line of the input contains three integers n, a and b (1 ≤ n ≤ 10 000, 1 ≤ a, b ≤ 100) — the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.
Output
If there is no way to assigns seats to parliamentarians in a proper way print -1.
Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.
Examples
Input
3 2 2
Output
0 3
1 2
Input
8 4 3
Output
7 8 3
0 1 4
6 0 5
0 2 0
Input
10 2 2
Output
-1
Note
In the first sample there are many other possible solutions. For example,
3 2
0 1
and
2 1
3 0
The following assignment
3 2
1 0
is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MaxN = 1000;
int w[1005][1005], n, m, ans, tot, a, b;
void pdo() {
for (int i = 1; i <= a; i++) {
for (int j = 1; j <= b; j++) {
tot++;
if (tot > n) break;
w[i][j] = tot;
}
if (tot > n) break;
}
for (int i = 1; i <= a; i++) {
if (i % 2 == 0) {
for (int j = 1; j <= b; j++) printf("%d ", w[i][b + 1 - j]);
} else {
for (int j = 1; j <= b; j++) {
printf("%d ", w[i][j]);
}
}
printf("\n");
}
}
int main() {
scanf("%d %d %d", &n, &a, &b);
if (n <= a * b)
pdo();
else
printf("-1\n");
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Arseniy is already grown-up and independent. His mother decided to leave him alone for m days and left on a vacation. She have prepared a lot of food, left some money and washed all Arseniy's clothes.
Ten minutes before her leave she realized that it would be also useful to prepare instruction of which particular clothes to wear on each of the days she will be absent. Arseniy's family is a bit weird so all the clothes is enumerated. For example, each of Arseniy's n socks is assigned a unique integer from 1 to n. Thus, the only thing his mother had to do was to write down two integers li and ri for each of the days — the indices of socks to wear on the day i (obviously, li stands for the left foot and ri for the right). Each sock is painted in one of k colors.
When mother already left Arseniy noticed that according to instruction he would wear the socks of different colors on some days. Of course, that is a terrible mistake cause by a rush. Arseniy is a smart boy, and, by some magical coincidence, he posses k jars with the paint — one for each of k colors.
Arseniy wants to repaint some of the socks in such a way, that for each of m days he can follow the mother's instructions and wear the socks of the same color. As he is going to be very busy these days he will have no time to change the colors of any socks so he has to finalize the colors now.
The new computer game Bota-3 was just realised and Arseniy can't wait to play it. What is the minimum number of socks that need their color to be changed in order to make it possible to follow mother's instructions and wear the socks of the same color during each of m days.
Input
The first line of input contains three integers n, m and k (2 ≤ n ≤ 200 000, 0 ≤ m ≤ 200 000, 1 ≤ k ≤ 200 000) — the number of socks, the number of days and the number of available colors respectively.
The second line contain n integers c1, c2, ..., cn (1 ≤ ci ≤ k) — current colors of Arseniy's socks.
Each of the following m lines contains two integers li and ri (1 ≤ li, ri ≤ n, li ≠ ri) — indices of socks which Arseniy should wear during the i-th day.
Output
Print one integer — the minimum number of socks that should have their colors changed in order to be able to obey the instructions and not make people laugh from watching the socks of different colors.
Examples
Input
3 2 3
1 2 3
1 2
2 3
Output
2
Input
3 2 2
1 1 2
1 2
2 1
Output
0
Note
In the first sample, Arseniy can repaint the first and the third socks to the second color.
In the second sample, there is no need to change any colors.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 200005;
int n, m, k;
int c[N];
map<int, int> cnt;
vector<int> adj[N];
int mark[N];
void dfs(int u) {
mark[u] = 1;
cnt[c[u]]++;
for (auto v : adj[u])
if (!mark[v]) dfs(v);
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
scanf("%d %d %d", &n, &m, &k);
for (int i = 1; i <= n; i++) scanf("%d", &c[i]);
for (int i = 1; i <= m; i++) {
int l, r;
scanf("%d%d", &l, &r);
adj[l].push_back(r);
adj[r].push_back(l);
}
int ans = 0;
for (int i = 1; i <= n; i++) {
if (mark[i]) continue;
dfs(i);
int chd = 0, mx = 0;
for (auto j : cnt) chd += j.second, mx = max(mx, j.second);
ans += chd - mx;
cnt.clear();
}
printf("%d", ans);
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
Coloring of the vertices of a tree G is called a good coloring when, for every pair of two vertices u and v painted in the same color, picking u as the root and picking v as the root would result in isomorphic rooted trees.
Also, the colorfulness of G is defined as the minimum possible number of different colors used in a good coloring of G.
You are given a tree with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i. We will construct a new tree T by repeating the following operation on this tree some number of times:
* Add a new vertex to the tree by connecting it to one of the vertices in the current tree with an edge.
Find the minimum possible colorfulness of T. Additionally, print the minimum number of leaves (vertices with degree 1) in a tree T that achieves the minimum colorfulness.
Constraints
* 2 \leq N \leq 100
* 1 \leq a_i,b_i \leq N(1\leq i\leq N-1)
* The given graph 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 two integers with a space in between. First, print the minimum possible colorfulness of a tree T that can be constructed. Second, print the minimum number of leaves in a tree that achieves it.
It can be shown that, under the constraints of this problem, the values that should be printed fit into 64-bit signed integers.
Examples
Input
5
1 2
2 3
3 4
3 5
Output
2 4
Input
8
1 2
2 3
4 3
5 4
6 7
6 8
3 6
Output
3 4
Input
10
1 2
2 3
3 4
4 5
5 6
6 7
3 8
5 9
3 10
Output
4 6
Input
13
5 6
6 4
2 8
4 7
8 9
3 2
10 4
11 10
2 4
13 10
1 8
12 1
Output
4 12
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
#define llong long long
#define pii pair<int,llong>
#define fi first
#define se second
int n;
int ed[110][2];
struct data{
int to,nxt;
}mp[220];
int head[110],cnt;
void link(int x,int y)
{
mp[++cnt].to=y;
mp[cnt].nxt=head[x];
head[x]=cnt;
}
int md[110];
int dep[110];
queue<int>q;
pii solve(int x,int y)
{
pii res;res.fi=res.se=0;
memset(dep,0,sizeof(dep));
memset(md,0,sizeof(md));
q.push(x);dep[x]=1;
if(y)q.push(y),dep[y]=1;
int u,v,d;
while(!q.empty())
{
u=q.front();q.pop();
res.fi=max(res.fi,dep[u]);
d=0;
for(int i=head[u];i;i=mp[i].nxt)
if(!dep[mp[i].to])
{
v=mp[i].to;
dep[v]=dep[u]+1;
q.push(v);
d++;
}
md[dep[u]]=max(md[dep[u]],d);
}
res.se=y?2:1;
for(int i=1;md[i];++i) res.se*=md[i];
return res;
}
pii ans;
int main()
{
scanf("%d",&n);
int xx,yy;
for(int i=1;i<n;++i)
{
scanf("%d%d",&xx,&yy);
link(xx,yy);link(yy,xx);
ed[i][0]=xx;ed[i][1]=yy;
}
ans.fi=22832737;ans.se=23721837;
for(int i=1;i<=n;++i)
ans=min(ans,solve(i,0));
for(int i=1;i<n;++i)
ans=min(ans,solve(ed[i][0],ed[i][1]));
printf("%d %lld\n",ans.fi,ans.se);
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".
Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.
You can find the definitions for a subsequence and a correct bracket sequence in the notes.
Input
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
Output
Print the answer to each question on a single line. Print the answers in the order they go in the input.
Examples
Input
())(())(())(
7
1 1
2 3
1 2
1 12
8 12
5 11
2 10
Output
0
0
2
10
4
6
6
Note
A subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 < k2 < ... < k|x| ≤ |s|).
A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.
For the third query required sequence will be «()».
For the fourth query required sequence will be «()(())(())».
### Response
```cpp
#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:16777216")
using namespace std;
inline int input() {
int ret = 0;
bool isN = 0;
char c = getchar();
while (c < '0' || c > '9') {
c = getchar();
}
while (c >= '0' && c <= '9') {
ret = ret * 10 + c - '0';
c = getchar();
}
return ret;
}
inline void output(int x) {
if (x < 0) {
putchar('-');
x = -x;
}
int len = 0, data[11];
while (x) {
data[len++] = x % 10;
x /= 10;
}
if (!len) data[len++] = 0;
while (len--) putchar(data[len] + 48);
putchar('\n');
}
const int N = (int)(1e6) + 5;
int n, open[2 * N], good[N];
char s[N];
int Query(int l, int r) {
int res = N;
for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
if ((l & 1) == 1) res = min(res, open[l++]);
if ((r & 1) == 1) res = min(res, open[--r]);
}
return res;
}
int main() {
scanf("%s", s);
n = strlen(s) + 1;
int op = 0, go = 0;
for (int i = 1; i < n; i++) {
if (s[i - 1] == '(') {
op++;
} else {
if (op > 0) {
op--;
go++;
}
}
open[i + n] = op;
good[i] = go;
}
for (int i = n - 1; i > 0; --i) open[i] = min(open[i << 1], open[i << 1 | 1]);
int m = input();
for (int i = 0; i < m; i++) {
int l = input();
int r = input();
output(2 * (good[r] - good[l - 1] -
max(0, (open[n + l - 1] - Query(l, r + 1)))));
}
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.
Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").
Galya has already made k shots, all of them were misses.
Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.
It is guaranteed that there is at least one valid ships placement.
Input
The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made.
The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
Output
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.
In the second line print the cells Galya should shoot at.
Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left.
If there are multiple answers, you can print any of them.
Examples
Input
5 1 2 1
00100
Output
2
4 2
Input
13 3 2 3
1000000010001
Output
2
7 11
Note
There is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > r;
vector<int> p, ans;
char s[200005];
int main() {
int n, a, b, k;
scanf("%d %d %d %d %s", &n, &a, &b, &k, s);
int pre = 0;
for (int(i) = (0); (i) <= (n - 1); (i)++)
if (s[i] == '1') r.push_back(pair<int, int>(pre, i - 1)), pre = i + 1;
if (pre != n) r.push_back(pair<int, int>(pre, n - 1));
for (int(i) = (0); (i) <= (r.size() - 1); (i)++)
for (int j = r[i].first + b - 1; j <= r[i].second; j += b) p.push_back(j);
for (int(i) = (0); (i) <= (p.size() - a); (i)++) ans.push_back(p[i]);
printf("%d\n", (int)ans.size());
for (auto o : ans) printf("%d ", o + 1);
putchar(10);
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i
After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.
Help him to restore initial integers!
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree.
The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.
It is guaranteed that the values of p_i describe a rooted tree with n vertices.
Output
If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.
If there are no solutions, print "NO".
Examples
Input
3
2 0
0 2
2 0
Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long mx = 105;
const long long maxn = 1e5 + 1;
const long long mod = 1000000007;
vector<long long> ans;
vector<vector<int>> adj;
vector<long long> c;
bool pos;
vector<long long> dfs(long long v, long long p) {
long long i, j, k;
vector<long long> te;
for (i = 0; i < (int)adj[v].size(); i++) {
if (adj[v][i] != p) {
vector<long long> te1 = dfs(adj[v][i], v);
te.insert(te.begin(), te1.begin(), te1.end());
}
}
if (c[v] > (int)te.size()) {
cout << "NO\n";
exit(0);
}
te.insert(te.begin() + c[v], v);
return te;
}
void solve() {
long long n, i, j, k, p;
cin >> n;
pos = true;
adj.clear();
adj.resize(n + 1);
c.clear();
c.resize(n + 1);
long long r;
for (i = 1; i <= n; i++) {
cin >> p >> c[i];
if (p != 0) {
adj[i].push_back(p);
adj[p].push_back(i);
} else {
r = i;
}
}
long long res[n + 1];
ans = dfs(r, -1);
if (pos) {
for (i = 0; i < n; i++) {
res[ans[i]] = i + 1;
}
cout << "YES\n";
for (i = 1; i <= n; i++) cout << res[i] << " ";
cout << "\n";
} else {
cout << "NO\n";
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
long long t = 1;
long long n, i, j, k;
while (t--) {
solve();
}
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Santa has n candies and he wants to gift them to k kids. He wants to divide as many candies as possible between all k kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all.
Suppose the kid who recieves the minimum number of candies has a candies and the kid who recieves the maximum number of candies has b candies. Then Santa will be satisfied, if the both conditions are met at the same time:
* b - a ≤ 1 (it means b = a or b = a + 1);
* the number of kids who has a+1 candies (note that a+1 not necessarily equals b) does not exceed ⌊k/2⌋ (less than or equal to ⌊k/2⌋).
⌊k/2⌋ is k divided by 2 and rounded down to the nearest integer. For example, if k=5 then ⌊k/2⌋=⌊5/2⌋=2.
Your task is to find the maximum number of candies Santa can give to kids so that he will be satisfied.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases.
The next t lines describe test cases. The i-th test case contains two integers n and k (1 ≤ n, k ≤ 10^9) — the number of candies and the number of kids.
Output
For each test case print the answer on it — the maximum number of candies Santa can give to kids so that he will be satisfied.
Example
Input
5
5 2
19 4
12 7
6 2
100000 50010
Output
5
18
10
6
75015
Note
In the first test case, Santa can give 3 and 2 candies to kids. There a=2, b=3,a+1=3.
In the second test case, Santa can give 5, 5, 4 and 4 candies. There a=4,b=5,a+1=5. The answer cannot be greater because then the number of kids with 5 candies will be 3.
In the third test case, Santa can distribute candies in the following way: [1, 2, 2, 1, 1, 2, 1]. There a=1,b=2,a+1=2. He cannot distribute two remaining candies in a way to be satisfied.
In the fourth test case, Santa can distribute candies in the following way: [3, 3]. There a=3, b=3, a+1=4. Santa distributed all 6 candies.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long t;
cin >> t;
while (t--) {
long long n, k;
cin >> n >> k;
long long temp = k;
long long ans = (n / k) * k;
n -= (n / k) * k;
ans += min(k / 2, n);
cout << ans << '\n';
}
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem that costs b points. Besides, Misha submitted the problem c minutes after the contest started and Vasya submitted the problem d minutes after the contest started. As you know, on Codeforces the cost of a problem reduces as a round continues. That is, if you submit a problem that costs p points t minutes after the contest started, you get <image> points.
Misha and Vasya are having an argument trying to find out who got more points. Help them to find out the truth.
Input
The first line contains four integers a, b, c, d (250 ≤ a, b ≤ 3500, 0 ≤ c, d ≤ 180).
It is guaranteed that numbers a and b are divisible by 250 (just like on any real Codeforces round).
Output
Output on a single line:
"Misha" (without the quotes), if Misha got more points than Vasya.
"Vasya" (without the quotes), if Vasya got more points than Misha.
"Tie" (without the quotes), if both of them got the same number of points.
Examples
Input
500 1000 20 30
Output
Vasya
Input
1000 1000 1 1
Output
Tie
Input
1500 1000 176 177
Output
Misha
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
double a, b, c, d;
while (cin >> a >> b >> c >> d) {
double a1 = max((3 * a) / 10, a - (a / 250) * c);
double b1 = max((3 * b) / 10, b - (b / 250) * d);
if (a1 > b1) {
cout << "Misha" << endl;
} else if (a1 < b1) {
cout << "Vasya" << endl;
} else {
cout << "Tie" << endl;
}
}
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
All modern mobile applications are divided into free and paid. Even a single application developers often release two versions: a paid version without ads and a free version with ads.
<image>
Suppose that a paid version of the app costs p (p is an integer) rubles, and the free version of the application contains c ad banners. Each user can be described by two integers: ai — the number of rubles this user is willing to pay for the paid version of the application, and bi — the number of banners he is willing to tolerate in the free version.
The behavior of each member shall be considered strictly deterministic:
* if for user i, value bi is at least c, then he uses the free version,
* otherwise, if value ai is at least p, then he buys the paid version without advertising,
* otherwise the user simply does not use the application.
Each user of the free version brings the profit of c × w rubles. Each user of the paid version brings the profit of p rubles.
Your task is to help the application developers to select the optimal parameters p and c. Namely, knowing all the characteristics of users, for each value of c from 0 to (max bi) + 1 you need to determine the maximum profit from the application and the corresponding parameter p.
Input
The first line contains two integers n and w (1 ≤ n ≤ 105; 1 ≤ w ≤ 105) — the number of users and the profit from a single banner. Each of the next n lines contains two integers ai and bi (0 ≤ ai, bi ≤ 105) — the characteristics of the i-th user.
Output
Print (max bi) + 2 lines, in the i-th line print two integers: pay — the maximum gained profit at c = i - 1, p (0 ≤ p ≤ 109) — the corresponding optimal app cost. If there are multiple optimal solutions, print any of them.
Examples
Input
2 1
2 0
0 2
Output
0 3
3 2
4 2
2 2
Input
3 1
3 1
2 2
1 3
Output
0 4
3 4
7 3
7 2
4 2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline char gc() {
static char buf[1 << 16], *S, *T;
if (S == T) {
T = (S = buf) + fread(buf, 1, 1 << 16, stdin);
if (T == S) return EOF;
}
return *S++;
}
inline int read() {
int x = 0, f = 1;
char ch = gc();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = gc();
}
while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = gc();
return x * f;
}
int n, w, mxb, mxa, bel[100010], nn, cnt[350], q[350][350], qh[350], qt[350];
long long d[100010];
struct data {
int a, b;
friend bool operator<(data a, data b) { return a.b < b.b; }
} A[100010];
inline double slope(int i, int j) { return (d[i] - d[j]) * 1.0 / (j - i); }
inline void gao(int i, int x) {
while (qh[i] < qt[i] && slope(q[i][qh[i]], q[i][qh[i] + 1]) <= x) ++qh[i];
}
inline void rebuild(int id, int l, int r) {
qh[id] = 1;
qt[id] = 0;
for (int i = l; i <= r; ++i) {
while (qh[id] < qt[id] &&
slope(q[id][qt[id]], i) < slope(q[id][qt[id] - 1], q[id][qt[id]]))
--qt[id];
q[id][++qt[id]] = i;
}
gao(id, 0);
}
inline void add(int x) {
if (!x) return;
for (int i = 1; i < bel[x]; ++i) gao(i, ++cnt[i]);
int l = (bel[x] - 1) * nn + 1, r = min(bel[x] * nn, mxa), id = bel[x];
for (int i = l; i <= r; ++i) d[i] += (long long)cnt[id] * i;
for (int i = l; i <= x; ++i) d[i] += i;
cnt[id] = 0;
rebuild(id, l, r);
}
int main() {
n = read();
w = read();
for (int i = 1; i <= n; ++i)
A[i].a = read(), A[i].b = read(), mxb = max(mxb, A[i].b),
mxa = max(mxa, A[i].a);
sort(A + 1, A + n + 1);
int now = 1;
nn = sqrt(mxa);
for (int i = 1; i <= mxa; ++i) bel[i] = (i - 1) / nn + 1;
int tot = bel[mxa];
for (int i = 1; i <= tot; ++i) qh[i] = 1, q[i][++qt[i]] = min(i * nn, mxa);
int flag = 0;
for (int c = 0; c <= mxb + 1; ++c) {
while (now <= n && A[now].b < c) add(A[now].a), ++now;
long long ans = 0;
int ans1 = 0;
for (int i = 1; i <= tot; ++i) {
int x = q[i][qh[i]];
if (d[x] + (long long)x * cnt[i] > ans)
ans = d[x] + (long long)x * cnt[i], ans1 = x;
}
printf("%I64d %d\n", ans + (long long)w * c * (n - now + 1), ans1);
if (c == 1) flag = ans + (long long)w * c * (n - now + 1);
}
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.
The exam consists of n problems that can be solved in T minutes. Thus, the exam begins at time 0 and ends at time T. Petya can leave the exam at any integer time from 0 to T, inclusive.
All problems are divided into two types:
* easy problems — Petya takes exactly a minutes to solve any easy problem;
* hard problems — Petya takes exactly b minutes (b > a) to solve any hard problem.
Thus, if Petya starts solving an easy problem at time x, then it will be solved at time x+a. Similarly, if at a time x Petya starts to solve a hard problem, then it will be solved at time x+b.
For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time t_i (0 ≤ t_i ≤ T) at which it will become mandatory (required). If Petya leaves the exam at time s and there is such a problem i that t_i ≤ s and he didn't solve it, then he will receive 0 points for the whole exam. Otherwise (i.e if he has solved all such problems for which t_i ≤ s) he will receive a number of points equal to the number of solved problems. Note that leaving at time s Petya can have both "mandatory" and "non-mandatory" problems solved.
For example, if n=2, T=5, a=2, b=3, the first problem is hard and t_1=3 and the second problem is easy and t_2=2. Then:
* if he leaves at time s=0, then he will receive 0 points since he will not have time to solve any problems;
* if he leaves at time s=1, he will receive 0 points since he will not have time to solve any problems;
* if he leaves at time s=2, then he can get a 1 point by solving the problem with the number 2 (it must be solved in the range from 0 to 2);
* if he leaves at time s=3, then he will receive 0 points since at this moment both problems will be mandatory, but he will not be able to solve both of them;
* if he leaves at time s=4, then he will receive 0 points since at this moment both problems will be mandatory, but he will not be able to solve both of them;
* if he leaves at time s=5, then he can get 2 points by solving all problems.
Thus, the answer to this test is 2.
Help Petya to determine the maximal number of points that he can receive, before leaving the exam.
Input
The first line contains the integer m (1 ≤ m ≤ 10^4) — the number of test cases in the test.
The next lines contain a description of m test cases.
The first line of each test case contains four integers n, T, a, b (2 ≤ n ≤ 2⋅10^5, 1 ≤ T ≤ 10^9, 1 ≤ a < b ≤ 10^9) — the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively.
The second line of each test case contains n numbers 0 or 1, separated by single space: the i-th number means the type of the i-th problem. A value of 0 means that the problem is easy, and a value of 1 that the problem is hard.
The third line of each test case contains n integers t_i (0 ≤ t_i ≤ T), where the i-th number means the time at which the i-th problem will become mandatory.
It is guaranteed that the sum of n for all test cases does not exceed 2⋅10^5.
Output
Print the answers to m test cases. For each set, print a single integer — maximal number of points that he can receive, before leaving the exam.
Example
Input
10
3 5 1 3
0 0 1
2 1 4
2 5 2 3
1 0
3 2
1 20 2 4
0
16
6 20 2 5
1 1 0 1 0 0
0 8 2 9 11 6
4 16 3 6
1 0 1 1
8 3 5 6
6 20 3 6
0 1 0 0 1 0
20 11 3 20 16 17
7 17 1 6
1 1 0 1 0 0 0
1 7 0 11 10 15 10
6 17 2 6
0 0 1 0 0 1
7 6 3 7 10 12
5 17 2 5
1 1 1 1 0
17 11 10 6 4
1 1 1 2
0
1
Output
3
2
1
0
1
4
0
1
2
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int m;
int count[200005][2];
cin >> m;
while (m--) {
int n, a, b;
long long T;
cin >> n >> T >> a >> b;
vector<pair<int, int> > problems(n + 1);
for (int i = 1; i <= n; i++) {
cin >> problems[i].second;
}
for (int i = 1; i <= n; i++) {
cin >> problems[i].first;
}
sort(problems.begin(), problems.end());
count[0][0] = 0;
count[0][1] = 0;
for (int i = 1; i <= n; i++) {
count[i][problems[i].second] = count[i - 1][problems[i].second] + 1;
count[i][problems[i].second ^ 1] = count[i - 1][problems[i].second ^ 1];
}
long long curr = 0;
int res = 0;
for (int i = 1; i <= n; i++) {
long long spare = problems[i].first - 1 - curr;
curr += problems[i].second ? b : a;
if (spare < 0) continue;
int res1 = i - 1;
if (spare)
for (int type = 0; type <= 1; type++) {
long long currCount = count[n][type] - count[i - 1][type];
long long solvable = min(spare / (type ? b : a), currCount);
res1 += solvable;
spare -= solvable * (type ? b : a);
}
res = max(res, res1);
}
if (T >= curr)
cout << n << '\n';
else
cout << res << '\n';
}
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
For an array b of length m we define the function f as
f(b) = \begin{cases} b[1] & if m = 1 \\\ f(b[1] ⊕ b[2],b[2] ⊕ b[3],...,b[m-1] ⊕ b[m]) & otherwise, \end{cases}
where ⊕ is [bitwise exclusive OR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
For example, f(1,2,4,8)=f(1⊕2,2⊕4,4⊕8)=f(3,6,12)=f(3⊕6,6⊕12)=f(5,10)=f(5⊕10)=f(15)=15
You are given an array a and a few queries. Each query is represented as two integers l and r. The answer is the maximum value of f on all continuous subsegments of the array a_l, a_{l+1}, …, a_r.
Input
The first line contains a single integer n (1 ≤ n ≤ 5000) — the length of a.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2^{30}-1) — the elements of the array.
The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of queries.
Each of the next q lines contains a query represented as two integers l, r (1 ≤ l ≤ r ≤ n).
Output
Print q lines — the answers for the queries.
Examples
Input
3
8 4 1
2
2 3
1 2
Output
5
12
Input
6
1 2 4 8 16 32
4
1 6
2 5
3 4
1 2
Output
60
30
12
3
Note
In first sample in both queries the maximum value of the function is reached on the subsegment that is equal to the whole segment.
In second sample, optimal segment for first query are [3,6], for second query — [2,5], for third — [3,4], for fourth — [1,2].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct IO {
char buf[(1 << 20)], *p1, *p2;
char pbuf[(1 << 20)], *pp;
IO() : p1(buf), p2(buf), pp(pbuf) {}
inline char gc() {
return getchar();
if (p1 == p2) p2 = (p1 = buf) + fread(buf, 1, (1 << 20), stdin);
return p1 == p2 ? ' ' : *p1++;
}
inline bool blank(char ch) {
return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t';
}
template <class T>
inline void read(T &x) {
register double tmp = 1;
register bool sign = 0;
x = 0;
register char ch = gc();
for (; !(ch >= '0' && ch <= '9'); ch = gc())
if (ch == '-') sign = 1;
for (; (ch >= '0' && ch <= '9'); ch = gc()) x = x * 10 + (ch - '0');
if (ch == '.')
for (ch = gc(); (ch >= '0' && ch <= '9'); ch = gc())
tmp /= 10.0, x += tmp * (ch - '0');
if (sign) x = -x;
}
inline void read(char *s) {
register char ch = gc();
for (; blank(ch); ch = gc())
;
for (; !blank(ch); ch = gc()) *s++ = ch;
*s = 0;
}
inline void read(char &c) {
for (c = gc(); blank(c); c = gc())
;
}
template <class t>
inline void write(t x) {
if (x < 0)
putchar('-'), write(-x);
else {
if (x > 9) write(x / 10);
putchar('0' + x % 10);
}
}
} io;
const int mod = 1e9 + 7;
const int mo = 998244353;
const int N = 5005;
int n, m, a[N], f[N][N];
int main() {
io.read(n);
for (int i = (1); i <= (n); i++) io.read(a[i]), f[1][i] = a[i];
for (int i = (2); i <= (n); i++)
for (int j = (i); j <= (n); j++) f[i][j] = f[i - 1][j] ^ f[i - 1][j - 1];
for (int i = (1); i <= (n); i++)
for (int j = (i); j <= (n); j++)
f[i][j] = max(max(f[i - 1][j], f[i - 1][j - 1]), f[i][j]);
io.read(m);
for (; m--;) {
int l, r;
io.read(l), io.read(r);
io.write(f[r - l + 1][r]), puts("");
}
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long N = 1e3 + 10;
long long n, m, k, ans, tmp, sum, SIZ, MX;
long long a[N], comp[N], yal[N], sz[N];
vector<long long> nei[N];
vector<pair<long long, long long> > y;
bool mark[N], khas[N];
void read_input() {
cin >> n >> m >> k;
for (long long i = 0; i < k; i++) {
cin >> a[i];
}
for (long long i = 0; i < m; i++) {
long long u, v;
cin >> u >> v;
y.push_back({u, v});
nei[u].push_back(v);
nei[v].push_back(u);
}
}
void dfs(long long v) {
sz[tmp]++;
mark[v] = true;
comp[v] = tmp;
khas[v] = true;
for (long long u : nei[v]) {
if (!mark[u]) {
dfs(u);
}
}
}
int32_t main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
read_input();
for (long long i = 0; i < k; i++) {
tmp++;
dfs(a[i]);
}
for (long long i = 0; i < y.size(); i++) {
long long u = y[i].first;
long long v = y[i].second;
if (khas[u]) {
yal[comp[u]]++;
} else {
sum++;
}
}
for (long long i = 1; i <= n; i++) {
if (!khas[i]) {
SIZ++;
}
}
for (long long i = 1; i <= tmp; i++) {
if (sz[i] > sz[MX]) {
MX = i;
}
}
for (long long i = 1; i <= tmp; i++) {
long long yy = sz[i] * (sz[i] - 1) / 2;
ans += yy - yal[i];
}
long long zz = SIZ * (SIZ - 1) / 2;
ans += zz - sum;
ans += sz[MX] * SIZ;
cout << ans;
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Tsuruga Castle, a symbol of Aizuwakamatsu City, was named "Tsuruga Castle" after Gamo Ujisato built a full-scale castle tower. You can overlook the Aizu basin from the castle tower. On a clear day, you can see Tsuruga Castle from the summit of Mt. Iimori, which is famous for Byakkotai.
<image>
We decided to conduct a dating survey of visitors to Tsuruga Castle to use as a reference for future public relations activities in Aizuwakamatsu City. Please create a program that inputs the age of visitors and outputs the number of people by age group below.
Category | Age
--- | ---
Under 10 years old | 0 ~ 9
Teens | 10 ~ 19
20s | 20 ~ 29
30s | 30 ~ 39
40s | 40 ~ 49
50s | 50 ~ 59
Over 60 years old | 60 ~
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
a1
a2
::
an
The first line gives the number of visitors n (1 ≤ n ≤ 1000000), and the following n lines give the age of the i-th visitor ai (0 ≤ ai ≤ 120).
Output
The number of people is output in the following format for each data set.
Line 1: Number of people under 10
Line 2: Number of teens
Line 3: Number of people in their 20s
Line 4: Number of people in their 30s
Line 5: Number of people in their 40s
Line 6: Number of people in their 50s
Line 7: Number of people over 60
Example
Input
8
71
34
65
11
41
39
6
5
4
67
81
78
65
0
Output
2
1
0
2
1
0
2
0
0
0
0
0
0
4
### Response
```cpp
#include <iostream>
int main(){int n,x,i;while(std::cin>>n,n){int dat[7]={};for(i=0;i<n;std::cin>>x,x=x/10>6?60:x,dat[x/10]++,i++);for(i=0;i<7;std::cout<<dat[i]<<'\n',i++);}}
``` |
### Prompt
Create a solution in cpp for the following problem:
You are given a bipartite graph: the first part of this graph contains n_1 vertices, the second part contains n_2 vertices, and there are m edges. The graph can contain multiple edges.
Initially, each edge is colorless. For each edge, you may either leave it uncolored (it is free), paint it red (it costs r coins) or paint it blue (it costs b coins). No edge can be painted red and blue simultaneously.
There are three types of vertices in this graph — colorless, red and blue. Colored vertices impose additional constraints on edges' colours:
* for each red vertex, the number of red edges indicent to it should be strictly greater than the number of blue edges incident to it;
* for each blue vertex, the number of blue edges indicent to it should be strictly greater than the number of red edges incident to it.
Colorless vertices impose no additional constraints.
Your goal is to paint some (possibly none) edges so that all constraints are met, and among all ways to do so, you should choose the one with minimum total cost.
Input
The first line contains five integers n_1, n_2, m, r and b (1 ≤ n_1, n_2, m, r, b ≤ 200) — the number of vertices in the first part, the number of vertices in the second part, the number of edges, the amount of coins you have to pay to paint an edge red, and the amount of coins you have to pay to paint an edge blue, respectively.
The second line contains one string consisting of n_1 characters. Each character is either U, R or B. If the i-th character is U, then the i-th vertex of the first part is uncolored; R corresponds to a red vertex, and B corresponds to a blue vertex.
The third line contains one string consisting of n_2 characters. Each character is either U, R or B. This string represents the colors of vertices of the second part in the same way.
Then m lines follow, the i-th line contains two integers u_i and v_i (1 ≤ u_i ≤ n_1, 1 ≤ v_i ≤ n_2) denoting an edge connecting the vertex u_i from the first part and the vertex v_i from the second part.
The graph may contain multiple edges.
Output
If there is no coloring that meets all the constraints, print one integer -1.
Otherwise, print an integer c denoting the total cost of coloring, and a string consisting of m characters. The i-th character should be U if the i-th edge should be left uncolored, R if the i-th edge should be painted red, or B if the i-th edge should be painted blue. If there are multiple colorings with minimum possible cost, print any of them.
Examples
Input
3 2 6 10 15
RRB
UB
3 2
2 2
1 2
1 1
2 1
1 1
Output
35
BUURRU
Input
3 1 3 4 5
RRR
B
2 1
1 1
3 1
Output
-1
Input
3 1 3 4 5
URU
B
2 1
1 1
3 1
Output
14
RBB
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int hed[1010], dis[1010], mn[1010], pre[1010], bh[1010], tot = 1, s, t, mxfl,
mincost;
bool in[1010];
struct edg {
int to, nxt, f, v;
} e[2010000];
void add(int x, int y, int f, int v) {
e[++tot] = (edg){y, hed[x], f, v};
hed[x] = tot;
e[++tot] = (edg){x, hed[y], 0, -v};
hed[y] = tot;
}
void dfs(int x) {
e[bh[x]].f -= mn[t];
e[bh[x] ^ 1].f += mn[t];
if (pre[x] != s) dfs(pre[x]);
}
queue<int> q;
bool spfa() {
for (int i = 1; i <= t + 2; i++) dis[i] = 2e9;
dis[s] = 0;
mn[s] = 2e9;
q.push(s);
while (!q.empty()) {
int x = q.front();
q.pop();
in[x] = 0;
for (int i = hed[x]; i; i = e[i].nxt) {
int to = e[i].to;
if (dis[to] > dis[x] + e[i].v && e[i].f > 0) {
dis[to] = dis[x] + e[i].v;
mn[to] = min(mn[x], e[i].f);
pre[to] = x;
bh[to] = i;
if (!in[to]) q.push(to), in[to] = 1;
}
}
}
if (dis[t] == 2e9) return 0;
dfs(t);
return 1;
}
void ek() {
mxfl = 0;
mincost = 0;
while (spfa()) {
mincost += dis[t] * mn[t];
mxfl += mn[t];
}
}
int n, m, k, a, b, S, T, ss, tt, x, y, d[1010], ans, sum;
void add1(int x, int y, int f, int v) {
ans += v;
d[x]--;
d[y]++;
add(x, y, f, v);
}
char ch1[1010], ch2[1010];
int main() {
scanf("%d%d%d%d%d", &n, &m, &k, &a, &b);
scanf("%s%s", ch1 + 1, ch2 + 1);
S = n + m + 1, T = n + m + 2;
ss = T + 1;
tt = ss + 1;
for (int i = 1; i <= k; i++) {
scanf("%d%d", &x, &y);
add(x, y + n, 1, a), add(y + n, x, 1, b);
}
for (int i = 1; i <= n; i++)
if (ch1[i] == 'R')
add1(ss, i, k, 0);
else if (ch1[i] == 'B')
add1(i, tt, k, 0);
else
add(ss, i, k, 0), add(i, tt, k, 0);
for (int i = 1; i <= m; i++)
if (ch2[i] == 'B')
add1(ss, i + n, k, 0);
else if (ch2[i] == 'R')
add1(i + n, tt, k, 0);
else
add(ss, i + n, k, 0), add(i + n, tt, k, 0);
add(tt, ss, 2e9, 0);
for (int i = 1; i <= n + m + 4; i++)
if (d[i] > 0)
add(S, i, d[i], 0), sum += d[i];
else if (d[i] < 0)
add(i, T, -d[i], 0);
s = S, t = T;
ek();
if (mxfl != sum) {
printf("-1");
return 0;
}
printf("%d\n", ans + mincost);
for (int i = 0; i < k; i++) {
if (!e[i * 4 + 2].f)
printf("R");
else if (!e[i * 4 + 4].f)
printf("B");
else
printf("U");
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Snow Queen told Kay to form a word "eternity" using pieces of ice. Kay is eager to deal with the task, because he will then become free, and Snow Queen will give him all the world and a pair of skates.
Behind the palace of the Snow Queen there is an infinite field consisting of cells. There are n pieces of ice spread over the field, each piece occupying exactly one cell and no two pieces occupying the same cell. To estimate the difficulty of the task Kay looks at some squares of size k × k cells, with corners located at the corners of the cells and sides parallel to coordinate axis and counts the number of pieces of the ice inside them.
This method gives an estimation of the difficulty of some part of the field. However, Kay also wants to estimate the total difficulty, so he came up with the following criteria: for each x (1 ≤ x ≤ n) he wants to count the number of squares of size k × k, such that there are exactly x pieces of the ice inside.
Please, help Kay estimate the difficulty of the task given by the Snow Queen.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 300) — the number of pieces of the ice and the value k, respectively. Each of the next n lines contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — coordinates of the cell containing i-th piece of the ice. It's guaranteed, that no two pieces of the ice occupy the same cell.
Output
Print n integers: the number of squares of size k × k containing exactly 1, 2, ..., n pieces of the ice.
Example
Input
5 3
4 5
4 6
5 5
5 6
7 7
Output
10 8 1 4 0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;
}
multiset<int> s;
int n, K, top, q[100000 + 5];
pair<int, int> a[100000 + 5];
long long ans[100000 + 5];
int main() {
n = read();
K = read();
for (int i = 1; i <= n; ++i) a[i].first = read(), a[i].second = read();
sort(a + 1, a + n + 1);
for (int i = 1, j; i <= n; i = j + 1) {
for (j = i + 1; j <= n && a[j].first - a[j - 1].first < K; ++j)
;
--j;
s.clear();
for (int k = a[i].first, l = i, r = i; k <= a[j].first + K - 1; ++k) {
for (; l <= j && a[l].first <= k; ++l) s.insert(a[l].second);
for (; r <= j && a[r].first + K <= k; ++r)
s.erase(s.lower_bound(a[r].second));
top = 0;
for (multiset<int>::iterator it = s.begin(); it != s.end(); ++it)
q[++top] = *it;
for (int L = 1, R = 1, pre = q[1] - 1; L <= top;) {
if (R <= top && q[R] <= q[L] + K)
ans[R - L] += q[R] - pre, pre = q[R], ++R;
else
ans[R - L] += q[L] + K - pre, pre = q[L] + K, ++L;
}
}
}
for (int i = 1; i <= n; ++i) printf("%lld ", ans[i]);
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Grigory loves strings. Recently he found a metal strip on a loft. The strip had length n and consisted of letters "V" and "K". Unfortunately, rust has eaten some of the letters so that it's now impossible to understand which letter was written.
Grigory couldn't understand for a long time what these letters remind him of, so he became interested in the following question: if we put a letter "V" or "K" on each unreadable position, which values can the period of the resulting string be equal to?
A period of a string is such an integer d from 1 to the length of the string that if we put the string shifted by d positions to the right on itself, then all overlapping letters coincide. For example, 3 and 5 are periods of "VKKVK".
Input
There are several (at least one) test cases in the input. The first line contains single integer — the number of test cases.
There is an empty line before each test case. Each test case is described in two lines: the first line contains single integer n (1 ≤ n ≤ 5·105) — the length of the string, the second line contains the string of length n, consisting of letters "V", "K" and characters "?". The latter means the letter on its position is unreadable.
It is guaranteed that the sum of lengths among all test cases doesn't exceed 5·105.
For hacks you can only use tests with one test case.
Output
For each test case print two lines. In the first line print the number of possible periods after we replace each unreadable letter with "V" or "K". In the next line print all these values in increasing order.
Example
Input
3
5
V??VK
6
??????
4
?VK?
Output
2
3 5
6
1 2 3 4 5 6
3
2 3 4
Note
In the first test case from example we can obtain, for example, "VKKVK", which has periods 3 and 5.
In the second test case we can obtain "VVVVVV" which has all periods from 1 to 6.
In the third test case string "KVKV" has periods 2 and 4, and string "KVKK" has periods 3 and 4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1048576;
struct comp {
double x, y;
comp() {}
comp(double a, double b) {
x = a;
y = b;
}
comp operator+(const comp &A) const { return comp(x + A.x, y + A.y); }
comp operator-(const comp &A) const { return comp(x - A.x, y - A.y); }
comp operator*(const comp &A) const {
return comp(x * A.x - y * A.y, x * A.y + y * A.x);
}
} a[maxn], b[maxn];
const double pi = acos(-1.0);
void fft(comp *a, int N, int sign) {
for (int i = 1, j = 0, k = N; i < N; ++i, k = N) {
do j ^= (k >>= 1);
while (j < k);
if (j < i) swap(a[i], a[j]);
}
for (int j = 2; j <= N; j <<= 1) {
int m = j >> 1;
comp wn(cos(2.0 * pi / j), sign * sin(2.0 * pi / j));
for (comp *p = a; p != a + N; p = p + j) {
comp w(1, 0);
for (int k = 0; k < m; ++k, w = w * wn) {
comp t = w * p[m + k];
p[m + k] = p[k] - t;
p[k] = p[k] + t;
}
}
}
if (sign == -1) {
for (int i = 0; i < N; ++i) a[i].x /= N;
}
}
int n;
char str[maxn];
int seq[maxn], revseq[maxn];
double sum[maxn];
bool check(int x) {
for (int i = x; i < n; i += x) {
if (fabs(sum[n - i - 1]) > 1e-6) return false;
}
return true;
}
void work() {
scanf("%d%s", &n, str);
for (int i = 0; i < n; ++i) {
seq[i] = (str[i] == '?') ? 0 : (str[i] == 'V' ? 1 : 2);
}
for (int i = 0; i < n; ++i) {
revseq[i] = seq[n - i - 1];
}
for (int i = 0; i < n; ++i) {
a[i] = comp(seq[i] * seq[i] * seq[i], 0);
b[i] = comp(revseq[i], 0);
}
int N = 1;
while (N <= n) N <<= 1;
N <<= 1;
for (int i = 0; i < N; ++i) sum[i] = 0;
for (int i = n; i < N; ++i) a[i] = comp(0, 0);
for (int i = n; i < N; ++i) b[i] = comp(0, 0);
fft(a, N, 1);
fft(b, N, 1);
for (int i = 0; i < N; ++i) a[i] = a[i] * b[i];
fft(a, N, -1);
for (int i = 0; i < N; ++i) sum[i] += a[i].x;
for (int i = 0; i < n; ++i) {
a[i] = comp(seq[i], 0);
b[i] = comp(revseq[i] * revseq[i] * revseq[i], 0);
}
for (int i = n; i < N; ++i) a[i] = comp(0, 0);
for (int i = n; i < N; ++i) b[i] = comp(0, 0);
fft(a, N, 1);
fft(b, N, 1);
for (int i = 0; i < N; ++i) a[i] = a[i] * b[i];
fft(a, N, -1);
for (int i = 0; i < N; ++i) sum[i] += a[i].x;
for (int i = 0; i < n; ++i) {
a[i] = comp(seq[i] * seq[i], 0);
b[i] = comp(revseq[i] * revseq[i], 0);
}
for (int i = n; i < N; ++i) a[i] = comp(0, 0);
for (int i = n; i < N; ++i) b[i] = comp(0, 0);
fft(a, N, 1);
fft(b, N, 1);
for (int i = 0; i < N; ++i) a[i] = a[i] * b[i];
fft(a, N, -1);
for (int i = 0; i < N; ++i) sum[i] -= 2.0 * a[i].x;
int cnt = 1;
for (int i = 1; i < n; ++i) {
if (check(i)) cnt++;
}
printf("%d\n", cnt);
for (int i = 1; i < n; ++i) {
if (check(i)) printf("%d ", i);
}
printf("%d\n", n);
}
int main() {
a[0].x = 1;
a[1].x = 1;
int tests;
scanf("%d", &tests);
while (tests--) {
work();
}
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
This is the hard version of the problem. You can find the easy version in the Div. 2 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.
This is an interactive problem.
You're considering moving to another city, where one of your friends already lives. There are n cafés in this city, where n is a power of two. The i-th café produces a single variety of coffee a_i.
As you're a coffee-lover, before deciding to move or not, you want to know the number d of distinct varieties of coffees produced in this city.
You don't know the values a_1, …, a_n. Fortunately, your friend has a memory of size k, where k is a power of two.
Once per day, you can ask him to taste a cup of coffee produced by the café c, and he will tell you if he tasted a similar coffee during the last k days.
You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30\ 000 times.
More formally, the memory of your friend is a queue S. Doing a query on café c will:
* Tell you if a_c is in S;
* Add a_c at the back of S;
* If |S| > k, pop the front element of S.
Doing a reset request will pop all elements out of S.
Your friend can taste at most (3n^2)/(2k) cups of coffee in total. Find the diversity d (number of distinct values in the array a).
Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.
In some test cases the behavior of the interactor is adaptive. It means that the array a may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array a consistent with all the answers given so far.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 1024, k and n are powers of two).
It is guaranteed that (3n^2)/(2k) ≤ 15\ 000.
Interaction
You begin the interaction by reading n and k.
* To ask your friend to taste a cup of coffee produced by the café c, in a separate line output
? c
Where c must satisfy 1 ≤ c ≤ n. Don't forget to flush, to get the answer.
In response, you will receive a single letter Y (yes) or N (no), telling you if variety a_c is one of the last k varieties of coffee in his memory.
* To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30\ 000 times.
* When you determine the number d of different coffee varieties, output
! d
In case your query is invalid, you asked more than (3n^2)/(2k) queries of type ? or you asked more than 30\ 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.
After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Hack format
The first line should contain the word fixed
The second line should contain two integers n and k, separated by space (1 ≤ k ≤ n ≤ 1024, k and n are powers of two).
It must hold that (3n^2)/(2k) ≤ 15\ 000.
The third line should contain n integers a_1, a_2, …, a_n, separated by spaces (1 ≤ a_i ≤ n).
Examples
Input
4 2
N
N
Y
N
N
N
N
Output
? 1
? 2
? 3
? 4
R
? 4
? 1
? 2
! 3
Input
8 8
N
N
N
N
Y
Y
Output
? 2
? 6
? 4
? 5
? 2
? 5
! 6
Note
In the first example, the array is a = [1, 4, 1, 3]. The city produces 3 different varieties of coffee (1, 3 and 4).
The successive varieties of coffee tasted by your friend are 1, 4, 1, 3, 3, 1, 4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.
In the second example, the array is a = [1, 2, 3, 4, 5, 6, 6, 6]. The city produces 6 different varieties of coffee.
The successive varieties of coffee tasted by your friend are 2, 6, 4, 5, 2, 5.
### Response
```cpp
#include <bits/stdc++.h>
namespace IO {
char gc() { return getchar(); }
template <typename Tp>
bool get1(Tp &x) {
bool neg = 0;
char c = gc();
while (c != EOF && (c < '0' || c > '9') && c != '-') c = gc();
if (c == '-') c = gc(), neg = 1;
if (c == EOF) return false;
x = 0;
for (; c >= '0' && c <= '9'; c = gc()) x = x * 10 + c - '0';
if (neg) x = -x;
return true;
}
template <typename Tp>
void printendl(Tp x) {
if (x < 0) putchar('-'), x = -x;
static short a[40], sz;
sz = 0;
while (x > 0) a[sz++] = x % 10, x /= 10;
if (sz == 0) putchar('0');
for (int i = sz - 1; i >= 0; i--) putchar('0' + a[i]);
puts("");
}
} // namespace IO
using IO::get1;
using IO::printendl;
const int inf = 0x3f3f3f3f;
const long long Linf = 1ll << 61;
void reset() {
puts("R");
fflush(stdout);
}
int count;
int query(int c) {
static char s[5];
count++;
printf("? %d\n", c);
fflush(stdout);
scanf("%s", s);
if (s[0] == 'Y')
return 1;
else
return 0;
}
const int maxn = 1111;
int n, k;
bool alive[maxn];
int main() {
get1(n) && get1(k);
int Block = std::max(1, k / 2), BlockN = n / Block;
for (int i = 1; i <= n; i++) alive[i] = 1;
for (int dltB = 1; dltB < BlockN; dltB++) {
for (int stB = 1; stB <= dltB && stB + dltB <= BlockN; stB++) {
reset();
for (int b = stB; b <= BlockN; b += dltB) {
for (int i = 0; i < Block; i++) {
int cur = (b - 1) * Block + i + 1;
if (query(cur)) alive[cur] = 0;
}
}
}
}
int ans = 0;
for (int i = 1; i <= n; i++) ans += alive[i];
printf("! %d\n", ans);
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a × b.
After n - 1 steps there is only one number left. Can you make this number equal to 24?
Input
The first line contains a single integer n (1 ≤ n ≤ 105).
Output
If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes).
If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces.
If there are multiple valid answers, you may print any of them.
Examples
Input
1
Output
NO
Input
8
Output
YES
8 * 7 = 56
6 * 5 = 30
3 - 4 = -1
1 - 2 = -1
30 - -1 = 31
56 - 31 = 25
25 + -1 = 24
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
map<long long, long long> mp;
queue<long long> q;
void solve() {
int n;
cin >> n;
if (n < 4) {
cout << "NO";
return;
}
cout << "YES\n";
vector<int> v;
int cnt = 0;
if (n % 2) {
for (int i = n; i > 6; i -= 2) {
cout << i << " - " << i - 1 << " = 1\n";
cnt++;
}
cout << "4 * 2 = 8\n";
cout << "5 * 3 = 15\n";
cout << "15 + 8 = 23\n";
cout << "23 + 1 = 24\n";
for (int i = 1; i <= cnt - 1; i += 2) {
cout << "24 + 1 = 25\n";
cout << "25 - 1 = 24\n";
}
if (cnt % 2) cout << "24 * 1 = 24";
} else {
for (int i = n; i > 5; i -= 2) {
cout << i << " - " << i - 1 << " = 1\n";
cnt++;
}
cout << "4 * 3 = 12\n";
cout << "12 * 2 = 24\n";
for (int i = 1; i <= cnt; i += 2) {
cout << "24 + 1 = 25\n";
cout << "25 - 1 = 24\n";
}
if (cnt % 2 == 0) cout << "24 * 1 = 24";
}
}
int main() {
int t = 1;
while (t--) {
solve();
cout << endl;
}
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
Input
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph.
The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space.
Output
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
Examples
Input
3
2 3
1 0
1 0
Output
2
1 0
2 0
Input
2
1 1
1 0
Output
1
0 1
Note
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 70000;
int deg[N], xorsum[N], xorhave[N], n;
vector<pair<int, int> > ans;
stack<int> nodes;
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d%d", °[i], &xorsum[i]);
if (deg[i] == 1) {
nodes.push(i);
}
}
while (!nodes.empty()) {
if (deg[nodes.top()] == 0) {
nodes.pop();
continue;
}
int newnode = xorhave[nodes.top()] ^ xorsum[nodes.top()];
deg[newnode]--;
deg[nodes.top()]--;
xorhave[newnode] ^= nodes.top();
ans.push_back(make_pair(nodes.top(), newnode));
nodes.pop();
if (deg[newnode] == 1) {
nodes.push(newnode);
}
}
int sz = ans.size();
printf("%d\n", sz);
for (int i = 0; i < sz; i++) {
printf("%d %d\n", ans[i].first, ans[i].second);
}
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
<image>
Recently, a wild Krakozyabra appeared at Jelly Castle. It is, truth to be said, always eager to have something for dinner.
Its favorite meal is natural numbers (typically served with honey sauce), or, to be more precise, the zeros in their corresponding decimal representations. As for other digits, Krakozyabra dislikes them; moreover, they often cause it indigestion! So, as a necessary precaution, Krakozyabra prefers to sort the digits of a number in non-descending order before proceeding to feast. Then, the leading zeros of the resulting number are eaten and the remaining part is discarded as an inedible tail.
For example, if Krakozyabra is to have the number 57040 for dinner, its inedible tail would be the number 457.
Slastyona is not really fond of the idea of Krakozyabra living in her castle. Hovewer, her natural hospitality prevents her from leaving her guest without food. Slastyona has a range of natural numbers from L to R, which she is going to feed the guest with. Help her determine how many distinct inedible tails are going to be discarded by Krakozyabra by the end of the dinner.
Input
In the first and only string, the numbers L and R are given – the boundaries of the range (1 ≤ L ≤ R ≤ 1018).
Output
Output the sole number – the answer for the problem.
Examples
Input
1 10
Output
9
Input
40 57
Output
17
Input
157 165
Output
9
Note
In the first sample case, the inedible tails are the numbers from 1 to 9. Note that 10 and 1 have the same inedible tail – the number 1.
In the second sample case, each number has a unique inedible tail, except for the pair 45, 54. The answer to this sample case is going to be (57 - 40 + 1) - 1 = 17.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10, mod = 1e9 + 7;
const long long inf = 1e18;
int l[20], r[20], cnt[20], tmp[20], tmp2[20];
long long ans;
void inp(int *a) {
long long x;
cin >> x;
for (int i = 0; i < 20; i++) {
a[19 - i] = x % 10;
x /= 10;
}
}
bool checkr(int pos) {
memcpy(tmp2, tmp, sizeof tmp2);
int lim = 0;
while (pos < 20) {
while (lim < 20 && tmp2[lim] == 0) lim++;
if (r[pos] < lim) return 0;
if (r[pos] > lim) return 1;
tmp2[r[pos]]--, pos++;
}
return 1;
}
bool checkl(int pos) {
memcpy(tmp2, tmp, sizeof tmp2);
int lim = 9;
while (pos < 20) {
while (lim >= 0 && tmp2[lim] == 0) lim--;
if (l[pos] > lim) return 0;
if (l[pos] < lim) return 1;
tmp2[l[pos]]--, pos++;
}
return 1;
}
bool ok() {
memcpy(tmp, cnt, sizeof cnt);
int pt = 0;
while (pt < 20 && l[pt] == r[pt]) {
if (tmp[l[pt]] == 0) return 0;
tmp[l[pt]]--;
pt++;
}
if (pt == 20) return 1;
for (int w = l[pt] + 1; w < r[pt]; w++) {
if (tmp[w]) return 1;
}
if (tmp[l[pt]]) {
tmp[l[pt]]--;
if (checkl(pt + 1)) return 1;
tmp[l[pt]]++;
}
if (tmp[r[pt]]) {
tmp[r[pt]]--;
if (checkr(pt + 1)) return 1;
}
return 0;
}
void go(int sm = 0, int who = 1) {
if (who == 10) {
cnt[0] = 20 - sm;
ans += ok();
return;
}
for (cnt[who] = 0; sm <= 18; cnt[who]++, sm++) {
go(sm, who + 1);
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
inp(l), inp(r), go();
return cout << ans << endl, 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Arkady's code contains n variables. Each variable has a unique name consisting of lowercase English letters only. One day Arkady decided to shorten his code.
He wants to replace each variable name with its non-empty prefix so that these new names are still unique (however, a new name of some variable can coincide with some old name of another or same variable). Among such possibilities he wants to find the way with the smallest possible total length of the new names.
A string a is a prefix of a string b if you can delete some (possibly none) characters from the end of b and obtain a.
Please find this minimum possible total length of new names.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of variables.
The next n lines contain variable names, one per line. Each name is non-empty and contains only lowercase English letters. The total length of these strings is not greater than 10^5. The variable names are distinct.
Output
Print a single integer — the minimum possible total length of new variable names.
Examples
Input
3
codeforces
codehorses
code
Output
6
Input
5
abba
abb
ab
aa
aacada
Output
11
Input
3
telegram
digital
resistance
Output
3
Note
In the first example one of the best options is to shorten the names in the given order as "cod", "co", "c".
In the second example we can shorten the last name to "aac" and the first name to "a" without changing the other names.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100000;
struct Trie_Tree {
int cnt, Trie[MAXN + 5][30];
int fin[MAXN + 5], depth[MAXN + 5];
void Build() {
cnt = 0;
memset(Trie, 0, sizeof(Trie));
memset(fin, 0, sizeof(fin));
}
void Insert(char *str) {
int len = strlen(str), u = 0;
for (int i = 0; i < len; i++) {
int num = str[i] - 'a';
if (!Trie[u][num]) Trie[u][num] = ++cnt;
depth[Trie[u][num]] = depth[u] + 1;
u = Trie[u][num];
}
fin[u]++;
}
} Tree;
struct cmp {
bool operator()(int a, int b) { return Tree.depth[a] < Tree.depth[b]; }
};
priority_queue<int, vector<int>, cmp> Que[MAXN + 5];
void solve(int root) {
for (int i = 0; i < 26; i++) {
if (Tree.Trie[root][i] == 0) continue;
solve(Tree.Trie[root][i]);
while (!Que[Tree.Trie[root][i]].empty()) {
Que[root].push(Que[Tree.Trie[root][i]].top());
Que[Tree.Trie[root][i]].pop();
}
}
if (!Que[root].empty() && Tree.fin[root] == 0 && root != 0) {
Tree.fin[Que[root].top()]--;
Tree.fin[root]++;
Que[root].pop();
}
if (Tree.fin[root] == 1) Que[root].push(root);
}
int n;
char str[MAXN + 5];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%s", str), Tree.Insert(str);
solve(0);
int sum = 0;
while (!Que[0].empty()) {
sum += Tree.depth[Que[0].top()];
Que[0].pop();
}
printf("%d\n", sum);
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Little Petya very much likes playing with little Masha. Recently he has received a game called "Zero-One" as a gift from his mother. Petya immediately offered Masha to play the game with him.
Before the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card contains a digit: 0 or 1. Players move in turns and Masha moves first. During each move a player should remove a card from the table and shift all other cards so as to close the gap left by the removed card. For example, if before somebody's move the cards on the table formed a sequence 01010101, then after the fourth card is removed (the cards are numbered starting from 1), the sequence will look like that: 0100101.
The game ends when exactly two cards are left on the table. The digits on these cards determine the number in binary notation: the most significant bit is located to the left. Masha's aim is to minimize the number and Petya's aim is to maximize it.
An unpleasant accident occurred before the game started. The kids spilled juice on some of the cards and the digits on the cards got blurred. Each one of the spoiled cards could have either 0 or 1 written on it. Consider all possible variants of initial arrangement of the digits (before the juice spilling). For each variant, let's find which two cards are left by the end of the game, assuming that both Petya and Masha play optimally. An ordered pair of digits written on those two cards is called an outcome. Your task is to find the set of outcomes for all variants of initial digits arrangement.
Input
The first line contains a sequence of characters each of which can either be a "0", a "1" or a "?". This sequence determines the initial arrangement of cards on the table from the left to the right. The characters "?" mean that the given card was spoiled before the game. The sequence's length ranges from 2 to 105, inclusive.
Output
Print the set of outcomes for all possible initial digits arrangements. Print each possible outcome on a single line. Each outcome should be represented by two characters: the digits written on the cards that were left by the end of the game. The outcomes should be sorted lexicographically in ascending order (see the first sample).
Examples
Input
????
Output
00
01
10
11
Input
1010
Output
10
Input
1?1
Output
01
11
Note
In the first sample all 16 variants of numbers arrangement are possible. For the variant 0000 the outcome is 00. For the variant 1111 the outcome is 11. For the variant 0011 the outcome is 01. For the variant 1100 the outcome is 10. Regardless of outcomes for all other variants the set which we are looking for will contain all 4 possible outcomes.
In the third sample only 2 variants of numbers arrangement are possible: 111 and 101. For the variant 111 the outcome is 11. For the variant 101 the outcome is 01, because on the first turn Masha can remove the first card from the left after which the game will end.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
char s[1234567], t[1234567];
string evaluate(int n) {
queue<int> q[2];
for (int i = 0; i < n; ++i) {
q[t[i] - '0'].push(i);
}
int cnt = 0;
while (cnt < n - 2) q[cnt % 2 == 0].pop(), ++cnt;
if (q[0].front() < q[1].front()) return "01";
return "10";
}
int main() {
scanf("%s", s);
int n = strlen(s);
set<string> ans;
int zero = 0, one = 0, spoiled = 0;
for (int i = 0; i < n; ++i) {
if (s[i] == '0')
zero++;
else if (s[i] == '1')
one++;
else
spoiled++;
}
for (int extraZero = 0; extraZero <= spoiled; ++extraZero) {
int zeros = zero + extraZero;
int ones = one + spoiled - extraZero;
if (zeros - 2 >= ones || zeros > ones)
ans.insert("00");
else if (ones - 2 >= zeros)
ans.insert("11");
else {
int remain = extraZero;
for (int i = 0; i < n; ++i) {
if (s[i] != '?')
t[i] = s[i];
else if (remain)
t[i] = '0', remain--;
else
t[i] = '1';
}
ans.insert(evaluate(n));
remain = spoiled - extraZero;
for (int i = 0; i < n; ++i) {
if (s[i] != '?')
t[i] = s[i];
else if (remain)
t[i] = '1', remain--;
else
t[i] = '0';
}
ans.insert(evaluate(n));
}
}
for (auto p : ans) puts(p.c_str());
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input
The only line contains an integer n (1 ≤ n ≤ 10000).
Output
Print two non-negative space-separated integers a and b, where a is the numbers of feet and b is the number of inches.
Examples
Input
42
Output
1 2
Input
5
Output
0 2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, i, f;
int main() {
cin >> n;
while (n >= 3) {
n -= 3;
i++;
}
if (n == 2) i++;
while (i >= 12) {
i -= 12;
f++;
}
cout << f << " " << i;
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
There are N squares arranged in a row, numbered 1 to N from left to right. Takahashi will stack building blocks on these squares, on which there are no blocks yet.
He wants to stack blocks on the squares evenly, so he will repeat the following operation until there are H blocks on every square:
* Let M and m be the maximum and minimum numbers of blocks currently stacked on a square, respectively. Choose a square on which m blocks are stacked (if there are multiple such squares, choose any one of them), and add a positive number of blocks on that square so that there will be at least M and at most M + D blocks on that square.
Tell him how many ways there are to have H blocks on every square by repeating this operation. Since there can be extremely many ways, print the number modulo 10^9+7.
Constraints
* 2 \leq N \leq 10^6
* 1 \leq D \leq H \leq 10^6
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N H D
Output
Print the number of ways to have H blocks on every square, modulo 10^9+7.
Examples
Input
2 2 1
Output
6
Input
2 30 15
Output
94182806
Input
31415 9265 3589
Output
312069529
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
static const ll mod=1000000007;
ll N,H,D;
ll dp[2][1000005];
ll fac[1000005];
int main(){
cin>>N>>H>>D;
fac[0]=1;ll sum=0;
for(ll i=1;i<=N;i++){
fac[i]=(fac[i-1]*i)%mod;
sum=(sum+fac[i])%mod;
}dp[1][0]=fac[N];
for(ll i=1;i<H;i++){
dp[1][i]=(sum*(dp[0][i-1]+dp[1][i-1]))%mod;
dp[0][i]=(dp[0][i-1]+dp[1][i-1])%mod;
if(0<=i-D)
dp[0][i]=(dp[0][i]-dp[1][i-D]+mod)%mod;
}ll ans=(dp[0][H-1]+dp[1][H-1])%mod;
cout<<ans<<endl;
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Let T be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree T:
1. Set pointer to the root of a tree.
2. Return success if the value in the current vertex is equal to the number you are looking for
3. Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for
4. Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for
5. Return fail if you try to go to the vertex that doesn't exist
Here is the pseudo-code of the described algorithm:
bool find(TreeNode t, int x) {
if (t == null)
return false;
if (t.value == x)
return true;
if (x < t.value)
return find(t.left, x);
else
return find(t.right, x);
}
find(root, x);
The described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree.
Since the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree.
If the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately.
Input
First line contains integer number n (1 ≤ n ≤ 105) — number of vertices in the tree.
Each of the next n lines contains 3 numbers v, l, r (0 ≤ v ≤ 109) — value on current vertex, index of the left child of the vertex and index of the right child of the vertex, respectively. If some child doesn't exist then number - 1 is set instead. Note that different vertices of the tree may contain the same values.
Output
Print number of times when search algorithm will fail.
Examples
Input
3
15 -1 -1
10 1 3
5 -1 -1
Output
2
Input
8
6 2 3
3 4 5
12 6 7
1 -1 8
4 -1 -1
5 -1 -1
14 -1 -1
2 -1 -1
Output
1
Note
In the example the root of the tree in vertex 2. Search of numbers 5 and 15 will return fail because on the first step algorithm will choose the subtree which doesn't contain numbers you are looking for.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 7;
int n, rt;
int val[100005], pa[100005], son[100005][2];
int ans;
multiset<int> lebnd, ribnd;
map<int, bool> can;
void dfs(int x) {
if (*lebnd.rbegin() <= val[x] && *ribnd.begin() >= val[x]) can[val[x]] = 1;
ribnd.insert(val[x]);
if (son[x][0] != -1) dfs(son[x][0]);
ribnd.erase(ribnd.find(val[x]));
lebnd.insert(val[x]);
if (son[x][1] != -1) dfs(son[x][1]);
lebnd.erase(lebnd.find(val[x]));
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d %d %d", &val[i], &son[i][0], &son[i][1]);
if (son[i][0] != -1) pa[son[i][0]] = i;
if (son[i][1] != -1) pa[son[i][1]] = i;
}
rt = 1;
while (pa[rt]) rt = pa[rt];
lebnd.insert(-INF), ribnd.insert(INF);
dfs(rt);
for (int i = 1; i <= n; i++)
if (!can.count(val[i])) ans++;
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
In AtCoder Kingdom, Gregorian calendar is used, and dates are written in the "year-month-day" order, or the "month-day" order without the year.
For example, May 3, 2018 is written as 2018-5-3, or 5-3 without the year.
In this country, a date is called Takahashi when the month and the day are equal as numbers. For example, 5-5 is Takahashi.
How many days from 2018-1-1 through 2018-a-b are Takahashi?
Constraints
* a is an integer between 1 and 12 (inclusive).
* b is an integer between 1 and 31 (inclusive).
* 2018-a-b is a valid date in Gregorian calendar.
Input
Input is given from Standard Input in the following format:
a b
Output
Print the number of days from 2018-1-1 through 2018-a-b that are Takahashi.
Examples
Input
5 5
Output
5
Input
2 1
Output
1
Input
11 30
Output
11
### Response
```cpp
#include<iostream>
using namespace std;
int main(){
int A,B;cin>>A>>B;
A<=B ? cout<<A<<endl:cout<<A-1<<endl;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Petya has equal wooden bars of length n. He wants to make a frame for two equal doors. Each frame has two vertical (left and right) sides of length a and one top side of length b. A solid (i.e. continuous without breaks) piece of bar is needed for each side.
Determine a minimal number of wooden bars which are needed to make the frames for two doors. Petya can cut the wooden bars into any parts, but each side of each door should be a solid piece of a wooden bar (or a whole wooden bar).
Input
The first line contains a single integer n (1 ≤ n ≤ 1 000) — the length of each wooden bar.
The second line contains a single integer a (1 ≤ a ≤ n) — the length of the vertical (left and right) sides of a door frame.
The third line contains a single integer b (1 ≤ b ≤ n) — the length of the upper side of a door frame.
Output
Print the minimal number of wooden bars with length n which are needed to make the frames for two doors.
Examples
Input
8
1
2
Output
1
Input
5
3
4
Output
6
Input
6
4
2
Output
4
Input
20
5
6
Output
2
Note
In the first example one wooden bar is enough, since the total length of all six sides of the frames for two doors is 8.
In the second example 6 wooden bars is enough, because for each side of the frames the new wooden bar is needed.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 105 + 777, maxd = 1e8;
const long long mod = 1e9 + 7;
const int INF = 0x7f7f7f7f;
int n, a, b;
int m[7];
int main() {
scanf("%d %d %d", &n, &a, &b);
m[0] = m[1] = b;
m[2] = m[3] = m[4] = m[5] = a;
sort(m, m + 6);
int ans = 6;
do {
int sum = n, i = 0, t = 1;
for (int i = 0; i < 6; ++i) {
if (sum < m[i]) {
t++;
sum = n - m[i];
} else
sum -= m[i];
}
ans = min(ans, t);
} while (next_permutation(m, m + 6));
printf("%d", ans);
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Jack has become a soldier now. Unfortunately, he has trouble with the drill. Instead of marching beginning with the left foot and then changing legs with each step, as ordered, he keeps repeating a sequence of steps, in which he sometimes makes the wrong steps or — horror of horrors! — stops for a while. For example, if Jack uses the sequence 'right, left, break', when the sergeant yells: 'Left! Right! Left! Right! Left! Right!', Jack first makes a step with the right foot, then one with the left foot, then he is confused and stops for a moment, then again - this time according to the order - starts with the right foot, then uses the left foot, then - to the sergeant's irritation - he stops to catch his breath, to incorrectly start with the right foot again... Marching this way, Jack will make the step that he is supposed to in the given moment in only one third of cases.
When the officers convinced him he should do something about it, Jack decided to modify the basic sequence of steps that he repeats. However, in order not to get too tired, he has decided that the only thing he'll do is adding any number of breaks in any positions of the original sequence (a break corresponds to stopping for the duration of one step). Of course, Jack can't make a step on the same foot twice in a row, if there is no pause between these steps. It is, however, not impossible that the sequence of steps he used so far is incorrect (it would explain a lot, actually).
Help Private Jack! Given the sequence of steps he keeps repeating, calculate the maximal percentage of time that he can spend marching correctly after adding some breaks to his scheme.
Input
The first line of input contains a sequence consisting only of characters 'L', 'R' and 'X', where 'L' corresponds to a step with the left foot, 'R' — with the right foot, and 'X' — to a break. The length of the sequence will not exceed 106.
Output
Output the maximum percentage of time that Jack can spend marching correctly, rounded down to exactly six digits after the decimal point.
Examples
Input
X
Output
0.000000
Input
LXRR
Output
50.000000
Note
In the second example, if we add two breaks to receive LXXRXR, Jack will march: LXXRXRLXXRXRL... instead of LRLRLRLRLRLRL... and will make the correct step in half the cases. If we didn't add any breaks, the sequence would be incorrect — Jack can't step on his right foot twice in a row.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 2e6 + 10;
char c[N], s[N];
double f[N][2];
int m = 0;
inline bool check(double mid) {
for (register int i = 1; i <= m; i++) {
f[i][0] = f[i][1] = INT_MIN;
}
f[0][0] = 0;
f[0][1] = -mid;
for (register int i = 1; i <= m; i++) {
if (s[i] == 'L') {
f[i][1] = max(f[i][1], f[i - 1][0] + 1 - mid);
} else {
f[i][1] = max(f[i][1], f[i - 1][0] - mid);
}
if (s[i] == 'R') {
f[i][0] = max(f[i][0], f[i - 1][1] + 1 - mid);
} else {
f[i][0] = max(f[i][0], f[i - 1][1] - mid);
}
f[i][1] = max(f[i][1], f[i][0] - mid);
f[i][0] = max(f[i][0], f[i][1] - mid);
}
if (f[m][0] > 0) {
return 1;
} else {
return 0;
}
}
signed main() {
scanf("%s", c + 1);
int n = strlen(c + 1);
if (c[1] == c[n] && c[1] == 'R') {
m++;
s[m] = 'X';
}
for (register int i = 1; i <= n; i++) {
m++;
s[m] = c[i];
if (i != n && c[i] != 'X' && c[i + 1] != 'X' && c[i] == c[i + 1]) {
m++;
s[m] = 'X';
}
}
if (s[1] != 'X' && s[m] == s[1] && s[m] == 'L') {
m++;
s[m] = 'X';
}
double l = 0, r = 1;
double ans = 0;
while (l <= r - 1e-9) {
double mid = (l + r) / 2;
if (check(mid)) {
l = mid;
} else {
r = mid;
}
}
int count = (l + 1e-9) * 1e8;
printf("%d.%.06d", count / 1000000, count % 1000000);
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
You are given two positive integer numbers x and y. An array F is called an y-factorization of x iff the following conditions are met:
* There are y elements in F, and all of them are integer numbers;
* <image>.
You have to count the number of pairwise distinct arrays that are y-factorizations of x. Two arrays A and B are considered different iff there exists at least one index i (1 ≤ i ≤ y) such that Ai ≠ Bi. Since the answer can be very large, print it modulo 109 + 7.
Input
The first line contains one integer q (1 ≤ q ≤ 105) — the number of testcases to solve.
Then q lines follow, each containing two integers xi and yi (1 ≤ xi, yi ≤ 106). Each of these lines represents a testcase.
Output
Print q integers. i-th integer has to be equal to the number of yi-factorizations of xi modulo 109 + 7.
Example
Input
2
6 3
4 2
Output
36
6
Note
In the second testcase of the example there are six y-factorizations:
* { - 4, - 1};
* { - 2, - 2};
* { - 1, - 4};
* {1, 4};
* {2, 2};
* {4, 1}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
long long fac[2000005];
long long fastpow(long long base, long long ex) {
long long ret = 1;
while (ex) {
if (ex % 2) {
ret *= base;
ret %= mod;
ex--;
}
base *= base;
base %= mod;
ex /= 2;
}
return ret;
}
long long Comb(long long n, long long r) {
long long ret = fac[n];
ret *= fastpow(fac[r], mod - 2);
ret %= mod;
ret *= fastpow(fac[n - r], mod - 2);
ret %= mod;
return ret;
}
void solve(int tt) {
long long n, m;
cin >> n >> m;
long long ans = 1;
long long temp = n;
for (int i = 2; i * i <= temp; i++) {
long long counter = 0;
while (n % i == 0) {
n /= i;
counter++;
}
if (counter) {
ans *= Comb(counter + m - 1, m - 1);
ans %= mod;
}
}
if (n > 1) {
ans *= (Comb(m, m - 1));
ans %= mod;
}
ans *= fastpow(2, m - 1);
ans %= mod;
cout << ans << "\n";
}
int main() {
ios::sync_with_stdio(NULL);
cin.tie(NULL);
cout.tie(NULL);
fac[0] = 1;
for (long long(i) = (1); (i) < (2e6 + 4); (i)++) {
fac[i] = fac[i - 1] * i;
fac[i] %= mod;
}
int tc;
tc = 1;
cin >> tc;
for (long long(tt) = (1); (tt) < (tc + 1); (tt)++) {
solve(tt);
}
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference is maximal possible!
Your task is to write a program which calculates two things:
1. The maximum beauty difference of flowers that Pashmak can give to Parmida.
2. The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way.
Input
The first line of the input contains n (2 ≤ n ≤ 2·105). In the next line there are n space-separated integers b1, b2, ..., bn (1 ≤ bi ≤ 109).
Output
The only line of output should contain two integers. The maximum beauty difference and the number of ways this may happen, respectively.
Examples
Input
2
1 2
Output
1 1
Input
3
1 4 5
Output
4 1
Input
5
3 1 2 3 1
Output
2 4
Note
In the third sample the maximum beauty difference is 2 and there are 4 ways to do this:
1. choosing the first and the second flowers;
2. choosing the first and the fifth flowers;
3. choosing the fourth and the second flowers;
4. choosing the fourth and the fifth flowers.
### Response
```cpp
#include <bits/stdc++.h>
int main() {
long long i, n, *b, w, cmax = 0, cmin = 0, max, min;
scanf("%lld", &n);
b = (long long *)malloc(n * sizeof(long long));
for (i = 0; i < n; i++) {
scanf("%lld", &b[i]);
if (i == 0)
max = min = b[i];
else if (b[i] > max)
max = b[i];
else if (b[i] < min)
min = b[i];
}
if (max == min)
w = n * (n - 1) / 2;
else {
for (i = 0; i < n; i++) {
if (b[i] == max)
cmax++;
else if (b[i] == min)
cmin++;
}
w = cmax * cmin;
}
printf("%lld %lld", max - min, w);
free(b);
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is erased from the tree.
Monocarp has given you a list of n - 1 pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
Input
The first line contains one integer n (2 ≤ n ≤ 1 000) — the number of vertices in the tree.
Each of the next n-1 lines contains two integers a_i and b_i each (1 ≤ a_i < b_i ≤ n) — the maximal indices of vertices in the components formed if the i-th edge is removed.
Output
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next n - 1 lines. Each of the last n - 1 lines should contain two integers x_i and y_i (1 ≤ x_i, y_i ≤ n) — vertices connected by an edge.
Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
Examples
Input
4
3 4
1 4
3 4
Output
YES
1 3
3 2
2 4
Input
3
1 3
1 3
Output
NO
Input
3
1 2
2 3
Output
NO
Note
Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline long long power(long long a, long long b) {
long long x = 1;
a = a % 1000000007ULL;
while (b) {
if (b & 1) x = (x * a) % 1000000007ULL;
a = (a * a) % 1000000007ULL;
b >>= 1;
}
return x;
}
inline long long inv(long long a) { return power(a, 1000000007ULL - 2); }
long long gcd(long long a, long long b) { return a ? gcd(b % a, a) : b; }
const int N = 1e5 + 5;
queue<int> unused;
int n;
int cnt[1005];
map<int, pair<int, int> > mpp;
vector<int> adj[N];
int main() {
ios_base::sync_with_stdio(false);
cin >> n;
int u, v;
for (int i = 1; i < n; i++) {
cin >> u >> v;
adj[u].push_back(i);
adj[v].push_back(i);
cnt[u]++;
cnt[v]++;
}
for (int i = 1; i < n; i++) {
if (cnt[i] == 0)
unused.push(i);
else {
int v = i;
int tmp = cnt[i];
if (unused.size() < tmp - 1) {
cout << "NO\n";
return 0;
}
int par = n;
for (auto it : adj[i]) {
if (cnt[i] == 1) {
cnt[i]--;
mpp[it] = make_pair(par, i);
break;
}
int uu = unused.front();
unused.pop();
mpp[it] = make_pair(par, uu);
par = uu;
cnt[i]--;
}
}
}
cout << "YES\n";
for (int i = 1; i < n; i++)
cout << mpp[i].first << " " << mpp[i].second << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Little Maxim loves interesting problems. He decided to share one such problem with you.
Initially there is an array a, consisting of n zeroes. The elements of the array are indexed, starting from 1. Then follow queries to change array a. Each query is characterized by two integers vi, ti. In the answer to the query we should make the vi-th array element equal ti (avi = ti; 1 ≤ vi ≤ n).
Maxim thinks that some pairs of integers (x, y) are good and some are not. Maxim thinks that array a, consisting of n integers, is lucky, if for all integer i, (1 ≤ i ≤ n - 1) the pair of integers (ai, ai + 1) — is good. Note that the order of numbers in the pairs is important, that is, specifically, (1, 2) ≠ (2, 1).
After each query to change array a Maxim wants to know, how many ways there are to replace all zeroes in array a with integers from one to three so as to make the resulting array (without zeroes) lucky. Of course, distinct zeroes can be replaced by distinct integers.
Maxim told you the sequence of queries and all pairs of integers he considers lucky. Help Maxim, solve this problem for him.
Input
The first line contains integers n and m (1 ≤ n, m ≤ 77777) — the number of elements in the array and the number of commands.
The next three lines contain matrix w, consisting only of zeroes and ones; the j-th number in the i-th of these lines — wi, j. If wi, j = 1 (1 ≤ i, j ≤ 3), then pair (i, j) is good, otherwise it is not good. Matrix does not have to be symmetric relative to the main diagonal.
Next m lines contain pairs of integers vi, ti (1 ≤ vi ≤ n, 0 ≤ ti ≤ 3) — the queries to change the array.
Output
Print m integers — the i-th number should equal to the number of ways to replace all zeroes in array a (changed after the i-th query) by integers from one to three so as to make the resulting array (without zeroes) lucky. Separate the numbers by whitespaces. As the answers can be rather large, print the remainder from dividing them by 777777777.
Examples
Input
3 10
1 1 0
1 0 0
1 1 1
1 1
1 3
2 2
3 0
2 1
3 0
3 1
2 0
3 1
1 0
Output
3
6
1
1
2
2
1
3
3
6
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3fffffff;
const int SINF = 0x7fffffff;
const long long LINF = 0x3fffffffffffffff;
const long long SLINF = 0x7fffffffffffffff;
const int MAXN = 80007;
const int MAX = 3;
const int MOD = 777777777;
const int MAXS = MAXN * 4;
const int MAXL = 131072;
const int TP = 4;
struct mT {
mT() { clear(); }
void clear() { memset(a, 0, sizeof(a)); }
void setunit() {
clear();
for (int i = 0; i < MAX; ++i) a[i][i] = 1;
}
mT operator*(const mT &x) const {
mT ans;
for (int i = 0; i < MAX; ++i) {
for (int j = 0; j < MAX; ++j) {
for (int k = 0; k < MAX; ++k) ans.a[i][j] += a[i][k] * x.a[k][j];
ans.a[i][j] %= MOD;
}
}
return ans;
}
void operator*=(const mT &x) { (*this) = (*this) * x; }
long long a[MAX][MAX];
};
class stT {
public:
stT() {
for (int i = 0; i < MAXS; ++i) data[i].setunit();
}
void upd(int p, mT &x) {
p += MAXL - 1;
data[p] = x;
for (p >>= 1; p; p >>= 1) data[p] = data[p << 1 | 1] * data[p << 1];
}
mT query() { return data[1]; }
private:
mT data[MAXS];
} st;
int n, m, fp;
mT mat[TP];
int v, t;
void init();
void input();
void inputq();
void work();
int main() {
init();
input();
work();
}
void init() { ios::sync_with_stdio(false); }
void input() {
scanf("%d%d", &n, &m);
for (int i = 0; i < MAX; ++i)
for (int j = 0; j < MAX; ++j) scanf("%d", &mat[0].a[j][i]);
}
void inputq() { scanf("%d%d", &v, &t); }
void work() {
for (int i = 1; i < TP; ++i) {
for (int j = 0; j < MAX; ++j)
for (int k = 0; k < MAX; ++k)
if (j == i - 1) mat[i].a[j][k] = mat[0].a[j][k];
}
for (int i = 1; i < n; ++i) st.upd(i, mat[0]);
fp = 0;
int cc;
mT now;
for (int i = 0; i < m; ++i) {
inputq();
--v;
if (v) {
st.upd(v, mat[t]);
} else
fp = t;
now.clear();
if (fp)
now.a[fp - 1][0] = 1;
else
for (int i = 0; i < MAX; ++i) now.a[i][0] = 1;
now = st.query() * now;
cc = 0;
for (int i = 0; i < MAX; ++i) (cc += now.a[i][0]) %= MOD;
printf("%d\n", cc);
}
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
You are given two integer sequences S and T of length N and M, respectively, both consisting of integers between 1 and 10^5 (inclusive).
In how many pairs of a subsequence of S and a subsequence of T do the two subsequences are the same in content?
Here the subsequence of A is a sequence obtained by removing zero or more elements from A and concatenating the remaining elements without changing the order.
For both S and T, we distinguish two subsequences if the sets of the indices of the removed elements are different, even if the subsequences are the same in content.
Since the answer can be tremendous, print the number modulo 10^9+7.
Constraints
* 1 \leq N, M \leq 2 \times 10^3
* The length of S is N.
* The length of T is M.
* 1 \leq S_i, T_i \leq 10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
S_1 S_2 ... S_{N-1} S_{N}
T_1 T_2 ... T_{M-1} T_{M}
Output
Print the number of pairs of a subsequence of S and a subsequence of T such that the subsequences are the same in content, modulo 10^9+7.
Examples
Input
2 2
1 3
3 1
Output
3
Input
2 2
1 1
1 1
Output
6
Input
4 4
3 4 5 6
3 4 5 6
Output
16
Input
10 9
9 6 5 7 5 9 8 5 6 7
8 6 8 5 5 7 9 9 7
Output
191
Input
20 20
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
846527861
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
long long dp[2010][2010];
int s[2010];
int t[2010];
int main()
{
int n, m;
cin >> n >> m;
for (int i=1;i<=n;i++)
cin >> s[i];
for (int i=1;i<=m;i++)
cin >> t[i];
for (int i=0;i<=n;i++)
dp[i][0]=1;
for (int j=0;j<=m;j++)
dp[0][j]=1;
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++){
dp[i][j]=dp[i][j-1]+dp[i-1][j]-dp[i-1][j-1];
if (s[i]==t[j]) dp[i][j]+=dp[i-1][j-1];
dp[i][j]=(dp[i][j]+1000000007)%1000000007;
}
cout << dp[n][m];
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
The only difference between easy and hard versions is constraints.
Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.
There are n voters, and two ways to convince each of them to vote for you. The first way to convince the i-th voter is to pay him p_i coins. The second way is to make m_i other voters vote for you, and the i-th voter will vote for free.
Moreover, the process of such voting takes place in several steps. For example, if there are five voters with m_1 = 1, m_2 = 2, m_3 = 2, m_4 = 4, m_5 = 5, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: {5} → {1, 5} → {1, 2, 3, 5} → {1, 2, 3, 4, 5}.
Calculate the minimum number of coins you have to spend so that everyone votes for you.
Input
The first line contains one integer t (1 ≤ t ≤ 5000) — the number of test cases.
The first line of each test case contains one integer n (1 ≤ n ≤ 5000) — the number of voters.
The next n lines contains the description of voters. i-th line contains two integers m_i and p_i (1 ≤ p_i ≤ 10^9, 0 ≤ m_i < n).
It is guaranteed that the sum of all n over all test cases does not exceed 5000.
Output
For each test case print one integer — the minimum number of coins you have to spend so that everyone votes for you.
Example
Input
3
3
1 5
2 10
2 8
7
0 1
3 1
1 1
6 1
1 1
4 1
4 1
6
2 6
2 3
2 8
2 7
4 4
5 5
Output
8
0
7
Note
In the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: {3} → {1, 3} → {1, 2, 3}.
In the second example you don't need to buy votes. The set of people voting for you will change as follows: {1} → {1, 3, 5} → {1, 2, 3, 5} → {1, 2, 3, 5, 6, 7} → {1, 2, 3, 4, 5, 6, 7}.
In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: {2, 5} → {1, 2, 3, 4, 5} → {1, 2, 3, 4, 5, 6}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int NR = 2e5 + 5;
vector<int> g[NR];
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n, x, y;
scanf("%d", &n);
for (int i = 0; i <= n; i++) g[i].clear();
for (int i = 1; i <= n; i++) {
scanf("%d%d", &x, &y);
g[x].push_back(y);
}
long long ans = 0;
priority_queue<int, vector<int>, greater<int> > q;
for (int i = n - 1; i >= 0; i--) {
for (unsigned int j = 0; j < g[i].size(); j++) {
q.push(g[i][j]);
}
while (i > n - (int)q.size()) {
ans += 1ll * q.top();
q.pop();
}
}
printf("%lld\n", ans);
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
You are given a permutation p_1, p_2, ..., p_n. A permutation of length n is a sequence such that each integer between 1 and n occurs exactly once in the sequence.
Find the number of pairs of indices (l, r) (1 ≤ l ≤ r ≤ n) such that the value of the median of p_l, p_{l+1}, ..., p_r is exactly the given number m.
The median of a sequence is the value of the element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used.
For example, if a=[4, 2, 7, 5] then its median is 4 since after sorting the sequence, it will look like [2, 4, 5, 7] and the left of two middle elements is equal to 4. The median of [7, 1, 2, 9, 6] equals 6 since after sorting, the value 6 will be in the middle of the sequence.
Write a program to find the number of pairs of indices (l, r) (1 ≤ l ≤ r ≤ n) such that the value of the median of p_l, p_{l+1}, ..., p_r is exactly the given number m.
Input
The first line contains integers n and m (1 ≤ n ≤ 2⋅10^5, 1 ≤ m ≤ n) — the length of the given sequence and the required value of the median.
The second line contains a permutation p_1, p_2, ..., p_n (1 ≤ p_i ≤ n). Each integer between 1 and n occurs in p exactly once.
Output
Print the required number.
Examples
Input
5 4
2 4 5 3 1
Output
4
Input
5 5
1 2 3 4 5
Output
1
Input
15 8
1 15 2 14 3 13 4 8 12 5 11 6 10 7 9
Output
48
Note
In the first example, the suitable pairs of indices are: (1, 3), (2, 2), (2, 3) and (2, 4).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int v[200001];
int main() {
long long int n, m, mi;
vector<long long int> vleft;
vector<long long int> vright(1, 0);
bool swapou = false;
cin >> n >> m;
for (int i = 0; i < n; i++) {
int a, vai = 1;
cin >> a;
if (a > m)
vai = 1;
else
vai = -1;
v[i] = a;
if (a == m) {
swapou = true;
} else if (swapou) {
vright.push_back(vai);
} else {
vleft.push_back(vai);
}
}
vleft.push_back(0);
reverse(vleft.begin(), vleft.end());
for (int i = 1; i < vleft.size(); i++) {
vleft[i] += vleft[i - 1];
}
for (int i = 1; i < vright.size(); i++) {
vright[i] += vright[i - 1];
}
sort(vleft.begin(), vleft.end());
map<long long int, long long int> M;
for (long long int x : vright) {
M[x]++;
}
long long int cnt = 0;
for (long long int x : vleft) {
cnt += M[-x] + M[1ll - x];
}
cout << cnt << "\n";
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.
Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.
A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
Input
The first line contains string a, and the second line — string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
Output
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
Examples
Input
abcd
defgh
Output
5
Input
a
a
Output
-1
Note
In the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
char a[800000], b[800000];
int t = 0;
cin >> a >> b;
if (strlen(a) > strlen(b))
cout << strlen(a);
else if (strlen(a) < strlen(b))
cout << strlen(b);
else {
for (int i = 0; i < strlen(a); i++) {
if (a[i] != b[i]) {
t = 1;
break;
}
}
if (t == 1)
cout << strlen(a);
else
cout << -1;
}
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
The Hedgehog likes to give presents to his friend, but no less he likes to receive them.
Having received another present today, the Hedgehog suddenly understood that he has no place to put it as there was no room left on the special shelf in the cupboard. He will have to choose another shelf, but which one should he choose, how large should it be?
In order to get to know this, the Hedgehog asks you to write him a program that will count the estimated number of presents that he will receive during the following N days. Besides, he is guided by the principle:
* on each holiday day the Hedgehog will necessarily receive a present,
* he receives presents at least every K days (i.e., if he received a present on the i-th day, he will receive the next present no later than on the i + K-th day).
For the given N and K, as well as the list of holidays among the following N days count the minimal number of presents that could be given to the Hedgehog. The number of today's day is zero, and you should regard today's present as already given (i.e., you shouldn't count it in the answer).
Input
The first line contains integers N and K (1 ≤ N ≤ 365, 1 ≤ K ≤ N).
The second line contains a number C which represents the number of holidays (0 ≤ C ≤ N). Then in the same line follow C numbers ranging from 1 to N which are the numbers of holiday days. The numbers are given in the increasing order, without repeating numbers among them.
Output
Print a single number — the minimal number of presents the Hedgehog will receive over the following N days.
Examples
Input
5 2
1 3
Output
3
Input
10 1
3 6 7 8
Output
10
### Response
```cpp
#include <bits/stdc++.h>
int main(void) {
int n, k, c;
static char days[366];
int i;
int count;
int end;
scanf("%d %d", &n, &k);
memset(days, 0, n + 1);
scanf("%d", &c);
for (i = 0; i < c; i++) {
int t;
scanf("%d", &t);
days[t] = 1;
}
end = k;
for (i = 1, count = 0; i <= n; i++) {
if (days[i] || i == end) {
count++;
end = i + k;
}
}
printf("%d\n", count);
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare.
In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) mod 2.
Euclid can sum any subset of S and archive another m-dimensional vector over Z_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.
Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1.
Help Euclid and calculate |T|, the number of m-dimensional vectors over Z_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input.
Consider sets A and B such that |A| = |B|. Let a_1, a_2, ... a_{|A|} and b_1, b_2, ... b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i.
Input
In the first line of input, there are two integers n, m (1 ≤ n, m ≤ 5 ⋅ 10^5) denoting the number of vectors in S and the number of dimensions.
Next n lines contain the description of the vectors in S. In each of them there is an integer k (1 ≤ k ≤ 2) and then follow k distinct integers x_1, ... x_k (1 ≤ x_i ≤ m). This encodes an m-dimensional vector having 1s on coordinates x_1, ... x_k and 0s on the rest of them.
Among the n vectors, no two are the same.
Output
In the first line, output two integers: remainder modulo 10^9+7 of |T| and |S'|. In the second line, output |S'| numbers, indices of the elements of S' in ascending order. The elements of S are numbered from 1 in the order they are given in the input.
Examples
Input
3 2
1 1
1 2
2 2 1
Output
4 2
1 2
Input
2 3
2 1 3
2 1 2
Output
4 2
1 2
Input
3 5
2 1 2
1 3
1 4
Output
8 3
1 2 3
Note
In the first example we are given three vectors:
* 10
* 01
* 11
It turns out that we can represent all vectors from our 2-dimensional space using these vectors:
* 00 is a sum of the empty subset of above vectors;
* 01 = 11 + 10, is a sum of the first and third vector;
* 10 = 10, is just the first vector;
* 11 = 10 + 01, is a sum of the first and the second vector.
Hence, T = \{00, 01, 10, 11\}. We can choose any two of the three vectors from S and still be able to obtain all the vectors in T. In such a case, we choose the two vectors which appear first in the input. Since we cannot obtain all vectors in T using only a single vector from S, |S'| = 2 and S' = \{10, 01\} (indices 1 and 2), as set \{1, 2 \} is lexicographically the smallest. We can represent all vectors from T, using only vectors from S', as shown below:
* 00 is a sum of the empty subset;
* 01 = 01 is just the second vector;
* 10 = 10 is just the first vector;
* 11 = 10 + 01 is a sum of the first and the second vector.
### Response
```cpp
#include <bits/stdc++.h>
//#include <bits/extc++.h>
#define ll long long
#define ull unsigned ll
#define endl "\n"
#define pb push_back
#define ms(v,x) memset(v,x,sizeof(v))
#define ff first
#define ss second
#define td(v) v.begin(),v.end()
#define rep(i,a,n) for (int i=(a);i<(n);i++)
#define per(i,a,n) for (int i=(n-1);i>=a;i--)
#define trav(a, x) for(auto& a : x)
#define re(v) {for(auto &_re : v) cin >> _re;}
#define pr(v) {for(auto _pr : v) cout << _pr << " "; cout << endl;}
//#define sz(x) (int)(x).size()
#define all(x) x.begin(), x.end()
#define pii pair<int,int>
#define pll pair<ll,ll>
#define vi vector<int>
#define vl vector<ll>
#define eb emplace_back
using namespace std;
using vvi = vector<vi>;
using vvl = vector<vl>;
const ll M = 1e9 + 7;
//const ll M = 998244353;
//const ll M = 1e9 + 9;
//const ll M = 1e6;
#define tiii tuple<int,int,int>
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll binpow(ll a, ll b){
ll ret = 1;
while(b){
if(b & 1){
ret = ret * a % M;
}
a = a * a % M;
b >>= 1;
}
return ret;
}
void solve(){
int n, m;
cin >> n >> m;
vi basis(m + 1);
vi nxt(m + 1);
iota(td(nxt), 0);
function<int (int)> f = [&](int i){
if(nxt[i] == i or nxt[i] == -1) return nxt[i];
return nxt[i] = f(nxt[i]);
};
vector<vector<int>> vecs(n);
vector<int> s;
for(int i=0;i<n;i++){
int k; cin >> k;
vecs[i].resize(k);
re(vecs[i]);
sort(td(vecs[i]));
// check if is represented
int a = f(vecs[i][0]);
int b = -1;
if(k > 1) b = f(vecs[i][1]);
if(a == b){
continue;
}
if(a == -1){
if(b == -1) continue;
basis[b] = 1;
s.eb(i);
nxt[b] = -1;
}
else{
basis[a] = i;
s.eb(i);
nxt[a] = b;
}
}
cout << binpow(2, s.size()) << " " << s.size() << endl;
for(int x : s) cout << x + 1 << " ";
cout << endl;
}
int32_t main(){
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
//freopen(".in", "r", stdin);
//freopen(".out", "w", stdout);
int t = 1;
//cin >> t;
while(t--){
solve();
}
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k.
Please, help Kate to find I_2, I_3, ..., I_n.
Input
The first and only line in the input consists of only one integer n (2≤ n ≤ 5 ⋅ 10^5) — the size of the given set S.
Output
Output contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.
Examples
Input
2
Output
1
Input
3
Output
1 1
Note
First sample: answer is 1, because gcd(1, 2) = 1.
Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const double eps = 1e-2;
const int mod = 1e9 + 7;
const int maxn = 3e6 + 100;
const int maxm = maxn * 150;
const int inf = 0x3f3f3f3f;
const double pi = acos(-1.0);
int n, m;
int a[maxn];
int main() {
scanf("%d", &n);
int m = (int)sqrt(n + 0.9);
for (int i = 2; i <= n; i++) {
a[i] = 1;
for (int j = 2; j * j <= i; j++) {
if (i % j == 0) {
a[i] = i / j;
break;
}
}
}
for (int i = 2; i <= n; i++) a[i] == -1 ? 1 : i / a[i];
sort(a + 2, a + 1 + n);
for (int i = 2; i <= n; i++) {
printf("%d ", a[i]);
}
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Acacius is studying strings theory. Today he came with the following problem.
You are given a string s of length n consisting of lowercase English letters and question marks. It is possible to replace question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a resulting string exactly once?
Each question mark should be replaced with exactly one lowercase English letter. For example, string "a?b?c" can be transformed into strings "aabbc" and "azbzc", but can't be transformed into strings "aabc", "a?bbc" and "babbc".
Occurrence of a string t of length m in the string s of length n as a substring is a index i (1 ≤ i ≤ n - m + 1) such that string s[i..i+m-1] consisting of m consecutive symbols of s starting from i-th equals to string t. For example string "ababa" has two occurrences of a string "aba" as a substring with i = 1 and i = 3, but there are no occurrences of a string "aba" in the string "acba" as a substring.
Please help Acacius to check if it is possible to replace all question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a resulting string exactly once.
Input
First line of input contains an integer T (1 ≤ T ≤ 5000), number of test cases. T pairs of lines with test case descriptions follow.
The first line of a test case description contains a single integer n (7 ≤ n ≤ 50), length of a string s.
The second line of a test case description contains string s of length n consisting of lowercase English letters and question marks.
Output
For each test case output an answer for it.
In case if there is no way to replace question marks in string s with a lowercase English letters in such a way that there is exactly one occurrence of a string "abacaba" in the resulting string as a substring output "No".
Otherwise output "Yes" and in the next line output a resulting string consisting of n lowercase English letters. If there are multiple possible strings, output any.
You may print every letter in "Yes" and "No" in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answer).
Example
Input
6
7
abacaba
7
???????
11
aba?abacaba
11
abacaba?aba
15
asdf???f???qwer
11
abacabacaba
Output
Yes
abacaba
Yes
abacaba
Yes
abadabacaba
Yes
abacabadaba
No
No
Note
In first example there is exactly one occurrence of a string "abacaba" in the string "abacaba" as a substring.
In second example seven question marks can be replaced with any seven lowercase English letters and with "abacaba" in particular.
In sixth example there are two occurrences of a string "abacaba" as a substring.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const string target = "abacaba";
bool isok(string s) {
int cnt = 0;
for (int i = 0; i < s.size() - 6; i++)
if (s.substr(i, 7) == target) cnt++;
return cnt == 1;
}
void solve() {
int n;
cin >> n;
string s;
cin >> s;
string old = string(7, ' ');
for (int i = 0; i < n - 6; i++) {
bool ok = true;
for (int j = 0; j < 7; j++) {
old[j] = s[i + j];
if (s[i + j] == '?') s[i + j] = target[j];
}
if (isok(s)) {
for (int i = 0; i < n; i++)
if (s[i] == '?') s[i] = 'z';
puts("YES");
cout << s << endl;
return;
}
for (int j = 0; j < 7; j++) s[i + j] = old[j];
}
puts("NO");
}
int main() {
int tt;
cin >> tt;
while (tt--) solve();
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Slime has a sequence of positive integers a_1, a_2, …, a_n.
In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}.
In this problem, for the integer multiset s, the median of s is equal to the ⌊ (|s|+1)/(2)⌋-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5.
Slime wants Orac to make a_1 = a_2 = … = a_n = k using these operations.
Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times.
Input
The first line of the input is a single integer t: the number of queries.
The first line of each query contains two integers n\ (1≤ n≤ 100 000) and k\ (1≤ k≤ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1≤ a_i≤ 10^9)
The total sum of n is at most 100 000.
Output
The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase.
Example
Input
5
5 3
1 5 2 6 1
1 6
6
3 2
1 2 3
4 3
3 1 2 3
10 3
1 2 3 4 5 6 7 8 9 10
Output
no
yes
yes
no
yes
Note
In the first query, Orac can't turn all elements into 3.
In the second query, a_1=6 is already satisfied.
In the third query, Orac can select the complete array and turn all elements into 2.
In the fourth query, Orac can't turn all elements into 3.
In the fifth query, Orac can select [1,6] at first and then select [2,10].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long a[400005];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
long long test;
cin >> test;
while (test > 0) {
test--;
long long n, k;
cin >> n >> k;
set<long long> h;
for (int i = 0; i < n; i++) {
cin >> a[i];
h.insert(a[i]);
}
if (n == 1) {
if (k == a[0])
cout << "yes\n";
else
cout << "no\n";
continue;
}
if (h.count(k) == 0) {
cout << "no\n";
continue;
}
if (n == 2) {
if (a[0] >= k && a[1] >= k)
cout << "yes\n";
else
cout << "no\n";
continue;
}
bool yes = false;
for (int i = 0; i < n - 2; i++) {
int cnt = 0;
if (a[i] >= k) cnt++;
if (a[i + 1] >= k) cnt++;
if (a[i + 2] >= k) cnt++;
if (cnt >= 2) yes = true;
}
if (yes)
cout << "yes\n";
else
cout << "no\n";
}
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices.
A set of edges is called a matching if no two edges share an endpoint.
A set of vertices is called an independent set if no two vertices are connected with an edge.
Input
The first line contains a single integer T ≥ 1 — the number of graphs you need to process. The description of T graphs follows.
The first line of description of a single graph contains two integers n and m, where 3 ⋅ n is the number of vertices, and m is the number of edges in the graph (1 ≤ n ≤ 10^{5}, 0 ≤ m ≤ 5 ⋅ 10^{5}).
Each of the next m lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ 3 ⋅ n), meaning that there is an edge between vertices v_i and u_i.
It is guaranteed that there are no self-loops and no multiple edges in the graph.
It is guaranteed that the sum of all n over all graphs in a single test does not exceed 10^{5}, and the sum of all m over all graphs in a single test does not exceed 5 ⋅ 10^{5}.
Output
Print your answer for each of the T graphs. Output your answer for a single graph in the following format.
If you found a matching of size n, on the first line print "Matching" (without quotes), and on the second line print n integers — the indices of the edges in the matching. The edges are numbered from 1 to m in the input order.
If you found an independent set of size n, on the first line print "IndSet" (without quotes), and on the second line print n integers — the indices of the vertices in the independent set.
If there is no matching and no independent set of the specified size, print "Impossible" (without quotes).
You can print edges and vertices in any order.
If there are several solutions, print any. In particular, if there are both a matching of size n, and an independent set of size n, then you should print exactly one of such matchings or exactly one of such independent sets.
Example
Input
4
1 2
1 3
1 2
1 2
1 3
1 2
2 5
1 2
3 1
1 4
5 1
1 6
2 15
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
4 5
4 6
5 6
Output
Matching
2
IndSet
1
IndSet
2 4
Matching
1 15
Note
The first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer.
The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly n.
The fourth graph does not have an independent set of size 2, but there is a matching of size 2.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long int mod = 1e9 + 7;
const long double PI = acos(-1.0);
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long int T;
cin >> T;
while (T--) {
long long int n, m;
cin >> n >> m;
vector<long long int> ver(3 * n + 1, 0);
vector<pair<long long int, long long int>> edge(m);
for (long long int i = 0; i < m; i++) {
cin >> edge[i].first;
cin >> edge[i].second;
}
vector<long long int> ans1;
for (long long int i = 0; i < m; i++) {
if (ver[edge[i].first] == 0 && ver[edge[i].second] == 0) {
ans1.push_back(i + 1);
ver[edge[i].first] = 1;
ver[edge[i].second] = 1;
}
if (ans1.size() == n) break;
}
if (ans1.size() == n) {
cout << "Matching" << '\n';
for (auto i : ans1) cout << i << " ";
cout << '\n';
} else {
cout << "IndSet" << '\n';
long long int done = 0;
for (long long int i = 1; i < 3 * n + 1; i++) {
if (ver[i] == 0) {
done++;
cout << i << " ";
}
if (done == n) break;
}
cout << '\n';
}
}
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.
He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substring. For example, the strings "abc" and "abca" suit him, while the string "aba" doesn't. He also want the number of letters 'c' in his string to be as little as possible.
Input
The first line contains single integer n (1 ≤ n ≤ 2·105) — the length of the string.
Output
Print the string that satisfies all the constraints.
If there are multiple answers, print any of them.
Examples
Input
2
Output
aa
Input
3
Output
bba
Note
A palindrome is a sequence of characters which reads the same backward and forward.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int s = 0;
for (int i = 0; i < n; i++) {
if (s == 0) {
putchar('a');
s++;
} else if (s == 1) {
putchar('a');
s++;
} else if (s == 2) {
putchar('b');
s++;
} else {
putchar('b');
s = 0;
}
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Vasya is a regular participant at programming contests and is already experienced in finding important sentences in long statements. Of course, numbers constraints are important — factorization of a number less than 1000000 is easier than of a number less than 1000000000. However, sometimes it's hard to understand the number at the first glance. Could it be shortened? For example, instead of 1000000 you could write 10^{6}, instead of 1000000000 —10^{9}, instead of 1000000007 — 10^{9}+7.
Vasya decided that, to be concise, the notation should follow several rules:
* the notation should only consist of numbers, operations of addition ("+"), multiplication ("*") and exponentiation ("^"), in particular, the use of braces is forbidden;
* the use of several exponentiation operations in a row is forbidden, for example, writing "2^3^4" is unacceptable;
* the value of the resulting expression equals to the initial number;
* the notation should consist of the minimal amount of symbols.
Given n, find the equivalent concise notation for it.
Input
The only line contains a single integer n (1 ≤ n ≤ 10 000 000 000).
Output
Output a concise notation of the number n. If there are several concise notations, output any of them.
Examples
Input
2018
Output
2018
Input
1000000007
Output
10^9+7
Input
10000000000
Output
100^5
Input
2000000000
Output
2*10^9
Note
The third sample allows the answer 10^10 also of the length 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const bool debugger1 = 1;
const bool debugger2 = 0;
const bool debugger3 = 0;
const bool debugger4 = 0;
const bool debugger5 = 0;
const long long wielkosc = 1e5 + 90;
const long long maxlen = 7;
long long n;
long long p10[10];
map<long long, string> m;
set<long long> second[10];
template <class T>
string toString(T x) {
ostringstream sout;
sout << x;
return sout.str();
}
long long getlen(long long x) {
long long ans = 0;
while (x) {
x /= 10;
ans++;
}
return max(ans, (long long)1);
}
string daj(long long x) {
if (m.count(x)) return m[x];
return toString(x);
}
void uprosc(long long x, string str) {
if (x > n || str.length() >= getlen(x)) return;
if (m.count(x) && m[x].length() <= str.length()) return;
second[m[x].length()].erase(x);
m[x] = str;
second[str.length()].insert(x);
}
void pot10() {
p10[0] = 1;
for (int i = 1; i < 10; i++) p10[i] = 10 * p10[i - 1];
}
void zrob_potegi() {
for (long long x = 2; x * x <= n; x++) {
long long c = x * x;
long long akpot = 2;
while (c <= n) {
string temp = toString(x) + "^" + toString(akpot);
uprosc(c, temp);
c *= x;
akpot++;
}
}
}
void potrazypot() {
for (long long i = 1; i <= maxlen; i++) {
for (long long j = i; i + j + 1 <= maxlen; j++) {
for (auto x : second[i]) {
for (auto y : second[j]) {
uprosc(x * y, daj(x) + "*" + daj(y));
}
}
}
}
}
void potrazynum() {
for (long long i = 1; i + 2 <= maxlen; i++) {
for (long long x = 1; x < p10[maxlen - 1 - i]; x++) {
for (long long y : second[i]) {
uprosc(x * y, toString(x) + '*' + daj(y));
}
}
}
}
void pocz() {
zrob_potegi();
potrazypot();
potrazynum();
}
string ans;
void ustans(string second) {
if (ans.length() > second.length()) {
ans = second;
}
}
void dajodp() {
for (long long i = 1; i * 2 + 1 < ans.length(); i++) {
for (long long x = 1; x <= p10[i]; x++) {
ustans(daj(n - x) + "+" + daj(x));
if (n % x == 0) {
ustans(daj(n / x) + "*" + daj(x));
}
}
for (auto x : second[i]) {
ustans(daj(n - x) + "+" + daj(x));
if (n % x == 0) {
ustans(daj(n / x) + "*" + daj(x));
}
}
}
}
int main() {
pot10();
scanf("%lld", &n);
pocz();
ans = daj(n);
dajodp();
cout << ans;
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
There is a bus route as shown in Figure 1. There are 10 stops, each numbered 0-9. The bus turns back at stop 0, but the other side is a circulation route, which circulates in the order of 5 → 6 → 7 → 8 → 9 → 5 as shown in the figure.
<image>
For this bus route, create a program that inputs the stop to get on and the stop to get off, and outputs the number of the stop that goes from getting on to getting off.
However, you can take a two-way bus at stops 1-5, but we will take a bus that arrives at the stop on a shorter route. For example, if you are going from stop 4 to stop 2, take the bus going to the left and follow the route "4 → 3 → 2". Also, once you get on the bus, you will not get off the bus. The same stop is not designated as a boarding stop or a getting-off stop.
Input
Given multiple datasets. The first line gives the number of datasets n (n ≤ 20). For each dataset, the stop number to get on and the stop number to get off are given on one line separated by blanks.
Output
For each data set, output the list of passing stop numbers on one line separated by blanks.
Example
Input
2
2 4
4 2
Output
2 3 4
4 3 2
### Response
```cpp
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<cctype>
#include<complex>
#include<iostream>
#include<sstream>
#include<algorithm>
#include<functional>
#include<vector>
#include<string>
#include<stack>
#include<queue>
#include<map>
using namespace std;
const int dx[] = {1,0,-1,0},dy[] = {0,1,0,-1};
#define INF 999999
#define rep(i,j) for(int i=0;i<(j);++i)
#define reps(i,j,k) for(int i=j;i<k;++i)
typedef long long ll;
typedef unsigned long long ull;
int main(){
int n;
scanf("%d",&n);
int a[] = {0,1,2,3,4,5,6,7,8,9,5,4,3,2,1,0,1,2,3,4,5,6,7,8};
int b[] = {0,1,2,3,4,5};
rep(q,n){
int from,to;
bool f = false;
scanf("%d%d",&from,&to);
if(from < 6 && to < 6){
if(from > to){
int x = from;
while(1){
if(b[x] == to){
printf(" %d\n",to);
break;
}
if(f)printf(" ");
printf("%d",b[x]);
x--;
f = true;
}
}
else{
int x = from;
while(1){
if(b[x] == to){
printf(" %d\n",to);
break;
}
if(f)printf(" ");
printf("%d",b[x]);
x++;
f = true;
}
}
}
else{
int x = from;
while(1){
if(a[x] == to){
printf(" %d\n",to);
break;
}
if(f)printf(" ");
printf("%d",a[x]);
x++;
f = true;
}
}
}
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to <image>. Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it.
He painted a few lines, parallel to the sides of the hexagon. The lines split the hexagon into regular triangles with sides of 1 centimeter. Now Gerald wonders how many triangles he has got. But there were so many of them that Gerald lost the track of his counting. Help the boy count the triangles.
Input
The first and the single line of the input contains 6 space-separated integers a1, a2, a3, a4, a5 and a6 (1 ≤ ai ≤ 1000) — the lengths of the sides of the hexagons in centimeters in the clockwise order. It is guaranteed that the hexagon with the indicated properties and the exactly such sides exists.
Output
Print a single integer — the number of triangles with the sides of one 1 centimeter, into which the hexagon is split.
Examples
Input
1 1 1 1 1 1
Output
6
Input
1 2 1 2 1 2
Output
13
Note
This is what Gerald's hexagon looks like in the first sample:
<image>
And that's what it looks like in the second sample:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a, b, c, d, e, f, n_tringle;
cin >> a >> b >> c >> d >> e >> f;
n_tringle = (a + b + c) * (a + b + c) - (a * a + c * c + e * e);
cout << n_tringle << endl;
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Two players, A and B, play the game using cards with numbers from 0 to 9. First, the two arrange the given n cards face down in a horizontal row. After that, the two players turn their cards face up one by one from the left, and the owner of the card with the larger number takes the two cards. At this time, the sum of the numbers written on the two cards shall be the score of the player who took the card. However, if the same number is written on the two open cards, it is a draw and each player takes one of his own cards.
For example, consider the case where the hands of A and B are arranged as shown in the following input examples 1 to 3. However, the input file consists of n + 1 lines, the first line contains the number of cards n for each player, and the i + 1 line (i = 1, 2, ..., n) is A. The numbers on the i-th card from the left and the numbers on the i-th card from the left of B are written in this order, with a blank as the delimiter. That is, from the second row onward of the input file, the left column represents the sequence of A cards, and the right column represents the sequence of B cards. At this time, the scores of A and B after the end of the game are shown in the corresponding output examples, respectively.
Create a program that outputs the score of A and the score of B when the game corresponding to the input file ends on one line with a space as a delimiter in this order. However, n ≤ 10000.
Input example 1 | Input example 2 | Input example 3
--- | --- | ---
3 | 3 | 3
9 1 | 9 1 | 9 1
5 4 | 5 4 | 5 5
0 8 | 1 0 | 1 8
Output example 1 | Output example 2 | Output example 3
19 8 | 20 0 | 15 14
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each dataset, the score of A and the score of B are output on one line.
Input example
3
9 1
5 4
0 8
3
9 1
5 4
Ten
3
9 1
5 5
1 8
0
Output example
19 8
20 0
15 14
Insert a line break after the output of each dataset (after the score of B).
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
Example
Input
3
9 1
5 4
0 8
3
9 1
5 4
1 0
3
9 1
5 5
1 8
0
Output
19 8
20 0
15 14
### Response
```cpp
#include<cstdio>
int n;
int main(){
while(1){
int A,B,Aanswer=0,Banswer=0;
scanf("%d",&n);
if(n==0)return 0;
for(int i=0;i<n;i++){
scanf("%d %d",&A,&B);
if(A>B)Aanswer+=A+B;
else if(A<B)Banswer+=A+B;
else{
Aanswer+=A;
Banswer+=B;
}
}
printf("%d %d\n",Aanswer,Banswer);
}
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
There is a stack of N cards, each of which has a non-negative integer written on it. The integer written on the i-th card from the top is A_i.
Snuke will repeat the following operation until two cards remain:
* Choose three consecutive cards from the stack.
* Eat the middle card of the three.
* For each of the other two cards, replace the integer written on it by the sum of that integer and the integer written on the card eaten.
* Return the two cards to the original position in the stack, without swapping them.
Find the minimum possible sum of the integers written on the last two cards remaining.
Constraints
* 2 \leq N \leq 18
* 0 \leq A_i \leq 10^9 (1\leq i\leq N)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible sum of the integers written on the last two cards remaining.
Examples
Input
4
3 1 4 2
Output
16
Input
6
5 2 4 1 6 9
Output
51
Input
10
3 1 4 1 5 9 2 6 5 3
Output
115
### Response
```cpp
#include <iostream>
#include <algorithm>
#include <vector>
#include <tuple>
#include <functional>
#include <limits>
using namespace std;
int main(){
int N;
cin>>N;
vector<int64_t> A(N);
for(auto &a:A) cin>>a;
function<int64_t(int64_t,int64_t,int64_t,int64_t)> rec = [&](int64_t l, int64_t r, int64_t lx, int64_t rx){
if(r-l==1) return int64_t(0);
int64_t ret = numeric_limits<int64_t>::max();
for(int k=l+1;k<r;k++){
ret = min(ret, rec(l,k,lx,lx+rx)+rec(k,r,lx+rx,rx)+A[k]*(lx+rx));
}
return ret;
};
cout<<rec(0,N-1,1,1)+A[0]+A[N-1]<<endl;
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
The following sorting operation is repeated for the stacked blocks as shown in Fig. A.
1. Stack all the bottom blocks (white blocks in Figure a) on the right edge (the remaining blocks will automatically drop one step down, as shown in Figure b).
2. If there is a gap between the blocks, pack it to the left to eliminate the gap (from Fig. B to Fig. C).
For an integer k greater than or equal to 1, a number represented by k × (k + 1) / 2 (example: 1, 3, 6, 10, ...) is called a triangular number. If the total number of blocks is a triangular number, it is expected that if the above sorting is repeated, the height of the left end will be 1 and the total number will increase by 1 toward the right (Fig. D shows the total number). For 15).
<image>
When the first sequence of blocks is given, when the triangle of the block as explained above is created by the operation less than the predetermined number of times, create a program that outputs the minimum number of operations until the triangle is obtained. please.
input
The input consists of multiple datasets. The end of the input is indicated by a single zero line. Each dataset is given in the following format.
N
b1 b2 ... bN
Each dataset has two rows and represents the first sequence of blocks. N (1 ≤ N ≤ 100) indicates the number of blocks in the bottom row. bi (1 ≤ bi ≤ 10000) indicates the number of blocks stacked in the i-th position from the left. bi and bi + 1 are separated by a single space. The total number of blocks is 3 or more.
The number of datasets does not exceed 20.
output
For each data set, the number of sorting operations performed until the triangle is formed is output on one line. However, if a triangle cannot be created or the number of operations exceeds 10000, -1 is output.
Example
Input
6
1 4 1 3 2 4
5
1 2 3 4 5
10
1 1 1 1 1 1 1 1 1 1
9
1 1 1 1 1 1 1 1 1
12
1 4 1 3 2 4 3 3 2 1 2 2
1
5050
3
10000 10000 100
0
Output
24
0
10
-1
48
5049
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
while(cin >> n, n != 0){
vector<int> b(n);
for(int i = 0;i < n;i++){
cin >> b[i];
}
int cnt = 0;
while(1){
if(cnt == 10001){
break;
}
bool f = (b[0] == 1);
for(int i = 0;i < b.size()-1;i++){
f = (f && (b[i] == b[i+1]-1));
}
if(f) break;
vector<int> c;
for(int i = 0;i < b.size();i++){
if(b[i] - 1 > 0){
c.push_back(b[i]-1);
}
}
c.push_back(b.size());
b = c;
cnt++;
}
cout << (cnt == 10001 ? -1 : cnt) << endl;
}
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Example
Input
anagram
grandmother
Output
4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define for_(i,a,b) for(int i=(a);i<(b);++i)
#define for_rev(i,a,b) for(int i=(a);i>=(b);--i)
typedef unsigned long long ull;
const ull BASE = 1e9 + 7;
ull mul[4003];
string A, B;
int n, m;
bool check(int k) {
if (k == 0) return true;
vector< int > c(26, 0);
for_(i,0,k) c[A[i] - 'a']++;
ull h = 0;
for_(i,0,26) h = h + c[i] * mul[i];
unordered_set< ull > hash_set;
hash_set.insert(h);
auto hash_update = [&](int i, int add) {
h = h - c[i] * mul[i];
c[i] += add;
h = h + c[i] * mul[i];
};
for_(i,k,n) {
hash_update(A[i-k]-'a', -1);
hash_update(A[i]-'a', 1);
hash_set.insert(h);
}
c.assign(26, 0);
for_(i,0,k) c[B[i] - 'a']++;
h = 0;
for_(i,0,26) h = h + c[i] * mul[i];
if (hash_set.count(h)) return true;
for_(i,k,m) {
hash_update(B[i-k]-'a', -1);
hash_update(B[i]-'a', 1);
if (hash_set.count(h)) return true;
}
return false;
}
int main() {
cin >> A;
cin >> B;
n = A.size();
m = B.size();
mul[0] = 1;
for_(i,1,4003) mul[i] = mul[i-1] * BASE;
for_rev(i,min(n,m),0) {
if (check(i)) {
cout << i << endl;
break;
}
}
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
This is an interactive problem. In the interaction section below you will see the information about flushing the output.
In this problem, you will be playing a game with Hongcow. How lucky of you!
Hongcow has a hidden n by n matrix M. Let Mi, j denote the entry i-th row and j-th column of the matrix. The rows and columns are labeled from 1 to n.
The matrix entries are between 0 and 109. In addition, Mi, i = 0 for all valid i. Your task is to find the minimum value along each row, excluding diagonal elements. Formally, for each i, you must find <image>.
To do this, you can ask Hongcow some questions.
A question consists of giving Hongcow a subset of distinct indices {w1, w2, ..., wk}, with 1 ≤ k ≤ n. Hongcow will respond with n integers. The i-th integer will contain the minimum value of min1 ≤ j ≤ kMi, wj.
You may only ask Hongcow at most 20 questions — he thinks you only need that many questions answered.
When you are ready to answer, print out a single integer - 1 on its own line, then n integers on the next line. The i-th integer should be the minimum value in the i-th row of the matrix, excluding the i-th element. Do not forget to flush the final answer as well. Printing the answer does not count as asking a question.
You will get Wrong Answer verdict if
* Your question or answers are not in the format described in this statement.
* You ask strictly more than 20 questions.
* Your question contains duplicate indices.
* The value of k in your question does not lie in the range from 1 to n, inclusive.
* Your final answer is not correct.
You will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).
Input
The first line of input will contain a single integer n (2 ≤ n ≤ 1, 000).
Output
To print the final answer, print out the string -1 on its own line. Then, the next line should contain n integers. The i-th integer should be the minimum value of the i-th row of the matrix, excluding elements on the diagonal. Do not forget to flush your answer!
Interaction
To ask a question, print out a single integer k on its own line, denoting the size of your subset. Then, the next line should contain k integers w1, w2, ... wk. Note, you must flush your output to get a response.
Hongcow will respond by printing out a line with n integers. The i-th integer in this line represents the minimum value of Mi, wj where j is between 1 and k.
You may only ask a question at most 20 times, otherwise, you will get Wrong Answer.
To flush you can use (just after printing an integer and end-of-line):
* fflush(stdout) in C++;
* System.out.flush() in Java;
* stdout.flush() in Python;
* flush(output) in Pascal;
* See the documentation for other languages.
Hacking To hack someone, use the following format
n
M_{1,1} M_{1,2} ... M_{1,n}
M_{2,1} M_{2,2} ... M_{2,n}
...
M_{n,1} M_{n,2} ... M_{n,n}
Of course, contestant programs will not be able to see this input.
Examples
Input
3
0 0 0
2 7 0
0 0 4
3 0 8
0 5 4
Output
3
1 2 3
1
3
2
1 2
1
2
1
1
-1
2 5 4
Input
2
0 0
0 0
Output
1
2
1
1
-1
0 0
Note
In the first sample, Hongcow has the hidden matrix
[
[0, 3, 2],
[5, 0, 7],
[4, 8 ,0],
]
Here is a more readable version demonstrating the interaction. The column on the left represents Hongcow, while the column on the right represents the contestant.
3
3
1 2 3
0 0 0
1
3
2 7 0
2
1 2
0 0 4
1
2
3 0 8
1
1
0 5 4
-1
2 5 4
For the second sample, it is possible for off-diagonal elements of the matrix to be zero.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int main() {
ios::sync_with_stdio(0);
int n;
cin >> n;
vector<int> ans(n, INF);
for (int i = 0; (1 << i) <= n; ++i) {
vector<bool> bad(n);
int nr = 0;
for (int j = 0; j < n; ++j) {
if ((1 << i) & j) nr++, bad[j] = 1;
}
if (nr < 1) continue;
cout << nr << endl;
for (int j = 0; j < n; ++j) {
if ((1 << i) & j) cout << j + 1 << ' ';
}
cout << endl;
for (int j = 0, x; j < n; ++j) {
cin >> x;
if (!bad[j]) ans[j] = min(ans[j], x);
}
}
for (int i = 0; (1 << i) <= n; ++i) {
vector<bool> bad(n);
int nr = 0;
for (int j = 0; j < n; ++j) {
if (!((1 << i) & j)) nr++, bad[j] = 1;
}
if (nr < 1) continue;
cout << nr << endl;
for (int j = 0; j < n; ++j) {
if (!((1 << i) & j)) cout << j + 1 << ' ';
}
cout << endl;
for (int j = 0, x; j < n; ++j) {
cin >> x;
if (!bad[j]) ans[j] = min(ans[j], x);
}
}
cout << -1 << endl;
for (int i = 0; i < n; ++i) cout << ans[i] << ' ';
cout << endl;
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Recall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
A sequence a is a subsegment of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l, r], where l, r are two integers with 1 ≤ l ≤ r ≤ n. This indicates the subsegment where l-1 elements from the beginning and n-r elements from the end are deleted from the sequence.
For a permutation p_1, p_2, …, p_n, we define a framed segment as a subsegment [l,r] where max\\{p_l, p_{l+1}, ..., p_r\} - min\\{p_l, p_{l+1}, ..., p_r\} = r - l. For example, for the permutation (6, 7, 1, 8, 5, 3, 2, 4) some of its framed segments are: [1, 2], [5, 8], [6, 7], [3, 3], [8, 8]. In particular, a subsegment [i,i] is always a framed segments for any i between 1 and n, inclusive.
We define the happiness of a permutation p as the number of pairs (l, r) such that 1 ≤ l ≤ r ≤ n, and [l, r] is a framed segment. For example, the permutation [3, 1, 2] has happiness 5: all segments except [1, 2] are framed segments.
Given integers n and m, Jongwon wants to compute the sum of happiness for all permutations of length n, modulo the prime number m. Note that there exist n! (factorial of n) different permutations of length n.
Input
The only line contains two integers n and m (1 ≤ n ≤ 250 000, 10^8 ≤ m ≤ 10^9, m is prime).
Output
Print r (0 ≤ r < m), the sum of happiness for all permutations of length n, modulo a prime number m.
Examples
Input
1 993244853
Output
1
Input
2 993244853
Output
6
Input
3 993244853
Output
32
Input
2019 993244853
Output
923958830
Input
2020 437122297
Output
265955509
Note
For sample input n=3, let's consider all permutations of length 3:
* [1, 2, 3], all subsegments are framed segment. Happiness is 6.
* [1, 3, 2], all subsegments except [1, 2] are framed segment. Happiness is 5.
* [2, 1, 3], all subsegments except [2, 3] are framed segment. Happiness is 5.
* [2, 3, 1], all subsegments except [2, 3] are framed segment. Happiness is 5.
* [3, 1, 2], all subsegments except [1, 2] are framed segment. Happiness is 5.
* [3, 2, 1], all subsegments are framed segment. Happiness is 6.
Thus, the sum of happiness is 6+5+5+5+5+6 = 32.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long N = 3e5 + 11;
long long fact[N];
long long n, m;
void compute() {
fact[0] = 1;
for (long long i = 1; i < N; ++i) fact[i] = (fact[i - 1] * i) % m;
}
int32_t main() {
ios::sync_with_stdio(false);
cin >> n >> m;
compute();
long long ans = 0;
for (long long i = 1; i <= n; ++i) {
long long val = fact[i];
val = (val * (n - i + 1)) % m;
val = (val * (n - i + 1)) % m;
val = (val * fact[n - i]) % m;
ans = (ans + val) % m;
}
cout << ans;
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
There are n students at Berland State University. Every student has two skills, each measured as a number: ai — the programming skill and bi — the sports skill.
It is announced that an Olympiad in programming and sports will be held soon. That's why Berland State University should choose two teams: one to take part in the programming track and one to take part in the sports track.
There should be exactly p students in the programming team and exactly s students in the sports team. A student can't be a member of both teams.
The university management considers that the strength of the university on the Olympiad is equal to the sum of two values: the programming team strength and the sports team strength. The strength of a team is the sum of skills of its members in the corresponding area, so the strength of the programming team is the sum of all ai and the strength of the sports team is the sum of all bi over corresponding team members.
Help Berland State University to compose two teams to maximize the total strength of the university on the Olympiad.
Input
The first line contains three positive integer numbers n, p and s (2 ≤ n ≤ 3000, p + s ≤ n) — the number of students, the size of the programming team and the size of the sports team.
The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 3000), where ai is the programming skill of the i-th student.
The third line contains n positive integers b1, b2, ..., bn (1 ≤ bi ≤ 3000), where bi is the sports skill of the i-th student.
Output
In the first line, print the the maximum strength of the university on the Olympiad. In the second line, print p numbers — the members of the programming team. In the third line, print s numbers — the members of the sports team.
The students are numbered from 1 to n as they are given in the input. All numbers printed in the second and in the third lines should be distinct and can be printed in arbitrary order.
If there are multiple solutions, print any of them.
Examples
Input
5 2 2
1 3 4 5 2
5 3 2 1 4
Output
18
3 4
1 5
Input
4 2 2
10 8 8 3
10 7 9 4
Output
31
1 2
3 4
Input
5 3 1
5 2 5 1 7
6 3 1 6 3
Output
23
1 3 5
4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int max_N = 3000 + 10;
pair<int, pair<int, int> > t[max_N];
int dp[max_N][max_N], par[max_N][max_N], x[max_N];
bool cmp(pair<int, pair<int, int> > a, pair<int, pair<int, int> > b) {
return (a.first > b.first);
}
void pp(int i, int j) {
if (!i || j < 0) return;
if (par[i][j] == 1) {
x[t[i - 1].second.second] = 1;
pp(i - 1, j - 1);
} else if (par[i][j] == 2) {
x[t[i - 1].second.second] = 2;
pp(i - 1, j);
} else
pp(i - 1, j);
}
int main() {
ios::sync_with_stdio(false);
int n, p, s, a, b;
cin >> n >> p >> s;
for (int i = 0; i < n; i++) cin >> t[i].second.first;
for (int i = 0; i < n; i++) {
cin >> t[i].first;
t[i].second.second = i;
}
sort(t, t + n, cmp);
dp[0][0] = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= min(p, i + 1); j++) {
int tmp1 = (j) ? dp[i][j - 1] + t[i].second.first : 0;
int tmp2 = (i >= j) ? dp[i][j] : 0;
if (i >= j && i - j < s) tmp2 += t[i].first, par[i + 1][j] = 2;
if (tmp1 > tmp2)
dp[i + 1][j] = tmp1, par[i + 1][j] = 1;
else
dp[i + 1][j] = tmp2;
}
}
cout << dp[n][p] << endl;
pp(n, p);
for (int i = 0; i < n; i++)
if (x[i] == 1) cout << i + 1 << ' ';
cout << endl;
for (int i = 0; i < n; i++)
if (x[i] == 2) cout << i + 1 << ' ';
cout << endl;
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
It is Borya's eleventh birthday, and he has got a great present: n cards with numbers. The i-th card has the number ai written on it. Borya wants to put his cards in a row to get one greater number. For example, if Borya has cards with numbers 1, 31, and 12, and he puts them in a row in this order, he would get a number 13112.
He is only 11, but he already knows that there are n! ways to put his cards in a row. But today is a special day, so he is only interested in such ways that the resulting big number is divisible by eleven. So, the way from the previous paragraph is good, because 13112 = 1192 × 11, but if he puts the cards in the following order: 31, 1, 12, he would get a number 31112, it is not divisible by 11, so this way is not good for Borya. Help Borya to find out how many good ways to put the cards are there.
Borya considers all cards different, even if some of them contain the same number. For example, if Borya has two cards with 1 on it, there are two good ways.
Help Borya, find the number of good ways to put the cards. This number can be large, so output it modulo 998244353.
Input
Input data contains multiple test cases. The first line of the input data contains an integer t — the number of test cases (1 ≤ t ≤ 100). The descriptions of test cases follow.
Each test is described by two lines.
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of cards in Borya's present.
The second line contains n integers ai (1 ≤ ai ≤ 109) — numbers written on the cards.
It is guaranteed that the total number of cards in all tests of one input data doesn't exceed 2000.
Output
For each test case output one line: the number of ways to put the cards to the table so that the resulting big number was divisible by 11, print the number modulo 998244353.
Example
Input
4
2
1 1
3
1 31 12
3
12345 67 84
9
1 2 3 4 5 6 7 8 9
Output
2
2
2
31680
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long qpow(long long a, long long b, long long p) {
long long ans = 1;
while (b) {
if (b & 1) ans = ans * a % p;
a = a * a % p;
b >>= 1;
}
return ans;
}
const int maxn = 2e3 + 10;
int a[maxn], b[maxn];
int mod = 998244353;
int f[2][maxn][12], g[2][maxn][12];
inline int add(long long a, long long b) { return (a + b + mod) % mod; }
long long fac[maxn], invfac[maxn], t[maxn];
void init(int n, long long MOD) {
fac[0] = 1;
mod = MOD;
for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % mod;
invfac[n] = qpow(fac[n], mod - 2, mod);
for (int i = n; i >= 1; i--) invfac[i - 1] = invfac[i] * i % mod;
}
long long C(long long n, long long m) {
return n >= m ? fac[n] * invfac[n - m] % mod * invfac[m] % mod : 0;
}
long long cal(long long n, long long m) {
if (!m) return (n == 0);
return fac[n] * C(n + m - 1, m - 1) % mod;
}
int main() {
int T;
init(maxn - 1, mod);
fac[0] = 1;
cin >> T;
while (T--) {
int n;
cin >> n;
int cnta = 0, cntb = 0;
for (int i = 1; i <= n; i++) {
int x;
scanf("%d", &x);
if (to_string(x).size() & 1)
a[++cnta] = x % 11;
else
b[++cntb] = x % 11;
}
memset(f, 0, sizeof(f));
memset(g, 0, sizeof(g));
f[0][0][0] = 1;
g[0][0][0] = 1;
for (int i = 1; i <= cnta; i++) {
int curi = i & 1, lasti = !(i & 1);
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= 10; k++) {
f[curi][j][k] = add(f[curi][j][k], f[lasti][j][(k - a[i] + 11) % 11]);
if (j)
f[curi][j][k] =
add(f[curi][j][k], f[lasti][j - 1][(k + a[i]) % 11]);
}
}
memset(f[lasti], 0, sizeof(f[lasti]));
}
for (int i = 1; i <= cntb; i++) {
int curi = i & 1, lasti = !(i & 1);
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= 10; k++) {
g[curi][j][k] = add(g[curi][j][k], g[lasti][j][(k - b[i] + 11) % 11]);
if (j)
g[curi][j][k] =
add(g[curi][j][k], g[lasti][j - 1][(k + b[i]) % 11]);
}
}
memset(g[lasti], 0, sizeof(g[lasti]));
}
long long ans = 0;
long long temp = fac[cnta / 2] * fac[cnta - cnta / 2] % mod;
int m = cnta / 2 + 1;
for (int i = 0; i <= cntb; i++) {
for (int j = 0; j < 11; j++) {
int p = cntb - i;
long long val = (long long)g[cntb & 1][i][j] *
f[cnta & 1][cnta / 2][(11 - j) % 11] % mod * temp %
mod * cal(p, m) % mod * cal(i, cnta - cnta / 2) % mod;
ans = (ans + val) % mod;
}
}
printf("%lld\n", ans);
}
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
You've got a rectangular table with length a and width b and the infinite number of plates of radius r. Two players play the following game: they take turns to put the plates on the table so that the plates don't lie on each other (but they can touch each other), and so that any point on any plate is located within the table's border. During the game one cannot move the plates that already lie on the table. The player who cannot make another move loses. Determine which player wins, the one who moves first or the one who moves second, provided that both players play optimally well.
Input
A single line contains three space-separated integers a, b, r (1 ≤ a, b, r ≤ 100) — the table sides and the plates' radius, correspondingly.
Output
If wins the player who moves first, print "First" (without the quotes). Otherwise print "Second" (without the quotes).
Examples
Input
5 5 2
Output
First
Input
6 7 4
Output
Second
Note
In the first sample the table has place for only one plate. The first player puts a plate on the table, the second player can't do that and loses.
<image>
In the second sample the table is so small that it doesn't have enough place even for one plate. So the first player loses without making a single move.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long M = 1e7 + 10;
long long prime[M];
int dr[] = {-1, 0, 1, 0};
int dc[] = {0, 1, 0, -1};
vector<int> graph[200001];
void precompute() {
for (long long i = 2; i < M; i++) {
if (!prime[i]) {
for (long long j = 1; i * j < M; j++) prime[i * j] = i;
}
}
}
long long power(long long x, long long y, long long p) {
long long res = 1;
x = x % p;
while (y > 0) {
if (y & 1) res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long t, i, j, n, m, k, temp, x, y, z, a, b, r;
cin >> a >> b >> r;
if (2 * r > min(a, b))
cout << "Second\n";
else
cout << "First\n";
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Evi has N integers a_1,a_2,..,a_N. His objective is to have N equal integers by transforming some of them.
He may transform each integer at most once. Transforming an integer x into another integer y costs him (x-y)^2 dollars. Even if a_i=a_j (i≠j), he has to pay the cost separately for transforming each of them (See Sample 2).
Find the minimum total cost to achieve his objective.
Constraints
* 1≦N≦100
* -100≦a_i≦100
Input
The input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum total cost to achieve Evi's objective.
Examples
Input
2
4 8
Output
8
Input
3
1 1 3
Output
3
Input
3
4 2 5
Output
5
Input
4
-100 -100 -100 -100
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int N; cin>>N;
int sum=0;
vector<int> a(N);
for(int i=0;i<N;i++){
cin>>a.at(i);
sum+=a.at(i);
}
int x=sum/N;
int y=sum%N;
if(2*y>N){
x++;
}
int cost=0;
for(int i=0;i<N;i++){
cost+=(a.at(i)-x)*(a.at(i)-x);
}
cout<<cost<<endl;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Given are a prime number p and a sequence of p integers a_0, \ldots, a_{p-1} consisting of zeros and ones.
Find a polynomial of degree at most p-1, f(x) = b_{p-1} x^{p-1} + b_{p-2} x^{p-2} + \ldots + b_0, satisfying the following conditions:
* For each i (0 \leq i \leq p-1), b_i is an integer such that 0 \leq b_i \leq p-1.
* For each i (0 \leq i \leq p-1), f(i) \equiv a_i \pmod p.
Constraints
* 2 \leq p \leq 2999
* p is a prime number.
* 0 \leq a_i \leq 1
Input
Input is given from Standard Input in the following format:
p
a_0 a_1 \ldots a_{p-1}
Output
Print b_0, b_1, \ldots, b_{p-1} of a polynomial f(x) satisfying the conditions, in this order, with spaces in between.
It can be proved that a solution always exists. If multiple solutions exist, any of them will be accepted.
Examples
Input
2
1 0
Output
1 1
Input
3
0 0 0
Output
0 0 0
Input
5
0 1 0 1 0
Output
0 2 0 1 3
### Response
```cpp
#include <iostream>
using namespace std;
long long p;
long long a[3000], s[3000], t[3000], b[3000];
int main()
{
cin >> p;
for (long long i = 0; i < p; i++)
cin >> a[i];
for (long long i = 0; i < p; i++)
b[i] = 0;
s[0] = 1;
t[0] = 1;
for (long long i = 1; i < p; i++) {
s[i] = s[i - 1] * i % p;
long long j = s[i], k = 1;
while (k < (p - 2) / 2) {
j = j * j % p;
k *= 2;
}
while (k < p - 2) {
j = j * s[i] % p;
k++;
}
t[i] = j;
}
for (long long i = 0; i < p; i++) {
if (a[i] == 1) {
b[p - 1] = (b[p - 1] - 1 + p) % p;
if (i == 0)
b[0] = (b[0] + 1) % p;
else {
long long u = i, v = 1;
while (v < (p - 2) / 2) {
u = u * u % p;
v *= 2;
}
while (v < p - 2) {
u = u * i % p;
v++;
}
long long w = u;
for (long long j = 1; j < p - 1; j++) {
if (j % 2 == 0)
b[j] = (b[j] - s[p - 1] * t[j] % p * t[p - 1 - j] % p * w + p) % p;
else
b[j] = (b[j] + s[p - 1] * t[j] % p * t[p - 1 - j] % p * w) % p;
w = w * u % p;
}
}
}
}
for (long long i = 0; i < p - 1; i++)
cout << b[i] << " ";
cout << b[p - 1] << endl;
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
"This problem is rubbish! There is not statement, and there are only 5 test cases. The problemsetter took liberties with this problem!" — people complained in the comments to one round on Codeforces. And even more... No, wait, the checker for the problem was alright, that's a mercy.
Input
The only line of the input contains an integer between 1 and 5, inclusive. All tests for this problem are different. The contents of the test case doesn't need to be equal to its index.
Output
The only line of the output contains an integer between 1 and 3, inclusive.
Examples
Note
This problem has no samples, since there so few test cases.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int res[5] = {2, 3, 1, 2, 1};
int a;
cin >> a;
cout << res[a - 1] << endl;
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Diameter of a Tree
Given a tree T with non-negative weight, find the diameter of the tree.
The diameter of a tree is the maximum distance between two nodes in a tree.
Constraints
* 1 ≤ n ≤ 100,000
* 0 ≤ wi ≤ 1,000
Input
n
s1 t1 w1
s2 t2 w2
:
sn-1 tn-1 wn-1
The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively.
In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge.
Output
Print the diameter of the tree in a line.
Examples
Input
4
0 1 2
1 2 1
1 3 3
Output
5
Input
4
0 1 1
1 2 2
2 3 4
Output
7
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using i64 = int64_t;
using vi = vector<i64>;
using vvi = vector<vi>;
int main() {
int n;
cin >> n;
using ii = pair<int, i64>;
using vii = vector<ii>;
vector<vii> adj(n);
for (int i = 0; i < n - 1; i++) {
int s, t, w;
cin >> s >> t >> w;
adj[s].push_back(ii(t, w));
adj[t].push_back(ii(s, w));
}
vi dist(n, 1e18);
dist[0] = 0;
function<void(int s)> dfs = [&](int s) {
for (ii& v: adj[s]) {
if (v.second + dist[s] < dist[v.first]) {
dist[v.first] = v.second + dist[s];
dfs(v.first);
}
}
};
dfs(0);
i64 ma = -1;
int mai = -1;
for (int i = 0; i < n; i++) {
if (dist[i] > ma) {
ma = dist[i];
mai = i;
}
}
dist = vi(n, 1e18);
dist[mai] = 0;
dfs(mai);
ma = -1;
for (int i = 0; i < n; i++) {
ma = max(ma, dist[i]);
}
cout << ma << endl;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Today Peter has got an additional homework for tomorrow. The teacher has given three integers to him: n, m and k, and asked him to mark one or more squares on a square grid of size n × m.
The marked squares must form a connected figure, and there must be exactly k triples of marked squares that form an L-shaped tromino — all three squares are inside a 2 × 2 square.
The set of squares forms a connected figure if it is possible to get from any square to any other one if you are allowed to move from a square to any adjacent by a common side square.
Peter cannot fulfill the task, so he asks you for help. Help him to create such figure.
Input
Input data contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100).
Each of the following t test cases is described by a line that contains three integers: n, m and k (3 ≤ n, m, n × m ≤ 105, 0 ≤ k ≤ 109).
The sum of values of n × m for all tests in one input data doesn't exceed 105.
Output
For each test case print the answer.
If it is possible to create such figure, print n lines, m characters each, use asterisk '*' to denote the marked square, and dot '.' to denote the unmarked one.
If there is no solution, print -1.
Print empty line between test cases.
Example
Input
3
3 3 4
3 3 5
3 3 3
Output
.*.
***
.*.
**.
**.
*..
.*.
***
*..
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int x, y, n, m, k;
vector<char> a[200500];
void go(bool get_next = false) {
a[x][y] = '*';
if (get_next) {
x++;
if (x == n) {
x = 0;
y++;
}
}
}
bool solveC() {
for (int i = 0; i < n; i++) {
a[i].resize(m + 10, '\0');
for (int j = 0; j < m; j++) a[i][j] = '.';
a[i][0] = '*';
}
if (k == 0) return true;
x = 0;
y = 1;
while (k) {
if (y == m) {
return false;
}
int l = 4;
if (x == 0)
l = 1;
else if (x == n - 1)
l = 3;
if (k >= l) {
k -= l;
go(true);
continue;
}
if (l == 3) {
if (y == m - 1) return false;
if (k == 1) {
x = 0;
y++;
go();
return true;
}
y++;
go();
x--;
go();
return true;
}
if (k == 1) {
x = n - 1;
go();
return true;
}
if (k == 2) {
if (x + 1 < n - 1) {
x++;
go();
return true;
}
if (y == m - 1) return false;
x++;
go();
y++;
go();
x--;
go();
return true;
}
if (x + 3 <= n - 1) {
x++;
go();
x = n - 1;
go();
return true;
}
if (y == m - 1) return false;
if (x + 2 <= n - 1) {
x++;
go();
y++;
go();
x++;
go();
return true;
}
x++;
go();
y++;
go();
x--;
go();
x = 0;
go();
return true;
}
return true;
}
int main() {
int t = 1000000;
scanf("%d", &t);
for (int q = 0; q < t; q++) {
if (q) printf("\n");
n = q % 100;
n += 3;
m = (q / 100) % 100;
m += 3;
k = q / 1000;
scanf("%d%d%d", &n, &m, &k);
int kk = k;
if (solveC()) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) printf("%c", a[i][j]);
printf("\n");
}
} else {
swap(n, m);
k = kk;
if (solveC()) {
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) printf("%c", a[i][j]);
printf("\n");
}
} else
puts("-1");
}
}
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
You are given a string S consisting of letters `b`, `d`, `p` and `q`. Determine whether S is a mirror string.
Here, a mirror string is a string S such that the following sequence of operations on S results in the same string S:
1. Reverse the order of the characters in S.
2. Replace each occurrence of `b` by `d`, `d` by `b`, `p` by `q`, and `q` by `p`, simultaneously.
Constraints
* 1 \leq |S| \leq 10^5
* S consists of letters `b`, `d`, `p`, and `q`.
Input
The input is given from Standard Input in the following format:
S
Output
If S is a mirror string, print `Yes`. Otherwise, print `No`.
Examples
Input
pdbq
Output
Yes
Input
ppqb
Output
No
### Response
```cpp
#include<bits/stdc++.h>
#define ll long long
#define reg register
using namespace std;
string s;
map<char,int>a;
int main()
{
a['p']=1;
a['d']=2;
a['q']=3;
cin>>s;
s=" "+s;
for(reg int l=s.length()-1,i=1;i<=(l>>1)+1;i++)
if(a[s[i]]^((a[s[l-i+1]]+2)%4))return puts("No"),0;
return puts("Yes"),0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
The only difference between easy and hard versions is constraints.
Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.
There are n voters, and two ways to convince each of them to vote for you. The first way to convince the i-th voter is to pay him p_i coins. The second way is to make m_i other voters vote for you, and the i-th voter will vote for free.
Moreover, the process of such voting takes place in several steps. For example, if there are five voters with m_1 = 1, m_2 = 2, m_3 = 2, m_4 = 4, m_5 = 5, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: {5} → {1, 5} → {1, 2, 3, 5} → {1, 2, 3, 4, 5}.
Calculate the minimum number of coins you have to spend so that everyone votes for you.
Input
The first line contains one integer t (1 ≤ t ≤ 5000) — the number of test cases.
The first line of each test case contains one integer n (1 ≤ n ≤ 5000) — the number of voters.
The next n lines contains the description of voters. i-th line contains two integers m_i and p_i (1 ≤ p_i ≤ 10^9, 0 ≤ m_i < n).
It is guaranteed that the sum of all n over all test cases does not exceed 5000.
Output
For each test case print one integer — the minimum number of coins you have to spend so that everyone votes for you.
Example
Input
3
3
1 5
2 10
2 8
7
0 1
3 1
1 1
6 1
1 1
4 1
4 1
6
2 6
2 3
2 8
2 7
4 4
5 5
Output
8
0
7
Note
In the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: {3} → {1, 3} → {1, 2, 3}.
In the second example you don't need to buy votes. The set of people voting for you will change as follows: {1} → {1, 3, 5} → {1, 2, 3, 5} → {1, 2, 3, 5, 6, 7} → {1, 2, 3, 4, 5, 6, 7}.
In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: {2, 5} → {1, 2, 3, 4, 5} → {1, 2, 3, 4, 5, 6}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<int> g[200005];
priority_queue<int, vector<int>, greater<int> > qu;
int main() {
int T, n, x, y;
scanf("%d", &T);
while (T--) {
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d%d", &x, &y);
g[x].push_back(y);
}
long long ans = 0;
for (int i = n - 1; i >= 0; --i) {
for (int j = 0, sz = g[i].size(); j < sz; ++j) qu.push(g[i][j]);
while (qu.size() > n - i) ans += qu.top(), qu.pop();
}
printf("%lld\n", ans);
for (int i = 0; i < n; ++i) g[i].clear();
while (!qu.empty()) qu.pop();
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Polycarp is flying in the airplane. Finally, it is his favorite time — the lunchtime. The BerAvia company stewardess is giving food consecutively to all the passengers from the 1-th one to the last one. Polycarp is sitting on seat m, that means, he will be the m-th person to get food.
The flight menu has k dishes in total and when Polycarp boarded the flight, he had time to count the number of portions of each dish on board. Thus, he knows values a1, a2, ..., ak, where ai is the number of portions of the i-th dish.
The stewardess has already given food to m - 1 passengers, gave Polycarp a polite smile and asked him what he would prefer. That's when Polycarp realized that they might have run out of some dishes by that moment. For some of the m - 1 passengers ahead of him, he noticed what dishes they were given. Besides, he's heard some strange mumbling from some of the m - 1 passengers ahead of him, similar to phrase 'I'm disappointed'. That happened when a passenger asked for some dish but the stewardess gave him a polite smile and said that they had run out of that dish. In that case the passenger needed to choose some other dish that was available. If Polycarp heard no more sounds from a passenger, that meant that the passenger chose his dish at the first try.
Help Polycarp to find out for each dish: whether they could have run out of the dish by the moment Polyarp was served or that dish was definitely available.
Input
Each test in this problem consists of one or more input sets. First goes a string that contains a single integer t (1 ≤ t ≤ 100 000) — the number of input data sets in the test. Then the sets follow, each set is preceded by an empty line.
The first line of each set of the input contains integers m, k (2 ≤ m ≤ 100 000, 1 ≤ k ≤ 100 000) — the number of Polycarp's seat and the number of dishes, respectively.
The second line contains a sequence of k integers a1, a2, ..., ak (1 ≤ ai ≤ 100 000), where ai is the initial number of portions of the i-th dish.
Then m - 1 lines follow, each line contains the description of Polycarp's observations about giving food to a passenger sitting in front of him: the j-th line contains a pair of integers tj, rj (0 ≤ tj ≤ k, 0 ≤ rj ≤ 1), where tj is the number of the dish that was given to the j-th passenger (or 0, if Polycarp didn't notice what dish was given to the passenger), and rj — a 1 or a 0, depending on whether the j-th passenger was or wasn't disappointed, respectively.
We know that sum ai equals at least m, that is,Polycarp will definitely get some dish, even if it is the last thing he wanted. It is guaranteed that the data is consistent.
Sum m for all input sets doesn't exceed 100 000. Sum k for all input sets doesn't exceed 100 000.
Output
For each input set print the answer as a single line. Print a string of k letters "Y" or "N". Letter "Y" in position i should be printed if they could have run out of the i-th dish by the time the stewardess started serving Polycarp.
Examples
Input
2
3 4
2 3 2 1
1 0
0 0
5 5
1 2 1 3 1
3 0
0 0
2 1
4 0
Output
YNNY
YYYNY
Note
In the first input set depending on the choice of the second passenger the situation could develop in different ways:
* If he chose the first dish, then by the moment the stewardess reaches Polycarp, they will have run out of the first dish;
* If he chose the fourth dish, then by the moment the stewardess reaches Polycarp, they will have run out of the fourth dish;
* Otherwise, Polycarp will be able to choose from any of the four dishes.
Thus, the answer is "YNNY".
In the second input set there is, for example, the following possible scenario. First, the first passenger takes the only third dish, then the second passenger takes the second dish. Then, the third passenger asks for the third dish, but it is not available, so he makes disappointed muttering and ends up with the second dish. Then the fourth passenger takes the fourth dish, and Polycarp ends up with the choice between the first, fourth and fifth dish.
Likewise, another possible scenario is when by the time the stewardess comes to Polycarp, they will have run out of either the first or the fifth dish (this can happen if one of these dishes is taken by the second passenger). It is easy to see that there is more than enough of the fourth dish, so Polycarp can always count on it. Thus, the answer is "YYYNY".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const double eps = 1e-9;
const int mod = (int)1e+9 + 7;
const double pi = acos(-1.);
const int maxn = 100100;
int cnt[maxn];
bool ans[maxn];
int bludo[maxn], ok[maxn];
bool used[maxn];
int main() {
srand(time(0));
const string file = "";
if (!file.empty()) {
freopen((file + ".in").c_str(), "r", stdin);
freopen((file + ".out").c_str(), "w", stdout);
}
int T;
scanf("%d", &T);
for (; T > 0; T--) {
int m, k;
scanf("%d%d", &m, &k);
m--;
for (int i = 0; i < k; i++) {
scanf("%d", &cnt[i]);
}
bool kill = 0;
for (int i = 0; i < m; i++) {
scanf("%d%d", &bludo[i], &ok[i]);
if (ok[i]) {
kill = 1;
}
if (kill) {
used[bludo[i] - 1] = 1;
}
}
kill = 0;
int empty = 0;
for (int i = 0; i < m; i++) {
if (ok[i] && (!kill)) {
kill = 1;
int minn = mod;
for (int f = 0; f < k; f++) {
if (cnt[f] <= empty && (!used[f])) {
ans[f] = 1;
}
if (!used[f]) minn = min(minn, cnt[f]);
}
empty -= minn;
}
if (bludo[i] != 0) {
cnt[bludo[i] - 1]--;
} else {
empty++;
}
}
for (int i = 0; i < k; i++) {
if (cnt[i] <= empty) {
ans[i] = 1;
}
}
for (int i = 0; i < k; i++) {
if (ans[i] == 1) {
printf("Y");
} else {
printf("N");
}
ans[i] = 0;
used[i] = 0;
}
printf("\n");
}
return (0);
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Two players, A and B, play the game using cards with numbers from 0 to 9. First, the two arrange the given n cards face down in a horizontal row. After that, the two players turn their cards face up one by one from the left, and the owner of the card with the larger number takes the two cards. At this time, the sum of the numbers written on the two cards shall be the score of the player who took the card. However, if the same number is written on the two open cards, it is a draw and each player takes one of his own cards.
For example, consider the case where the hands of A and B are arranged as shown in the following input examples 1 to 3. However, the input file consists of n + 1 lines, the first line contains the number of cards n for each player, and the i + 1 line (i = 1, 2, ..., n) is A. The numbers on the i-th card from the left and the numbers on the i-th card from the left of B are written in this order, with a blank as the delimiter. That is, from the second row onward of the input file, the left column represents the sequence of A cards, and the right column represents the sequence of B cards. At this time, the scores of A and B after the end of the game are shown in the corresponding output examples, respectively.
Create a program that outputs the score of A and the score of B when the game corresponding to the input file ends on one line with a space as a delimiter in this order. However, n ≤ 10000.
Input example 1 | Input example 2 | Input example 3
--- | --- | ---
3 | 3 | 3
9 1 | 9 1 | 9 1
5 4 | 5 4 | 5 5
0 8 | 1 0 | 1 8
Output example 1 | Output example 2 | Output example 3
19 8 | 20 0 | 15 14
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each dataset, the score of A and the score of B are output on one line.
Input example
3
9 1
5 4
0 8
3
9 1
5 4
Ten
3
9 1
5 5
1 8
0
Output example
19 8
20 0
15 14
Insert a line break after the output of each dataset (after the score of B).
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
Example
Input
3
9 1
5 4
0 8
3
9 1
5 4
1 0
3
9 1
5 5
1 8
0
Output
19 8
20 0
15 14
### Response
```cpp
#include<stdio.h>
int main()
{
int a,b,at,bt,k,i;
while(1){
scanf("%d",&k);
if(k==0)break;
at=0;
bt=0;
for(i=0;i<k;i++){
scanf("%d %d",&a,&b);
if(a>b)at+=a+b;
else if(b>a)bt+=a+b;
else {
bt+=b;
at+=a;
}
}
printf("%d %d\n",at,bt);
}
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
This is the easy version of this problem. The only difference is the limit of n - the length of the input string. In this version, 1 ≤ n ≤ 2000. The hard version of this challenge is not offered in the round for the second division.
Let's define a correct bracket sequence and its depth as follow:
* An empty string is a correct bracket sequence with depth 0.
* If "s" is a correct bracket sequence with depth d then "(s)" is a correct bracket sequence with depth d + 1.
* If "s" and "t" are both correct bracket sequences then their concatenation "st" is a correct bracket sequence with depth equal to the maximum depth of s and t.
For a (not necessarily correct) bracket sequence s, we define its depth as the maximum depth of any correct bracket sequence induced by removing some characters from s (possibly zero). For example: the bracket sequence s = "())(())" has depth 2, because by removing the third character we obtain a correct bracket sequence "()(())" with depth 2.
Given a string a consists of only characters '(', ')' and '?'. Consider all (not necessarily correct) bracket sequences obtained by replacing all characters '?' in a by either '(' or ')'. Calculate the sum of all the depths of all these bracket sequences. As this number can be large, find it modulo 998244353.
Hacks in this problem in the first division can be done only if easy and hard versions of this problem was solved.
Input
The only line contains a non-empty string consist of only '(', ')' and '?'. The length of the string is at most 2000.
Output
Print the answer modulo 998244353 in a single line.
Examples
Input
??
Output
1
Input
(?(?))
Output
9
Note
In the first test case, we can obtain 4 bracket sequences by replacing all characters '?' with either '(' or ')':
* "((". Its depth is 0;
* "))". Its depth is 0;
* ")(". Its depth is 0;
* "()". Its depth is 1.
So, the answer is 1 = 0 + 0 + 0 + 1.
In the second test case, we can obtain 4 bracket sequences by replacing all characters '?' with either '(' or ')':
* "(((())". Its depth is 2;
* "()()))". Its depth is 2;
* "((()))". Its depth is 3;
* "()(())". Its depth is 2.
So, the answer is 9 = 2 + 2 + 3 + 2.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2005;
const long long mod = 998244353;
string s, t;
long long p[maxn], n;
long long dp[maxn][maxn];
long long ksm(long long a, long long b) {
long long r = 1;
while (b) {
if (b & 1) r = (r * a) % mod;
a = a * a % mod;
b >>= 1;
}
return r;
}
long long dfs(int l, int r) {
if (dp[l][r] != -1) return dp[l][r];
if (l >= r || l > n || r <= 0) return dp[l][r] = 0;
long long ans = 0;
if (s[l] != '(') ans = (ans + dfs(l + 1, r)) % mod;
if (s[r] != ')') ans = (ans + dfs(l, r - 1)) % mod;
if (s[l] != '(' && s[r] != ')') ans = (ans - dfs(l + 1, r - 1) + mod) % mod;
if (s[l] != ')' && s[r] != '(')
ans = (ans + dfs(l + 1, r - 1) + ksm(2, p[r - 1] - p[l])) % mod;
return dp[l][r] = ans;
}
int main() {
s += '#';
cin >> t;
s += t;
n = t.size();
memset(dp, -1, sizeof(dp));
for (int i = 1; i <= n; i++) p[i] = p[i - 1] + (s[i] == '?');
dfs(1, n);
cout << dp[1][n] << endl;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long a[100009];
signed main() {
long long i, n, k = -1, j, ct = 0;
cin >> n;
for (i = 0; i < n; i++) cin >> a[i];
for (j = 30; j >= 0; j--) {
ct = 0;
for (i = 0; i < n; i++) {
if ((a[i] >> j) & 1) {
ct++;
k = i;
}
}
if (ct == 1) break;
}
if (ct == 1) swap(a[0], a[k]);
for (i = 0; i < n; i++) cout << a[i] << " ";
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills.
Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisible by 64, in the binary numerical system.
Input
In the only line given a non-empty binary string s with length up to 100.
Output
Print «yes» (without quotes) if it's possible to remove digits required way and «no» otherwise.
Examples
Input
100010001
Output
yes
Input
100
Output
no
Note
In the first test case, you can get string 1 000 000 after removing two ones which is a representation of number 64 in the binary numerical system.
You can read more about binary numeral system representation here: <https://en.wikipedia.org/wiki/Binary_system>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
char s[101];
int main() {
scanf("%s", s);
int i = 0, n = strlen(s);
while (i < n && s[i] == '0') ++i;
++i;
int z = 0;
while (i < n) z += s[i++] == '0';
printf("%s\n", z >= 6 ? "yes" : "no");
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
At the end of last year, Santa Claus forgot to give Christmas presents to the children in JOI village. Therefore, I decided to deliver the chocolate cake to the children as an apology. The day to deliver is approaching tomorrow, so it's time to come up with a move plan.
JOI village is divided into a grid shape by W roads extending straight in the north-south direction and H roads extending straight in the east-west direction. The W roads in the north-south direction are west. The numbers 1, 2, ..., W are numbered in order from the south, and the H roads in the east-west direction are numbered 1, 2, ..., H in order from the south. The intersection of the xth north-south road and the yth east-west road from the south is represented by (x, y). There are N houses in JOI village, and they are located at one of the intersections. Santa Claus can only move along the road. The time it takes to move between adjacent intersections is 1.
Every house in JOI village has children, so Santa Claus has to deliver one chocolate cake to every house in JOI village. It's a little to fly with a reindeer with an important chocolate cake. Being dangerous, Santa Claus and Reindeer landed at one of the intersections in JOI Village, where Santa Claus decided to walk to deliver the chocolate cake. Santa Claus would not carry more than one chocolate cake at the same time. In other words, Santa Claus returns to the intersection where he landed every time he delivered a chocolate cake to a house.
Santa Claus decided to choose a travel plan that would minimize the time it took to deliver the chocolate cake to all homes after landing in JOI Village. Note that the time it takes to return to the intersection after delivering the chocolate cake to the last house is not included in the time required. Also, I don't think about anything other than the time it takes to move.
input
Read the following input from standard input.
* On the first line, the integers W and H, which represent the number of roads in each direction, are written with blanks as delimiters.
* The second line contains the integer N, which represents the number of houses.
* The following N lines contain information on the location of the house. On the second line of i + (1 ≤ i ≤ N), the integers Xi and Yi are written separated by blanks, indicating that the i-th house is located at the intersection (Xi, Yi). These N intersections are all different.
output
Output the following data to standard output.
* The first line must contain one integer that represents the minimum required time.
* On the second line, when the intersection to be landed to minimize the required time is (x, y), the two integers x, y must be written in this order, separated by blanks. If there are multiple suitable intersections, the westernmost one (that is, the value of x is small), and if it is still not one, the one that is the southernmost (that is, the value of y is small). ) Choose an intersection.
Example
Input
5 4
3
1 1
3 4
5 3
Output
10
3 3
### Response
```cpp
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
int ox[100000];
int oy[100000];
int x[100000];
int y[100000];
int n;
long long calc(int a,int b){
int md=0,i;
long long ans=0;
for(i=0;i<n;i++){
int d=abs(ox[i]-a)+abs(oy[i]-b);
md=max(md,d);
ans+=(long long)d*2;
}
return ans-(long long)md;
}
int max(int a,int b){return a>b?a:b;}
int main(){
int w,h,i,j;
scanf("%d %d",&w,&h);
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d %d",&ox[i],&oy[i]);
x[i]=ox[i];
y[i]=oy[i];
}
sort(x,x+n);
sort(y,y+n);
long long ans=1000000000000000000LL;
int ax[2];
int ay[2];
ax[0]=x[n/2];
ay[0]=y[n/2];
int nx,ny;
if(n%2==0){
ax[1]=x[n/2-1];
ay[1]=y[n/2-1];
for(i=1;i>=0;i--)for(j=1;j>=0;j--){
if(ans>calc(ax[i],ay[j])){
ans=calc(ax[i],ay[j]);
nx=ax[i];
ny=ay[j];
}
}
}else{
ans=calc(ax[0],ay[0]);
nx=ax[0];
ny=ay[0];
}
printf("%lld\n",ans);
printf("%d %d\n",nx,ny);
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct.
Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information.
Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out.
Input
The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format.
Output
The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations.
Examples
Input
4
XOOO
XXOO
OOOO
XXXX
XOOO
XOOO
XOXO
XOXX
Output
Yes
Input
2
XX
OO
XO
OX
Output
No
Note
In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void rotate90(char **&a, int n);
void flip(char **a, int n);
bool check(char **&a, char **b, int n);
int main() {
int n;
cin >> n;
char **a = new char *[n];
char **b = new char *[n];
for (int i = 0; i < n; i++) {
a[i] = new char[n + 1];
for (int j = 0; j < n; j++) cin >> a[i][j];
a[i][n] = '\0';
b[i] = new char[n + 1];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) cin >> b[i][j];
b[i][n] = '\0';
}
if (check(a, b, n))
cout << "Yes";
else
cout << "No";
for (int i = 0; i < n; i++) {
delete[] a[i];
delete[] b[i];
}
delete[] a;
delete[] b;
return 0;
}
void rotate90(char **&a, int n) {
char **c = new char *[n];
for (int i = 0; i < n; i++) {
c[i] = new char[n + 1];
for (int j = 0; j < n; j++) c[i][j] = a[j][n - i - 1];
c[i][n] = '\0';
}
for (int i = 0; i < n; i++) delete[] a[i];
delete[] a;
a = c;
}
void flip(char **a, int n) {
for (int i = 0; i < n / 2; i++) {
for (int j = 0; j < n; j++) swap(a[i][j], a[n - i - 1][j]);
}
}
bool check(char **&a, char **b, int n) {
int j, k;
for (int i = 0; i < 4; i++) {
for (j = 0; j < n; j++)
if (strcmp(a[j], b[j]) != 0) break;
if (j == n) return true;
rotate90(a, n);
}
for (int i = 0; i < 4; i++) {
flip(a, n);
for (j = 0; j < n; j++)
if (strcmp(a[j], b[j]) != 0) break;
if (j == n) return true;
flip(a, n);
rotate90(a, n);
}
return false;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Suppose you are given two strings a and b. You can apply the following operation any number of times: choose any contiguous substring of a or b, and sort the characters in it in non-descending order. Let f(a, b) the minimum number of operations you have to apply in order to make them equal (or f(a, b) = 1337 if it is impossible to make a and b equal using these operations).
For example:
* f(ab, ab) = 0;
* f(ba, ab) = 1 (in one operation, we can sort the whole first string);
* f(ebcda, ecdba) = 1 (in one operation, we can sort the substring of the second string starting from the 2-nd character and ending with the 4-th character);
* f(a, b) = 1337.
You are given n strings s_1, s_2, ..., s_k having equal length. Calculate ∑ _{i = 1}^{n} ∑_{j = i + 1}^{n} f(s_i, s_j).
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of strings.
Then n lines follow, each line contains one of the strings s_i, consisting of lowercase Latin letters. |s_1| = |s_2| = … = |s_n|, and n ⋅ |s_1| ≤ 2 ⋅ 10^5. All these strings are pairwise distinct.
Output
Print one integer: ∑ _{i = 1}^{n} ∑_{j = i + 1}^{n} f(s_i, s_j).
Examples
Input
4
zzz
bac
abc
acb
Output
4015
Input
2
a
b
Output
1337
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair <int, int> ii;
const int Maxn = 200005;
const int Maxl = 26;
const int Maxm = 1000000;
struct node {
int ch[Maxl];
int cnt;
node() {
fill(ch, ch + Maxl, 0);
cnt = 0;
}
};
char tmp[Maxn];
int n, m;
map <string, map <string, int> > M;
string str[Maxn];
int strcnt[Maxn];
ii lr[Maxn];
int mynode[Maxn];
int slen;
node V[Maxm];
int par[Maxm], siz[Maxm];
int vlen;
ll res;
int getPar(int x) { return par[x] == x? x: par[x] = getPar(par[x]); }
int createNew() {
par[vlen] = vlen;
siz[vlen] = 1;
return vlen++;
}
void Read(string &s)
{
scanf("%s", tmp);
s = tmp;
}
void Merge(int &A, int B)
{
if (A == 0) { A = B; return; }
if (B == 0) return;
if (siz[A] < siz[B]) swap(A, B);
siz[A] += siz[B]; par[B] = A;
V[A].cnt += V[B].cnt;
for (int i = 0; i < Maxl; i++)
Merge(V[A].ch[i], V[B].ch[i]);
}
int Count(int tr, const string &s, int lvl)
{
if (tr == 0 || lvl < 0) return 0;
int res = V[tr].cnt;
int ind = s[lvl] - 'a';
if (V[tr].ch[ind]) res += Count(V[tr].ch[ind], s, lvl - 1);
return res;
}
int Solve(int lvl, const vector <int> &all)
{
if (lvl >= m) {
int v = all[0];
lr[v] = ii(m, m - 1);
mynode[v] = createNew();
V[mynode[v]].cnt += strcnt[v];
return mynode[v];
}
int root = 0;
vector <int> spec[Maxl] = {};
for (int i = 0; i < all.size(); i++)
spec[str[all[i]][lvl] - 'a'].push_back(all[i]);
for (int i = 0; i < Maxl; i++) if (!spec[i].empty()) {
int got = Solve(lvl + 1, spec[i]);
for (int j = 0; j < spec[i].size(); j++)
res -= ll(strcnt[spec[i][j]]) * Count(root, str[spec[i][j]], m - 1);
Merge(root, got);
for (int j = 0; j < spec[i].size(); j++) {
int v = spec[i][j];
if (lvl + 1 == m || str[v][lvl] > str[v][lvl + 1]) {
int pos = getPar(mynode[v]);
V[pos].cnt -= strcnt[v];
while (lr[v].first <= lr[v].second) {
int ind = str[v][lr[v].second] - 'a';
if (!V[pos].ch[ind]) V[pos].ch[ind] = createNew();
pos = V[pos].ch[ind];
lr[v].second--;
}
mynode[v] = pos;
V[mynode[v]].cnt += strcnt[v];
}
lr[v].first = lvl;
}
}
return root;
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++) {
string s; Read(s);
string srt = s;
sort(srt.begin(), srt.end());
M[srt][s]++;
}
createNew();
int was = 0;
for (auto it = M.begin(); it != M.end(); it++) {
slen = 0;
int add = 0;
for (auto it2 = it->second.begin(); it2 != it->second.end(); it2++) {
str[slen] = it2->first; strcnt[slen] = it2->second;
res += 1337ll * ll(was) * strcnt[slen] + 2ll * ll(add) * strcnt[slen];
add += strcnt[slen];
slen++;
}
m = str[0].length();
vector <int> seq;
for (int i = 0; i < slen; i++)
seq.push_back(i);
Solve(0, seq);
was += add;
}
cout << res << endl;
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
There are league games and tournament games in sports competitions. In soccer league games, points are given to each of the wins, losses, and draws, and the rankings are competed based on the points. The points are win (3 points), negative (0 points), and draw (1 point), respectively.
Enter the number of teams and the results of the league match, sort them in order of best results (in descending order of points), and create a program that outputs the team name and points. If the points are tied, output in the order of input.
Input
Given multiple datasets. Each dataset is given in the following format:
n
name1 w1 l1 d1
name2 w2 l2 d2
::
namen wn ln dn
The number of teams n (n ≤ 10) is given on the first line. The next n lines are given the name of team i (alphabet of up to 20 characters), the number of wins wi, the number of negatives li, and the number of draws di (0 ≤ wi, li, di ≤ 9), separated by spaces. ..
When the number of teams is 0, the input is completed. The number of datasets does not exceed 50.
Output
Print a sorted list of teams for each dataset. Print the name of the i-th team and the points on the i-line, separated by commas.
Insert one blank line between the datasets.
Example
Input
4
Japan 1 0 2
Egypt 1 2 0
Canada 0 2 1
Spain 2 0 1
3
India 0 2 0
Poland 1 0 1
Italy 1 0 1
0
Output
Spain,7
Japan,5
Egypt,3
Canada,1
Poland,4
Italy,4
India,0
### Response
```cpp
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main(){
int n,d = 0;
while(cin >> n, n){
if(d) cout << endl;
int a,b,c,z[100],tmp;
string s[100],tmp2;
for(int i=0;i<n;i++){
cin >> s[i] >> a >> b >> c;
z[i] = a * 3 + c;
}
for(int i=0;i<n-1;i++){
for(int j=n-1;j>i;j--){
if(z[j] > z[j - 1]){
tmp = z[j];
z[j] = z[j - 1];
z[j - 1] = tmp;
tmp2 = s[j];
s[j] = s[j - 1];
s[j - 1] = tmp2;
}
}
}
for(int i=0;i<n;i++) cout << s[i] << "," << z[i] << endl;
d = 1;
}
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Daisy is a senior software engineer at RainyDay, LLC. She has just implemented three new features in their product: the first feature makes their product work, the second one makes their product fast, and the third one makes their product correct. The company encourages at least some testing of new features, so Daisy appointed her intern Demid to write some tests for the new features.
Interestingly enough, these three features pass all the tests on Demid's development server, which has index 1, but might fail the tests on some other servers.
After Demid has completed this task, Daisy appointed you to deploy these three features to all n servers of your company. For every feature f and every server s, Daisy told you whether she wants the feature f to be deployed on the server s. If she wants it to be deployed, it must be done even if the feature f fails the tests on the server s. If she does not want it to be deployed, you may not deploy it there.
Your company has two important instruments for the deployment of new features to servers: Continuous Deployment (CD) and Continuous Testing (CT). CD can be established between several pairs of servers, forming a directed graph. CT can be set up on some set of servers.
If CD is configured from the server s_1 to the server s_2 then every time s_1 receives a new feature f the system starts the following deployment process of f to s_2:
* If the feature f is already deployed on the server s_2, then nothing is done.
* Otherwise, if CT is not set up on the server s_1, then the server s_1 just deploys the feature f to the server s_2 without any testing.
* Otherwise, the server s_1 runs tests for the feature f. If the tests fail on the server s_1, nothing is done. If the tests pass, then the server s_1 deploys the feature f to the server s_2.
You are to configure the CD/CT system, and after that Demid will deploy all three features on his development server. Your CD/CT system must deploy each feature exactly to the set of servers that Daisy wants.
Your company does not have a lot of computing resources, so you can establish CD from one server to another at most 264 times.
Input
The first line contains integer n (2 ≤ n ≤ 256) — the number of servers in your company.
Next n lines contain three integers each. The j-th integer in the i-th line is 1 if Daisy wants the j-th feature to be deployed to the i-th server, or 0 otherwise.
Next n lines contain three integers each. The j-th integer in the i-th line is 1 if tests pass for the j-th feature on the i-th server, or 0 otherwise.
Demid's development server has index 1. It is guaranteed that Daisy wants all three features to be deployed to the server number 1, and all three features pass their tests on the server number 1.
Output
If it is impossible to configure CD/CT system with CD being set up between at most 264 pairs of servers, then output the single line "Impossible".
Otherwise, the first line of the output must contain the line "Possible".
Next line must contain n space-separated integers — the configuration of CT. The i-th integer should be 1 if you set up CT on the i-th server, or 0 otherwise.
Next line must contain the integer m (0 ≤ m ≤ 264) — the number of CD pairs you want to set up.
Each of the next m lines must describe CD configuration, each line with two integers s_i and t_i (1 ≤ s_i, t_i ≤ n; s_i ≠ t_i), establishing automated deployment of new features from the server s_i to the server t_i.
Examples
Input
3
1 1 1
1 0 1
1 1 1
1 1 1
0 0 0
1 0 1
Output
Possible
1 1 1
2
3 2
1 3
Input
2
1 1 1
0 0 1
1 1 1
1 1 0
Output
Impossible
Note
CD/CT system for the first sample test is shown below.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MX = 500;
int deploy[MX][3];
int tests[MX][3];
bool enabled[MX], done[MX];
string state[MX];
bool can(int from, int too, bool from_en) {
for (int i = 0; i < 3; i++) {
bool en = (from_en ? (state[from][i] == 'c') : (state[from][i] != 'a'));
if (state[too][i] == 'a') {
if (en) return false;
} else {
if (not en) return false;
}
}
return true;
}
bool can_two(int one, int two, int target) {
for (int i = 0; i < 3; i++) {
if (state[target][i] == 'a') {
if (state[one][i] == 'c' || state[two][i] == 'c') return false;
} else {
if (state[one][i] != 'c' && state[two][i] != 'c') return false;
}
}
return true;
}
char get_ch(int a, int b) {
if (a == 0) return 'a';
if (b == 0) return 'b';
return 'c';
}
void solve(int n) {
for (int i = 1; i <= n; i++) {
enabled[i] = false;
done[i] = false;
}
for (int i = 1; i <= n; i++) {
for (int j = 0; j < 3; j++) {
ignore = scanf("%d", &deploy[i][j]);
}
}
for (int i = 1; i <= n; i++) {
for (int j = 0; j < 3; j++) {
ignore = scanf("%d", &tests[i][j]);
}
}
for (int i = 1; i <= n; i++) {
state[i] = "";
for (int j = 0; j < 3; j++) {
state[i] += get_ch(deploy[i][j], tests[i][j]);
}
}
vector<pair<int, int> > edges;
int not_done = n - 1;
done[1] = true;
enabled[1] = true;
while (not_done != 0) {
int saved_not_done = not_done;
for (int i = 1; i <= n; i++) {
if (done[i]) continue;
bool found = false;
for (int j = 1; j <= n; j++) {
if (not done[j]) continue;
if (can(j, i, enabled[j])) {
done[i] = true;
enabled[i] = true;
edges.emplace_back(j, i);
found = true;
not_done--;
break;
}
}
if (found) continue;
for (int j = 1; j <= n; j++) {
if (not done[j] || enabled[j] == false) continue;
for (int k = j + 1; k <= n; k++) {
if (not done[k] || enabled[k] == false) continue;
if (can_two(j, k, i)) {
done[i] = true;
enabled[i] = false;
edges.emplace_back(j, i);
edges.emplace_back(k, i);
found = true;
not_done--;
goto WHILE_END;
}
}
}
}
WHILE_END:;
if (saved_not_done == not_done) {
printf("Impossible\n");
return;
}
}
printf("Possible\n");
for (int i = 1; i <= n; i++) {
printf("%d ", enabled[i] ? 1 : 0);
}
printf("\n");
printf("%d\n", (int)edges.size());
assert(edges.size() <= 264);
for (auto e : edges) {
printf("%d %d\n", e.first, e.second);
}
}
int main() {
int n;
while (scanf("%d", &n) != EOF) {
solve(n);
}
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
A string s of length n can be encrypted by the following algorithm:
* iterate over all divisors of n in decreasing order (i.e. from n to 1),
* for each divisor d, reverse the substring s[1 ... d] (i.e. the substring which starts at position 1 and ends at position d).
For example, the above algorithm applied to the string s="codeforces" leads to the following changes: "codeforces" → "secrofedoc" → "orcesfedoc" → "rocesfedoc" → "rocesfedoc" (obviously, the last reverse operation doesn't change the string because d=1).
You are given the encrypted string t. Your task is to decrypt this string, i.e., to find a string s such that the above algorithm results in string t. It can be proven that this string s always exists and is unique.
Input
The first line of input consists of a single integer n (1 ≤ n ≤ 100) — the length of the string t. The second line of input consists of the string t. The length of t is n, and it consists only of lowercase Latin letters.
Output
Print a string s such that the above algorithm results in t.
Examples
Input
10
rocesfedoc
Output
codeforces
Input
16
plmaetwoxesisiht
Output
thisisexampletwo
Input
1
z
Output
z
Note
The first example is described in the problem statement.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
char s[105];
void turn(int m) {
char temp[105];
for (int k = 1; k <= m; k++) temp[k] = s[k];
for (int k = 1; k <= m; k++) s[k] = temp[m - k + 1];
}
int main() {
int n;
cin >> n;
scanf("%s", s + 1);
for (int i = 1; i <= n; i++) {
if (n % i == 0) turn(i);
}
for (int i = 1; i <= n; i++) cout << s[i];
cout << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
During a New Year special offer the "Sudislavl Bars" offered n promo codes. Each promo code consists of exactly six digits and gives right to one free cocktail at the bar "Mosquito Shelter". Of course, all the promocodes differ.
As the "Mosquito Shelter" opens only at 9, and partying in Sudislavl usually begins at as early as 6, many problems may arise as to how to type a promotional code without errors. It is necessary to calculate such maximum k, that the promotional code could be uniquely identified if it was typed with no more than k errors. At that, k = 0 means that the promotional codes must be entered exactly.
A mistake in this problem should be considered as entering the wrong numbers. For example, value "123465" contains two errors relative to promocode "123456". Regardless of the number of errors the entered value consists of exactly six digits.
Input
The first line of the output contains number n (1 ≤ n ≤ 1000) — the number of promocodes.
Each of the next n lines contains a single promocode, consisting of exactly 6 digits. It is guaranteed that all the promocodes are distinct. Promocodes can start from digit "0".
Output
Print the maximum k (naturally, not exceeding the length of the promocode), such that any promocode can be uniquely identified if it is typed with at most k mistakes.
Examples
Input
2
000000
999999
Output
2
Input
6
211111
212111
222111
111111
112111
121111
Output
0
Note
In the first sample k < 3, so if a bar customer types in value "090909", then it will be impossible to define which promocode exactly corresponds to it.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1010;
string s[maxn];
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) cin >> s[i];
int ans = 6, cnt;
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
cnt = 0;
for (int k = 0; k < 6; k++)
if (s[i][k] != s[j][k]) cnt++;
ans = min(ans, (cnt + 1) / 2 - 1);
}
}
cout << ans;
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a].
By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT.
The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon?
Input
The single line of the input contains two integers a, b (1 ≤ a, b ≤ 107).
Output
Print a single integer representing the answer modulo 1 000 000 007 (109 + 7).
Examples
Input
1 1
Output
0
Input
2 2
Output
8
Note
For the first sample, there are no nice integers because <image> is always zero.
For the second sample, the set of nice integers is {3, 5}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long unsigned a, b;
cin >> a >> b;
long long unsigned ans = a * (a + 1);
ans /= 2;
ans %= 1000000007;
ans *= b;
ans %= 1000000007;
ans = ans + a;
ans %= 1000000007;
long long unsigned k = b * (b - 1);
k /= 2;
k %= 1000000007;
ans = ans * k;
ans %= 1000000007;
cout << ans;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Mike is a bartender at Rico's bar. At Rico's, they put beer glasses in a special shelf. There are n kinds of beer at Rico's numbered from 1 to n. i-th kind of beer has ai milliliters of foam on it.
<image>
Maxim is Mike's boss. Today he told Mike to perform q queries. Initially the shelf is empty. In each request, Maxim gives him a number x. If beer number x is already in the shelf, then Mike should remove it from the shelf, otherwise he should put it in the shelf.
After each query, Mike should tell him the score of the shelf. Bears are geeks. So they think that the score of a shelf is the number of pairs (i, j) of glasses in the shelf such that i < j and <image> where <image> is the greatest common divisor of numbers a and b.
Mike is tired. So he asked you to help him in performing these requests.
Input
The first line of input contains numbers n and q (1 ≤ n, q ≤ 2 × 105), the number of different kinds of beer and number of queries.
The next line contains n space separated integers, a1, a2, ... , an (1 ≤ ai ≤ 5 × 105), the height of foam in top of each kind of beer.
The next q lines contain the queries. Each query consists of a single integer integer x (1 ≤ x ≤ n), the index of a beer that should be added or removed from the shelf.
Output
For each query, print the answer for that query in one line.
Examples
Input
5 6
1 2 3 4 6
1
2
3
4
5
1
Output
0
1
3
5
6
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n, m, i, j, ans, x, vis[200005], cnt[500005], p[500005], q[500005],
all;
vector<long long> num[200005];
int main() {
scanf("%I64d%I64d", &n, &m);
for (i = 1; i <= n; i++) {
scanf("%I64d", &x);
for (j = 2; (j) * (j) <= x; j++) {
if (x % j == 0) {
num[i].push_back(j);
while (x % j == 0) x /= j;
}
}
if (x > 1) num[i].push_back(x);
sort(num[i].begin(), num[i].end());
}
for (i = 1; i <= 500000; i++) p[i] = 1;
for (i = 2; i <= 500000; i++) {
if (q[i]) continue;
for (j = 1; i * j <= 500000; j++) {
p[i * j] = -p[i * j];
q[i * j] = 1;
}
}
while (m--) {
scanf("%I64d", &x);
if (!vis[x]) {
all++;
for (i = 1; i < (1 << num[x].size()); i++) {
long long t = 1;
for (j = 0; j < num[x].size(); j++)
if ((i >> j) & 1) t *= num[x][j];
ans += p[t] * cnt[t] * (cnt[t] - 1) / 2;
cnt[t]++;
ans -= p[t] * cnt[t] * (cnt[t] - 1) / 2;
}
} else {
all--;
for (i = 1; i < (1 << num[x].size()); i++) {
long long t = 1;
for (j = 0; j < num[x].size(); j++)
if ((i >> j) & 1) t *= num[x][j];
ans += p[t] * cnt[t] * (cnt[t] - 1) / 2;
cnt[t]--;
ans -= p[t] * cnt[t] * (cnt[t] - 1) / 2;
}
}
vis[x] ^= 1;
printf("%I64d\n", (all * (all - 1)) / 2 - ans);
}
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Takahashi has a string S of length N consisting of digits from `0` through `9`.
He loves the prime number P. He wants to know how many non-empty (contiguous) substrings of S - there are N \times (N + 1) / 2 of them - are divisible by P when regarded as integers written in base ten.
Here substrings starting with a `0` also count, and substrings originated from different positions in S are distinguished, even if they are equal as strings or integers.
Compute this count to help Takahashi.
Constraints
* 1 \leq N \leq 2 \times 10^5
* S consists of digits.
* |S| = N
* 2 \leq P \leq 10000
* P is a prime number.
Input
Input is given from Standard Input in the following format:
N P
S
Output
Print the number of non-empty (contiguous) substrings of S that are divisible by P when regarded as an integer written in base ten.
Examples
Input
4 3
3543
Output
6
Input
4 2
2020
Output
10
Input
20 11
33883322005544116655
Output
68
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ar array
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
//freopen("input.txt","r",stdin);
int n, p;
string s;
cin >> n >> p >> s;
ll ans=0;
if(p==2) {
for(int i=0; i<n; ++i)
if((s[i]-'0')%2==0)
ans+=i+1;
} else if(p==5) {
for(int i=0; i<n; ++i)
if((s[i]-'0')%5==0)
ans+=i+1;
} else {
map<int, int> mp;
++mp[0];
int t=0, p2=1;
for(int i=n-1; ~i; --i) {
t=(t+(s[i]-'0')*p2)%p;
ans+=mp[t];
mp[t]++;
p2=p2*10%p;
//cout<<t<<" "<<ans<<endl;
}
}
cout << ans;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
In programming, hexadecimal notation is often used.
In hexadecimal notation, besides the ten digits 0, 1, ..., 9, the six letters `A`, `B`, `C`, `D`, `E` and `F` are used to represent the values 10, 11, 12, 13, 14 and 15, respectively.
In this problem, you are given two letters X and Y. Each X and Y is `A`, `B`, `C`, `D`, `E` or `F`.
When X and Y are seen as hexadecimal numbers, which is larger?
Constraints
* Each X and Y is `A`, `B`, `C`, `D`, `E` or `F`.
Input
Input is given from Standard Input in the following format:
X Y
Output
If X is smaller, print `<`; if Y is smaller, print `>`; if they are equal, print `=`.
Examples
Input
A B
Output
<
Input
E C
Output
>
Input
F F
Output
=
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
string x,y;
int main(){cin >> x >> y;cout << ((x <y)? "<":(x==y)?"=":">")<< endl;}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
You are given k sequences of integers. The length of the i-th sequence equals to n_i.
You have to choose exactly two sequences i and j (i ≠ j) such that you can remove exactly one element in each of them in such a way that the sum of the changed sequence i (its length will be equal to n_i - 1) equals to the sum of the changed sequence j (its length will be equal to n_j - 1).
Note that it's required to remove exactly one element in each of the two chosen sequences.
Assume that the sum of the empty (of the length equals 0) sequence is 0.
Input
The first line contains an integer k (2 ≤ k ≤ 2 ⋅ 10^5) — the number of sequences.
Then k pairs of lines follow, each pair containing a sequence.
The first line in the i-th pair contains one integer n_i (1 ≤ n_i < 2 ⋅ 10^5) — the length of the i-th sequence. The second line of the i-th pair contains a sequence of n_i integers a_{i, 1}, a_{i, 2}, ..., a_{i, n_i}.
The elements of sequences are integer numbers from -10^4 to 10^4.
The sum of lengths of all given sequences don't exceed 2 ⋅ 10^5, i.e. n_1 + n_2 + ... + n_k ≤ 2 ⋅ 10^5.
Output
If it is impossible to choose two sequences such that they satisfy given conditions, print "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), in the second line — two integers i, x (1 ≤ i ≤ k, 1 ≤ x ≤ n_i), in the third line — two integers j, y (1 ≤ j ≤ k, 1 ≤ y ≤ n_j). It means that the sum of the elements of the i-th sequence without the element with index x equals to the sum of the elements of the j-th sequence without the element with index y.
Two chosen sequences must be distinct, i.e. i ≠ j. You can print them in any order.
If there are multiple possible answers, print any of them.
Examples
Input
2
5
2 3 1 3 2
6
1 1 2 2 2 1
Output
YES
2 6
1 2
Input
3
1
5
5
1 1 1 1 1
2
2 3
Output
NO
Input
4
6
2 2 2 2 2 2
5
2 2 2 2 2
3
2 2 2
5
2 2 2 2 2
Output
YES
2 2
4 1
Note
In the first example there are two sequences [2, 3, 1, 3, 2] and [1, 1, 2, 2, 2, 1]. You can remove the second element from the first sequence to get [2, 1, 3, 2] and you can remove the sixth element from the second sequence to get [1, 1, 2, 2, 2]. The sums of the both resulting sequences equal to 8, i.e. the sums are equal.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t, n;
cin >> t;
vector<pair<int, pair<int, int>>> v;
for (int j = 0; j < t; j++) {
cin >> n;
int a[n], su = 0;
for (int i = 0; i < n; i++) {
cin >> a[i];
su += a[i];
}
for (int i = 0; i < n; i++) {
v.push_back({su - a[i], {j, i}});
}
}
int in = 1;
sort(v.begin(), v.end());
for (int i = 0; i < v.size() - 1; i++) {
if (v[i].first == v[i + 1].first &&
v[i].second.first != v[i + 1].second.first) {
cout << "YES\n";
cout << v[i].second.first + 1 << " " << v[i].second.second + 1 << endl;
cout << v[i + 1].second.first + 1 << " " << v[i + 1].second.second + 1
<< endl;
in = 0;
break;
}
}
if (in == 1) cout << "NO\n";
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Johnny's younger sister Megan had a birthday recently. Her brother has bought her a box signed as "Your beautiful necklace — do it yourself!". It contains many necklace parts and some magic glue.
The necklace part is a chain connecting two pearls. Color of each pearl can be defined by a non-negative integer. The magic glue allows Megan to merge two pearls (possibly from the same necklace part) into one. The beauty of a connection of pearls in colors u and v is defined as follows: let 2^k be the greatest power of two dividing u ⊕ v — [exclusive or](https://en.wikipedia.org/wiki/Exclusive_or#Computer_science) of u and v. Then the beauty equals k. If u = v, you may assume that beauty is equal to 20.
Each pearl can be combined with another at most once. Merging two parts of a necklace connects them. Using the glue multiple times, Megan can finally build the necklace, which is a cycle made from connected necklace parts (so every pearl in the necklace is combined with precisely one other pearl in it). The beauty of such a necklace is the minimum beauty of a single connection in it. The girl wants to use all available necklace parts to build exactly one necklace consisting of all of them with the largest possible beauty. Help her!
Input
The first line contains n (1 ≤ n ≤ 5 ⋅ 10^5) — the number of necklace parts in the box. Each of the next n lines contains two integers a and b (0 ≤ a, b < 2^{20}), which denote colors of pearls presented in the necklace parts. Pearls in the i-th line have indices 2i - 1 and 2i respectively.
Output
The first line should contain a single integer b denoting the maximum possible beauty of a necklace built from all given parts.
The following line should contain 2n distinct integers p_i (1 ≤ p_i ≤ 2n) — the indices of initial pearls in the order in which they appear on a cycle. Indices of pearls belonging to the same necklace part have to appear at neighboring positions in this permutation (so 1 4 3 2 is not a valid output, whereas 2 1 4 3 and 4 3 1 2 are). If there are many possible answers, you can print any.
Examples
Input
5
13 11
11 1
3 5
17 1
9 27
Output
3
8 7 9 10 5 6 1 2 3 4
Input
5
13 11
11 1
3 5
17 1
7 29
Output
2
8 7 10 9 5 6 4 3 2 1
Input
1
1 1
Output
20
2 1
Note
In the first example the following pairs of pearls are combined: (7, 9), (10, 5), (6, 1), (2, 3) and (4, 8). The beauties of connections equal correspondingly: 3, 3, 3, 20, 20.
The following drawing shows this construction.
<image>
### Response
```cpp
#include <bits/stdc++.h>
template <typename T>
class IntegerIterator {
public:
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = T*;
using reference = T;
using iterator_category = std::input_iterator_tag;
explicit IntegerIterator(T value) : value(value) {}
IntegerIterator& operator++() {
++value;
return *this;
}
IntegerIterator operator++(int) {
IntegerIterator copy = *this;
++value;
return copy;
}
IntegerIterator& operator--() {
--value;
return *this;
}
IntegerIterator operator--(int) {
IntegerIterator copy = *this;
--value;
return copy;
}
T operator*() const { return value; }
bool operator==(IntegerIterator rhs) const { return value == rhs.value; }
bool operator!=(IntegerIterator rhs) const { return !(*this == rhs); }
private:
T value;
};
template <typename T>
class IntegerRange {
public:
IntegerRange(T begin, T end) : begin_(begin), end_(end) { ; }
IntegerIterator<T> begin() const { return IntegerIterator<T>(begin_); }
IntegerIterator<T> end() const { return IntegerIterator<T>(end_); }
private:
T begin_;
T end_;
};
template <typename T>
class ReversedIntegerRange {
using IteratorType = std::reverse_iterator<IntegerIterator<T>>;
public:
ReversedIntegerRange(T begin, T end) : begin_(begin), end_(end) { ; }
IteratorType begin() const {
return IteratorType(IntegerIterator<T>(begin_));
}
IteratorType end() const { return IteratorType(IntegerIterator<T>(end_)); }
private:
T begin_;
T end_;
};
template <typename T>
IntegerRange<T> range(T to) {
return IntegerRange<T>(0, to);
}
template <typename T>
IntegerRange<T> range(T from, T to) {
return IntegerRange<T>(from, to);
}
template <typename T>
IntegerRange<T> inclusiveRange(T to) {
return IntegerRange<T>(0, to + 1);
}
template <typename T>
IntegerRange<T> inclusiveRange(T from, T to) {
return IntegerRange<T>(from, to + 1);
}
template <typename T>
ReversedIntegerRange<T> downrange(T from) {
return ReversedIntegerRange<T>(from, 0);
}
template <typename T>
ReversedIntegerRange<T> downrange(T from, T to) {
return ReversedIntegerRange<T>(from, to);
}
template <typename T>
ReversedIntegerRange<T> inclusiveDownrange(T from) {
return ReversedIntegerRange<T>(from + 1, 0);
}
template <typename T>
ReversedIntegerRange<T> inclusiveDownrange(T from, T to) {
return ReversedIntegerRange<T>(from + 1, to);
}
class DSU {
public:
explicit DSU(std::size_t n) : dsu(n) {
for (std::size_t i = 0; i < n; ++i) {
dsu[i] = i;
}
}
std::size_t getSet(std::size_t v) {
;
if (v == dsu[v]) {
return v;
}
return dsu[v] = getSet(dsu[v]);
}
bool unite(std::size_t u, std::size_t v) {
;
;
u = getSet(u);
v = getSet(v);
if (u == v) {
return false;
} else {
dsu[v] = u;
return true;
}
}
std::size_t components() const {
std::size_t count = 0;
for (std::size_t i = 0; i < dsu.size(); ++i) {
if (dsu[i] == i) {
++count;
}
}
return count;
}
private:
std::vector<std::size_t> dsu;
};
using namespace std;
class CDzhonniIOzhereleMegan {
public:
static constexpr int kStressCount = 0;
static void generateTest(std::ostream& test) {}
void solve(std::istream& in, std::ostream& out) {
int n;
in >> n;
vector<int> a(2 * n);
for (int i : range(2 * n)) {
in >> a[i];
}
for (int k : inclusiveDownrange(20, 0)) {
vector<int> degs(1 << k);
for (int i : range(2 * n)) {
++degs[a[i] % (1 << k)];
}
bool ok = true;
for (int i : range(1 << k)) {
if (degs[i] % 2 != 0) {
ok = false;
break;
}
}
if (!ok) {
continue;
}
DSU dsu(1 << k);
for (int i : range(n)) {
dsu.unite(a[2 * i] % (1 << k), a[2 * i + 1] % (1 << k));
}
int expected_components = 1;
for (int x : degs) {
if (x == 0) {
++expected_components;
}
}
if (dsu.components() != expected_components) {
continue;
}
out << k << "\n";
vector<set<int>> edges(1 << k);
for (int i : range(0, n)) {
edges[a[2 * i] % (1 << k)].insert(2 * i);
edges[a[2 * i + 1] % (1 << k)].insert(2 * i + 1);
}
int v = a[0] % (1 << k);
stack<int> s;
stack<int> s2;
s.push(v);
s2.push(-1);
vector<int> ans;
while (!s.empty()) {
auto w = s.top();
if (!edges[w].empty()) {
auto e = *edges[w].begin();
auto u = a[e ^ 1] % (1 << k);
edges[w].erase(e);
edges[u].erase(e ^ 1);
s.push(u);
s2.push(e ^ 1);
} else {
ans.push_back(w);
s.pop();
s2.pop();
}
}
map<pair<int, int>, set<int>> pdr;
for (int i : range(0, n)) {
pdr[{
a[2 * i] % (1 << k),
a[2 * i + 1] % (1 << k),
}]
.insert(2 * i);
pdr[{
a[2 * i + 1] % (1 << k),
a[2 * i] % (1 << k),
}]
.insert(2 * i + 1);
}
for (int i = 0; i + 1 < ans.size(); ++i) {
assert(!pdr.at({ans[i], ans[i + 1]}).empty());
auto z = *pdr.at({ans[i], ans[i + 1]}).begin();
out << z + 1 << ' ' << (z ^ 1) + 1 << " ";
pdr[{ans[i], ans[i + 1]}].erase(z);
pdr[{ans[i + 1], ans[i]}].erase(z ^ 1);
}
return;
}
}
};
int main() {
std::ios_base::sync_with_stdio(false);
CDzhonniIOzhereleMegan solver;
std::istream& in(std::cin);
std::ostream& out(std::cout);
in.tie(nullptr);
out << std::fixed;
out.precision(20);
solver.solve(in, out);
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
There is a sequence of length N: A_1, A_2, ..., A_N. Initially, this sequence is a permutation of 1, 2, ..., N.
On this sequence, Snuke can perform the following operation:
* Choose K consecutive elements in the sequence. Then, replace the value of each chosen element with the minimum value among the chosen elements.
Snuke would like to make all the elements in this sequence equal by repeating the operation above some number of times. Find the minimum number of operations required. It can be proved that, Under the constraints of this problem, this objective is always achievable.
Constraints
* 2 \leq K \leq N \leq 100000
* A_1, A_2, ..., A_N is a permutation of 1, 2, ..., N.
Input
Input is given from Standard Input in the following format:
N K
A_1 A_2 ... A_N
Output
Print the minimum number of operations required.
Examples
Input
4 3
2 3 1 4
Output
2
Input
3 3
1 2 3
Output
1
Input
8 3
7 3 1 8 4 6 2 5
Output
4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int N,K; cin >> N >> K;
cout <<(((N-K)+(K-2))/(K-1))+1<< endl;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm.
Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current sequence and adds them c times to the end. More formally, if we represent the current sequence as a1, a2, ..., an, then after we apply the described operation, the sequence transforms into a1, a2, ..., an[, a1, a2, ..., al] (the block in the square brackets must be repeated c times).
A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja.
Input
The first line contains integer m (1 ≤ m ≤ 105) — the number of stages to build a sequence.
Next m lines contain the description of the stages in the order they follow. The first number in the line is a type of stage (1 or 2). Type 1 means adding one number to the end of the sequence, in this case the line contains integer xi (1 ≤ xi ≤ 105) — the number to add. Type 2 means copying a prefix of length li to the end ci times, in this case the line further contains two integers li, ci (1 ≤ li ≤ 105, 1 ≤ ci ≤ 104), li is the length of the prefix, ci is the number of copyings. It is guaranteed that the length of prefix li is never larger than the current length of the sequence.
The next line contains integer n (1 ≤ n ≤ 105) — the number of elements Sereja is interested in. The next line contains the numbers of elements of the final sequence Sereja is interested in. The numbers are given in the strictly increasing order. It is guaranteed that all numbers are strictly larger than zero and do not exceed the length of the resulting sequence. Consider the elements of the final sequence numbered starting from 1 from the beginning to the end of the sequence.
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.
Output
Print the elements that Sereja is interested in, in the order in which their numbers occur in the input.
Examples
Input
6
1 1
1 2
2 2 1
1 3
2 5 2
1 4
16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Output
1 2 1 2 3 1 2 1 2 3 1 2 1 2 3 4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct Op {
int ty;
int a, b;
};
int main() {
int m;
cin >> m;
vector<int> a;
vector<Op> ops(m);
for (int i = 0; i < (int)(m); i++) {
scanf("%d", &ops[i].ty);
scanf("%d", &ops[i].a);
if (ops[i].ty == 2) {
scanf("%d", &ops[i].b);
}
}
int q;
cin >> q;
vector<long long> p(q);
for (int i = 0; i < (int)(q); i++) {
cin >> p[i];
p[i]--;
}
int j = 0;
long long n = 0;
for (int i = 0; i < (int)(m); i++) {
if (ops[i].ty == 1) {
if (a.size() < 100000) a.push_back(ops[i].a);
if (p[j] == n) {
cout << ops[i].a << " ";
j++;
}
n++;
} else {
int l = ops[i].a;
int c = ops[i].b;
for (int it = 0; it < (int)(c); it++) {
for (int k = 0; k < (int)(l); k++) {
if (a.size() == 100000) break;
a.push_back(a[k]);
}
if (a.size() == 100000) break;
}
while (j < q && p[j] < n + l * c) {
cout << a[(p[j] - n) % l] << " ";
j++;
}
n += l * c;
}
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Little Artyom decided to study probability theory. He found a book with a lot of nice exercises and now wants you to help him with one of them.
Consider two dices. When thrown each dice shows some integer from 1 to n inclusive. For each dice the probability of each outcome is given (of course, their sum is 1), and different dices may have different probability distributions.
We throw both dices simultaneously and then calculate values max(a, b) and min(a, b), where a is equal to the outcome of the first dice, while b is equal to the outcome of the second dice. You don't know the probability distributions for particular values on each dice, but you know the probability distributions for max(a, b) and min(a, b). That is, for each x from 1 to n you know the probability that max(a, b) would be equal to x and the probability that min(a, b) would be equal to x. Find any valid probability distribution for values on the dices. It's guaranteed that the input data is consistent, that is, at least one solution exists.
Input
First line contains the integer n (1 ≤ n ≤ 100 000) — the number of different values for both dices.
Second line contains an array consisting of n real values with up to 8 digits after the decimal point — probability distribution for max(a, b), the i-th of these values equals to the probability that max(a, b) = i. It's guaranteed that the sum of these values for one dice is 1. The third line contains the description of the distribution min(a, b) in the same format.
Output
Output two descriptions of the probability distribution for a on the first line and for b on the second line.
The answer will be considered correct if each value of max(a, b) and min(a, b) probability distribution values does not differ by more than 10 - 6 from ones given in input. Also, probabilities should be non-negative and their sums should differ from 1 by no more than 10 - 6.
Examples
Input
2
0.25 0.75
0.75 0.25
Output
0.5 0.5
0.5 0.5
Input
3
0.125 0.25 0.625
0.625 0.25 0.125
Output
0.25 0.25 0.5
0.5 0.25 0.25
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename T>
ostream& operator<<(ostream& cout, const vector<T>& a) {
if ((int)a.size() == 0) {
return (cout << "()");
}
cout << "(" << a[0];
for (int i = 1; i < (int)a.size(); i++) {
cout << "; " << a[i];
}
return (cout << ")");
}
template <typename T>
ostream& operator<<(ostream& cout, const set<T>& a) {
if ((int)a.size() == 0) {
return (cout << "{}");
}
auto it = a.begin();
cout << "{" << *it;
++it;
for (; it != a.end(); ++it) {
cout << "; " << *it;
}
return (cout << "}");
}
template <typename T>
ostream& operator<<(ostream& cout, const multiset<T>& a) {
if ((int)a.size() == 0) {
return (cout << "{}");
}
auto it = a.begin();
cout << "{" << *it;
++it;
for (; it != a.end(); ++it) {
cout << "; " << *it;
}
return (cout << "}");
}
template <typename T1, typename T2>
ostream& operator<<(ostream& cout, const pair<T1, T2>& a) {
return cout << "(" << a.first << "; " << a.second << ")";
}
const int nmax = 2000 * 1000;
const int inf = 2000 * 1000 * 1000;
const long long infl = 1000ll * 1000ll * 1000ll * 1000ll * 1000ll * 1000ll;
const int mod = 1000 * 1000 * 1000 + 7;
const long double pi = acos(-1.0);
int n;
long double ma[nmax], mi[nmax], ans1[nmax], ans2[nmax];
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> ma[i];
}
for (int i = 0; i < n; i++) {
cin >> mi[i];
}
long double x1 = 0, x2 = 0;
for (int i = n - 1; i >= 0; i--) {
long double c = ma[i];
long double d = mi[i];
long double b = (x1 - x2 + c + d);
long double cc = -(c + d) * x2 + d;
long double D = b * b - 4 * cc;
if (D < 1e-16) {
D = 0;
}
ans2[i] = (b + sqrtl(D)) / 2;
ans1[i] = c + d - ans2[i];
x1 += ans1[i];
x2 += ans2[i];
}
for (int i = 0; i < n; i++) {
printf("%.10lf ", (double)ans1[i]);
}
printf("\n");
for (int i = 0; i < n; i++) {
printf("%.10lf ", (double)ans2[i]);
}
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
At the children's festival, children were dancing in a circle. When music stopped playing, the children were still standing in a circle. Then Lena remembered, that her parents gave her a candy box with exactly k candies "Wilky May". Lena is not a greedy person, so she decided to present all her candies to her friends in the circle. Lena knows, that some of her friends have a sweet tooth and others do not. Sweet tooth takes out of the box two candies, if the box has at least two candies, and otherwise takes one. The rest of Lena's friends always take exactly one candy from the box.
Before starting to give candies, Lena step out of the circle, after that there were exactly n people remaining there. Lena numbered her friends in a clockwise order with positive integers starting with 1 in such a way that index 1 was assigned to her best friend Roma.
Initially, Lena gave the box to the friend with number l, after that each friend (starting from friend number l) took candies from the box and passed the box to the next friend in clockwise order. The process ended with the friend number r taking the last candy (or two, who knows) and the empty box. Please note that it is possible that some of Lena's friends took candy from the box several times, that is, the box could have gone several full circles before becoming empty.
Lena does not know which of her friends have a sweet tooth, but she is interested in the maximum possible number of friends that can have a sweet tooth. If the situation could not happen, and Lena have been proved wrong in her observations, please tell her about this.
Input
The only line contains four integers n, l, r and k (1 ≤ n, k ≤ 10^{11}, 1 ≤ l, r ≤ n) — the number of children in the circle, the number of friend, who was given a box with candies, the number of friend, who has taken last candy and the initial number of candies in the box respectively.
Output
Print exactly one integer — the maximum possible number of sweet tooth among the friends of Lena or "-1" (quotes for clarity), if Lena is wrong.
Examples
Input
4 1 4 12
Output
2
Input
5 3 4 10
Output
3
Input
10 5 5 1
Output
10
Input
5 4 5 6
Output
-1
Note
In the first example, any two friends can be sweet tooths, this way each person will receive the box with candies twice and the last person to take sweets will be the fourth friend.
In the second example, sweet tooths can be any three friends, except for the friend on the third position.
In the third example, only one friend will take candy, but he can still be a sweet tooth, but just not being able to take two candies. All other friends in the circle can be sweet tooths as well, they just will not be able to take a candy even once.
In the fourth example, Lena is wrong and this situation couldn't happen.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n, l, r, k;
inline bool check(long long y) {
if (y > n || y < 0) return false;
long long y1min, y1max, ost;
ost = k % (n + y);
y1min = y - min(n - r, y) - 1;
y1max = min(r, y);
if (y1min <= ost && ost <= y1max) {
cout << y << endl;
return true;
}
return false;
}
int main() {
cin >> n >> l >> r >> k;
r = (r + n - l) % n + 1;
k -= r;
if (k < 0) {
cout << -1 << endl;
return 0;
}
if (check(n - r + k + 1)) return 0;
if (check(n - r + k)) return 0;
if (n < 1e7) {
for (long long y = n; y >= 0; --y)
if (check(y)) return 0;
cout << -1 << endl;
return 0;
}
for (long long z = 1; k >= n; ++z) {
k -= n;
long long y2 = min(n - r, k / z);
long long y1 = min(r, (k + 1 - z * y2) / (z + 1));
long long dy = min(y2, r - y1);
long long left = z * (y2 + y1) + y1;
if (left - (y1 ? 1 : 0) == k || left == k || dy >= k - left) {
cout << y1 + y2 << endl;
return 0;
}
}
cout << -1 << endl;
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Write a program which reads the two dices constructed in the same way as Dice I, and determines whether these two dices are identical. You can roll a dice in the same way as Dice I, and if all integers observed from the six directions are the same as that of another dice, these dices can be considered as identical.
Constraints
* $0 \leq $ the integer assigned to a face $ \leq 100$
Input
In the first line, six integers assigned to faces of a dice are given in ascending order of their corresponding labels.
In the second line, six integers assigned to faces of another dice are given in ascending order of their corresponding labels.
Output
Print "Yes" if two dices are identical, otherwise "No" in a line.
Examples
Input
1 2 3 4 5 6
6 2 4 3 5 1
Output
Yes
Input
1 2 3 4 5 6
6 5 4 3 2 1
Output
No
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
struct Dice
{
int x, y;
int l, r, f, b, d, u;
void RollF()
{
--y;
int buff = d;
d = f;
f = u;
u = b;
b = buff;
}
void RollB()
{
++y;
int buff = d;
d = b;
b = u;
u = f;
f = buff;
}
void RollL()
{
--x;
int buff = d;
d = l;
l = u;
u = r;
r = buff;
}
void RollR()
{
++x;
int buff = d;
d = r;
r = u;
u = l;
l = buff;
}
};
int main()
{
auto input = []()
{
Dice dice;
cin >> dice.u;
cin >> dice.f;
cin >> dice.l;
cin >> dice.r;
cin >> dice.b;
cin >> dice.d;
return (dice);
};
Dice d1 = input();
Dice d2 = input();
for(int i = 0; i < 4; i++) {
d1.RollL();
for(int j = 0; j < 4; j++) {
d1.RollB();
for(int k = 0; k < 4; k++) {
d1.RollL();
if(d1.u == d2.u && d1.f == d2.f && d1.l == d2.l && d1.r == d2.r && d1.b == d2.b && d1.d == d2.d) {
cout << "Yes" << endl;
return (0);
}
}
}
}
cout << "No" << endl;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Old MacDonald has a farm and a large potato field, (1010 + 1) × (1010 + 1) square meters in size. The field is divided into square garden beds, each bed takes up one square meter.
Old McDonald knows that the Colorado potato beetle is about to invade his farm and can destroy the entire harvest. To fight the insects, Old McDonald wants to spray some beds with insecticides.
So Old McDonald went to the field, stood at the center of the central field bed and sprayed this bed with insecticides. Now he's going to make a series of movements and spray a few more beds. During each movement Old McDonald moves left, right, up or down the field some integer number of meters. As Old McDonald moves, he sprays all the beds he steps on. In other words, the beds that have any intersection at all with Old McDonald's trajectory, are sprayed with insecticides.
When Old McDonald finished spraying, he wrote out all his movements on a piece of paper. Now he wants to know how many beds won't be infected after the invasion of the Colorado beetles.
It is known that the invasion of the Colorado beetles goes as follows. First some bed on the field border gets infected. Than any bed that hasn't been infected, hasn't been sprayed with insecticides and has a common side with an infected bed, gets infected as well. Help Old McDonald and determine the number of beds that won't be infected by the Colorado potato beetle.
Input
The first line contains an integer n (1 ≤ n ≤ 1000) — the number of Old McDonald's movements.
Next n lines contain the description of Old McDonald's movements. The i-th of these lines describes the i-th movement. Each movement is given in the format "di xi", where di is the character that determines the direction of the movement ("L", "R", "U" or "D" for directions "left", "right", "up" and "down", correspondingly), and xi (1 ≤ xi ≤ 106) is an integer that determines the number of meters in the movement.
Output
Print a single integer — the number of beds that won't be infected by the Colorado potato beetle.
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
R 8
U 9
L 9
D 8
L 2
Output
101
Input
7
R 10
D 2
L 7
U 9
D 2
R 3
D 10
Output
52
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int DIM = 3000;
const int dx[4] = {-1, 0, 1, 0};
const int dy[4] = {0, 1, 0, -1};
char mrk[DIM][DIM];
vector<int> lstX, lstY;
pair<int, int> que[DIM * DIM];
pair<char, int> mut[DIM];
void add(pair<int, int> pos) {
for (int d = 0; d <= 1; ++d) {
lstX.push_back(pos.first + d);
lstY.push_back(pos.second + d);
}
}
int findX(int x) {
return lower_bound(lstX.begin(), lstX.end(), x) - lstX.begin();
}
int findY(int y) {
return lower_bound(lstY.begin(), lstY.end(), y) - lstY.begin();
}
void mark(pair<int, int> pos) {
pair<int, int> npos = make_pair(findX(pos.first), findY(pos.second));
mrk[npos.first][npos.second] = -1;
}
int main(void) {
int n;
cin >> n;
pair<int, int> pos(0, 0);
lstX.push_back(-2e9);
lstX.push_back(2e9);
lstY.push_back(-2e9);
lstY.push_back(2e9);
add(pos);
for (int i = 1; i <= n; ++i) {
cin >> mut[i].first >> mut[i].second;
if (mut[i].first == 'U') pos.first += mut[i].second;
if (mut[i].first == 'R') pos.second += mut[i].second;
if (mut[i].first == 'D') pos.first -= mut[i].second;
if (mut[i].first == 'L') pos.second -= mut[i].second;
add(pos);
}
sort(lstX.begin(), lstX.end());
lstX.resize(unique(lstX.begin(), lstX.end()) - lstX.begin());
sort(lstY.begin(), lstY.end());
lstY.resize(unique(lstY.begin(), lstY.end()) - lstY.begin());
pos = make_pair(0, 0);
for (int i = 1; i <= n; ++i) {
if (mut[i].first == 'U') {
int px1 = findX(pos.first), px2 = findX(pos.first + mut[i].second),
py = findY(pos.second);
for (; px1 <= px2; ++px1) mrk[px1][py] = -1;
pos.first += mut[i].second;
}
if (mut[i].first == 'D') {
int px1 = findX(pos.first), px2 = findX(pos.first - mut[i].second),
py = findY(pos.second);
for (; px1 >= px2; --px1) mrk[px1][py] = -1;
pos.first -= mut[i].second;
}
if (mut[i].first == 'R') {
int px = findX(pos.first), py1 = findY(pos.second),
py2 = findY(pos.second + mut[i].second);
for (; py1 <= py2; ++py1) mrk[px][py1] = -1;
pos.second += mut[i].second;
}
if (mut[i].first == 'L') {
int px = findX(pos.first), py1 = findY(pos.second),
py2 = findY(pos.second - mut[i].second);
for (; py1 >= py2; --py1) mrk[px][py1] = -1;
pos.second -= mut[i].second;
}
}
que[0] = make_pair(0, 0);
mrk[0][0] = 1;
for (int st = 0, en = 0; st <= en; ++st) {
pair<int, int> pos = que[st];
for (int d = 0; d < 4; ++d) {
pair<int, int> npos = make_pair(pos.first + dx[d], pos.second + dy[d]);
if (npos.first < 0 or npos.first >= lstX.size()) continue;
if (npos.second < 0 or npos.second >= lstY.size()) continue;
if (mrk[npos.first][npos.second] == 0) {
mrk[npos.first][npos.second] = 1;
que[++en] = npos;
}
}
}
long long ans = 0;
for (int i = 0; i < lstX.size(); ++i)
for (int j = 0; j < lstY.size(); ++j)
if (mrk[i][j] <= 0)
ans += 1LL * (lstX[i + 1] - lstX[i]) * (lstY[j + 1] - lstY[j]);
cout << ans;
return 0;
}
``` |
Subsets and Splits