text
stringlengths 424
69.5k
|
---|
### Prompt
In cpp, your task is to solve the following problem:
A card pyramid of height 1 is constructed by resting two cards against each other. For h>1, a card pyramid of height h is constructed by placing a card pyramid of height h-1 onto a base. A base consists of h pyramids of height 1, and h-1 cards on top. For example, card pyramids of heights 1, 2, and 3 look as follows:
<image>
You start with n cards and build the tallest pyramid that you can. If there are some cards remaining, you build the tallest pyramid possible with the remaining cards. You repeat this process until it is impossible to build another pyramid. In the end, how many pyramids will you have constructed?
Input
Each test consists of multiple test cases. The first line contains a single integer t (1≤ t≤ 1000) — the number of test cases. Next t lines contain descriptions of test cases.
Each test case contains a single integer n (1≤ n≤ 10^9) — the number of cards.
It is guaranteed that the sum of n over all test cases does not exceed 10^9.
Output
For each test case output a single integer — the number of pyramids you will have constructed in the end.
Example
Input
5
3
14
15
24
1
Output
1
2
1
3
0
Note
In the first test, you construct a pyramid of height 1 with 2 cards. There is 1 card remaining, which is not enough to build a pyramid.
In the second test, you build two pyramids, each of height 2, with no cards remaining.
In the third test, you build one pyramid of height 3, with no cards remaining.
In the fourth test, you build one pyramid of height 3 with 9 cards remaining. Then you build a pyramid of height 2 with 2 cards remaining. Then you build a final pyramid of height 1 with no cards remaining.
In the fifth test, one card is not enough to build any pyramids.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int32_t main() {
long long t;
cin >> t;
;
while (t--) {
long long n;
cin >> n;
;
long long sum = 0;
while (n > 1) {
long long h = floor((sqrt(1 + 24 * n) - 1) / 6);
n = n - h * (3 * h + 1) / 2;
sum++;
}
cout << sum << endl;
;
}
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Little Petya loves training spiders. Petya has a board n × m in size. Each cell of the board initially has a spider sitting on it. After one second Petya chooses a certain action for each spider, and all of them humbly perform its commands. There are 5 possible commands: to stay idle or to move from current cell to some of the four side-neighboring cells (that is, one command for each of the four possible directions). Petya gives the commands so that no spider leaves the field. It is allowed for spiders to pass through each other when they crawl towards each other in opposite directions. All spiders crawl simultaneously and several spiders may end up in one cell. Petya wants to know the maximum possible number of spider-free cells after one second.
Input
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 40, n·m ≤ 40) — the board sizes.
Output
In the first line print the maximum number of cells without spiders.
Examples
Input
1 1
Output
0
Input
2 3
Output
4
Note
In the first sample the only possible answer is:
s
In the second sample one of the possible solutions is:
rdl
rul
s denotes command "stay idle", l, r, d, u denote commands "crawl left", "crawl right", "crawl down", "crawl up", correspondingly.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m, l, c, h[45][45];
void d(int x, int y) {
if (y == m) x++, y = 0;
if (c == l) return;
if (x == n) {
if (h[n - 1][m - 1])
l = c;
else
l = c + 1;
return;
}
c++;
if (x) h[x - 1][y]++;
if (y) h[x][y - 1]++;
if (x + 1 < n) h[x + 1][y]++;
if (y + 1 < m) h[x][y + 1]++;
h[x][y]++;
d(x, y + 1);
c--;
if (x) h[x - 1][y]--;
if (y) h[x][y - 1]--;
if (x + 1 < n) h[x + 1][y]--;
if (y + 1 < m) h[x][y + 1]--;
h[x][y]--;
if (x && h[x - 1][y] == 0) return;
if (x + 1 == n && y && h[x][y - 1] == 0) return;
d(x, y + 1);
}
int main() {
scanf("%d%d", &n, &m);
memset(h, 0, sizeof(h));
l = 15;
d(0, 0);
printf("%d\n", n * m - l);
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection.
At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency.
* Baggage is shaped like a rectangular parallelepiped with only one side short.
* Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular.
* Individual items are packed so that their rectangular sides are parallel to the sides of the baggage.
* On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle.
Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal.
Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included.
Input
The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format.
> H W
> Analysis result 1
> Analysis result 2
> ...
> Analysis result H
>
H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.).
For all datasets, it is guaranteed that there are no more than seven material types.
Output
For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line.
Sample Input
6
1 1
..
3 3
...
.W.
...
10 10
..........
.DDDDCC ..
.DDDDCC ..
.DDDDCC ..
ADDDDCCC ..
AAA .. CCC ..
AAABB BBC ..
AAABBBB ...
..BBBBB ...
..........
10 10
..........
.DDDDDD ...
.DDDDCC ..
.DDDDCC ..
ADDDDCCC ..
AAA .. CCC ..
AAABB BBC ..
AAABBBB ...
..BBBBB ...
..........
10 10
R..E..C.T.
R.EEE.C.T.
.EEEEE ....
EEEEEEE ...
.EEEEEEE ..
..EEEEEEE.
... EEEEEEE
.... EEEEE.
..... EEE ..
...... E ...
16 50
.................................................................
......... AAAAAAAAAAAAAAAAA ............................
.... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .....
.... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .....
.... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ....
.... PPP .............. AAAAA.AAAAAAAAAAAAAAAA .......
.... PPP ................ A .... AAA.AAAAAAAAAA ........
.... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........
..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........
..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ......
.... PPP .................. AAAAAAAAAAA .....
MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA ....
MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ...
MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ...
MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ...
MMMMMMMMMMMMMMMMMMMMMM ............................
Output for the Sample Input
SAFE
SAFE
SAFE
SUSPICIOUS
SUSPICIOUS
SUSPICIOUS
Example
Input
6
1 1
.
3 3
...
.W.
...
10 10
..........
.DDDDCCC..
.DDDDCCC..
.DDDDCCC..
ADDDDCCC..
AAA..CCC..
AAABBBBC..
AAABBBB...
..BBBBB...
..........
10 10
..........
.DDDDDD...
.DDDDCCC..
.DDDDCCC..
ADDDDCCC..
AAA..CCC..
AAABBBBC..
AAABBBB...
..BBBBB...
..........
10 10
R..E..C.T.
R.EEE.C.T.
.EEEEE....
EEEEEEE...
.EEEEEEE..
..EEEEEEE.
...EEEEEEE
....EEEEE.
.....EEE..
......E...
16 50
..................................................
.........AAAAAAAAAAAAAAAA.........................
....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.....
....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.....
....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA....
....PPP..............AAAAA.AAAAAAAAAAAAAAAA.......
....PPP................A....AAA.AAAAAAAAAA........
....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........
..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........
..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA......
....PPP............................AAAAAAAAAA.....
MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA....
MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA...
MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA...
MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA...
MMMMMMMMMMMMMMMMMMMMMM............................
Output
SAFE
SAFE
SAFE
SUSPICIOUS
SUSPICIOUS
SUSPICIOUS
### Response
```cpp
#include <bits/stdc++.h>
#define ll long long
#define fi first
#define se second
#define rep(i, j, k) for (auto i = j; i < k; i++)
#define rrep(i, j, k) for (auto i = j; i > k; i--)
using namespace std;
void solve() {
int h, w; cin >> h >> w;
char a[51][51], b[51][51];
set<char> set1;
rep(i, 0, h) rep(j, 0, w) {
cin >> a[i][j];
if (a[i][j] == '.') continue;
set1.insert(a[i][j]);
}
if (set1.size() < 1) {
cout << "SAFE" << endl;
return;
}
assert(set1.size() < 8);
vector<char> v;
for (auto ite : set1) v.push_back(ite);
sort(v.begin(), v.end());
do {
rep(i, 0, h) rep(j, 0, w) b[i][j] = a[i][j];
bool ok = true;
rep(nowi, 0, (int)v.size()) {
int left = INT_MAX, right = INT_MIN;
rep(j, 0, w) rep(i, 0, h) {
if (b[i][j] == v[nowi]) {
left = min(left, j);
right = max(right, j);
}
}
int up = INT_MAX, down = INT_MIN;
rep(i, 0, h) rep(j, 0, w) {
if (b[i][j] == v[nowi]) {
up = min(up, i);
down = max(down, i);
}
}
[&]{
rep(i, up, down + 1) rep(j, left, right + 1) {
if (b[i][j] != v[nowi] && b[i][j] != '*') {
ok = false;
return;
}
}
}();
if (ok) {
rep(i, up, down + 1) rep(j, left, right + 1) {
if (b[i][j] == v[nowi]) b[i][j] = '*';
}
} else {
break;
}
}
if (ok) {
cout << "SAFE" << endl;
return;
}
} while (next_permutation(v.begin(), v.end()));
cout << "SUSPICIOUS" << endl;
}
int main() {
int n; cin >> n;
rep(i, 0, n) solve();
}
//////////////////////////////////////////////////////////////////////////
//NOTE
//////////////////////////////////////////////////////////////////////////
// 一つのカバンに入っている物の数は7種類以下とわかっているので、
// どんな順でx座標が大きくなっていくのかを、全通り試していければ良い.
``` |
### Prompt
Your task is to create a Cpp solution to 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 N, M, K, s, t, r, b, tot, R[501], B[501], fst[501],
cnt = 1, to[100001], flow[100001], len[100001], nxt[100001], mflow[501],
pre[501];
long long dis[501], ans;
bool in[501];
int get() {
int x = 0;
char c = getchar();
while (c < '0' || c > '9') c = getchar();
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x;
}
void add(int u, int v, int f, int l) {
to[++cnt] = v, flow[cnt] = f, len[cnt] = l, nxt[cnt] = fst[u], fst[u] = cnt;
to[++cnt] = u, flow[cnt] = 0, len[cnt] = -l, nxt[cnt] = fst[v], fst[v] = cnt;
}
bool spfa() {
memset(dis, 0x3f, sizeof(dis));
memset(in, 0, sizeof(in));
queue<int> q;
q.push(s);
dis[s] = 0;
in[s] = 1;
mflow[s] = 0x3fffffff;
while (!q.empty()) {
int u = q.front();
q.pop();
in[u] = 0;
for (int i = fst[u]; i; i = nxt[i])
if (flow[i] && dis[to[i]] > dis[u] + len[i]) {
dis[to[i]] = dis[u] + len[i];
mflow[to[i]] = min(mflow[u], flow[i]);
pre[to[i]] = i;
if (!in[to[i]]) q.push(to[i]), in[to[i]] = 1;
}
}
return dis[t] != 0x3f3f3f3f3f3f3f3f;
}
void upd() {
int x = t;
while (x != s) {
x = pre[x];
flow[x] -= mflow[t], flow[x ^ 1] += mflow[t], x = to[x ^ 1];
}
ans += dis[t] * mflow[t];
}
int main() {
N = get(), M = get(), K = get(), r = get(), b = get(), s = 0, t = N + M + 1;
for (int i = 1; i <= N; i++) {
char c;
cin >> c;
c == 'R' || c == 'B' ? tot++,
c == 'R' ? add(s, i, 1, -0x3fffffff),
add(s, i, 0x3fffffff, 0)
: (add(i, t, 1, -0x3fffffff), add(i, t, 0x3fffffff, 0))
: (add(s, i, 0x3fffffff, 0), add(i, t, 0x3fffffff, 0));
}
for (int i = 1; i <= M; i++) {
char c;
cin >> c;
c == 'R' || c == 'B' ? tot++,
c == 'R' ? add(i + N, t, 1, -0x3fffffff),
add(i + N, t, 0x3fffffff, 0)
: (add(s, i + N, 1, -0x3fffffff), add(s, i + N, 0x3fffffff, 0))
: (add(s, i + N, 0x3fffffff, 0), add(i + N, t, 0x3fffffff, 0));
}
for (int i = 1; i <= K; i++) {
int u, v;
cin >> u >> v;
add(u, v + N, 1, r);
R[i] = cnt - 1;
add(v + N, u, 1, b);
B[i] = cnt - 1;
}
while (spfa()) {
if (dis[t] <= 0)
upd();
else if (ans + tot * 0x3fffffff < 0x3fffffff)
break;
}
ans += 1ll * tot * 0x3fffffff;
if (ans > 0x3fffffff) {
cout << -1 << endl;
return 0;
}
cout << ans << endl;
for (int i = 1; i <= K; i++)
cout << (!flow[R[i]] ? 'R' : !flow[B[i]] ? 'B' : 'U');
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
AtCoDeer the deer recently bought three paint cans. The color of the one he bought two days ago is a, the color of the one he bought yesterday is b, and the color of the one he bought today is c. Here, the color of each paint can is represented by an integer between 1 and 100, inclusive.
Since he is forgetful, he might have bought more than one paint can in the same color. Count the number of different kinds of colors of these paint cans and tell him.
Constraints
* 1≦a,b,c≦100
Input
The input is given from Standard Input in the following format:
a b c
Output
Print the number of different kinds of colors of the paint cans.
Examples
Input
3 1 4
Output
3
Input
3 3 33
Output
2
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int x;
map<int,int> a;
int main(){
cin>>x;a[x]++;
cin>>x;a[x]++;
cin>>x;a[x]++;
cout<<a.size()<<endl;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
You are given an integer sequence A of length N and an integer K. You will perform the following operation on this sequence Q times:
* Choose a contiguous subsequence of length K, then remove the smallest element among the K elements contained in the chosen subsequence (if there are multiple such elements, choose one of them as you like).
Let X and Y be the values of the largest and smallest element removed in the Q operations. You would like X-Y to be as small as possible. Find the smallest possible value of X-Y when the Q operations are performed optimally.
Constraints
* 1 \leq N \leq 2000
* 1 \leq K \leq N
* 1 \leq Q \leq N-K+1
* 1 \leq A_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K Q
A_1 A_2 ... A_N
Output
Print the smallest possible value of X-Y.
Examples
Input
5 3 2
4 3 1 5 2
Output
1
Input
10 1 6
1 1 2 3 5 8 13 21 34 55
Output
7
Input
11 7 5
24979445 861648772 623690081 433933447 476190629 262703497 211047202 971407775 628894325 731963982 822804784
Output
451211184
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n,K,Q,a[2005],w[2005],s[2005],temp[2005];
int main(){
scanf("%d%d%d",&n,&K,&Q);
for(int i=1;i<=n;i++) scanf("%d",&a[i]),w[i]=a[i];
sort(w+1,w+n+1);
int ans=2e9;
for(int i=1;i<=n;i++){
int top=0;
for(int p=1,j;p<=n;){
if(a[p]<w[i]){
p++;continue;
}
for(j=p;a[j]>=w[i]&&j<=n;j++) temp[j-p+1]=a[j];
sort(temp+1,temp+j-p+1);
for(int k=1;k<=j-p-K+1;k++) s[++top]=temp[k];
p=j;
}
sort(s+1,s+top+1);
if(top>=Q) ans=min(ans,s[Q]-s[1]);
}
printf("%d",ans);
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food:
* on Mondays, Thursdays and Sundays he eats fish food;
* on Tuesdays and Saturdays he eats rabbit stew;
* on other days of week he eats chicken stake.
Polycarp plans to go on a trip and already packed his backpack. His backpack contains:
* a daily rations of fish food;
* b daily rations of rabbit stew;
* c daily rations of chicken stakes.
Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally.
Input
The first line of the input contains three positive integers a, b and c (1 ≤ a, b, c ≤ 7⋅10^8) — the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly.
Output
Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally.
Examples
Input
2 1 1
Output
4
Input
3 2 2
Output
7
Input
1 100 1
Output
3
Input
30 20 10
Output
39
Note
In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday — rabbit stew and during Wednesday — chicken stake. So, after four days of the trip all food will be eaten.
In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack.
In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long N, K, M, a, b, i, j, c, d, A, B, C;
string S;
void solve() {
cin >> a >> b >> c;
A = a / 3;
B = b / 2;
C = c / 2;
d = min(A, min(B, C));
A = a - 3 * d;
B = b - 2 * d;
C = c - 2 * d;
d *= 7;
int Aa[8], Bb[4];
Aa[1] = 1;
Aa[4] = 1;
Aa[7] = 1;
Aa[2] = 2;
Aa[6] = 2;
Aa[5] = 3;
Aa[3] = 3;
Bb[1] = A;
Bb[2] = B;
Bb[3] = C;
int q = 0;
for (int i = 1; i < 8; i++) {
j = i;
int count = 7, p = 0;
int Cc[8];
for (int i = 1; i < 8; i++) Cc[i] = Bb[i];
while (count--) {
if (Cc[Aa[j]] > 0) {
p++;
Cc[Aa[j]]--;
} else
break;
j++;
if (j == 8) j = 1;
}
q = max(q, p);
}
cout << q + d << endl;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t = 1;
while (t--) {
solve();
}
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Urpal lives in a big city. He has planned to meet his lover tonight.
The city has n junctions numbered from 1 to n. The junctions are connected by m directed streets, all the roads have equal length. Urpal lives in junction a and the date is planned in a restaurant in junction b. He wants to use public transportation to get to junction b. There are k bus transportation companies. At the beginning of every second, a bus from the i-th company chooses a random shortest path between junction si and junction ti and passes through it. There might be no path from si to ti. In that case no bus will leave from si to ti. If a bus passes through a junction where Urpal stands, he can get on the bus. He can also get off the bus at any junction along the path.
Now Urpal wants to know if it's possible to go to the date using public transportation in a finite amount of time (the time of travel is the sum of length of the traveled roads) and what is the minimum number of buses he should take in the worst case.
At any moment Urpal knows only his own position and the place where the date will be. When he gets on the bus he knows only the index of the company of this bus. Of course Urpal knows the city map and the the pairs (si, ti) for each company.
Note that Urpal doesn't know buses velocity.
Input
The first line of the input contains four integers n, m, a, b (2 ≤ n ≤ 100; 0 ≤ m ≤ n·(n - 1); 1 ≤ a, b ≤ n; a ≠ b).
The next m lines contain two integers each ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) describing a directed road from junction ui to junction vi. All roads in the input will be distinct.
The next line contains an integer k (0 ≤ k ≤ 100). There will be k lines after this, each containing two integers si and ti (1 ≤ si, ti ≤ n; si ≠ ti) saying there is a bus route starting at si and ending at ti. Please note that there might be no path from si to ti, this case is described in the problem statement.
Output
In the only line of output print the minimum number of buses Urpal should get on on his way in the worst case. If it's not possible to reach the destination in the worst case print -1.
Examples
Input
7 8 1 7
1 2
1 3
2 4
3 4
4 6
4 5
6 7
5 7
3
2 7
1 4
5 7
Output
2
Input
4 4 1 2
1 2
1 3
2 4
3 4
1
1 4
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m, k, vs[200], a, b, d[2000][2000], aa[2000], bb[2000], ans = -1;
int que[2000000], dist[20000], vis[20000], f[2000], tot = 0, dp[2000];
int bo[2000][2000], head[200000], line = 0, p[2000][2000];
int dfs(int x, int s, int k) {
if (vis[x] == tot) return dp[x];
int cmp = -1;
vis[x] = tot;
for (int i = 1; i <= n; ++i) {
int y = i;
if (d[x][y] == 1 && d[x][bb[k]] == d[y][bb[k]] + 1) {
cmp = max(cmp, dfs(y, s, k));
}
}
if (cmp == -1) cmp = 1e9;
cmp = min(cmp, f[x]);
return dp[x] = cmp;
}
int main() {
scanf("%d%d%d%d", &n, &m, &a, &b);
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j)
if (i != j) d[i][j] = 1e9;
int x, y;
for (int i = 1; i <= m; ++i) {
scanf("%d%d", &x, &y);
d[x][y] = 1;
}
for (int k = 1; k <= n; ++k)
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j) d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
scanf("%d", &k);
for (int i = 1; i <= n; ++i) f[i] = 1e9, dp[i] = 1e9;
memset(vs, 0, sizeof(vs));
for (int i = 1; i <= k; ++i) {
scanf("%d%d", &x, &y);
aa[i] = x, bb[i] = y;
if (d[x][y] == 1e9) continue;
for (int l = 1; l <= n; ++l)
if (d[x][l] + d[l][y] == d[x][y]) ++vs[d[x][l]];
for (int j = 1; j <= n; ++j)
if (d[x][j] + d[j][y] == d[x][y]) {
if (vs[d[x][j]] == 1) bo[i][j] = 1;
vs[d[x][j]] = 0;
}
}
int t = 1;
f[b] = 0;
while (t) {
t = 0;
for (int i = 1; i <= k; ++i)
for (int j = 1; j <= n; ++j)
if (bo[i][j]) {
tot++;
int cnt = dfs(j, i, i) + 1;
if (cnt < f[j]) f[j] = cnt, t = 1;
}
}
if (f[a] == 1e9)
printf("-1");
else
printf("%d\n", f[a]);
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero.
Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9).
Input
The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 109; 0 ≤ m ≤ n).
Output
Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9).
Examples
Input
5 3 2
Output
3
Input
5 4 2
Output
6
Note
Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points.
Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4.
Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const unsigned long long P = 239017, MaxN = 2100000, INF = 100000000;
const long long mod = 1000000009;
long long step(int t) {
if (t == 0) return 1;
if (t % 2 == 0) {
long long a = step(t / 2);
return (a * a) % mod;
}
return (2 * step(t - 1)) % mod;
}
int n, m, k;
int main() {
scanf("%d%d%d", &n, &m, &k);
int t = m - n % k - (n / k) * (k - 1);
if (t <= 0) {
printf("%d", m);
return 0;
}
long long ans =
(((long long)k * (step(t + 1) - 2)) % mod + m - t * k + mod) % mod;
printf("%I64d", ans);
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Fibonacci numbers are the sequence of integers: f0 = 0, f1 = 1, f2 = 1, f3 = 2, f4 = 3, f5 = 5, ..., fn = fn - 2 + fn - 1. So every next number is the sum of the previous two.
Bajtek has developed a nice way to compute Fibonacci numbers on a blackboard. First, he writes a 0. Then, below it, he writes a 1. Then he performs the following two operations:
* operation "T": replace the top number with the sum of both numbers;
* operation "B": replace the bottom number with the sum of both numbers.
If he performs n operations, starting with "T" and then choosing operations alternately (so that the sequence of operations looks like "TBTBTBTB..."), the last number written will be equal to fn + 1.
Unfortunately, Bajtek sometimes makes mistakes and repeats an operation two or more times in a row. For example, if Bajtek wanted to compute f7, then he would want to do n = 6 operations: "TBTBTB". If he instead performs the sequence of operations "TTTBBT", then he will have made 3 mistakes, and he will incorrectly compute that the seventh Fibonacci number is 10. The number of mistakes in the sequence of operations is the number of neighbouring equal operations («TT» or «BB»).
You are given the number n of operations that Bajtek has made in an attempt to compute fn + 1 and the number r that is the result of his computations (that is last written number). Find the minimum possible number of mistakes that Bajtek must have made and any possible sequence of n operations resulting in r with that number of mistakes.
Assume that Bajtek always correctly starts with operation "T".
Input
The first line contains the integers n and r (1 ≤ n, r ≤ 106).
Output
The first line of the output should contain one number — the minimum possible number of mistakes made by Bajtek. The second line should contain n characters, starting with "T", describing one possible sequence of operations with that number of mistakes. Each character must be either "T" or "B".
If the required sequence doesn't exist, output "IMPOSSIBLE" (without quotes).
Examples
Input
6 10
Output
2
TBBTTB
Input
4 5
Output
0
TBTB
Input
2 1
Output
IMPOSSIBLE
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int mx = 1000005;
const int inf = 0x3f3f3f3f;
int t, n, r, ans;
char a[mx], c[mx];
void solve(int t, int b) {
int j = 1;
while (t != b && t >= 0 && b >= 0) {
if (t > b) {
c[j++] = 'T';
t -= b;
} else {
c[j++] = 'B';
b -= t;
}
}
if (j != n || t != 1) return;
c[n] = 'T';
int sum = 0;
for (int i = 0; i < n; i++)
if (c[i] == c[i + 1]) sum++;
if (sum < ans) {
ans = sum;
for (int i = 0; i < n; i++) {
a[i] = c[n - i];
}
a[n] = '\n';
}
}
int main() {
while (scanf("%d%d", &n, &r) != EOF) {
ans = inf;
for (int i = 1; i <= r; i++) {
solve(i, r);
solve(r, i);
}
if (ans == inf)
printf("IMPOSSIBLE\n");
else {
printf("%d\n", ans);
for (int i = 0; i < n; i++) printf("%c", a[i]);
puts("");
}
}
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
As we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with n vertices and m edges. There's a character written on each edge, a lowercase English letter.
<image>
Max and Lucas are playing the game. Max goes first, then Lucas, then Max again and so on. Each player has a marble, initially located at some vertex. Each player in his/her turn should move his/her marble along some edge (a player can move the marble from vertex v to vertex u if there's an outgoing edge from v to u). If the player moves his/her marble from vertex v to vertex u, the "character" of that round is the character written on the edge from v to u. There's one additional rule; the ASCII code of character of round i should be greater than or equal to the ASCII code of character of round i - 1 (for i > 1). The rounds are numbered for both players together, i. e. Max goes in odd numbers, Lucas goes in even numbers. The player that can't make a move loses the game. The marbles may be at the same vertex at the same time.
Since the game could take a while and Lucas and Max have to focus on finding Dart, they don't have time to play. So they asked you, if they both play optimally, who wins the game?
You have to determine the winner of the game for all initial positions of the marbles.
Input
The first line of input contains two integers n and m (2 ≤ n ≤ 100, <image>).
The next m lines contain the edges. Each line contains two integers v, u and a lowercase English letter c, meaning there's an edge from v to u written c on it (1 ≤ v, u ≤ n, v ≠ u). There's at most one edge between any pair of vertices. It is guaranteed that the graph is acyclic.
Output
Print n lines, a string of length n in each one. The j-th character in i-th line should be 'A' if Max will win the game in case her marble is initially at vertex i and Lucas's marble is initially at vertex j, and 'B' otherwise.
Examples
Input
4 4
1 2 b
1 3 a
2 4 c
3 4 b
Output
BAAA
ABAA
BBBA
BBBB
Input
5 8
5 3 h
1 2 c
3 1 c
3 2 r
5 1 r
4 3 z
5 4 r
5 2 h
Output
BABBB
BBBBB
AABBB
AAABA
AAAAB
Note
Here's the graph in the first sample test case:
<image>
Here's the graph in the second sample test case:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
const int maxn = 1e2 + 5;
const int inf = 0x3f3f3f3f;
struct node {
int v, next, w;
} e[maxn * maxn / 2];
int head[maxn], tot, dp[maxn][maxn][30];
int dfs(int u, int v, int val) {
if (dp[u][v][val] != -1) return dp[u][v][val];
dp[u][v][val] = 0;
for (int i = head[u]; i + 1; i = e[i].next) {
if (e[i].w >= val && !dfs(v, e[i].v, e[i].w)) dp[u][v][val] = 1;
}
return dp[u][v][val];
}
void add(int u, int v, int w) {
e[tot].v = v;
e[tot].w = w;
e[tot].next = head[u];
head[u] = tot++;
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
memset(head, -1, sizeof(head));
memset(dp, -1, sizeof(dp));
while (m--) {
int u, v;
char s[2];
scanf("%d%d%s", &u, &v, s);
add(u, v, s[0] - 'a');
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (dfs(i, j, 0))
printf("A");
else
printf("B");
}
puts("");
}
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.
Note that the order of the points inside the group of three chosen points doesn't matter.
Input
The first line contains two integers: n and d (1 ≤ n ≤ 105; 1 ≤ d ≤ 109). The next line contains n integers x1, x2, ..., xn, their absolute value doesn't exceed 109 — the x-coordinates of the points that Petya has got.
It is guaranteed that the coordinates of the points in the input strictly increase.
Output
Print a single integer — the number of groups of three points, where the distance between two farthest points doesn't exceed d.
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
4 3
1 2 3 4
Output
4
Input
4 2
-3 -2 -1 0
Output
2
Input
5 19
1 10 20 30 50
Output
1
Note
In the first sample any group of three points meets our conditions.
In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.
In the third sample only one group does: {1, 10, 20}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, d;
int arr[100012];
cin >> n >> d;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
long long lower = 0;
int higher = 0;
long long kount = 0;
arr[n] = 1e9 + 7;
for (long long i = 0; i < n; i++) {
while (arr[higher] - arr[i] <= d && higher < n) higher++;
kount = kount + (higher - i - 1) * (higher - i - 2) / 2;
}
cout << kount << endl;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
There is a bar of chocolate with a height of H blocks and a width of W blocks. Snuke is dividing this bar into exactly three pieces. He can only cut the bar along borders of blocks, and the shape of each piece must be a rectangle.
Snuke is trying to divide the bar as evenly as possible. More specifically, he is trying to minimize S_{max} - S_{min}, where S_{max} is the area (the number of blocks contained) of the largest piece, and S_{min} is the area of the smallest piece. Find the minimum possible value of S_{max} - S_{min}.
Constraints
* 2 ≤ H, W ≤ 10^5
Input
Input is given from Standard Input in the following format:
H W
Output
Print the minimum possible value of S_{max} - S_{min}.
Examples
Input
3 5
Output
0
Input
4 5
Output
2
Input
5 5
Output
4
Input
100000 2
Output
1
Input
100000 100000
Output
50000
### Response
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void){
long long int h, w;
cin >> h >> w;
long long int m = 1e9;
for (int i = 1; i < h; i++){
m = min(m, max(w/2*i, max((w-w/2)*i, w*(h-i))) - min(w/2*i, min((w-w/2)*i, w*(h-i))));
}
for (int i = 1; i < w; i++){
m = min(m, max(h/2*i, max((h-h/2)*i, h*(w-i))) - min(h/2*i, min((h-h/2)*i, h*(w-i))));
}
if (h % 3 == 0 || w % 3 == 0)
m = 0;
m = min(m, min(h, w));
cout << m << endl;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.
For instance, if we are given an array [10, 20, 30, 40], we can permute it so that it becomes [20, 40, 10, 30]. Then on the first and the second positions the integers became larger (20>10, 40>20) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals 2. Read the note for the first example, there is one more demonstrative test case.
Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the array.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the array.
Output
Print a single integer — the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array.
Examples
Input
7
10 1 1 1 5 5 3
Output
4
Input
5
1 1 1 1 1
Output
0
Note
In the first sample, one of the best permutations is [1, 5, 5, 3, 10, 1, 1]. On the positions from second to fifth the elements became larger, so the answer for this permutation is 4.
In the second sample, there is no way to increase any element with a permutation, so the answer is 0.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, ans = 0;
cin >> n;
long long int arr[n];
for (int i = 0; i < n; i++) cin >> arr[i];
sort(arr, arr + n);
int i = 0, j = 1;
while (j != n) {
if (arr[i] < arr[j])
i++, j++, ans++;
else
j++;
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
The final round of Bayan Programming Contest will be held in Tehran, and the participants will be carried around with a yellow bus. The bus has 34 passenger seats: 4 seats in the last row and 3 seats in remaining rows.
<image>
The event coordinator has a list of k participants who should be picked up at the airport. When a participant gets on the bus, he will sit in the last row with an empty seat. If there is more than one empty seat in that row, he will take the leftmost one.
In order to keep track of the people who are on the bus, the event coordinator needs a figure showing which seats are going to be taken by k participants. Your task is to draw the figure representing occupied seats.
Input
The only line of input contains integer k, (0 ≤ k ≤ 34), denoting the number of participants.
Output
Print the figure of a bus with k passengers as described in sample tests. Character '#' denotes an empty seat, while 'O' denotes a taken seat. 'D' is the bus driver and other characters in the output are for the purpose of beautifying the figure. Strictly follow the sample test cases output format. Print exactly six lines. Do not output extra space or other characters.
Examples
Input
9
Output
+------------------------+
|O.O.O.#.#.#.#.#.#.#.#.|D|)
|O.O.O.#.#.#.#.#.#.#.#.|.|
|O.......................|
|O.O.#.#.#.#.#.#.#.#.#.|.|)
+------------------------+
Input
20
Output
+------------------------+
|O.O.O.O.O.O.O.#.#.#.#.|D|)
|O.O.O.O.O.O.#.#.#.#.#.|.|
|O.......................|
|O.O.O.O.O.O.#.#.#.#.#.|.|)
+------------------------+
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n;
void printLine() {
cout << '+';
for (int i = 0; i < (int)(24); ++i) cout << '-';
cout << "+\n";
}
void pLine(int cnt, bool d = false) {
printf("|");
for (int i = 0; i < (int)(cnt); ++i) printf("O.");
for (int i = 0; i < (int)(11 - cnt); ++i) printf("#.");
printf("|");
if (d)
printf("D");
else
printf(".");
printf("|");
}
void pLine2() {
printf("|");
if (n < 3)
printf("#");
else
printf("O");
for (int i = 0; i < (int)(23); ++i) printf(".");
printf("|");
}
int main() {
scanf("%d", &n);
printLine();
int m = n - 4;
if (n == 0)
pLine(0, true);
else if (n <= 4)
pLine(1, true);
else
pLine(1 + (m + 2) / 3, true);
printf(")\n");
if (n <= 1)
pLine(0);
else if (n <= 4)
pLine(1);
else
pLine(1 + (m + 1) / 3);
printf("\n");
pLine2();
printf("\n");
if (n <= 3)
pLine(0);
else if (n == 4)
pLine(1);
else
pLine(1 + m / 3);
printf(")\n");
printLine();
return 0;
}
``` |
### Prompt
Please create a solution in cpp 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;
int n;
string s[1055];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (int i = 0; i < n; i++) cin >> s[i];
int res = 6;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
int cnt = 0;
for (int k = 0; k < 6; k++) cnt += s[i][k] != s[j][k];
res = min(res, (cnt - 1) / 2);
}
}
cout << res << '\n';
return 0;
}
``` |
### Prompt
Please create a solution in CPP to 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 double eps = 1e-9;
const int mod = (int)1e+9 + 7;
const double pi = acos(-1.);
const int maxn = 100100;
string s, t;
long double check(string s) {
int g = 0, t = 0, f = 0, c = 0;
for (unsigned int i = 0; i < s.length(); i++) {
if (s[i] == 'X')
t++;
else if (s[i] == (t & 1 ? 'R' : 'L'))
g++, t++, f = 0;
else
g++, t += 2, c += f, f = !f;
}
if (t & 1) t++, c += f;
if (g * 2 > t) g -= c, t -= c * 2;
return double(g) / t;
}
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);
}
}
getline(cin, s);
int n = s.length();
for (int i = 0; i < n; i++) {
if (i && s[i] == s[i - 1] && s[i] != 'X') t += 'X';
t += s[i];
}
long double ans;
if (s[0] == s[n - 1] && s[0] != 'X') {
ans = max(check('X' + t), check(t + 'X'));
} else {
ans = check(t);
}
printf("%.6lf\n", double(floor(ans * 1e8) / 1e6));
return (0);
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Niwango bought a piece of land that can be represented as a half-open interval [0, X).
Niwango will lay out N vinyl sheets on this land. The sheets are numbered 1,2, \ldots, N, and they are distinguishable. For Sheet i, he can choose an integer j such that 0 \leq j \leq X - L_i and cover [j, j + L_i) with this sheet.
Find the number of ways to cover the land with the sheets such that no point in [0, X) remains uncovered, modulo (10^9+7). We consider two ways to cover the land different if and only if there is an integer i (1 \leq i \leq N) such that the region covered by Sheet i is different.
Constraints
* 1 \leq N \leq 100
* 1 \leq L_i \leq X \leq 500
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N X
L_1 L_2 \ldots L_N
Output
Print the answer.
Examples
Input
3 3
1 1 2
Output
10
Input
18 477
324 31 27 227 9 21 41 29 50 34 2 362 92 11 13 17 183 119
Output
134796357
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int64_t MOD = 1e9+7;
void add(int64_t& a, int64_t b){
a = (a+b) % MOD;
}
void mul(int64_t& a, int64_t b){
a = a*b % MOD;
}
vector<int64_t> fact, seq_inv, fact_inv;
void create_fact_mod(int num){
fact[0] = fact[1] = 1;
for(int i=2; i<=num; i++) fact[i] = fact[i-1] * i % MOD;
}
void create_seq_inv_mod(int num){
seq_inv[0] = seq_inv[1] = 1;
for(int i=2; i<=num; i++) seq_inv[i] = (MOD - MOD/i) * seq_inv[MOD%i] % MOD;
}
void create_fact_inv_mod(int num){
fact_inv[0] = fact_inv[1] = 1;
for(int i=2; i<=num; i++) fact_inv[i] = fact_inv[i-1] * seq_inv[i] % MOD;
}
void create_mod_tables(int num){
fact.resize(num+1);
seq_inv.resize(num+1);
fact_inv.resize(num+1);
create_fact_mod(num);
create_seq_inv_mod(num);
create_fact_inv_mod(num);
}
int64_t comb_mod(int n, int k){
return fact[n] * fact_inv[n-k] % MOD * fact_inv[k] % MOD;
}
int64_t perm_mod(int n, int k){
return fact[n] * fact_inv[n-k] % MOD;
}
int64_t power_mod(int64_t num, int64_t power){
int64_t prod = 1;
num %= MOD;
while(power > 0){
if(power&1) prod = prod * num % MOD;
num = num * num % MOD;
power >>= 1;
}
return prod;
}
int64_t extgcd(int64_t a, int64_t b, int64_t& x, int64_t& y){
int64_t d = a;
if(b != 0){
d = extgcd(b, a%b, y, x);
y -= (a/b) * x;
}else{
x = 1; y = 0;
}
return d;
}
int64_t inv_mod(int64_t a){
int64_t x, y;
extgcd(a, MOD, x, y);
return (MOD + x%MOD) % MOD;
}
int main(){
int N, X;
cin >> N >> X;
vector<int> L(N);
for(int i=0; i<N; i++) cin >> L[i];
sort(L.begin(), L.end());
create_mod_tables(2*X);
const int M = 510;
int64_t small_invs[M];
for(int i=1; i<=X; i++) small_invs[i] = inv_mod(i);
static int64_t pre[M][M][M], pre_inv[M][M][M];
for(int n=0; n<=X; n++) for(int s=0; s<=X; s++) pre[0][n][s] = pre_inv[0][n][s] = 1;
for(int i=0; i<N; i++) for(int n=0; n<=X; n++) for(int s=0; s<=X; s++){
int v = max(1, s-(L[i]-1)*n);
pre[i+1][n][s] = v * pre[i][n][s] % MOD;
pre_inv[i+1][n][s] = small_invs[v] * pre_inv[i][n][s] % MOD;
}
static int64_t dp[2][M][M][2];
dp[X%2][0][0][0] = 1;
int pt = N-1;
for(int x=X; x>0; x--){
while(pt >= 0 && L[pt] > x) pt--;
for(int n=0; n<=X; n++) for(int s=0; s<=X; s++) for(int f=0; f<2; f++){
if(f == 0 && pt < N-1) continue;
int64_t bef = dp[x%2][n][s][f] * pre_inv[pt+1][n][s] % MOD;
if(bef == 0) continue;
for(int k=0; s+x*k+n+k-1<=X; k++){
int n2 = n+k, s2 = s+x*k, f2 = f|(k>0);
int64_t res = bef * pre[pt+1][n2][s2] % MOD * comb_mod(n2, k) % MOD;
add(dp[(x-1)%2][n2][s2][f2], res);
}
}
for(int n=0; n<=X; n++) for(int s=0; s<=X; s++) for(int f=0; f<2; f++) dp[x%2][n][s][f] = 0;
}
int64_t ans = 0;
for(int n=1; n<=X; n++) for(int s=0; s+n-1<=X; s++){
int rest = X - (s+n-1);
int64_t res = comb_mod(rest+n, n) * dp[0][n][s][1] % MOD;
int blank = X-s;
if(blank%2) res = MOD-res;
add(ans, res);
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
This is the easy version of the problem. The only difference between the easy version and the hard version is the constraints on n. You can only make hacks if both versions are solved.
A permutation of 1, 2, …, n is a sequence of n integers, where each integer from 1 to n appears exactly once. For example, [2,3,1,4] is a permutation of 1, 2, 3, 4, but [1,4,2,2] isn't because 2 appears twice in it.
Recall that the number of inversions in a permutation a_1, a_2, …, a_n is the number of pairs of indices (i, j) such that i < j and a_i > a_j.
Let p and q be two permutations of 1, 2, …, n. Find the number of permutation pairs (p,q) that satisfy the following conditions:
* p is lexicographically smaller than q.
* the number of inversions in p is greater than the number of inversions in q.
Print the number of such pairs modulo mod. Note that mod may not be a prime.
Input
The only line contains two integers n and mod (1≤ n≤ 50, 1≤ mod≤ 10^9).
Output
Print one integer, which is the answer modulo mod.
Example
Input
4 403458273
Output
17
Note
The following are all valid pairs (p,q) when n=4.
* p=[1,3,4,2], q=[2,1,3,4],
* p=[1,4,2,3], q=[2,1,3,4],
* p=[1,4,3,2], q=[2,1,3,4],
* p=[1,4,3,2], q=[2,1,4,3],
* p=[1,4,3,2], q=[2,3,1,4],
* p=[1,4,3,2], q=[3,1,2,4],
* p=[2,3,4,1], q=[3,1,2,4],
* p=[2,4,1,3], q=[3,1,2,4],
* p=[2,4,3,1], q=[3,1,2,4],
* p=[2,4,3,1], q=[3,1,4,2],
* p=[2,4,3,1], q=[3,2,1,4],
* p=[2,4,3,1], q=[4,1,2,3],
* p=[3,2,4,1], q=[4,1,2,3],
* p=[3,4,1,2], q=[4,1,2,3],
* p=[3,4,2,1], q=[4,1,2,3],
* p=[3,4,2,1], q=[4,1,3,2],
* p=[3,4,2,1], q=[4,2,1,3].
### Response
```cpp
#include <iostream>
#include <cmath>
#include <utility>
using namespace std;
#define mp make_pair
#define x first
#define y second
typedef pair<int,int> pii;
typedef long long ll;
ll dp[55][55][2505],sum[55][2505],suff[55][2505],C[55][55];
int mod;
ll add(ll x,ll y){
return (x+y)%mod;
}
ll mult(ll x,ll y){
return x*y%mod;
}
void invprep(){
dp[1][1][0]=1ll;
sum[1][0]=1ll;
for(int i=2;i<=50;i++){
for(int j=1;j<=i;j++){
for(int k=0;k<=i*i/2;k++){
if(k>=j-1) dp[i][j][k]=sum[i-1][k-j+1];
}
}
for(int k=0;k<=i*i/2;k++){
for(int j=1;j<=i;j++){
sum[i][k]=add(sum[i][k],dp[i][j][k]);
}
}
}
}
void coefprep(){
C[1][0]=1ll;
C[1][1]=1ll;
for(ll i=2;i<=50;i++){
C[i][i]=1ll;
for(int j=0;j<i;j++){
C[i][j]=mult(C[i-1][j],i);
}
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
ll n;
cin>>n;
cin>>mod;
invprep();
for(int i=1;i<=n;i++){
for(int j=i*i/2;j>=0;j--){
suff[i][j]=add(suff[i][j+1],sum[i][j]);
}
}
// for(int i=0;i<=(n-1)*n/2;i++){
// cout<<sum[n][i]<<" ";
// }
// cout<<endl;
coefprep();
ll sol=0ll;
ll temp;
ll mn;
ll fakt,suma;
for(ll i=0;i<n-2;i++){
mn=C[n][n-i];
suma=0ll;
for(ll j=1;j<n-i;j++){
temp=n-i-j;
fakt=0ll;
for(ll k=0;k<n*n/2;k++){
fakt=add(fakt,mult(sum[n-i-1][k],suff[n-i-1][k+j+1]));
}
suma=add(suma,mult(fakt,temp));
}
sol=add(sol,mult(mn,suma));
}
cout<<sol;
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
AtCoder Inc. has decided to lock the door of its office with a 3-digit PIN code.
The company has an N-digit lucky number, S. Takahashi, the president, will erase N-3 digits from S and concatenate the remaining 3 digits without changing the order to set the PIN code.
How many different PIN codes can he set this way?
Both the lucky number and the PIN code may begin with a 0.
Constraints
* 4 \leq N \leq 30000
* S is a string of length N consisting of digits.
Input
Input is given from Standard Input in the following format:
N
S
Output
Print the number of different PIN codes Takahashi can set.
Examples
Input
4
0224
Output
3
Input
6
123123
Output
17
Input
19
3141592653589793238
Output
329
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int N;
string S;
cin >> N >> S;
int ans = 0;
for(int i = 0;i < 1000;i++){
int a[3] = {i / 100, (i / 10) % 10, i % 10};
int cnt = 0;
for(int j = 0;j < N;j++){
if(S[j] == ('0' + a[cnt])){
cnt++;
}
if(cnt == 3){
ans++;
break;
}
}
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Takahashi is at an all-you-can-eat restaurant.
The restaurant offers N kinds of dishes. It takes A_i minutes to eat the i-th dish, whose deliciousness is B_i.
The restaurant has the following rules:
* You can only order one dish at a time. The dish ordered will be immediately served and ready to eat.
* You cannot order the same kind of dish more than once.
* Until you finish eating the dish already served, you cannot order a new dish.
* After T-0.5 minutes from the first order, you can no longer place a new order, but you can continue eating the dish already served.
Let Takahashi's happiness be the sum of the deliciousness of the dishes he eats in this restaurant.
What is the maximum possible happiness achieved by making optimal choices?
Constraints
* 2 \leq N \leq 3000
* 1 \leq T \leq 3000
* 1 \leq A_i \leq 3000
* 1 \leq B_i \leq 3000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N T
A_1 B_1
:
A_N B_N
Output
Print the maximum possible happiness Takahashi can achieve.
Examples
Input
2 60
10 10
100 100
Output
110
Input
3 60
10 10
10 20
10 30
Output
60
Input
3 60
30 10
30 20
30 30
Output
50
Input
10 100
15 23
20 18
13 17
24 12
18 29
19 27
23 21
18 20
27 15
22 25
Output
145
### Response
```cpp
#include <bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(0), cin.tie(0)
using namespace std;
typedef pair<int, int> pii;
typedef long long ll;
int n, t;
int a[3000];
int b[3000];
int dp[3000][3000][2];
int f(int i, int j, int k)
{
if (i == n) return 0;
int &ret = dp[i][j][k];
if (ret != -1) return ret;
ret = f(i + 1, j, k);
if (j + a[i] < t)
ret = max(f(i + 1, j + a[i], k) + b[i], ret);
if (k == 1) ret = max(ret, f(i + 1, j, 0) + b[i]);
return ret;
}
int main()
{
fastio;
cin >> n >> t;
for (int i = 0; i < n; i++) cin >> a[i] >> b[i];
memset(dp, -1, sizeof(dp));
cout << f(0, 0, 1);
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Koa the Koala has a directed graph G with n nodes and m edges. Each edge has a capacity associated with it. Exactly k edges of the graph, numbered from 1 to k, are special, such edges initially have a capacity equal to 0.
Koa asks you q queries. In each query she gives you k integers w_1, w_2, …, w_k. This means that capacity of the i-th special edge becomes w_i (and other capacities remain the same).
Koa wonders: what is the [maximum flow](https://en.wikipedia.org/wiki/Maximum_flow_problem#Definition) that goes from node 1 to node n after each such query?
Help her!
Input
The first line of the input contains four integers n, m, k, q (2 ≤ n ≤ 10^4, 1 ≤ m ≤ 10^4, 1 ≤ k ≤ min(10, m), 1 ≤ q ≤ 2 ⋅ 10^5) — the number of nodes, the number of edges, the number of special edges and the number of queries.
Each of the next m lines contains three integers u, v, w (1 ≤ u, v ≤ n; 0 ≤ w ≤ 25) — the description of a directed edge from node u to node v with capacity w.
Edges are numbered starting from 1 in the same order they are listed in the input. The first k edges are the special edges. It is guaranteed that w_i = 0 for all i with 1 ≤ i ≤ k.
Each of the next q lines contains k integers w_1, w_2, …, w_k (0 ≤ w_i ≤ 25) — the description of the query. w_i denotes the capacity of i-th edge.
Output
For the i-th query, print one integer res_i — the maximum flow that can be obtained from node 1 to node n given the i-th query's special edge weights.
Examples
Input
2 1 1 3
1 2 0
0
1
2
Output
0
1
2
Input
4 4 2 5
1 2 0
2 3 0
2 4 5
3 4 2
0 0
1 10
10 0
7 1
7 2
Output
0
1
5
6
7
Note
For the second sample, the following images correspond to the first two queries (from left to right respectively). For each edge there is a pair flow/capacity denoting flow pushed through the edge and edge's capacity. The special edges are colored in red.
<image>
As you can see in first query maximum flow from node 1 to node 4 equals 0 and in second query equals 1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using Vi = vector<int>;
using Pii = pair<int, int>;
int uplg(int n) { return 32 - __builtin_clz(n); }
int uplg(ll n) { return 64 - __builtin_clzll(n); }
void run();
int main() {
cin.sync_with_stdio(0);
cin.tie(0);
cout << fixed << setprecision(18);
run();
return 0;
}
using flow_t = int;
constexpr flow_t INF = 1e9 + 10;
struct MaxFlow {
struct Edge {
int to, inv;
flow_t rem, cap;
};
vector<basic_string<Edge>> G;
vector<flow_t> extra;
Vi hei, arc, prv, nxt, act, bot;
queue<int> Q;
int n, high, cut, work;
MaxFlow(int k = 0) : G(k) {}
int addEdge(int u, int v, flow_t cap, flow_t rcap = 0) {
G[u].push_back({v, int((G[v]).size()), 0, cap});
G[v].push_back({u, int((G[u]).size()) - 1, 0, rcap});
return int((G[u]).size()) - 1;
}
void raise(int v, int h) {
if (hei[v] < n) prv[nxt[prv[v]] = nxt[v]] = prv[v];
if ((hei[v] = h) < n) {
if (extra[v] > 0) {
bot[v] = act[h], act[h] = v;
high = max(high, h);
}
cut = max(cut, h);
nxt[v] = nxt[prv[v] = h += n];
prv[nxt[nxt[h] = v]] = v;
}
}
void global(int t) {
hei.assign(n, n);
act.assign(n, -1);
iota((prv).begin(), (prv).end(), 0);
iota((nxt).begin(), (nxt).end(), 0);
hei[t] = high = cut = work = 0;
for (Q.push(t); !Q.empty(); Q.pop()) {
int v = Q.front();
for (auto& e : (G[v]))
if (hei[e.to] == n && G[e.to][e.inv].rem)
Q.push(e.to), raise(e.to, hei[v] + 1);
}
}
void push(int v, Edge& e) {
auto f = min(extra[v], e.rem);
if (f > 0) {
if (!extra[e.to]) {
bot[e.to] = act[hei[e.to]];
act[hei[e.to]] = e.to;
}
e.rem -= f;
G[e.to][e.inv].rem += f;
extra[v] -= f;
extra[e.to] += f;
}
}
void discharge(int v) {
int h = n;
auto go = [&](int a, int b) {
for (int i = (a); i < (b); i++) {
auto& e = G[v][i];
if (e.rem) {
if (hei[v] == hei[e.to] + 1) {
push(v, e);
if (extra[v] <= 0) return arc[v] = i, 0;
} else
h = min(h, hei[e.to] + 1);
}
}
return 1;
};
if (go(arc[v], int((G[v]).size())) && go(0, arc[v])) {
int k = hei[v] + n;
if (nxt[k] == prv[k]) {
for (int j = (k); j < (cut + n + 1); j++)
while (nxt[j] < n) raise(nxt[j], n);
cut = k - n - 1;
} else
raise(v, h), work++;
}
}
flow_t maxFlow(int src, int dst) {
extra.assign(n = int((G).size()), 0);
hei.assign(n, 0);
arc.assign(n, 0);
prv.resize(n * 2);
nxt.resize(n * 2);
act.resize(n);
bot.resize(n);
for (auto& v : (G))
for (auto& e : (v)) e.rem = e.cap;
extra[dst] = -(extra[src] = INF);
for (auto& e : (G[src])) push(src, e);
global(dst);
for (; high; high--)
while (act[high] != -1) {
int v = act[high];
act[high] = bot[v];
if (hei[v] == high) {
discharge(v);
if (work > 4 * n) global(dst);
}
}
return extra[dst] + INF;
}
};
void run() {
int n, m, k, q;
cin >> n >> m >> k >> q;
MaxFlow flow(n);
vector<Pii> edges;
for (int i = (0); i < (m); i++) {
int u, v, w;
cin >> u >> v >> w;
edges.push_back({u - 1, flow.addEdge(u - 1, v - 1, w)});
}
Vi cuts(1 << k);
for (int mask = (0); mask < (1 << k); mask++) {
for (int i = (0); i < (k); i++) {
Pii e = edges[i];
flow.G[e.first][e.second].cap = ((mask >> i) & 1 ? 0 : INF);
}
cuts[mask] = flow.maxFlow(0, n - 1);
}
Vi weights(k), sums(1 << k);
while (q--) {
int ans = INF;
for (auto& w : (weights)) cin >> w;
for (int mask = (1); mask < (1 << k); mask++)
sums[mask] = sums[mask & (mask - 1)] + weights[__builtin_ctz(mask)];
for (int mask = (0); mask < (1 << k); mask++)
ans = min(ans, cuts[mask] + sums[mask]);
cout << ans << '\n';
}
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
AtCoDeer the deer has N cards with positive integers written on them. The number on the i-th card (1≤i≤N) is a_i. Because he loves big numbers, he calls a subset of the cards good when the sum of the numbers written on the cards in the subset, is K or greater.
Then, for each card i, he judges whether it is unnecessary or not, as follows:
* If, for any good subset of the cards containing card i, the set that can be obtained by eliminating card i from the subset is also good, card i is unnecessary.
* Otherwise, card i is NOT unnecessary.
Find the number of the unnecessary cards. Here, he judges each card independently, and he does not throw away cards that turn out to be unnecessary.
Constraints
* All input values are integers.
* 1≤N≤5000
* 1≤K≤5000
* 1≤a_i≤10^9 (1≤i≤N)
Input
The input is given from Standard Input in the following format:
N K
a_1 a_2 ... a_N
Output
Print the number of the unnecessary cards.
Examples
Input
3 6
1 4 3
Output
1
Input
5 400
3 1 4 1 5
Output
5
Input
6 20
10 4 3 10 25 2
Output
3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve(long long N, long long K, std::vector<long long> a) {
sort(a.begin(), a.end());
reverse(a.begin(), a.end());
ll sum = 0;
ll res = N;
for (int i = 0; i < N; i++) {
if (sum + a[i] < K) {
sum += a[i];
} else {
res = min(res, N - i - 1);
}
}
cout << res << endl;
}
int main() {
long long N;
scanf("%lld", &N);
long long K;
scanf("%lld", &K);
std::vector<long long> a(N);
for (int i = 0; i < N; i++) {
scanf("%lld", &a[i]);
}
solve(N, K, std::move(a));
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
KM country has N kinds of coins and each coin has its value a_i.
The king of the country, Kita_masa, thought that the current currency system is poor, and he decided to make it beautiful by changing the values of some (possibly no) coins.
A currency system is called beautiful if each coin has an integer value and the (i+1)-th smallest value is divisible by the i-th smallest value for all i (1 \leq i \leq N-1).
For example, the set {1, 5, 10, 50, 100, 500} is considered as a beautiful system, while the set {1, 5, 10, 25, 50, 100} is NOT, because 25 is not divisible by 10.
Since changing the currency system may confuse citizens, the king, Kita_masa, wants to minimize the maximum value of the confusion ratios. Here, the confusion ratio for the change in the i-th coin is defined as |a_i - b_i| / a_i, where a_i and b_i is the value of i-th coin before and after the structure changes, respectively.
Note that Kita_masa can change the value of each existing coin, but he cannot introduce new coins nor eliminate existing coins. After the modification, the values of two or more coins may coincide.
Input
Each dataset contains two lines. The first line contains a single integer, N, and the second line contains N integers, {a_i}.
You may assume the following constraints:
1 \leq N \leq 20
1 \leq a_1 \lt a_2 \lt... \lt a_N \lt 10^5
Output
Output one number that represents the minimum of the maximum value of the confusion ratios. The value may be printed with an arbitrary number of decimal digits, but may not contain an absolute error greater than or equal to 10^{-8}.
Examples
Input
3
6 11 12
Output
0.090909090909
Input
3
6 11 24
Output
0.090909090909
Input
3
6 11 30
Output
0.166666666667
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define MAX_N 21
#define MAX_M 150001
#define INF (1<<29)
typedef long long ll;
double dp[MAX_N][MAX_M];
int main()
{
int N;
cin >> N;
vector<double> v(N);
for (int i = 0; i < N; i++) {
cin >> v[i];
}
fill(dp[0], dp[MAX_N], INF);
dp[0][1] = 0;
for (int i = 0; i < N; i++) {
for (int j = MAX_M-1; j >= 0; j--) {
if (dp[i][j] == INF) continue;
for (int k = 1; k <= MAX_M; k++) {
ll nv = (ll)j * k;
if (nv >= MAX_M) break;
dp[i+1][nv] = min(dp[i+1][nv],
max(dp[i][j], abs(v[i]-nv) / v[i]));
}
}
}
double res = INF;
for (int i = 0; i < MAX_M; i++) {
res = min(res, dp[N][i]);
}
printf("%.15f\n", res);
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
A penguin Rocher has n sticks. He has exactly one stick with length i for all 1 ≤ i ≤ n.
He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his set and can be used for the next connections.
He wants to create the maximum number of sticks that have the same length. It is not necessary to make all sticks have the same length, some sticks can have the other length. How many sticks with the equal length he can create?
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. Next t lines contain descriptions of test cases.
For each test case, the only line contains a single integer n (1 ≤ n ≤ 10^{9}).
Output
For each test case, print a single integer — the answer to the problem.
Example
Input
4
1
2
3
4
Output
1
1
2
2
Note
In the third case, he can connect two sticks with lengths 1 and 2 and he will get one stick with length 3. So, he will have two sticks with lengths 3.
In the fourth case, he can connect two sticks with lengths 1 and 3 and he will get one stick with length 4. After that, he will have three sticks with lengths \{2, 4, 4\}, so two sticks have the same length, and one stick has the other length.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
long long int n;
cin >> n;
cout << (long long int)ceil((double)n / (double)2) << endl;
}
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Makoto has a big blackboard with a positive integer n written on it. He will perform the following action exactly k times:
Suppose the number currently written on the blackboard is v. He will randomly pick one of the divisors of v (possibly 1 and v) and replace v with this divisor. As Makoto uses his famous random number generator (RNG) and as he always uses 58 as his generator seed, each divisor is guaranteed to be chosen with equal probability.
He now wonders what is the expected value of the number written on the blackboard after k steps.
It can be shown that this value can be represented as P/Q where P and Q are coprime integers and Q not≡ 0 \pmod{10^9+7}. Print the value of P ⋅ Q^{-1} modulo 10^9+7.
Input
The only line of the input contains two integers n and k (1 ≤ n ≤ 10^{15}, 1 ≤ k ≤ 10^4).
Output
Print a single integer — the expected value of the number on the blackboard after k steps as P ⋅ Q^{-1} \pmod{10^9+7} for P, Q defined above.
Examples
Input
6 1
Output
3
Input
6 2
Output
875000008
Input
60 5
Output
237178099
Note
In the first example, after one step, the number written on the blackboard is 1, 2, 3 or 6 — each occurring with equal probability. Hence, the answer is (1+2+3+6)/(4)=3.
In the second example, the answer is equal to 1 ⋅ 9/16+2 ⋅ 3/16+3 ⋅ 3/16+6 ⋅ 1/16=15/8.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 4;
const int MOD = 1e9 + 7;
const int K = 100;
int dp[N][K];
int vis[N][K], visid;
long long inv[K], pw[K];
long long p;
int k;
long long power(long long a, long long b) {
long long x = 1, y = a;
while (b > 0) {
if (b & 1) {
x = (x * y);
if (x > MOD) x %= MOD;
}
y = y * y;
if (y > MOD) y %= MOD;
b >>= 1;
}
return x;
}
int solve(int idx, int j) {
int &ret = dp[idx][j];
if (vis[idx][j] == visid) return ret;
vis[idx][j] = visid;
if (idx == k) return ret = pw[j];
ret = 0;
for (int i = 0; i <= j; i++) {
ret += solve(idx + 1, j - i) * inv[j + 1] % MOD;
if (ret >= MOD) ret -= MOD;
}
return ret;
}
int main() {
pw[0] = 1;
for (int i = 1; i < K; i++) inv[i] = power(i, MOD - 2) % MOD;
long long ans = 1;
long long n;
cin >> n >> k;
for (long long i = 2; i * i <= n; i++) {
if (n % i == 0) {
visid++;
p = i;
int cnt = 0;
while (n % i == 0) {
cnt++;
n /= i;
}
for (int j = 1; j <= cnt; j++) pw[j] = 1LL * pw[j - 1] * i % MOD;
ans = ans * solve(0, cnt) % MOD;
}
}
if (n != 1) {
p = n;
pw[1] = n % MOD;
visid++;
ans = ans * solve(0, 1) % MOD;
}
cout << ans << "\n";
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Prime numbers are widely applied for cryptographic and communication technology. A twin prime is a prime number that differs from another prime number by 2. For example, (5, 7) and (11, 13) are twin prime pairs.
In this problem, we call the greater number of a twin prime "size of the twin prime."
Your task is to create a program which reads an integer n and prints a twin prime which has the maximum size among twin primes less than or equals to n
You may assume that 5 ≤ n ≤ 10000.
Input
The input is a sequence of datasets. The end of the input is indicated by a line containing one zero. Each dataset is formatted as follows:
n (integer)
Output
For each dataset, print the twin prime p and q (p < q). p and q should be separated by a single space.
Example
Input
12
100
200
300
0
Output
5 7
71 73
197 199
281 283
### Response
```cpp
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
int main(){
int N = 100000;
bool a[100000];
for(int i = 0; i < N; i++){
a[i] = true;
}
a[0] = false;
a[1] = false;
for(int i = 2; i < N; i++){
if(a[i]){
for(int j = i * 2; j < N; j += i){
a[j] = false;
}
}
}
int n;
while(true){
cin >> n;
if(n == 0){
break;
}else if(n < 5 || n > 10000){
printf("NA\n");
continue;
}else{
for(int i = n; i > 2; i--){
if(a[i] && a[i - 2]){
printf("%d %d\n", i - 2, i);
break;
}
}
}
}
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Filya just learned new geometry object — rectangle. He is given a field consisting of n × n unit cells. Rows are numbered from bottom to top with integer from 1 to n. Columns are numbered from left to right with integers from 1 to n. Cell, located at the intersection of the row r and column c is denoted as (r, c). Filya has painted two rectangles, such that their sides are parallel to coordinate axes and each cell lies fully inside or fully outside each of them. Moreover, no cell lies in both rectangles.
Later, hedgehog Filya became interested in the location of his rectangles but was unable to find the sheet of paper they were painted on. They were taken by Sonya and now she wants to play a little game with Filya. He tells her a query rectangle and she replies with the number of initial rectangles that lie fully inside the given query rectangle. The query rectangle should match the same conditions as initial rectangles. Rectangle lies fully inside the query if each o its cells lies inside the query.
Filya knows Sonya really well, so is sure that if he asks more than 200 questions she will stop to reply.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 216) — size of the field.
For each query an integer between 0 and 2 is returned — the number of initial rectangles that lie fully inside the query rectangle.
Output
To make a query you have to print "? x1 y1 x2 y2" (without quotes) (1 ≤ x1 ≤ x2 ≤ n, 1 ≤ y1 ≤ y2 ≤ n), where (x1, y1) stands for the position of the bottom left cell of the query and (x2, y2) stands for the up right cell of the query. You are allowed to ask no more than 200 queries. After each query you should perform "flush" operation and read the answer.
In case you suppose you've already determined the location of two rectangles (or run out of queries) you should print "! x11 y11 x12 y12 x21 y21 x22 y22" (without quotes), where first four integers describe the bottom left and up right cells of the first rectangle, and following four describe the corresponding cells of the second rectangle. You can print the rectangles in an arbitrary order. After you have printed the answer, print the end of the line and perform "flush". Your program should terminate immediately after it print the answer.
Interaction
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.
You will get the Wrong Answer verdict if you ask more than 200 queries, or if you print an incorrect coordinates.
You will get the Idleness Limit Exceeded verdict if you don't print anything (but you should) or if you forget about flushing the output (more info below).
Hacking.
The first line should contain an integer n (2 ≤ n ≤ 216).
The second line should contain four integers x1, y1, x2, y2 (1 ≤ x1 ≤ x2 ≤ n, 1 ≤ y1 ≤ y2 ≤ n) — the description of the first rectangle.
The third line contains the description of the second rectangle in the similar way.
Example
Input
5
2
1
0
1
1
1
0
1
Output
? 1 1 5 5
? 1 1 3 3
? 1 1 3 1
? 2 2 2 2
? 3 3 5 5
? 3 3 3 5
? 3 3 3 4
? 3 4 3 5
! 2 2 2 2 3 4 3 5
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct abc {
int x1, y1, x2, y2;
void print() { cout << x1 << " " << y1 << " " << x2 << " " << y2 << " "; }
};
int query(int x1, int y1, int x2, int y2) {
if (x1 > x2) swap(x1, x2);
if (y1 > y2) swap(y1, y2);
cout << "? " << x1 << " " << y1 << " " << x2 << " " << y2 << endl;
int ans;
cin >> ans;
return ans;
}
abc fi(int xx1, int yy1, int xx2, int yy2) {
abc Ans;
int l = yy1, r = yy2, ans = yy1;
while (l <= r) {
int mid = (l + r) / 2;
if (query(xx1, yy1, xx2, mid) < 1)
l = mid + 1;
else
r = mid - 1, ans = mid;
}
Ans.y2 = ans;
l = yy1, r = yy2, ans = yy1;
while (l <= r) {
int mid = (l + r) / 2;
if (query(xx1, mid, xx2, yy2) < 1)
r = mid - 1;
else
l = mid + 1, ans = mid;
}
Ans.y1 = ans;
l = xx1, r = xx2, ans = xx1;
while (l <= r) {
int mid = (l + r) / 2;
if (query(xx1, yy1, mid, yy2) < 1)
l = mid + 1;
else
r = mid - 1, ans = mid;
}
Ans.x2 = ans;
l = xx1, r = xx2, ans = xx1;
while (l <= r) {
int mid = (l + r) / 2;
if (query(mid, yy1, xx2, yy2) < 1)
r = mid - 1;
else
l = mid + 1, ans = mid;
}
Ans.x1 = ans;
return Ans;
}
int main() {
int n;
scanf("%d", &n);
int l = 1, r = n, ans = 1;
while (l <= r) {
int mid = (l + r) / 2;
if (query(1, 1, mid, n) < 1)
l = mid + 1;
else
r = mid - 1, ans = mid;
}
if (query(1, 1, ans, n) == 1 && query(ans + 1, 1, n, n) == 1) {
abc r1 = fi(1, 1, ans, n);
abc r2 = fi(ans + 1, 1, n, n);
cout << "! ";
r1.print();
r2.print();
return 0;
}
l = 1, r = n, ans = 1;
while (l <= r) {
int mid = (l + r) / 2;
if (query(1, 1, n, mid) < 1)
l = mid + 1;
else
r = mid - 1, ans = mid;
}
abc r1 = fi(1, 1, n, ans);
abc r2 = fi(1, ans + 1, n, n);
cout << "! ";
r1.print();
r2.print();
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Example
Input
1
Output
)(
### Response
```cpp
#include <bits/stdc++.h>
#define ll long long
using namespace std;
int A;
int c[200010];
int n,now;
int main()
{
scanf("%d",&A);
n=1;
while ((ll)n*(n+1)/2<(ll)A) n++;
int p=A-(ll)n*(n-1)/2;
c[1]=1; c[1+p]=2;now=1;
for(int i=1;i<=2*n;i++) if(c[i]==0) if(now<n) c[i]=1,now++;else c[i]=2;
for(int i=1;i<=2*n;i++) if(c[i]==1) printf(")");else printf("(");
printf("\n");
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game «Call of Soldiers 3».
The game has (m + 1) players and n types of soldiers in total. Players «Call of Soldiers 3» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each player has an army. Army of the i-th player can be described by non-negative integer xi. Consider binary representation of xi: if the j-th bit of number xi equal to one, then the army of the i-th player has soldiers of the j-th type.
Fedor is the (m + 1)-th player of the game. He assume that two players can become friends if their armies differ in at most k types of soldiers (in other words, binary representations of the corresponding numbers differ in at most k bits). Help Fedor and count how many players can become his friends.
Input
The first line contains three integers n, m, k (1 ≤ k ≤ n ≤ 20; 1 ≤ m ≤ 1000).
The i-th of the next (m + 1) lines contains a single integer xi (1 ≤ xi ≤ 2n - 1), that describes the i-th player's army. We remind you that Fedor is the (m + 1)-th player.
Output
Print a single integer — the number of Fedor's potential friends.
Examples
Input
7 3 1
8
5
111
17
Output
0
Input
3 3 3
1
2
3
4
Output
3
### Response
```cpp
#include <bits/stdc++.h>
#pragma gcc optimize("Ofast")
using namespace std;
const int INF = signed(1e9) + 7;
const long double EPS = 1e-7, Pi = acos(-1);
bitset<21> bts[1001];
void solve() {
int n, m, k;
cin >> n >> m >> k;
for (int i = 0; i < m + 1; ++i) {
int q;
cin >> q;
bts[i] |= q;
}
int ans = 0;
for (int i = 0; i < m; ++i) {
ans += int((bts[i] ^ bts[m]).count() <= k);
}
cout << ans << '\n';
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout << fixed << setprecision(10);
int tests = 1;
while (tests--) {
solve();
}
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.
The head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least k times?
Input
The first line contains two integers, n and k (1 ≤ n ≤ 2000; 1 ≤ k ≤ 5). The next line contains n integers: y1, y2, ..., yn (0 ≤ yi ≤ 5), where yi shows the number of times the i-th person participated in the ACM ICPC world championship.
Output
Print a single number — the answer to the problem.
Examples
Input
5 2
0 4 5 1 0
Output
1
Input
6 4
0 1 2 3 4 5
Output
0
Input
6 5
0 0 0 0 0 0
Output
2
Note
In the first sample only one team could be made: the first, the fourth and the fifth participants.
In the second sample no teams could be created.
In the third sample two teams could be created. Any partition into two teams fits.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k, i, temp, res = 0;
cin >> n >> k;
for (i = 0; i < n; i++) {
cin >> temp;
if (temp <= 5 - k) res++;
}
cout << (res / 3) << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Valery is a PE teacher at a school in Berland. Soon the students are going to take a test in long jumps, and Valery has lost his favorite ruler!
However, there is no reason for disappointment, as Valery has found another ruler, its length is l centimeters. The ruler already has n marks, with which he can make measurements. We assume that the marks are numbered from 1 to n in the order they appear from the beginning of the ruler to its end. The first point coincides with the beginning of the ruler and represents the origin. The last mark coincides with the end of the ruler, at distance l from the origin. This ruler can be repesented by an increasing sequence a1, a2, ..., an, where ai denotes the distance of the i-th mark from the origin (a1 = 0, an = l).
Valery believes that with a ruler he can measure the distance of d centimeters, if there is a pair of integers i and j (1 ≤ i ≤ j ≤ n), such that the distance between the i-th and the j-th mark is exactly equal to d (in other words, aj - ai = d).
Under the rules, the girls should be able to jump at least x centimeters, and the boys should be able to jump at least y (x < y) centimeters. To test the children's abilities, Valery needs a ruler to measure each of the distances x and y.
Your task is to determine what is the minimum number of additional marks you need to add on the ruler so that they can be used to measure the distances x and y. Valery can add the marks at any integer non-negative distance from the origin not exceeding the length of the ruler.
Input
The first line contains four positive space-separated integers n, l, x, y (2 ≤ n ≤ 105, 2 ≤ l ≤ 109, 1 ≤ x < y ≤ l) — the number of marks, the length of the ruler and the jump norms for girls and boys, correspondingly.
The second line contains a sequence of n integers a1, a2, ..., an (0 = a1 < a2 < ... < an = l), where ai shows the distance from the i-th mark to the origin.
Output
In the first line print a single non-negative integer v — the minimum number of marks that you need to add on the ruler.
In the second line print v space-separated integers p1, p2, ..., pv (0 ≤ pi ≤ l). Number pi means that the i-th mark should be at the distance of pi centimeters from the origin. Print the marks in any order. If there are multiple solutions, print any of them.
Examples
Input
3 250 185 230
0 185 250
Output
1
230
Input
4 250 185 230
0 20 185 250
Output
0
Input
2 300 185 230
0 300
Output
2
185 230
Note
In the first sample it is impossible to initially measure the distance of 230 centimeters. For that it is enough to add a 20 centimeter mark or a 230 centimeter mark.
In the second sample you already can use the ruler to measure the distances of 185 and 230 centimeters, so you don't have to add new marks.
In the third sample the ruler only contains the initial and the final marks. We will need to add two marks to be able to test the children's skills.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[100005];
bool solve();
int finds(int);
int n, length, x, y;
int main() {
scanf("%d%d%d%d", &n, &length, &x, &y);
memset(a, 0, sizeof(a));
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
solve();
return 0;
}
bool solve() {
int r1, r2, r3, r4;
r1 = finds(x);
r2 = finds(y);
r3 = finds(x + y);
r4 = finds(y - x);
if (r1 != -1 && r2 != -1) {
printf("0\n");
} else {
if (r1 != -1)
printf("%d\n%d\n", 1, y);
else if (r2 != -1)
printf("%d\n%d\n", 1, x);
else if (r3 != -1)
printf("%d\n%d\n", 1, r3 - y);
else if (r4 != -1) {
if (r4 - y > 0)
printf("%d\n%d\n", 1, r4 - y);
else if (r4 + x < length)
printf("%d\n%d\n", 1, r4 + x);
} else
printf("%d\n%d %d\n", 2, x, y);
}
return true;
}
int finds(int pos) {
int tmp;
for (int i = 0; i < n; i++) {
tmp = lower_bound(a, a + n, a[i] + pos) - a;
if (tmp == n)
break;
else {
if (a[tmp] == a[i] + pos) {
if (pos == y - x) {
if (a[tmp] - y < 0 && a[tmp] + x > length)
continue;
else
return a[tmp];
} else
return a[tmp];
}
}
}
return -1;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The n-th triangular number is the number of dots in a triangle with n dots on a side. <image>. You can learn more about these numbers from Wikipedia (http://en.wikipedia.org/wiki/Triangular_number).
Your task is to find out if a given integer is a triangular number.
Input
The first line contains the single number n (1 ≤ n ≤ 500) — the given integer.
Output
If the given integer is a triangular number output YES, otherwise output NO.
Examples
Input
1
Output
YES
Input
2
Output
NO
Input
3
Output
YES
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n;
int main() {
cin >> n;
n *= 2;
for (int i = 1; i < n; i++) {
if (i * (i + 1) > n)
break;
else if (i * (i + 1) != n)
continue;
else {
cout << "YES";
return 0;
}
}
cout << "NO" << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Ostap is preparing to play chess again and this time he is about to prepare. Thus, he was closely monitoring one recent chess tournament. There were m players participating and each pair of players played exactly one game. The victory gives 2 points, draw — 1 points, lose — 0 points.
Ostap is lazy, so he never tries to remember the outcome of each game. Instead, he computes the total number of points earned by each of the players (the sum of his points in all games which he took part in), sort these value in non-ascending order and then remembers first n integers in this list.
Now the Great Strategist Ostap wonders whether he remembers everything correct. He considers that he is correct if there exists at least one tournament results table such that it will produce the given integers. That means, if we count the sum of points for each player, sort them and take first n elements, the result will coincide with what Ostap remembers. Can you check if such table exists?
Input
The first line of the input contains two integers m and n (1 ≤ n ≤ m ≤ 3000) — the number of participants of the tournament and the number of top results Ostap remembers.
The second line contains n integers, provided in non-ascending order — the number of points earned by top participants as Ostap remembers them. It's guaranteed that this integers are non-negative and do not exceed 2·m.
Output
If there is no tournament such that Ostap can obtain the given set of integers using the procedure described in the statement, then print "no" in the only line of the output. Otherwise, the first line of the output should contain the word "yes". Next m lines should provide the description of any valid tournament. Each of these lines must contain m characters 'X', 'W', 'D' and 'L'. Character 'X' should always be located on the main diagonal (and only there), that is on the i-th position of the i-th string. Character 'W' on the j-th position of the i-th string means that the i-th player won the game against the j-th. In the same way character 'L' means loose and 'D' means draw.
The table you print must be consistent and the points earned by best n participants should match the memory of Ostap. If there are many possible answers, print any of them.
Examples
Input
5 5
8 6 4 2 0
Output
yes
XWWWW
LXWWW
LLXWW
LLLXW
LLLLX
Input
5 1
9
Output
no
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0, f = 1;
char ch = getchar();
while (ch > '9' || ch < '0') ch == '-' && (f = 0) || (ch = getchar());
while (ch <= '9' && ch >= '0')
x = (x << 3) + (x << 1) + ch - '0', ch = getchar();
return f ? x : -x;
}
int n, m, f[3010][3010];
struct misaka {
int x, y;
friend bool operator<(const misaka &p, const misaka &q) { return p.x > q.x; }
} a[3010];
void get(int k) {
sort(a + k, a + n + 1);
int w = a[k].x;
for (int i = n; i > k; i--) {
if (w > 1)
w -= 2, f[a[k].y][a[i].y] = 1;
else if (!w)
a[i].x -= 2, f[a[i].y][a[k].y] = 1;
else
w--, a[i].x--, f[a[k].y][a[i].y] = f[a[i].y][a[k].y] = 2;
}
a[k].x = 0;
}
int main(int argc, char const *argv[]) {
cin >> n >> m;
int x = 0, sum = 0;
for (int i = 1; i <= m; i++) {
cin >> a[i].x;
a[i].y = i;
x += n - i << 1;
sum += a[i].x;
if (sum > x) return puts("no") & 0;
}
for (int i = m + 1; i <= n; i++) {
a[i].y = i;
x += n - i << 1;
a[i].x = min(a[i - 1].x, x - sum);
sum += a[i].x;
}
if (sum != x) return puts("no") & 0;
for (int i = 1; i < n; i++) get(i);
puts("yes");
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i == j)
putchar('X');
else if (!f[i][j])
putchar('L');
else if (f[i][j] == 1)
putchar('W');
else
putchar('D');
}
puts("");
}
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.
The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has n hotels, where the i-th hotel is located in the city with coordinate x_i. Sonya is a smart girl, so she does not open two or more hotels in the same city.
Sonya understands that her business needs to be expanded by opening new hotels, so she decides to build one more. She wants to make the minimum distance from this hotel to all others to be equal to d. The girl understands that there are many possible locations to construct such a hotel. Thus she wants to know the number of possible coordinates of the cities where she can build a new hotel.
Because Sonya is lounging in a jacuzzi in one of her hotels, she is asking you to find the number of cities where she can build a new hotel so that the minimum distance from the original n hotels to the new one is equal to d.
Input
The first line contains two integers n and d (1≤ n≤ 100, 1≤ d≤ 10^9) — the number of Sonya's hotels and the needed minimum distance from a new hotel to all others.
The second line contains n different integers in strictly increasing order x_1, x_2, …, x_n (-10^9≤ x_i≤ 10^9) — coordinates of Sonya's hotels.
Output
Print the number of cities where Sonya can build a new hotel so that the minimum distance from this hotel to all others is equal to d.
Examples
Input
4 3
-3 2 9 16
Output
6
Input
5 2
4 8 11 18 19
Output
5
Note
In the first example, there are 6 possible cities where Sonya can build a hotel. These cities have coordinates -6, 5, 6, 12, 13, and 19.
In the second example, there are 5 possible cities where Sonya can build a hotel. These cities have coordinates 2, 6, 13, 16, and 21.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, a[101], i, d, s = 2;
cin >> n >> d;
for (i = 1; i <= n; i++) cin >> a[i];
for (i = 2; i <= n; i++) {
if (a[i] - a[i - 1] > 2 * d)
s += 2;
else if (a[i] - a[i - 1] == 2 * d)
s++;
}
cout << s;
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Mike has always been thinking about the harshness of social inequality. He's so obsessed with it that sometimes it even affects him while solving problems. At the moment, Mike has two sequences of positive integers A = [a1, a2, ..., an] and B = [b1, b2, ..., bn] of length n each which he uses to ask people some quite peculiar questions.
To test you on how good are you at spotting inequality in life, he wants you to find an "unfair" subset of the original sequence. To be more precise, he wants you to select k numbers P = [p1, p2, ..., pk] such that 1 ≤ pi ≤ n for 1 ≤ i ≤ k and elements in P are distinct. Sequence P will represent indices of elements that you'll select from both sequences. He calls such a subset P "unfair" if and only if the following conditions are satisfied: 2·(ap1 + ... + apk) is greater than the sum of all elements from sequence A, and 2·(bp1 + ... + bpk) is greater than the sum of all elements from the sequence B. Also, k should be smaller or equal to <image> because it will be to easy to find sequence P if he allowed you to select too many elements!
Mike guarantees you that a solution will always exist given the conditions described above, so please help him satisfy his curiosity!
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the sequences.
On the second line there are n space-separated integers a1, ..., an (1 ≤ ai ≤ 109) — elements of sequence A.
On the third line there are also n space-separated integers b1, ..., bn (1 ≤ bi ≤ 109) — elements of sequence B.
Output
On the first line output an integer k which represents the size of the found subset. k should be less or equal to <image>.
On the next line print k integers p1, p2, ..., pk (1 ≤ pi ≤ n) — the elements of sequence P. You can print the numbers in any order you want. Elements in sequence P should be distinct.
Example
Input
5
8 7 4 8 3
4 2 5 3 7
Output
3
1 4 5
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 50;
struct A {
int x, y, i;
} a[MAXN];
vector<int> v;
bool cmp(A a, A b) {
if (a.x == b.x) return a.y > b.y;
return a.x > b.x;
}
int main() {
ios::sync_with_stdio(false);
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i].x;
a[i].i = i;
}
for (int i = 1; i <= n; i++) {
cin >> a[i].y;
}
sort(a + 1, a + n + 1, cmp);
v.push_back(a[1].i);
if (n % 2 == 0) {
v.push_back(a[n].i);
}
for (int i = 2; i <= n - 1; i += 2) {
if (a[i].y >= a[i + 1].y) {
v.push_back(a[i].i);
} else
v.push_back(a[i + 1].i);
}
int l = v.size();
cout << l << endl;
for (int i = 0; i < l; i++) {
cout << v[i] << ' ';
}
cout << endl;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
The cows have just learned what a primitive root is! Given a prime p, a primitive root <image> is an integer x (1 ≤ x < p) such that none of integers x - 1, x2 - 1, ..., xp - 2 - 1 are divisible by p, but xp - 1 - 1 is.
Unfortunately, computing primitive roots can be time consuming, so the cows need your help. Given a prime p, help the cows find the number of primitive roots <image>.
Input
The input contains a single line containing an integer p (2 ≤ p < 2000). It is guaranteed that p is a prime.
Output
Output on a single line the number of primitive roots <image>.
Examples
Input
3
Output
1
Input
5
Output
2
Note
The only primitive root <image> is 2.
The primitive roots <image> are 2 and 3.
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC diagnostic ignored "-Wunused-result"
using namespace std;
int main() {
int p, ans = 0;
scanf("%d", &p);
for (int x = 1; x < p; x++) {
int i, y = 1;
for (i = 1; i <= p - 2; i++) {
y = y * x % p;
if (y == 1) break;
}
if (i == p - 1 && y * x % p == 1) ans++;
}
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
I have n tickets for a train with a rabbit. Each ticket is numbered from 0 to n − 1, and you can use the k ticket to go to p⋅ak + q⋅bk station.
Rabbit wants to go to the all-you-can-eat carrot shop at the station m station ahead of the current station, but wants to walk as short as possible. The stations are lined up at regular intervals. When using, how many stations can a rabbit walk to reach the store?
Input
1 ≤ n, m, a, b, p, q ≤ 1 000 000 000 000 (integer)
Output
Output the number of rabbits that can reach the store on foot at the minimum number of stations in one line.
Examples
Input
6 200 2 3 4 5
Output
1
Input
6 1 2 3 4 5
Output
1
### Response
```cpp
#include<iostream>
#include<string>
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<queue>
#include<ciso646>
#include<random>
#include<map>
#include<set>
#include<complex>
#include<bitset>
#include<stack>
#include<unordered_map>
#include<utility>
using namespace std;
typedef long long ll;
typedef unsigned long long ul;
typedef unsigned int ui;
const ll mod = 1000000007;
typedef long double ld;
const ll INF = mod*mod;
typedef pair<int, int> P;
#define stop char nyaa;cin>>nyaa;
#define rep(i,n) for(int i=0;i<n;i++)
#define per(i,n) for(int i=n-1;i>=0;i--)
#define Rep(i,sta,n) for(int i=sta;i<n;i++)
#define rep1(i,n) for(int i=1;i<=n;i++)
#define per1(i,n) for(int i=n;i>=1;i--)
#define Rep1(i,sta,n) for(int i=sta;i<=n;i++)
const ld eps = 1e-8;
const ld pi = acos(-1.0);
typedef pair<ld, ld> LDP;
typedef pair<ll, ll> LP;
#define fr first
#define sc second
//t個が1,x以下とx以上を求める
LP calc(ll x, int t,int sup=40) {
vector<int> v;
rep(i, sup) {
ll k = (ll)1 << i;
if (x&k)v.push_back(i);
}
int len = v.size();
ll le = 0;
if (t <= len) {
for (int i = len - 1; i >= len - t; i--) {
le += (ll)1 << v[i];
}
}
else {
bool f = false;
rep(i, len) {
int cnt = v[i];
cnt += len - 1 - i;
if (cnt >= t) {
for (int j = len - 1; j > i; j--) {
le += (ll)1<<v[j];
}
int r = t - (len - 1 - i);
rep(j, r) {
le += (ll)1 << j;
}
f = true;
break;
}
}
if (!f)le = -INF;
}
ll ri = 0;
if (t <= len) {
int tmp = len;
rep(i, sup) {
ll k = (ll)1 << i;
if (k&x) {
tmp--; continue;
}
int cnt = i;
cnt += tmp;
cnt++;
if (tmp + 1 <= t && cnt >= t) {
ri += k;
Rep(j, len-tmp, len) {
ri += (ll)1 << v[j];
}
int r = t - (tmp + 1);
rep(j, r) {
ri += (ll)1 << j;
}
break;
}
}
}
else {
rep(i, len) {
ri += (ll)1 << v[i];
}
int r = t - len;
rep(j, sup) {
if (r == 0)break;
ll k = (ll)1 << j;
if ((x&k) == 0) {
ri += k; r--;
}
}
}
return { le,ri };
}
string add(string a, string b) {
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int len = max(a.length(), b.length());
int rest = 0; string res;
rep(i, len + 1) {
if (i < (int)a.length()) {
rest += a[i] - '0';
}
if (i < (int)b.length()) {
rest += b[i] - '0';
}
res.push_back('0' + (rest % 10));
rest /= 10;
}
while (res.length() && res[res.length() - 1] == '0')res.erase(res.end() - 1);
reverse(res.begin(), res.end());
return res;
}
string multi0(int m, string a) {
string res;
reverse(a.begin(), a.end());
int len = a.length();
int rest = 0;
rep(i, len) {
rest += m * (a[i] - '0');
res.push_back('0' + (rest % 10));
rest /= 10;
}
if (rest)res.push_back('0' + rest);
reverse(res.begin(), res.end());
return res;
}
string multi(string a, string b) {
int len = a.length(); string res = "0";
per(i, len) {
int t = a[i] - '0'; int rest = len - i - 1;
string nex = multi0(t, b);
rep(j, rest) {
nex.push_back('0');
}
res = add(res, nex);
}
return res;
}
bool invalid(ll a,ll p) {
string s = to_string(a); string t = to_string(p);
string st = multi(s, t);
if (st.size() >= 15)return true;
else return false;
}
void solve() {
ll n, m, a, b, p, q; cin >> n >> m >> a >> b >> p >> q;
if (a > b) {
swap(a, b); swap(p, q);
}
ll ans = INF;
if (invalid(a, p) || invalid(b, q)) {
ans = m;
ans = min(ans, abs(m - p - q));
}
else if (invalid(a,a)||invalid(b,b)) {
//cout << "hello" << endl;
ans = min(ans, m);
ans = min(ans, abs(m - p - q));
if (n > 1) {
ans = min(ans, abs(m - p * a - q * b));
ans = min(ans, abs(m - p * a - q * b - p - q));
}
}
else if (a == 1 && b == 1) {
ll le = m / (p + q);
if (n < le) {
ll sum = (p + q)*n;
ans = min(ans, m - sum);
}
else {
ans = min(ans, m - (p + q)*le);
}
if (n >= le + 1) {
ans = min(ans, (p + q)*(le + 1) - m);
}
}
else if (a == 1 && b == 2) {
ll x = a, y = b;
rep(i, n) {
ll sum = p * x + q * y;
if (sum >= m) {
ans = min(ans, sum - m); break;
}
x = x * a; y = y * b;
}
ll s = min(n, (ll)40);
//i個使う
rep1(i, s) {
ll mm = m - i * p;
ll d = mm / q;
LP z = calc(d, i, s);
if (z.first != -INF) {
ans = min(ans, abs(mm - q * z.first));
}
ans = min(ans, abs(mm - q * z.second));
//ll lesum = q * z.first, risum = q * z.second;
//cout << lesum + i * p << " i " << risum + i * p << endl;
//ans = min(ans, abs(mm - lesum));
//ans = min(ans, abs(risum - mm));
}
}
else if (a == 2 && b == 2) {
ll d = m / (p + q);
ll s = min(n, (ll)40);
ll z = 0;
rep(i, s) {
z += (ll)1 << i;
}
if (z < m)ans = min(ans, m - z * (p + q));
else {
ll le = d;
ans = min(ans, m - le * (p + q));
le++;
ll las = 0;
rep(i, 40) {
ll k = (ll)1 << i;
if (k&le) {
las = i;
}
}
if (las < n) {
ans = min(ans, m - le * (p + q));
}
}
}
else {
ll x = 1, y = 1;
vector<ll> v;
rep(i, n) {
ll sum = p * x + q * y;
if (sum >= m) {
ans = min(ans, sum - m);
break;
}
v.push_back(sum);
x = x * a; y = y * b;
}
int len = v.size();
ll sum = 0;
per(i, v.size()) {
if (sum + v[i] <= m) {
sum += v[i];
}
else {
ans = min(ans, abs(m - sum-v[i]));
}
}
ans = min(ans, abs(m - sum));
/*cout << len << endl;
rep(i, (1 << len)) {
ll u = 0;
rep(j, len) {
if (i&(1 << j))u += v[j];
}
ans = min(ans, abs(m - u));
}*/
}
cout << ans << endl;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
solve();
//stop
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1, p2, ..., pn.
Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k distinct elements.
Input
The single line of the input contains two space-separated positive integers n, k (1 ≤ k < n ≤ 105).
Output
Print n integers forming the permutation. If there are multiple answers, print any of them.
Examples
Input
3 2
Output
1 3 2
Input
3 1
Output
1 2 3
Input
5 2
Output
1 3 2 4 5
Note
By |x| we denote the absolute value of number x.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
while (cin >> n >> m) {
int i = 1;
for (i; i <= m; i++) {
if (i != 1) printf(" ");
if (i % 2 == 1)
printf("%d", i / 2 + 1);
else
printf("%d", n - i / 2 + 1);
}
if (i % 2 == 1) {
int end = (i + 1) / 2;
for (int j = n - (i + 1) / 2 + 1; j >= end; j--) {
printf(" %d", j);
}
printf("\n");
} else {
int end = n - (i + 1) / 2 + 1;
for (int j = (i - 1) / 2 + 2; j <= end; j++) {
printf(" %d", j);
}
printf("\n");
}
}
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Alyona has built n towers by putting small cubes some on the top of others. Each cube has size 1 × 1 × 1. A tower is a non-zero amount of cubes standing on the top of each other. The towers are next to each other, forming a row.
Sometimes Alyona chooses some segment towers, and put on the top of each tower several cubes. Formally, Alyouna chooses some segment of towers from li to ri and adds di cubes on the top of them.
Let the sequence a1, a2, ..., an be the heights of the towers from left to right. Let's call as a segment of towers al, al + 1, ..., ar a hill if the following condition holds: there is integer k (l ≤ k ≤ r) such that al < al + 1 < al + 2 < ... < ak > ak + 1 > ak + 2 > ... > ar.
After each addition of di cubes on the top of the towers from li to ri, Alyona wants to know the maximum width among all hills. The width of a hill is the number of towers in it.
Input
The first line contain single integer n (1 ≤ n ≤ 3·105) — the number of towers.
The second line contain n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the number of cubes in each tower.
The third line contain single integer m (1 ≤ m ≤ 3·105) — the number of additions.
The next m lines contain 3 integers each. The i-th of these lines contains integers li, ri and di (1 ≤ l ≤ r ≤ n, 1 ≤ di ≤ 109), that mean that Alyona puts di cubes on the tio of each of the towers from li to ri.
Output
Print m lines. In i-th line print the maximum width of the hills after the i-th addition.
Example
Input
5
5 5 5 5 5
3
1 3 2
2 2 1
4 4 1
Output
2
4
5
Note
The first sample is as follows:
After addition of 2 cubes on the top of each towers from the first to the third, the number of cubes in the towers become equal to [7, 7, 7, 5, 5]. The hill with maximum width is [7, 5], thus the maximum width is 2.
After addition of 1 cube on the second tower, the number of cubes in the towers become equal to [7, 8, 7, 5, 5]. The hill with maximum width is now [7, 8, 7, 5], thus the maximum width is 4.
After addition of 1 cube on the fourth tower, the number of cubes in the towers become equal to [7, 8, 7, 6, 5]. The hill with maximum width is now [7, 8, 7, 6, 5], thus the maximum width is 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1500001;
struct JS {
int l, r, sum, ld, rd, ud, lud, udr;
long long d, lone, rone;
} f[N];
int i, j, n, m;
long long a[N], b[N];
void update(int k) {
if (f[k].l == f[k].r) {
return;
}
long long x = f[2 * k].rone + f[2 * k].d,
y = f[2 * k + 1].lone + f[2 * k + 1].d;
f[k].lone = f[2 * k].lone + f[2 * k].d;
f[k].rone = f[2 * k + 1].rone + f[2 * k + 1].d;
if (f[2 * k + 1].rd < f[2 * k + 1].sum || x >= y)
f[k].rd = f[2 * k + 1].rd;
else
f[k].rd = f[2 * k + 1].sum + f[2 * k].rd;
if (f[2 * k].ld < f[2 * k].sum || x <= y)
f[k].ld = f[2 * k].ld;
else
f[k].ld = f[2 * k].sum + f[2 * k + 1].ld;
f[k].lud = f[2 * k].lud;
if (f[2 * k].lud == f[2 * k].sum && x > y)
f[k].lud = max(f[k].lud, f[2 * k].sum + f[2 * k + 1].ld);
if (f[2 * k].rd == f[2 * k].sum && x < y)
f[k].lud = max(f[k].lud, f[2 * k].sum + f[2 * k + 1].lud);
f[k].udr = f[2 * k + 1].udr;
if (f[2 * k + 1].udr == f[2 * k + 1].sum && x < y)
f[k].udr = max(f[k].udr, f[2 * k].rd + f[2 * k + 1].sum);
if (f[2 * k + 1].ld == f[2 * k + 1].sum && x > y)
f[k].udr = max(f[k].udr, f[2 * k].udr + f[2 * k + 1].sum);
f[k].ud = max(f[2 * k].ud, f[2 * k + 1].ud);
if (x > y) f[k].ud = max(f[k].ud, f[2 * k].udr + f[2 * k + 1].ld);
if (x < y) f[k].ud = max(f[k].ud, f[2 * k].rd + f[2 * k + 1].lud);
}
void push(int k) {
f[2 * k].d += f[k].d;
f[2 * k + 1].d += f[k].d;
f[k].d = 0;
}
void build(int k, int l, int r) {
f[k].l = l;
f[k].r = r;
f[k].sum = r - l + 1;
if (l == r) {
f[k].d = a[l];
f[k].ld = f[k].rd = f[k].ud = f[k].lud = f[k].udr = 1;
} else {
int mid = (l + r) / 2;
build(2 * k, l, mid);
build(2 * k + 1, mid + 1, r);
update(k);
}
}
void change(int k, int L, int R, long long x) {
if (L <= f[k].l && f[k].r <= R)
f[k].d += x;
else {
push(k);
int mid = (f[k].l + f[k].r) / 2;
if (L <= mid) change(2 * k, L, R, x);
if (R > mid) change(2 * k + 1, L, R, x);
update(k);
}
}
long long get(int k, int wh) {
if (f[k].l == f[k].r) return f[k].d;
f[2 * k].d += f[k].d;
f[2 * k + 1].d += f[k].d;
f[k].d = 0;
int mid = (f[k].l + f[k].r) / 2;
if (wh <= mid)
return get(2 * k, wh);
else
return get(2 * k + 1, wh);
}
int main() {
scanf("%d", &n);
for (i = 1; i <= n; i++) scanf("%lld", &a[i]);
build(1, 1, n);
scanf("%d", &m);
for (i = 1; i <= m; i++) {
int x, y;
long long z;
scanf("%d%d%lld", &x, &y, &z);
change(1, x, y, z);
printf("%d\n", f[1].ud);
}
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Alexey, a merry Berland entrant, got sick of the gray reality and he zealously wants to go to university. There are a lot of universities nowadays, so Alexey is getting lost in the diversity — he has not yet decided what profession he wants to get. At school, he had bad grades in all subjects, and it's only thanks to wealthy parents that he was able to obtain the graduation certificate.
The situation is complicated by the fact that each high education institution has the determined amount of voluntary donations, paid by the new students for admission — ni berubleys. He cannot pay more than ni, because then the difference between the paid amount and ni can be regarded as a bribe!
Each rector is wearing the distinctive uniform of his university. Therefore, the uniform's pockets cannot contain coins of denomination more than ri. The rector also does not carry coins of denomination less than li in his pocket — because if everyone pays him with so small coins, they gather a lot of weight and the pocket tears. Therefore, a donation can be paid only by coins of denomination x berubleys, where li ≤ x ≤ ri (Berland uses coins of any positive integer denomination). Alexey can use the coins of different denominations and he can use the coins of the same denomination any number of times. When Alexey was first confronted with such orders, he was puzzled because it turned out that not all universities can accept him! Alexey is very afraid of going into the army (even though he had long wanted to get the green uniform, but his dad says that the army bullies will beat his son and he cannot pay to ensure the boy's safety). So, Alexey wants to know for sure which universities he can enter so that he could quickly choose his alma mater.
Thanks to the parents, Alexey is not limited in money and we can assume that he has an unlimited number of coins of each type.
In other words, you are given t requests, each of them contains numbers ni, li, ri. For each query you need to answer, whether it is possible to gather the sum of exactly ni berubleys using only coins with an integer denomination from li to ri berubleys. You can use coins of different denominations. Coins of each denomination can be used any number of times.
Input
The first line contains the number of universities t, (1 ≤ t ≤ 1000) Each of the next t lines contain three space-separated integers: ni, li, ri (1 ≤ ni, li, ri ≤ 109; li ≤ ri).
Output
For each query print on a single line: either "Yes", if Alexey can enter the university, or "No" otherwise.
Examples
Input
2
5 2 3
6 4 5
Output
Yes
No
Note
You can pay the donation to the first university with two coins: one of denomination 2 and one of denomination 3 berubleys. The donation to the second university cannot be paid.
### Response
```cpp
#include <bits/stdc++.h>
long long int n, k, a, b;
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n;
for (int i = 0; i < n; i++) {
cin >> k >> a >> b;
if (k / a != k / b || k % a == 0 || k % b == 0)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
You are given two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n. Each element of both sequences is either 0, 1 or 2. The number of elements 0, 1, 2 in the sequence a is x_1, y_1, z_1 respectively, and the number of elements 0, 1, 2 in the sequence b is x_2, y_2, z_2 respectively.
You can rearrange the elements in both sequences a and b however you like. After that, let's define a sequence c as follows:
c_i = \begin{cases} a_i b_i & \mbox{if }a_i > b_i \\\ 0 & \mbox{if }a_i = b_i \\\ -a_i b_i & \mbox{if }a_i < b_i \end{cases}
You'd like to make ∑_{i=1}^n c_i (the sum of all elements of the sequence c) as large as possible. What is the maximum possible sum?
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases.
Each test case consists of two lines. The first line of each test case contains three integers x_1, y_1, z_1 (0 ≤ x_1, y_1, z_1 ≤ 10^8) — the number of 0-s, 1-s and 2-s in the sequence a.
The second line of each test case also contains three integers x_2, y_2, z_2 (0 ≤ x_2, y_2, z_2 ≤ 10^8; x_1 + y_1 + z_1 = x_2 + y_2 + z_2 > 0) — the number of 0-s, 1-s and 2-s in the sequence b.
Output
For each test case, print the maximum possible sum of the sequence c.
Example
Input
3
2 3 2
3 3 1
4 0 1
2 3 0
0 0 1
0 0 1
Output
4
2
0
Note
In the first sample, one of the optimal solutions is:
a = \{2, 0, 1, 1, 0, 2, 1\}
b = \{1, 0, 1, 0, 2, 1, 0\}
c = \{2, 0, 0, 0, 0, 2, 0\}
In the second sample, one of the optimal solutions is:
a = \{0, 2, 0, 0, 0\}
b = \{1, 1, 0, 1, 0\}
c = \{0, 2, 0, 0, 0\}
In the third sample, the only possible solution is:
a = \{2\}
b = \{2\}
c = \{0\}
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int t;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> t;
while (t--) {
int a[3];
int b[3];
cin >> a[0] >> a[1] >> a[2];
cin >> b[0] >> b[1] >> b[2];
long long sum = 0;
int aux = 0;
for (int i = 2; i >= 0; i--) {
if (i == 2) {
for (int j : {1, 2, 0}) {
aux = min(a[i], b[j]);
if (i > j)
sum += aux * i * j;
else if (i < j)
sum -= aux * i * j;
a[i] -= aux;
b[j] -= aux;
}
} else if (i == 1) {
for (int j : {1, 0, 2}) {
aux = min(a[i], b[j]);
if (i > j)
sum += aux * i * j;
else if (i < j)
sum -= aux * i * j;
a[i] -= aux;
b[j] -= aux;
}
} else {
for (int j : {0, 1, 2}) {
aux = min(a[i], b[j]);
if (i > j)
sum += aux * i * j;
else if (i < j)
sum -= aux * i * j;
a[i] -= aux;
b[j] -= aux;
}
}
}
cout << sum << "\n";
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Demiurges Shambambukli and Mazukta love to watch the games of ordinary people. Today, they noticed two men who play the following game.
There is a rooted tree on n nodes, m of which are leaves (a leaf is a nodes that does not have any children), edges of the tree are directed from parent to children. In the leaves of the tree integers from 1 to m are placed in such a way that each number appears exactly in one leaf.
Initially, the root of the tree contains a piece. Two players move this piece in turns, during a move a player moves the piece from its current nodes to one of its children; if the player can not make a move, the game ends immediately. The result of the game is the number placed in the leaf where a piece has completed its movement. The player who makes the first move tries to maximize the result of the game and the second player, on the contrary, tries to minimize the result. We can assume that both players move optimally well.
Demiurges are omnipotent, so before the game they can arbitrarily rearrange the numbers placed in the leaves. Shambambukli wants to rearrange numbers so that the result of the game when both players play optimally well is as large as possible, and Mazukta wants the result to be as small as possible. What will be the outcome of the game, if the numbers are rearranged by Shambambukli, and what will it be if the numbers are rearranged by Mazukta? Of course, the Demiurges choose the best possible option of arranging numbers.
Input
The first line contains a single integer n — the number of nodes in the tree (1 ≤ n ≤ 2·105).
Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n) — the ends of the edge of the tree; the edge leads from node ui to node vi. It is guaranteed that the described graph is a rooted tree, and the root is the node 1.
Output
Print two space-separated integers — the maximum possible and the minimum possible result of the game.
Examples
Input
5
1 2
1 3
2 4
2 5
Output
3 2
Input
6
1 2
1 3
3 4
1 5
5 6
Output
3 3
Note
Consider the first sample. The tree contains three leaves: 3, 4 and 5. If we put the maximum number 3 at node 3, then the first player moves there and the result will be 3. On the other hand, it is easy to see that for any rearrangement the first player can guarantee the result of at least 2.
In the second sample no matter what the arragment is the first player can go along the path that ends with a leaf with number 3.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int SIZE = 2e5 + 50;
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 << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
return f * x;
}
int n, num_edge, leaves;
int head[SIZE];
int dp_min[SIZE][2], dp_max[SIZE][2];
struct node {
int to, nxt;
};
node edge[SIZE << 1];
inline void add(int u, int v) {
edge[++num_edge].to = v;
edge[num_edge].nxt = head[u];
head[u] = num_edge;
}
void pre(int u, int fa) {
int son = 0;
for (int i = head[u]; i; i = edge[i].nxt) {
int v = edge[i].to;
if (v == fa) continue;
son++;
pre(v, u);
}
if (!son) {
leaves++;
dp_min[u][1] = dp_min[u][0] = dp_max[u][1] = dp_max[u][0] = 1;
}
}
void dfs(int u, int fa) {
if (dp_min[u][1]) return;
dp_min[u][1] = 0;
dp_min[u][0] = 1e9;
dp_max[u][1] = 1e9;
dp_max[u][0] = 0;
for (int i = head[u]; i; i = edge[i].nxt) {
int v = edge[i].to;
if (v == fa) continue;
dfs(v, u);
dp_min[u][1] += dp_min[v][0];
dp_min[u][0] = min(dp_min[u][0], dp_min[v][1]);
dp_max[u][1] = min(dp_max[u][1], dp_max[v][0]);
dp_max[u][0] += dp_max[v][1];
}
}
int main() {
n = read();
for (int i = 1; i < n; ++i) {
int u = read(), v = read();
add(u, v), add(v, u);
}
pre(1, 1);
dfs(1, 1);
printf("%d %d\n", leaves - dp_max[1][1] + 1, dp_min[1][1]);
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants.
The Roman Empire consisted of n cities numbered from 1 to n. It also had m bidirectional roads numbered from 1 to m. Each road connected two different cities. Any two cities were connected by no more than one road.
We say that there is a path between cities c1 and c2 if there exists a finite sequence of cities t1, t2, ..., tp (p ≥ 1) such that:
* t1 = c1
* tp = c2
* for any i (1 ≤ i < p), cities ti and ti + 1 are connected by a road
We know that there existed a path between any two cities in the Roman Empire.
In the Empire k merchants lived numbered from 1 to k. For each merchant we know a pair of numbers si and li, where si is the number of the city where this merchant's warehouse is, and li is the number of the city where his shop is. The shop and the warehouse could be located in different cities, so the merchants had to deliver goods from the warehouse to the shop.
Let's call a road important for the merchant if its destruction threatens to ruin the merchant, that is, without this road there is no path from the merchant's warehouse to his shop. Merchants in the Roman Empire are very greedy, so each merchant pays a tax (1 dinar) only for those roads which are important for him. In other words, each merchant pays di dinars of tax, where di (di ≥ 0) is the number of roads important for the i-th merchant.
The tax collection day came in the Empire. The Smart Beaver from ABBYY is very curious by nature, so he decided to count how many dinars each merchant had paid that day. And now he needs your help.
Input
The first input line contains two integers n and m, separated by a space, n is the number of cities, and m is the number of roads in the empire.
The following m lines contain pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), separated by a space — the numbers of cities connected by the i-th road. It is guaranteed that any two cities are connected by no more than one road and that there exists a path between any two cities in the Roman Empire.
The next line contains a single integer k — the number of merchants in the empire.
The following k lines contain pairs of integers si, li (1 ≤ si, li ≤ n), separated by a space, — si is the number of the city in which the warehouse of the i-th merchant is located, and li is the number of the city in which the shop of the i-th merchant is located.
The input limitations for getting 20 points are:
* 1 ≤ n ≤ 200
* 1 ≤ m ≤ 200
* 1 ≤ k ≤ 200
The input limitations for getting 50 points are:
* 1 ≤ n ≤ 2000
* 1 ≤ m ≤ 2000
* 1 ≤ k ≤ 2000
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 105
* 1 ≤ m ≤ 105
* 1 ≤ k ≤ 105
Output
Print exactly k lines, the i-th line should contain a single integer di — the number of dinars that the i-th merchant paid.
Examples
Input
7 8
1 2
2 3
3 4
4 5
5 6
5 7
3 5
4 7
4
1 5
2 4
2 6
4 7
Output
2
1
2
0
Note
The given sample is illustrated in the figure below.
<image>
Let's describe the result for the first merchant. The merchant's warehouse is located in city 1 and his shop is in city 5. Let us note that if either road, (1, 2) or (2, 3) is destroyed, there won't be any path between cities 1 and 5 anymore. If any other road is destroyed, the path will be preserved. That's why for the given merchant the answer is 2.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<int> a[100005], e[100005];
int dep[100005], low[100005];
int u[100005], g[100005];
int FIND(int x) { return g[x] == x ? x : g[x] = FIND(g[x]); }
void UNION(int x, int y) { g[FIND(x)] = FIND(y); }
void go(int lev, int x, int from = -1) {
u[x] = 1;
dep[x] = lev;
low[x] = lev;
for (int i = 0; i < (int)a[x].size(); i++) {
if (!u[a[x][i]]) {
go(lev + 1, a[x][i], x);
if (low[a[x][i]] <= lev) {
UNION(a[x][i], x);
low[x] = min(low[x], low[a[x][i]]);
}
} else if (a[x][i] != from) {
if (low[a[x][i]] <= lev) {
UNION(a[x][i], x);
low[x] = min(low[x], low[a[x][i]]);
}
}
}
}
int ldep[100005];
int lca[100005];
vector<pair<int, int> > q[100005];
int gg[100005];
int v[100005];
int FIND2(int x) { return x == gg[x] ? x : gg[x] = FIND2(gg[x]); }
void UNION2(int x, int y) { gg[FIND2(x)] = FIND2(y); }
void dfs(int x, int from = -1, int lev = 0) {
v[x] = 1;
ldep[x] = lev;
for (int i = 0; i < (int)e[x].size(); i++) {
int y = e[x][i];
if (!v[y]) dfs(y, x, lev + 1);
}
for (int i = 0; i < (int)q[x].size(); i++) {
int to = q[x][i].first;
if (v[to]) lca[q[x][i].second] = ldep[x] + ldep[to] - 2 * ldep[FIND2(to)];
}
UNION2(x, from);
v[x] = 2;
}
int main(void) {
int n, m, k;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) g[i] = i;
for (int i = 0; i < m; i++) {
int x, y;
scanf("%d%d", &x, &y);
a[x].push_back(y);
a[y].push_back(x);
}
scanf("%d", &k);
for (int i = 1; i <= n; i++) gg[i] = i;
for (int i = 1; i <= n; i++) {
if (!u[i]) {
go(0, i);
}
}
for (int i = 1; i <= n; i++)
for (int j = 0; j < (int)a[i].size(); j++)
if (FIND(i) != FIND(a[i][j])) e[FIND(i)].push_back(FIND(a[i][j]));
for (int i = 0; i < k; i++) {
int x, y;
scanf("%d%d", &x, &y);
x = FIND(x);
y = FIND(y);
q[x].push_back(make_pair(y, i));
q[y].push_back(make_pair(x, i));
}
dfs(FIND(1));
for (int i = 0; i < k; i++) printf("%d\n", lca[i]);
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
There are N rabbits, numbered 1 through N.
The i-th (1≤i≤N) rabbit likes rabbit a_i. Note that no rabbit can like itself, that is, a_i≠i.
For a pair of rabbits i and j (i<j), we call the pair (i,j) a friendly pair if the following condition is met.
* Rabbit i likes rabbit j and rabbit j likes rabbit i.
Calculate the number of the friendly pairs.
Constraints
* 2≤N≤10^5
* 1≤a_i≤N
* a_i≠i
Input
The input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the number of the friendly pairs.
Examples
Input
4
2 1 4 3
Output
2
Input
3
2 3 1
Output
0
Input
5
5 5 5 5 1
Output
1
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
int n,a[100010];
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
a[i]--;
}
int ans=0;
for(int i=0;i<n;i++) if(a[a[i]]==i){ ans++; a[i]=-1;}
cout<<ans<<endl;
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
You are given a mysterious language (codenamed "Secret") available in "Custom Test" tab. Find out what this language is and write a program which outputs its name. Note that the program must be written in this language.
Input
This program has only one test, and it's empty (it doesn't give your program anything to read).
Output
Output the name of the mysterious language.
Examples
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
puts("INTERCAL");
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Bogdan has a birthday today and mom gave him a tree consisting of n vertecies. For every edge of the tree i, some number xi was written on it. In case you forget, a tree is a connected non-directed graph without cycles. After the present was granted, m guests consecutively come to Bogdan's party. When the i-th guest comes, he performs exactly one of the two possible operations:
1. Chooses some number yi, and two vertecies ai and bi. After that, he moves along the edges of the tree from vertex ai to vertex bi using the shortest path (of course, such a path is unique in the tree). Every time he moves along some edge j, he replaces his current number yi by <image>, that is, by the result of integer division yi div xj.
2. Chooses some edge pi and replaces the value written in it xpi by some positive integer ci < xpi.
As Bogdan cares about his guests, he decided to ease the process. Write a program that performs all the operations requested by guests and outputs the resulting value yi for each i of the first type.
Input
The first line of the input contains integers, n and m (2 ≤ n ≤ 200 000, 1 ≤ m ≤ 200 000) — the number of vertecies in the tree granted to Bogdan by his mom and the number of guests that came to the party respectively.
Next n - 1 lines contain the description of the edges. The i-th of these lines contains three integers ui, vi and xi (1 ≤ ui, vi ≤ n, ui ≠ vi, 1 ≤ xi ≤ 1018), denoting an edge that connects vertecies ui and vi, with the number xi initially written on it.
The following m lines describe operations, requested by Bogdan's guests. Each description contains three or four integers and has one of the two possible forms:
* 1 ai bi yi corresponds to a guest, who chooses the operation of the first type.
* 2 pi ci corresponds to a guests, who chooses the operation of the second type.
It is guaranteed that all the queries are correct, namely 1 ≤ ai, bi ≤ n, 1 ≤ pi ≤ n - 1, 1 ≤ yi ≤ 1018 and 1 ≤ ci < xpi, where xpi represents a number written on edge pi at this particular moment of time that is not necessarily equal to the initial value xpi, as some decreases may have already been applied to it. The edges are numbered from 1 to n - 1 in the order they appear in the input.
Output
For each guest who chooses the operation of the first type, print the result of processing the value yi through the path from ai to bi.
Examples
Input
6 6
1 2 1
1 3 7
1 4 4
2 5 5
2 6 2
1 4 6 17
2 3 2
1 4 6 17
1 5 5 20
2 4 1
1 5 1 3
Output
2
4
20
3
Input
5 4
1 2 7
1 3 3
3 4 2
3 5 5
1 4 2 100
1 5 4 1
2 2 2
1 1 3 4
Output
2
0
2
Note
Initially the tree looks like this:
<image>
The response to the first query is: <image> = 2
After the third edge is changed, the tree looks like this:
<image>
The response to the second query is: <image> = 4
In the third query the initial and final vertex coincide, that is, the answer will be the initial number 20.
After the change in the fourth edge the tree looks like this:
<image>
In the last query the answer will be: <image> = 3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m;
vector<pair<int, unsigned long long int> > e[200110];
int parent[200110];
unsigned long long int parent_weight[200110];
int depth[200110];
int sz[200110];
unsigned long long int seg[200110 * 3];
pair<int, int> num[200110];
int tnum[200110];
int lca[200110][19];
pair<int, int> yol[200110];
int st = 1;
inline unsigned long long int carp(unsigned long long int x,
unsigned long long int y) {
if (x == 0) return 0;
if (y == 0) return 0;
unsigned long long int c = x * y;
if (c / x == y)
return c;
else
return 2000000000000000000LL;
}
unsigned long long int find(int d, int a, int b, int x, int y) {
if (b < x || y < a) return 1;
if (x <= a && b <= y) return seg[d];
return carp(find(d * 2, a, (a + b) / 2, x, y),
find(d * 2 + 1, (a + b) / 2 + 1, b, x, y));
}
unsigned long long int update(int d, int a, int b, int x,
unsigned long long int y) {
if (b < x || x < a) return seg[d];
if (a == b && a == x) return seg[d] = y;
return seg[d] = carp(update(d * 2, a, (a + b) / 2, x, y),
update(d * 2 + 1, (a + b) / 2 + 1, b, x, y));
}
int dfs1(int x, int pr, int dep, unsigned long long int yol) {
sz[x] = 1;
depth[x] = dep;
parent_weight[x] = yol;
parent[x] = pr;
for (int i = 0; i < e[x].size(); i++) {
int y = e[x][i].first;
unsigned long long int c = e[x][i].second;
if (y == pr) continue;
sz[x] += dfs1(y, x, dep + 1, c);
}
return sz[x];
}
void dfs2(int x, int par, int dontgo) {
if (par == -1) {
par = st;
num[x] = make_pair(st, st);
tnum[st] = x;
st++;
} else {
tnum[st] = x;
num[x] = make_pair(st++, par);
}
update(1, 1, n + 10, num[x].first, parent_weight[x]);
for (int i = 0; i < e[x].size(); i++) {
int y = e[x][i].first;
if (y == dontgo) continue;
if (sz[y] > sz[x] / 2) dfs2(y, par, x);
}
for (int i = 0; i < e[x].size(); i++) {
int y = e[x][i].first;
if (y == dontgo) continue;
if (sz[y] <= sz[x] / 2) dfs2(y, -1, x);
}
}
void dfs3(int x, int y, unsigned long long int& c) {
if (x == y) return;
int ay = num[y].first;
while (true) {
int ax = num[x].first;
int stx = num[x].second;
if (stx <= ay && ay <= ax) {
c /= find(1, 1, n + 10, ay + 1, ax);
break;
} else {
c /= find(1, 1, n + 10, stx + 1, ax);
c /= parent_weight[tnum[stx]];
x = parent[tnum[stx]];
}
}
}
void MakeLCA() {
for (int i = 1; i <= n; i++) lca[i][0] = parent[i];
for (int k = 1; k <= 18; k++)
for (int i = 1; i <= n; i++) lca[i][k] = lca[lca[i][k - 1]][k - 1];
}
int GetLCA(int x, int y) {
if (x == y) return x;
if (depth[x] < depth[y]) swap(x, y);
for (int k = 18; k >= 0; k--)
if (lca[x][k] != 0 && depth[lca[x][k]] >= depth[y]) x = lca[x][k];
if (x == y) return x;
for (int k = 18; k >= 0; k--)
if (lca[x][k] != 0 && lca[x][k] != lca[y][k]) x = lca[x][k], y = lca[y][k];
x = lca[x][0];
return x;
}
unsigned long long int getans(int x, int y, unsigned long long int c) {
int lca = GetLCA(x, y);
dfs3(x, lca, c);
dfs3(y, lca, c);
return c;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i < n; i++) {
int x, y;
unsigned long long int c;
scanf("%d%d%I64d", &x, &y, &c);
e[x].push_back(make_pair(y, c));
e[y].push_back(make_pair(x, c));
yol[i] = make_pair(x, y);
}
dfs1(1, 0, 1, 0);
dfs2(1, -1, -1);
update(1, 1, n + 10, 1, 1);
MakeLCA();
while (m--) {
int t;
scanf("%d", &t);
int x, y;
unsigned long long int c;
if (t == 1) {
scanf("%d%d%I64d", &x, &y, &c);
unsigned long long int cevap = getans(x, y, c);
printf("%I64d\n", cevap);
} else {
scanf("%d%I64d", &x, &c);
int a1 = yol[x].first;
int a2 = yol[x].second;
if (parent[a1] == a2) swap(a1, a2);
update(1, 1, n + 10, num[a2].first, c);
parent_weight[a2] = c;
}
}
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Takahashi the Jumbo will practice golf.
His objective is to get a carry distance that is a multiple of K, while he can only make a carry distance of between A and B (inclusive).
If he can achieve the objective, print `OK`; if he cannot, print `NG`.
Constraints
* All values in input are integers.
* 1 \leq A \leq B \leq 1000
* 1 \leq K \leq 1000
Input
Input is given from Standard Input in the following format:
K
A B
Output
If he can achieve the objective, print `OK`; if he cannot, print `NG`.
Examples
Input
7
500 600
Output
OK
Input
4
5 7
Output
NG
Input
1
11 11
Output
OK
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int k,a,b;
cin>>k>>a>>b;
if(b-a>=k-a%k||a%k==0)cout<<"OK";
else cout<<"NG";
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Does the card fit in a snack? (Are Cards Snacks?)
square1001 You have $ N $ cards.
Each of these cards has an integer written on it, and the integer on the $ i $ th card is $ A_i $.
square1001 Your random number today is $ K $. square1001 You want to choose some of these $ N $ cards so that they add up to $ K $.
E869120, who was watching this situation, wanted to prevent this.
Specifically, I want to eat a few cards in advance so that square1001 doesn't add up to $ K $ no matter how you choose the rest of the cards.
However, E869120 is full and I don't want to eat cards as much as possible.
Now, how many cards can you eat at least E869120 to prevent this?
input
Input is given from standard input in the following format.
$ N $ $ K $
$ A_1 $ $ A_2 $ $ A_3 $ $ \ cdots $ $ A_N $
output
E869120 Print the minimum number of cards you eat to achieve your goal in one line.
However, insert a line break at the end.
Constraint
* $ 1 \ leq N \ leq 20 $
* $ 1 \ leq K \ leq 1000000000 \ (= 10 ^ 9) $
* $ 0 \ leq A_i \ leq 1000000 \ (= 10 ^ 6) $
* All inputs are integers.
Input example 1
5 9
8 6 9 1 2
Output example 1
2
For example, you can thwart square1001's purpose by eating the third card (which has a 9) and the fourth card (which has a 1).
Input example 2
8 2
1 1 1 1 1 1 1 1
Output example 2
7
Input example 3
20 200
31 12 21 17 19 29 25 40 5 8 32 1 27 20 31 13 35 1 8 5
Output example 3
6
Example
Input
5 9
8 6 9 1 2
Output
2
### Response
```cpp
#include<iostream>
using namespace std;
bool ng[1<<20] = {};
int popcnt[1<<20] = {};
int main(){
int n, k;
cin >> n >> k;
int a[n], ret = n;
for(int i = 0; i < n; i++) cin >> a[i];
for(int s = 1; s < 1<<n; s++){
int sum = 0;
for(int i = 0; i < n; i++) if((s>>i)&1) sum += a[i], popcnt[s]++;
ng[s] = sum==k;
for(int i = 0; i < n; i++) if((s>>i)&1) ng[s] |= ng[s^(1<<i)];
if(!ng[s]) ret = min(ret, n-popcnt[s]);
}
cout << ret << endl;
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
A breakthrough among computer games, "Civilization XIII", is striking in its scale and elaborate details. Let's take a closer look at one of them.
The playing area in the game is split into congruent cells that are regular hexagons. The side of each cell is equal to 1. Each unit occupies exactly one cell of the playing field. The field can be considered infinite.
Let's take a look at the battle unit called an "Archer". Each archer has a parameter "shot range". It's a positive integer that determines the radius of the circle in which the archer can hit a target. The center of the circle coincides with the center of the cell in which the archer stays. A cell is considered to be under the archer’s fire if and only if all points of this cell, including border points are located inside the circle or on its border.
The picture below shows the borders for shot ranges equal to 3, 4 and 5. The archer is depicted as A.
<image>
Find the number of cells that are under fire for some archer.
Input
The first and only line of input contains a single positive integer k — the archer's shot range (1 ≤ k ≤ 106).
Output
Print the single number, the number of cells that are under fire.
Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cout stream (also you may use the %I64d specificator).
Examples
Input
3
Output
7
Input
4
Output
13
Input
5
Output
19
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct pt {
double x;
double y;
};
int dcmp(double x) { return x < -1e-8 ? -1 : x > 1e-8; }
double dis(pt p) { return (p.x * p.x) + (p.y * p.y); }
int n, edge;
double d = sqrt(3);
pt p;
pt p0, p1, p2;
int main() {
int i, j, lf, rt, mid;
int a, b;
long long cnt = 0;
long long res;
while (scanf("%d", &n) != EOF) {
lf = 0;
rt = 50000000;
while (lf <= rt) {
mid = (lf + rt) / 2;
p = (pt){0.5 * (3 * mid + 1), 0.5 * d * (mid + 1)};
if (dcmp(dis(p) - (double)n * n) <= 0)
lf = mid + 1;
else
rt = mid - 1;
}
a = lf;
lf = 0;
rt = 50000000;
while (lf <= rt) {
mid = (lf + rt) / 2;
p = (pt){1 + 3.0 / 2 * mid, (mid % 2 == 0 ? 0 : d / 2)};
if (dcmp(dis(p) - (double)n * n) <= 0)
lf = mid + 1;
else
rt = mid - 1;
}
b = lf;
for (i = 0, res = 1; i < a; i++) res += (long long)i * 6;
for (i = a, cnt = 0; i < b; i++) {
lf = 0, rt = i / 2;
while (lf <= rt) {
mid = (lf + rt) / 2;
p0 = (pt){0.5 * (3 * i + 1), 0.5 * d * (i % 2 + 1 + 2 * mid)};
p1 = (pt){0.5 * (3 * i + 2), 0.5 * d * (i % 2 + 2 * mid)};
p2 = (pt){0.5 * (3 * i + 1), 0.5 * d * (i % 2 - 1 + 2 * mid)};
if (dcmp(dis(p0) - double(n) * n) <= 0 &&
dcmp(dis(p1) - double(n) * n) <= 0 &&
dcmp(dis(p2) - double(n) * n) <= 0)
lf = mid + 1;
else
rt = mid - 1;
}
cnt += 2 * lf;
if (i % 2 == 0) cnt--;
}
res += 6 * cnt;
cout << res << endl;
}
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i ⋅ a_j where a_1, ..., a_n is some sequence of positive integers.
Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, ..., a_n. Help Sasha restore the array!
Input
The first line contains a single integer n (3 ⩽ n ⩽ 10^3), the size of the table.
The next n lines contain n integers each. The j-th number of the i-th line contains the number M_{ij} (1 ≤ M_{ij} ≤ 10^9). The table has zeroes on the main diagonal, that is, M_{ii}=0.
Output
In a single line print n integers, the original array a_1, ..., a_n (1 ≤ a_i ≤ 10^9). It is guaranteed that an answer exists. If there are multiple answers, print any.
Examples
Input
5
0 4 6 2 4
4 0 6 2 4
6 6 0 3 6
2 2 3 0 2
4 4 6 2 0
Output
2 2 3 1 2
Input
3
0 99990000 99970002
99990000 0 99980000
99970002 99980000 0
Output
9999 10000 9998
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long int n;
cin >> n;
long long int arr[n][n];
for (long long int i = 0; i < n; i++) {
for (long long int j = 0; j < n; j++) {
cin >> arr[i][j];
}
}
long long int a = (arr[0][2] * arr[1][2]) / arr[0][1];
a = sqrt(a);
for (long long int i = 0; i < n; i++) {
if (i == 2)
cout << a << " ";
else
cout << (arr[i][2] / a) << " ";
}
return 0;
;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Just in case somebody missed it: this winter is totally cold in Nvodsk! It is so cold that one gets funny thoughts. For example, let's say there are strings with the length exactly n, based on the alphabet of size m. Any its substring with length equal to k is a palindrome. How many such strings exist? Your task is to find their quantity modulo 1000000007 (109 + 7). Be careful and don't miss a string or two!
Let us remind you that a string is a palindrome if it can be read the same way in either direction, from the left to the right and from the right to the left.
Input
The first and only line contains three integers: n, m and k (1 ≤ n, m, k ≤ 2000).
Output
Print a single integer — the number of strings of the described type modulo 1000000007 (109 + 7).
Examples
Input
1 1 1
Output
1
Input
5 2 4
Output
2
Note
In the first sample only one string is valid: "a" (let's denote the only letter of our alphabet as "a").
In the second sample (if we denote the alphabet letters as "a" and "b") the following strings are valid: "aaaaa" and "bbbbb".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int find(int v, vector<int> &p) {
if (p[v] < 0) return v;
while (true) {
if (p[v] == -1) return v;
v = p[v];
}
return 0;
}
long long mod = 1000000007;
long long power(long long m, long long e) {
long long ans = 1;
for (long long i = 0; i < e; i++) {
ans = ans * m;
ans = ans % mod;
}
return ans;
}
int main() {
int n, m, k;
cin >> n >> m >> k;
vector<pair<int, int>> v;
vector<int> p(n + 1, -1), v1, sz(n + 1, 1);
for (int i = 0; i < n - k + 1; i++) {
for (int j = 0; j < k / 2; j++) {
int x = i + j, y = i + k - 1 - j;
int x1 = find(x, p), y1 = find(y, p);
if (x1 != y1) {
if (sz[x1] < sz[y1]) {
swap(x, y);
}
p[y1] = x1;
sz[x1] = sz[x1] + sz[y1];
}
}
}
int e = 0;
for (int i = 0; i < n; i++) {
if (p[i] == -1) {
e++;
}
}
cout << power(m, e) << endl;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
You are given an array a with n elements. Each element of a is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 ≤ n ≤ 3·105, 0 ≤ k ≤ n) — the number of elements in a and the parameter k.
The second line contains n integers ai (0 ≤ ai ≤ 1) — the elements of a.
Output
On the first line print a non-negative integer z — the maximal value of f(a) after no more than k changes of zeroes to ones.
On the second line print n integers aj — the elements of the array a after the changes.
If there are multiple answers, you can print any one of them.
Examples
Input
7 1
1 0 0 1 1 0 1
Output
4
1 0 0 1 1 1 1
Input
10 2
1 0 0 1 0 1 0 1 0 1
Output
5
1 0 0 1 1 1 1 1 0 1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
cin >> n >> k;
vector<int> numbers(n);
for (int i = 0; i < n; ++i) {
cin >> numbers[i];
}
int l = 0;
int r = -1;
int count = 0;
while (count <= k && r < n) {
++r;
if (numbers[r] == 0) ++count;
}
pair<int, int> max_len = make_pair(l, r);
while (r < n && l < n) {
if (numbers[l] == 0) --count;
++l;
while (count <= k && r < n) {
++r;
if (r == n) continue;
if (numbers[r] == 0) ++count;
}
if (r - l > max_len.second - max_len.first) max_len = make_pair(l, r);
}
for (int i = max_len.first; i < max_len.second; ++i) {
numbers[i] = 1;
}
cout << max_len.second - max_len.first << endl;
for (int i = 0; i < n; ++i) {
cout << numbers[i] << " ";
}
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
During a voyage of the starship Hakodate-maru (see Problem A), researchers found strange synchronized movements of stars. Having heard these observations, Dr. Extreme proposed a theory of "super stars". Do not take this term as a description of actors or singers. It is a revolutionary theory in astronomy.
According to this theory, stars we are observing are not independent objects, but only small portions of larger objects called super stars. A super star is filled with invisible (or transparent) material, and only a number of points inside or on its surface shine. These points are observed as stars by us.
In order to verify this theory, Dr. Extreme wants to build motion equations of super stars and to compare the solutions of these equations with observed movements of stars. As the first step, he assumes that a super star is sphere-shaped, and has the smallest possible radius such that the sphere contains all given stars in or on it. This assumption makes it possible to estimate the volume of a super star, and thus its mass (the density of the invisible material is known).
You are asked to help Dr. Extreme by writing a program which, given the locations of a number of stars, finds the smallest sphere containing all of them in or on it. In this computation, you should ignore the sizes of stars. In other words, a star should be regarded as a point. You may assume the universe is a Euclidean space.
Input
The input consists of multiple data sets. Each data set is given in the following format.
n
x1 y1 z1
x2 y2 z2
...
xn yn zn
The first line of a data set contains an integer n, which is the number of points. It satisfies the condition 4 ≤ n ≤ 30.
The locations of n points are given by three-dimensional orthogonal coordinates: (xi, yi, zi) (i = 1,..., n). Three coordinates of a point appear in a line, separated by a space character.
Each value is given by a decimal fraction, and is between 0.0 and 100.0 (both ends inclusive). Points are at least 0.01 distant from each other.
The end of the input is indicated by a line containing a zero.
Output
For each data set, the radius ofthe smallest sphere containing all given points should be printed, each in a separate line. The printed values should have 5 digits after the decimal point. They may not have an error greater than 0.00001.
Example
Input
4
10.00000 10.00000 10.00000
20.00000 10.00000 10.00000
20.00000 20.00000 10.00000
10.00000 20.00000 10.00000
4
10.00000 10.00000 10.00000
10.00000 50.00000 50.00000
50.00000 10.00000 50.00000
50.00000 50.00000 10.00000
0
Output
7.07107
34.64102
### Response
```cpp
#include<iostream>
#include<valarray>
#include<cmath>
using namespace std;
double dist(valarray<double> a,valarray<double> b){
double s=0;
for(int i=0;i<3;i++){
s+=(a[i]-b[i])*(a[i]-b[i]);
}
return sqrt(s);
}
int main(){
for(int n;cin>>n,n;){
valarray<double> p[30];
for(int i=0;i<n;i++){
p[i].resize(3);
cin>>p[i][0]>>p[i][1]>>p[i][2];
}
valarray<double> c(50,3);
double w=1;
double ld;
for(int i=0;i<100000;i++,w*=.999){
double m=-1;
int x;
for(int j=0;j<n;j++){
auto d=dist(p[j],c);
if(d>m){
m=d;
x=j;
}
}
ld=m;
valarray<double> v=p[x]-c;
c+=v*w;
}
cout.precision(5);
cout<<fixed<<ld<<endl;
}
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store.
Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group.
Jzzhu wonders how to get the maximum possible number of groups. Can you help him?
Input
A single integer n (1 ≤ n ≤ 105), the number of the apples.
Output
The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group.
If there are several optimal answers you can print any of them.
Examples
Input
6
Output
2
6 3
2 4
Input
9
Output
3
9 3
2 4
6 8
Input
2
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 200002;
int n, used[N];
vector<int> ds[N], ans;
int gcd(int l, int r) { return !l ? r : gcd(r % l, l); }
int main() {
cin >> n;
for (int i = 2; i <= n; i++)
if (i % 2 && !used[i])
for (int j = i; j <= n; j += i) {
if (!used[j]) ds[i].push_back(j);
used[j] = 1;
}
for (int i = 2; i + i <= n; i++)
if (ds[i].size()) {
if (ds[i].size() % 2) {
used[ds[i][1]] = 0;
ds[i][1] = ds[i].back();
ds[i].pop_back();
}
while (ds[i].size()) {
ans.push_back(ds[i].back());
ds[i].pop_back();
}
}
for (int i = 2; i <= n; i += 2)
if (!used[i]) ds[2].push_back(i);
for (int i = 2; i <= ds[2].size(); i += 2) {
ans.push_back(ds[2][i - 1]);
ans.push_back(ds[2][i - 2]);
}
cout << ans.size() / 2 << endl;
while (ans.size()) {
cout << ans.back();
ans.pop_back();
cout << " " << ans.back() << endl;
ans.pop_back();
}
cin >> n;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
Input
The first line of input will be a single string s (1 ≤ |s| ≤ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'–'z').
Output
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
Examples
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
Note
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
string in;
set<string> s;
int main(int argc, char const *argv[]) {
while (cin >> in) {
int len = in.length();
for (int i = 0; i < len; i++) {
in += in[i];
}
for (int i = 0; i < len; i++) {
string tmp;
for (int j = 0; j < len; j++) {
tmp += in[i + j];
}
s.insert(tmp);
}
cout << s.size() << endl;
}
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
There are n parrots standing in a circle. Each parrot has a certain level of respect among other parrots, namely r_i. When a parrot with respect level x starts chattering, x neighbours to the right and to the left of it start repeating the same words in 1 second. Their neighbours then start repeating as well, and so on, until all the birds begin to chatter.
You are given the respect levels of all parrots. For each parrot answer a question: if this certain parrot starts chattering, how many seconds will pass until all other birds will start repeating it?
Input
In the first line of input there is a single integer n, the number of parrots (1 ≤ n ≤ 10^5).
In the next line of input there are n integers r_1, ..., r_n, the respect levels of parrots in order they stand in the circle (1 ≤ r_i ≤ n).
Output
Print n integers. i-th of them should equal the number of seconds that is needed for all parrots to start chattering if the i-th parrot is the first to start.
Examples
Input
4
1 1 4 1
Output
2 2 1 2
Input
8
1 2 2 1 5 1 3 1
Output
3 3 2 2 1 2 2 3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, a[100007 * 3];
pair<int, int> seg[17][100007 * 3], Seg[17][100007 * 12];
void Build(int i, int k, int l, int r) {
if (l == r) {
Seg[i][k] = seg[i][l];
return;
}
int mid = (l + r) >> 1;
Build(i, k * 2, l, mid);
Build(i, k * 2 + 1, mid + 1, r);
Seg[i][k].first = min(Seg[i][k * 2].first, Seg[i][k * 2 + 1].first);
Seg[i][k].second = max(Seg[i][k * 2].second, Seg[i][k * 2 + 1].second);
}
int fst, sec;
void Get(int i, int k, int l, int r, int L, int R) {
if (L <= l && r <= R) {
fst = min(fst, Seg[i][k].first);
sec = max(sec, Seg[i][k].second);
return;
}
int res = 1, mid = (l + r) >> 1;
if (L <= mid) Get(i, k * 2, l, mid, L, R);
if (R > mid) Get(i, k * 2 + 1, mid + 1, r, L, R);
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
a[n + i] = a[n * 2 + i] = a[i];
}
if (n == 1) {
puts("0");
return 0;
}
for (int i = 1; i <= n * 3; ++i) {
seg[0][i].first = max(i - a[i], 1);
seg[0][i].second = min(i + a[i], n * 3);
}
Build(0, 1, 1, n * 3);
for (int i = 1; i < 17; ++i) {
for (int j = 1; j <= n * 3; ++j) {
fst = seg[i - 1][j].first, sec = seg[i - 1][j].second;
Get(i - 1, 1, 1, n * 3, fst, sec);
seg[i][j].first = fst, seg[i][j].second = sec;
}
Build(i, 1, 1, n * 3);
}
for (int i = 1; i <= n; ++i) {
int ans = n, cur = 0, l = n + i, r = n + i;
for (int j = 16; j >= 0; --j) {
fst = l, sec = r;
Get(j, 1, 1, n * 3, l, r);
if (sec - fst + 1 >= n)
ans = min(ans, cur + (1 << j));
else
l = fst, r = sec, cur += 1 << j;
}
printf("%d%c", ans, " \n"[i == n]);
}
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Little beaver is a beginner programmer, so informatics is his favorite subject. Soon his informatics teacher is going to have a birthday and the beaver has decided to prepare a present for her. He planted n flowers in a row on his windowsill and started waiting for them to grow. However, after some time the beaver noticed that the flowers stopped growing. The beaver thinks it is bad manners to present little flowers. So he decided to come up with some solutions.
There are m days left to the birthday. The height of the i-th flower (assume that the flowers in the row are numbered from 1 to n from left to right) is equal to ai at the moment. At each of the remaining m days the beaver can take a special watering and water w contiguous flowers (he can do that only once at a day). At that each watered flower grows by one height unit on that day. The beaver wants the height of the smallest flower be as large as possible in the end. What maximum height of the smallest flower can he get?
Input
The first line contains space-separated integers n, m and w (1 ≤ w ≤ n ≤ 105; 1 ≤ m ≤ 105). The second line contains space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Output
Print a single integer — the maximum final height of the smallest flower.
Examples
Input
6 2 3
2 2 2 2 1 1
Output
2
Input
2 5 1
5 8
Output
9
Note
In the first sample beaver can water the last 3 flowers at the first day. On the next day he may not to water flowers at all. In the end he will get the following heights: [2, 2, 2, 3, 2, 2]. The smallest flower has height equal to 2. It's impossible to get height 3 in this test.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m, w, i, step, Max;
int a[100000 + 5], sum[100000 + 5];
bool ok(int l) {
int crt, m2;
m2 = m;
for (int j = 1; j <= n; ++j) sum[j] = 0;
for (int j = 1; j <= n; ++j) {
sum[j] += sum[j - 1];
if (sum[j] + a[j] >= l) continue;
crt = sum[j] + a[j];
if (l - crt > m2) return false;
m2 -= (l - crt);
sum[j] += (l - crt);
sum[min(n + 1, j + w)] -= (l - crt);
}
return true;
}
int main() {
scanf("%d%d%d", &n, &m, &w);
for (i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
Max = max(Max, a[i] + m);
}
for (step = 1; step < Max; step <<= 1)
;
for (i = 0; step; step >>= 1)
if (i + step <= Max)
if (ok(i + step)) i += step;
printf("%d\n", i);
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
"Search" is an operation to obtain the desired information from a large amount of information. Familiar examples include "finding your own exam number from a large number of exam numbers" when announcing your success, or "finding Taro Aizu's phone number" from your phone book. This search operation is also widely used in the computer field.
<image>
There are many ways to search. Consider a search method that can be used when the data to be searched is arranged in ascending (or largest) order.
Using the magnitude relationship between the value located in the center of the data string arranged in ascending order (or in descending order) and the target value, the first half is set as the search range or the second half is searched from the value located in the center. There is a way to narrow down the search range by deciding whether to make it a range. The procedure is as follows.
1. The entire column of data is the scope of the search.
2. Examine the value located in the center of the search range.
3. If the desired value matches the centered value, the search ends.
4. If it is smaller than the target value and the value located in the center, the first half is the search range, and if it is larger, the second half is the search range and returns to 2.
The following is an example of the search method described above. The desired value in this example is 51. Each piece of data is numbered (index), which starts at 0.
Step 1: Initially, the search range is the entire number 0-6.
Step 2: Find the value in the center of the search range. However, the "centered value" is the value at the position of the number obtained by dividing (the number on the left side + the number on the right side) by 2. In other words, in this case, (0 + 6) ÷ 2 is calculated, and the value (36) at number 3 is the value located in the center.
Step 3: Compare the desired value (51) with the centrally located value (36).
Step 4: From the result of step 3, the target value is larger than the value located in the center, so the search range is from number 4 (next to the value located in the center) in the latter half. Use the same procedure to check the value located in the center of the search range, and if the target value is smaller than the value located in the center, the first half is the search range, and if it is larger, the second half is the search range. I will make it smaller. (Repeat of steps 2 to 4) The search ends when the target value matches the value located in the center or the search range is reached.
| <image>
--- | ---
Create a program that takes an array of n numbers as input and outputs the number of times the target value is compared with the value located in the center. However, if the number of the value located in the center is not divisible, the value rounded down to the nearest whole number will be used as the number. It is assumed that the given data columns are sorted in ascending order.
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
k
The number of numbers n (1 ≤ n ≤ 100) is given on the first line, and the i-th number ai (1 ≤ ai ≤ 100000, integer) is given on the following n lines.
The following line is given the value k (1 ≤ k ≤ 100000) to search for.
Output
The number of comparisons until the search is completed for each data set is output on one line.
Example
Input
7
11
15
23
36
51
61
86
51
4
1
2
3
5
4
0
Output
3
3
### Response
```cpp
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
int n,s;
int a[101];
while(cin >> n){
if(n == 0)break;
for(int i = 0; i < n; i++) cin >> a[i];
cin >> s;
int left = 0,right = n-1;
int cnt = 0;
while(1){
if(left > right)break;
int mid = (left + right) / 2;
cnt++;
if(a[mid] == s){
break;
}
else if(a[mid] < s){
left = mid + 1;
}
else
right = mid - 1;
}
printf("%d\n",cnt);
}
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
Nikolay has a lemons, b apples and c pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1: 2: 4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, apples and pears — should be put in the compote as whole fruits.
Your task is to determine the maximum total number of lemons, apples and pears from which Nikolay can cook the compote. It is possible that Nikolay can't use any fruits, in this case print 0.
Input
The first line contains the positive integer a (1 ≤ a ≤ 1000) — the number of lemons Nikolay has.
The second line contains the positive integer b (1 ≤ b ≤ 1000) — the number of apples Nikolay has.
The third line contains the positive integer c (1 ≤ c ≤ 1000) — the number of pears Nikolay has.
Output
Print the maximum total number of lemons, apples and pears from which Nikolay can cook the compote.
Examples
Input
2
5
7
Output
7
Input
4
7
13
Output
21
Input
2
3
2
Output
0
Note
In the first example Nikolay can use 1 lemon, 2 apples and 4 pears, so the answer is 1 + 2 + 4 = 7.
In the second example Nikolay can use 3 lemons, 6 apples and 12 pears, so the answer is 3 + 6 + 12 = 21.
In the third example Nikolay don't have enough pears to cook any compote, so the answer is 0.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long MAX = 500 + 100, INF = 1e9;
bool vis[MAX];
vector<int> adj[MAX];
int main() {
int a, b, c, x = 0;
cin >> a >> b >> c;
for (int i = 1;; i++) {
if (a >= i && (b >= 2 * i && c >= 4 * i))
x = i;
else
break;
}
cout << 7 * x;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
You are given a permutation p. Calculate the total number of inversions in all permutations that lexicographically do not exceed the given one.
As this number can be very large, print it modulo 1000000007 (109 + 7).
Input
The first line contains a single integer n (1 ≤ n ≤ 106) — the length of the permutation. The second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n).
Output
Print a single number — the answer to the problem modulo 1000000007 (109 + 7).
Examples
Input
2
2 1
Output
1
Input
3
2 1 3
Output
2
Note
Permutation p of length n is the sequence that consists of n distinct integers, each of them is from 1 to n.
An inversion of permutation p1, p2, ..., pn is a pair of indexes (i, j), such that i < j and pi > pj.
Permutation a do not exceed permutation b lexicographically, if either a = b or there exists such number i, for which the following logical condition fulfills: <image> AND (ai < bi).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 20;
const long long mod = 1e9 + 7;
struct node {
int lazy, t;
long long sum;
node() { lazy = t = sum = 0; }
};
node seg[maxn * 4];
int a[maxn];
long long fac[maxn];
node merge(node a, node b) {
node c;
c.sum = a.sum + b.sum;
c.t = a.t + b.t;
return c;
}
void build(int s, int e, int v) {
if (e - s < 2) {
seg[v].sum = s;
return;
}
int m = (s + e) / 2;
build(s, m, 2 * v);
build(m, e, 2 * v + 1);
seg[v] = merge(seg[2 * v], seg[2 * v + 1]);
}
void rem(int p, int s, int e, int v) {
if (e - s < 2) {
seg[v].sum = 0;
seg[v].t = 1;
return;
}
int m = (s + e) / 2;
if (p < m)
rem(p, s, m, 2 * v);
else
rem(p, m, e, 2 * v + 1);
seg[v] = merge(seg[2 * v], seg[2 * v + 1]);
}
void ok(long long s, long long e, int v, long long val) {
seg[v].sum += (e - s - seg[v].t) * val;
seg[v].lazy += val;
}
void shift(int s, int e, int v) {
if (e - s >= 2 && seg[v].lazy != 0) {
int m = (s + e) / 2;
ok(s, m, 2 * v, seg[v].lazy);
ok(m, e, 2 * v + 1, seg[v].lazy);
}
seg[v].lazy = 0;
}
void add(int l, int r, int val, int s, int e, int v) {
if (l <= s && e <= r) {
ok(s, e, v, val);
return;
}
if (r <= s || e <= l) return;
shift(s, e, v);
int m = (s + e) / 2;
add(l, r, val, s, m, 2 * v);
add(l, r, val, m, e, 2 * v + 1);
seg[v] = merge(seg[2 * v], seg[2 * v + 1]);
}
long long get(int l, int r, int s, int e, int v) {
if (l <= s && e <= r) return seg[v].sum % mod;
if (r <= s || e <= l) return 0;
shift(s, e, v);
int m = (s + e) / 2;
return (get(l, r, s, m, 2 * v) + get(l, r, m, e, 2 * v + 1)) % mod;
}
int get_r(int l, int r, int s, int e, int v) {
if (l <= s && e <= r) return seg[v].t;
if (r <= s || e <= l) return 0;
int m = (s + e) / 2;
return get_r(l, r, s, m, 2 * v) + get_r(l, r, m, e, 2 * v + 1);
}
long long f(long long x) { return (x * (x - 1) / 2) % mod; }
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
fac[2] = 1;
for (long long i = 3; i < maxn; i++) fac[i] = (fac[i - 1] * i) % mod;
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i], a[i]--;
build(0, n, 1);
long long res = 0, tmp = 0;
for (int i = 0; i < n; i++) {
long long k = a[i] - get_r(0, a[i], 0, n, 1);
long long w = ((n - i - 1 < 2) ? 1 : fac[n - i - 1] * 2) % mod;
res += (((fac[n - i - 1] * f(n - i - 1)) % mod) * k) % mod;
res += (w * get(0, a[i], 0, n, 1)) % mod;
res += (((tmp * w) % mod) * k) % mod;
res %= mod;
tmp += get(a[i], a[i] + 1, 0, n, 1);
rem(a[i], 0, n, 1);
tmp %= mod;
add(a[i], n, -1, 0, n, 1);
}
res += tmp;
cout << res % mod << endl;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Iroha loves Haiku. Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order.
To create a Haiku, Iroha has come up with three different phrases. These phrases have A, B and C syllables, respectively. Determine whether she can construct a Haiku by using each of the phrases once, in some order.
Constraints
* 1≦A,B,C≦10
Input
The input is given from Standard Input in the following format:
A B C
Output
If it is possible to construct a Haiku by using each of the phrases once, print `YES` (case-sensitive). Otherwise, print `NO`.
Examples
Input
5 5 7
Output
YES
Input
7 7 5
Output
NO
### Response
```cpp
#include <iostream>
using namespace std;
int main(){
int a,b,c;
cin>>a>>b>>c;
if(a+b+c==17&&(a==5||b==5||c==5)&&(a==7||b==7||c==7))cout<<"YES"<<endl;
else cout<<"NO"<<endl;
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.
A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
Input
The first line contains single positive integer n (1 ≤ n ≤ 105) — the number of integers.
The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Output
Print the maximum length of an increasing subarray of the given array.
Examples
Input
5
1 7 2 11 15
Output
3
Input
6
100 100 100 100 100 100
Output
1
Input
3
1 2 3
Output
3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const double eps = 1e-9;
int a[100009] = {0};
int main() {
int i, j, k;
int n;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
int ans = 0;
int pre = 1;
int c = 0;
for (i = 0; i < n; i++) {
if (a[i] > pre) {
c++;
pre = a[i];
} else {
ans = max(ans, c);
c = 1;
pre = a[i];
}
}
ans = max(ans, c);
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Peter is a person with erratic sleep habits. He goes to sleep at twelve o'lock every midnight. He gets up just after one hour of sleep on some days; he may even sleep for twenty-three hours on other days. His sleeping duration changes in a cycle, where he always sleeps for only one hour on the first day of the cycle.
Unfortunately, he has some job interviews this month. No doubt he wants to be in time for them. He can take anhydrous caffeine to reset his sleeping cycle to the beginning of the cycle anytime. Then he will wake up after one hour of sleep when he takes caffeine. But of course he wants to avoid taking caffeine as possible, since it may affect his health and accordingly his very important job interviews.
Your task is to write a program that reports the minimum amount of caffeine required for Peter to attend all his interviews without being late, where the information about the cycle and the schedule of his interviews are given. The time for move to the place of each interview should be considered negligible.
Input
The input consists of multiple datasets. Each dataset is given in the following format:
T
t1 t2 ... tT
N
D1 M1
D2 M2
...
DN MN
T is the length of the cycle (1 ≤ T ≤ 30); ti (for 1 ≤ i ≤ T ) is the amount of sleep on the i-th day of the cycle, given in hours (1 ≤ ti ≤ 23); N is the number of interviews (1 ≤ N ≤ 100); Dj (for 1 ≤ j ≤ N) is the day of the j-th interview (1 ≤ Dj ≤ 100); Mj (for 1 ≤ j ≤ N) is the hour when the j-th interview starts (1 ≤ Mj ≤ 23).
The numbers in the input are all integers. t1 is always 1 as stated above. The day indicated by 1 is the first day in the cycle of Peter's sleep.
The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed.
Output
For each dataset, print the minimum number of times Peter needs to take anhydrous caffeine.
Example
Input
2
1 23
3
1 1
2 1
3 1
0
Output
2
### Response
```cpp
#include <iostream>
#include <algorithm>
using namespace std;
static const int INF = (1<<20);
int T, t[30], N, D, M, dp[101][30], m[101];
int main(){
while(cin >> T && T){
for(int i=0;i<T;i++) cin >> t[i];
cin >> N;
fill(m, m+101, INF);
for(int i=0;i<N;i++){
cin >> D >> M;
m[D-1] = min(m[D-1], M);
}
fill(dp[0], dp[101], INF);
dp[0][0] = 0;
for(int i=0;i<100;i++){
for(int j=0;j<T;j++){
if(t[j] <= m[i]){
dp[i+1][(j+1)%T] = min(dp[i+1][(j+1)%T], dp[i][j]);
dp[i+1][0] = min(dp[i+1][0], dp[i][j]+1);
}
}
}
int ans = INF;
for(int i=0;i<T;i++) ans = min(ans, dp[100][i]);
cout << ans << endl;
}
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Write a program which reads an integer n and identifies the number of combinations of a, b, c and d (0 ≤ a, b, c, d ≤ 9) which meet the following equality:
a + b + c + d = n
For example, for n = 35, we have 4 different combinations of (a, b, c, d): (8, 9, 9, 9), (9, 8, 9, 9), (9, 9, 8, 9), and (9, 9, 9, 8).
Input
The input consists of several datasets. Each dataset consists of n (1 ≤ n ≤ 50) in a line. The number of datasets is less than or equal to 50.
Output
Print the number of combination in a line.
Example
Input
35
1
Output
4
4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int res;
int n;
void dfs(int u, int all)
{
if(u == 4)
{
if(all == n) res ++;
return;
}
for(int i = 0; i < 10; i ++ )
dfs(u + 1, all + i);
}
int main()
{
while(cin >> n)
{
res = 0;
dfs(0, 0);
cout << res << endl;
}
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Yaroslav has an array p = p1, p2, ..., pn (1 ≤ pi ≤ n), consisting of n distinct integers. Also, he has m queries:
* Query number i is represented as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).
* The answer to the query li, ri is the number of pairs of integers q, w (li ≤ q, w ≤ ri) such that pq is the divisor of pw.
Help Yaroslav, answer all his queries.
Input
The first line contains the integers n and m (1 ≤ n, m ≤ 2·105). The second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n). The following m lines contain Yaroslav's queries. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n).
Output
Print m integers — the answers to Yaroslav's queries in the order they appear in the input.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
1 1
1
1 1
Output
1
Input
10 9
1 2 3 4 5 6 7 8 9 10
1 10
2 9
3 8
4 7
5 6
2 2
9 10
5 10
4 10
Output
27
14
8
4
2
1
2
7
9
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int SIZE = 2e5 + 5;
int tree[SIZE], n, m, N, p[SIZE], indx[SIZE], res[SIZE];
pair<int, int> divP[18 * SIZE];
struct data {
int u, v, p;
} queries[SIZE];
bool compare(const pair<int, int> &a, const pair<int, int> &b) {
return a.second < b.second;
}
bool compareD(const data &a, const data &b) { return a.v < b.v; }
void Input() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> p[i];
indx[p[i]] = i;
}
for (int i = 1; i <= m; i++) {
int x, y;
cin >> x >> y;
queries[i] = {x, y, i};
}
}
void make_Div_pair() {
for (int i = 1; i <= n; i++) {
for (int pj = p[i]; pj <= n; pj += p[i]) {
int j = indx[pj];
divP[++N] = (i < j) ? make_pair(i, j) : make_pair(j, i);
}
}
}
int sum(int u) {
int temp = 0;
for (; u > 0; u -= (u & -u)) temp += tree[u];
return temp;
}
int get_sum(int u, int v) { return sum(v) - sum(u - 1); }
void update(int u, int val) {
for (; u <= n; u += (u & -u)) tree[u] += val;
}
void Solve() {
make_Div_pair();
sort(divP + 1, divP + N + 1, compare);
sort(queries + 1, queries + m + 1, compareD);
int now = 1;
for (int i = 1; i <= m; i++) {
int u = queries[i].u;
int v = queries[i].v;
int p = queries[i].p;
while (now <= N && divP[now].second <= v) {
update(divP[now].first, 1);
now++;
}
res[p] = get_sum(u, v);
}
}
void Print() {
for (int i = 1; i <= m; i++) cout << res[i] << '\n';
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
Input();
Solve();
Print();
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0, 1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.
The stones always fall to the center of Liss's interval. When Liss occupies the interval [k - d, k + d] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [k - d, k]. If she escapes to the right, her new interval will be [k, k + d].
You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls.
Input
The input consists of only one line. The only line contains the string s (1 ≤ |s| ≤ 106). Each character in s will be either "l" or "r".
Output
Output n lines — on the i-th line you should print the i-th stone's number from the left.
Examples
Input
llrlr
Output
3
5
4
2
1
Input
rrlll
Output
1
2
5
4
3
Input
lrlrr
Output
2
4
5
3
1
Note
In the first example, the positions of stones 1, 2, 3, 4, 5 will be <image>, respectively. So you should print the sequence: 3, 5, 4, 2, 1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[1000001];
int main() {
int i, l;
string s;
cin >> s;
l = s.size();
int rt = l - 1, lt = 0, st = 1;
for (i = 0; i < l; i++) {
if (s[i] == 'r') {
a[lt] = st;
st++;
lt++;
} else {
a[rt] = st;
st++;
rt--;
}
}
for (i = 0; i < l; i++) printf("%d\n", a[i]);
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
For integers b (b \geq 2) and n (n \geq 1), let the function f(b,n) be defined as follows:
* f(b,n) = n, when n < b
* f(b,n) = f(b,\,{\rm floor}(n / b)) + (n \ {\rm mod} \ b), when n \geq b
Here, {\rm floor}(n / b) denotes the largest integer not exceeding n / b, and n \ {\rm mod} \ b denotes the remainder of n divided by b.
Less formally, f(b,n) is equal to the sum of the digits of n written in base b. For example, the following hold:
* f(10,\,87654)=8+7+6+5+4=30
* f(100,\,87654)=8+76+54=138
You are given integers n and s. Determine if there exists an integer b (b \geq 2) such that f(b,n)=s. If the answer is positive, also find the smallest such b.
Constraints
* 1 \leq n \leq 10^{11}
* 1 \leq s \leq 10^{11}
* n,\,s are integers.
Input
The input is given from Standard Input in the following format:
n
s
Output
If there exists an integer b (b \geq 2) such that f(b,n)=s, print the smallest such b. If such b does not exist, print `-1` instead.
Examples
Input
87654
30
Output
10
Input
87654
138
Output
100
Input
87654
45678
Output
-1
Input
31415926535
1
Output
31415926535
Input
1
31415926535
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define ll long long
ll n,s;
ll f( ll b,ll n)
{
return n<b?n:f(b,n/b)+n%b;
}
int main()
{
scanf("%lld%lld",&n,&s);
if(s>n)return puts("-1"),0;
if(s==n)return printf("%lld\n",n+1),0;
ll m=sqrt(n)+1;
for(ll i=2; i<=m; ++i)
if(f(i,n)==s)return printf( "%lld",i),0;
ll ans=1e11;
n-=s;
for( ll i=1; i*i<=n; ++i)
if(n%i==0)
{
ll b=n/i+1;
if(f(b,n+s)==s)ans=min(ans,b);
}
return printf("%lld\n",ans!=1e11?ans:-1),0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Takahashi has many red balls and blue balls. Now, he will place them in a row.
Initially, there is no ball placed.
Takahashi, who is very patient, will do the following operation 10^{100} times:
* Place A blue balls at the end of the row of balls already placed. Then, place B red balls at the end of the row.
How many blue balls will be there among the first N balls in the row of balls made this way?
Constraints
* 1 \leq N \leq 10^{18}
* A, B \geq 0
* 0 < A + B \leq 10^{18}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
Print the number of blue balls that will be there among the first N balls in the row of balls.
Examples
Input
8 3 4
Output
4
Input
8 0 4
Output
0
Input
6 2 4
Output
2
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main()
{
long long n,a,b;
cin>>n>>a>>b;
long long ans=n/(a+b)*a+(n%(a+b)>a?a:(n%(a+b)));
cout<<ans;
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of n small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to learn those letters. That's why he decided to lose some part of the string (not necessarily a connected part). The lost part can consist of any number of segments of any length, at any distance from each other. However, Gerald knows that if he loses more than k characters, it will be very suspicious.
Find the least number of distinct characters that can remain in the string after no more than k characters are deleted. You also have to find any possible way to delete the characters.
Input
The first input data line contains a string whose length is equal to n (1 ≤ n ≤ 105). The string consists of lowercase Latin letters. The second line contains the number k (0 ≤ k ≤ 105).
Output
Print on the first line the only number m — the least possible number of different characters that could remain in the given string after it loses no more than k characters.
Print on the second line the string that Gerald can get after some characters are lost. The string should have exactly m distinct characters. The final string should be the subsequence of the initial string. If Gerald can get several different strings with exactly m distinct characters, print any of them.
Examples
Input
aaaaa
4
Output
1
aaaaa
Input
abacaba
4
Output
1
aaaa
Input
abcdefgh
10
Output
0
Note
In the first sample the string consists of five identical letters but you are only allowed to delete 4 of them so that there was at least one letter left. Thus, the right answer is 1 and any string consisting of characters "a" from 1 to 5 in length.
In the second sample you are allowed to delete 4 characters. You cannot delete all the characters, because the string has length equal to 7. However, you can delete all characters apart from "a" (as they are no more than four), which will result in the "aaaa" string.
In the third sample you are given a line whose length is equal to 8, and k = 10, so that the whole line can be deleted. The correct answer is 0 and an empty string.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[500];
bool mark[1000];
int main() {
string s;
cin >> s;
int n = s.length();
int k;
cin >> k;
int ans = 0;
int MAX = 0;
for (int i = 0; i < n; i++) {
if (a[s[i]] == 0) ans++;
a[s[i]]++;
if (a[s[i]] > a[MAX]) MAX = s[i];
}
for (int i = 0; i < n; i++) {
int minin = MAX;
for (int j = 0; j < n; j++) {
if (a[s[j]] < a[minin] && a[s[j]] > 0) minin = s[j];
}
if (k >= a[minin]) {
mark[minin] = true;
k -= a[minin];
ans--;
a[minin] = 10000000;
} else
break;
}
cout << ans << endl;
for (int i = 0; i < n; i++)
if (!mark[s[i]]) cout << s[i];
cout << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
The only difference between easy and hard versions is constraints.
There are n kids, each of them is reading a unique book. At the end of any day, the i-th kid will give his book to the p_i-th kid (in case of i = p_i the kid will give his book to himself). It is guaranteed that all values of p_i are distinct integers from 1 to n (i.e. p is a permutation). The sequence p doesn't change from day to day, it is fixed.
For example, if n=6 and p=[4, 6, 1, 3, 5, 2] then at the end of the first day the book of the 1-st kid will belong to the 4-th kid, the 2-nd kid will belong to the 6-th kid and so on. At the end of the second day the book of the 1-st kid will belong to the 3-th kid, the 2-nd kid will belong to the 2-th kid and so on.
Your task is to determine the number of the day the book of the i-th child is returned back to him for the first time for every i from 1 to n.
Consider the following example: p = [5, 1, 2, 4, 3]. The book of the 1-st kid will be passed to the following kids:
* after the 1-st day it will belong to the 5-th kid,
* after the 2-nd day it will belong to the 3-rd kid,
* after the 3-rd day it will belong to the 2-nd kid,
* after the 4-th day it will belong to the 1-st kid.
So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 1000) — the number of queries. Then q queries follow.
The first line of the query contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of kids in the query. The second line of the query contains n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i are distinct, i.e. p is a permutation), where p_i is the kid which will get the book of the i-th kid.
It is guaranteed that ∑ n ≤ 2 ⋅ 10^5 (sum of n over all queries does not exceed 2 ⋅ 10^5).
Output
For each query, print the answer on it: n integers a_1, a_2, ..., a_n, where a_i is the number of the day the book of the i-th child is returned back to him for the first time in this query.
Example
Input
6
5
1 2 3 4 5
3
2 3 1
6
4 6 2 1 5 3
1
1
4
3 4 1 2
5
5 1 2 4 3
Output
1 1 1 1 1
3 3 3
2 3 3 2 1 3
1
2 2 2 2
4 4 4 1 4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
constexpr ll INF = 1LL << 60;
constexpr int MOD = 998244353;
struct UnionFind {
vector<int> par, weight;
UnionFind(int n) : par(n, -1), weight(n) {}
void unite(int x, int y, int w = 0) {
x = find(x);
y = find(y);
if (x == y) return;
if (par[x] > par[y]) swap(x, y), w = -w;
par[x] += par[y];
par[y] = x;
return;
}
bool same(int x, int y) { return find(x) == find(y); }
int find(int x) {
if (par[x] < 0) return x;
int r = find(par[x]);
return par[x] = r;
}
int sizeOf(int x) { return -par[find(x)]; }
};
int q, n, a[200020], b[200020];
int main() {
cin.tie(0);
ios_base::sync_with_stdio(false);
cin >> q;
while (q--) {
cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[i];
UnionFind uf(n + 1);
for (int i = 1; i <= n; ++i) uf.unite(i, a[i]);
for (int i = 1; i <= n; ++i) cout << uf.sizeOf(i) << " \n"[n == i];
}
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Polycarp has 26 tasks. Each task is designated by a capital letter of the Latin alphabet.
The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot return to the previous task.
Polycarp can only solve one task during the day. Every day he wrote down what task he solved. Now the teacher wants to know if Polycarp followed his advice.
For example, if Polycarp solved tasks in the following order: "DDBBCCCBBEZ", then the teacher will see that on the third day Polycarp began to solve the task 'B', then on the fifth day he got distracted and began to solve the task 'C', on the eighth day Polycarp returned to the task 'B'. Other examples of when the teacher is suspicious: "BAB", "AABBCCDDEEBZZ" and "AAAAZAAAAA".
If Polycarp solved the tasks as follows: "FFGZZZY", then the teacher cannot have any suspicions. Please note that Polycarp is not obligated to solve all tasks. Other examples of when the teacher doesn't have any suspicious: "BA", "AFFFCC" and "YYYYY".
Help Polycarp find out if his teacher might be suspicious.
Input
The first line contains an integer t (1 ≤ t ≤ 1000). Then t test cases follow.
The first line of each test case contains one integer n (1 ≤ n ≤ 50) — the number of days during which Polycarp solved tasks.
The second line contains a string of length n, consisting of uppercase Latin letters, which is the order in which Polycarp solved the tasks.
Output
For each test case output:
* "YES", if the teacher cannot be suspicious;
* "NO", otherwise.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
3
ABA
11
DDBBCCCBBEZ
7
FFGZZZY
1
Z
2
AB
Output
NO
NO
YES
YES
YES
### Response
```cpp
#pragma GCC optimize("Ofast","unroll-loops","omit-frame-pointer","inline")
#pragma GCC option("arch=native","tune=native","no-zero-upper")
#pragma GCC target("avx2")
#include <bits/stdc++.h>
using namespace std;
#define INF 2147483647
#define infL (1LL<<60)
#define inf (1<<30)
#define inf9 (1000000000)
#define MOD 998244353//1000000007
#define EPS 1e-9
#define Gr 9.8
#define PI acos(-1)
#define REP(i,n) for(int (i)=0;(i)<(int)(n);(i)++)
#define REQ(i,n) for(int (i)=1;(i)<=(int)(n);(i)++)
#define lch (rt<<1)
#define rch (rt<<1|1)
#define readmp(n) for(int i=0,u,v;i<n;i++) {scanf("%d%d",&u,&v); mp[u].push_back(v); mp[v].push_back(u);}
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef long double ld;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef ll ValType;
template<typename T> void maxtt(T& t1, T t2) {
t1=max(t1,t2);
}
template<typename T> void mintt(T& t1, T t2) {
t1=min(t1,t2);
}
#define MAX (135)
bool debug = 0;
int n,m,k;
int dx[4] = {0,1,0,-1}, dy[4] = {1,0,-1,0};
string direc="RDLU";
const ll MOD2 = (ll)MOD * (ll)MOD;
ll ln, lk, lm;
void etp(bool f = 0) {
puts(f ?"YES" : "NO");
exit(0);
}
void addmod(int &x, int y, int mod = MOD){
x+=y; if (x>=mod) x-=mod;
if(x<0) x+=mod;
assert(x>=0 && x<mod);
}
void et(int x=-1) {
printf("%d\n", x); exit(0);
}
ll fastPow(ll x, ll y, int mod=MOD) {
ll ans = 1;
while(y>0) {
if(y&1) ans = (x * ans)%mod;
x = x*x%mod;
y>>=1;
}
return ans;
}
ll gcd1(ll x, ll y) {
return y?gcd1(y,x%y):x;
}
//#include <atcoder/all>
//using mint = atcoder::modint1000000007;
char s[MAX];
void fmain(int tid) {
scanf("%d", &n);
scanf("%s", s+1);
vector<char> vp;
REQ(i,n) {
if(vp.empty() || vp.back()!=s[i]) {
vp.push_back(s[i]);
}
}
sort(vp.begin(), vp.end());
int N=unique(vp.begin(),vp.end())-vp.begin();
if(N==vp.size()) {
puts("YES");
} else puts("NO");
}
int main() {
// freopen("smallrand2.in","r",stdin);
// freopen("output.txt","w",stdout);
int t=1;
// init();
scanf("%d", &t);
REQ(i,t) {
fmain(i);
}
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
The Super Duper Secret Meeting of the Super Duper Secret Military Squad takes place in a Super Duper Secret Place. The place is an infinite plane with introduced Cartesian coordinate system. The meeting table is represented as a rectangle whose sides are parallel to the coordinate axes and whose vertexes are located at the integer points of the plane. At each integer point which belongs to the table perimeter there is a chair in which a general sits.
Some points on the plane contain radiators for the generals not to freeze in winter. Each radiator is characterized by the number ri — the radius of the area this radiator can heat. That is, if the distance between some general and the given radiator is less than or equal to ri, than the general feels comfortable and warm. Here distance is defined as Euclidean distance, so the distance between points (x1, y1) and (x2, y2) is <image>
Each general who is located outside the radiators' heating area can get sick. Thus, you should bring him a warm blanket. Your task is to count the number of warm blankets you should bring to the Super Duper Secret Place.
The generals who are already comfortable do not need a blanket. Also the generals never overheat, ever if they are located in the heating area of several radiators. The radiators can be located at any integer points on the plane, even inside the rectangle (under the table) or on the perimeter (directly under some general). Even in this case their radius does not change.
Input
The first input line contains coordinates of two opposite table corners xa, ya, xb, yb (xa ≠ xb, ya ≠ yb). The second line contains integer n — the number of radiators (1 ≤ n ≤ 103). Then n lines contain the heaters' coordinates as "xi yi ri", the numbers are separated by spaces. All input data numbers are integers. The absolute value of all coordinates does not exceed 1000, 1 ≤ ri ≤ 1000. Several radiators can be located at the same point.
Output
Print the only number — the number of blankets you should bring.
Examples
Input
2 5 4 2
3
3 1 2
5 3 1
1 3 2
Output
4
Input
5 2 6 3
2
6 2 2
6 5 3
Output
0
Note
In the first sample the generals are sitting at points: (2, 2), (2, 3), (2, 4), (2, 5), (3, 2), (3, 5), (4, 2), (4, 3), (4, 4), (4, 5). Among them, 4 generals are located outside the heating range. They are the generals at points: (2, 5), (3, 5), (4, 4), (4, 5).
In the second sample the generals are sitting at points: (5, 2), (5, 3), (6, 2), (6, 3). All of them are located inside the heating range.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1000 + 1;
struct Point {
int x, y;
double r;
} P[MAXN];
int xa, ya, xb, yb;
int n;
bool DIS(int x, int y) {
for (int i = 0; i < n; i++) {
double dis =
((x - P[i].x) * (x - P[i].x) + (y - P[i].y) * (y - P[i].y)) * 1.0;
if (dis <= P[i].r * P[i].r) return false;
}
return true;
}
bool run() {
if (scanf("%d%d%d%d", &xa, &ya, &xb, &yb) == EOF) return false;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d%d%lf", &P[i].x, &P[i].y, &P[i].r);
}
int ans = 0;
int MinX = min(xa, xb);
int MaxX = max(xa, xb);
int MinY = min(ya, yb);
int MaxY = max(ya, yb);
for (int i = MinX; i <= MaxX; i++) {
if (DIS(i, MinY)) ans++;
}
for (int i = MinX; i <= MaxX; i++) {
if (DIS(i, MaxY)) ans++;
}
for (int i = MinY + 1; i < MaxY; i++) {
if (DIS(MinX, i)) ans++;
}
for (int i = MinY + 1; i < MaxY; i++) {
if (DIS(MaxX, i)) ans++;
}
printf("%d\n", ans);
return true;
}
int main() {
while (run())
;
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Let N be a positive odd number.
There are N coins, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), when Coin i is tossed, it comes up heads with probability p_i and tails with probability 1 - p_i.
Taro has tossed all the N coins. Find the probability of having more heads than tails.
Constraints
* N is an odd number.
* 1 \leq N \leq 2999
* p_i is a real number and has two decimal places.
* 0 < p_i < 1
Input
Input is given from Standard Input in the following format:
N
p_1 p_2 \ldots p_N
Output
Print the probability of having more heads than tails. The output is considered correct when the absolute error is not greater than 10^{-9}.
Examples
Input
3
0.30 0.60 0.80
Output
0.612
Input
1
0.50
Output
0.5
Input
5
0.42 0.01 0.42 0.99 0.42
Output
0.3821815872
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(void){
int n;
cin>>n;
double *DP=new double[n+1];
DP[0]=1;
for(int i=1;i<=n;i++) DP[i]=0;
for(int i=0;i<n;i++){
double p;
cin>>p;
for(int j=i+1;j>0;j--){
DP[j]=DP[j]*(1-p)+DP[j-1]*p;
}
DP[0]*=(1-p);
}
double ans=0;
for(int i=n;i>n/2;i--){
ans+=DP[i];
}
printf("%.10f\n",ans);
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any city you can get to any other one by moving along the roads.
You want to destroy the largest possible number of roads in the country so that the remaining roads would allow you to get from city s1 to city t1 in at most l1 hours and get from city s2 to city t2 in at most l2 hours.
Determine what maximum number of roads you need to destroy in order to meet the condition of your plan. If it is impossible to reach the desired result, print -1.
Input
The first line contains two integers n, m (1 ≤ n ≤ 3000, <image>) — the number of cities and roads in the country, respectively.
Next m lines contain the descriptions of the roads as pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi). It is guaranteed that the roads that are given in the description can transport you from any city to any other one. It is guaranteed that each pair of cities has at most one road between them.
The last two lines contains three integers each, s1, t1, l1 and s2, t2, l2, respectively (1 ≤ si, ti ≤ n, 0 ≤ li ≤ n).
Output
Print a single number — the answer to the problem. If the it is impossible to meet the conditions, print -1.
Examples
Input
5 4
1 2
2 3
3 4
4 5
1 3 2
3 5 2
Output
0
Input
5 4
1 2
2 3
3 4
4 5
1 3 2
2 4 2
Output
1
Input
5 4
1 2
2 3
3 4
4 5
1 3 2
3 5 1
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(int argc, char const *argv[]) {
ios_base::sync_with_stdio(false);
int n, m;
cin >> n >> m;
vector<vector<int>> g(n);
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
a--;
b--;
g[a].push_back(b);
g[b].push_back(a);
}
vector<vector<int>> d(n, vector<int>(n, -1));
for (int i = 0; i < n; i++) {
queue<int> q;
q.push(i);
d[i][i] = 0;
while (!q.empty()) {
auto v = q.front();
q.pop();
for (int j = 0; j < g[v].size(); j++) {
auto v2 = g[v][j];
if (d[i][v2] == -1) {
d[i][v2] = d[i][v] + 1;
q.push(v2);
}
}
}
}
int s[2], t[2], l[2];
for (int i = 0; i < 2; i++) {
cin >> s[i] >> t[i] >> l[i];
s[i]--;
t[i]--;
}
int minEdges = m + 1;
for (int k = 0; k < 2; k++) {
swap(s[0], t[0]);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
auto route0 = d[s[0]][i] + d[i][j] + d[j][t[0]];
auto route1 = d[s[1]][i] + d[i][j] + d[j][t[1]];
if (route0 <= l[0] && route1 <= l[1]) {
minEdges = min(minEdges, route0 + route1 - d[i][j]);
}
}
}
}
auto route0 = d[s[0]][t[0]];
auto route1 = d[s[1]][t[1]];
if (route0 <= l[0] && route1 <= l[1]) {
minEdges = min(minEdges, route0 + route1);
}
int result = 0;
if (minEdges > m) {
result = -1;
} else {
result = m - minEdges;
}
cout << result << endl;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Takahashi is meeting up with Aoki.
They have planned to meet at a place that is D meters away from Takahashi's house in T minutes from now.
Takahashi will leave his house now and go straight to the place at a speed of S meters per minute.
Will he arrive in time?
Constraints
* 1 \leq D \leq 10000
* 1 \leq T \leq 10000
* 1 \leq S \leq 10000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
D T S
Output
If Takahashi will reach the place in time, print `Yes`; otherwise, print `No`.
Examples
Input
1000 15 80
Output
Yes
Input
2000 20 100
Output
Yes
Input
10000 1 1
Output
No
### Response
```cpp
#include<stdio.h>
int main()
{
int d,t,s;
scanf("%d %d %d",&d,&t,&s);
if(d<=t*s)printf("Yes");
else printf("No");
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Piegirl got bored with binary, decimal and other integer based counting systems. Recently she discovered some interesting properties about number <image>, in particular that q2 = q + 1, and she thinks it would make a good base for her new unique system. She called it "golden system". In golden system the number is a non-empty string containing 0's and 1's as digits. The decimal value of expression a0a1...an equals to <image>.
Soon Piegirl found out that this system doesn't have same properties that integer base systems do and some operations can not be performed on it. She wasn't able to come up with a fast way of comparing two numbers. She is asking for your help.
Given two numbers written in golden system notation, determine which of them has larger decimal value.
Input
Input consists of two lines — one for each number. Each line contains non-empty string consisting of '0' and '1' characters. The length of each string does not exceed 100000.
Output
Print ">" if the first number is larger, "<" if it is smaller and "=" if they are equal.
Examples
Input
1000
111
Output
<
Input
00100
11
Output
=
Input
110
101
Output
>
Note
In the first example first number equals to <image>, while second number is approximately 1.6180339882 + 1.618033988 + 1 ≈ 5.236, which is clearly a bigger number.
In the second example numbers are equal. Each of them is ≈ 2.618.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX = 1e5 + 1000;
int a1[MAX], a2[MAX];
int main() {
string a, b;
cin >> a >> b;
for (int i = a.length() - 1; i >= 0; i--) a1[a.length() - i - 1] = a[i] - '0';
for (int i = b.length() - 1; i >= 0; i--) a2[b.length() - i - 1] = b[i] - '0';
for (int i = MAX - 10; i >= 0; i--) {
for (int j = i; a1[j] && a1[j + 1]; j += 2)
a1[j] = a1[j + 1] = 0, a1[j + 2] = 1;
for (int j = i; a2[j] && a2[j + 1]; j += 2)
a2[j] = a2[j + 1] = 0, a2[j + 2] = 1;
}
for (int i = MAX - 1; i >= 0; i--)
if (a1[i] > a2[i])
return cout << '>', 0;
else if (a1[i] < a2[i])
return cout << '<', 0;
cout << '=';
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.
Input
The first line contains a positive integer k (1 ≤ k ≤ 26) — the number of strings that should be in a beautiful sequence.
The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.
Output
If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s1, s2, ..., sk.
If there are multiple possible answers, print any of them.
Examples
Input
1
abca
Output
YES
abca
Input
2
aaacas
Output
YES
aaa
cas
Input
4
abc
Output
NO
Note
In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
set<char> arr;
string str;
cin >> str;
for (int i = 0; i < str.size(); i++) {
arr.insert(str[i]);
}
if (arr.size() < n) {
cout << "NO\n";
} else {
cout << "YES\n";
set<char> temp;
cout << str[0];
int ctr = 1;
temp.insert(str[0]);
int i;
for (i = 1; i < str.size(); i++) {
if (temp.count(str[i]))
cout << str[i];
else {
ctr++;
temp.insert(str[i]);
if (ctr > n) {
break;
}
cout << "\n";
cout << str[i];
}
}
for (int j = i; j < str.size(); j++) cout << str[j];
}
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.
Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.
Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!
Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
Input
The first line contains a single integer T (1 ≤ T ≤ 100): the number of bags for which you need to solve the problem.
The first line of each bag description contains a single integer n (2 ≤ n ≤ 10^5): the number of patty-cakes in it. The second line of the bag description contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling.
It is guaranteed that the sum of n over all bags does not exceed 10^5.
Output
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
Example
Input
4
7
1 7 1 6 4 4 6
8
1 1 4 6 4 6 4 7
3
3 3 3
6
2 5 2 3 1 4
Output
3
2
0
4
Note
For the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): 1, 6, 4, 7, 1, 6, 4 (in this way, the minimum distance is equal to 3).
For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): 1, 4, 6, 7, 4, 1, 6, 4 (in this way, the minimum distance is equal to 2).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 7;
const int mod = 1e9 + 7;
int a[maxn], vis[maxn], num[maxn];
map<int, int> mp;
int cmp(int x, int y) { return x > y; }
int main() {
int T;
scanf("%d", &T);
while (T--) {
mp.clear();
int n;
scanf("%d", &n);
int cnt = 0;
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
vis[i] = 0;
num[i] = 0;
if (!mp[a[i]]) mp[a[i]] = ++cnt;
a[i] = mp[a[i]];
}
for (int i = 1; i <= n; i++) vis[a[i]]++;
sort(vis + 1, vis + 1 + cnt, cmp);
int len = vis[1];
if (cnt == 1) {
printf("0\n");
continue;
}
int flag = 0;
for (int i = 1; i <= n; i++) {
if (vis[i] == len) vis[i]--;
}
len--;
int now = 1;
for (int i = 1; i <= cnt; i++) {
int tmp = vis[i];
while (tmp) {
tmp--;
num[now]++;
now = now + 1;
if (now == len + 1) now = 1;
}
}
printf("%d\n", num[len] - 1);
}
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Snuke is standing on a two-dimensional plane. In one operation, he can move by 1 in the positive x-direction, or move by 1 in the positive y-direction.
Let us define a function f(r, c) as follows:
* f(r,c) := (The number of paths from the point (0, 0) to the point (r, c) that Snuke can trace by repeating the operation above)
Given are integers r_1, r_2, c_1, and c_2. Find the sum of f(i, j) over all pair of integers (i, j) such that r_1 ≤ i ≤ r_2 and c_1 ≤ j ≤ c_2, and compute this value modulo (10^9+7).
Constraints
* 1 ≤ r_1 ≤ r_2 ≤ 10^6
* 1 ≤ c_1 ≤ c_2 ≤ 10^6
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
r_1 c_1 r_2 c_2
Output
Print the sum of f(i, j) modulo (10^9+7).
Examples
Input
1 1 2 2
Output
14
Input
314 159 2653 589
Output
602215194
### Response
```cpp
#include <iostream>
#include <vector>
using namespace std;
// a^b % m
long long powmod(long long a, long long b, long long m)
{
long long r = 1;
for (; b>0; b>>=1, a=a*a%m)
if (b&1)
r = r*a%m;
return r;
}
int main()
{
long long r1, c1, r2, c2;
cin>>r1>>c1>>r2>>c2;
long long M = 1000000007;
vector<long long> F(2000002);
F[0] = 1;
for (int i=1; i<=2000001; i++)
F[i] = F[i-1]*i%M;
auto C = [&](long long x, long long y)
{
return F[x]*powmod(F[y], M-2, M)%M*powmod(F[x-y], M-2, M)%M;
};
long long ans = 0;
for (long long r=r1; r<=r2; r++)
{
ans += C(r+c2+1, c2) - C(r+c1, c1-1);
ans = (ans%M+M)%M;
}
cout<<ans<<endl;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Let’s take a prime P = 200\,003. You are given N integers A_1, A_2, \ldots, A_N. Find the sum of ((A_i \cdot A_j) \bmod P) over all N \cdot (N-1) / 2 unordered pairs of elements (i < j).
Please note that the sum isn't computed modulo P.
Constraints
* 2 \leq N \leq 200\,000
* 0 \leq A_i < P = 200\,003
* All values in input are integers.
Input
Input is given from Standard Input in the following format.
N
A_1 A_2 \cdots A_N
Output
Print one integer — the sum over ((A_i \cdot A_j) \bmod P).
Examples
Input
4
2019 0 2020 200002
Output
474287
Input
5
1 1 2 2 100000
Output
600013
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
#define int long long
const double Pi=acos(-1.0);
const int mod=200003,G=2,N=4000010;
struct CP{
CP (double xx=0,double yy=0){x=xx,y=yy;}
double x,y;
CP operator + (CP const &B) const
{return CP(x+B.x,y+B.y);}
CP operator - (CP const &B) const
{return CP(x-B.x,y-B.y);}
CP operator * (CP const &B) const
{return CP(x*B.x-y*B.y,x*B.y+y*B.x);}
};
int tr[N];
void fft(CP *f,int n,int flag){
for(int i=0;i<n;++i)
if(i<tr[i]) swap(f[i],f[tr[i]]);
for(int p=2;p<=n;p<<=1){
int len=p>>1;
CP tg(cos(2*Pi/p),sin(2*Pi/p));
if(flag==-1) tg.y*=-1;
for(int k=0;k<n;k+=p){
CP buf(1,0),tt;
for(int l=k;l<k+len;++l)
tt=buf*f[l+len],
f[l+len]=f[l]-tt,
f[l]=f[l]+tt,
buf=buf*tg;
}
}
if(flag==-1){
for(int i=0;i<n;++i)
f[i].x/=n;
}
}
CP f[N];
int Lg[N],a[N],g[N];
int ksm(int b,int n){
int res=1;
while(n){
if(n&1) res=res*b%mod;
b=b*b%mod; n>>=1;
}
return res;
}
void init(){
int x=1;
for(int i=0;i<mod-1;++i)
g[i]=x,Lg[x]=i,x=x*G%mod;
//for(int i=0;i<mod-1;++i)
// cout<<g[i]<<" ";cout<<endl;
//cout<<"egerdf\n";
}
signed main(){
// freopen("2.out","w",stdout);
init();
int n,x;
cin>>n;
for(int i=1;i<=n;++i){
cin>>a[i];
if(a[i])f[Lg[a[i]]].x++;
}
int limit=1;
while(limit<=((mod-1)<<1)) limit<<=1;
//cout<<limit<<endl;
for(int i=0;i<limit;++i)
tr[i]=(tr[i>>1]>>1)|(i&1?limit>>1:0);
//cout<<"segrtryhaw\n";
fft(f,limit,1);
for(int i=0;i<limit;++i)
f[i]=f[i]*f[i];
fft(f,limit,-1);
//for(int i=0;i<limit;++i)cout<<f[i].x<<" ";cout<<endl;
//cout<<"wegrtjrtsfh\n";
for(int i=1;i<=n;++i)
if(a[i])f[Lg[a[i]]+Lg[a[i]]].x--;
int ans=0;
//cout<<"fgrerttdfbdfgb\n";
for(int i=0;i<limit;++i)
ans+=(long long)(f[i].x/2+1e-1)*g[i%(mod-1)];
cout<<ans;
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
You've got an n × m table (n rows and m columns), each cell of the table contains a "0" or a "1".
Your task is to calculate the number of rectangles with the sides that are parallel to the sides of the table and go along the cell borders, such that the number one occurs exactly k times in the rectangle.
Input
The first line contains three space-separated integers n, m and k (1 ≤ n, m ≤ 2500, 0 ≤ k ≤ 6) — the sizes of the table and the required number of numbers one.
Next n lines each contains m characters "0" or "1". The i-th character of the j-th line corresponds to the character that is in the j-th row and the i-th column of the table.
Output
Print a single number — the number of rectangles that contain exactly k numbers one.
Please, do not write 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
3 3 2
101
000
101
Output
8
Input
5 5 1
00000
00000
00100
00000
00000
Output
81
Input
5 5 6
01010
10101
01010
10101
01010
Output
12
Input
3 3 0
001
010
000
Output
15
Input
4 4 0
0000
0101
0000
0000
Output
52
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int K;
int grid[2][2505][2505];
int up[2505][8], up_sum[2505][8];
int down[2505][8], down_sum[2505][8];
long long compute(int x1, int y1, int x2, int y2, int d) {
if (x1 == x2 && y1 == y2) {
return grid[d][x1][y1] - grid[d][x1 - 1][y1] == K;
}
if (x2 - x1 < y2 - y1) {
swap(x1, y1);
swap(x2, y2);
d ^= 1;
}
int mid = (x1 + x2) >> 1;
long long ret = 0;
for (int i = (y1); i < int(y2 + 1); i++) {
for (int k = 0; k < int(K + 1); k++) {
up_sum[i][k] = 0;
down_sum[i][k] = 0;
up[i][k] = x1;
down[i][k] = x2;
}
for (int j = (i); j < int(y2 + 1); j++) {
for (int k = 0; k < int(K + 1); k++) {
up_sum[i][k] += grid[d][mid][j] - grid[d][up[i][k] - 1][j];
while (up_sum[i][k] > k) {
up_sum[i][k] -=
grid[d ^ 1][j][up[i][k]] - grid[d ^ 1][i - 1][up[i][k]];
up[i][k]++;
}
down_sum[i][k] += grid[d][down[i][k]][j] - grid[d][mid][j];
while (down_sum[i][k] > k) {
down_sum[i][k] -=
grid[d ^ 1][j][down[i][k]] - grid[d ^ 1][i - 1][down[i][k]];
down[i][k]--;
}
}
for (int k = 0; k < int(K + 1); k++) {
if (up_sum[i][k] != k || down_sum[i][K - k] != K - k) {
continue;
}
int l, r;
if (k == 0) {
l = mid - up[i][k] + 1;
} else {
l = up[i][k - 1] - up[i][k];
}
if (k == K) {
r = down[i][K - k] - mid;
} else {
r = down[i][K - k] - down[i][K - k - 1];
}
ret += l * r;
}
}
}
ret += compute(x1, y1, mid, y2, d);
ret += compute(mid + 1, y1, x2, y2, d);
return ret;
}
int main() {
std::ios_base::sync_with_stdio(false);
int m, n;
cin >> m >> n >> K;
for (int i = 0; i < int(m); i++) {
for (int j = 0; j < int(n); j++) {
char c;
cin >> c;
grid[0][i + 1][j + 1] = c - '0';
grid[1][j + 1][i + 1] = c - '0';
}
}
for (int i = 0; i < int(m); i++) {
for (int j = 0; j < int(n); j++) {
grid[0][i + 1][j + 1] += grid[0][i][j + 1];
grid[1][j + 1][i + 1] += grid[1][j][i + 1];
}
}
cout << compute(1, 1, m, n, 0);
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Petya and Vasya got employed as couriers. During the working day they are to deliver packages to n different points on the line. According to the company's internal rules, the delivery of packages must be carried out strictly in a certain order. Initially, Petya is at the point with the coordinate s1, Vasya is at the point with the coordinate s2, and the clients are at the points x1, x2, ..., xn in the order of the required visit.
The guys agree in advance who of them will deliver the package to which of the customers, and then they act as follows. When the package for the i-th client is delivered, the one who delivers the package to the (i + 1)-st client is sent to the path (it can be the same person who went to the point xi, or the other). The friend who is not busy in delivering the current package, is standing still.
To communicate with each other, the guys have got walkie-talkies. The walkie-talkies work rather poorly at great distances, so Petya and Vasya want to distribute the orders so that the maximum distance between them during the day is as low as possible. Help Petya and Vasya to minimize the maximum distance between them, observing all delivery rules.
Input
The first line contains three integers n, s1, s2 (1 ≤ n ≤ 100 000, 0 ≤ s1, s2 ≤ 109) — number of points of delivery and starting positions of Petya and Vasya.
The second line contains n integers x1, x2, ..., xn — customers coordinates (0 ≤ xi ≤ 109), in the order to make a delivery.
It is guaranteed, that among the numbers s1, s2, x1, ..., xn there are no two equal.
Output
Output the only integer, minimum possible maximal distance between couriers during delivery.
Examples
Input
2 0 10
5 6
Output
10
Input
3 2 1
3 4 5
Output
1
Input
1 4 5
2
Output
2
Note
In the first test case the initial distance between the couriers is 10. This value will be the answer, for example, Petya can perform both deliveries, and Vasya will remain at the starting point.
In the second test case you can optimally act, for example, like this: Vasya delivers the package to the first customer, Petya to the second and, finally, Vasya delivers the package to the third client. With this order of delivery, the distance between the couriers will never exceed 1.
In the third test case only two variants are possible: if the delivery of a single package is carried out by Petya, the maximum distance between them will be 5 - 2 = 3. If Vasya will deliver the package, the maximum distance is 4 - 2 = 2. The latter method is optimal.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, s1, s2;
int a[100005];
inline int read() {
int s = 0, w = 1;
char c = getchar();
for (; !isdigit(c); c = getchar())
if (c == '-') w = -1;
for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
return s * w;
}
inline bool check(int x) {
int l = -0x3f3f3f3f, r = 0x3f3f3f3f;
for (register int i = n; i >= 1; i--) {
if (l <= a[i] && a[i] <= r)
l = a[i] - x, r = a[i] + x;
else
l = max(l, a[i] - x), r = min(r, a[i] + x);
}
return (l <= s1 && s1 <= r) || (l <= s2 && s2 <= r);
}
int main() {
n = read(), s1 = read(), s2 = read();
for (int i = 1; i <= n; ++i) a[i] = read();
int l = abs(s1 - s2), r = 0x3f3f3f3f;
while (l < r) {
int mid = (l + r) >> 1;
if (check(mid))
r = mid;
else
l = mid + 1;
}
printf("%d\n", l);
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
A 3×3 grid with a integer written in each square, is called a magic square if and only if the integers in each row, the integers in each column, and the integers in each diagonal (from the top left corner to the bottom right corner, and from the top right corner to the bottom left corner), all add up to the same sum.
You are given the integers written in the following three squares in a magic square:
* The integer A at the upper row and left column
* The integer B at the upper row and middle column
* The integer C at the middle row and middle column
Determine the integers written in the remaining squares in the magic square.
It can be shown that there exists a unique magic square consistent with the given information.
Constraints
* 0 \leq A, B, C \leq 100
Input
The input is given from Standard Input in the following format:
A
B
C
Output
Output the integers written in the magic square, in the following format:
X_{1,1} X_{1,2} X_{1,3}
X_{2,1} X_{2,2} X_{2,3}
X_{3,1} X_{3,2} X_{3,3}
where X_{i,j} is the integer written in the square at the i-th row and j-th column.
Examples
Input
8
3
5
Output
8 3 4
1 5 9
6 7 2
Input
1
1
1
Output
1 1 1
1 1 1
1 1 1
### Response
```cpp
#include <stdio.h>
int main()
{
int a,b,c;
scanf ("%d %d %d",&a,&b,&c);
for (int s=-1000;s<=1000;s++){
int p[3][3];
p[0][0] = a;
p[0][1] = b;
p[1][1] = c;
p[0][2] = s - a - b;
p[2][0] = s - c - p[0][2];
p[1][0] = s - a - p[2][0];
p[1][2] = s - c - p[1][0];
p[2][1] = s - b - c;
p[2][2] = s - a - c;
bool good = 1;
for (int i=0;i<3;i++) if (p[i][0] + p[i][1] + p[i][2] != s) good = 0;
for (int i=0;i<3;i++) if (p[0][i] + p[1][i] + p[2][i] != s) good = 0;
if (p[0][0] + p[1][1] + p[2][2] != s) good = 0;
if (p[2][0] + p[1][1] + p[0][2] != s) good = 0;
if (good){
for (int i=0;i<3;i++) for (int j=0;j<3;j++) printf ("%d%c",p[i][j],j+1<3?' ':'\n');
return 0;
}
}
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Min Element
Given the sequence a_1, a_2, .., a_N.
Find the minimum number in this sequence.
If the minimum value is in more than one place, answer the one with the lowest number.
input
N
a_1 a_2 ... a_N
output
Output the smallest i such that a_i is the minimum value in the sequence.
Constraint
* 1 \ leq N \ leq 10 ^ 5
* 1 \ leq a_i \ leq 10 ^ 9
Input example
6
8 6 9 1 2 1
Output example
Four
Example
Input
6
8 6 9 1 2 1
Output
4
### Response
```cpp
#include <iostream>
using namespace std;
int main(){
int n;cin>>n;
int mn = 1000000000;
int mnp = -1;
for(int i = 0; n > i; i++){
int t;cin>>t;
if(mn > t){
mnp = i;
mn = t;
}
}
cout << mnp+1 << endl;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
This is an interactive problem.
You are given a sorted in increasing order singly linked list. You should find the minimum integer in the list which is greater than or equal to x.
More formally, there is a singly liked list built on an array of n elements. Element with index i contains two integers: valuei is the integer value in this element, and nexti that is the index of the next element of the singly linked list (or -1, if the current element is the last). The list is sorted, i.e. if nexti ≠ - 1, then valuenexti > valuei.
You are given the number of elements in the list n, the index of the first element start, and the integer x.
You can make up to 2000 queries of the following two types:
* ? i (1 ≤ i ≤ n) — ask the values valuei and nexti,
* ! ans — give the answer for the problem: the minimum integer, greater than or equal to x, or ! -1, if there are no such integers. Your program should terminate after this query.
Write a program that solves this problem.
Input
The first line contains three integers n, start, x (1 ≤ n ≤ 50000, 1 ≤ start ≤ n, 0 ≤ x ≤ 109) — the number of elements in the list, the index of the first element and the integer x.
Output
To print the answer for the problem, print ! ans, where ans is the minimum integer in the list greater than or equal to x, or -1, if there is no such integer.
Interaction
To make a query of the first type, print ? i (1 ≤ i ≤ n), where i is the index of element you want to know information about.
After each query of type ? read two integers valuei and nexti (0 ≤ valuei ≤ 109, - 1 ≤ nexti ≤ n, nexti ≠ 0).
It is guaranteed that if nexti ≠ - 1, then valuenexti > valuei, and that the array values give a valid singly linked list with start being the first element.
Note that you can't ask more than 1999 queries of the type ?.
If nexti = - 1 and valuei = - 1, then it means that you asked more queries than allowed, or asked an invalid query. Your program should immediately terminate (for example, by calling exit(0)). You will receive "Wrong Answer", it means that you asked more queries than allowed, or asked an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.
Your solution will get "Idleness Limit Exceeded", if you don't print anything or forget to flush the output, including the final answer.
To flush you can use (just after printing a query and line end):
* fflush(stdout) in C++;
* System.out.flush() in Java;
* stdout.flush() in Python;
* flush(output) in Pascal;
* For other languages see documentation.
Hacks format
For hacks, use the following format:
In the first line print three integers n, start, x (1 ≤ n ≤ 50000, 1 ≤ start ≤ n, 0 ≤ x ≤ 109).
In the next n lines print the description of the elements of the list: in the i-th line print two integers valuei and nexti (0 ≤ valuei ≤ 109, - 1 ≤ nexti ≤ n, nexti ≠ 0).
The printed structure should be a valid singly linked list. In particular, it should be possible to reach all elements from start by following links nexti, and the last element end should have -1 in the nextend.
Example
Input
5 3 80
97 -1
58 5
16 2
81 1
79 4
Output
? 1
? 2
? 3
? 4
? 5
! 81
Note
You can read more about singly linked list by the following link: <https://en.wikipedia.org/wiki/Linked_list#Singly_linked_list>
The illustration for the first sample case. Start and finish elements are marked dark. <image>
### Response
```cpp
#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
const int M = 1e6 + 5, INF = 0x3f3f3f3f, mod = 1000007;
int A[M], val[M], nxt[M];
int Rand() { return (rand() << 15) | rand(); }
int main() {
srand(time(NULL));
int n, st, x;
scanf("%d%d%d", &n, &st, &x);
for (int j = 1; j <= n; j++) {
A[j] = j;
}
for (int j = 1; j <= M; j++) {
int a = Rand() % n + 1, b = Rand() % n + 1;
swap(A[a], A[b]);
}
printf("? %d", st);
cout << endl;
scanf("%d%d", &val[st], &nxt[st]);
int up = INF, down = val[st];
int uppos, downpos = st;
for (int j = 1; j <= min(n, 999); j++) {
printf("? %d", A[j]);
cout << endl;
int a, b;
scanf("%d%d", &a, &b);
val[A[j]] = a;
nxt[A[j]] = b;
if (a >= x && a <= up) {
up = a;
uppos = A[j];
}
if (a <= x && a >= down) {
down = a;
downpos = A[j];
}
}
if (up == x) {
printf("! %d", x);
cout << endl;
return 0;
}
if (down >= x) {
printf("! %d", down);
cout << endl;
return 0;
}
int left = 999;
while (left--) {
if (nxt[downpos] == -1) break;
printf("? %d", nxt[downpos]);
cout << endl;
downpos = nxt[downpos];
int a, b;
scanf("%d%d", &a, &b);
if (a >= x) {
printf("! %d", a);
cout << endl;
return 0;
}
val[downpos] = a;
nxt[downpos] = b;
}
printf("! %d", up == INF ? -1 : up);
cout << endl;
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
In a magical land there are n cities conveniently numbered 1, 2, ..., n. Some pairs of these cities are connected by magical colored roads. Magic is unstable, so at any time, new roads may appear between two cities.
Vicky the witch has been tasked with performing deliveries between some pairs of cities. However, Vicky is a beginner, so she can only complete a delivery if she can move from her starting city to her destination city through a double rainbow. A double rainbow is a sequence of cities c_1, c_2, ..., c_k satisfying the following properties:
* For each i with 1 ≤ i ≤ k - 1, the cities c_i and c_{i + 1} are connected by a road.
* For each i with 1 ≤ i ≤ (k - 1)/(2), the roads connecting c_{2i} with c_{2i - 1} and c_{2i + 1} have the same color.
For example if k = 5, the road between c_1 and c_2 must be the same color as the road between c_2 and c_3, and the road between c_3 and c_4 must be the same color as the road between c_4 and c_5.
Vicky has a list of events in chronological order, where each event is either a delivery she must perform, or appearance of a new road. Help her determine which of her deliveries she will be able to complete.
Input
The first line contains four integers n, m, c, and q (2 ≤ n ≤ 10^5, 1 ≤ m, c, q ≤ 10^5), denoting respectively the number of cities, the number of roads initially present, the number of different colors the roads can take, and the number of events.
Each of the following m lines contains three integers x, y, and z (1 ≤ x, y ≤ n, 1 ≤ z ≤ c), describing that there initially exists a bidirectional road with color z between cities x and y.
Then q lines follow, describing the events. Each event is one of the following two types:
1. + x y z (1 ≤ x, y ≤ n, 1 ≤ z ≤ c), meaning a road with color z appears between cities x and y;
2. ? x y (1 ≤ x, y ≤ n), meaning you should determine whether Vicky can make a delivery starting at city x and ending at city y. It is guaranteed that x ≠ y.
It is guaranteed that at any moment, there is at most one road connecting any pair of cities, and that no road connects a city to itself. It is guaranteed that the input contains at least one event of the second type.
Output
For each event of the second type, print a single line containing "Yes" (without quotes) if the delivery can be made, or a single line containing "No" (without quotes) otherwise.
Example
Input
4 3 2 4
1 2 1
2 3 1
3 4 2
? 1 4
? 4 1
+ 3 1 2
? 4 1
Output
Yes
No
Yes
Note
The following picture corresponds to the sample.
<image>
For her first delivery, Vicky can use the sequence 1, 2, 3, 4 which is a double rainbow. However, she cannot complete the second delivery, as she can only reach city 3. After adding the road between cities 1 and 3, she can now complete a delivery from city 4 to city 1 by using the double rainbow 4, 3, 1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct bian {
int to, nxt, va;
} bi[400040];
int n, m, c, q, siz, head[100010], num, tot, f[100010], id[100010], idnum,
d[100010];
int query[100010][4];
bitset<700> lt[100010];
map<int, int> mp[100010];
void add(int from, int to, int va) {
bi[++num].nxt = head[from];
head[from] = num;
bi[num].to = to;
bi[num].va = va;
}
int find(int x) {
if (x != f[x]) return f[x] = find(f[x]);
return x;
}
int main() {
scanf("%d %d %d %d", &n, &m, &c, &q);
int x, y, z;
for (int i = 1; i <= m; ++i) {
scanf("%d %d %d", &x, &y, &z);
add(x, y, z);
++d[x];
add(y, x, z);
++d[y];
}
tot = 2 * m;
char op;
for (int i = 1; i <= q; ++i) {
scanf(" %c", &op);
if (op == '+') {
scanf("%d %d %d", &x, &y, &z);
query[i][1] = x, query[i][2] = y, query[i][3] = z;
++d[x], ++d[y];
tot += 2;
} else {
scanf("%d %d", &x, &y);
query[i][0] = 1, query[i][1] = x, query[i][2] = y;
}
}
siz = sqrt(tot);
for (int i = 1; i <= n; ++i) f[i] = i;
for (int i = 1; i <= n; ++i)
if (d[i] >= siz) {
id[i] = ++idnum;
for (int j = head[i]; j; j = bi[j].nxt) lt[bi[j].to].set(idnum);
}
for (int i = 1; i <= n; ++i)
for (int j = head[i]; j; j = bi[j].nxt) {
if (mp[i].count(bi[j].va)) {
x = find(bi[j].to), y = find(mp[i][bi[j].va]);
if (x != y) lt[y] |= lt[x], f[x] = y;
} else
mp[i][bi[j].va] = bi[j].to;
}
for (int i = 1; i <= q; ++i) {
if (query[i][0]) {
x = query[i][1], y = query[i][2];
if (find(x) == find(y)) {
printf("Yes\n");
continue;
}
bool flag = 0;
if (d[y] < siz) {
for (int j = head[y]; j; j = bi[j].nxt)
if (find(x) == find(bi[j].to)) {
flag = 1;
break;
}
} else
flag = lt[find(x)][id[y]];
if (flag)
printf("Yes\n");
else
printf("No\n");
} else {
x = query[i][1], y = query[i][2], z = query[i][3];
add(x, y, z), add(y, x, z);
if (id[y]) lt[find(x)].set(id[y]);
if (id[x]) lt[find(y)].set(id[x]);
if (mp[x][z]) {
if (find(mp[x][z]) != find(y)) {
lt[find(y)] |= lt[find(mp[x][z])];
f[find(mp[x][z])] = find(y);
}
} else
mp[x][z] = y;
swap(x, y);
if (mp[x][z]) {
if (find(mp[x][z]) != find(y)) {
lt[find(y)] |= lt[find(mp[x][z])];
f[find(mp[x][z])] = find(y);
}
} else
mp[x][z] = y;
}
}
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a connection.
The government designed a plan to build n network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the i-th network station will provide service only for the i-th and the (i + 1)-th city (the n-th station is connected to the n-th and the 1-st city).
All network stations have capacities: the i-th station can provide the connection to at most b_i households.
Now the government asks you to check can the designed stations meet the needs of all cities or not — that is, is it possible to assign each household a network station so that each network station i provides the connection to at most b_i households.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains the single integer n (2 ≤ n ≤ 10^6) — the number of cities and stations.
The second line of each test case contains n integers (1 ≤ a_i ≤ 10^9) — the number of households in the i-th city.
The third line of each test case contains n integers (1 ≤ b_i ≤ 10^9) — the capacities of the designed stations.
It's guaranteed that the sum of n over test cases doesn't exceed 10^6.
Output
For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).
Example
Input
5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
Output
YES
YES
NO
YES
YES
Note
In the first test case:
* the first network station can provide 2 connections to the first city and 1 connection to the second city;
* the second station can provide 2 connections to the second city and 1 connection to the third city;
* the third station can provide 3 connections to the third city.
In the second test case:
* the 1-st station can provide 2 connections to the 1-st city;
* the 2-nd station can provide 3 connections to the 2-nd city;
* the 3-rd station can provide 3 connections to the 3-rd city and 1 connection to the 1-st station.
In the third test case, the fourth city needs 5 connections, but the third and the fourth station has 4 connections in total.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 2e6 + 10;
int q;
int n;
long long ar[N], mx[N], pre[N];
long long tot, cur;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> q;
while (q--) {
bool ok = 1;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> ar[i];
pre[i + i] = -ar[i];
}
for (int i = 1; i <= n; i++) {
cin >> mx[i];
int id = (i + i) % (n + n) + 1;
pre[id] = mx[i];
}
n = n + n;
for (int i = 1; i <= n; i++) {
pre[n + i] = pre[i];
}
for (int i = 1; i <= n + n; i++) {
pre[i] = pre[i] + pre[i - 1];
}
if (pre[n] < 0) {
cout << "NO" << '\n';
continue;
}
long long mx = 0;
for (int i = 0; i <= n + n; i++) {
if (i & 1) {
if (pre[i] - mx < 0) {
ok = 0;
break;
}
} else {
mx = max(mx, pre[i]);
}
}
if (ok)
cout << "YES" << '\n';
else
cout << "NO" << '\n';
}
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Duff is in love with lovely numbers! A positive integer x is called lovely if and only if there is no such positive integer a > 1 such that a2 is a divisor of x.
<image>
Malek has a number store! In his store, he has only divisors of positive integer n (and he has all of them). As a birthday present, Malek wants to give her a lovely number from his store. He wants this number to be as big as possible.
Malek always had issues in math, so he asked for your help. Please tell him what is the biggest lovely number in his store.
Input
The first and only line of input contains one integer, n (1 ≤ n ≤ 1012).
Output
Print the answer in one line.
Examples
Input
10
Output
10
Input
12
Output
6
Note
In first sample case, there are numbers 1, 2, 5 and 10 in the shop. 10 isn't divisible by any perfect square, so 10 is lovely.
In second sample case, there are numbers 1, 2, 3, 4, 6 and 12 in the shop. 12 is divisible by 4 = 22, so 12 is not lovely, while 6 is indeed lovely.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(int argc, char const *argv[]) {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long int n, i;
cin >> n;
long long int ans = n;
for (i = 2; i <= sqrt(n); i++) {
long long int x = i * i;
while (ans % x == 0) ans /= i;
}
cout << ans << endl;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards.
The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful.
You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case.
Input
First line of the input consists of two integers n and m (1 ≤ n, m ≤ 1000), separated by space — number of cards in each deck, and number of decks.
Output
On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10 - 6.
Examples
Input
2 2
Output
0.6666666666666666
Input
4 4
Output
0.4000000000000000
Input
1 2
Output
1.0000000000000000
Note
In the first sample, with probability <image> Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed.
With the remaining <image> probability he took two different cards, and the probability of pulling off the trick is <image>.
The resulting probability is <image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int INF = 1000000000;
int n, m, k;
int a[1005];
int main() {
while (~scanf("%d%d", &n, &m)) {
double ans = 0, p = 1.0, b = n * m - m - n + 1;
for (int i = 1; i < n; i++) p = p * (b + i) / (b + i + m - 1);
ans += p * 1 * 1;
for (int i = 2; i <= min(n, m); i++) {
p = p * (m - i + 1) / i * (n - i + 1) / ((n - 1) * (m - 1) + i - 1);
ans += p * i * i;
}
ans /= n;
printf("%.8f\n", ans);
}
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution 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 long long N = 2e5 + 1;
pair<long long, long long> mp[N];
void solve() {
long long n;
cin >> n;
long long x, y;
for (long long i = 1; i <= n; i++) {
cin >> x >> y;
mp[i] = {x, y};
}
sort(mp + 1, mp + n + 1);
long long ans = 0;
priority_queue<long long, vector<long long>, greater<long long> > price;
long long extra = 0;
for (long long i = n; i > 0; i--) {
long long m = mp[i].first;
while (i > 0 && mp[i].first == m) {
price.push(mp[i].second);
i--;
}
i++;
long long need = m - (i - 1 + extra);
if (need <= 0) continue;
while (need--) {
extra++;
ans += price.top();
price.pop();
}
}
cout << ans << endl;
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long t;
cin >> t;
while (t--) solve();
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
You are given an integer sequence of length N, a_1,a_2,...,a_N.
For each 1≤i≤N, you have three choices: add 1 to a_i, subtract 1 from a_i or do nothing.
After these operations, you select an integer X and count the number of i such that a_i=X.
Maximize this count by making optimal choices.
Constraints
* 1≤N≤10^5
* 0≤a_i<10^5 (1≤i≤N)
* a_i is an integer.
Input
The input is given from Standard Input in the following format:
N
a_1 a_2 .. a_N
Output
Print the maximum possible number of i such that a_i=X.
Examples
Input
7
3 1 4 1 5 9 2
Output
4
Input
10
0 1 2 3 4 5 6 7 8 9
Output
3
Input
1
99999
Output
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll N, A[100005], AI;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> N;
for (ll i = 0; i < N; i++) {
cin >> AI;
for (ll j = max(AI-1, 0LL); j <= AI+1; j++) {
A[j]++;
}
}
cout << *max_element(A, A+100005) << "\n";
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Takahashi, who works at DISCO, is standing before an iron bar. The bar has N-1 notches, which divide the bar into N sections. The i-th section from the left has a length of A_i millimeters.
Takahashi wanted to choose a notch and cut the bar at that point into two parts with the same length. However, this may not be possible as is, so he will do the following operations some number of times before he does the cut:
* Choose one section and expand it, increasing its length by 1 millimeter. Doing this operation once costs 1 yen (the currency of Japan).
* Choose one section of length at least 2 millimeters and shrink it, decreasing its length by 1 millimeter. Doing this operation once costs 1 yen.
Find the minimum amount of money needed before cutting the bar into two parts with the same length.
Constraints
* 2 \leq N \leq 200000
* 1 \leq A_i \leq 2020202020
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 A_3 ... A_N
Output
Print an integer representing the minimum amount of money needed before cutting the bar into two parts with the same length.
Examples
Input
3
2 4 3
Output
3
Input
12
100 104 102 105 103 103 101 105 104 102 104 101
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main(){
int n;
cin >> n;
vector<int> an(n);
ll tot = 0;
for(int i=0; i<n; ++i){
cin >> an[i];
tot += an[i];
}
ll ans = tot;
ll tot2 = 0;
for(int i=0; i<n-1; ++i){
tot2 += an[i];
ans = min(ans, abs(tot -tot2*2));
}
cout << ans << endl;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
You are given a connected undirected simple graph, which has N vertices and M edges. The vertices are numbered 1 through N, and the edges are numbered 1 through M. Edge i connects vertices A_i and B_i. Your task is to find a path that satisfies the following conditions:
* The path traverses two or more vertices.
* The path does not traverse the same vertex more than once.
* A vertex directly connected to at least one of the endpoints of the path, is always contained in the path.
It can be proved that such a path always exists. Also, if there are more than one solution, any of them will be accepted.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq A_i < B_i \leq N
* The given graph is connected and simple (that is, for every pair of vertices, there is at most one edge that directly connects them).
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1
A_2 B_2
:
A_M B_M
Output
Find one path that satisfies the conditions, and print it in the following format. In the first line, print the count of the vertices contained in the path. In the second line, print a space-separated list of the indices of the vertices, in order of appearance in the path.
Examples
Input
5 6
1 3
1 4
2 3
1 5
3 5
2 4
Output
4
2 3 1 4
Input
7 8
1 2
2 3
3 4
4 5
5 6
6 7
3 5
2 6
Output
7
1 2 3 4 5 6 7
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<int> graph[100005];
bool visit[100005];
vector<int> path;
vector<int> path2;
void dfs(int t)
{
visit[t] = true;
path.push_back(t);
for (int nxt : graph[t])
{
if (visit[nxt] == false)
{
dfs(nxt);
return;
}
}
}
int main()
{
cin.sync_with_stdio(false);
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++)
{
int a, b;
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
dfs(1);
swap(path, path2);
dfs(1);
printf("%zd\n", path.size() + path2.size() - 1);
for (int i = (int)path2.size() - 1; i >= 1; i--)
{
printf("%d ", path2[i]);
}
for (int t : path) printf("%d ", t);
printf("\n");
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
Output
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
Examples
Input
7
1 2 3 4 5 6 7
Output
2
3 2 1
6 5 4
Input
3
2 2 3
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long i, j, k, l, m, n, t;
map<long long, long long> a;
priority_queue<pair<long long, long long> > q;
vector<vector<long long> > msd;
int main() {
cin >> n;
for (i = 0; i < n; i++) {
cin >> t;
a[t]++;
}
for (map<long long, long long>::iterator it = a.begin(); it != a.end();
++it) {
q.push(make_pair(it->second, it->first));
}
while (q.size() >= 3) {
vector<long long> res;
for (i = 0; i < 3; i++) {
res.push_back(q.top().second);
q.pop();
}
msd.push_back(res);
for (i = 0; i < 3; i++) {
if (--a[res[i]]) q.push(make_pair(a[res[i]], res[i]));
}
}
cout << msd.size() << endl;
for (i = 0; i < msd.size(); i++) {
sort(msd[i].begin(), msd[i].end());
cout << msd[i][2] << " " << msd[i][1] << " " << msd[i][0] << endl;
}
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Consider the infinite sequence s of positive integers, created by repeating the following steps:
1. Find the lexicographically smallest triple of positive integers (a, b, c) such that
* a ⊕ b ⊕ c = 0, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
* a, b, c are not in s.
Here triple of integers (a_1, b_1, c_1) is considered to be lexicographically smaller than triple (a_2, b_2, c_2) if sequence [a_1, b_1, c_1] is lexicographically smaller than sequence [a_2, b_2, c_2].
2. Append a, b, c to s in this order.
3. Go back to the first step.
You have integer n. Find the n-th element of s.
You have to answer t independent test cases.
A sequence a is lexicographically smaller than a sequence b if in the first position where a and b differ, the sequence a has a smaller element than the corresponding element in b.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases.
Each of the next t lines contains a single integer n (1≤ n ≤ 10^{16}) — the position of the element you want to know.
Output
In each of the t lines, output the answer to the corresponding test case.
Example
Input
9
1
2
3
4
5
6
7
8
9
Output
1
2
3
4
8
12
5
10
15
Note
The first elements of s are 1, 2, 3, 4, 8, 12, 5, 10, 15, ...
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long x[4][3] = {{0, 0, 0}, {1, 2, 3}, {2, 3, 1}, {3, 1, 2}};
int main() {
ios::sync_with_stdio(false);
cout.tie(nullptr);
int t;
cin >> t;
while (t-- > 0) {
long long n;
cin >> n;
n -= 1;
long long m3 = n % 3;
n /= 3;
long long mul = 1;
long long res = 0;
while (n > 0) {
n -= 1;
long long a = n % 4;
res += mul * x[a][m3];
mul *= 4;
n /= 4;
}
res += mul * (m3 + 1);
cout << res << "\n";
}
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
A group of university students wants to get to the top of a mountain to have a picnic there. For that they decided to use a cableway.
A cableway is represented by some cablecars, hanged onto some cable stations by a cable. A cable is scrolled cyclically between the first and the last cable stations (the first of them is located at the bottom of the mountain and the last one is located at the top). As the cable moves, the cablecar attached to it move as well.
The number of cablecars is divisible by three and they are painted three colors: red, green and blue, in such manner that after each red cablecar goes a green one, after each green cablecar goes a blue one and after each blue cablecar goes a red one. Each cablecar can transport no more than two people, the cablecars arrive with the periodicity of one minute (i. e. every minute) and it takes exactly 30 minutes for a cablecar to get to the top.
All students are divided into three groups: r of them like to ascend only in the red cablecars, g of them prefer only the green ones and b of them prefer only the blue ones. A student never gets on a cablecar painted a color that he doesn't like,
The first cablecar to arrive (at the moment of time 0) is painted red. Determine the least time it will take all students to ascend to the mountain top.
Input
The first line contains three integers r, g and b (0 ≤ r, g, b ≤ 100). It is guaranteed that r + g + b > 0, it means that the group consists of at least one student.
Output
Print a single number — the minimal time the students need for the whole group to ascend to the top of the mountain.
Examples
Input
1 3 2
Output
34
Input
3 2 1
Output
33
Note
Let's analyze the first sample.
At the moment of time 0 a red cablecar comes and one student from the r group get on it and ascends to the top at the moment of time 30.
At the moment of time 1 a green cablecar arrives and two students from the g group get on it; they get to the top at the moment of time 31.
At the moment of time 2 comes the blue cablecar and two students from the b group get on it. They ascend to the top at the moment of time 32.
At the moment of time 3 a red cablecar arrives but the only student who is left doesn't like red and the cablecar leaves empty.
At the moment of time 4 a green cablecar arrives and one student from the g group gets on it. He ascends to top at the moment of time 34.
Thus, all the students are on the top, overall the ascension took exactly 34 minutes.
### Response
```cpp
#include <bits/stdc++.h>
int main() {
int i, j, k, s[3], sum = 0;
scanf("%d %d %d", &s[0], &s[1], &s[2]);
k = (s[0] + 1) / 2;
j = 0;
for (i = 1; i < 3; i++)
if ((s[j] + 1) / 2 <= (s[i] + 1) / 2) {
k = (s[i] + 1) / 2;
j = i;
}
sum = sum + 30 + (k - 1) * 3 + j;
printf("%d", sum);
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
We have A cards, each of which has an integer 1 written on it. Similarly, we also have B cards with 0s and C cards with -1s.
We will pick up K among these cards. What is the maximum possible sum of the numbers written on the cards chosen?
Constraints
* All values in input are integers.
* 0 \leq A, B, C
* 1 \leq K \leq A + B + C \leq 2 \times 10^9
Input
Input is given from Standard Input in the following format:
A B C K
Output
Print the maximum possible sum of the numbers written on the cards chosen.
Examples
Input
2 1 1 3
Output
2
Input
1 2 3 4
Output
0
Input
2000000000 0 0 2000000000
Output
2000000000
### Response
```cpp
#include <bits/stdc++.h>
#define int long long
using namespace std;
signed main(){
int A,B,C,K; cin>>A>>B>>C>>K;
cout<<(K<=A+B ? min(A,K) : A-(K-A-B))<<endl;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
You are given an array a consisting of n integer numbers.
Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.
You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible instability.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 10^5) — the number of elements in the array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5) — elements of the array a.
Output
Print one integer — the minimum possible instability of the array if you have to remove exactly one element from the array a.
Examples
Input
4
1 3 3 7
Output
2
Input
2
1 100000
Output
0
Note
In the first example you can remove 7 then instability of the remaining array will be 3 - 1 = 2.
In the second example you can remove either 1 or 100000 then instability of the remaining array will be 100000 - 100000 = 0 and 1 - 1 = 0 correspondingly.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[100001];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
sort(a, a + n);
int x1 = a[n - 1] - a[0];
int y1 = a[n - 2] - a[0];
int x2 = a[n - 1] - a[1];
cout << min(x1, min(y1, x2));
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Celebrating the new year, many people post videos of falling dominoes; Here's a list of them: https://www.youtube.com/results?search_query=New+Years+Dominos
User ainta, who lives in a 2D world, is going to post a video as well.
There are n dominoes on a 2D Cartesian plane. i-th domino (1 ≤ i ≤ n) can be represented as a line segment which is parallel to the y-axis and whose length is li. The lower point of the domino is on the x-axis. Let's denote the x-coordinate of the i-th domino as pi. Dominoes are placed one after another, so p1 < p2 < ... < pn - 1 < pn holds.
User ainta wants to take a video of falling dominoes. To make dominoes fall, he can push a single domino to the right. Then, the domino will fall down drawing a circle-shaped orbit until the line segment totally overlaps with the x-axis.
<image>
Also, if the s-th domino touches the t-th domino while falling down, the t-th domino will also fall down towards the right, following the same procedure above. Domino s touches domino t if and only if the segment representing s and t intersects.
<image>
See the picture above. If he pushes the leftmost domino to the right, it falls down, touching dominoes (A), (B) and (C). As a result, dominoes (A), (B), (C) will also fall towards the right. However, domino (D) won't be affected by pushing the leftmost domino, but eventually it will fall because it is touched by domino (C) for the first time.
<image>
The picture above is an example of falling dominoes. Each red circle denotes a touch of two dominoes.
User ainta has q plans of posting the video. j-th of them starts with pushing the xj-th domino, and lasts until the yj-th domino falls. But sometimes, it could be impossible to achieve such plan, so he has to lengthen some dominoes. It costs one dollar to increase the length of a single domino by 1. User ainta wants to know, for each plan, the minimum cost needed to achieve it. Plans are processed independently, i. e. if domino's length is increased in some plan, it doesn't affect its length in other plans. Set of dominos that will fall except xj-th domino and yj-th domino doesn't matter, but the initial push should be on domino xj.
Input
The first line contains an integer n (2 ≤ n ≤ 2 × 105)— the number of dominoes.
Next n lines describe the dominoes. The i-th line (1 ≤ i ≤ n) contains two space-separated integers pi, li (1 ≤ pi, li ≤ 109)— the x-coordinate and the length of the i-th domino. It is guaranteed that p1 < p2 < ... < pn - 1 < pn.
The next line contains an integer q (1 ≤ q ≤ 2 × 105) — the number of plans.
Next q lines describe the plans. The j-th line (1 ≤ j ≤ q) contains two space-separated integers xj, yj (1 ≤ xj < yj ≤ n). It means the j-th plan is, to push the xj-th domino, and shoot a video until the yj-th domino falls.
Output
For each plan, print a line containing the minimum cost needed to achieve it. If no cost is needed, print 0.
Examples
Input
6
1 5
3 3
4 4
9 2
10 1
12 1
4
1 2
2 4
2 5
2 6
Output
0
1
1
2
Note
Consider the example. The dominoes are set like the picture below.
<image>
Let's take a look at the 4th plan. To make the 6th domino fall by pushing the 2nd domino, the length of the 3rd domino (whose x-coordinate is 4) should be increased by 1, and the 5th domino (whose x-coordinate is 9) should be increased by 1 (other option is to increase 4th domino instead of 5th also by 1). Then, the dominoes will fall like in the picture below. Each cross denotes a touch between two dominoes.
<image> <image> <image> <image> <image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <class T1, class T2>
inline istream& operator>>(istream& fin, pair<T1, T2>& pr) {
fin >> pr.first >> pr.second;
return fin;
}
template <class T0, class T1, class T2>
inline istream& operator>>(istream& fin, tuple<T0, T1, T2>& t) {
fin >> get<0>(t) >> get<1>(t) >> get<2>(t);
return fin;
}
template <class T>
inline istream& operator>>(istream& fin, vector<T>& a) {
if (!a.size()) {
size_t n;
fin >> n;
a.resize(n);
}
for (auto& u : a) fin >> u;
return fin;
}
int build_tree(const int x, const int y, const int l, const int r,
const size_t id, vector<int>& tree, const vector<int>& leaf) {
if (y < leaf[l] + 1 || leaf[r] < x + 1) return 0;
int inc = 0;
if (x < leaf[l] + 1 && leaf[r] < y + 1)
inc = (leaf[r] - leaf[l]) - tree[id];
else if (tree[id] != leaf[r] - leaf[l]) {
const auto mid = (l + r) >> 1;
inc = build_tree(x, y, l, mid, 2 * id + 1, tree, leaf) +
build_tree(x, y, mid, r, 2 * id + 2, tree, leaf);
}
tree[id] += inc;
return inc;
}
int query_tree(const int x, const int y, const int l, const int r,
const size_t id, const vector<int>& tree,
const vector<int>& leaf) {
if (y < leaf[l] + 1 || leaf[r] < x + 1) return 0;
if (x < leaf[l] + 1 && leaf[r] < y + 1) return tree[id];
if (tree[id] == leaf[r] - leaf[l]) return min(y, leaf[r]) - max(x, leaf[l]);
const auto mid = (l + r) >> 1;
return query_tree(x, y, l, mid, 2 * id + 1, tree, leaf) +
query_tree(x, y, mid, r, 2 * id + 2, tree, leaf);
}
void e500() {
vector<pair<int, int> > a;
vector<pair<size_t, size_t> > query;
cin >> a >> query;
vector<int> leaf;
leaf.reserve(a.size());
for (auto& pr : a) {
leaf.push_back(pr.first);
leaf.push_back(pr.first + pr.second);
pr.second += pr.first;
}
sort(begin(leaf), end(leaf));
leaf.erase(unique(begin(leaf), end(leaf)), end(leaf));
;
vector<size_t> idx(query.size());
iota(begin(idx), end(idx), 0);
const auto comp = [&query](const size_t i, const size_t j) {
return query[i] > query[j];
};
sort(begin(idx), end(idx), comp);
vector<int> soln(query.size());
vector<int> tree(leaf.size() * 4);
auto iter = a.rbegin();
for (const auto i : idx) {
const auto x = a[query[i].first - 1].first;
const auto y = a[query[i].second - 1].first;
for (; iter != a.rend() && x < iter->first + 1; ++iter)
build_tree(iter->first, iter->second, 0, leaf.size() - 1, 0, tree, leaf);
soln[i] = y - x - query_tree(x, y, 0, leaf.size() - 1, 0, tree, leaf);
}
copy(begin(soln), end(soln), ostream_iterator<int>(cout, "\n"));
}
int main(const int argc, char* argv[]) {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
e500();
return EXIT_SUCCESS;
}
``` |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.