text
stringlengths 424
69.5k
|
---|
### Prompt
Please create a solution in Cpp to the following problem:
You're given the centers of three equal sides of a strictly convex tetragon. Your task is to restore the initial tetragon.
Input
The first input line contains one number T — amount of tests (1 ≤ T ≤ 5·104). Each of the following T lines contains numbers x1, y1, x2, y2, x3, y3 — coordinates of different points that are the centers of three equal sides (non-negative integer numbers, not exceeding 10).
Output
For each test output two lines. If the required tetragon exists, output in the first line YES, in the second line — four pairs of numbers — coordinates of the polygon's vertices in clockwise or counter-clockwise order. Don't forget, please, that the tetragon should be strictly convex, i.e. no 3 of its points lie on one line. Output numbers with 9 characters after a decimal point.
If the required tetragon doen't exist, output NO in the first line, and leave the second line empty.
Examples
Input
3
1 1 2 2 3 3
0 1 1 0 2 2
9 3 7 9 9 8
Output
NO
YES
3.5 1.5 0.5 2.5 -0.5 -0.5 2.5 0.5
NO
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int m, n, j, k, l, i, o, p, __t, X1, Y1, X2, Y2, X3, Y3;
double ax1, ay1, ax2, ax3, ax4, ay2, ay3, ay4;
char ch;
void read(int &a) {
for (ch = getchar(); (ch < '0' || ch > '9') && (ch != '-'); ch = getchar())
;
if (ch == '-')
a = 0, __t = -1;
else
a = ch - '0', __t = 1;
for (ch = getchar(); ch >= '0' && ch <= '9'; ch = getchar())
a = a * 10 + ch - '0';
a *= __t;
}
double f(int x11, int x12, int x21, int x22) { return x11 * x22 - x12 * x21; }
bool cut(double X1, double Y1, double X2, double Y2, double X3, double Y3,
double X4, double Y4) {
double xj1 = (X3 - X1) * (Y2 - Y1) - (Y3 - Y1) * (X2 - X1);
double xj2 = (X4 - X1) * (Y2 - Y1) - (Y4 - Y1) * (X2 - X1);
if (xj1 * xj2 <= 0) return 1;
return 0;
}
bool solve(int X1, int Y1, int X2, int Y2, int X3, int Y3) {
int X4 = 2 * X2 - X3;
int Y4 = 2 * Y2 - Y3;
int A1 = 2 * (X1 - X4), B1 = 2 * (Y1 - Y4),
C1 = X1 * X1 + Y1 * Y1 - X4 * X4 - Y4 * Y4;
int A2 = 2 * (X2 - X4), B2 = 2 * (Y2 - Y4),
C2 = X2 * X2 + Y2 * Y2 - X4 * X4 - Y4 * Y4;
double _x2 = f(C1, B1, C2, B2) / f(A1, B1, A2, B2);
double _y2 = f(A1, C1, A2, C2) / f(A1, B1, A2, B2);
double _x1 = 2 * X1 - _x2;
double _y1 = 2 * Y1 - _y2;
double _x3 = 2 * X2 - _x2;
double _y3 = 2 * Y2 - _y2;
double _x4 = 2 * X3 - _x3;
double _y4 = 2 * Y3 - _y3;
if ((_x1 - _x4) * (_y3 - _y4) == (_y1 - _y4) * (_x3 - _x4)) return 0;
if (cut(_x1, _y1, _x2, _y2, _x3, _y3, _x4, _y4)) return 0;
if (cut(_x2, _y2, _x3, _y3, _x4, _y4, _x1, _y1)) return 0;
double xj1 = (_x1 - _x2) * (_y2 - _y3) - (_x2 - _x3) * (_y1 - _y2);
double xj2 = (_x2 - _x3) * (_y3 - _y4) - (_x3 - _x4) * (_y2 - _y3);
double xj3 = (_x3 - _x4) * (_y4 - _y1) - (_x4 - _x1) * (_y3 - _y4);
double xj4 = (_x4 - _x1) * (_y1 - _y2) - (_x1 - _x2) * (_y4 - _y1);
if (fabs(xj1) < 1e-8 || fabs(xj2) < 1e-8 || fabs(xj3) < 1e-8 ||
fabs(xj4) < 1e-8)
return 0;
bool pos = 0;
if (xj1 < 0) pos = 1;
if ((pos != (xj2 < 0)) || (pos != (xj3 < 0)) || (pos != (xj4 < 0))) return 0;
ax1 = _x1;
ax2 = _x2;
ax3 = _x3;
ax4 = _x4;
ay1 = _y1;
ay2 = _y2;
ay3 = _y3;
ay4 = _y4;
return 1;
}
int main() {
read(m);
for (int i = 1; i <= m; i++) {
read(X1), read(Y1), read(X2), read(Y2), read(X3), read(Y3);
if ((X2 - X1) * (Y3 - Y1) == (Y2 - Y1) * (X3 - X1)) {
printf("NO\n\n");
continue;
}
if (solve(X1, Y1, X2, Y2, X3, Y3) || solve(X1, Y1, X3, Y3, X2, Y2) ||
solve(X2, Y2, X1, Y1, X3, Y3))
printf("YES\n%.9lf %.9lf %.9lf %.9lf %.9lf %.9lf %.9lf %.9lf\n", ax1, ay1,
ax2, ay2, ax3, ay3, ax4, ay4);
else
printf("NO\n\n");
}
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of piles.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_1, a_2, …, a_n ≤ 10^9), which mean the i-th pile has a_i stones.
Output
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
Examples
Input
1
0
Output
cslnb
Input
2
1 0
Output
cslnb
Input
2
2 2
Output
sjfnb
Input
3
2 3 1
Output
sjfnb
Note
In the first example, Tokitsukaze cannot take any stone, so CSL will win.
In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.
In the third example, Tokitsukaze will win. Here is one of the optimal ways:
* Firstly, Tokitsukaze can choose the first pile and take a stone from that pile.
* Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately.
* Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose.
In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> a(n);
map<int, int> mp;
for (int i = 0; i < n; i++) {
cin >> a[i];
mp[a[i]]++;
}
sort(a.begin(), a.end());
int cnt = 0;
map<int, int>::iterator it;
for (it = mp.begin(); it != mp.end(); it++) {
if (it->second > 2) {
cout << "cslnb" << endl;
return 0;
} else if (it->second == 2) {
if (mp[it->first - 1] > 0) {
cout << "cslnb" << endl;
return 0;
}
if (it->first == 0) {
cout << "cslnb" << endl;
return 0;
}
cnt++;
}
}
if (cnt >= 2) {
cout << "cslnb" << endl;
return 0;
}
int sum = 0;
for (int i = 0; i < n; i++) sum += a[i];
sum -= ((n * (n - 1)) / 2);
if (sum % 2)
cout << "sjfnb\n";
else
cout << "cslnb\n";
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Medicine faculty of Berland State University has just finished their admission campaign. As usual, about 80\% of applicants are girls and majority of them are going to live in the university dormitory for the next 4 (hopefully) years.
The dormitory consists of n rooms and a single mouse! Girls decided to set mouse traps in some rooms to get rid of the horrible monster. Setting a trap in room number i costs c_i burles. Rooms are numbered from 1 to n.
Mouse doesn't sit in place all the time, it constantly runs. If it is in room i in second t then it will run to room a_i in second t + 1 without visiting any other rooms inbetween (i = a_i means that mouse won't leave room i). It's second 0 in the start. If the mouse is in some room with a mouse trap in it, then the mouse get caught into this trap.
That would have been so easy if the girls actually knew where the mouse at. Unfortunately, that's not the case, mouse can be in any room from 1 to n at second 0.
What it the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from?
Input
The first line contains as single integers n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of rooms in the dormitory.
The second line contains n integers c_1, c_2, ..., c_n (1 ≤ c_i ≤ 10^4) — c_i is the cost of setting the trap in room number i.
The third line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — a_i is the room the mouse will run to the next second after being in room i.
Output
Print a single integer — the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from.
Examples
Input
5
1 2 3 2 10
1 3 4 3 3
Output
3
Input
4
1 10 2 10
2 4 2 2
Output
10
Input
7
1 1 1 1 1 1 1
2 2 2 3 6 7 6
Output
2
Note
In the first example it is enough to set mouse trap in rooms 1 and 4. If mouse starts in room 1 then it gets caught immideately. If mouse starts in any other room then it eventually comes to room 4.
In the second example it is enough to set mouse trap in room 2. If mouse starts in room 2 then it gets caught immideately. If mouse starts in any other room then it runs to room 2 in second 1.
Here are the paths of the mouse from different starts from the third example:
* 1 → 2 → 2 → ...;
* 2 → 2 → ...;
* 3 → 2 → 2 → ...;
* 4 → 3 → 2 → 2 → ...;
* 5 → 6 → 7 → 6 → ...;
* 6 → 7 → 6 → ...;
* 7 → 6 → 7 → ...;
So it's enough to set traps in rooms 2 and 6.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool cmp(const pair<long long, long long> &a,
const pair<long long, long long> &b) {
return (a.first > b.first);
}
long long power(long long x, long long y) {
long long res = 1;
x = x;
if (x == 0) return 0;
while (y > 0) {
if (y & 1) res = (res * x);
y = y >> 1;
x = (x * x);
}
return res;
}
long long power2(long long x, long long y, long long p) {
long long res = 1;
x = x % p;
if (x == 0) return 0;
while (y > 0) {
if (y & 1) res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
long long n, a[200010], c[200010], vis[200010], ans;
int main() {
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long i, j;
cin >> n;
for (i = 1; i <= n; i++) cin >> c[i];
for (i = 1; i <= n; i++) cin >> a[i];
for (i = 1; i <= n; i++) {
long long x = i, v, mn;
while (!vis[x]) {
vis[x] = i;
x = a[x];
}
if (vis[x] != i) continue;
v = x;
mn = c[x];
while (a[x] != v) {
x = a[x];
mn = min(mn, c[x]);
};
ans += mn;
}
cout << ans;
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Snuke found a record of a tree with N vertices in ancient ruins. The findings are as follows:
* The vertices of the tree were numbered 1,2,...,N, and the edges were numbered 1,2,...,N-1.
* Edge i connected Vertex a_i and b_i.
* The length of each edge was an integer between 1 and 10^{18} (inclusive).
* The sum of the shortest distances from Vertex i to Vertex 1,...,N was s_i.
From the information above, restore the length of each edge. The input guarantees that it is possible to determine the lengths of the edges consistently with the record. Furthermore, it can be proved that the length of each edge is uniquely determined in such a case.
Constraints
* 2 \leq N \leq 10^{5}
* 1 \leq a_i,b_i \leq N
* 1 \leq s_i \leq 10^{18}
* The given graph is a tree.
* All input values are integers.
* It is possible to consistently restore the lengths of the edges.
* In the restored graph, the length of each edge is an integer between 1 and 10^{18} (inclusive).
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
s_1 s_2 ... s_{N}
Output
Print N-1 lines. The i-th line must contain the length of Edge i.
Examples
Input
4
1 2
2 3
3 4
8 6 6 8
Output
1
2
1
Input
5
1 2
1 3
1 4
1 5
10 13 16 19 22
Output
1
2
3
4
Input
15
9 10
9 15
15 4
4 13
13 2
13 11
2 14
13 6
11 1
1 12
12 3
12 7
2 5
14 8
1154 890 2240 883 2047 2076 1590 1104 1726 1791 1091 1226 841 1000 901
Output
5
75
2
6
7
50
10
95
9
8
78
28
89
8
### Response
```cpp
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#define SIZE 100005
using namespace std;
typedef long long int ll;
struct edge
{
int to,id;
edge(int to=0,int id=0):to(to),id(id){}
};
vector <edge> vec[SIZE];
int nd[SIZE];
int A[SIZE],B[SIZE];
ll C[SIZE];
ll sum[SIZE];
ll all;
void dfs(int v=0,int p=-1)
{
nd[v]=1;
for(int i=0;i<vec[v].size();i++)
{
int to=vec[v][i].to;
if(to!=p)
{
dfs(to,v);
nd[v]+=nd[to];
}
}
}
void dfs2(int v=0,int p=-1,ll d=0)
{
all+=d;
for(int i=0;i<vec[v].size();i++)
{
edge e=vec[v][i];
if(e.to!=p)
{
dfs2(e.to,v,d+C[e.id]);
}
}
}
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n-1;i++)
{
scanf("%d %d",&A[i],&B[i]);
A[i]--,B[i]--;
vec[A[i]].push_back(edge(B[i],i));
vec[B[i]].push_back(edge(A[i],i));
C[i]=-1;
}
for(int i=0;i<n;i++) scanf("%lld",&sum[i]);
dfs();
int a=-1,b=-1;
for(int i=0;i<n-1;i++)
{
if(nd[A[i]]<nd[B[i]]) swap(A[i],B[i]);
//A[i] : parent of B[i]
if(sum[A[i]]!=sum[B[i]])
{
//A[i]=a+b+nd[b]*C[i]
//B[i]=a+b+(n-nd[b])*C[i]
C[i]=(sum[A[i]]-sum[B[i]])/(ll) (2*nd[B[i]]-n);
}
else
{
a=A[i];
b=B[i];
}
}
if(a!=-1)
{
all=0;
dfs2(b,a,0);
dfs2(a,b,0);
for(int i=0;i<n-1;i++)
{
if(C[i]==-1)
{
C[i]=(sum[A[i]]-all)/(ll) nd[B[i]];
}
}
}
for(int i=0;i<n-1;i++) printf("%lld\n",C[i]);
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Note that the difference between easy and hard versions is that in hard version unavailable cells can become available again and in easy version can't. You can make hacks only if all versions are solved.
Ildar and Ivan are tired of chess, but they really like the chessboard, so they invented a new game. The field is a chessboard 2n × 2m: it has 2n rows, 2m columns, and the cell in row i and column j is colored white if i+j is even, and is colored black otherwise.
The game proceeds as follows: Ildar marks some of the white cells of the chessboard as unavailable, and asks Ivan to place n × m kings on the remaining white cells in such way, so that there are no kings attacking each other. A king can attack another king if they are located in the adjacent cells, sharing an edge or a corner.
Ildar would like to explore different combinations of cells. Initially all cells are marked as available, and then he has q queries. In each query he marks a cell as unavailable. After each query he would like to know whether it is possible to place the kings on the available cells in a desired way. Please help him!
Input
The first line of input contains three integers n, m, q (1 ≤ n, m, q ≤ 200 000) — the size of the board and the number of queries.
q lines follow, each of them contains a description of a query: two integers i and j, denoting a white cell (i, j) on the board (1 ≤ i ≤ 2n, 1 ≤ j ≤ 2m, i + j is even) that becomes unavailable. It's guaranteed, that each cell (i, j) appears in input at most once.
Output
Output q lines, i-th line should contain answer for a board after i queries of Ildar. This line should contain "YES" if it is possible to place the kings on the available cells in the desired way, or "NO" otherwise.
Examples
Input
1 3 3
1 1
1 5
2 4
Output
YES
YES
NO
Input
3 2 7
4 2
6 4
1 3
2 2
2 4
4 4
3 1
Output
YES
YES
NO
NO
NO
NO
NO
Note
In the first example case after the second query only cells (1, 1) and (1, 5) are unavailable. Then Ivan can place three kings on cells (2, 2), (2, 4) and (2, 6).
After the third query three cells (1, 1), (1, 5) and (2, 4) are unavailable, so there remain only 3 available cells: (2, 2), (1, 3) and (2, 6). Ivan can not put 3 kings on those cells, because kings on cells (2, 2) and (1, 3) attack each other, since these cells share a corner.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
set<int> stl[maxn], str[maxn];
map<pair<int, int>, int> mp;
int n, m, q;
namespace Segtree {
int mx[maxn << 2], mi[maxn << 2], eleg[maxn << 2];
void pushup(int o) {
int lch = o * 2, rch = o * 2 + 1;
mx[o] = max(mx[lch], mx[rch]);
mi[o] = min(mi[lch], mi[rch]);
eleg[o] = (eleg[lch] | eleg[rch]);
eleg[o] |= (mx[rch] >= mi[lch]);
return;
}
void build(int o, int L, int R) {
int lch = o * 2, rch = o * 2 + 1;
if (L == R) {
mx[o] = 0;
mi[o] = m + 1;
eleg[o] = 0;
return;
}
int mid = (L + R) / 2;
build(lch, L, mid);
build(rch, mid + 1, R);
pushup(o);
}
void update(int o, int L, int R, int pos) {
int lch = o * 2, rch = o * 2 + 1;
if (L == R) {
if (str[L].empty())
mx[o] = 0;
else
mx[o] = *str[L].rbegin();
if (stl[L].empty())
mi[o] = m + 1;
else
mi[o] = *stl[L].begin();
eleg[o] = (mx[o] >= mi[o] ? 1 : 0);
return;
}
int mid = (L + R) / 2;
if (pos <= mid)
update(lch, L, mid, pos);
else
update(rch, mid + 1, R, pos);
pushup(o);
return;
}
}; // namespace Segtree
using namespace Segtree;
int main() {
scanf("%d%d%d", &n, &m, &q);
build(1, 1, n);
while (q--) {
int x, y;
scanf("%d%d", &x, &y);
++x;
x /= 2;
++y;
if (y & 1) {
if (str[x].count(y / 2))
str[x].erase(y / 2);
else
str[x].insert(y / 2);
} else {
if (stl[x].count(y / 2))
stl[x].erase(y / 2);
else
stl[x].insert(y / 2);
}
update(1, 1, n, x);
printf("%s\n", eleg[1] ? "NO" : "YES");
}
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Piet is one of the most known visual esoteric programming languages. The programs in Piet are constructed from colorful blocks of pixels and interpreted using pretty complicated rules. In this problem we will use a subset of Piet language with simplified rules.
The program will be a rectangular image consisting of colored and black pixels. The color of each pixel will be given by an integer number between 0 and 9, inclusive, with 0 denoting black. A block of pixels is defined as a rectangle of pixels of the same color (not black). It is guaranteed that all connected groups of colored pixels of the same color will form rectangular blocks. Groups of black pixels can form arbitrary shapes.
The program is interpreted using movement of instruction pointer (IP) which consists of three parts:
* current block pointer (BP); note that there is no concept of current pixel within the block;
* direction pointer (DP) which can point left, right, up or down;
* block chooser (CP) which can point to the left or to the right from the direction given by DP; in absolute values CP can differ from DP by 90 degrees counterclockwise or clockwise, respectively.
Initially BP points to the block which contains the top-left corner of the program, DP points to the right, and CP points to the left (see the orange square on the image below).
One step of program interpretation changes the state of IP in a following way. The interpreter finds the furthest edge of the current color block in the direction of the DP. From all pixels that form this edge, the interpreter selects the furthest one in the direction of CP. After this, BP attempts to move from this pixel into the next one in the direction of DP. If the next pixel belongs to a colored block, this block becomes the current one, and two other parts of IP stay the same. It the next pixel is black or outside of the program, BP stays the same but two other parts of IP change. If CP was pointing to the left, now it points to the right, and DP stays the same. If CP was pointing to the right, now it points to the left, and DP is rotated 90 degrees clockwise.
This way BP will never point to a black block (it is guaranteed that top-left pixel of the program will not be black).
You are given a Piet program. You have to figure out which block of the program will be current after n steps.
Input
The first line of the input contains two integer numbers m (1 ≤ m ≤ 50) and n (1 ≤ n ≤ 5·107). Next m lines contain the rows of the program. All the lines have the same length between 1 and 50 pixels, and consist of characters 0-9. The first character of the first line will not be equal to 0.
Output
Output the color of the block which will be current after n steps of program interpretation.
Examples
Input
2 10
12
43
Output
1
Input
3 12
1423
6624
6625
Output
6
Input
5 9
10345
23456
34567
45678
56789
Output
5
Note
In the first example IP changes in the following way. After step 1 block 2 becomes current one and stays it after two more steps. After step 4 BP moves to block 3, after step 7 — to block 4, and finally after step 10 BP returns to block 1.
<image>
The sequence of states of IP is shown on the image: the arrows are traversed clockwise, the main arrow shows direction of DP, the side one — the direction of CP.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
char a[55][55];
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
int n, T, m;
inline int valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; }
int cyc[55][55][4][2] = {};
int main(void) {
scanf("%d%d", &n, &T);
for (int i = 0; i < n; i++) scanf("%s", a[i]);
m = strlen(a[0]);
int x = 0, y = 0, DP = 0, CP = 0;
int Cx = -dy[DP] * (CP ? -1 : 1), Cy = dx[DP] * (CP ? -1 : 1);
int Dx = dx[DP], Dy = dy[DP];
for (int step = 1; step <= T; step++) {
while (valid(x + Dx, y + Dy) && a[x + Dx][y + Dy] == a[x][y])
x += Dx, y += Dy;
while (valid(x + Cx, y + Cy) && a[x + Cx][y + Cy] == a[x][y])
x += Cx, y += Cy;
if (cyc[x][y][DP][CP]) {
int ii = step - cyc[x][y][DP][CP];
while (step + ii <= T) step += ii;
} else
cyc[x][y][DP][CP] = step;
if (!valid(x + Dx, y + Dy) || a[x + Dx][y + Dy] == '0') {
if (CP == 0)
CP = 1;
else if (CP == 1) {
DP = (DP + 1) % 4;
CP = 0;
}
Cx = -dy[DP] * (CP ? -1 : 1), Cy = dx[DP] * (CP ? -1 : 1);
Dx = dx[DP], Dy = dy[DP];
} else
x += Dx, y += Dy;
}
printf("%c\n", a[x][y]);
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
You are given an unweighted tree with n vertices. Then n - 1 following operations are applied to the tree. A single operation consists of the following steps:
1. choose two leaves;
2. add the length of the simple path between them to the answer;
3. remove one of the chosen leaves from the tree.
Initial answer (before applying operations) is 0. Obviously after n - 1 such operations the tree will consist of a single vertex.
Calculate the maximal possible answer you can achieve, and construct a sequence of operations that allows you to achieve this answer!
Input
The first line contains one integer number n (2 ≤ n ≤ 2·105) — the number of vertices in the tree.
Next n - 1 lines describe the edges of the tree in form ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi). It is guaranteed that given graph is a tree.
Output
In the first line print one integer number — maximal possible answer.
In the next n - 1 lines print the operations in order of their applying in format ai, bi, ci, where ai, bi — pair of the leaves that are chosen in the current operation (1 ≤ ai, bi ≤ n), ci (1 ≤ ci ≤ n, ci = ai or ci = bi) — choosen leaf that is removed from the tree in the current operation.
See the examples for better understanding.
Examples
Input
3
1 2
1 3
Output
3
2 3 3
2 1 1
Input
5
1 2
1 3
2 4
2 5
Output
9
3 5 5
4 3 3
4 1 1
4 2 2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long maxn = 2e5 + 7;
const long long mod = 1e9 + 9;
const long long INF = 1e9 + 7;
const long long mlog = 21;
const long long SQ = 400;
struct NODE {
long long a;
long long b;
long long c;
};
vector<long long> adj[maxn];
vector<long long> leaves;
long long n;
long long par[mlog][maxn];
long long h[maxn];
long long loss[maxn];
long long vr = 1, ur;
void dfs(long long v, long long pr = -1) {
for (long long u : adj[v]) {
if (u != pr) {
h[u] = h[v] + 1, par[0][u] = v;
if (h[u] > h[vr]) vr = u;
dfs(u, v);
}
}
}
void pre_process() {
for (long long j = 1; j < mlog; j++)
for (long long i = 1; i <= n; i++) par[j][i] = par[j - 1][par[j - 1][i]];
}
long long getpar(long long v, long long l) {
for (long long j = 0; j < mlog; j++)
if (l & (1 << j)) v = par[j][v];
return v;
}
long long LCA(long long u, long long v) {
if (h[u] < h[v]) swap(u, v);
u = getpar(u, h[u] - h[v]);
if (u == v) return v;
for (long long j = mlog - 1; j >= 0; j--) {
long long p1 = par[j][u];
long long p2 = par[j][v];
if (p1 != p2) u = p1, v = p2;
}
return par[0][v];
}
pair<long long, long long> ADD(long long v) {
long long lcaU = LCA(ur, v);
long long lcaV = LCA(vr, v);
return ((h[v] + h[ur] - 2 * h[lcaU] > h[v] + h[vr] - 2 * h[lcaV])
? (make_pair(ur, h[v] + h[ur] - 2 * h[lcaU]))
: make_pair(vr, h[v] + h[vr] - 2 * h[lcaV]));
}
long long mark[maxn];
long long ans = 0;
vector<NODE> path;
void solve() {
dfs(1);
h[vr] = 0;
ur = vr;
par[0][vr] = 0;
dfs(vr);
long long x = vr;
while (x != 0) {
mark[x] = true;
x = par[0][x];
}
pre_process();
for (long long i = 1; i <= n; i++)
if (adj[i].size() == 1 && !mark[i]) leaves.push_back(i);
long long i = 0;
long long m = leaves.size();
while (i < m) {
if (leaves[i] == -1) {
i++;
continue;
}
long long v = leaves[i];
loss[par[0][v]]++;
pair<long long, long long> p1 = ADD(v);
ans += p1.second;
path.push_back({p1.first, v, v});
if (!mark[par[0][v]] && adj[par[0][v]].size() - loss[par[0][v]] == 1)
leaves[i] = par[0][v];
else
leaves[i] = -1;
}
x = vr;
while (x != ur) {
ans += h[x];
path.push_back({ur, x, x});
x = par[0][x];
}
}
int32_t main() {
long long t = 1;
while (t--) {
scanf("%lld", &n);
for (long long i = 0; i < n - 1; i++) {
long long u, v;
scanf("%lld%lld", &u, &v);
adj[u].push_back(v);
adj[v].push_back(u);
}
solve();
cout << ans << "\n";
for (auto v : path) printf("%lld %lld %lld\n", v.a, v.b, v.c);
}
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
The ICPC committee would like to have its meeting as soon as possible to address every little issue of the next contest. However, members of the committee are so busy maniacally developing (possibly useless) programs that it is very difficult to arrange their schedules for the meeting. So, in order to settle the meeting date, the chairperson requested every member to send back a list of convenient dates by E-mail. Your mission is to help the chairperson, who is now dedicated to other issues of the contest, by writing a program that chooses the best date from the submitted lists. Your program should find the date convenient for the most members. If there is more than one such day, the earliest is the best.
Input
The input has multiple data sets, each starting with a line containing the number of committee members and the quorum of the meeting.
> N Q
Here, N, meaning the size of the committee, and Q meaning the quorum, are positive integers. N is less than 50, and, of course, Q is less than or equal to N.
N lines follow, each describing convenient dates for a committee member in the following format.
> M Date1 Date2 ... DateM
Here, M means the number of convenient dates for the member, which is an integer greater than or equal to zero. The remaining items in the line are his/her dates of convenience, which are positive integers less than 100, that is, 1 means tomorrow, 2 means the day after tomorrow, and so on. They are in ascending order without any repetition and separated by a space character. Lines have neither leading nor trailing spaces.
A line containing two zeros indicates the end of the input.
Output
For each data set, print a single line containing the date number convenient for the largest number of committee members. If there is more than one such date, print the earliest. However, if no dates are convenient for more than or equal to the quorum number of members, print 0 instead.
Example
Input
3 2
2 1 4
0
3 3 4 8
3 2
4 1 5 8 9
3 2 5 9
5 2 4 5 7 9
3 3
2 1 4
3 2 5 9
2 2 4
3 3
2 1 2
3 1 2 9
2 2 4
0 0
Output
4
5
0
2
### Response
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define all(c) (c).begin(), (c).end()
int main(){
int N, Q;
while(cin >> N >> Q, N|Q){
vector<int> date(100); date[0] = Q - 1;
while(N--){
int M;
cin >> M;
while(M--){
int d;
cin >> d;
date[d]++;
}
}
cout << max_element(all(date)) - date.begin() << '\n';
}
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers.
Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of n cities with m bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads.
The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning.
The gang is going to rob a bank! The bank is located in city 1. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city n. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan.
First of all the path which they are going to use on their way back from city 1 to their headquarters n must be as short as possible, since it is important to finish operation as fast as possible.
Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional.
If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation.
Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired).
Can you help Walter complete his task and gain the gang's trust?
Input
The first line of input contains two integers n, m (2 ≤ n ≤ 105, <image>), the number of cities and number of roads respectively.
In following m lines there are descriptions of roads. Each description consists of three integers x, y, z (1 ≤ x, y ≤ n, <image>) meaning that there is a road connecting cities number x and y. If z = 1, this road is working, otherwise it is not.
Output
In the first line output one integer k, the minimum possible number of roads affected by gang.
In the following k lines output three integers describing roads that should be affected. Each line should contain three integers x, y, z (1 ≤ x, y ≤ n, <image>), cities connected by a road and the new state of a road. z = 1 indicates that the road between cities x and y should be repaired and z = 0 means that road should be blown up.
You may output roads in any order. Each affected road should appear exactly once. You may output cities connected by a single road in any order. If you output a road, it's original state should be different from z.
After performing all operations accroding to your plan, there should remain working only roads lying on some certain shortest past between city 1 and n.
If there are multiple optimal answers output any.
Examples
Input
2 1
1 2 0
Output
1
1 2 1
Input
4 4
1 2 1
1 3 0
2 3 1
3 4 1
Output
3
1 2 0
1 3 1
2 3 0
Input
8 9
1 2 0
8 3 0
2 3 1
1 4 1
8 7 0
1 5 1
4 6 1
5 7 0
6 8 0
Output
3
2 3 0
1 5 0
6 8 1
Note
In the first test the only path is 1 - 2
In the second test the only shortest path is 1 - 3 - 4
In the third test there are multiple shortest paths but the optimal is 1 - 4 - 6 - 8
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct Node {
int node;
int dist;
int fixs;
Node() {}
Node(int node, int dist, int fixs) {
this->node = node;
this->dist = dist;
this->fixs = fixs;
}
};
int n;
int parentOf[100001];
int changesTo[100001];
int distanceTo[100001];
vector<Node> graph[100001];
set<pair<int, int> > toFix;
set<pair<int, int> > toBlow;
bool operator<(Node n1, Node n2) {
if (n1.dist == n2.dist) return n1.fixs > n2.fixs;
return n1.dist > n2.dist;
}
void DIJKSTRA(int source, int target) {
int current;
int newFixs;
int newDist;
priority_queue<Node> toVisit;
for (int i = 0; i < n; i++) {
parentOf[i] = -1;
changesTo[i] = INT_MAX;
distanceTo[i] = INT_MAX;
}
parentOf[source] = -2;
changesTo[source] = 0;
distanceTo[source] = 0;
toVisit.push(Node(source, distanceTo[source], changesTo[source]));
while (!toVisit.empty()) {
current = toVisit.top().node;
toVisit.pop();
for (Node child : graph[current]) {
newFixs = changesTo[current] + child.fixs;
newDist = distanceTo[current] + child.dist;
if (distanceTo[child.node] >= newDist) {
if (distanceTo[child.node] > newDist) {
parentOf[child.node] = current;
changesTo[child.node] = newFixs;
distanceTo[child.node] = newDist;
toVisit.push(
Node(child.node, distanceTo[child.node], changesTo[child.node]));
} else if (changesTo[child.node] > newFixs) {
parentOf[child.node] = current;
changesTo[child.node] = newFixs;
toVisit.push(
Node(child.node, distanceTo[child.node], changesTo[child.node]));
}
}
}
}
}
void getRoads() {
int node1;
int node2;
vector<pair<int, int> > fixes;
node1 = n - 1;
while (node1 != -2) {
node2 = parentOf[node1];
if (toFix.count({node1, node2}) != 0 || toFix.count({node2, node1}) != 0) {
toFix.erase({node1, node2});
toFix.erase({node2, node1});
fixes.push_back({node1, node2});
} else {
toBlow.erase({node1, node2});
toBlow.erase({node2, node1});
}
node1 = parentOf[node1];
}
printf("%d\n", fixes.size() + toBlow.size());
for (pair<int, int> road : fixes)
printf("%d %d %d\n", road.first + 1, road.second + 1, 1);
for (pair<int, int> road : toBlow)
printf("%d %d %d\n", road.first + 1, road.second + 1, 0);
}
int main() {
int m;
int x;
int y;
int z;
scanf("%d", &n);
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf("%d", &x);
scanf("%d", &y);
scanf("%d", &z);
x--;
y--;
z ^= 1;
graph[x].push_back(Node(y, 1, z));
graph[y].push_back(Node(x, 1, z));
if (z == 1) {
toFix.insert({x, y});
toFix.insert({y, x});
} else
toBlow.insert({x, y});
}
DIJKSTRA(0, n - 1);
getRoads();
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya got an array consisting of n numbers, it is the gift for his birthday. Now he wants to sort it in the non-decreasing order. However, a usual sorting is boring to perform, that's why Petya invented the following limitation: one can swap any two numbers but only if at least one of them is lucky. Your task is to sort the array according to the specified limitation. Find any possible sequence of the swaps (the number of operations in the sequence should not exceed 2n).
Input
The first line contains an integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n positive integers, not exceeding 109 — the array that needs to be sorted in the non-decreasing order.
Output
On the first line print number k (0 ≤ k ≤ 2n) — the number of the swaps in the sorting. On the following k lines print one pair of distinct numbers (a pair per line) — the indexes of elements to swap. The numbers in the array are numbered starting from 1. If it is impossible to sort the given sequence, print the single number -1.
If there are several solutions, output any. Note that you don't have to minimize k. Any sorting with no more than 2n swaps is accepted.
Examples
Input
2
4 7
Output
0
Input
3
4 2 1
Output
1
1 3
Input
7
77 66 55 44 33 22 11
Output
7
1 7
7 2
2 6
6 7
3 4
5 3
4 5
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
struct data {
int id, num, sortid;
};
data a[maxn];
int circle[maxn];
vector<pair<int, int> > path;
vector<pair<int, int> >::iterator ite;
bool lucky[maxn] = {0}, h[maxn] = {0};
bool cmp1(data a, data b) {
if (a.num == b.num)
return a.id < b.id;
else
return a.num < b.num;
}
bool cmp2(data a, data b) { return a.id < b.id; }
bool check(int);
void init();
void gao();
void output();
int n, totlucky, pos_lucky, confirm;
int minswap;
int main() {
init();
gao();
output();
return 0;
}
bool check(int n) {
while (n) {
if (n % 10 != 4 && n % 10 != 7) return false;
n /= 10;
}
return true;
}
void init() {
int i;
scanf("%d", &n);
totlucky = 0;
confirm = -1;
pos_lucky = -1;
for (i = 1; i <= n; i++) {
scanf("%d", &a[i].num);
a[i].id = i;
a[i].sortid = 0;
lucky[i] = check(a[i].num);
if (lucky[i]) {
totlucky++;
pos_lucky = i;
confirm = 0;
}
}
}
void gao() {
int head, tail, bp, i;
minswap = 0;
path.clear();
sort(a + 1, a + n + 1, cmp1);
head = 1;
while (head <= n) {
tail = head;
while (a[tail].num == a[head].num) tail++;
for (i = head; i < tail; i++)
if (a[i].id >= head && a[i].id < tail)
a[i].sortid = a[i].id, h[a[i].id] = 1;
bp = head;
for (i = head; i < tail; i++)
if (a[i].id < head || a[i].id >= tail) {
while (h[bp]) bp++;
a[i].sortid = bp;
h[bp] = 1;
}
head = tail;
}
sort(a + 1, a + n + 1, cmp2);
int j, cnt, havelucky, loc, _cnt;
for (i = 1; i <= n; i++)
if (h[i]) {
j = i;
cnt = 0;
havelucky = 0;
loc = -1;
while (h[j]) {
circle[cnt++] = j;
if (lucky[j]) havelucky = 1, loc = cnt - 1;
h[j] = 0;
j = a[j].sortid;
}
if (cnt == 1 || havelucky) {
minswap += cnt - 1;
j = loc;
_cnt = cnt;
while (_cnt-- > 1) {
path.push_back(make_pair(circle[j], circle[(j - 1 + cnt) % cnt]));
j = (j - 1 + cnt) % cnt;
}
if (!confirm && loc >= 0) {
confirm = 1;
pos_lucky = a[circle[loc]].sortid;
}
} else {
minswap += cnt + 1;
if (confirm < 0) return;
path.push_back(make_pair(pos_lucky, i));
j = 0;
_cnt = cnt;
while (_cnt-- > 1) {
path.push_back(make_pair(circle[j], circle[(j - 1 + cnt) % cnt]));
j = (j - 1 + cnt) % cnt;
}
path.push_back(make_pair(pos_lucky, a[i].sortid));
}
if (minswap > 2 * n) return;
}
}
void output() {
if (minswap && !totlucky)
printf("-1\n");
else if (minswap > 2 * n)
printf("-1\n");
else {
printf("%d\n", minswap);
for (ite = path.begin(); ite != path.end(); ite++)
printf("%d %d\n", ite->first, ite->second);
}
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
You are a warrior fighting against the machine god Thor.
Thor challenge you to solve the following problem:
There are n conveyors arranged in a line numbered with integers from 1 to n from left to right. Each conveyor has a symbol "<" or ">". The initial state of the conveyor i is equal to the i-th character of the string s. There are n+1 holes numbered with integers from 0 to n. The hole 0 is on the left side of the conveyor 1, and for all i ≥ 1 the hole i is on the right side of the conveyor i.
When a ball is on the conveyor i, the ball moves by the next rules:
If the symbol "<" is on the conveyor i, then:
* If i=1, the ball falls into the hole 0.
* If the symbol "<" is on the conveyor i-1, the ball moves to the conveyor i-1.
* If the symbol ">" is on the conveyor i-1, the ball falls into the hole i-1.
If the symbol ">" is on the conveyor i, then:
* If i=n, the ball falls into the hole n.
* If the symbol ">" is on the conveyor i+1, the ball moves to the conveyor i+1.
* If the symbol "<" is on the conveyor i+1, the ball falls into the hole i.
You should answer next q queries, each query is defined by the pair of integers l, r (1 ≤ l ≤ r ≤ n):
* First, for all conveyors l,l+1,...,r, the symbol "<" changes to ">" and vice versa. These changes remain for the next queries.
* After that, put one ball on each conveyor l,l+1,...,r. Then, each ball falls into some hole. Find the maximum number of balls in one hole. After the query all balls disappear and don't considered in the next queries.
Input
The first line contains two integers n, q (1 ≤ n ≤ 5 × 10^5 , 1 ≤ q ≤ 10^5).
The second line contains a string s of length n. It consists of characters "<" and ">".
Next q lines contain the descriptions of the queries, i-th of them contains two integers l, r (1 ≤ l ≤ r ≤ n), describing the i-th query.
Output
Print q lines, in the i-th of them print the answer to the i-th query.
Example
Input
5 6
><>><
2 4
3 5
1 5
1 3
2 4
1 5
Output
3
3
5
3
2
3
Note
* In the first query, the conveyors change to ">><<<". After that, put a ball on each conveyor \{2,3,4\}. All three balls fall into the hole 2. So the answer is 3.
* In the second query, the conveyors change to ">>>>>". After that, put a ball on each conveyor \{3,4,5\}. All three balls fall into the hole 5. So the answer is 3.
* In the third query, the conveyors change to "<<<<<". After that, put a ball on each conveyor \{1,2,3,4,5\}. All five balls fall into the hole 0. So the answer is 5.
* In the fourth query, the conveyors change to ">>><<". After that, put a ball on each conveyor \{1,2,3\}. All three balls fall into the hole 3. So the answer is 3.
* In the fifth query, the conveyors change to "><<><". After that, put a ball on each conveyor \{2,3,4\}. Two balls fall into the hole 1, and one ball falls into the hole 4. So, the answer is 2.
* In the sixth query, the conveyors change to "<>><>". After that, put a ball on each conveyor \{1,2,3,4,5\}. Three balls fall into the hole 3, one ball falls into the hole 0 and one ball falls into the hole 5. So, the answer is 3.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3fLL;
const double EPS = 1e-8;
const int MOD = 1000000007;
const int dy[] = {1, 0, -1, 0}, dx[] = {0, -1, 0, 1};
const int dy8[] = {1, 1, 0, -1, -1, -1, 0, 1},
dx8[] = {0, -1, -1, -1, 0, 1, 1, 1};
template <typename T, typename U>
inline bool chmax(T &a, U b) {
return a < b ? (a = b, true) : false;
}
template <typename T, typename U>
inline bool chmin(T &a, U b) {
return a > b ? (a = b, true) : false;
}
struct IOSetup {
IOSetup() {
cin.tie(nullptr);
ios_base::sync_with_stdio(false);
cout << fixed << setprecision(20);
}
} iosetup;
template <typename Monoid, typename OperatorMonoid = Monoid>
struct LazySegmentTree {
using MM = function<Monoid(Monoid, Monoid)>;
using MOI = function<Monoid(Monoid, OperatorMonoid, int)>;
using OO = function<OperatorMonoid(OperatorMonoid, OperatorMonoid)>;
LazySegmentTree(int sz, MM mm, MOI moi, OO oo, const Monoid M_UNITY,
const OperatorMonoid O_UNITY)
: mm(mm), moi(moi), oo(oo), M_UNITY(M_UNITY), O_UNITY(O_UNITY) {
init(sz);
dat.assign(n << 1, M_UNITY);
}
LazySegmentTree(const vector<Monoid> &a, MM mm, MOI moi, OO oo,
const Monoid M_UNITY, const OperatorMonoid O_UNITY)
: mm(mm), moi(moi), oo(oo), M_UNITY(M_UNITY), O_UNITY(O_UNITY) {
int a_sz = a.size();
init(a_sz);
dat.resize(n << 1);
for (int i = (0); i < (a_sz); ++i) dat[i + n] = a[i];
for (int i = n - 1; i > 0; --i) dat[i] = mm(dat[i << 1], dat[(i << 1) + 1]);
}
void update(int a, int b, OperatorMonoid val) { update(a, b, val, 1, 0, n); }
Monoid query(int a, int b) { return query(a, b, 1, 0, n); }
Monoid operator[](const int idx) { return query(idx, idx + 1); }
private:
int n = 1;
MM mm;
MOI moi;
OO oo;
const Monoid M_UNITY;
const OperatorMonoid O_UNITY;
vector<Monoid> dat;
vector<OperatorMonoid> lazy;
vector<bool> need_to_be_eval;
void init(int sz) {
while (n < sz) n <<= 1;
lazy.assign(n << 1, O_UNITY);
need_to_be_eval.assign(n << 1, false);
}
inline void evaluate(int node, int len) {
if (need_to_be_eval[node]) {
dat[node] = moi(dat[node], lazy[node], len);
if (node < n) {
lazy[node << 1] = oo(lazy[node << 1], lazy[node]);
need_to_be_eval[node << 1] = true;
lazy[(node << 1) + 1] = oo(lazy[(node << 1) + 1], lazy[node]);
need_to_be_eval[(node << 1) + 1] = true;
}
lazy[node] = O_UNITY;
need_to_be_eval[node] = false;
}
}
void update(int a, int b, OperatorMonoid val, int node, int left, int right) {
evaluate(node, right - left);
if (right <= a || b <= left) return;
if (a <= left && right <= b) {
lazy[node] = oo(lazy[node], val);
need_to_be_eval[node] = true;
evaluate(node, right - left);
} else {
update(a, b, val, node << 1, left, (left + right) >> 1);
update(a, b, val, (node << 1) + 1, (left + right) >> 1, right);
dat[node] = mm(dat[node << 1], dat[(node << 1) + 1]);
}
}
Monoid query(int a, int b, int node, int left, int right) {
evaluate(node, right - left);
if (right <= a || b <= left) return M_UNITY;
if (a <= left && right <= b) return dat[node];
return mm(query(a, b, node << 1, left, (left + right) >> 1),
query(a, b, (node << 1) + 1, (left + right) >> 1, right));
}
};
int main() {
int n, q;
cin >> n >> q;
string s;
cin >> s;
struct Node {
int l0, l1, l01, l10, r0, r1, r10, r01, len, ans, rev;
Node(int l0 = 0, int l1 = 0, int l01 = 0, int l10 = 0, int r0 = 0,
int r1 = 0, int r01 = 0, int r10 = 0, int len = 0, int ans = 0,
int rev = 0)
: l0(l0),
l1(l1),
l01(l01),
l10(l10),
r0(r0),
r1(r1),
r01(r01),
r10(r10),
len(len),
ans(ans),
rev(rev) {}
};
vector<Node> init;
for (char c : s) {
init.emplace_back(c == '>' ? Node(1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1)
: Node(0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1));
}
function<Node(Node, Node)> mm = [](Node a, Node b) {
Node node;
node.l0 = a.l0 == a.len ? a.l0 + b.l0 : a.l0;
node.l1 = a.l1 == a.len ? a.l1 + b.l1 : a.l1;
if (a.l0 == a.len) {
node.l01 = a.l0 + b.l01;
} else if (a.l01 == a.len) {
node.l01 = a.l01 + b.l1;
} else {
node.l01 = a.l01;
}
if (a.l1 == a.len) {
node.l10 = a.l1 + b.l10;
} else if (a.l10 == a.len) {
node.l10 = a.l10 + b.l0;
} else {
node.l10 = a.l10;
}
node.r0 = b.r0 == b.len ? b.r0 + a.r0 : b.r0;
node.r1 = b.r1 == b.len ? b.r1 + a.r1 : b.r1;
if (b.r0 == b.len) {
node.r10 = b.r0 + a.r10;
} else if (b.r10 == b.len) {
node.r10 = b.r10 + a.r1;
} else {
node.r10 = b.r10;
}
if (b.r1 == b.len) {
node.r01 = b.r1 + a.r01;
} else if (b.r01 == b.len) {
node.r01 = b.r01 + a.r0;
} else {
node.r01 = b.r01;
}
node.len = a.len + b.len;
node.ans = max({a.ans, b.ans, node.l01, node.r01});
chmax(node.ans, max({a.r0 + b.l01, a.r01 + b.l1}));
node.rev = max({a.rev, b.rev, node.l10, node.r10});
chmax(node.rev, max({a.r1 + b.l10, a.r10 + b.l0}));
return node;
};
function<Node(Node, int, int)> moi = [](Node m, int o, int i) {
if (o) {
swap(m.l0, m.l1);
swap(m.l01, m.l10);
swap(m.r0, m.r1);
swap(m.r01, m.r10);
swap(m.ans, m.rev);
}
return m;
};
function<int(int, int)> oo = [](int a, int b) { return a ^ b; };
LazySegmentTree<Node, int> seg(init, mm, moi, oo, Node(), 0);
while (q--) {
int l, r;
cin >> l >> r;
--l;
--r;
seg.update(l, r + 1, 1);
cout << seg.query(l, r + 1).ans << '\n';
}
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Berland has a long and glorious history. To increase awareness about it among younger citizens, King of Berland decided to compose an anthem.
Though there are lots and lots of victories in history of Berland, there is the one that stand out the most. King wants to mention it in the anthem as many times as possible.
He has already composed major part of the anthem and now just needs to fill in some letters. King asked you to help him with this work.
The anthem is the string s of no more than 105 small Latin letters and question marks. The most glorious victory is the string t of no more than 105 small Latin letters. You should replace all the question marks with small Latin letters in such a way that the number of occurrences of string t in string s is maximal.
Note that the occurrences of string t in s can overlap. Check the third example for clarification.
Input
The first line contains string of small Latin letters and question marks s (1 ≤ |s| ≤ 105).
The second line contains string of small Latin letters t (1 ≤ |t| ≤ 105).
Product of lengths of strings |s|·|t| won't exceed 107.
Output
Output the maximum number of occurrences of string t you can achieve by replacing all the question marks in string s with small Latin letters.
Examples
Input
winlose???winl???w??
win
Output
5
Input
glo?yto?e??an?
or
Output
3
Input
??c?????
abcab
Output
2
Note
In the first example the resulting string s is "winlosewinwinlwinwin"
In the second example the resulting string s is "glorytoreorand". The last letter of the string can be arbitrary.
In the third example occurrences of string t are overlapping. String s with maximal number of occurrences of t is "abcabcab".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int const sze = 1 << 17, MOD1 = 1e9 + 9, x1 = 119, INF = -1e6;
int get(const string &s, const string &f, int ind) {
int length = 0;
while (length != f.length() && ind + length < s.length() &&
(s[ind + length] == '?' || s[ind + length] == f[length]))
length++;
return length;
}
signed main() {
string s, f;
cin >> s >> f;
int n = s.size(), m = f.size();
vector<vector<bool>> may_pref(n);
vector<int> may_suf(n);
for (int i = 0; i < n; ++i) {
may_pref[i].resize(m + 1);
}
for (int i = 0; i + m - 1 < n; ++i) {
int v = get(s, f, i);
for (int j = 0; j < v; ++j) may_pref[i + j][j + 1] = 1;
}
for (int i = 0; i < n; ++i) {
int length = 0;
while (i >= length && m > length &&
(s[i - length] == '?' || s[i - length] == f[m - length - 1]))
length++;
may_suf[i] = length;
}
vector<int> dp(n);
vector<int> lengthes;
for (int i = 1; i < m; ++i) {
if (f.substr(0, i) == f.substr(m - i, i)) lengthes.push_back(i);
}
int cur = 0;
vector<int> c(n);
for (int i = 0; i < n; ++i) {
if (i >= m) {
cur = max(cur, dp[i - m]);
dp[i] = max(dp[i], cur);
}
c[i] = dp[i];
if (i) {
c[i] = max(c[i], c[i - 1]);
}
if (may_suf[i] == m && !lengthes.size())
dp[i] = max(dp[i], (i + 1 == m ? 1 : cur + 1));
for (int j : lengthes) {
if (may_pref[i][j] && i + (m - j) < n &&
may_suf[i + (m - j)] >= (m - j)) {
dp[i + (m - j)] =
max(dp[i + (m - j)], max(dp[i], (i >= j) ? c[i - j] : 0) + 1);
}
}
}
int ans = dp[n - 1];
for (int i = 0; i < n; ++i) ans = max(ans, dp[i]);
cout << ans << '\n';
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Greg has an array a = a1, a2, ..., an and m operations. Each operation looks as: li, ri, di, (1 ≤ li ≤ ri ≤ n). To apply operation i to the array means to increase all array elements with numbers li, li + 1, ..., ri by value di.
Greg wrote down k queries on a piece of paper. Each query has the following form: xi, yi, (1 ≤ xi ≤ yi ≤ m). That means that one should apply operations with numbers xi, xi + 1, ..., yi to the array.
Now Greg is wondering, what the array a will be after all the queries are executed. Help Greg.
Input
The first line contains integers n, m, k (1 ≤ n, m, k ≤ 105). The second line contains n integers: a1, a2, ..., an (0 ≤ ai ≤ 105) — the initial array.
Next m lines contain operations, the operation number i is written as three integers: li, ri, di, (1 ≤ li ≤ ri ≤ n), (0 ≤ di ≤ 105).
Next k lines contain the queries, the query number i is written as two integers: xi, yi, (1 ≤ xi ≤ yi ≤ m).
The numbers in the lines are separated by single spaces.
Output
On a single line print n integers a1, a2, ..., an — the array after executing all the queries. Separate the printed numbers by spaces.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
Examples
Input
3 3 3
1 2 3
1 2 1
1 3 2
2 3 4
1 2
1 3
2 3
Output
9 18 17
Input
1 1 1
1
1 1 1
1 1
Output
2
Input
4 3 6
1 2 3 4
1 2 1
2 3 2
3 4 4
1 2
1 3
2 3
1 2
1 3
2 3
Output
5 18 31 20
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 300010;
long long n, m, k, tree[4 * N], lz[4 * N], l[N], r[N], d[N], f[N], a[N];
void lazy(long long l, long long r, long long pos) {
tree[pos] += ((r - l + 1) * lz[pos]);
if (l != r) {
lz[2 * pos] += lz[pos];
lz[2 * pos + 1] += lz[pos];
}
lz[pos] = 0;
return;
}
void update(long long l, long long r, long long pos, long long L, long long R,
long long v) {
lazy(l, r, pos);
if (l > R || r < L) return;
if (l >= L && r <= R) {
tree[pos] += v * (r - l + 1);
if (l != r) {
lz[2 * pos] += v;
lz[2 * pos + 1] += v;
}
return;
}
long long mid = (l + r) / 2;
update(l, mid, 2 * pos, L, R, v);
update(mid + 1, r, 2 * pos + 1, L, R, v);
tree[pos] = tree[2 * pos] + tree[2 * pos + 1];
return;
}
long long query(long long l, long long r, long long pos, long long P) {
lazy(l, r, pos);
if (l > P || r < P) return 0;
if (l == r && l == P) return tree[pos];
long long mid = (l + r) / 2;
return query(l, mid, 2 * pos, P) + query(mid + 1, r, 2 * pos + 1, P);
}
int solve() {
scanf("%lld%lld", &n, &m);
scanf("%lld", &k);
for (int i = 1; i <= n; i++) scanf("%lld", &a[i]);
for (int i = 1; i <= m; i++) {
scanf("%lld%lld", &l[i], &r[i]);
scanf("%lld", &d[i]);
}
while (k--) {
long long x, y;
scanf("%lld%lld", &x, &y);
update(1, m, 1, x, y, 1);
}
for (int i = 1; i <= m; i++) {
f[i] = query(1, m, 1, i);
}
memset(tree, 0, sizeof(tree));
for (int i = 1; i <= m; i++) {
update(1, n, 1, l[i], r[i], d[i] * f[i]);
}
for (int i = 1; i <= n; i++) {
printf("%lld ", a[i] + query(1, n, 1, i));
}
return 0;
}
int main() { return solve(); }
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Butler Ostin wants to show Arkady that rows of odd number of fountains are beautiful, while rows of even number of fountains are not.
The butler wants to show Arkady n gardens. Each garden is a row of m cells, the i-th garden has one fountain in each of the cells between li and ri inclusive, and there are no more fountains in that garden. The issue is that some of the gardens contain even number of fountains, it is wrong to show them to Arkady.
Ostin wants to choose two integers a ≤ b and show only part of each of the gardens that starts at cell a and ends at cell b. Of course, only such segments suit Ostin that each garden has either zero or odd number of fountains on this segment. Also, it is necessary that at least one garden has at least one fountain on the segment from a to b.
Help Ostin to find the total length of all such segments, i.e. sum up the value (b - a + 1) for each suitable pair (a, b).
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2·105) — the number of gardens and the length of each garden.
n lines follow. The i-th of these lines contains two integers li and ri (1 ≤ li ≤ ri ≤ m) — the bounds of the segment that contains fountains in the i-th garden.
Output
Print one integer: the total length of all suitable segments.
Examples
Input
1 5
2 4
Output
23
Input
3 6
2 4
3 6
4 4
Output
19
Note
In the first example the following pairs suit Ostin: (a, b): (1, 2), (1, 4), (1, 5), (2, 2), (2, 4), (2, 5), (3, 3), (4, 4), (4, 5).
In the second example the following pairs suit Ostin: (a, b): (1, 2), (1, 5), (2, 2), (2, 5), (3, 3), (4, 4), (4, 6), (5, 5), (6, 6).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long N = 2e5 + 20;
long long n, m, l[N], r[N];
long long x[N], p[N], d[N], t[N];
map<long long, long long> cnt, sum;
long long ans;
inline long long get_random() {
return 1ll * rand() * rand() * rand() + rand() * rand() + rand();
}
int32_t main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
srand(time(NULL));
cin >> n >> m;
for (long long i = 0; i < n; i++) {
cin >> l[i] >> r[i];
l[i]--;
long long val = get_random();
x[l[i]] ^= val;
x[r[i]] ^= val;
d[l[i]] ^= val;
t[r[i]] ^= val;
}
for (long long i = 0; i < m; i++) {
if (i) {
x[i] ^= x[i - 1];
p[i] ^= p[i - 1];
d[i] ^= d[i - 1];
t[i] ^= t[i - 1];
}
p[i] ^= x[i];
cnt[(i ? p[i - 1] : 0) ^ t[i]]++;
sum[(i ? p[i - 1] : 0) ^ t[i]] += i;
ans += cnt[p[i] ^ d[i]] * (i + 1) - sum[p[i] ^ d[i]];
}
long long last = -1;
for (long long i = 0; i < m; i++) {
if (!x[i]) {
ans -= (i - last) * (i - last + 1) / 2;
} else
last = i;
}
cout << ans << '\n';
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
C --Misawa's rooted tree
Problem Statement
You noticed that your best friend Misawa's birthday was near, and decided to give him a rooted binary tree as a gift. Here, the rooted binary tree has the following graph structure. (Figure 1)
* Each vertex has exactly one vertex called the parent of that vertex, which is connected to the parent by an edge. However, only one vertex, called the root, has no parent as an exception.
* Each vertex has or does not have exactly one vertex called the left child. If you have a left child, it is connected to the left child by an edge, and the parent of the left child is its apex.
* Each vertex has or does not have exactly one vertex called the right child. If you have a right child, it is connected to the right child by an edge, and the parent of the right child is its apex.
<image>
Figure 1. An example of two rooted binary trees and their composition
You wanted to give a handmade item, so I decided to buy two commercially available rooted binary trees and combine them on top of each other to make one better rooted binary tree. Each vertex of the two trees you bought has a non-negative integer written on it. Mr. Misawa likes a tree with good cost performance, such as a small number of vertices and large numbers, so I decided to create a new binary tree according to the following procedure.
1. Let the sum of the integers written at the roots of each of the two binary trees be the integers written at the roots of the new binary tree.
2. If both binary trees have a left child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the left child of the new binary tree root. Otherwise, the root of the new bifurcation has no left child.
3. If the roots of both binaries have the right child, create a binary tree by synthesizing each of the binary trees rooted at them, and use it as the right child of the root of the new binary tree. Otherwise, the root of the new bifurcation has no right child.
You decide to see what the resulting rooted binary tree will look like before you actually do the compositing work. Given the information of the two rooted binary trees you bought, write a program to find the new rooted binary tree that will be synthesized according to the above procedure.
Here, the information of the rooted binary tree is expressed as a character string in the following format.
> (String representing the left child) [Integer written at the root] (String representing the right child)
A tree without nodes is an empty string. For example, the synthesized new rooted binary tree in Figure 1 is `(() [6] ()) [8] (((() [4] ()) [7] ()) [9] () ) `Written as.
Input
The input is expressed in the following format.
$ A $
$ B $
$ A $ and $ B $ are character strings that represent the information of the rooted binary tree that you bought, and the length is $ 7 $ or more and $ 1000 $ or less. The information given follows the format described above and does not include extra whitespace. Also, rooted trees that do not have nodes are not input. You can assume that the integers written at each node are greater than or equal to $ 0 $ and less than or equal to $ 1000 $. However, note that the integers written at each node of the output may not fall within this range.
Output
Output the information of the new rooted binary tree created by synthesizing the two rooted binary trees in one line. In particular, be careful not to include extra whitespace characters other than line breaks at the end of the line.
Sample Input 1
((() [8] ()) [2] ()) [5] (((() [2] ()) [6] (() [3] ())) [1] ())
(() [4] ()) [3] (((() [2] ()) [1] ()) [8] (() [3] ()))
Output for the Sample Input 1
(() [6] ()) [8] (((() [4] ()) [7] ()) [9] ())
Sample Input 2
(() [1] ()) [2] (() [3] ())
(() [1] (() [2] ())) [3] ()
Output for the Sample Input 2
(() [2] ()) [5] ()
Sample Input 3
(() [1] ()) [111] ()
() [999] (() [9] ())
Output for the Sample Input 3
() [1110] ()
Sample Input 4
(() [2] (() [4] ())) [8] ((() [16] ()) [32] (() [64] ()))
((() [1] ()) [3] ()) [9] (() [27] (() [81] ()))
Output for the Sample Input 4
(() [5] ()) [17] (() [59] (() [145] ()))
Sample Input 5
() [0] ()
() [1000] ()
Output for the Sample Input 5
() [1000] ()
Example
Input
((()[8]())[2]())[5](((()[2]())[6](()[3]()))[1]())
(()[4]())[3](((()[2]())[1]())[8](()[3]()))
Output
(()[6]())[8](((()[4]())[7]())[9]())
### Response
```cpp
#include <bits/stdc++.h>
#define FOR(i,k,n) for(int i=(k);i<(int)(n);++i)
#define REP(i,n) FOR(i,0,n)
#define ALL(x) begin(x),end(x)
using namespace std;
pair<int, int> num(const string &s, int i) {
int n = 0;
while (isdigit(s[i])) {
n *= 10;
n += s[i] - '0';
++i;
}
return make_pair(n, i);
}
int skip(const string &s, int i) {
if (s[i] == '(') {
i = skip(s, i+1);
assert(s[i] == ')');
assert(s[i+1] == '[');
i = num(s, i+2).second;
assert(s[i] == ']');
assert(s[i+1] == '(');
i = skip(s, i+2);
return i+1;
} else {
return i;
}
}
pair<int, int> parse(const string &a, const string &b, int i, int j) {
if (a[i] == '(' && b[j] == '(') {
cout << '(';
tie(i, j) = parse(a, b, i+1, j+1);
assert(a[i] == ')');
assert(b[j] == ')');
cout << ')';
assert(a[i+1] == '[');
assert(b[j+1] == '[');
cout << '[';
int n, m;
tie(n, i) = num(a, i+2);
tie(m, j) = num(b, j+2);
cout << (n+m);
assert(a[i] == ']');
assert(b[j] == ']');
cout << ']';
assert(a[i+1] == '(');
assert(b[j+1] == '(');
cout << '(';
tie(i, j) = parse(a, b, i+2, j+2);
assert(a[i] == ')');
assert(b[j] == ')');
cout << ')';
++i; ++j;
} else {
if (a[i] == '(') {
i = skip(a, i);
} else if (b[j] == '(') {
j = skip(b, j);
}
}
return make_pair(i, j);
}
int main() {
string a, b;
cin>>a>>b;
parse(a, b, 0, 0);
cout << endl;
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
There is a blackboard on which all integers from -10^{18} through 10^{18} are written, each of them appearing once. Takahashi will repeat the following sequence of operations any number of times he likes, possibly zero:
* Choose an integer between 1 and N (inclusive) that is written on the blackboard. Let x be the chosen integer, and erase x.
* If x-2 is not written on the blackboard, write x-2 on the blackboard.
* If x+K is not written on the blackboard, write x+K on the blackboard.
Find the number of possible sets of integers written on the blackboard after some number of operations, modulo M. We consider two sets different when there exists an integer contained in only one of the sets.
Constraints
* 1 \leq K\leq N \leq 150
* 10^8\leq M\leq 10^9
* N, K, and M are integers.
Input
Input is given from Standard Input in the following format:
N K M
Output
Print the number of possible sets of integers written on the blackboard after some number of operations, modulo M.
Examples
Input
3 1 998244353
Output
7
Input
6 3 998244353
Output
61
Input
9 4 702443618
Output
312
Input
17 7 208992811
Output
128832
Input
123 45 678901234
Output
256109226
### Response
```cpp
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<queue>
#include<deque>
#include<stack>
#include<string>
#include<string.h>
#include<vector>
#include<set>
#include<map>
#include<bitset>
#include<stdlib.h>
#include<cassert>
#include<time.h>
#include<bitset>
using namespace std;
const long long mod=1000000007;
const long long inf=mod*mod;
const long long d2=(mod+1)/2;
const double EPS=1e-10;
const double INF=1e+10;
const double PI=acos(-1.0);
const int C_SIZE = 3121000;
long long fact[C_SIZE];
long long finv[C_SIZE];
long long inv[C_SIZE];
long long Comb(int a,int b){
if(a<b||b<0)return 0;
return fact[a]*finv[b]%mod*finv[a-b]%mod;
}
void init_C(int n){
fact[0]=finv[0]=inv[1]=1;
for(int i=2;i<n;i++){
inv[i]=(mod-(mod/i)*inv[mod%i]%mod)%mod;
}
for(int i=1;i<n;i++){
fact[i]=fact[i-1]*i%mod;
finv[i]=finv[i-1]*inv[i]%mod;
}
}
long long pw(long long a,long long b){
long long ret=1;
while(b){
if(b%2)ret=ret*a%mod;
a=a*a%mod;
b/=2;
}
return ret;
}
int ABS(int a){return max(a,-a);}
long long ABS(long long a){return max(a,-a);}
double ABS(double a){return max(a,-a);}
// ここから編集しろ
long long M;
long long dp[160][80][80][80];
long long DP[160][160][160];
int main(){
int a,b;
scanf("%d%d%lld",&a,&b,&M);
if(b%2==0){
DP[0][0][1]=1;
for(int i=0;i<a;i++){
for(int j=0;j<=i+1;j++){
for(int k=0;k<=i+1;k++){
if(!DP[i][j][k])continue;
if(i%2==0){
DP[i+1][i+2][k]=(DP[i+1][i+2][k]+DP[i][j][k])%M;
if(i-j<b)DP[i+1][j][k]=(DP[i+1][j][k]+DP[i][j][k])%M;
}else{
DP[i+1][j][i+2]=(DP[i+1][j][i+2]+DP[i][j][k])%M;
if(i-k<b)DP[i+1][j][k]=(DP[i+1][j][k]+DP[i][j][k])%M;
}
}
}
}
long long ret=0;
for(int i=0;i<=a+1;i++){
for(int j=0;j<=a+1;j++){
ret+=DP[a][i][j];
}
}
ret%=M;
printf("%lld\n",ret);
return 0;
}else{
dp[0][0][0][79]=1;
for(int i=0;i<a;i++){
for(int j=0;j<80;j++){
for(int k=0;k<80;k++){
for(int l=0;l<80;l++){
if(!dp[i][j][k][l])continue;
int x=j*2-2;
int y=k*2-1;
// printf("%d %d %d %d: %lld\n",i,x,y,l,dp[i][j][k][l]);
if(x<y){
if(i%2==0){
if(i<l*2)dp[i+1][j][k][l]=(dp[i+1][j][k][l]+dp[i][j][k][l])%M;
dp[i+1][(i+2)/2][k][79]=(dp[i+1][(i+2)/2][k][79]+dp[i][j][k][l])%M;
}else{
if(x+2+b<=i)dp[i+1][j][k][min(l,(y+2+b)/2)]=(dp[i+1][j][k][min(l,(y+b+2)/2)]+dp[i][j][k][l])%M;
else dp[i+1][j][k][l]=(dp[i+1][j][k][l]+dp[i][j][k][l])%M;
dp[i+1][j][(i+1)/2][l]=(dp[i+1][j][(i+1)/2][l]+dp[i][j][k][l])%M;
}
}else{
if(i%2==1){
if(i<l*2-1)dp[i+1][j][k][l]=(dp[i+1][j][k][l]+dp[i][j][k][l])%M;
dp[i+1][j][(i+1)/2][79]=(dp[i+1][j][(i+1)/2][79]+dp[i][j][k][l])%M;
}else{
if(y+2+b<=i)dp[i+1][j][k][min(l,(x+b+3)/2)]=(dp[i+1][j][k][min(l,(x+b+3)/2)]+dp[i][j][k][l])%M;
else dp[i+1][j][k][l]=(dp[i+1][j][k][l]+dp[i][j][k][l])%M;
dp[i+1][(i+2)/2][k][l]=(dp[i+1][(i+2)/2][k][l]+dp[i][j][k][l])%M;
}
}
}
}
}
}
long long ret=0;
for(int i=0;i<80;i++){
for(int j=0;j<80;j++){
for(int k=0;k<80;k++){
ret+=dp[a][i][j][k];
}
}
}
ret%=M;
printf("%lld\n",ret);
}
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Now Fox Ciel becomes a commander of Tree Land. Tree Land, like its name said, has n cities connected by n - 1 undirected roads, and for any two cities there always exists a path between them.
Fox Ciel needs to assign an officer to each city. Each officer has a rank — a letter from 'A' to 'Z'. So there will be 26 different ranks, and 'A' is the topmost, so 'Z' is the bottommost.
There are enough officers of each rank. But there is a special rule must obey: if x and y are two distinct cities and their officers have the same rank, then on the simple path between x and y there must be a city z that has an officer with higher rank. The rule guarantee that a communications between same rank officers will be monitored by higher rank officer.
Help Ciel to make a valid plan, and if it's impossible, output "Impossible!".
Input
The first line contains an integer n (2 ≤ n ≤ 105) — the number of cities in Tree Land.
Each of the following n - 1 lines contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b) — they mean that there will be an undirected road between a and b. Consider all the cities are numbered from 1 to n.
It guaranteed that the given graph will be a tree.
Output
If there is a valid plane, output n space-separated characters in a line — i-th character is the rank of officer in the city with number i.
Otherwise output "Impossible!".
Examples
Input
4
1 2
1 3
1 4
Output
A B B B
Input
10
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
Output
D C B A D C B D C D
Note
In the first example, for any two officers of rank 'B', an officer with rank 'A' will be on the path between them. So it is a valid solution.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 10;
vector<int> g[MAXN];
char c[MAXN];
int mark[MAXN], n, l = 1, dp[MAXN], par[MAXN];
int go(int v, int sz, int p = 0) {
par[v] = p;
dp[v] = 1;
mark[v] = l;
int ans = -1;
for (int i = 0; i < g[v].size(); i++) {
int u = g[v][i];
if (mark[u] != l - 1) continue;
int q = go(u, sz, v);
dp[v] += dp[u];
if (q != -1 && ans == -1) ans = q;
}
if (ans != -1) return ans;
if (dp[v] >= (sz + 1) / 2) {
mark[v] = -mark[v];
return v;
}
return -1;
}
void solve(int v, int sz, int p) {
l = p;
int cen = go(v, sz);
for (int u : g[cen])
if (mark[u] > 0)
if (u == par[cen])
solve(u, sz - dp[cen], p + 1);
else
solve(u, dp[u], p + 1);
}
int main() {
cin >> n;
for (int i = 1; i < n; i++) {
int v, u;
cin >> v >> u;
g[v].push_back(u);
g[u].push_back(v);
}
solve(1, n, 1);
for (int i = 1; i <= n; i++) cout << char(abs(mark[i]) + 'A' - 1) << " ";
cout << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Consider a permutation p_1, p_2, ... p_n of integers from 1 to n. We call a sub-segment p_l, p_{l+1}, ..., p_{r-1}, p_{r} of the permutation an interval if it is a reordering of some set of consecutive integers. For example, the permutation (6,7,1,8,5,3,2,4) has the intervals (6,7), (5,3,2,4), (3,2), and others.
Each permutation has some trivial intervals — the full permutation itself and every single element. We call a permutation interval-free if it does not have non-trivial intervals. In other words, interval-free permutation does not have intervals of length between 2 and n - 1 inclusive.
Your task is to count the number of interval-free permutations of length n modulo prime number p.
Input
In the first line of the input there are two integers t (1 ≤ t ≤ 400) and p (10^8 ≤ p ≤ 10^9) — the number of test cases to solve and the prime modulo. In each of the next t lines there is one integer n (1 ≤ n ≤ 400) — the length of the permutation.
Output
For each of t test cases print a single integer — the number of interval-free permutations modulo p.
Examples
Input
4 998244353
1
4
5
9
Output
1
2
6
28146
Input
1 437122297
20
Output
67777575
Note
For n = 1 the only permutation is interval-free. For n = 4 two interval-free permutations are (2,4,1,3) and (3,1,4,2). For n = 5 — (2,4,1,5,3), (2,5,3,1,4), (3,1,5,2,4), (3,5,1,4,2), (4,1,3,5,2), and (4,2,5,1,3). We will not list all 28146 for n = 9, but for example (4,7,9,5,1,8,2,6,3), (2,4,6,1,9,7,3,8,5), (3,6,9,4,1,5,8,2,7), and (8,4,9,1,3,6,2,7,5) are interval-free.
The exact value for n = 20 is 264111424634864638.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 4e2 + 5;
long long mod;
long long A[maxn], B[maxn][maxn];
long long G[maxn], F[maxn];
void pre() {
A[1] = A[0] = 1;
for (int i = 2; i < maxn; i++) A[i] = A[i - 1] * i % mod;
B[0][0] = 1;
for (int i = 1; i < maxn; i++)
for (int j = 1; j <= i; j++)
for (int k = 1; k <= i; k++)
B[i][j] = (B[i][j] + B[i - k][j - 1] * A[k] % mod) % mod;
for (int i = 1; i < maxn; i++) {
F[i] = G[i] = A[i];
for (int k = 1; k < i; k++) {
G[i] = (G[i] - G[k] * A[i - k] % mod + mod) % mod;
F[i] = (F[i] - 2 * G[k] % mod * A[i - k] % mod + mod) % mod;
}
for (int k = 4; k < i; k++)
F[i] = (F[i] - B[i][k] * F[k] % mod + mod) % mod;
}
F[2] = 2;
}
int main() {
int t;
cin >> t >> mod;
pre();
while (t--) {
int n;
cin >> n;
cout << F[n] << endl;
}
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Assume that you have k one-dimensional segments s_1, s_2, ... s_k (each segment is denoted by two integers — its endpoints). Then you can build the following graph on these segments. The graph consists of k vertexes, and there is an edge between the i-th and the j-th vertexes (i ≠ j) if and only if the segments s_i and s_j intersect (there exists at least one point that belongs to both of them).
For example, if s_1 = [1, 6], s_2 = [8, 20], s_3 = [4, 10], s_4 = [2, 13], s_5 = [17, 18], then the resulting graph is the following:
<image>
A tree of size m is good if it is possible to choose m one-dimensional segments so that the graph built on these segments coincides with this tree.
You are given a tree, you have to find its good subtree with maximum possible size. Recall that a subtree is a connected subgraph of a tree.
Note that you have to answer q independent queries.
Input
The first line contains one integer q (1 ≤ q ≤ 15 ⋅ 10^4) — the number of the queries.
The first line of each query contains one integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree.
Each of the next n - 1 lines contains two integers x and y (1 ≤ x, y ≤ n) denoting an edge between vertices x and y. It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of all n does not exceed 3 ⋅ 10^5.
Output
For each query print one integer — the maximum size of a good subtree of the given tree.
Example
Input
1
10
1 2
1 3
1 4
2 5
2 6
3 7
3 8
4 9
4 10
Output
8
Note
In the first query there is a good subtree of size 8. The vertices belonging to this subtree are {9, 4, 10, 2, 5, 1, 6, 3}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = int(3e5 + 5);
int n;
vector<int> G[MAXN];
int dp[MAXN], FA[MAXN];
void Addedge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
}
void Dfs(int u, int fa) {
int cnt = 0, Max = 0;
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if (v == fa) continue;
FA[v] = u;
Dfs(v, u);
cnt++;
Max = max(Max, dp[v]);
}
if (cnt == 0) {
dp[u] = 1;
return;
}
dp[u] = cnt + Max;
}
int Solve(int u) {
int Max1 = 0, Max2 = 0, cnt = 0;
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if (v == FA[u]) continue;
cnt++;
if (dp[v] >= Max1) {
Max2 = Max1;
Max1 = dp[v];
} else if (dp[v] >= Max2)
Max2 = dp[v];
}
if (cnt == 0) return 2;
if (cnt == 1) return Max1 + (u != 1) + 1;
if (u == 1) return G[u].size() - 2 + Max1 + Max2 + 1;
return G[u].size() - 3 + Max1 + Max2 + 2;
}
int ANS() {
int ret = 0;
for (int i = 1; i <= n; i++) ret = max(ret, Solve(i));
return ret;
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
scanf("%d", &n);
for (int i = 0; i <= n; i++) {
dp[i] = 0;
G[i].clear();
}
int u, v;
for (int i = 1; i <= n - 1; i++) {
scanf("%d%d", &u, &v);
Addedge(u, v);
}
Dfs(1, -1);
printf("%d\n", ANS());
}
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from 1.
Polycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers.
Given this information, is it possible to restore the exact floor for flat n?
Input
The first line contains two integers n and m (1 ≤ n ≤ 100, 0 ≤ m ≤ 100), where n is the number of the flat you need to restore floor for, and m is the number of flats in Polycarp's memory.
m lines follow, describing the Polycarp's memory: each of these lines contains a pair of integers ki, fi (1 ≤ ki ≤ 100, 1 ≤ fi ≤ 100), which means that the flat ki is on the fi-th floor. All values ki are distinct.
It is guaranteed that the given information is not self-contradictory.
Output
Print the number of the floor in which the n-th flat is located, if it is possible to determine it in a unique way. Print -1 if it is not possible to uniquely restore this floor.
Examples
Input
10 3
6 2
2 1
7 3
Output
4
Input
8 4
3 1
6 2
5 2
2 1
Output
-1
Note
In the first example the 6-th flat is on the 2-nd floor, while the 7-th flat is on the 3-rd, so, the 6-th flat is the last on its floor and there are 3 flats on each floor. Thus, the 10-th flat is on the 4-th floor.
In the second example there can be 3 or 4 flats on each floor, so we can't restore the floor for the 8-th flat.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
long long n, m;
cin >> n >> m;
long long f[m + 5];
long long k[m + 5];
for (int i = 0; i < m; i++) {
cin >> k[i] >> f[i];
}
int e = -1;
bool lol = true;
long long cnt = 0;
long long ans = 0;
for (int x = 1; x <= 200; x++) {
bool fl = true;
for (int i = 0; i < m; i++) {
int y = f[i];
int s = k[i];
if (s <= y * x && s >= (y - 1) * x + 1) {
} else {
fl = false;
}
}
if (fl) {
int w = (n - 1) / x + 1;
if (e == -1) {
e = w;
} else {
if (w != e) {
lol = false;
}
}
cnt++;
ans = x;
}
}
int kek = (n - 1) / ans + 1;
if (lol == true) {
cout << kek;
} else {
cout << -1;
}
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Sereja has painted n distinct points on the plane. The coordinates of each point are integers. Now he is wondering: how many squares are there with sides parallel to the coordinate axes and with points painted in all its four vertexes? Help him, calculate this number.
Input
The first line contains integer n (1 ≤ n ≤ 105). Each of the next n lines contains two integers xi, yi (0 ≤ xi, yi ≤ 105), the integers represent the coordinates of the i-th point. It is guaranteed that all the given points are distinct.
Output
In a single line print the required number of squares.
Examples
Input
5
0 0
0 2
2 0
2 2
1 1
Output
1
Input
9
0 0
1 1
2 2
0 1
1 0
0 2
2 0
1 2
2 1
Output
5
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 7;
const int inf = 0x3f3f3f3f;
const long long INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;
int n;
struct Point {
int x, y;
bool operator<(const Point &rhs) const {
if (y == rhs.y)
return x < rhs.x;
else
return y < rhs.y;
}
} a[N];
set<pair<int, int> > st;
vector<int> X[N];
vector<int> Y[N];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d%d", &a[i].x, &a[i].y);
sort(a + 1, a + 1 + n);
int ans = 0;
for (int i = 1; i <= n; i++) {
if (X[a[i].x].size() < Y[a[i].y].size()) {
for (int j = 0; j < X[a[i].x].size(); j++) {
int len = a[i].y - X[a[i].x][j];
if (st.count(make_pair(a[i].x - len, a[i].y)) &&
st.count(make_pair(a[i].x - len, a[i].y - len)))
ans++;
}
} else {
for (int j = 0; j < Y[a[i].y].size(); j++) {
int len = a[i].x - Y[a[i].y][j];
if (st.count(make_pair(a[i].x, a[i].y - len)) &&
st.count(make_pair(a[i].x - len, a[i].y - len)))
ans++;
}
}
st.insert(make_pair(a[i].x, a[i].y));
X[a[i].x].push_back(a[i].y);
Y[a[i].y].push_back(a[i].x);
}
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
The only difference between easy and hard versions are constraints on n and k.
You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0).
Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend.
You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 ≤ id_i ≤ 10^9).
If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages.
Otherwise (i.e. if there is no conversation with id_i on the screen):
* Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen.
* Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen.
* The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down.
Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages.
Input
The first line of the input contains two integers n and k (1 ≤ n, k ≤ 2 ⋅ 10^5) — the number of messages and the number of conversations your smartphone can show.
The second line of the input contains n integers id_1, id_2, ..., id_n (1 ≤ id_i ≤ 10^9), where id_i is the ID of the friend which sends you the i-th message.
Output
In the first line of the output print one integer m (1 ≤ m ≤ min(n, k)) — the number of conversations shown after receiving all n messages.
In the second line print m integers ids_1, ids_2, ..., ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages.
Examples
Input
7 2
1 2 3 2 1 3 2
Output
2
2 1
Input
10 4
2 3 3 1 1 2 1 2 3 3
Output
3
1 3 2
Note
In the first example the list of conversations will change in the following way (in order from the first to last message):
* [];
* [1];
* [2, 1];
* [3, 2];
* [3, 2];
* [1, 3];
* [1, 3];
* [2, 1].
In the second example the list of conversations will change in the following way:
* [];
* [2];
* [3, 2];
* [3, 2];
* [1, 3, 2];
* and then the list will not change till the end.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
long long int power(long long int x, long long int y) {
long long int temp;
if (y == 0) return 1;
temp = power(x, y / 2);
if (y % 2 == 0)
return temp * temp;
else
return x * temp * temp;
}
long long int GCD(long long int A, long long int B) {
if (B == 0)
return A;
else
return GCD(B, A % B);
}
int main() {
ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
srand(time(NULL));
long long int n, k, i, j;
cin >> n >> k;
map<long long int, bool> m;
deque<long long int> q;
for (i = 0; i < n; i++) {
long long int x;
cin >> x;
if (m.find(x) != m.end() || m[x] == 1) {
} else if (q.size() < k) {
q.push_front(x);
m[x] = 1;
} else {
long long int t = q[q.size() - 1];
m.erase(t);
q.pop_back();
q.push_front(x);
m[x] = 1;
}
}
cout << q.size() << endl;
for (i = 0; i < q.size(); i++) cout << q[i] << " ";
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
We have N points numbered 1 to N arranged in a line in this order.
Takahashi decides to make an undirected graph, using these points as the vertices. In the beginning, the graph has no edge. Takahashi will do M operations to add edges in this graph. The i-th operation is as follows:
* The operation uses integers L_i and R_i between 1 and N (inclusive), and a positive integer C_i. For every pair of integers (s, t) such that L_i \leq s < t \leq R_i, add an edge of length C_i between Vertex s and Vertex t.
The integers L_1, ..., L_M, R_1, ..., R_M, C_1, ..., C_M are all given as input.
Takahashi wants to solve the shortest path problem in the final graph obtained. Find the length of the shortest path from Vertex 1 to Vertex N in the final graph.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq L_i < R_i \leq N
* 1 \leq C_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N M
L_1 R_1 C_1
:
L_M R_M C_M
Output
Print the length of the shortest path from Vertex 1 to Vertex N in the final graph. If there is no shortest path, print `-1` instead.
Examples
Input
4 3
1 3 2
2 4 3
1 4 6
Output
5
Input
4 2
1 2 1
3 4 2
Output
-1
Input
10 7
1 5 18
3 4 8
1 3 5
4 7 10
5 9 8
6 10 5
8 10 3
Output
28
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
int N, M, Li, Ri, Ci;
vector < pair <int, int> > evs[MAXN];
int main(){
scanf("%d %d", &N, &M);
while(M--){
scanf("%d %d %d", &Li, &Ri, &Ci);
Li--, Ri--;
evs[Li].push_back(make_pair(Ri, Ci));
}
set < pair <long long, int> > S;
S.insert(make_pair(0, 0));
for(int i = 0; i < N; i++){
while(!S.empty() && S.begin()->second < i)
S.erase(S.begin());
if(S.empty()){
printf("-1\n");
return 0;
}
long long dist = S.begin()->first;
if(i == N - 1){
printf("%lld\n", dist);
return 0;
}
for(pair <int, int> e : evs[i])
S.insert(make_pair(dist + e.second, e.first));
}
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game.
Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, Bob computes the values of n variables. Each variable is assigned either a constant m-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values.
Bob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose.
Input
The first line contains two integers n and m, the number of variables and bit depth, respectively (1 ≤ n ≤ 5000; 1 ≤ m ≤ 1000).
The following n lines contain descriptions of the variables. Each line describes exactly one variable. Description has the following format: name of a new variable, space, sign ":=", space, followed by one of:
1. Binary number of exactly m bits.
2. The first operand, space, bitwise operation ("AND", "OR" or "XOR"), space, the second operand. Each operand is either the name of variable defined before or symbol '?', indicating the number chosen by Peter.
Variable names are strings consisting of lowercase Latin letters with length at most 10. All variable names are different.
Output
In the first line output the minimum number that should be chosen by Peter, to make the sum of all variable values minimum possible, in the second line output the minimum number that should be chosen by Peter, to make the sum of all variable values maximum possible. Both numbers should be printed as m-bit binary numbers.
Examples
Input
3 3
a := 101
b := 011
c := ? XOR b
Output
011
100
Input
5 1
a := 1
bb := 0
cx := ? OR a
d := ? XOR ?
e := d AND bb
Output
0
0
Note
In the first sample if Peter chooses a number 0112, then a = 1012, b = 0112, c = 0002, the sum of their values is 8. If he chooses the number 1002, then a = 1012, b = 0112, c = 1112, the sum of their values is 15.
For the second test, the minimum and maximum sum of variables a, bb, cx, d and e is 2, and this sum doesn't depend on the number chosen by Peter, so the minimum Peter can choose is 0.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int TYPE_CONSTANT = 0;
const int TYPE_OPERATION = 1;
const int OPERATION_AND = 0;
const int OPERATION_XOR = 1;
const int OPERATION_OR = 2;
struct Clause {
int type;
string constant;
int op1, op2;
int optype;
};
map<string, int> mp;
int getidx(const string& str) {
if (str == "?") return 0;
int& val = mp[str];
if (val == 0) {
val = mp.size();
}
return val;
}
bool isnumber(const string& str) {
for (char c : str)
if (c != '0' && c != '1') return false;
return true;
}
int32_t main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, m;
cin >> n >> m;
vector<Clause> clauses(n + 1);
for (int i = 0; i < n; ++i) {
string aaa;
cin >> aaa;
Clause& c = clauses[getidx(aaa)];
string __;
cin >> __;
string lhs;
cin >> lhs;
if (isnumber(lhs)) {
c.type = TYPE_CONSTANT;
c.constant = lhs;
} else {
c.type = TYPE_OPERATION;
string optype, rhs;
cin >> optype >> rhs;
if (optype == "AND") {
c.optype = OPERATION_AND;
} else if (optype == "XOR") {
c.optype = OPERATION_XOR;
} else {
c.optype = OPERATION_OR;
}
c.op1 = getidx(lhs);
c.op2 = getidx(rhs);
}
}
auto solvebit = [&](const int idx, const bool val) {
vector<bool> values(n + 1);
values[0] = val;
for (int i = 1; i <= n; ++i) {
Clause& c = clauses[i];
if (c.type == TYPE_CONSTANT) {
values[i] = c.constant[idx] == '1';
} else {
if (c.optype == OPERATION_AND) {
values[i] = values[c.op1] && values[c.op2];
} else if (c.optype == OPERATION_XOR) {
values[i] = values[c.op1] != values[c.op2];
} else {
values[i] = values[c.op1] || values[c.op2];
}
}
}
int ans = 0;
for (int i = 1; i <= n; ++i) ans += values[i];
return ans;
};
vector<bool> best(m);
for (int i = 0; i < m; ++i) {
if (solvebit(i, 1) < solvebit(i, 0)) {
best[i] = true;
}
}
for (int i = 0; i < m; ++i) cout << (best[i] ? '1' : '0');
cout << endl;
fill(best.begin(), best.end(), false);
for (int i = 0; i < m; ++i) {
if (solvebit(i, 1) > solvebit(i, 0)) {
best[i] = true;
}
}
for (int i = 0; i < m; ++i) cout << (best[i] ? '1' : '0');
cout << endl;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Write a program which reads an integer n and draws a Koch curve based on recursive calles of depth n.
The Koch curve is well known as a kind of fractals.
You can draw a Koch curve in the following algorithm:
* Divide a given segment (p1, p2) into three equal segments.
* Replace the middle segment by the two sides of an equilateral triangle (s, u, t) of the same length as the segment.
* Repeat this procedure recursively for new segments (p1, s), (s, u), (u, t), (t, p2).
<image>
You should start (0, 0), (100, 0) as the first segment.
Notes
Constraints
* 0 ≤ n ≤ 6
Input
An integer n is given.
Output
Print each point (x, y) of the Koch curve. Print a point in a line. You should start the point(0, 0), which is the endpoint of the first segment and end with the point (100, 0), the other endpoint so that you can draw the Koch curve as an unbroken line. Each solution should be given as a decimal with an arbitrary number of fractional digits, and with an absolute error of at most 10-4.
Examples
Input
1
Output
0.00000000 0.00000000
33.33333333 0.00000000
50.00000000 28.86751346
66.66666667 0.00000000
100.00000000 0.00000000
Input
2
Output
0.00000000 0.00000000
11.11111111 0.00000000
16.66666667 9.62250449
22.22222222 0.00000000
33.33333333 0.00000000
38.88888889 9.62250449
33.33333333 19.24500897
44.44444444 19.24500897
50.00000000 28.86751346
55.55555556 19.24500897
66.66666667 19.24500897
61.11111111 9.62250449
66.66666667 0.00000000
77.77777778 0.00000000
83.33333333 9.62250449
88.88888889 0.00000000
100.00000000 0.00000000
### Response
```cpp
#include <cstdio>
#include <cmath>
using namespace std;
struct P{
double x,y;
};
const double th=M_PI*60.0/180.0;
void koch(int n,P a,P b){
if(n==0)
return ;
P s,t,u;
s.x=(2*a.x+b.x)/3;
s.y=(2*a.y+b.y)/3;
t.x=(a.x+2*b.x)/3;
t.y=(a.y+2*b.y)/3;
u.x=(t.x-s.x)*cos(th)-(t.y-s.y)*sin(th)+s.x;
u.y=(t.y-s.y)*cos(th)+(t.x-s.x)*sin(th)+s.y;
koch(n-1,a,s);
printf("%.5f %.5f\n",s.x,s.y);
koch(n-1,s,u);
printf("%.5f %.5f\n",u.x,u.y);
koch(n-1,u,t);
printf("%.5f %.5f\n",t.x,t.y);
koch(n-1,t,b);
}
int main(){
int n;
scanf("%d",&n);
P a={0,0},b={100.0,0};
printf("%.5f %.5f\n",a.x,a.y);
koch(n,a,b);
printf("%.5f %.5f\n",b.x,b.y);
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Recently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string s = s_1 s_2 ... s_{n} of length n where each letter is either R, S or P.
While initializing, the bot is choosing a starting index pos (1 ≤ pos ≤ n), and then it can play any number of rounds. In the first round, he chooses "Rock", "Scissors" or "Paper" based on the value of s_{pos}:
* if s_{pos} is equal to R the bot chooses "Rock";
* if s_{pos} is equal to S the bot chooses "Scissors";
* if s_{pos} is equal to P the bot chooses "Paper";
In the second round, the bot's choice is based on the value of s_{pos + 1}. In the third round — on s_{pos + 2} and so on. After s_n the bot returns to s_1 and continues his game.
You plan to play n rounds and you've already figured out the string s but still don't know what is the starting index pos. But since the bot's tactic is so boring, you've decided to find n choices to each round to maximize the average number of wins.
In other words, let's suggest your choices are c_1 c_2 ... c_n and if the bot starts from index pos then you'll win in win(pos) rounds. Find c_1 c_2 ... c_n such that (win(1) + win(2) + ... + win(n))/(n) is maximum possible.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
Next t lines contain test cases — one per line. The first and only line of each test case contains string s = s_1 s_2 ... s_{n} (1 ≤ n ≤ 2 ⋅ 10^5; s_i ∈ \{R, S, P\}) — the string of the bot.
It's guaranteed that the total length of all strings in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print n choices c_1 c_2 ... c_n to maximize the average number of wins. Print them in the same manner as the string s.
If there are multiple optimal answers, print any of them.
Example
Input
3
RRRR
RSP
S
Output
PPPP
RSP
R
Note
In the first test case, the bot (wherever it starts) will always choose "Rock", so we can always choose "Paper". So, in any case, we will win all n = 4 rounds, so the average is also equal to 4.
In the second test case:
* if bot will start from pos = 1, then (s_1, c_1) is draw, (s_2, c_2) is draw and (s_3, c_3) is draw, so win(1) = 0;
* if bot will start from pos = 2, then (s_2, c_1) is win, (s_3, c_2) is win and (s_1, c_3) is win, so win(2) = 3;
* if bot will start from pos = 3, then (s_3, c_1) is lose, (s_1, c_2) is lose and (s_2, c_3) is lose, so win(3) = 0;
The average is equal to (0 + 3 + 0)/(3) = 1 and it can be proven that it's the maximum possible average.
A picture from Wikipedia explaining "Rock paper scissors" game:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
string solve(string &S) {
int n = S.size();
int r = 0, s = 0, p = 0;
for (int i = 0; i < n; i++) {
if (S[i] == 'R')
r++;
else if (S[i] == 'S')
s++;
else
p++;
}
vector<pair<int, char>> ranks(3);
ranks[0] = make_pair(r, 'P');
ranks[1] = make_pair(s, 'R');
ranks[2] = make_pair(p, 'S');
sort(ranks.begin(), ranks.end());
string ans = "";
while (n > 0) {
ans += ranks[2].second;
n--;
}
return ans;
}
int main() {
int t;
cin >> t;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
while (t--) {
string S;
getline(cin, S);
cout << solve(S) << endl;
}
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Tree is a connected acyclic graph. Suppose you are given a tree consisting of n vertices. The vertex of this tree is called centroid if the size of each connected component that appears if this vertex is removed from the tree doesn't exceed <image>.
You are given a tree of size n and can perform no more than one edge replacement. Edge replacement is the operation of removing one edge from the tree (without deleting incident vertices) and inserting one new edge (without adding new vertices) in such a way that the graph remains a tree. For each vertex you have to determine if it's possible to make it centroid by performing no more than one edge replacement.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 400 000) — the number of vertices in the tree. Each of the next n - 1 lines contains a pair of vertex indices ui and vi (1 ≤ ui, vi ≤ n) — endpoints of the corresponding edge.
Output
Print n integers. The i-th of them should be equal to 1 if the i-th vertex can be made centroid by replacing no more than one edge, and should be equal to 0 otherwise.
Examples
Input
3
1 2
2 3
Output
1 1 1
Input
5
1 2
1 3
1 4
1 5
Output
1 0 0 0 0
Note
In the first sample each vertex can be made a centroid. For example, in order to turn vertex 1 to centroid one have to replace the edge (2, 3) with the edge (1, 3).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n;
vector<int> E[400000 + 5];
int dp[400000 + 5];
int max1[400000 + 5];
int max2[400000 + 5];
int sz[400000 + 5];
void dfs1(int x, int fa) {
sz[x] = 1;
dp[x] = 0;
for (int y : E[x]) {
if (y != fa) {
dfs1(y, x);
sz[x] += sz[y];
if (dp[y] > dp[x]) {
dp[x] = dp[y];
max2[x] = max1[x];
max1[x] = y;
} else if (dp[y] > dp[max2[x]])
max2[x] = y;
}
}
if (sz[x] <= n / 2) dp[x] = sz[x];
}
int ans[400000 + 5];
void dfs2(int x, int fa, int pre) {
int flag = 1;
for (int y : E[x]) {
if (y == fa) {
if (n - sz[x] > n / 2 && n - sz[x] - pre > n / 2) flag = 0;
} else if (sz[y] > n / 2) {
if (sz[y] - dp[y] > n / 2) flag = 0;
}
}
ans[x] = flag;
for (int y : E[x]) {
if (y != fa) {
int tmp;
if (n - sz[y] <= n / 2)
tmp = n - sz[y];
else {
if (y == max1[x])
tmp = max(pre, dp[max2[x]]);
else
tmp = max(pre, dp[max1[x]]);
}
dfs2(y, x, tmp);
}
}
}
int main() {
int u, v;
scanf("%d", &n);
for (int i = 1; i < n; i++) {
scanf("%d %d", &u, &v);
E[u].push_back(v);
E[v].push_back(u);
}
dfs1(1, 0);
dfs2(1, 0, 0);
for (int i = 1; i <= n; i++) printf("%d ", ans[i]);
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 ≤ i, j ≤ m the condition Ai ≥ Bj holds. Help Leha rearrange the numbers in the array A so that the sum <image> is maximally possible, where A' is already rearranged array.
Input
First line of input data contains single integer m (1 ≤ m ≤ 2·105) — length of arrays A and B.
Next line contains m integers a1, a2, ..., am (1 ≤ ai ≤ 109) — array A.
Next line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 109) — array B.
Output
Output m integers a'1, a'2, ..., a'm — array A' which is permutation of the array A.
Examples
Input
5
7 3 5 3 4
2 1 3 2 3
Output
4 7 3 5 3
Input
7
4 6 5 8 8 2 6
2 1 2 2 1 1 2
Output
2 6 4 5 8 8 6
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxN = 2 * 1e5 + 190;
int n, A[maxN], ans[maxN];
pair<int, int> B[maxN];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (int i = 0; i < n; ++i) cin >> A[i];
for (int i = 0; i < n; ++i) {
cin >> B[i].first;
B[i].second = i;
}
sort(A, A + n);
sort(B, B + n);
for (int i = 0; i < n; ++i) ans[B[n - i - 1].second] = A[i];
for (int i = 0; i < n; ++i) cout << ans[i] << " ";
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Allen and Bessie are playing a simple number game. They both know a function f: \{0, 1\}^n → R, i. e. the function takes n binary arguments and returns a real value. At the start of the game, the variables x_1, x_2, ..., x_n are all set to -1. Each round, with equal probability, one of Allen or Bessie gets to make a move. A move consists of picking an i such that x_i = -1 and either setting x_i → 0 or x_i → 1.
After n rounds all variables are set, and the game value resolves to f(x_1, x_2, ..., x_n). Allen wants to maximize the game value, and Bessie wants to minimize it.
Your goal is to help Allen and Bessie find the expected game value! They will play r+1 times though, so between each game, exactly one value of f changes. In other words, between rounds i and i+1 for 1 ≤ i ≤ r, f(z_1, ..., z_n) → g_i for some (z_1, ..., z_n) ∈ \{0, 1\}^n. You are to find the expected game value in the beginning and after each change.
Input
The first line contains two integers n and r (1 ≤ n ≤ 18, 0 ≤ r ≤ 2^{18}).
The next line contains 2^n integers c_0, c_1, ..., c_{2^n-1} (0 ≤ c_i ≤ 10^9), denoting the initial values of f. More specifically, f(x_0, x_1, ..., x_{n-1}) = c_x, if x = \overline{x_{n-1} … x_0} in binary.
Each of the next r lines contains two integers z and g (0 ≤ z ≤ 2^n - 1, 0 ≤ g ≤ 10^9). If z = \overline{z_{n-1} ... z_0} in binary, then this means to set f(z_0, ..., z_{n-1}) → g.
Output
Print r+1 lines, the i-th of which denotes the value of the game f during the i-th round. Your answer must have absolute or relative error within 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}.
Examples
Input
2 2
0 1 2 3
2 5
0 4
Output
1.500000
2.250000
3.250000
Input
1 0
2 3
Output
2.500000
Input
2 0
1 1 1 1
Output
1.000000
Note
Consider the second test case. If Allen goes first, he will set x_1 → 1, so the final value will be 3. If Bessie goes first, then she will set x_1 → 0 so the final value will be 2. Thus the answer is 2.5.
In the third test case, the game value will always be 1 regardless of Allen and Bessie's play.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
map<long long, int> m;
int main() {
int n, r;
long long z, g;
long long sum = 0;
scanf("%d%d", &n, &r);
for (long long i = 0; i < pow(2, n); i++) {
scanf("%d", &m[i]);
sum += m[i];
}
printf("%f\n", sum / pow(2, n));
while (r--) {
scanf("%lld%lld", &z, &g);
sum += g - m[z];
m[z] = g;
printf("%f\n", sum / pow(2, n));
}
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
A student's life is fraught with complications. Some Berland University students know this only too well. Having studied for two years, they contracted strong antipathy towards the chairperson of some department. Indeed, the person in question wasn't the kindest of ladies to begin with: prone to reforming groups, banning automatic passes and other mean deeds. At last the students decided that she just can't get away with all this anymore...
The students pulled some strings on the higher levels and learned that the next University directors' meeting is going to discuss n orders about the chairperson and accept exactly p of them. There are two values assigned to each order: ai is the number of the chairperson's hairs that turn grey if she obeys the order and bi — the displeasement of the directors if the order isn't obeyed. The students may make the directors pass any p orders chosen by them. The students know that the chairperson will obey exactly k out of these p orders. She will pick the orders to obey in the way that minimizes first, the directors' displeasement and second, the number of hairs on her head that turn grey.
The students want to choose p orders in the way that maximizes the number of hairs on the chairperson's head that turn grey. If there are multiple ways to accept the orders, then the students are keen on maximizing the directors' displeasement with the chairperson's actions. Help them.
Input
The first line contains three integers n (1 ≤ n ≤ 105), p (1 ≤ p ≤ n), k (1 ≤ k ≤ p) — the number of orders the directors are going to discuss, the number of orders to pass and the number of orders to be obeyed by the chairperson, correspondingly. Each of the following n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109), describing the corresponding order.
Output
Print in an arbitrary order p distinct integers — the numbers of the orders to accept so that the students could carry out the revenge. The orders are indexed from 1 to n in the order they occur in the input. If there are multiple solutions, you can print any of them.
Examples
Input
5 3 2
5 6
5 8
1 3
4 3
4 11
Output
3 1 2
Input
5 3 3
10 18
18 17
10 20
20 18
20 18
Output
2 4 5
Note
In the first sample one of optimal solutions is to pass orders 1, 2, 3. In this case the chairperson obeys orders number 1 and 2. She gets 10 new grey hairs in the head and the directors' displeasement will equal 3. Note that the same result can be achieved with order 4 instead of order 3.
In the second sample, the chairperson can obey all the orders, so the best strategy for the students is to pick the orders with the maximum sum of ai values. The chairperson gets 58 new gray hairs and the directors' displeasement will equal 0.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct Data {
int a, b, id;
};
bool cmp1(const Data& x, const Data& y) {
return x.b != y.b ? x.b > y.b : x.a != y.a ? x.a < y.a : x.id < y.id;
}
bool cmp2(const Data& x, const Data& y) { return x.a > y.a; }
int N, P, K;
Data data[100010];
bool use[100010];
int main() {
scanf("%d%d%d", &N, &P, &K);
for (int i = 0; i < N; i++) {
int a, b;
scanf("%d%d", &a, &b);
data[i].a = a;
data[i].b = b;
data[i].id = i;
}
sort(data, data + N, cmp1);
stable_sort(data, data + N - P + K, cmp2);
for (int i = 0; i < K; i++) {
printf("%d ", data[i].id + 1);
use[data[i].id] = true;
}
sort(data, data + N, cmp1);
int cnt = 0, t;
for (t = 0; t < N; t++) {
if (use[data[t].id]) cnt++;
if (cnt == K) break;
}
t++;
for (int i = 0; i < P - K; i++) printf("%d ", data[t + i].id + 1);
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
There is a square grid of size n × n. Some cells are colored in black, all others are colored in white. In one operation you can select some rectangle and color all its cells in white. It costs max(h, w) to color a rectangle of size h × w. You are to make all cells white for minimum total cost.
Input
The first line contains a single integer n (1 ≤ n ≤ 50) — the size of the square grid.
Each of the next n lines contains a string of length n, consisting of characters '.' and '#'. The j-th character of the i-th line is '#' if the cell with coordinates (i, j) is black, otherwise it is white.
Output
Print a single integer — the minimum total cost to paint all cells in white.
Examples
Input
3
###
#.#
###
Output
3
Input
3
...
...
...
Output
0
Input
4
#...
....
....
#...
Output
2
Input
5
#...#
.#.#.
.....
.#...
#....
Output
5
Note
The examples and some of optimal solutions are shown on the pictures below.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
constexpr int MOD = 1e9 + 7;
constexpr int INF = INT32_MAX;
constexpr int MAXN = 2e6 + 10;
using ll = long long;
using Pii = pair<int, int>;
using Pll = pair<ll, ll>;
using Vec = vector<int>;
template <class T>
void Min(T &a, T &&b) {
if (b < a) a = b;
}
template <class T>
void Max(T &a, T &&b) {
if (b > a) a = b;
}
ll N, M, K, T;
Vec A;
string grid[MAXN];
;
ll Solution() {
int dp[N + 2][N + 2][N + 2][N + 2];
memset(dp, 0, sizeof dp);
for (int i = (int)(1); i < (int)(N + 1); ++i) {
for (int j = (int)(1); j < (int)(N + 1); ++j) {
dp[1][1][i][j] = (grid[i - 1][j - 1] == '#');
}
}
for (int h = (int)(1); h < (int)(N + 1); ++h) {
for (int w = (int)(1); w < (int)(N + 1); ++w) {
for (int i = (int)(1); i < (int)(N - h + 2); ++i) {
for (int j = (int)(1); j < (int)(N - w + 2); ++j) {
if (h == 1 && w == 1) continue;
dp[h][w][i][j] = max(h, w);
for (int k = (int)(0); k < (int)(h + 1); ++k) {
Min(dp[h][w][i][j], dp[k][w][i][j] + dp[h - k][w][i + k][j]);
}
for (int k = (int)(0); k < (int)(w + 1); ++k) {
Min(dp[h][w][i][j], dp[h][k][i][j] + dp[h][w - k][i][j + k]);
}
}
}
}
}
return dp[N][N][1][1];
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
while (cin >> N) {
for (int i = (int)(0); i < (int)(N); ++i) {
cin >> grid[i];
}
cout << Solution() << '\n';
}
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Alice and Bob begin their day with a quick game. They first choose a starting number X0 ≥ 3 and try to reach one million by the process described below.
Alice goes first and then they take alternating turns. In the i-th turn, the player whose turn it is selects a prime number smaller than the current number, and announces the smallest multiple of this prime number that is not smaller than the current number.
Formally, he or she selects a prime p < Xi - 1 and then finds the minimum Xi ≥ Xi - 1 such that p divides Xi. Note that if the selected prime p already divides Xi - 1, then the number does not change.
Eve has witnessed the state of the game after two turns. Given X2, help her determine what is the smallest possible starting number X0. Note that the players don't necessarily play optimally. You should consider all possible game evolutions.
Input
The input contains a single integer X2 (4 ≤ X2 ≤ 106). It is guaranteed that the integer X2 is composite, that is, is not prime.
Output
Output a single integer — the minimum possible X0.
Examples
Input
14
Output
6
Input
20
Output
15
Input
8192
Output
8191
Note
In the first test, the smallest possible starting number is X0 = 6. One possible course of the game is as follows:
* Alice picks prime 5 and announces X1 = 10
* Bob picks prime 7 and announces X2 = 14.
In the second case, let X0 = 15.
* Alice picks prime 2 and announces X1 = 16
* Bob picks prime 5 and announces X2 = 20.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long int x;
cin >> x;
vector<long long int> prime;
long long int n = x;
if (n % 2 == 0) {
prime.push_back(2);
while (n % 2 == 0) n /= 2;
}
for (int i = 3; i <= sqrt(n); i = i + 2) {
if (n % i == 0) {
prime.push_back(i);
while (n % i == 0) n = n / i;
}
}
if (n > 2) prime.push_back(n);
sort(prime.begin(), prime.end());
long long int great = prime[prime.size() - 1];
long long int lo = ((x / great) - 1) * great;
long long int ans = INT_MAX;
for (long long int i = lo + 1; i < x; i++) {
n = i;
vector<long long int> v;
if (n % 2 == 0) {
v.push_back(2);
while (n % 2 == 0) n /= 2;
}
for (int j = 3; j <= sqrt(n); j = j + 2) {
if (n % j == 0) {
v.push_back(j);
while (n % j == 0) n = n / j;
}
}
if (n > 2) v.push_back(n);
sort(v.begin(), v.end());
long long int val;
if (v[v.size() - 1] > 1) {
if ((((i / v[v.size() - 1]) - 1) * v[v.size() - 1]) > 0)
val = ((i / v[v.size() - 1]) - 1) * v[v.size() - 1];
else
val = i - 1;
ans = min(ans, val + 1);
}
}
cout << ans << endl;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Alice and Bob are playing a game with n piles of stones. It is guaranteed that n is an even number. The i-th pile has a_i stones.
Alice and Bob will play a game alternating turns with Alice going first.
On a player's turn, they must choose exactly n/2 nonempty piles and independently remove a positive number of stones from each of the chosen piles. They can remove a different number of stones from the piles in a single turn. The first player unable to make a move loses (when there are less than n/2 nonempty piles).
Given the starting configuration, determine who will win the game.
Input
The first line contains one integer n (2 ≤ n ≤ 50) — the number of piles. It is guaranteed that n is an even number.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 50) — the number of stones in the piles.
Output
Print a single string "Alice" if Alice wins; otherwise, print "Bob" (without double quotes).
Examples
Input
2
8 8
Output
Bob
Input
4
3 1 4 1
Output
Alice
Note
In the first example, each player can only remove stones from one pile (2/2=1). Alice loses, since Bob can copy whatever Alice does on the other pile, so Alice will run out of moves first.
In the second example, Alice can remove 2 stones from the first pile and 3 stones from the third pile on her first move to guarantee a win.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0, f = 0;
char ch = getchar();
while (!isdigit(ch)) f |= ch == '-', ch = getchar();
while (isdigit(ch)) x = x * 10 + (ch ^ 48), ch = getchar();
return f ? -x : x;
}
int a[500010];
signed main() {
int n = read();
for (int i = 1; i <= n; i++) a[i] = read();
sort(a + 1, a + n + 1);
puts(a[1] == a[n / 2 + 1] ? "Bob" : "Alice");
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
JAG mock qualifying practice session
The ACM-ICPC OB / OG Association (Japanese Alumni Group; JAG) has N questions in stock of questions to be asked in the mock contest, and each question is numbered with an integer from 1 to N. Difficulty evaluation and recommendation voting are conducted for each problem. Problem i has a difficulty level of di and a recommendation level of vi. The maximum difficulty level is M.
In the next contest, we plan to ask a total of M questions, one for each of the difficulty levels 1 to M. In order to improve the quality of the contest, I would like to select the questions so that the total recommendation level is maximized. However, since JAG's questioning ability is tremendous, it can be assumed that there is at least one question for each difficulty level.
Your job is to create a program that finds the maximum sum of the sums of recommendations when the questions are selected to meet the conditions.
Input
The input consists of multiple datasets. Each dataset is represented in the following format.
> N M
> d1 v1
> ...
> dN vN
>
The first line of the dataset is given an integer N, which represents the number of problem stocks, and a maximum difficulty value, M, separated by blanks. These numbers satisfy 1 ≤ M ≤ N ≤ 100. On the i-th line of the following N lines, the integers di and vi representing the difficulty level and recommendation level of problem i are given, separated by blanks. These numbers satisfy 1 ≤ di ≤ M and 0 ≤ vi ≤ 100. Also, for each 1 ≤ j ≤ M, it is guaranteed that there is at least one i such that di = j.
> The end of the input is represented by two zeros separated by a blank. Also, the number of datasets does not exceed 50.
> ### Output
For each data set, output the maximum value of the sum of the recommendation levels of the questions to be asked when one question is asked from each difficulty level on one line.
> ### Sample Input
5 3
1 1
twenty three
3 2
3 5
twenty one
4 2
1 7
twenty one
13
1 5
6 1
13
1 2
1 8
1 2
1 7
1 6
20 9
4 10
twenty four
5 3
6 6
6 3
7 4
8 10
4 6
7 5
1 8
5 7
1 5
6 6
9 9
5 8
6 7
14
6 4
7 10
3 5
19 6
4 1
6 5
5 10
1 10
3 10
4 6
twenty three
5 4
2 10
1 8
3 4
3 1
5 4
1 10
13
5 6
5 2
1 10
twenty three
0 0
There are 5 sample datasets, in order
Lines 1 to 6 are the first (N = 5, M = 3) test cases,
Lines 7 to 11 are the second (N = 4, M = 2) test case,
Lines 12-18 are the third (N = 6, M = 1) test case,
The fourth (N = 20, M = 9) test case from line 19 to line 39,
Lines 40 to 59 represent the fifth test case (N = 19, M = 6).
Output for Sample Input
9
8
8
71
51
Example
Input
5 3
1 1
2 3
3 2
3 5
2 1
4 2
1 7
2 1
1 3
1 5
6 1
1 3
1 2
1 8
1 2
1 7
1 6
20 9
4 10
2 4
5 3
6 6
6 3
7 4
8 10
4 6
7 5
1 8
5 7
1 5
6 6
9 9
5 8
6 7
1 4
6 4
7 10
3 5
19 6
4 1
6 5
5 10
1 10
3 10
4 6
2 3
5 4
2 10
1 8
3 4
3 1
5 4
1 10
1 3
5 6
5 2
1 10
2 3
0 0
Output
9
8
8
71
51
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
while(1) {
int n, m;
cin >> n >> m;
if(!n and !m) return 0;
vector<int> ans(m);
for(int i = 0; i < n; ++i) {
int d, x;
cin >> d >> x;
ans[d - 1] = max(ans[d - 1], x);
}
cout << accumulate(ans.begin(), ans.end(), 0LL) << endl;
}
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Translator's note: in Russia's most widespread grading system, there are four grades: 5, 4, 3, 2, the higher the better, roughly corresponding to A, B, C and F respectively in American grading system.
The term is coming to an end and students start thinking about their grades. Today, a professor told his students that the grades for his course would be given out automatically — he would calculate the simple average (arithmetic mean) of all grades given out for lab works this term and round to the nearest integer. The rounding would be done in favour of the student — 4.5 would be rounded up to 5 (as in example 3), but 4.4 would be rounded down to 4.
This does not bode well for Vasya who didn't think those lab works would influence anything, so he may receive a grade worse than 5 (maybe even the dreaded 2). However, the professor allowed him to redo some of his works of Vasya's choosing to increase his average grade. Vasya wants to redo as as few lab works as possible in order to get 5 for the course. Of course, Vasya will get 5 for the lab works he chooses to redo.
Help Vasya — calculate the minimum amount of lab works Vasya has to redo.
Input
The first line contains a single integer n — the number of Vasya's grades (1 ≤ n ≤ 100).
The second line contains n integers from 2 to 5 — Vasya's grades for his lab works.
Output
Output a single integer — the minimum amount of lab works that Vasya has to redo. It can be shown that Vasya can always redo enough lab works to get a 5.
Examples
Input
3
4 4 4
Output
2
Input
4
5 4 5 5
Output
0
Input
4
5 3 3 5
Output
1
Note
In the first sample, it is enough to redo two lab works to make two 4s into 5s.
In the second sample, Vasya's average is already 4.75 so he doesn't have to redo anything to get a 5.
In the second sample Vasya has to redo one lab work to get rid of one of the 3s, that will make the average exactly 4.5 so the final grade would be 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
const int base = 31337;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const int logo = 20;
const int off = 1 << logo;
const int treesiz = off << 1;
int n;
int niz[maxn];
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", niz + i);
niz[i] *= 2;
}
int sum = 0;
for (int i = 0; i < n; i++) sum += niz[i];
if (sum >= 9 * n)
printf("0");
else {
sort(niz, niz + n);
for (int i = 0; i < n; i++) {
sum += 10 - niz[i];
if (sum >= 9 * n) {
printf("%d\n", i + 1);
break;
}
}
}
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values of the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of bits in the cell.
The second line contains a string consisting of n characters — the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.
Output
Print a single integer — the number of bits in the cell which change their state after we add 1 to the cell.
Examples
Input
4
1100
Output
3
Input
4
1111
Output
4
Note
In the first sample the cell ends up with value 0010, in the second sample — with 0000.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int i, j, n;
int main() {
cin >> n;
string s;
cin >> s;
if (s[0] == 0) {
cout << 1;
return 0;
}
long long int ones = 0;
for (i = 0; i < s.size(); i++) {
if (s[i] == '1')
ones++;
else
break;
}
if (ones == n)
cout << n;
else
cout << i + 1;
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
A team of students from the city S is sent to the All-Berland Olympiad in Informatics. Traditionally, they go on the train. All students have bought tickets in one carriage, consisting of n compartments (each compartment has exactly four people). We know that if one compartment contain one or two students, then they get bored, and if one compartment contain three or four students, then the compartment has fun throughout the entire trip.
The students want to swap with other people, so that no compartment with students had bored students. To swap places with another person, you need to convince him that it is really necessary. The students can not independently find the necessary arguments, so they asked a sympathetic conductor for help. The conductor can use her life experience to persuade any passenger to switch places with some student.
However, the conductor does not want to waste time persuading the wrong people, so she wants to know what is the minimum number of people necessary to persuade her to change places with the students. Your task is to find the number.
After all the swaps each compartment should either have no student left, or have a company of three or four students.
Input
The first line contains integer n (1 ≤ n ≤ 106) — the number of compartments in the carriage. The second line contains n integers a1, a2, ..., an showing how many students ride in each compartment (0 ≤ ai ≤ 4). It is guaranteed that at least one student is riding in the train.
Output
If no sequence of swapping seats with other people leads to the desired result, print number "-1" (without the quotes). In another case, print the smallest number of people you need to persuade to swap places.
Examples
Input
5
1 2 2 4 3
Output
2
Input
3
4 1 1
Output
2
Input
4
0 3 0 4
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, x, k, z, tot, res;
int d[10];
int main() {
cin >> n;
for (int i = 1; i <= n; ++i) cin >> x, tot += x, d[x]++;
if (tot < 6 && tot != 4 && tot != 3) {
cout << -1 << endl;
exit(0);
}
if (d[2] > d[1])
k = 2;
else
k = 1;
z = d[3 - k];
res += z, d[k] -= z;
d[3] += z;
res += d[k] / 3 * 2, d[3] += d[k] / 3 * k, d[k] %= 3;
if (d[k] == 1 && d[k + 2])
++res;
else if (d[k])
res += 2;
cout << res << endl;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader is eliminated, and the next player after him becomes the new leader.
For example, if there are children with numbers [8, 10, 13, 14, 16] currently in the circle, the leader is child 13 and ai = 12, then counting-out rhyme ends on child 16, who is eliminated. Child 8 becomes the leader.
You have to write a program which prints the number of the child to be eliminated on every step.
Input
The first line contains two integer numbers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ n - 1).
The next line contains k integer numbers a1, a2, ..., ak (1 ≤ ai ≤ 109).
Output
Print k numbers, the i-th one corresponds to the number of child to be eliminated at the i-th step.
Examples
Input
7 5
10 4 11 4 1
Output
4 2 5 6 1
Input
3 2
2 5
Output
3 2
Note
Let's consider first example:
* In the first step child 4 is eliminated, child 5 becomes the leader.
* In the second step child 2 is eliminated, child 3 becomes the leader.
* In the third step child 5 is eliminated, child 6 becomes the leader.
* In the fourth step child 6 is eliminated, child 7 becomes the leader.
* In the final step child 1 is eliminated, child 3 becomes the leader.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long int i, j, n, t, k;
cin >> n >> k;
long long int a[k + 1];
for (i = 0; i < k; i++) {
cin >> a[i];
}
vector<long long int> v;
for (i = 1; i <= n; i++) {
v.push_back(i);
}
long long int leader = 0;
for (i = 0; i < k; i++) {
leader = (leader + a[i]) % n;
cout << v[leader] << " ";
v.erase(v.begin() + leader);
n--;
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Arcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor.
Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-empty prefix of some word on the screen, the editor proposes a possible autocompletion for this word, more precisely one of the already printed words such that its prefix matches the currently printed prefix if this word is unique. For example, if Arcady has already printed «codeforces», «coding» and «codeforces» once again, then there will be no autocompletion attempt for «cod», but if he proceeds with «code», the editor will propose «codeforces».
With a single click Arcady can follow the editor's proposal, i.e. to transform the current prefix to it. Note that no additional symbols are printed after the autocompletion (no spaces, line feeds, etc). What is the minimum number of keyboard clicks Arcady has to perform to print the entire text, if he is not allowed to move the cursor or erase the already printed symbols?
A word here is a contiguous sequence of latin letters bordered by spaces, punctuation signs and line/text beginnings/ends. Arcady uses only lowercase letters. For example, there are 20 words in «it's well-known that tic-tac-toe is a paper-and-pencil game for two players, x and o.».
Input
The only line contains Arcady's text, consisting only of lowercase latin letters, spaces, line feeds and the following punctuation signs: «.», «,», «?», «!», «'» and «-». The total amount of symbols doesn't exceed 3·105. It's guaranteed that all lines are non-empty.
Output
Print a single integer — the minimum number of clicks.
Examples
Input
snow affects sports such as skiing, snowboarding, and snowmachine travel.
snowboarding is a recreational activity and olympic and paralympic sport.
Output
141
Input
'co-co-co, codeforces?!'
Output
25
Input
thun-thun-thunder, thunder, thunder
thunder, thun-, thunder
thun-thun-thunder, thunder
thunder, feel the thunder
lightning then the thunder
thunder, feel the thunder
lightning then the thunder
thunder, thunder
Output
183
Note
In sample case one it's optimal to use autocompletion for the first instance of «snowboarding» after typing up «sn» and for the second instance of «snowboarding» after typing up «snowb». This will save 7 clicks.
In sample case two it doesn't matter whether to use autocompletion or not.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct Node {
int cnt;
int next[26];
Node() {
cnt = 0;
for (int i = 0; i < 26; ++i) next[i] = -1;
}
bool isLeaf;
};
Node nodes[1700000];
int sz = 1;
int answer = 0;
set<string> st;
void add_string(const string& s) {
bool isNeedPlusPlus = (st.find(s) == st.end());
if (isNeedPlusPlus) st.insert(s);
int v = 0;
int max_cnt = 0;
bool ok = 0;
for (size_t i = 0; i < s.length(); ++i) {
char c = s[i] - 'a';
if (nodes[v].next[c] == -1) {
nodes[v].next[c] = sz++;
}
if (nodes[v].cnt == 1 && !nodes[v].isLeaf) ++max_cnt;
if (v && isNeedPlusPlus) nodes[v].cnt++;
v = nodes[v].next[c];
if (nodes[v].cnt == 1 && nodes[v].isLeaf) ok = 1;
}
if (isNeedPlusPlus) nodes[v].cnt++;
nodes[v].isLeaf = true;
if (ok)
answer += min(s.size() - max_cnt + 1, s.size());
else
answer += s.size();
}
int main() {
string s;
while (getline(cin, s)) {
vector<string> v;
string cur = "";
for (int i = 0; i < s.size(); ++i) {
if (s[i] >= 'a' && s[i] <= 'z')
cur += s[i];
else {
if (cur != "") v.push_back(cur);
v.push_back(string(1, s[i]));
cur = "";
}
}
if (cur != "") v.push_back(cur);
for (int i = 0; i < v.size(); ++i) {
if (v[i][0] < 'a' || v[i][0] > 'z') {
answer++;
continue;
} else {
add_string(v[i]);
}
}
++answer;
}
cout << answer;
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
There are N pinholes on the xy-plane. The i-th pinhole is located at (x_i,y_i).
We will denote the Manhattan distance between the i-th and j-th pinholes as d(i,j)(=|x_i-x_j|+|y_i-y_j|).
You have a peculiar pair of compasses, called Manhattan Compass. This instrument always points at two of the pinholes. The two legs of the compass are indistinguishable, thus we do not distinguish the following two states: the state where the compass points at the p-th and q-th pinholes, and the state where it points at the q-th and p-th pinholes.
When the compass points at the p-th and q-th pinholes and d(p,q)=d(p,r), one of the legs can be moved so that the compass will point at the p-th and r-th pinholes.
Initially, the compass points at the a-th and b-th pinholes. Find the number of the pairs of pinholes that can be pointed by the compass.
Constraints
* 2≦N≦10^5
* 1≦x_i, y_i≦10^9
* 1≦a < b≦N
* When i ≠ j, (x_i, y_i) ≠ (x_j, y_j)
* x_i and y_i are integers.
Input
The input is given from Standard Input in the following format:
N a b
x_1 y_1
:
x_N y_N
Output
Print the number of the pairs of pinholes that can be pointed by the compass.
Examples
Input
5 1 2
1 1
4 3
6 1
5 5
4 8
Output
4
Input
6 2 3
1 3
5 3
3 5
8 4
4 7
2 5
Output
4
Input
8 1 2
1 5
4 3
8 2
4 7
8 8
3 3
6 6
4 8
Output
7
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
#define LL long long
const int maxn=1e5+10;
int n,A,B,D,cnt[maxn],f[maxn];
LL sz[maxn];
struct Point{
int x,y,id;
Point() {}
Point(int x,int y,int id):x(x),y(y),id(id) {}
bool operator < (const Point &p) const {return x==p.x?y<p.y:x<p.x;}
bool operator <= (const Point &p) const {return x==p.x?y<=p.y:x<p.x;}
bool operator == (const Point &p) const {return x==p.x&&y==p.y;}
}P[maxn];
int find(int x) {return x==f[x]?x:f[x]=find(f[x]);}
void Union(int x,int y,int times)
{
x=find(x); y=find(y);
if (x==y) {sz[x]+=times; return;}
sz[x]+=times+sz[y];
sz[y]=0; f[y]=x;
}
void solve(int flag)
{
int i,L=1,R=0;
memset(cnt,0,sizeof(cnt));
for (i=1;i<=n;i++)
{
while (L<=n&&P[L]<Point(P[i].x-D,P[i].y-D+flag,0)) L++;
while (R<n&&P[R+1]<=Point(P[i].x-D,P[i].y+D-flag,0)) R++;
if (L<=R) Union(P[i].id,P[L].id,1),cnt[L]++,cnt[R]--;
}
for (i=1;i<n;i++)
if (cnt[i]+=cnt[i-1]) Union(P[i].id,P[i+1].id,cnt[i]);
}
int main()
{
#ifdef h10
freopen("E.in","r",stdin);
freopen("E.out","w",stdout);
#endif
int i;
scanf("%d%d%d",&n,&A,&B);
for (i=1;i<=n;i++)
{
scanf("%d%d",&P[i].x,&P[i].y);
P[i]=Point(P[i].x-P[i].y,P[i].x+P[i].y,i);
}
D=max(abs(P[A].x-P[B].x),abs(P[A].y-P[B].y));
for (i=1;i<=n;i++) f[i]=i,sz[i]=0;
sort(P+1,P+n+1);
solve(0);
for (i=1;i<=n;i++)
swap(P[i].x,P[i].y);
sort(P+1,P+n+1);
solve(1);
printf("%lld\n",sz[find(A)]);
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Niwango-kun, an employee of Dwango Co., Ltd., likes Niconico TV-chan, so he collected a lot of soft toys of her and spread them on the floor.
Niwango-kun has N black rare soft toys of Niconico TV-chan and they are spread together with ordinary ones. He wanted these black rare soft toys to be close together, so he decided to rearrange them.
In an infinitely large two-dimensional plane, every lattice point has a soft toy on it. The coordinates (x_i,y_i) of N black rare soft toys are given. All soft toys are considered to be points (without a length, area, or volume).
He may perform the following operation arbitrarily many times:
* Put an axis-aligned square with side length D, rotate the square by 90 degrees with four soft toys on the four corners of the square. More specifically, if the left bottom corner's coordinate is (x, y), rotate four points (x,y) \rightarrow (x+D,y) \rightarrow (x+D,y+D) \rightarrow (x,y+D) \rightarrow (x,y) in this order. Each of the four corners of the square must be on a lattice point.
Let's define the scatteredness of an arrangement by the minimum side length of an axis-aligned square enclosing all black rare soft toys. Black rare soft toys on the edges or the vertices of a square are considered to be enclosed by the square.
Find the minimum scatteredness after he performs arbitrarily many operations.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq D \leq 1000
* 0 \leq x_i, y_i \leq 10^9
* Given coordinates are pairwise distinct
* All numbers given in input are integers
Input
Input is given from Standard Input in the following format:
N D
x_1 y_1
:
x_N y_N
Output
Print the answer.
Examples
Input
3 1
0 0
1 0
2 0
Output
1
Input
19 2
1 3
2 3
0 1
1 1
2 1
3 1
4 4
5 4
6 4
7 4
8 4
8 3
8 2
8 1
8 0
7 0
6 0
5 0
4 0
Output
4
Input
8 3
0 0
0 3
3 0
3 3
2 2
2 5
5 2
5 5
Output
4
### Response
```cpp
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n,d,v[3000][3000],s[3][3000][3000];
int S(int x1,int y1,int x2,int y2,int t)
{
return s[t][x2][y2]-s[t][x2][y1-1]-s[t][x1-1][y2]+s[t][x1-1][y1-1];
}
int check(int x)
{
int r=x%d;
for(int i=1;i<=d;i++)
for(int j=1;j<=d;j++)
{
int x1=i,y1=j,x2=x1+r,y2=y1+r,x3=x1+d-1,y3=y1+d-1;
if(!S(x1,y2+1,x3,y3,1)&&!S(x2+1,y1,x3,y3,1)&&!S(x2+1,y2+1,x3,y3,0))
return 1;
}
return 0;
}
int main()
{
scanf("%d%d",&n,&d);
memset(v,0,sizeof v);
for(int i=0;i<n;i++)
{
int x,y;
scanf("%d%d",&x,&y);
v[x%d+1][y%d+1]++;
}
int Mx=0,t;
for(int i=1;i<=d;i++)
for(int j=1;j<=d;j++)
v[i+d][j]=v[i][j+d]=v[i+d][j+d]=v[i][j],Mx=max(Mx,v[i][j]);
for(t=0;(t+1)*(t+1)<Mx;t++);
int l[3]={t*t+1,t*(t+1)+1,(int)1e9};
for(int i=1;i<=d*2;i++)
for(int j=1;j<=d*2;j++)
for(int t=0;t<2;t++)
{
s[t][i][j]=s[t][i-1][j]+s[t][i][j-1]-s[t][i-1][j-1];
if(l[t]<=v[i][j])
s[t][i][j]++;
}
int L=t*d,R=t*d+d,ans=R,mid;
while(L<=R)
if(check(mid=(L+R)>>1))
R=mid-1,ans=mid;
else
L=mid+1;
cout<<ans;
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
This is the easy version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved.
You are given an array [a_1, a_2, ..., a_n].
Your goal is to find the length of the longest subarray of this array such that the most frequent value in it is not unique. In other words, you are looking for a subarray such that if the most frequent value occurs f times in this subarray, then at least 2 different values should occur exactly f times.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
The first line contains a single integer n (1 ≤ n ≤ 200 000) — the length of the array.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ min(n, 100)) — elements of the array.
Output
You should output exactly one integer — the length of the longest subarray of the array whose most frequent value is not unique. If there is no such subarray, output 0.
Examples
Input
7
1 1 2 2 3 3 3
Output
6
Input
10
1 1 1 5 4 1 3 1 2 2
Output
7
Input
1
1
Output
0
Note
In the first sample, the subarray [1, 1, 2, 2, 3, 3] is good, but [1, 1, 2, 2, 3, 3, 3] isn't: in the latter there are 3 occurrences of number 3, and no other element appears 3 times.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 200005, M = 200000;
int n, a[N], cn[N], c[N], c0[N], ans, maxn, p[N << 1];
template <class I>
void Max(I& p, int q) {
p = (p > q ? p : q);
}
void ins(int x) { --c0[c[x]], ++c[x], ++c0[c[x]], Max(maxn, c[x]); }
void del(int x) { --c0[c[x]], --c[x], ++c0[c[x]], maxn -= (c0[maxn] == 0); }
int lst[N << 1];
int mx;
int solve1() {
int ans = 0;
int fix = 2e5;
for (int i = 1; i <= n; i++)
if (i != mx && cn[i] >= 512) {
for (int j = -n; j <= n; j++) lst[j + fix] = -1;
lst[fix] = 0;
int sum = 0;
for (int j = 1; j <= n; j++) {
sum += (a[j] == mx);
sum -= (a[j] == i);
if (lst[sum + fix] >= 0)
ans = max(ans, j - lst[sum + fix]);
else
lst[sum + fix] = j;
}
}
return ans;
}
int solve2() {
int ans = 0;
for (int i = 1; i <= 500; i++) {
for (int j = 1; j <= n; j++) c[j] = c0[j] = 0;
c0[maxn = 0] = n;
for (int j = 1, k = 1, x = 0; j <= n; j++) {
while (k <= n && x + (a[k] == mx) <= i) ins(a[k]), x += (a[k] == mx), ++k;
c0[maxn] >= 2 ? Max(ans, k - j), 0 : 0, del(a[j]), x -= (a[j] == mx);
}
}
return ans;
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]), ++cn[a[i]], cn[a[i]] > cn[mx] ? mx = a[i] : 0;
if (cn[mx] == n) return putchar('0'), 0;
int lim = (cn[mx] < 512 ? cn[mx] : 512);
ans = max(solve1(), solve2());
printf("%d", ans);
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
In BerSoft n programmers work, the programmer i is characterized by a skill r_i.
A programmer a can be a mentor of a programmer b if and only if the skill of the programmer a is strictly greater than the skill of the programmer b (r_a > r_b) and programmers a and b are not in a quarrel.
You are given the skills of each programmers and a list of k pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer i, find the number of programmers, for which the programmer i can be a mentor.
Input
The first line contains two integers n and k (2 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ k ≤ min(2 ⋅ 10^5, (n ⋅ (n - 1))/(2))) — total number of programmers and number of pairs of programmers which are in a quarrel.
The second line contains a sequence of integers r_1, r_2, ..., r_n (1 ≤ r_i ≤ 10^{9}), where r_i equals to the skill of the i-th programmer.
Each of the following k lines contains two distinct integers x, y (1 ≤ x, y ≤ n, x ≠ y) — pair of programmers in a quarrel. The pairs are unordered, it means that if x is in a quarrel with y then y is in a quarrel with x. Guaranteed, that for each pair (x, y) there are no other pairs (x, y) and (y, x) in the input.
Output
Print n integers, the i-th number should be equal to the number of programmers, for which the i-th programmer can be a mentor. Programmers are numbered in the same order that their skills are given in the input.
Examples
Input
4 2
10 4 10 15
1 2
4 3
Output
0 0 1 2
Input
10 4
5 4 1 5 4 3 7 1 2 5
4 6
2 1
10 8
3 5
Output
5 4 0 5 3 3 9 0 2 5
Note
In the first example, the first programmer can not be mentor of any other (because only the second programmer has a skill, lower than first programmer skill, but they are in a quarrel). The second programmer can not be mentor of any other programmer, because his skill is minimal among others. The third programmer can be a mentor of the second programmer. The fourth programmer can be a mentor of the first and of the second programmers. He can not be a mentor of the third programmer, because they are in a quarrel.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MaxN = 1e5;
int a[2 * MaxN + 5], ans[2 * MaxN + 5];
struct pp {
int w;
int id;
} b[2 * MaxN + 5];
bool cmp(pp x, pp y) { return x.w < y.w; }
int main() {
int n, m, mi, ma, x, u, v;
while (~scanf("%d %d", &n, &m)) {
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
b[i].id = i;
b[i].w = a[i];
}
sort(b + 1, b + 1 + n, cmp);
for (int i = 1; i <= n; i++) {
if (i > 1 && a[b[i].id] == a[b[i - 1].id])
ans[b[i].id] = ans[b[i - 1].id];
else
ans[b[i].id] = i - 1;
}
for (int i = 1; i <= m; i++) {
scanf("%d %d", &u, &v);
if (a[u] > a[v])
ans[u]--;
else if (a[v] > a[u])
ans[v]--;
}
for (int i = 1; i < n; i++) printf("%d ", ans[i]);
printf("%d\n", ans[n]);
}
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant.
In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant "n"; after this letter, there can be any letter (not only a vowel) or there can be no letter at all. For example, the words "harakiri", "yupie", "man", and "nbo" are Berlanese while the words "horse", "king", "my", and "nz" are not.
Help Vitya find out if a word s is Berlanese.
Input
The first line of the input contains the string s consisting of |s| (1≤ |s|≤ 100) lowercase Latin letters.
Output
Print "YES" (without quotes) if there is a vowel after every consonant except "n", otherwise print "NO".
You can print each letter in any case (upper or lower).
Examples
Input
sumimasen
Output
YES
Input
ninja
Output
YES
Input
codeforces
Output
NO
Note
In the first and second samples, a vowel goes after each consonant except "n", so the word is Berlanese.
In the third sample, the consonant "c" goes after the consonant "r", and the consonant "s" stands on the end, so the word is not Berlanese.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string m;
cin >> m;
for (int i = 0; i < m.size() - 1; i++) {
if ((m[i] != 'a') && (m[i] != 'i') && (m[i] != 'u') && (m[i] != 'o') &&
(m[i] != 'n') && (m[i] != 'e')) {
if ((m[i + 1] != 'a') && (m[i + 1] != 'i') && (m[i + 1] != 'u') &&
(m[i + 1] != 'o') && (m[i + 1] != 'e')) {
cout << "NO";
return 0;
}
}
}
if ((m[m.size() - 1] != 'a') && (m[m.size() - 1] != 'i') &&
(m[m.size() - 1] != 'u') && (m[m.size() - 1] != 'o') &&
(m[m.size() - 1] != 'n') && (m[m.size() - 1] != 'e'))
cout << "NO";
else
cout << "YES";
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Igor the analyst has adopted n little bunnies. As we all know, bunnies love carrots. Thus, Igor has bought a carrot to be shared between his bunnies. Igor wants to treat all the bunnies equally, and thus he wants to cut the carrot into n pieces of equal area.
Formally, the carrot can be viewed as an isosceles triangle with base length equal to 1 and height equal to h. Igor wants to make n - 1 cuts parallel to the base to cut the carrot into n pieces. He wants to make sure that all n pieces have the same area. Can you help Igor determine where to cut the carrot so that each piece have equal area?
<image> Illustration to the first example.
Input
The first and only line of input contains two space-separated integers, n and h (2 ≤ n ≤ 1000, 1 ≤ h ≤ 105).
Output
The output should contain n - 1 real numbers x1, x2, ..., xn - 1. The number xi denotes that the i-th cut must be made xi units away from the apex of the carrot. In addition, 0 < x1 < x2 < ... < xn - 1 < h must hold.
Your output will be considered correct if absolute or relative error of every number in your output doesn't exceed 10 - 6.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if <image>.
Examples
Input
3 2
Output
1.154700538379 1.632993161855
Input
2 100000
Output
70710.678118654752
Note
Definition of isosceles triangle: <https://en.wikipedia.org/wiki/Isosceles_triangle>.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 7;
const long long INFL = 1e18 + 123;
const double PI = atan2(0, -1);
int main() {
cerr << fixed << setprecision(15);
cout << fixed << setprecision(15);
int n, h;
scanf("%d%d", &n, &h);
double s = (h * 1) / 2.0 / n;
double cur = 1;
vector<double> ans;
for (int i = 0; i < n - 1; ++i) {
double l = cur, r = 0;
for (int j = 0; j < 100; ++j) {
double mid = (l + r) / 2;
if ((cur - mid) * h * (cur + mid) / 2 > s) {
r = mid;
} else {
l = mid;
}
}
ans.push_back(l * h);
cur = l;
}
sort(begin(ans), end(ans));
for (auto num : ans) {
cout << num << " ";
}
cout << "\n";
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Now that you have proposed a fake post for the HC2 Facebook page, Heidi wants to measure the quality of the post before actually posting it. She recently came across a (possibly fake) article about the impact of fractal structure on multimedia messages and she is now trying to measure the self-similarity of the message, which is defined as
<image>
where the sum is over all nonempty strings p and <image> is the number of occurences of p in s as a substring. (Note that the sum is infinite, but it only has a finite number of nonzero summands.)
Heidi refuses to do anything else until she knows how to calculate this self-similarity. Could you please help her? (If you would like to instead convince Heidi that a finite string cannot be a fractal anyway – do not bother, we have already tried.)
Input
The input starts with a line indicating the number of test cases T (1 ≤ T ≤ 10). After that, T test cases follow, each of which consists of one line containing a string s (1 ≤ |s| ≤ 100 000) composed of lowercase letters (a-z).
Output
Output T lines, every line containing one number – the answer to the corresponding test case.
Example
Input
4
aa
abcd
ccc
abcc
Output
5
10
14
12
Note
A string s contains another string p as a substring if p is a contiguous subsequence of s. For example, ab is a substring of cab but not of acb.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int t, Num_Edge, head[200001];
long long ret, siz[200001];
char s[200001];
struct Edge {
int v, nxt;
} E[300001];
void Add_Edge(int u, int v) {
E[++Num_Edge].v = v;
E[Num_Edge].nxt = head[u];
head[u] = Num_Edge;
}
struct SAM {
int tot = 1, pre = 1, fa[200001], v[200001], tr[200001][51];
void Clear() {
tot = pre = 1;
memset(fa, 0, sizeof(fa));
memset(v, 0, sizeof(v));
memset(tr, 0, sizeof(tr));
}
void Ins(int x) {
int now = ++tot, t = pre;
pre = now;
v[now] = v[t] + 1;
siz[now] = 1;
while (t && !tr[t][x]) {
tr[t][x] = now;
t = fa[t];
}
if (!t)
fa[now] = 1;
else if (v[tr[t][x]] == v[t] + 1)
fa[now] = tr[t][x];
else {
int nv = ++tot, pv = tr[t][x];
fa[nv] = fa[pv];
v[nv] = v[t] + 1;
for (int i = 0; i < 26; i++) tr[nv][i] = tr[pv][i];
while (t && tr[t][x] == pv) {
tr[t][x] = nv;
t = fa[t];
}
fa[now] = fa[pv] = nv;
}
}
} T;
void DFS(int x) {
for (int i = head[x]; i; i = E[i].nxt) {
DFS(E[i].v);
siz[x] += siz[E[i].v];
}
ret += siz[x] * siz[x] * (T.v[x] - T.v[T.fa[x]]);
}
int main() {
scanf("%d", &t);
while (t--) {
T.Clear();
ret = Num_Edge = 0;
memset(E, 0, sizeof(E));
memset(siz, 0, sizeof(siz));
memset(head, 0, sizeof(head));
scanf("%s", s);
int n = strlen(s);
for (int i = 0; i < n; i++) T.Ins(s[i] - 'a');
for (int i = 2; i <= T.tot; i++) Add_Edge(T.fa[i], i);
DFS(1);
printf("%lld\n", ret);
}
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
You are given a sequence of positive integers x1, x2, ..., xn and two non-negative integers a and b. Your task is to transform a into b. To do that, you can perform the following moves:
* subtract 1 from the current a;
* subtract a mod xi (1 ≤ i ≤ n) from the current a.
Operation a mod xi means taking the remainder after division of number a by number xi.
Now you want to know the minimum number of moves needed to transform a into b.
Input
The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers x1, x2, ..., xn (2 ≤ xi ≤ 109). The third line contains two integers a and b (0 ≤ b ≤ a ≤ 109, a - b ≤ 106).
Output
Print a single integer — the required minimum number of moves needed to transform number a into number b.
Examples
Input
3
3 4 5
30 17
Output
6
Input
3
5 6 7
1000 200
Output
206
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, a, b;
cin >> n;
vector<int> mod(n);
for (int i = 0; i < n; i++) cin >> mod[i];
sort(mod.begin(), mod.end());
mod.resize(unique(mod.begin(), mod.end()) - mod.begin());
n = mod.size();
cin >> a >> b;
priority_queue<pair<int, int>, vector<pair<int, int> >,
greater<pair<int, int> > >
next;
next.push(pair<int, int>(a, 0));
int ans = 0;
while (!next.empty()) {
pair<int, int> front = next.top();
next.pop();
int now = front.first, depth = front.second;
if (now == b) {
ans = depth;
break;
}
for (int i = 0; i < mod.size(); i++) {
int target = now - (now % mod[i]);
if (target >= b) next.push(pair<int, int>(target, depth + 1));
}
while (!mod.empty() && now - (now % mod.back()) < b) {
mod.pop_back();
}
next.push(pair<int, int>(now - 1, depth + 1));
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
Levian works as an accountant in a large company. Levian knows how much the company has earned in each of the n consecutive months — in the i-th month the company had income equal to a_i (positive income means profit, negative income means loss, zero income means no change). Because of the general self-isolation, the first ⌈ n/2 ⌉ months income might have been completely unstable, but then everything stabilized and for the last ⌊ n/2 ⌋ months the income was the same.
Levian decided to tell the directors n-k+1 numbers — the total income of the company for each k consecutive months. In other words, for each i between 1 and n-k+1 he will say the value a_i + a_{i+1} + … + a_{i + k - 1}. For example, if a=[-1, 0, 1, 2, 2] and k=3 he will say the numbers 0, 3, 5.
Unfortunately, if at least one total income reported by Levian is not a profit (income ≤ 0), the directors will get angry and fire the failed accountant.
Save Levian's career: find any such k, that for each k months in a row the company had made a profit, or report that it is impossible.
Input
The first line contains a single integer n (2 ≤ n ≤ 5⋅ 10^5) — the number of months for which Levian must account.
The second line contains ⌈{n/2}⌉ integers a_1, a_2, …, a_{⌈{n/2}⌉}, where a_i (-10^9 ≤ a_i ≤ 10^9) — the income of the company in the i-th month.
Third line contains a single integer x (-10^9 ≤ x ≤ 10^9) — income in every month from ⌈{n/2}⌉ + 1 to n.
Output
In a single line, print the appropriate integer k or -1, if it does not exist.
If there are multiple possible answers, you can print any.
Examples
Input
3
2 -1
2
Output
2
Input
5
2 2 -8
2
Output
-1
Input
6
-2 -2 6
-1
Output
4
Note
In the first example, k=2 and k=3 satisfy: in the first case, Levian will report the numbers 1, 1, and in the second case — one number 3.
In the second example, there is no such k.
In the third example, the only answer is k=4: he will report the numbers 1,2,3.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
mt19937 gen(chrono::steady_clock::now().time_since_epoch().count());
template <typename... T>
void rd(T&... args) {
((cin >> args), ...);
}
template <typename... T>
void wr(T... args) {
((cout << args << " "), ...);
cout << endl;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<ll> a(n);
for (int i = 0; i < int((n + 1) / 2); ++i) {
cin >> a[i];
}
int x;
cin >> x;
for (int i = (n + 1) / 2; i < n; i++) a[i] = x;
vector<ll> ps(n + 1);
partial_sum((a).begin(), (a).end(), ps.begin() + 1);
if (ps.back() > 0) return cout << n, 0;
if (x >= 0) return cout << -1, 0;
ll N2 = n / 2, N1 = n - N2, sum = ps.back();
ll mx = -1e18;
for (int i = 0; i <= N1; i++) {
mx = max(mx, ps[i] + x * ll(n - i));
if (mx < sum + x * ll(n - i)) {
cout << n - i;
return 0;
}
}
cout << -1;
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Let's denote a function f(x) in such a way: we add 1 to x, then, while there is at least one trailing zero in the resulting number, we remove that zero. For example,
* f(599) = 6: 599 + 1 = 600 → 60 → 6;
* f(7) = 8: 7 + 1 = 8;
* f(9) = 1: 9 + 1 = 10 → 1;
* f(10099) = 101: 10099 + 1 = 10100 → 1010 → 101.
We say that some number y is reachable from x if we can apply function f to x some (possibly zero) times so that we get y as a result. For example, 102 is reachable from 10098 because f(f(f(10098))) = f(f(10099)) = f(101) = 102; and any number is reachable from itself.
You are given a number n; your task is to count how many different numbers are reachable from n.
Input
The first line contains one integer n (1 ≤ n ≤ 10^9).
Output
Print one integer: the number of different numbers that are reachable from n.
Examples
Input
1098
Output
20
Input
10
Output
19
Note
The numbers that are reachable from 1098 are:
1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1098, 1099.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base ::sync_with_stdio(false);
cin.tie(NULL);
long long int n;
cin >> n;
set<long long int> s;
while (s.find(n) == s.end()) {
s.insert(n);
n += 1;
while (n % 10 == 0) n /= 10;
}
cout << s.size();
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
You are given a positive decimal number x.
Your task is to convert it to the "simple exponential notation".
Let x = a·10b, where 1 ≤ a < 10, then in general case the "simple exponential notation" looks like "aEb". If b equals to zero, the part "Eb" should be skipped. If a is an integer, it should be written without decimal point. Also there should not be extra zeroes in a and b.
Input
The only line contains the positive decimal number x. The length of the line will not exceed 106. Note that you are given too large number, so you can't use standard built-in data types "float", "double" and other.
Output
Print the only line — the "simple exponential notation" of the given number x.
Examples
Input
16
Output
1.6E1
Input
01.23400
Output
1.234
Input
.100
Output
1E-1
Input
100.
Output
1E2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
string s;
cin >> s;
size_t x = s.find_first_of("123456789");
size_t y = s.find_last_of("123456789");
size_t z = s.find('.');
if (z == string::npos) {
s += ".";
z = s.size() - 1;
}
if (x == string::npos) {
cout << 0 << endl;
} else {
int pow = (z < x) ? z - x : z - (x + 1);
string ss;
for (int i = x; i <= y; i++)
if (s[i] != '.') ss.push_back(s[i]);
cout << ss[0];
if (ss.size() > 1) cout << "." + ss.substr(1, ss.size() - 1);
if (pow != 0) cout << "E" << pow;
}
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
You have matrix a of size n × n. Let's number the rows of the matrix from 1 to n from top to bottom, let's number the columns from 1 to n from left to right. Let's use aij to represent the element on the intersection of the i-th row and the j-th column.
Matrix a meets the following two conditions:
* for any numbers i, j (1 ≤ i, j ≤ n) the following inequality holds: aij ≥ 0;
* <image>.
Matrix b is strictly positive, if for any numbers i, j (1 ≤ i, j ≤ n) the inequality bij > 0 holds. You task is to determine if there is such integer k ≥ 1, that matrix ak is strictly positive.
Input
The first line contains integer n (2 ≤ n ≤ 2000) — the number of rows and columns in matrix a.
The next n lines contain the description of the rows of matrix a. The i-th line contains n non-negative integers ai1, ai2, ..., ain (0 ≤ aij ≤ 50). It is guaranteed that <image>.
Output
If there is a positive integer k ≥ 1, such that matrix ak is strictly positive, print "YES" (without the quotes). Otherwise, print "NO" (without the quotes).
Examples
Input
2
1 0
0 1
Output
NO
Input
5
4 5 6 1 2
1 2 3 4 5
6 4 1 2 4
1 1 1 1 1
4 4 4 4 4
Output
YES
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2200;
const int MAXM = 4400000;
stack<int> sta;
int dfn[MAXN], low[MAXN], ins[MAXN];
int cntn, ans, n;
struct Edge {
int u, v, nxt;
} e[MAXM];
int e_cnt;
int head[MAXN];
void Add(int u, int v) {
int id = ++e_cnt;
e[id].u = u;
e[id].v = v;
e[id].nxt = head[u];
head[u] = id;
}
void Tarjan(int u) {
dfn[u] = low[u] = ++cntn;
sta.push(u);
ins[u] = 1;
for (int id = head[u]; ~id; id = e[id].nxt) {
int v = e[id].v;
if (!dfn[v]) {
Tarjan(v);
low[u] = min(low[u], low[v]);
} else if (ins[v])
low[u] = min(low[u], dfn[v]);
}
if (dfn[u] == low[u]) {
int v = -1;
while (u != v) {
v = sta.top();
ins[v] = 0;
sta.pop();
}
ans++;
}
}
int main() {
memset(head, -1, sizeof(head));
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
int x;
scanf("%d", &x);
if (x) Add(i, j);
}
}
for (int i = 1; i <= n; i++)
if (!dfn[i]) Tarjan(i);
if (ans > 1)
printf("NO");
else
printf("YES");
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
You are given a range of positive integers from l to r.
Find such a pair of integers (x, y) that l ≤ x, y ≤ r, x ≠ y and x divides y.
If there are multiple answers, print any of them.
You are also asked to answer T independent queries.
Input
The first line contains a single integer T (1 ≤ T ≤ 1000) — the number of queries.
Each of the next T lines contains two integers l and r (1 ≤ l ≤ r ≤ 998244353) — inclusive borders of the range.
It is guaranteed that testset only includes queries, which have at least one suitable pair.
Output
Print T lines, each line should contain the answer — two integers x and y such that l ≤ x, y ≤ r, x ≠ y and x divides y. The answer in the i-th line should correspond to the i-th query from the input.
If there are multiple answers, print any of them.
Example
Input
3
1 10
3 14
1 10
Output
1 7
3 9
5 10
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
vector<pair<int, int> > ans(t);
for (int i = 0; i < t; i++) {
int l;
int r;
cin >> l;
cin >> r;
ans[i].first = l;
ans[i].second = 2 * l;
}
for (int i = 0; i < t; i++) {
cout << ans[i].first << " " << ans[i].second << "\n";
}
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Long time ago Alex created an interesting problem about parallelogram. The input data for this problem contained four integer points on the Cartesian plane, that defined the set of vertices of some non-degenerate (positive area) parallelogram. Points not necessary were given in the order of clockwise or counterclockwise traversal.
Alex had very nice test for this problem, but is somehow happened that the last line of the input was lost and now he has only three out of four points of the original parallelogram. He remembers that test was so good that he asks you to restore it given only these three points.
Input
The input consists of three lines, each containing a pair of integer coordinates xi and yi ( - 1000 ≤ xi, yi ≤ 1000). It's guaranteed that these three points do not lie on the same line and no two of them coincide.
Output
First print integer k — the number of ways to add one new integer point such that the obtained set defines some parallelogram of positive area. There is no requirement for the points to be arranged in any special order (like traversal), they just define the set of vertices.
Then print k lines, each containing a pair of integer — possible coordinates of the fourth point.
Example
Input
0 0
1 0
0 1
Output
3
1 -1
-1 1
1 1
Note
If you need clarification of what parallelogram is, please check Wikipedia page:
https://en.wikipedia.org/wiki/Parallelogram
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int x1, y1, x2, y2, x3, y3;
scanf("%d %d %d %d %d %d", &x1, &y1, &x2, &y2, &x3, &y3);
int a, b;
printf("3\n%d %d\n%d %d\n%d %d\n", x1 - x2 + x3, y1 - y2 + y3, x2 - x3 + x1,
y2 - y3 + y1, x3 - x1 + x2, y3 - y1 + y2);
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
There are N islands floating in Ringo Sea, and M travel agents operate ships between these islands. For convenience, we will call these islands Island 1, 2, …, N, and call these agents Agent 1, 2, …, M.
The sea currents in Ringo Sea change significantly each day. Depending on the state of the sea on the day, Agent i (1 ≤ i ≤ M) operates ships from Island a_i to b_i, or Island b_i to a_i, but not both at the same time. Assume that the direction of the ships of each agent is independently selected with equal probability.
Now, Takahashi is on Island 1, and Hikuhashi is on Island 2. Let P be the probability that Takahashi and Hikuhashi can travel to the same island in the day by ships operated by the M agents, ignoring the factors such as the travel time for ships. Then, P × 2^M is an integer. Find P × 2^M modulo 10^9 + 7.
Constraints
* 2 ≤ N ≤ 15
* 1 ≤ M ≤ N(N-1)/2
* 1 ≤ a_i < b_i ≤ N
* All pairs (a_i, b_i) are distinct.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
Print the value P × 2^M modulo 10^9 + 7.
Examples
Input
4 3
1 3
2 3
3 4
Output
6
Input
5 5
1 3
2 4
3 4
3 5
4 5
Output
18
Input
6 6
1 2
2 3
3 4
4 5
5 6
1 6
Output
64
### Response
```cpp
#pragma GCC target("avx") // CPU 処理並列化
#pragma GCC optimize("O3") // CPU 処理並列化
#pragma GCC optimize("unroll-loops") // 条件処理の呼び出しを減らす
// #define BEGIN_STACK_EXTEND(size) void * stack_extend_memory_ = malloc(size);void * stack_extend_origin_memory_;char * stack_extend_dummy_memory_ = (char*)alloca((1+(int)(((long long)stack_extend_memory_)&127))*16);*stack_extend_dummy_memory_ = 0;asm volatile("mov %%rsp, %%rbx\nmov %%rax, %%rsp":"=b"(stack_extend_origin_memory_):"a"((char*)stack_extend_memory_+(size)-1024));
// #define END_STACK_EXTEND asm volatile("mov %%rax, %%rsp"::"a"(stack_extend_origin_memory_));free(stack_extend_memory_);
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<queue>
#include<deque>
#include<stack>
#include<string>
#include<string.h>
#include<vector>
#include<set>
#include<map>
#include<bitset>
#include<stdlib.h>
#include<cassert>
#include<time.h>
#include<bitset>
#include<numeric>
#include<unordered_set>
#include<unordered_map>
#include<complex>
using namespace std;
const long long mod=1000000007;
const long long inf=mod*mod;
const long long d2=(mod+1)/2;
const double EPS=1e-11;
const double INF=1e+10;
const double PI=acos(-1.0);
const int C_SIZE = 11100000;
const int UF_SIZE = 3100000;
namespace{
long long fact[C_SIZE];
long long finv[C_SIZE];
long long inv[C_SIZE];
inline long long Comb(int a,int b){
if(a<b||b<0)return 0;
return fact[a]*finv[b]%mod*finv[a-b]%mod;
}
void init_C(int n){
fact[0]=finv[0]=inv[1]=1;
for(int i=2;i<n;i++){
inv[i]=(mod-(mod/i)*inv[mod%i]%mod)%mod;
}
for(int i=1;i<n;i++){
fact[i]=fact[i-1]*i%mod;
finv[i]=finv[i-1]*inv[i]%mod;
}
}
long long pw(long long a,long long b){
if(a<0LL)return 0;
if(b<0LL)return 0;
long long ret=1;
while(b){
if(b%2)ret=ret*a%mod;
a=a*a%mod;
b/=2;
}
return ret;
}
long long pw_mod(long long a,long long b,long long M){
if(a<0LL)return 0;
if(b<0LL)return 0;
long long ret=1;
while(b){
if(b%2)ret=ret*a%M;
a=a*a%M;
b/=2;
}
return ret;
}
int pw_mod_int(int a,int b,int M){
if(a<0)return 0;
if(b<0)return 0;
int ret=1;
while(b){
if(b%2)ret=(long long)ret*a%M;
a=(long long)a*a%M;
b/=2;
}
return ret;
}
int ABS(int a){return max(a,-a);}
long long ABS(long long a){return max(a,-a);}
double ABS(double a){return max(a,-a);}
int sig(double r) { return (r < -EPS) ? -1 : (r > +EPS) ? +1 : 0; }
int UF[UF_SIZE];
void init_UF(int n){
for(int i=0;i<n;i++)UF[i]=-1;
}
int FIND(int a){
if(UF[a]<0)return a;
return UF[a]=FIND(UF[a]);
}
void UNION(int a,int b){
a=FIND(a);b=FIND(b);if(a==b)return;
if(UF[a]>UF[b])swap(a,b);
UF[a]+=UF[b];UF[b]=a;
}
}
// ここから編集しろ
long long dp[1<<15];
int p3[16];
int n;
int g[20][20];
int C[16][1<<15];
long long calc(int a){
if(~dp[a])return dp[a];
long long ret=1;
int t=0;
if(!(a&1))t=1;
int tmp=a;
while(tmp){
if(tmp!=a&&(tmp&(1<<t))){
int cnt=0;
for(int i=0;i<n;i++){
if(!(tmp&(1<<i)))continue;
cnt+=C[i][a-tmp];
}
ret=(ret+mod-calc(tmp)*pw(d2,cnt)%mod)%mod;
}
tmp=(tmp-1)&a;
}
// printf("%d: %lld\n",a,ret);
return dp[a]=ret;
}
int main(){
int a,b;scanf("%d%d",&a,&b);n=a;
for(int i=0;i<b;i++){
int s,t;scanf("%d%d",&s,&t);s--;t--;
g[s][t]=g[t][s]=1;
}
for(int i=0;i<a;i++){
for(int j=0;j<(1<<a);j++){
for(int k=0;k<a;k++){
if(j&(1<<k)){
if(g[i][k])C[i][j]++;
}
}
}
}
long long ret=0;
p3[0]=1;
for(int i=0;i<(1<<a);i++)dp[i]=-1;
for(int i=1;i<16;i++)p3[i]=p3[i-1]*3;
for(int i=0;i<p3[a];i++){
int A=0;
int B=0;
for(int j=0;j<a;j++){
if(i/p3[j]%3==1)A+=(1<<j);
if(i/p3[j]%3==2)B+=(1<<j);
}
if(!(A&1))continue;
if(!(B&2))continue;
bool ok=true;
int cnt=0;
for(int j=0;j<a;j++){
if(!(A&(1<<j)))continue;
if(C[j][B])ok=false;
}
if(!ok)continue;
for(int j=0;j<a;j++){
if(!(A&(1<<j)))continue;
cnt+=C[j][(1<<a)-1-A];
}
for(int j=0;j<a;j++){
if(!(B&(1<<j)))continue;
cnt+=C[j][(1<<a)-1-B];
}
// printf("%d: %lld\n",i,pw(d2,cnt)*calc(A)%mod*calc(B)%mod);
ret=(ret+pw(d2,cnt)*calc(A)%mod*calc(B))%mod;
}
ret=(1+mod-ret)%mod;
ret=ret*pw(2,b)%mod;
printf("%lld\n",ret);
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Alice and Bob play 5-in-a-row game. They have a playing field of size 10 × 10. In turns they put either crosses or noughts, one at a time. Alice puts crosses and Bob puts noughts.
In current match they have made some turns and now it's Alice's turn. She wonders if she can put cross in such empty cell that she wins immediately.
Alice wins if some crosses in the field form line of length not smaller than 5. This line can be horizontal, vertical and diagonal.
Input
You are given matrix 10 × 10 (10 lines of 10 characters each) with capital Latin letters 'X' being a cross, letters 'O' being a nought and '.' being an empty cell. The number of 'X' cells is equal to the number of 'O' cells and there is at least one of each type. There is at least one empty cell.
It is guaranteed that in the current arrangement nobody has still won.
Output
Print 'YES' if it's possible for Alice to win in one turn by putting cross in some empty cell. Otherwise print 'NO'.
Examples
Input
XX.XX.....
.....OOOO.
..........
..........
..........
..........
..........
..........
..........
..........
Output
YES
Input
XXOXX.....
OO.O......
..........
..........
..........
..........
..........
..........
..........
..........
Output
NO
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using vs = vector<string>;
bool gen(vs& v, int i, int j, int di, int dj) {
int cnt = 0;
for (int k = 0; k < 5 && i >= 0 && i < 10 && j >= 0 && j < 10;
k++, i += di, j += dj) {
cnt += v[i][j] == 'X';
}
return cnt == 5;
}
int check(vs& v) {
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++) {
if (gen(v, i, j, 0, 1)) return 1;
if (gen(v, i, j, 1, 0)) return 1;
if (gen(v, i, j, 1, 1)) return 1;
if (gen(v, i, j, 1, -1)) return 1;
}
return 0;
}
int main() {
ios_base::sync_with_stdio(0);
vs v(10);
for (int i = 0; i < 10; i++) cin >> v[i];
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
if (v[i][j] == '.') {
v[i][j] = 'X';
if (check(v)) {
cout << "YES" << endl;
return 0;
}
v[i][j] = '.';
}
cout << "NO" << endl;
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddly shaped, interlocking and tessellating pieces).
The shop assistant told the teacher that there are m puzzles in the shop, but they might differ in difficulty and size. Specifically, the first jigsaw puzzle consists of f1 pieces, the second one consists of f2 pieces and so on.
Ms. Manana doesn't want to upset the children, so she decided that the difference between the numbers of pieces in her presents must be as small as possible. Let A be the number of pieces in the largest puzzle that the teacher buys and B be the number of pieces in the smallest such puzzle. She wants to choose such n puzzles that A - B is minimum possible. Help the teacher and find the least possible value of A - B.
Input
The first line contains space-separated integers n and m (2 ≤ n ≤ m ≤ 50). The second line contains m space-separated integers f1, f2, ..., fm (4 ≤ fi ≤ 1000) — the quantities of pieces in the puzzles sold in the shop.
Output
Print a single integer — the least possible difference the teacher can obtain.
Examples
Input
4 6
10 12 10 7 5 22
Output
5
Note
Sample 1. The class has 4 students. The shop sells 6 puzzles. If Ms. Manana buys the first four puzzles consisting of 10, 12, 10 and 7 pieces correspondingly, then the difference between the sizes of the largest and the smallest puzzle will be equal to 5. It is impossible to obtain a smaller difference. Note that the teacher can also buy puzzles 1, 3, 4 and 5 to obtain the difference 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int i, n, m, mn = 996;
cin >> n >> m;
int a[m];
for (i = 0; i < m; i++) cin >> a[i];
sort(a, a + m);
for (i = 0; i <= m - n; i++)
if (a[n + i - 1] - a[i] < mn) mn = a[n + i - 1] - a[i];
cout << mn;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.
Output
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
Examples
Input
2
2 1
1 2
Output
1
Input
2
2 1
4 1
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
set<int> a, b;
vector<pair<int, int> > z;
int aa[101] = {0};
int n;
void refresh() {
for (__typeof((n)) i = (0); i < (n); i += 1) {
if (aa[i] == 0) {
if (a.find(z[i].first) != a.end() || b.find(z[i].second) != b.end()) {
a.insert(z[i].first);
b.insert(z[i].second);
aa[i] = 1;
refresh();
break;
}
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
int ans = -1;
for (__typeof((n)) i = (0); i < (n); i += 1) {
int x, y;
cin >> x >> y;
z.push_back(make_pair(x, y));
}
for (__typeof((n)) i = (0); i < (n); i += 1) {
if (aa[i] == 0) {
aa[i] = 1;
if (a.find(z[i].first) == a.end() && b.find(z[i].second) == b.end()) {
ans++;
a.insert(z[i].first);
b.insert(z[i].second);
refresh();
}
a.insert(z[i].first);
b.insert(z[i].second);
}
}
cout << ans;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
Input
The first line contains a single string s (1 ≤ |s| ≤ 103).
The second line contains a single integer k (0 ≤ k ≤ 103).
The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Output
Print a single integer — the largest possible value of the resulting string DZY could get.
Examples
Input
abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
41
Note
In the test sample DZY can obtain "abcbbc", value = 1·1 + 2·2 + 3·2 + 4·2 + 5·2 + 6·2 = 41.
### Response
```cpp
#include <bits/stdc++.h>
#pragma optimization_level 3
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx")
using namespace std;
using ll = long long;
using ld = long double;
const ll MOD = 1e+9 + 7;
const ll INF = LLONG_MAX;
const int N = (int)2e+5 + 8;
template <typename T>
string itos(T i) {
stringstream second;
second << i;
return second.str();
}
bool sortbysec(const pair<int, int> &a, const pair<int, int> &b) {
return (a.second < b.second);
}
int main() {
ios_base ::sync_with_stdio(false);
cout.tie(NULL);
cin.tie(NULL);
string second;
cin >> second;
int n;
cin >> n;
vector<pair<int, char>> vec;
int arr[123] = {0};
for (char i = 'a'; i <= 'z'; i++) {
int a;
cin >> a;
vec.push_back({a, i});
arr[i] = a;
}
sort(vec.begin(), vec.end());
reverse(vec.begin(), vec.end());
int temp = vec[0].first;
int index = 1;
ll res = 0;
for (int i = 0; i < second.length(); i++) {
res += index * arr[second[i]];
index++;
}
for (; index <= second.length() + n; index++) {
res += index * temp;
}
cout << res;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
In this problem, a n × m rectangular matrix a is called increasing if, for each row of i, when go from left to right, the values strictly increase (that is, a_{i,1}<a_{i,2}<...<a_{i,m}) and for each column j, when go from top to bottom, the values strictly increase (that is, a_{1,j}<a_{2,j}<...<a_{n,j}).
In a given matrix of non-negative integers, it is necessary to replace each value of 0 with some positive integer so that the resulting matrix is increasing and the sum of its elements is maximum, or find that it is impossible.
It is guaranteed that in a given value matrix all values of 0 are contained only in internal cells (that is, not in the first or last row and not in the first or last column).
Input
The first line contains integers n and m (3 ≤ n, m ≤ 500) — the number of rows and columns in the given matrix a.
The following lines contain m each of non-negative integers — the values in the corresponding row of the given matrix: a_{i,1}, a_{i,2}, ..., a_{i,m} (0 ≤ a_{i,j} ≤ 8000).
It is guaranteed that for all a_{i,j}=0, 1 < i < n and 1 < j < m are true.
Output
If it is possible to replace all zeros with positive numbers so that the matrix is increasing, print the maximum possible sum of matrix elements. Otherwise, print -1.
Examples
Input
4 5
1 3 5 6 7
3 0 7 0 9
5 0 0 0 10
8 9 10 11 12
Output
144
Input
3 3
1 2 3
2 0 4
4 5 6
Output
30
Input
3 3
1 2 3
3 0 4
4 5 6
Output
-1
Input
3 3
1 2 3
2 3 4
3 4 2
Output
-1
Note
In the first example, the resulting matrix is as follows:
1 3 5 6 7
3 6 7 8 9
5 7 8 9 10
8 9 10 11 12
In the second example, the value 3 must be put in the middle cell.
In the third example, the desired resultant matrix does not exist.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline void filee() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
}
int main() {
int n, m;
cin >> m >> n;
int sum = 0;
int a[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> a[i][j];
sum += a[i][j];
}
}
for (int i = m - 1; i >= 1; i--) {
for (int j = n - 1; j >= 1; j--) {
if (a[i][j] == 0) {
a[i][j] = min(a[i + 1][j], a[i][j + 1]) - 1;
sum += a[i][j];
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 1; j < n; j++) {
if (a[i][j] <= a[i][j - 1]) {
cout << -1;
return 0;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 1; j < m; j++) {
if (a[j][i] <= a[j - 1][i]) {
cout << -1;
return 0;
}
}
}
cout << sum;
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Pavel loves grid mazes. A grid maze is an n × m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input
The first line contains three integers n, m, k (1 ≤ n, m ≤ 500, 0 ≤ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze.
Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.
Output
Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.
Examples
Input
3 4 2
#..#
..#.
#...
Output
#.X#
X.#.
#...
Input
5 4 5
#...
#.#.
.#..
...#
.#.#
Output
#XXX
#X#.
X#..
...#
.#.#
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int row[] = {-1, 0, 0, 1};
int col[] = {0, -1, 1, 0};
int n, m, k;
char matrix[501][501];
bool visited[501][501] = {0};
bool isValid(int i, int j) {
if (i >= 0 && i < n && j >= 0 && j < m) return true;
return false;
}
void dfs(int i, int j) {
visited[i][j] = 1;
for (int x = 0; x < 4; x++) {
int new_i = i + row[x];
int new_j = j + col[x];
if (isValid(new_i, new_j) && !visited[new_i][new_j] &&
matrix[new_i][new_j] == '.')
dfs(new_i, new_j);
}
if (k == 0)
return;
else {
matrix[i][j] = 'X';
k--;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m >> k;
bool flag = true;
int start_i, start_j;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> matrix[i][j];
if (flag && matrix[i][j] == '.') {
start_i = i;
start_j = j;
flag = false;
}
}
}
dfs(start_i, start_j);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << matrix[i][j];
}
cout << "\n";
}
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
<image>
To monitor cryptocurrency exchange rates trader William invented a wonderful device consisting of n lights arranged in a row. The device functions in the following way:
Initially, all lights on William's device are turned off. At the beginning of a new iteration the device randomly, with a uniform distribution, picks a light that is turned off and turns it on, telling William which cryptocurrency he should invest in. After this iteration if any k consecutive lights contain more than one turned on light, then the device finishes working.
William doesn't like uncertainty, so he wants you to calculate the expected value of the number of lights that are turned on in the device after it finishes working.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10). Description of the test cases follows.
The only line for each test case contains two integers n and k (2 ≤ k ≤ n ≤ 10^5), which are the total number of lights and the length of subsegment of lights that are being checked, respectively.
Output
For each test case print the answer, modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}.
Example
Input
3
3 2
15 2
40 15
Output
333333338
141946947
329622137
Note
Explanation of the first sample test case:
Let's write out all possible sequences of light toggles, which will make the device complete its operation:
1. (1, 2) — 2 lights are turned on
2. (1, 3, 2) — 3 lights are turned on
3. (2, 1) — 2 lights are turned on
4. (2, 3) — 2 lights are turned on
5. (3, 2) — 2 lights are turned on
6. (3, 1, 2) — 3 lights are turned on
Then the final expected value will be equal to 2/6 + 3/6 + 2/6 + 2/6 + 2/6 + 3/6 = 14/6 = 7/3.
Then the required output will be 333333338, since 333333338 ⋅ 3 ≡ 7 \pmod{10^9+7}.
### Response
```cpp
#include <cstdio>
#include <cassert>
const int MOD=1e9+7;
int inv[200005]={0,1};
int fact[200005]={1,1};
int invfact[200005]={1,1};
int choose(int n,int k){
if(k<0||k>n) return 0;
return 1LL*fact[n]*invfact[k]%MOD*invfact[n-k]%MOD;
}
int invchoose(int n,int k){
if(k<0||k>n) return 0;
return 1LL*invfact[n]*fact[k]%MOD*fact[n-k]%MOD;
}
void solve(){
int ans=0;
int N,K;
scanf("%d %d",&N,&K);
for(int l=0;N>=(l-1)*(K-1);l++){
ans=(ans+1LL*invchoose(N,l)*choose(N-(l-1)*(K-1),l))%MOD;
//printf("%d=>%d: %d ways\n",l,l+1,choose(N-(l-1)*(K-1),l));
}
printf("%d\n",ans);
}
int main(){
for(int i=2;i<=200000;i++){
inv[i]=1LL*(MOD-MOD/i)*inv[MOD%i]%MOD;
//printf("%lld\n",1LL*i*inv[i]%MOD);
fact[i]=1LL*i*fact[i-1]%MOD;
invfact[i]=1LL*inv[i]*invfact[i-1]%MOD;
//printf("%lld\n",1LL*fact[i]*invfact[i]%MOD);
}
int T;
scanf("%d",&T);
while(T--){
solve();
}
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
There is a very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage, he penetrated into the Potatoland territory and reached the secret base.
Now he is standing at the entrance, but to get inside he need to pass combination lock. Minute ago one of the workers entered the password on the terminal and opened the door. The terminal is a square digital keyboard 3 × 3 with digits from 1 to 9.
Pearlo knows that the password consists from distinct digits and is probably symmetric with respect to the central button of the terminal. He has heat sensor which allowed him to detect the digits which the worker pressed. Now he wants to check whether the password entered by the worker is symmetric with respect to the central button of the terminal. This fact can Help Pearlo to reduce the number of different possible password combinations.
Input
Input contains the matrix of three rows of three symbols each. Symbol «X» means that the corresponding button was pressed, and «.» means that is was not pressed. The matrix may contain no «X», also it may contain no «.».
Output
Print YES if the password is symmetric with respect to the central button of the terminal and NO otherwise.
Examples
Input
XX.
...
.XX
Output
YES
Input
X.X
X..
...
Output
NO
Note
If you are not familiar with the term «central symmetry», you may look into http://en.wikipedia.org/wiki/Central_symmetry
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int i, j, flag, k;
char matrix[3][3];
int d[9] = {0};
k = 0;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
cin >> matrix[i][j];
k++;
if (matrix[i][j] == 'X') {
d[k - 1] = 1;
}
}
}
flag = 0;
for (i = 0; i < 9; i++) {
if ((d[0] && !d[8]) || (!d[0] && d[8])) {
flag = 1;
}
if ((d[1] && !d[7]) || (!d[1] && d[7])) {
flag = 1;
}
if ((d[2] && !d[6]) || (!d[2] && d[6])) {
flag = 1;
}
if ((d[3] && !d[5]) || (!d[3] && d[5])) {
flag = 1;
}
}
if (flag == 1) {
cout << "NO\n";
} else {
cout << "YES\n";
}
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Recent improvements in information and communication technology have made it possible to provide municipal service to a wider area more quickly and with less costs. Stimulated by this, and probably for saving their not sufficient funds, mayors of many cities started to discuss on mergers of their cities.
There are, of course, many obstacles to actually put the planned mergers in practice. Each city has its own culture of which citizens are proud. One of the largest sources of friction is with the name of the new city. All citizens would insist that the name of the new city should have the original name of their own city at least as a part of it. Simply concatenating all the original names would, however, make the name too long for everyday use.
You are asked by a group of mayors to write a program that finds the shortest possible name for the new city that includes all the original names of the merged cities. If two or more cities have common parts, they can be overlapped. For example, if "FUKUOKA", "OKAYAMA", and "YAMAGUCHI" cities are to be merged, "FUKUOKAYAMAGUCHI" is such a name that include all three of the original city names. Although this includes all the characters of the city name "FUKUYAMA" in this order, it does not appear as a consecutive substring, and thus "FUKUYAMA" is not considered to be included in the name.
Input
The input is a sequence of datasets. Each dataset begins with a line containing a positive integer n (n ≤ 14), which denotes the number of cities to be merged. The following n lines contain the names of the cities in uppercase alphabetical letters, one in each line. You may assume that none of the original city names has more than 20 characters. Of course, no two cities have the same name.
The end of the input is indicated by a line consisting of a zero.
Output
For each dataset, output the length of the shortest possible name of the new city in one line. The output should not contain any other characters.
Examples
Input
3
Output
16
Input
3
FUKUOKA
OKAYAMA
YAMAGUCHI
3
FUKUOKA
FUKUYAMA
OKAYAMA
2
ABCDE
EDCBA
4
GA
DEFG
CDDE
ABCD
2
ABCDE
C
14
AAAAA
BBBBB
CCCCC
DDDDD
EEEEE
FFFFF
GGGGG
HHHHH
IIIII
JJJJJ
KKKKK
LLLLL
MMMMM
NNNNN
0
Output
16
19
9
9
5
70
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> PI;
const double EPS=1e-6;
#define rep(i,n) for(int i=0;i<(int)(n);++i)
#define F first
#define S second
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)
#define SZ(a) (int)((a).size())
#define ALL(a) (a).begin(),(a).end()
#define RALL(a) a.rbegin(),a.rend()
#define FLL(a,b) memset((a),b,sizeof(a))
#define CLR(a) FLL(a,0)
#define declare(a,it) __typeof(a) it=(a)
#define FOR(it,a) for(declare(a.begin(),it);it!=a.end();++it)
#define FORR(it,a) for(declare(a.rbegin(),it);it!=a.rend();++it)
template<class T,class U> ostream& operator<< (ostream& o, const pair<T,U>& v){return o << "(" << v.F << ", " << v.S << ")";}
template<class T> ostream& operator<< (ostream& o, const vector<T>& v){o << "{";rep(i,SZ(v)) o << (i?", ":"") << v[i];return o << "}";}
int dx[]={0,1,0,-1,1,1,-1,-1};
int dy[]={1,0,-1,0,-1,1,1,-1};
int s2i(string& a){stringstream ss(a);int r;ss>>r;return r;}
int geti(){int n;scanf("%d", &n);return n;}
int n;
string in[100];
int over(string a,string b){
int ov = min(a.size(),b.size()) - 1;
for(;ov;--ov){
if(a.substr(a.size()-ov) == b.substr(0,ov)){
//cout << a << " " << b << " " << ov << endl;
return ov;
}
}
return 0;
}
int cost[100][100];
int memo[1<<14][14];
int rec(int st,int l){
if(st == (1<<l)){
//cout << "hitt" << endl;
return 0;//cost[l][l];
}
if(memo[st][l] >= 0)
return memo[st][l];
int& ret = memo[st][l] = 0;
for(int i = 0; (1<<i) <= st; ++i){
if(~st&(1<<i)) continue;
if(i == l) continue;
ret = max(ret, cost[i][l] + rec(st^(1<<l),i));
}
//cout << st << " " << l << " " << ret << endl;
return ret;
}
int main(){
while(cin >> n && n){
set<string> app;
for(int i = 0; i < n; ++i){
string s;
cin >> s;
app.insert(s);
}
set<string> use;
for(auto s : app){
bool ok = 1;
for(auto e : app){
if(s == e) continue;
ok &= e.find(s) == string::npos;
}
if(ok) use.insert(s);
}
vector<string> vs(use.begin(), use.end());
memset(cost, 0 , sizeof(cost));
for(int i = 0; i < vs.size(); ++i){
for(int j = 0; j < vs.size(); ++j)
cost[i][j] = over(vs[i], vs[j]);
cost[i][i] = 0;//vs[i].size();
}
int ans = 0;
memset(memo,-1 ,sizeof(memo));
int sum = 0;
for(int i = 0; i < vs.size(); ++i){
ans = max(ans, rec((1<<vs.size()) - 1, i));
sum += vs[i].size();
}
cout << sum - ans << endl;
}
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character.
You are playing the game on the new generation console so your gamepad have 26 buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons are pairwise distinct.
You are given a sequence of hits, the i-th hit deals a_i units of damage to the opponent's character. To perform the i-th hit you have to press the button s_i on your gamepad. Hits are numbered from 1 to n.
You know that if you press some button more than k times in a row then it'll break. You cherish your gamepad and don't want to break any of its buttons.
To perform a brutality you have to land some of the hits of the given sequence. You are allowed to skip any of them, however changing the initial order of the sequence is prohibited. The total damage dealt is the sum of a_i over all i for the hits which weren't skipped.
Note that if you skip the hit then the counter of consecutive presses the button won't reset.
Your task is to skip some hits to deal the maximum possible total damage to the opponent's character and not break your gamepad buttons.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of hits and the maximum number of times you can push the same button in a row.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the damage of the i-th hit.
The third line of the input contains the string s consisting of exactly n lowercase Latin letters — the sequence of hits (each character is the letter on the button you need to press to perform the corresponding hit).
Output
Print one integer dmg — the maximum possible damage to the opponent's character you can deal without breaking your gamepad buttons.
Examples
Input
7 3
1 5 16 18 7 2 10
baaaaca
Output
54
Input
5 5
2 4 1 3 1000
aaaaa
Output
1010
Input
5 4
2 4 1 3 1000
aaaaa
Output
1009
Input
8 1
10 15 2 1 4 8 15 16
qqwweerr
Output
41
Input
6 3
14 18 9 19 2 15
cccccc
Output
52
Input
2 1
10 10
qq
Output
10
Note
In the first example you can choose hits with numbers [1, 3, 4, 5, 6, 7] with the total damage 1 + 16 + 18 + 7 + 2 + 10 = 54.
In the second example you can choose all hits so the total damage is 2 + 4 + 1 + 3 + 1000 = 1010.
In the third example you can choose all hits expect the third one so the total damage is 2 + 4 + 3 + 1000 = 1009.
In the fourth example you can choose hits with numbers [2, 3, 6, 8]. Only this way you can reach the maximum total damage 15 + 2 + 8 + 16 = 41.
In the fifth example you can choose only hits with numbers [2, 4, 6] with the total damage 18 + 19 + 15 = 52.
In the sixth example you can change either first hit or the second hit (it does not matter) with the total damage 10.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, k;
long long process(priority_queue<int> &Q) {
long long ans = 0;
for (int i = 0; i < k; ++i) {
if (Q.empty()) {
break;
}
ans += Q.top();
Q.pop();
}
while (!Q.empty()) {
Q.pop();
}
return ans;
}
int a[200005];
int main() {
std::ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> k;
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
string s;
cin >> s;
priority_queue<int> Q;
long long ans = 0;
Q.push(a[0]);
for (int i = 1; i < s.size(); ++i) {
if (s[i] != s[i - 1]) {
ans += process(Q);
}
Q.push(a[i]);
}
ans += process(Q);
cout << ans;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Kevin Sun wants to move his precious collection of n cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into k boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single box. Since Kevin wishes to minimize expenses, he is curious about the smallest size box he can use to pack his entire collection.
Kevin is a meticulous cowbell collector and knows that the size of his i-th (1 ≤ i ≤ n) cowbell is an integer si. In fact, he keeps his cowbells sorted by size, so si - 1 ≤ si for any i > 1. Also an expert packer, Kevin can fit one or two cowbells into a box of size s if and only if the sum of their sizes does not exceed s. Given this information, help Kevin determine the smallest s for which it is possible to put all of his cowbells into k boxes of size s.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 2·k ≤ 100 000), denoting the number of cowbells and the number of boxes, respectively.
The next line contains n space-separated integers s1, s2, ..., sn (1 ≤ s1 ≤ s2 ≤ ... ≤ sn ≤ 1 000 000), the sizes of Kevin's cowbells. It is guaranteed that the sizes si are given in non-decreasing order.
Output
Print a single integer, the smallest s for which it is possible for Kevin to put all of his cowbells into k boxes of size s.
Examples
Input
2 1
2 5
Output
7
Input
4 3
2 3 5 9
Output
9
Input
3 2
3 5 7
Output
8
Note
In the first sample, Kevin must pack his two cowbells into the same box.
In the second sample, Kevin can pack together the following sets of cowbells: {2, 3}, {5} and {9}.
In the third sample, the optimal solution is {3, 5} and {7}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int kMaxN = 1e5 + 55;
int N, K;
int S[kMaxN];
int temp[kMaxN];
int main(void) {
int mx = -1;
scanf("%d %d", &N, &K);
for (int i = 0; i < N; ++i) {
scanf("%d", &S[i]);
mx = max(mx, S[i]);
}
if (K >= N) {
printf("%d\n", mx);
return 0;
}
int len = N - K;
mx = -1;
for (int i = N - 1; i >= len; --i) {
temp[N - 1 - i] = S[i];
mx = max(mx, temp[N - 1 - i]);
}
for (int i = len - 1, j = K - 1; i >= 0; --i, --j) {
temp[j] += S[i];
mx = max(mx, temp[j]);
}
printf("%d\n", mx);
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Write a program which reads a $n \times m$ matrix $A$ and a $m \times l$ matrix $B$, and prints their product, a $n \times l$ matrix $C$. An element of matrix $C$ is obtained by the following formula:
\\[ c_{ij} = \sum_{k=1}^m a_{ik}b_{kj} \\]
where $a_{ij}$, $b_{ij}$ and $c_{ij}$ are elements of $A$, $B$ and $C$ respectively.
Note
解説
Constraints
* $1 \leq n, m, l \leq 100$
* $0 \leq a_{ij}, b_{ij} \leq 10000$
Input
In the first line, three integers $n$, $m$ and $l$ are given separated by space characters
In the following lines, the $n \times m$ matrix $A$ and the $m \times l$ matrix $B$ are given.
Output
Print elements of the $n \times l$ matrix $C$ ($c_{ij}$). Print a single space character between adjacent elements.
Example
Input
3 2 3
1 2
0 3
4 5
1 2 1
0 3 2
Output
1 8 5
0 9 6
4 23 14
### Response
```cpp
#include<iostream>
#include<algorithm>
#include<vector>
#define rep(i, n) for(int i = 0; i < n; i++)
typedef long long ll;
using namespace std;
const int INF = 100;
int main()
{
int n, m, l;
cin >> n >> m >> l;
int A[200][200];
rep(i, n)rep(j, m)cin >> A[i][j];
int B[200][200];
rep(i, m)rep(j, l)cin >> B[i][j];
rep(i, n) {
rep(j, l) {
ll out = 0;
rep(k, m) {
out += A[i][k] * B[k][j];
}
if (j == 0) {
cout << out;
}
else {
cout << " " << out;
}
}
cout << endl;
}
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Your task is to shuffle a deck of n cards, each of which is marked by a alphabetical letter.
A single shuffle action takes out h cards from the bottom of the deck and moves them to the top of the deck.
The deck of cards is represented by a string as follows.
abcdeefab
The first character and the last character correspond to the card located at the bottom of the deck and the card on the top of the deck respectively.
For example, a shuffle with h = 4 to the above deck, moves the first 4 characters "abcd" to the end of the remaining characters "eefab", and generates the following deck:
eefababcd
You can repeat such shuffle operations.
Write a program which reads a deck (a string) and a sequence of h, and prints the final state (a string).
Constraints
* The length of the string ≤ 200
* 1 ≤ m ≤ 100
* 1 ≤ hi < The length of the string
* The number of datasets ≤ 10
Input
The input consists of multiple datasets. Each dataset is given in the following format:
A string which represents a deck
The number of shuffle m
h1
h2
.
.
hm
The input ends with a single character '-' for the string.
Output
For each dataset, print a string which represents the final state in a line.
Example
Input
aabc
3
1
2
1
vwxyz
2
3
4
-
Output
aabc
xyzvw
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define rep(i,x,to) for(int i=x;i<to;i++)
int main(){
string str;
while(1){
cin>>str;
if(str=="-")break;
int m,h;
cin>>m;
rep(i,0,m){
cin >> h;
str = str.substr(h)+str.substr(0,h);
}
cout<<str<<endl;
}
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Snuke has an integer sequence A of length N.
He will make three cuts in A and divide it into four (non-empty) contiguous subsequences B, C, D and E. The positions of the cuts can be freely chosen.
Let P,Q,R,S be the sums of the elements in B,C,D,E, respectively. Snuke is happier when the absolute difference of the maximum and the minimum among P,Q,R,S is smaller. Find the minimum possible absolute difference of the maximum and the minimum among P,Q,R,S.
Constraints
* 4 \leq N \leq 2 \times 10^5
* 1 \leq A_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Find the minimum possible absolute difference of the maximum and the minimum among P,Q,R,S.
Examples
Input
5
3 2 4 1 2
Output
2
Input
10
10 71 84 33 6 47 23 25 52 64
Output
36
Input
7
1 2 3 1000000000 4 5 6
Output
999999994
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n;
long long sum[200005],res=1e18;
void get(int l,int r,long long &x,long long &y)
{
long long res=1e18;
int lef=l,rig=r-1;
while (lef<=rig)
{
int m=lef+rig>>1;
long long a=sum[m]-sum[l-1];
long long b=sum[r]-sum[m];
if (abs(a-b)<res)
{
res=abs(a-b);
x=a;y=b;
}
if (a<=b) lef=m+1;
else rig=m-1;
}
}
int main()
{
cin>>n;
for (int i=1;i<=n;i++)
{
int x;
cin>>x;
sum[i]=x+sum[i-1];
}
for (int i=2;i<=n-2;i++)
{
long long a,b,c,d;
get(1,i,a,b);
get(i+1,n,c,d);
res=min(res,max({a,b,c,d})-min({a,b,c,d}));
}
cout<<res<<endl;
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
A rabbit who came to the fair found that the prize for a game at a store was a carrot cake. The rules for this game are as follows.
There is a grid-like field of vertical h squares x horizontal w squares, and each block has at most one block. Each block is a color represented by one of the uppercase letters ('A'-'Z'). When n or more blocks of the same color are lined up in a straight line vertically or horizontally, those blocks disappear.
Participants can select two adjacent cells next to each other and switch their states to each other. When blocks are exchanged, disappeared, or dropped and there are no blocks in the cell below the cell with the block, this block At this time, it disappears when n or more blocks of the same color are lined up again. However, the disappearance of the blocks does not occur while the falling blocks exist, and occurs at the same time when all the blocks have finished falling.
If you eliminate all the blocks on the field with one operation, this game will be successful and you will get a free gift cake. Rabbit wants to get the cake with one entry fee, can not do it If you don't want to participate. From the state of the field at the beginning of the game, answer if the rabbit should participate in this game.
Input
The first line of input is given h, w, n separated by spaces.
2 ≤ h, w, n ≤ 30
In the following h lines, the state of the field is given in order from the top. Uppercase letters represent blocks, and'.' Represents an empty space. The state of the given field is n or more consecutive blocks of the same color in the vertical or horizontal direction. No, no blocks are in a falling state. There is one or more blocks.
Output
Output "YES" if the rabbit should participate in this game, otherwise output "NO" on one line.
Examples
Input
4 6 3
......
...Y..
...Y..
RRYRYY
Output
YES
Input
4 6 3
......
...Y..
...Y..
RRYRY.
Output
NO
### Response
```cpp
#include<iostream>
#include<vector>
using namespace std;
#define inRange(x,a,b) (a <= x && x < b)
int di[2] = {0,1};
int dj[2] = {1,0};
int h, w, n;
bool check(vector<string> v){
// まず落下
for(int i = h-2; i >= 0; i--){
for(int j = 0; j < w; j++){
if(v[i][j] == '.') continue;
int cp = i;
while(cp+1 < h && v[cp+1][j] == '.'){
swap(v[cp][j], v[cp+1][j]);
cp++;
}
}
}
bool update = true;
while(update){
update = false;
vector<vector<bool>> erase(h, vector<bool>(w, 0));
for(int i = 0; i < h; i++){
for(int j = 0; j < w; j++){
if(v[i][j] == '.') continue;
for(int k = 0; k < 2; k++){
int ni = i+di[k], nj = j+dj[k], cnt = 1;
while(inRange(ni,0,h)&&inRange(nj,0,w)&&v[ni][nj]==v[i][j]){
ni += di[k], nj += dj[k], cnt++;
}
if(cnt < n) continue;
update = true;
do{
ni -= di[k], nj -= dj[k];
erase[ni][nj] = true;
}while(ni != i || nj != j);
}
}
}
for(int i = 0; i < h; i++){
for(int j = 0; j < w; j++){
if(erase[i][j]) v[i][j] = '.';
}
}
for(int i = h-2; i >= 0; i--){
for(int j = 0; j < w; j++){
if(v[i][j] == '.') continue;
int cp = i;
while(cp+1 < h && v[cp+1][j] == '.'){
update = true;
swap(v[cp][j], v[cp+1][j]);
cp++;
}
}
}
}
bool ret = true;
for(int i = 0; i < h; i++){
for(int j = 0; j < w; j++){
ret &= v[i][j]=='.';
}
}
return ret;
}
int main(){
cin >> h >> w >> n;
vector<string> v(h);
for(int i = 0; i < h; i++) cin >> v[i];
bool valid = false;
for(int i = 0; i < h; i++){
for(int j = 0; j < w; j++){
int ni = i+di[0], nj = j+dj[0];
if(!inRange(ni,0,h) || !inRange(nj,0,w) || v[i][j]==v[ni][nj]){
continue;
}
swap(v[i][j], v[ni][nj]);
valid |= check(v);
swap(v[i][j], v[ni][nj]);
}
}
cout << (valid ? "YES" : "NO") << endl;
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Dreamoon likes coloring cells very much.
There is a row of n cells. Initially, all cells are empty (don't contain any color). Cells are numbered from 1 to n.
You are given an integer m and m integers l_1, l_2, …, l_m (1 ≤ l_i ≤ n)
Dreamoon will perform m operations.
In i-th operation, Dreamoon will choose a number p_i from range [1, n-l_i+1] (inclusive) and will paint all cells from p_i to p_i+l_i-1 (inclusive) in i-th color. Note that cells may be colored more one than once, in this case, cell will have the color from the latest operation.
Dreamoon hopes that after these m operations, all colors will appear at least once and all cells will be colored. Please help Dreamoon to choose p_i in each operation to satisfy all constraints.
Input
The first line contains two integers n,m (1 ≤ m ≤ n ≤ 100 000).
The second line contains m integers l_1, l_2, …, l_m (1 ≤ l_i ≤ n).
Output
If it's impossible to perform m operations to satisfy all constraints, print "'-1" (without quotes).
Otherwise, print m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n - l_i + 1), after these m operations, all colors should appear at least once and all cells should be colored.
If there are several possible solutions, you can print any.
Examples
Input
5 3
3 2 2
Output
2 4 1
Input
10 1
1
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long ans[+400500], l[+400500], sum, n, i, m, j;
int main() {
srand(time(0));
ios_base::sync_with_stdio(0);
iostream::sync_with_stdio(0);
ios::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> m;
for (i = 1; i <= m; i++) cin >> l[i], sum += l[i];
if (sum < n)
cout << "-1";
else {
ans[1] = 1;
sum -= l[1];
i = 2;
j = 2;
while (i <= n) {
if (sum < n - i + 1)
i++;
else
ans[j++] = i, sum -= l[j - 1], i++;
}
if (j <= m) {
cout << "-1";
return 0;
}
for (i = 1; i <= m; i++) {
if (ans[i] + l[i] - 1 > n) {
cout << "-1";
return 0;
}
}
for (i = 1; i <= m; i++) cout << ans[i] << " ";
}
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something.
Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed his luck.
When he arrived home, he began to study how his generator works and learned the algorithm. The process of generating a permutation consists of n steps. At the i-th step, a place is chosen for the number i (1 ≤ i ≤ n). The position for the number i is defined as follows:
* For all j from 1 to n, we calculate r_j — the minimum index such that j ≤ r_j ≤ n, and the position r_j is not yet occupied in the permutation. If there are no such positions, then we assume that the value of r_j is not defined.
* For all t from 1 to n, we calculate count_t — the number of positions 1 ≤ j ≤ n such that r_j is defined and r_j = t.
* Consider the positions that are still not occupied by permutation and among those we consider the positions for which the value in the count array is maximum.
* The generator selects one of these positions for the number i. The generator can choose any position.
Let's have a look at the operation of the algorithm in the following example:
<image>
Let n = 5 and the algorithm has already arranged the numbers 1, 2, 3 in the permutation. Consider how the generator will choose a position for the number 4:
* The values of r will be r = [3, 3, 3, 4, ×], where × means an indefinite value.
* Then the count values will be count = [0, 0, 3, 1, 0].
* There are only two unoccupied positions in the permutation: 3 and 4. The value in the count array for position 3 is 3, for position 4 it is 1.
* The maximum value is reached only for position 3, so the algorithm will uniquely select this position for number 4.
Satisfied with his purchase, Denis went home. For several days without a break, he generated permutations. He believes that he can come up with random permutations no worse than a generator. After that, he wrote out the first permutation that came to mind p_1, p_2, …, p_n and decided to find out if it could be obtained as a result of the generator.
Unfortunately, this task was too difficult for him, and he asked you for help. It is necessary to define whether the written permutation could be obtained using the described algorithm if the generator always selects the position Denis needs.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. Then the descriptions of the test cases follow.
The first line of the test case contains a single integer n (1 ≤ n ≤ 10^5) — the size of the permutation.
The second line of the test case contains n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n) — the permutation written by Denis.
It is guaranteed that the sum of n over all test cases doesn't exceed 10^5.
Output
Print "Yes" if this permutation could be obtained as a result of the generator. Otherwise, print "No".
All letters can be displayed in any case.
Example
Input
5
5
2 3 4 5 1
1
1
3
1 3 2
4
4 2 3 1
5
1 5 2 4 3
Output
Yes
Yes
No
Yes
No
Note
Let's simulate the operation of the generator in the first test.
At the 1 step, r = [1, 2, 3, 4, 5], count = [1, 1, 1, 1, 1]. The maximum value is reached in any free position, so the generator can choose a random position from 1 to 5. In our example, it chose 5.
At the 2 step, r = [1, 2, 3, 4, ×], count = [1, 1, 1, 1, 0]. The maximum value is reached in positions from 1 to 4, so the generator can choose a random position among them. In our example, it chose 1.
At the 3 step, r = [2, 2, 3, 4, ×], count = [0, 2, 1, 1, 0]. The maximum value is 2 and is reached only at the 2 position, so the generator will choose this position.
At the 4 step, r = [3, 3, 3, 4, ×], count = [0, 0, 3, 1, 0]. The maximum value is 3 and is reached only at the 3 position, so the generator will choose this position.
At the 5 step, r = [4, 4, 4, 4, ×], count = [0, 0, 0, 4, 0]. The maximum value is 4 and is reached only at the 4 position, so the generator will choose this position.
In total, we got a permutation of 2, 3, 4, 5, 1, that is, a generator could generate it.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5;
int cnt[N + 100], vis[N + 100];
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n;
set<pair<int, int> > stp;
set<int> sti;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
int p;
scanf("%d", &p);
vis[p] = i;
stp.insert(make_pair(1, i));
sti.insert(i);
cnt[i] = 1;
}
bool flag = true;
for (int i = 1; i <= n; i++) {
auto e = stp.end();
e--;
int cur = vis[i];
if (e->first != cnt[cur]) {
flag = false;
break;
}
sti.erase(cur);
stp.erase(make_pair(cnt[cur], cur));
auto nxt = sti.lower_bound(cur);
if (nxt != sti.end()) {
int del = *nxt;
stp.erase(make_pair(cnt[del], del));
cnt[del] += cnt[cur];
stp.insert(make_pair(cnt[del], del));
}
}
if (flag == true) {
printf("Yes\n");
} else {
printf("No\n");
}
}
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Given is a string S, where each character is `0`, `1`, or `?`.
Consider making a string S' by replacing each occurrence of `?` with `0` or `1` (we can choose the character for each `?` independently). Let us define the unbalancedness of S' as follows:
* (The unbalancedness of S') = \max \\{ The absolute difference between the number of occurrences of `0` and `1` between the l-th and r-th character of S (inclusive) :\ 1 \leq l \leq r \leq |S|\\}
Find the minimum possible unbalancedness of S'.
Constraints
* 1 \leq |S| \leq 10^6
* Each character of S is `0`, `1`, or `?`.
Input
Input is given from Standard Input in the following format:
S
Output
Print the minimum possible unbalancedness of S'.
Examples
Input
0??
Output
1
Input
0??0
Output
2
Input
??00????0??0????0?0??00??1???11?1?1???1?11?111???1
Output
4
### Response
```cpp
#include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define FOR(i,n,m) for(int i=(int)(n); i<=(int)(m); i++)
#define RFOR(i,n,m) for(int i=(int)(n); i>=(int)(m); i--)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define RITR(x,c) for(__typeof(c.rbegin()) x=c.rbegin();x!=c.rend();x++)
#define setp(n) fixed << setprecision(n)
template<class T> bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T> bool chmin(T &a, const T &b) { if (a>b) { a=b; return 1; } return 0; }
#define ll long long
#define vll vector<ll>
#define vi vector<int>
#define pll pair<ll,ll>
#define pi pair<int,int>
#define all(a) (a.begin()),(a.end())
#define rall(a) (a.rbegin()),(a.rend())
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define ins insert
using namespace std;
const int INF=1e9;
//-------------------------------------------------
int main(void)
{
cin.tie(0);
ios::sync_with_stdio(false);
string S; cin>>S;
int N = S.size();
vi sum(N+1);
rep(i,N){
if (S[i]=='0') sum[i+1]=sum[i]+1;
else sum[i+1]=sum[i]-1;
}
vi maxi(N+1,-INF);
RFOR(i,N-1,0){
maxi[i] = max(maxi[i+1],sum[i+1]);
}
auto getDiff = [&](int x){
int res=0;
int c=0;
rep(i,N){
if (S[i]=='?' && maxi[i]+c+2<=x) c+=2;
chmin(res,sum[i+1]+c);
}
return x-res;
};
int minMax = max(0,maxi[0]);
int ans=min(getDiff(minMax), getDiff(minMax+1));
cout<<ans<<"\n";
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
problem
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided to move the plot while breaking the thin ice according to the following rules.
* You can start breaking thin ice from any compartment with thin ice.
* Adjacent to either north, south, east, or west, you can move to a section with thin ice that has not yet been broken.
* Be sure to break the thin ice in the area you moved to.
Create a program to find the maximum number of sections that JOI Taro can move while breaking thin ice. However, 1 ≤ m ≤ 90 and 1 ≤ n ≤ 90. With the input data given, there are no more than 200,000 ways to move.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The input is n + 2 lines. The integer m is written on the first line. The integer n is written on the second line. In each line from the 3rd line to the n + 2nd line, m 0s or 1s are written, separated by blanks, and indicates whether or not there is thin ice in each section. If we write the i-th section from the north and the j-th section from the west as (i, j) (1 ≤ i ≤ n, 1 ≤ j ≤ m), the j-th value on the second line of i + 2 is It is 1 if there is thin ice in compartment (i, j) and 0 if there is no thin ice in compartment (i, j).
When both m and n are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output the maximum number of sections that can be moved for each data set on one line.
Examples
Input
3
3
1 1 0
1 0 1
1 1 0
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
0
0
Output
5
5
Input
None
Output
None
### Response
```cpp
#include<stdio.h>
bool map[ 92 ][ 92 ] ;
int mx[] = { 0 ,1 ,-1 ,0 } ;
int my[] = { 1 ,0 ,0 ,-1 } ;
int ans ;
int move( int y ,int x ,int cnt )
{
map[ y ][ x ] = false ;
if( cnt > ans )
{
ans = cnt ;
}
for( int i = 0 ; i < 4 ; i++ )
{
int yy = y + my[ i ] ;
int xx = x + mx[ i ] ;
if( map[ yy ][ xx ] == true )
{
move( yy ,xx ,cnt + 1 ) ;
}
}
map[ y ][ x ] = true ;
return ans ;
}
int main()
{
int h ,w ;
while( true )
{
scanf( "%d %d" ,&h ,&w ) ;
if( w == h && !w )
{
return 0 ;
}
ans = 0 ;
for( int i = 1 ; i <= h ; i++ )
{
for( int j = 1 ; j <= w ; j++ )
{
scanf( "%d" ,&map[ i ][ j ] ) ;
}
}
for( int i = 1 ; i <= h ; i++ )
{
for( int j = 1 ; j <= w ; j++ )
{
if( map[ i ][ j ] == 1 )
{
int ans_ = move( i ,j ,1 ) ;
ans = ans < ans_ ? ans_ : ans ;
}
}
}
printf( "%d\n" ,ans ) ;
}
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Ivan has an array consisting of n different integers. He decided to reorder all elements in increasing order. Ivan loves merge sort so he decided to represent his array with one or several increasing sequences which he then plans to merge into one sorted array.
Ivan represent his array with increasing sequences with help of the following algorithm.
While there is at least one unused number in array Ivan repeats the following procedure:
* iterate through array from the left to the right;
* Ivan only looks at unused numbers on current iteration;
* if current number is the first unused number on this iteration or this number is greater than previous unused number on current iteration, then Ivan marks the number as used and writes it down.
For example, if Ivan's array looks like [1, 3, 2, 5, 4] then he will perform two iterations. On first iteration Ivan will use and write numbers [1, 3, 5], and on second one — [2, 4].
Write a program which helps Ivan and finds representation of the given array with one or several increasing sequences in accordance with algorithm described above.
Input
The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of elements in Ivan's array.
The second line contains a sequence consisting of distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — Ivan's array.
Output
Print representation of the given array in the form of one or more increasing sequences in accordance with the algorithm described above. Each sequence must be printed on a new line.
Examples
Input
5
1 3 2 5 4
Output
1 3 5
2 4
Input
4
4 3 2 1
Output
4
3
2
1
Input
4
10 30 50 101
Output
10 30 50 101
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
int a[maxn], b[maxn];
vector<int> g[maxn];
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
int pos = lower_bound(b + 1, b + n + 1, a[i]) - b;
pos--;
b[pos] = a[i];
g[pos].push_back(a[i]);
}
for (int i = n; i >= 1; i--) {
for (int j = 0; j < g[i].size(); j++) {
cout << g[i][j] << " ";
}
cout << endl;
}
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
A pitch-black room
When I woke up, Mr. A was in a pitch-black room. Apparently, Mr. A got lost in a dungeon consisting of N rooms. You couldn't know which room A got lost in, but fortunately he got a map of the dungeon. Let's show A the way to go and lead to a bright room.
It is known that M of the N rooms are pitch black, and the D_1, D_2, ..., and D_Mth rooms are pitch black, respectively. Also, there are exactly K one-way streets from all the rooms in order, and the roads from the i-th room are v_ {i, 1}, v_ {i, 2}, ..., v_ {i, respectively. , K} Connected to the third room. You can follow the a_1, a_2, ..., a_lth roads in order from the room you are in for Mr. A. However, when Mr. A reaches the bright room, he ignores the subsequent instructions. You cannot know the information of the room where Mr. A is currently before and after the instruction, so you must give the instruction sequence so that you can reach the bright room no matter which room you are in. Answer the length of the shortest of such instructions.
Constraints
* 2 ≤ N ≤ 100
* 1 ≤ M ≤ min (16, N − 1)
* 1 ≤ K ≤ N
* 1 ≤ D_i ≤ N
* D_i are all different
* 1 ≤ v_ {i, j} ≤ N
* All dark rooms can reach at least one bright room
Input Format
Input is given from standard input in the following format.
NMK
D_1 D_2 ... D_M
v_ {1,1} v_ {1,2} ... v_ {1,K}
v_ {2,1} v_ {2,2} ... v_ {2, K}
...
v_ {N, 1} v_ {N, 2} ... v_ {N, K}
Output Format
Print the answer in one line.
Sample Input 1
4 2 2
1 2
twenty four
3 1
4 2
13
Sample Output 1
2
<image>
If you give the instruction 1, 1
* If A's initial position is room 1, the second move will reach room 3.
* If A's initial position is room 2, the first move will reach room 3.
Sample Input 2
3 2 2
1 2
twenty three
1 2
twenty one
Sample Output 2
3
<image>
If you give instructions 2, 1, 2
* If A's initial position is room 1, the first move will reach room 3.
* If A's initial position is room 2, the third move will reach room 3.
Sample Input 3
6 3 3
one two Three
4 1 1
2 5 2
3 3 6
4 4 4
5 5 5
6 6 6
Sample Output 3
3
<image>
Beware of unconnected cases and cases with self-edges and multiple edges.
Example
Input
4 2 2
1 2
2 4
3 1
4 2
1 3
Output
2
### Response
```cpp
#define _USE_MATH_DEFINES
#include <bits/stdc++.h>
#define USE_LLONG_AS_INT
#ifdef USE_LLONG_AS_INT
#define int long long
#define inf (1ll<<60)
#else
#define inf (1<<30)
#endif
#define rep(i,n) for(int i=0;i<n;i++)
#define Rep(i,a,b) for(int i=a;i<b;i++)
#define REP(i,a,b) for(int i=a;i<=b;i++)
#define rev(i,n) for(int i=n-1;i>=0;i--)
#define vi vector<int>
#define vvi vector<vi>
#define pb push_back
#define pi pair<int,int>
#define vp vector<pair<int,int>>
#define mp make_pair
#define all(v) (v).begin(),(v).end()
#define fi first
#define se second
#define MEMSET(a) memset(a,0,sizeof(a))
#define Yes(f) cout<<(f?"Yes":"No")<<endl
#define yes(f) cout<<(f?"yes":"no")<<endl
#define YES(f) cout<<(f?"YES":"NO")<<endl
#define SORT(v) sort(all(v))
#define RSORT(v) sort(all(v), greater<int>())
using namespace std;
const int mod=1e9+7;
const string sp=" ";
void run();
void init() {
ios::sync_with_stdio(false);
cin.tie(0);
cout<<fixed<<setprecision(12);
}
signed main(){
init();
run();
return 0;
}
void run(){
int n,m,k;
cin>>n>>m>>k;
vi d(m);
rep(i,m){
cin>>d[i];
d[i]--;
}
vvi v(n,vi(k));
rep(i,n)rep(j,k){
cin>>v[i][j];
v[i][j]--;
}
int id[n];
memset(id,-1,sizeof(id));
rep(i,m)id[d[i]]=i;
int dp[1<<m];
memset(dp,-1,sizeof(dp));
dp[(1<<m)-1]=0;
queue<int> q;
q.push((1<<m)-1);
while(!q.empty()){
int s=q.front();
q.pop();
rep(i,k){
int ns=s;
int mask=0;
rep(j,m){
if((s>>j)&1){
ns^=(1<<j);
if(~id[v[d[j]][i]])mask|=1<<id[v[d[j]][i]];
}
}
ns|=mask;
if(!~dp[ns]&&s!=ns){
dp[ns]=dp[s]+1;
q.push(ns);
}
}
}
cout<<dp[0]<<endl;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
There are n balls. They are arranged in a row. Each ball has a color (for convenience an integer) and an integer value. The color of the i-th ball is ci and the value of the i-th ball is vi.
Squirrel Liss chooses some balls and makes a new sequence without changing the relative order of the balls. She wants to maximize the value of this sequence.
The value of the sequence is defined as the sum of following values for each ball (where a and b are given constants):
* If the ball is not in the beginning of the sequence and the color of the ball is same as previous ball's color, add (the value of the ball) × a.
* Otherwise, add (the value of the ball) × b.
You are given q queries. Each query contains two integers ai and bi. For each query find the maximal value of the sequence she can make when a = ai and b = bi.
Note that the new sequence can be empty, and the value of an empty sequence is defined as zero.
Input
The first line contains two integers n and q (1 ≤ n ≤ 105; 1 ≤ q ≤ 500). The second line contains n integers: v1, v2, ..., vn (|vi| ≤ 105). The third line contains n integers: c1, c2, ..., cn (1 ≤ ci ≤ n).
The following q lines contain the values of the constants a and b for queries. The i-th of these lines contains two integers ai and bi (|ai|, |bi| ≤ 105).
In each line integers are separated by single spaces.
Output
For each query, output a line containing an integer — the answer to the query. The i-th line contains the answer to the i-th query in the input order.
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
6 3
1 -2 3 4 0 -1
1 2 1 2 1 1
5 1
-2 1
1 0
Output
20
9
4
Input
4 1
-3 6 -1 2
1 2 3 1
1 -1
Output
5
Note
In the first example, to achieve the maximal value:
* In the first query, you should select 1st, 3rd, and 4th ball.
* In the second query, you should select 3rd, 4th, 5th and 6th ball.
* In the third query, you should select 2nd and 4th ball.
Note that there may be other ways to achieve the maximal value.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n;
long long a, b;
long long pd[110000];
long long v[110000], c[110000];
int prox[110000];
long long best[110000];
map<int, int> mapa;
bool ja[110000];
pair<long long, long long> atualiza(pair<long long, long long> a, long long x,
long long ant) {
if (a.first == ant) return make_pair(x, a.second);
if (a.second == ant) {
long long c = a.first, d = x;
return make_pair(max(c, d), min(c, d));
}
if (x > a.first) return make_pair(x, a.first);
return make_pair(a.first, max(a.second, x));
}
int main() {
int q;
scanf("%d%d", &n, &q);
for (int i = 0; i < n; i++) cin >> v[i];
for (int i = 0; i < n; i++) cin >> c[i], c[i]--;
multiset<int> S;
while (q--) {
memset(pd, -1, sizeof pd);
cin >> a >> b;
memset(best, 0, sizeof best);
for (int i = 0; i < n; i++) best[i] = -(1LL << 50);
memset(ja, 0, sizeof ja);
S.clear();
pair<long long, long long> ans = make_pair(0, 0);
for (int i = 0; i < n; i++) {
long long sem;
if (ans.first == best[c[i]])
sem = ans.second;
else
sem = ans.first;
long long aux = sem + b * v[i];
if (ja[c[i]]) aux = max(aux, best[c[i]] + a * v[i]);
long long ant = best[c[i]];
best[c[i]] = max(best[c[i]], aux);
ja[c[i]] = 1;
if (ant != best[c[i]]) ans = atualiza(ans, best[c[i]], ant);
}
long long ret = 0;
for (int i = 0; i < n; i++) ret = max(ret, best[i]);
cout << ret << endl;
}
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from 1 to n. Let's assume that Misha chose number m, and Andrew chose number a.
Then, by using a random generator they choose a random integer c in the range between 1 and n (any integer from 1 to n is chosen with the same probability), after which the winner is the player, whose number was closer to c. The boys agreed that if m and a are located on the same distance from c, Misha wins.
Andrew wants to win very much, so he asks you to help him. You know the number selected by Misha, and number n. You need to determine which value of a Andrew must choose, so that the probability of his victory is the highest possible.
More formally, you need to find such integer a (1 ≤ a ≤ n), that the probability that <image> is maximal, where c is the equiprobably chosen integer from 1 to n (inclusive).
Input
The first line contains two integers n and m (1 ≤ m ≤ n ≤ 109) — the range of numbers in the game, and the number selected by Misha respectively.
Output
Print a single number — such value a, that probability that Andrew wins is the highest. If there are multiple such values, print the minimum of them.
Examples
Input
3 1
Output
2
Input
4 3
Output
2
Note
In the first sample test: Andrew wins if c is equal to 2 or 3. The probability that Andrew wins is 2 / 3. If Andrew chooses a = 3, the probability of winning will be 1 / 3. If a = 1, the probability of winning is 0.
In the second sample test: Andrew wins if c is equal to 1 and 2. The probability that Andrew wins is 1 / 2. For other choices of a the probability of winning is less.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long int n, m;
scanf("%lld%lld", &n, &m);
int i, j;
if (n == 1) {
printf("1\n");
return 0;
} else if (n == 2) {
if (m == 1)
printf("2\n");
else
printf("1\n");
return 0;
}
long long int d = n / 2;
if (n % 2 == 0) {
if (m == d)
printf("%lld\n", d + 1);
else if (m > d)
printf("%lld\n", m - 1);
else
printf("%lld\n", m + 1);
} else {
d = d + 1;
if (m == d)
printf("%lld\n", d - 1);
else if (m > d)
printf("%lld\n", m - 1);
else
printf("%lld\n", m + 1);
}
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
<image>
A directed acyclic graph (DAG) can be used to represent the ordering of tasks. Tasks are represented by vertices and constraints where one task can begin before another, are represented by edges. For example, in the above example, you can undertake task B after both task A and task B are finished. You can obtain the proper sequence of all the tasks by a topological sort.
Given a DAG $G$, print the order of vertices after the topological sort.
Constraints
* $1 \leq |V| \leq 10,000$
* $0 \leq |E| \leq 100,000$
* There are no parallel edges in $G$
* There are no self loops in $G$
Input
A directed graph $G$ is given in the following format:
$|V|\;|E|$
$s_0 \; t_0$
$s_1 \; t_1$
:
$s_{|E|-1} \; t_{|E|-1}$
$|V|$ is the number of vertices and $|E|$ is the number of edges in the graph. The graph vertices are named with the numbers $0, 1,..., |V|-1$ respectively.
$s_i$ and $t_i$ represent source and target nodes of $i$-th edge (directed).
Output
Print the vertices numbers in order. Print a number in a line.
If there are multiple possible solutions, print any one of them (the solution is judged by a special validator).
Example
Input
6 6
0 1
1 2
3 1
3 4
4 5
5 2
Output
0
3
1
4
5
2
### Response
```cpp
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
#define rep(i,n) for(int i=0;i<(n);++i)
#define out(v) cout<<v<<"\n"
int main() {
cin.tie(0); ios::sync_with_stdio(false);
int V, E; cin >> V >> E;
vector<vector<bool>> edge(V, vector<bool>(V, false));
vector<int> in(V, 0);
queue<int> no_incoming_edge;
rep(i, E) {
int s, t;
cin >> s >> t;
edge[s][t] = true;
++in[t];
}
rep(i, V) {
if (in[i] == 0)
no_incoming_edge.push(i);
}
vector<int> ans;
while (!no_incoming_edge.empty()) {
int p = no_incoming_edge.front(); no_incoming_edge.pop();
ans.push_back(p);
rep(to, V) {
if (edge[p][to] == 1) {
--in[to];
if (in[to] == 0)
no_incoming_edge.push(to);
}
}
}
rep(i, V)
out(ans[i]);
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Lena is a programmer. She got a task to solve at work.
There is an empty set of pairs of integers and n queries to process. Each query is one of three types:
1. Add a pair (a, b) to the set.
2. Remove a pair added in the query number i. All queries are numbered with integers from 1 to n.
3. For a given integer q find the maximal value x·q + y over all pairs (x, y) from the set.
Help Lena to process the queries.
Input
The first line of input contains integer n (1 ≤ n ≤ 3·105) — the number of queries.
Each of the next n lines starts with integer t (1 ≤ t ≤ 3) — the type of the query.
A pair of integers a and b ( - 109 ≤ a, b ≤ 109) follows in the query of the first type.
An integer i (1 ≤ i ≤ n) follows in the query of the second type. It is guaranteed that i is less than the number of the query, the query number i has the first type and the pair from the i-th query is not already removed.
An integer q ( - 109 ≤ q ≤ 109) follows in the query of the third type.
Output
For the queries of the third type print on a separate line the desired maximal value of x·q + y.
If there are no pairs in the set print "EMPTY SET".
Example
Input
7
3 1
1 2 3
3 1
1 -1 100
3 1
2 4
3 1
Output
EMPTY SET
5
99
5
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
const long long N = 3e5 + 5, oo = 2e18;
long long n, block_size, ans[N], a[N], b[N], type[N], time_end[N], n1, n2,
process[N], n3, del[N];
pair<long long, long long> lines[N];
struct Line {
long long a, b;
Line() {}
Line(long long _a, long long _b) : a(_a), b(_b) {}
long long val(long long x) { return a * x + b; }
} st[N];
long long bad(Line a, Line b, Line c) {
return (c.b - a.b) * (b.a - c.a) <= (c.b - b.b) * (a.a - c.a);
}
void addLine(Line a) {
if (n3 && st[n3 - 1].a == a.a && st[n3 - 1].b == a.b) n3--;
while (n3 >= 2 && bad(a, st[n3 - 1], st[n3 - 2])) n3--;
st[n3++] = a;
}
long long query(long long x) {
long long ans = -oo, l = 0, r = n3 - 1;
while (l <= r) {
long long mid = (l + r) >> 1;
ans = max(ans, st[mid].val(x));
long long lmid = (mid == 0 ? -oo : st[mid - 1].val(x)),
rmid = (mid == n3 - 1 ? -oo : st[mid + 1].val(x));
if (lmid > rmid)
r = mid - 1;
else if (rmid > lmid)
l = mid + 1;
else
break;
}
return ans;
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
clock_t T = clock();
cin >> n;
for (long long i = 1; i <= n; ++i) {
cin >> type[i] >> a[i];
if (type[i] == 1) cin >> b[i];
}
block_size = 3000;
vector<long long> willadd, cur;
cur.clear();
for (long long L = 1; L <= n; L += block_size) {
willadd.clear();
n3 = 0;
long long R = min(n, L + block_size - 1);
for (long long i = L; i <= R; ++i)
if (type[i] == 2 && a[i] < L) willadd.push_back(a[i]), del[a[i]] = 2;
vector<pair<long long, long long> > V;
V.clear();
for (long long r : cur)
if (del[r] == 0) V.push_back({a[r], b[r]});
sort(V.begin(), V.end());
for (pair<long long, long long> d : V) addLine(Line(d.first, d.second));
for (long long j = L; j <= R; ++j) {
if (type[j] == 1) willadd.push_back(j);
if (type[j] == 2) del[a[j]] = 1;
if (type[j] == 3) {
ans[j] = -oo;
for (long long r : willadd)
if (del[r] != 1) ans[j] = max(ans[j], a[r] * a[j] + b[r]);
ans[j] = max(ans[j], query(a[j]));
}
}
for (long long r : willadd)
if (del[r] == 0) cur.push_back(r);
}
for (long long i = 1; i <= n; ++i)
if (type[i] == 3) {
if (ans[i] == -oo)
cout << "EMPTY SET" << '\n';
else
cout << ans[i] << '\n';
}
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i. e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.
Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (n ≤ k) values b1, b2, ..., bn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i. e. n < k. Note that the initial score wasn't announced.
Your task is to determine the number of options for the score the participant could have before the judges rated the participant.
Input
The first line contains two integers k and n (1 ≤ n ≤ k ≤ 2 000) — the number of jury members and the number of scores Polycarp remembers.
The second line contains k integers a1, a2, ..., ak ( - 2 000 ≤ ai ≤ 2 000) — jury's marks in chronological order.
The third line contains n distinct integers b1, b2, ..., bn ( - 4 000 000 ≤ bj ≤ 4 000 000) — the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order.
Output
Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes).
Examples
Input
4 1
-5 5 0 20
10
Output
3
Input
2 2
-2000 -2000
3998000 4000000
Output
1
Note
The answer for the first example is 3 because initially the participant could have - 10, 10 or 15 points.
In the second example there is only one correct initial score equaling to 4 002 000.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
int n, k, ans = 0;
cin >> k >> n;
vector<int> a(k), b(n);
vector<int> ps(k + 1, 0);
for (int i = 0; i < k; i++) {
cin >> a[i];
ps[i + 1] = ps[i] + a[i];
}
multiset<int> s;
for (int i = 0; i < n; i++) {
cin >> b[i];
s.insert(b[i]);
}
int b0 = b[0];
set<int> ans1;
for (int i = 0; i < k; i++) {
multiset<int> cur(s);
int stval = b0 - ps[i + 1];
cur.erase(b0);
for (int j = 0; j < k; j++) {
if (j == i) continue;
int crval = ps[j + 1] + stval;
if (cur.size() == 0) {
break;
}
if (cur.find(crval) != cur.end()) cur.erase(cur.find(crval));
}
if (cur.size() == 0) ans1.insert(stval);
}
cout << ans1.size() << endl;
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
The Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help.
A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers b1, b2, ..., bm (m ≤ n). All numbers from the message and from the key belong to the interval from 0 to c - 1, inclusive, and all the calculations are performed modulo c.
Encryption is performed in n - m + 1 steps. On the first step we add to each number a1, a2, ..., am a corresponding number b1, b2, ..., bm. On the second step we add to each number a2, a3, ..., am + 1 (changed on the previous step) a corresponding number b1, b2, ..., bm. And so on: on step number i we add to each number ai, ai + 1, ..., ai + m - 1 a corresponding number b1, b2, ..., bm. The result of the encryption is the sequence a1, a2, ..., an after n - m + 1 steps.
Help the Beaver to write a program that will encrypt messages in the described manner.
Input
The first input line contains three integers n, m and c, separated by single spaces.
The second input line contains n integers ai (0 ≤ ai < c), separated by single spaces — the original message.
The third input line contains m integers bi (0 ≤ bi < c), separated by single spaces — the encryption key.
The input limitations for getting 30 points are:
* 1 ≤ m ≤ n ≤ 103
* 1 ≤ c ≤ 103
The input limitations for getting 100 points are:
* 1 ≤ m ≤ n ≤ 105
* 1 ≤ c ≤ 103
Output
Print n space-separated integers — the result of encrypting the original message.
Examples
Input
4 3 2
1 1 1 1
1 1 1
Output
0 1 1 0
Input
3 1 5
1 2 3
4
Output
0 1 2
Note
In the first sample the encryption is performed in two steps: after the first step a = (0, 0, 0, 1) (remember that the calculations are performed modulo 2), after the second step a = (0, 1, 1, 0), and that is the answer.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[100000], b[100000], s[100000], s2[100000];
int main() {
int n, m, c;
cin >> n >> m >> c;
for (int i = 0; i < n; i++) cin >> a[i];
for (int i = 0; i < m; i++) cin >> b[i];
s[0] = b[0];
for (int i = 1; i < m; i++) s[i] = (s[i - 1] + b[i]);
s2[0] = b[m - 1];
for (int i = m - 2; i >= 0; i--) s2[m - i - 1] = (s2[m - i - 2] + b[i]);
int r1 = m - 1, l2 = n - m;
if (r1 <= l2) {
for (int i = 0; i < r1; i++) a[i] = (s[i] + a[i]) % c;
for (int i = r1; i <= l2; i++) a[i] = (a[i] + s[m - 1]) % c;
for (int i = n - 1; i > l2; i--) a[i] = (a[i] + s2[n - 1 - i]) % c;
} else {
for (int i = 0; i <= l2; i++) a[i] = (a[i] + s[i]) % c;
for (int i = l2 + 1; i <= r1; i++) a[i] = (a[i] + s[i] - s[i - l2 - 1]) % c;
for (int i = n - 1; i > r1; i--) a[i] = (a[i] + s2[n - i - 1]) % c;
}
for (int i = 0; i < n; i++) cout << a[i] << " ";
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
The Bubble Cup hypothesis stood unsolved for 130 years. Who ever proves the hypothesis will be regarded as one of the greatest mathematicians of our time! A famous mathematician Jerry Mao managed to reduce the hypothesis to this problem:
Given a number m, how many polynomials P with coefficients in set {\{0,1,2,3,4,5,6,7\}} have: P(2)=m?
Help Jerry Mao solve the long standing problem!
Input
The first line contains a single integer t (1 ≤ t ≤ 5⋅ 10^5) - number of test cases.
On next line there are t numbers, m_i (1 ≤ m_i ≤ 10^{18}) - meaning that in case i you should solve for number m_i.
Output
For each test case i, print the answer on separate lines: number of polynomials P as described in statement such that P(2)=m_i, modulo 10^9 + 7.
Example
Input
2
2 4
Output
2
4
Note
In first case, for m=2, polynomials that satisfy the constraint are x and 2.
In second case, for m=4, polynomials that satisfy the constraint are x^2, x + 2, 2x and 4.
### Response
```cpp
#include <bits/stdc++.h>
struct MI {
private:
char bb[4096];
FILE* f;
char *bs, *be;
char e;
bool o, l;
public:
MI() : f(stdin) {}
inline char get() {
if (o) {
o = 0;
return e;
}
if (bs == be) be = (bs = bb) + fread(bb, 1, sizeof(bb), f);
if (bs == be) {
l = 1;
return -1;
};
return *bs++;
}
inline void unget(char c) {
o = 1;
e = c;
}
template <class T>
inline T read() {
T r;
*this > r;
return r;
}
template <class T>
inline MI& operator>(T&);
};
template <class T>
struct Q {
const static bool U = T(-1) >= T(0);
inline void operator()(MI& t, T& r) const {
r = 0;
char c;
bool y = 0;
if (U)
for (;;) {
c = t.get();
if (c == -1) goto E;
if (isdigit(c)) break;
}
else
for (;;) {
c = t.get();
if (c == -1) goto E;
if (c == '-') {
c = t.get();
if (isdigit(c)) {
y = 1;
break;
};
} else if (isdigit(c))
break;
;
};
for (;;) {
if (c == -1) goto E;
if (isdigit(c))
r = r * 10 + (c ^ 48);
else
break;
c = t.get();
}
t.unget(c);
E:;
if (y) r = -r;
}
};
template <>
struct Q<char> {};
template <class T>
inline MI& MI::operator>(T& t) {
Q<T>()(*this, t);
return *this;
}
template <class T>
inline std::ostream& operator<(std::ostream& out, const T& t) {
return out << t;
}
using std::cout;
MI cin;
const long long lp = 1000000007;
const long long inv4 = 250000002;
int main() {
int T = (cin.read<int>());
while (T--) {
const long long n = cin.read<long long>();
long long ret = ((n >> 1) + 2) % lp;
ret = ret * ret % lp;
int rem = ((n >> 1) + 2) & 3;
rem = (rem * rem) & 3;
cout < ((ret - rem + lp) % lp * inv4 % lp) < ('\n');
}
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
It's a very unfortunate day for Volodya today. He got bad mark in algebra and was therefore forced to do some work in the kitchen, namely to cook borscht (traditional Russian soup). This should also improve his algebra skills.
According to the borscht recipe it consists of n ingredients that have to be mixed in proportion <image> litres (thus, there should be a1 ·x, ..., an ·x litres of corresponding ingredients mixed for some non-negative x). In the kitchen Volodya found out that he has b1, ..., bn litres of these ingredients at his disposal correspondingly. In order to correct his algebra mistakes he ought to cook as much soup as possible in a V litres volume pan (which means the amount of soup cooked can be between 0 and V litres). What is the volume of borscht Volodya will cook ultimately?
Input
The first line of the input contains two space-separated integers n and V (1 ≤ n ≤ 20, 1 ≤ V ≤ 10000). The next line contains n space-separated integers ai (1 ≤ ai ≤ 100). Finally, the last line contains n space-separated integers bi (0 ≤ bi ≤ 100).
Output
Your program should output just one real number — the volume of soup that Volodya will cook. Your answer must have a relative or absolute error less than 10 - 4.
Examples
Input
1 100
1
40
Output
40.0
Input
2 100
1 1
25 30
Output
50.0
Input
2 100
1 1
60 60
Output
100.0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int v;
cin >> v;
double a[n + 1];
double b[n + 1];
double m = 0;
for (int i = 1; i <= n; i++) {
cin >> a[i];
m += a[i];
}
for (int i = 1; i <= n; i++) {
cin >> b[i];
}
double x = 100000000;
for (int i = 1; i <= n; i++) {
x = min(x, b[i] / a[i]);
}
if (v < x * m) {
cout << v;
} else {
cout << x * m;
}
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
The Ohgas are a prestigious family based on Hachioji. The head of the family, Mr. Nemochi Ohga, a famous wealthy man, wishes to increase his fortune by depositing his money to an operation company. You are asked to help Mr. Ohga maximize his profit by operating the given money during a specified period.
From a given list of possible operations, you choose an operation to deposit the given fund to. You commit on the single operation throughout the period and deposit all the fund to it. Each operation specifies an annual interest rate, whether the interest is simple or compound, and an annual operation charge. An annual operation charge is a constant not depending on the balance of the fund. The amount of interest is calculated at the end of every year, by multiplying the balance of the fund under operation by the annual interest rate, and then rounding off its fractional part. For compound interest, it is added to the balance of the fund under operation, and thus becomes a subject of interest for the following years. For simple interest, on the other hand, it is saved somewhere else and does not enter the balance of the fund under operation (i.e. it is not a subject of interest in the following years). An operation charge is then subtracted from the balance of the fund under operation. You may assume here that you can always pay the operation charge (i.e. the balance of the fund under operation is never less than the operation charge). The amount of money you obtain after the specified years of operation is called ``the final amount of fund.'' For simple interest, it is the sum of the balance of the fund under operation at the end of the final year, plus the amount of interest accumulated throughout the period. For compound interest, it is simply the balance of the fund under operation at the end of the final year.
Operation companies use C, C++, Java, etc., to perform their calculations, so they pay a special attention to their interest rates. That is, in these companies, an interest rate is always an integral multiple of 0.0001220703125 and between 0.0001220703125 and 0.125 (inclusive). 0.0001220703125 is a decimal representation of 1/8192. Thus, interest rates' being its multiples means that they can be represented with no errors under the double-precision binary representation of floating-point numbers.
For example, if you operate 1000000 JPY for five years with an annual, compound interest rate of 0.03125 (3.125 %) and an annual operation charge of 3000 JPY, the balance changes as follows.
The balance of the fund under operation (at the beginning of year) | Interest| The balance of the fund under operation (at the end of year)
---|---|---
A| B = A × 0.03125 (and rounding off fractions) | A + B - 3000
1000000| 31250| 1028250
1028250| 32132| 1057382
1057382| 33043| 1087425
1087425| 33982| 1118407
1118407| 34950| 1150357
After the five years of operation, the final amount of fund is 1150357 JPY.
If the interest is simple with all other parameters being equal, it looks like:
The balance of the fund under operation (at the beginning of year) | Interest | The balance of the fund under operation (at the end of year) | Cumulative interest
---|---|---|---
A| B = A × 0.03125 (and rounding off fractions)| A - 3000|
1000000| 31250| 997000| 31250
997000| 31156| 994000| 62406
994000| 31062| 991000| 93468
991000| 30968| 988000| 124436
988000| 30875| 985000| 155311
In this case the final amount of fund is the total of the fund under operation, 985000 JPY, and the cumulative interests, 155311 JPY, which is 1140311 JPY.
Input
The input consists of datasets. The entire input looks like:
> the number of datasets (=m)
> 1st dataset
> 2nd dataset
> ...
> m-th dataset
>
The number of datasets, m, is no more than 100. Each dataset is formatted as follows.
> the initial amount of the fund for operation
> the number of years of operation
> the number of available operations (=n)
> operation 1
> operation 2
> ...
> operation n
>
The initial amount of the fund for operation, the number of years of operation, and the number of available operations are all positive integers. The first is no more than 100000000, the second no more than 10, and the third no more than 100.
Each ``operation'' is formatted as follows.
> simple-or-compound annual-interest-rate annual-operation-charge
where simple-or-compound is a single character of either '0' or '1', with '0' indicating simple interest and '1' compound. annual-interest-rate is represented by a decimal fraction and is an integral multiple of 1/8192. annual-operation-charge is an integer not exceeding 100000.
Output
For each dataset, print a line having a decimal integer indicating the final amount of fund for the best operation. The best operation is the one that yields the maximum final amount among the available operations. Each line should not have any character other than this number.
You may assume the final balance never exceeds 1000000000. You may also assume that at least one operation has the final amount of the fund no less than the initial amount of the fund.
Example
Input
4
1000000
5
2
0 0.03125 3000
1 0.03125 3000
6620000
7
2
0 0.0732421875 42307
1 0.0740966796875 40942
39677000
4
4
0 0.0709228515625 30754
1 0.00634765625 26165
0 0.03662109375 79468
0 0.0679931640625 10932
10585000
6
4
1 0.0054931640625 59759
1 0.12353515625 56464
0 0.0496826171875 98193
0 0.0887451171875 78966
Output
1150357
10559683
50796918
20829397
### Response
```cpp
#include<stdio.h>
int main(){
double a,b,unyou[100][5],syoki,max;
int i,j,k,m,nen,n;
scanf("%d",&m);
for(i=0;i<m;i++){
scanf("%lf%d%d",&syoki,&nen,&n);
// printf("i %d\n",i);
for(j=0;j<n;j++){
scanf("%lf%lf%lf",&unyou[j][0],&unyou[j][1],&unyou[j][2]);
a=syoki;
b=0;
// printf("j %d\n",j);
switch(int(unyou[j][0])){
case 0:
for(k=0;k<nen;k++){
// printf("k %d nen %d\n",k,nen);
b+=int(a*unyou[j][1]);
a=a-unyou[j][2];
}
unyou[j][3]=a+b;
// printf("%d %lf\n",j,unyou[j][3]);
break;
case 1:
for(k=0;k<nen;k++){
// printf("k %d nen %d\n",k,nen);
b=int(a*unyou[j][1]);
a=a-unyou[j][2]+b;
}
unyou[j][3]=a;
// printf("%d %lf\n",j,unyou[j][3]);
break;
}
}
max=0;
for(j=0;j<n;j++){
if(max<unyou[j][3]){
max=unyou[j][3];
}
}
printf("%.0f\n",max);
}
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.
Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (<image>), each column of the grid (<image>), and the two long diagonals of the grid (the main diagonal — <image> and the secondary diagonal — <image>) are equal.
Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible?
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 500) — the number of rows and columns of the magic grid.
n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai, j (1 ≤ ai, j ≤ 109 or ai, j = 0), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai, j will be equal to 0. Otherwise, ai, j is positive.
It is guaranteed that there is exactly one pair of integers i, j (1 ≤ i, j ≤ n) such that ai, j = 0.
Output
Output a single integer, the positive integer x (1 ≤ x ≤ 1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output - 1 instead.
If there are multiple solutions, you may print any of them.
Examples
Input
3
4 0 2
3 5 7
8 1 6
Output
9
Input
4
1 1 1 1
1 1 0 1
1 1 1 1
1 1 1 1
Output
1
Input
4
1 1 1 1
1 1 0 1
1 1 2 1
1 1 1 1
Output
-1
Note
In the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed,
The sum of numbers in each row is:
4 + 9 + 2 = 3 + 5 + 7 = 8 + 1 + 6 = 15.
The sum of numbers in each column is:
4 + 3 + 8 = 9 + 5 + 1 = 2 + 7 + 6 = 15.
The sum of numbers in the two diagonals is:
4 + 5 + 6 = 2 + 5 + 8 = 15.
In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square.
### Response
```cpp
#include <bits/stdc++.h>
int x, y, n;
long long c[505][505], sum, temp;
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
scanf("%I64d", &c[i][j]);
if (c[i][j] == 0) {
x = i;
y = j;
}
}
}
sum = 0;
if (n == 1) {
printf("1\n");
} else {
if (x == 1) {
for (int i = 1; i <= n; i++) {
sum += c[2][i];
}
} else {
for (int i = 1; i <= n; i++) {
sum += c[1][i];
}
}
temp = sum;
for (int i = 1; i <= n; i++) {
sum -= c[x][i];
}
c[x][y] = sum;
sum = temp;
int flag = 1;
for (int i = 1; i <= n && flag; i++) {
temp = 0;
for (int j = 1; j <= n; j++) {
temp += c[i][j];
}
if (temp != sum) flag = 0;
}
for (int i = 1; i <= n && flag; i++) {
temp = 0;
for (int j = 1; j <= n; j++) {
temp += c[j][i];
}
if (temp != sum) flag = 0;
}
temp = 0;
for (int i = 1; i <= n && flag; i++) temp += c[i][i];
if (temp != sum) flag = 0;
temp = 0;
for (int i = 1; i <= n && flag; i++) temp += c[i][n + 1 - i];
if (temp != sum) flag = 0;
if (flag && c[x][y] > 0) {
printf("%I64d\n", c[x][y]);
} else
printf("-1\n");
}
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building.
The slogan of the company consists of n characters, so the decorators hung a large banner, n meters wide and 1 meter high, divided into n equal squares. The first character of the slogan must be in the first square (the leftmost) of the poster, the second character must be in the second square, and so on.
Of course, the R1 programmers want to write the slogan on the poster themselves. To do this, they have a large (and a very heavy) ladder which was put exactly opposite the k-th square of the poster. To draw the i-th character of the slogan on the poster, you need to climb the ladder, standing in front of the i-th square of the poster. This action (along with climbing up and down the ladder) takes one hour for a painter. The painter is not allowed to draw characters in the adjacent squares when the ladder is in front of the i-th square because the uncomfortable position of the ladder may make the characters untidy. Besides, the programmers can move the ladder. In one hour, they can move the ladder either a meter to the right or a meter to the left.
Drawing characters and moving the ladder is very tiring, so the programmers want to finish the job in as little time as possible. Develop for them an optimal poster painting plan!
Input
The first line contains two integers, n and k (1 ≤ k ≤ n ≤ 100) — the number of characters in the slogan and the initial position of the ladder, correspondingly. The next line contains the slogan as n characters written without spaces. Each character of the slogan is either a large English letter, or digit, or one of the characters: '.', '!', ',', '?'.
Output
In t lines, print the actions the programmers need to make. In the i-th line print:
* "LEFT" (without the quotes), if the i-th action was "move the ladder to the left";
* "RIGHT" (without the quotes), if the i-th action was "move the ladder to the right";
* "PRINT x" (without the quotes), if the i-th action was to "go up the ladder, paint character x, go down the ladder".
The painting time (variable t) must be minimum possible. If there are multiple optimal painting plans, you can print any of them.
Examples
Input
2 2
R1
Output
PRINT 1
LEFT
PRINT R
Input
2 1
R1
Output
PRINT R
RIGHT
PRINT 1
Input
6 4
GO?GO!
Output
RIGHT
RIGHT
PRINT !
LEFT
PRINT O
LEFT
PRINT G
LEFT
PRINT ?
LEFT
PRINT O
LEFT
PRINT G
Note
Note that the ladder cannot be shifted by less than one meter. The ladder can only stand in front of some square of the poster. For example, you cannot shift a ladder by half a meter and position it between two squares. Then go up and paint the first character and the second character.
### Response
```cpp
#include <bits/stdc++.h>
int main() {
int n, k, i, mark, t;
char s[110];
while (scanf("%d%d", &n, &k) != EOF) {
scanf("%s", s);
t = n / 2;
mark = 0;
if (k <= t) {
if (k != 1)
for (i = 0; i < k - 1; i++) printf("LEFT\n");
} else {
mark = 1;
if (k != n)
for (i = 0; i < n - k; i++) printf("RIGHT\n");
}
if (mark)
for (i = n - 1; i >= 0; i--) {
printf("PRINT %c\n", s[i]);
if (i != 0) printf("LEFT\n");
}
else
for (i = 0; i < n; i++) {
printf("PRINT %c\n", s[i]);
if (i != n - 1) printf("RIGHT\n");
}
}
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Write a program which manipulates a sequence $A$ = {$a_0, a_1, ..., a_{n-1}$} with the following operations:
* $update(s, t, x)$: change $a_s, a_{s+1}, ..., a_t$ to $x$.
* $getSum(s, t)$: print the sum of $a_s, a_{s+1}, ..., a_t$.
Note that the initial values of $a_i ( i = 0, 1, ..., n-1 )$ are 0.
Constraints
* $1 ≤ n ≤ 100000$
* $1 ≤ q ≤ 100000$
* $0 ≤ s ≤ t < n$
* $-1000 ≤ x ≤ 1000$
Input
$n$ $q$
$query_1$
$query_2$
:
$query_q$
In the first line, $n$ (the number of elements in $A$) and $q$ (the number of queries) are given. Then, $i$-th query $query_i$ is given in the following format:
0 $s$ $t$ $x$
or
1 $s$ $t$
The first digit represents the type of the query. '0' denotes $update(s, t, x)$ and '1' denotes $find(s, t)$.
Output
For each $getSum$ query, print the sum in a line.
Example
Input
6 7
0 1 3 1
0 2 4 -2
1 0 5
1 0 1
0 3 5 3
1 3 4
1 0 5
Output
-5
1
6
8
### Response
```cpp
#include "bits/stdc++.h"
class LazySegmentTree
{
int n;
using T1 = long long;
using T2 = long long;
T1 id1 = 0;
T2 id2 = -INT_MAX;
std::vector<T1> node; // sum
std::vector<T2> lazy; // update
// 遅延評価
void eval(int k, int l, int r)
{
// 遅延配列が空なら終了
if (lazy[k] == id2)
return;
// 遅延配列を適用
node[k] = lazy[k];
if (r - l > 1)
{
lazy[2 * k + 1] = lazy[k] / 2;
lazy[2 * k + 2] = lazy[k] / 2;
}
// 遅延配列初期化
lazy[k] = id2;
}
public:
LazySegmentTree(int _n)
{
int sz = _n;
n = 1;
while (n < sz)
n *= 2;
// 配列初期化
node.resize(2 * n - 1, id1);
lazy.resize(2 * n - 1, id2);
}
// 半開区間 [a, b) に対して値 val を反映させる
void update(int a, int b, T2 val, int l = 0, int r = -1, int k = 0)
{
if (r < 0)
r = n;
// ノード k で遅延評価
eval(k, l, r);
if (b <= l || r <= a)
return;
// 区間が被覆されている場合
if (a <= l && r <= b)
{
// 遅延配列更新, 評価
lazy[k] = (r - l) * val;
eval(k, l, r);
}
else
{
// 子ノードの値を評価し, 更新
int mid = (l + r) / 2;
update(a, b, val, l, mid, 2 * k + 1);
update(a, b, val, mid, r, 2 * k + 2);
node[k] = node[2 * k + 1] + node[2 * k + 2];
}
}
// 半開区間 [a, b) に対してクエリを投げる
T1 query(int a, int b, int l = 0, int r = -1, int k = 0)
{
if (r < 0)
r = n;
eval(k, l, r);
// 範囲外なら単位元返す
if (b <= l || r <= a)
return id1;
if (a <= l && r <= b)
return node[k];
int mid = (l + r) / 2;
T1 vl = query(a, b, l, mid, 2 * k + 1);
T1 vr = query(a, b, mid, r, 2 * k + 2);
return vl + vr;
}
};
using namespace std;
void solve_dsl_2_i()
{
int n, q;
cin >> n >> q;
LazySegmentTree lst(n);
while (q--)
{
int type;
cin >> type;
if (type == 0)
{
int s, t, x;
cin >> s >> t >> x;
t++;
lst.update(s, t, x);
}
else
{
int s, t;
cin >> s >> t;
t++;
cout << lst.query(s, t) << endl;
}
}
}
int main()
{
solve_dsl_2_i();
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.
We will consider an extremely simplified subset of Python with only two types of statements.
Simple statements are written in a single line, one per line. An example of a simple statement is assignment.
For statements are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with "for" prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can't be empty.
You are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.
Input
The first line contains a single integer N (1 ≤ N ≤ 5000) — the number of commands in the program. N lines of the program follow, each line describing a single command. Each command is either "f" (denoting "for statement") or "s" ("simple statement"). It is guaranteed that the last line is a simple statement.
Output
Output one line containing an integer - the number of ways the given sequence of statements can be indented modulo 109 + 7.
Examples
Input
4
s
f
f
s
Output
1
Input
4
f
s
f
s
Output
2
Note
In the first test case, there is only one way to indent the program: the second for statement must be part of the body of the first one.
simple statement
for statement
for statement
simple statement
In the second test case, there are two ways to indent the program: the second for statement can either be part of the first one's body or a separate statement following the first one.
for statement
simple statement
for statement
simple statement
or
for statement
simple statement
for statement
simple statement
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 5e3 + 10;
const int md = 1e9 + 7;
int n;
char c[N];
int dp[N][N];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf(" %c", &c[i]);
dp[0][1] = 1;
c[0] = 's';
for (int i = 1; i <= n; i++) {
int tmp = 0;
for (int j = n; j >= 1; j--) {
if (c[i - 1] == 'f') dp[i][j] = dp[i - 1][j - 1];
if (c[i - 1] == 's') {
tmp += dp[i - 1][j], tmp %= md, dp[i][j] = tmp;
}
}
}
int ans = 0;
for (int i = 1; i <= n; i++) ans += dp[n][i], ans %= md;
cout << ans;
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
After a long journey, the super-space-time immigrant ship carrying you finally discovered a planet that seems to be habitable. The planet, named JOI, is a harsh planet with three types of terrain, "Jungle," "Ocean," and "Ice," as the name implies. A simple survey created a map of the area around the planned residence. The planned place of residence has a rectangular shape of M km north-south and N km east-west, and is divided into square sections of 1 km square. There are MN compartments in total, and the compartments in the p-th row from the north and the q-th column from the west are represented by (p, q). The northwest corner section is (1, 1) and the southeast corner section is (M, N). The terrain of each section is one of "jungle", "sea", and "ice". "Jungle" is represented by J, "sea" is represented by O, and "ice" is represented by one letter I.
Now, in making a detailed migration plan, I decided to investigate how many sections of "jungle," "sea," and "ice" are included in the rectangular area at K.
input
Read the following input from standard input.
* The integers M and N are written on the first line, separated by blanks, indicating that the planned residence is M km north-south and N km east-west.
* The integer K is written on the second line, which indicates the number of regions to be investigated.
* The following M line contains information on the planned residence. The second line of i + (1 ≤ i ≤ M) contains an N-character string consisting of J, O, and I that represents the information of the N section located on the i-th line from the north of the planned residence. ..
* The following K line describes the area to be investigated. On the second line of j + M + (1 ≤ j ≤ K), the positive integers aj, bj, cj, and dj representing the jth region are written with blanks as delimiters. (aj, bj) represents the northwest corner section of the survey area, and (cj, dj) represents the southeast corner section of the survey area. However, aj, bj, cj, and dj satisfy 1 ≤ aj ≤ cj ≤ M, 1 ≤ bj ≤ dj ≤ N.
output
Output K lines representing the results of the survey to standard output. Line j of the output contains three integers representing the number of "jungle" (J) compartments, the "sea" (O) compartment, and the "ice" (I) compartment in the jth survey area. , In this order, separated by blanks.
Example
Input
4 7
4
JIOJOIJ
IOJOIJO
JOIJOOI
OOJJIJO
3 5 4 7
2 2 3 6
2 2 2 2
1 1 4 7
Output
1 3 2
3 5 2
0 1 0
10 11 7
### Response
```cpp
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAX = 1001;
int H, W, K;
int J[MAX][MAX], O[MAX][MAX], I[MAX][MAX];
char field[MAX][MAX];
int main(void) {
while(cin >> H >> W >> K) {
memset(J, 0, sizeof(J));
memset(O, 0, sizeof(O));
memset(I, 0, sizeof(I));
for(int i = 1; i <= H; i++){
cin >> &field[i][1];
for(int j = 1 ; j <= W ; j++){
J[i][j] = J[i - 1][j] + J[i][j - 1] - J[i - 1][j - 1];
O[i][j] = O[i - 1][j] + O[i][j - 1] - O[i - 1][j - 1];
I[i][j] = I[i - 1][j] + I[i][j - 1] - I[i - 1][j - 1];
if(field[i][j] == 'J') J[i][j]++;
else if(field[i][j] == 'O') O[i][j]++;
else if(field[i][j] == 'I') I[i][j]++;
}
}
for(int i = 0 ; i < K ; i++) {
int px, py, qx, qy;
cin >> px >> py >> qx >> qy;
int ansJ, ansO, ansI;
ansJ = J[qx][qy] - J[px-1][qy] - J[qx][py-1] + J[px-1][py-1];
ansO = O[qx][qy] - O[px-1][qy] - O[qx][py-1] + O[px-1][py-1];
ansI = I[qx][qy] - I[px-1][qy] - I[qx][py-1] + I[px-1][py-1];
printf("%d %d %d\n", ansJ, ansO, ansI);
}
}
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Eric is the teacher of graph theory class. Today, Eric teaches independent set and edge-induced subgraph.
Given a graph G=(V,E), an independent set is a subset of vertices V' ⊂ V such that for every pair u,v ∈ V', (u,v) not ∈ E (i.e. no edge in E connects two vertices from V').
An edge-induced subgraph consists of a subset of edges E' ⊂ E and all the vertices in the original graph that are incident on at least one edge in the subgraph.
Given E' ⊂ E, denote G[E'] the edge-induced subgraph such that E' is the edge set of the subgraph. Here is an illustration of those definitions:
<image>
In order to help his students get familiar with those definitions, he leaves the following problem as an exercise:
Given a tree G=(V,E), calculate the sum of w(H) over all except null edge-induced subgraph H of G, where w(H) is the number of independent sets in H. Formally, calculate ∑ _{∅ not= E' ⊂ E} w(G[E']).
Show Eric that you are smarter than his students by providing the correct answer as quickly as possible. Note that the answer might be large, you should output the answer modulo 998,244,353.
Input
The first line contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5), representing the number of vertices of the graph G.
Each of the following n-1 lines contains two integers u and v (1 ≤ u,v ≤ n, u not= v), describing edges of the given tree.
It is guaranteed that the given edges form a tree.
Output
Output one integer, representing the desired value modulo 998,244,353.
Examples
Input
2
2 1
Output
3
Input
3
1 2
3 2
Output
11
Note
For the second example, all independent sets are listed below.
<image>
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
using namespace std;
const int N = 3e5 + 7;
const long long mod = 998244353;
long long dp[3][N];
int n;
vector<int> g[N];
void dfs(int v, int p = 0) {
dp[0][v] = dp[1][v] = dp[2][v] = 1;
for (int to : g[v]) {
if (to != p) {
dfs(to, v);
dp[0][v] *= (2 * dp[0][to] + 2 * dp[1][to] - dp[2][to]) % mod;
dp[0][v] %= mod;
dp[1][v] *= (2 * dp[0][to] + dp[1][to] - dp[2][to]) % mod;
dp[1][v] %= mod;
dp[2][v] *= (dp[0][to] + dp[1][to] - dp[2][to]) % mod;
dp[2][v] %= mod;
}
}
}
int main() {
cin >> n;
for (int i = 1; i < n; i++) {
int a, b;
scanf("%d%d", &a, &b);
g[a].push_back(b);
g[b].push_back(a);
}
dfs(1);
cout << (dp[0][1] + dp[1][1] - dp[2][1] - 1 + 2 * mod) % mod;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
[SIHanatsuka - EMber](https://soundcloud.com/hanatsuka/sihanatsuka-ember)
[SIHanatsuka - ATONEMENT](https://soundcloud.com/hanatsuka/sihanatsuka-atonement)
Back in time, the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.
One day, Nora's adoptive father, Phoenix Wyle, brought Nora n boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO.
She labelled all n boxes with n distinct integers a_1, a_2, …, a_n and asked ROBO to do the following action several (possibly zero) times:
* Pick three distinct indices i, j and k, such that a_i ∣ a_j and a_i ∣ a_k. In other words, a_i divides both a_j and a_k, that is a_j mod a_i = 0, a_k mod a_i = 0.
* After choosing, Nora will give the k-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty.
* After doing so, the box k becomes unavailable for any further actions.
Being amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the largest amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes.
Since ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them?
As the number of such piles can be very large, you should print the answer modulo 10^9 + 7.
Input
The first line contains an integer n (3 ≤ n ≤ 60), denoting the number of boxes.
The second line contains n distinct integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 60), where a_i is the label of the i-th box.
Output
Print the number of distinct piles having the maximum number of boxes that ROBO_Head can have, modulo 10^9 + 7.
Examples
Input
3
2 6 8
Output
2
Input
5
2 3 4 9 12
Output
4
Input
4
5 7 2 9
Output
1
Note
Let's illustrate the box pile as a sequence b, with the pile's bottommost box being at the leftmost position.
In the first example, there are 2 distinct piles possible:
* b = [6] ([2, 6, 8] \xrightarrow{(1, 3, 2)} [2, 8])
* b = [8] ([2, 6, 8] \xrightarrow{(1, 2, 3)} [2, 6])
In the second example, there are 4 distinct piles possible:
* b = [9, 12] ([2, 3, 4, 9, 12] \xrightarrow{(2, 5, 4)} [2, 3, 4, 12] \xrightarrow{(1, 3, 4)} [2, 3, 4])
* b = [4, 12] ([2, 3, 4, 9, 12] \xrightarrow{(1, 5, 3)} [2, 3, 9, 12] \xrightarrow{(2, 3, 4)} [2, 3, 9])
* b = [4, 9] ([2, 3, 4, 9, 12] \xrightarrow{(1, 5, 3)} [2, 3, 9, 12] \xrightarrow{(2, 4, 3)} [2, 3, 12])
* b = [9, 4] ([2, 3, 4, 9, 12] \xrightarrow{(2, 5, 4)} [2, 3, 4, 12] \xrightarrow{(1, 4, 3)} [2, 3, 12])
In the third sequence, ROBO can do nothing at all. Therefore, there is only 1 valid pile, and that pile is empty.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long MN = 62, MOD = 1000 * 1000 * 1000 + 7;
long long C[MN][MN], mark[MN], a[MN], mask[MN], dp[(1 << 16)][MN];
vector<long long> srs, oth, jda[MN], adj[MN], vec;
long long sol() {
long long n = srs.size(), m = oth.size();
long long num[MN] = {};
if (m == 0) return 1;
vec.push_back(m - 1);
for (long long i = 0; i < MN; i++) num[i] = -1;
long long cnt = 0;
for (long long i : srs) num[i] = cnt++;
for (long long cn = 1; cn <= m; cn++)
for (long long msk = 0; msk < (1 << n); msk++) dp[msk][cn] = 0;
for (long long i = 0; i < m; i++) {
mask[i] = 0;
for (long long u : jda[oth[i]])
if (num[u] != -1) mask[i] |= (1 << num[u]);
dp[mask[i]][1]++;
}
for (long long cn = 1; cn < m; cn++)
for (long long msk = 0; msk < (1 << n); msk++) {
vector<long long> gd, bd;
for (long long i = 0; i < m; i++) {
if ((mask[i] | msk) == msk)
gd.push_back(i);
else if (mask[i] & msk)
bd.push_back(i);
}
if (cn > gd.size()) continue;
(dp[msk][cn + 1] += (dp[msk][cn] * (gd.size() - cn)) % MOD) %= MOD;
for (long long u : bd) dp[msk | mask[u]][cn + 1] += dp[msk][cn];
}
return dp[(1 << n) - 1][m];
}
void dfs(long long v) {
mark[v] = 1 + (jda[v].size() ? 0 : 1);
for (long long i : adj[v])
if (!mark[i]) dfs(i);
for (long long i : jda[v])
if (!mark[i]) dfs(i);
(jda[v].size() ? oth : srs).push_back(v);
}
void pre() {
for (long long i = 0; i < MN; i++) {
C[i][i] = C[i][0] = 1;
for (long long j = 1; j < i; j++)
C[i][j] = (C[i - 1][j] + C[i - 1][j - 1]) % MOD;
}
}
long long solve(vector<long long> &vec) {
if (!vec.size()) return 1;
long long sum = 0;
for (long long u : vec) sum += u;
long long x = vec.back();
vec.pop_back();
return C[sum][x] * solve(vec);
}
int32_t main() {
pre();
long long n;
cin >> n;
for (long long i = 0; i < n; i++) cin >> a[i];
for (long long i = 0; i < n; i++)
for (long long j = 0; j < n; j++)
if (a[i] % a[j] == 0 && i != j) {
jda[i].push_back(j);
adj[j].push_back(i);
}
long long ans = 1;
for (long long i = 0; i < n; i++)
if (!mark[i]) {
dfs(i);
ans = ans * sol() % MOD;
srs.clear();
oth.clear();
}
ans = ans * solve(vec);
cout << ans;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Mr. Bill is shopping at the store. There are some coins in his wallet (10-yen coins, 50-yen coins, 100-yen coins, 500-yen coins), but he is now trying to consume as much of this coin as possible. In other words, by paying for the goods with an appropriate number of coins, we are trying to minimize the total number of coins after receiving the change.
Fortunately, the clerk at this store is so disciplined and kind that change is always delivered in the best possible way. Therefore, for example, five 100-yen coins will not be given instead of one 500-yen coin. You can also take out 5 10-yen coins and receive 50-yen coins as change. However, you must not pay the coins of the same type as the coins you issued so that they will be returned as change. For example, if a 10-yen coin is paid out and another 10-yen coin is returned as change, a completely meaningless exchange will occur.
However, Mr. Bill was not good at calculating, so he could not find out how many coins he should actually use. So he asked you for help. Your job is to write a program to determine the type and number of coins to use based on the number of coins in his wallet and the payment price. The clerk does not use banknotes for change.
Input
The input contains several test cases.
Each test case consists of two lines. The first line contains a single integer representing Mr. Bill's payment in yen. The second line contains four integers, which in turn represent the number of 10-yen coins, 50-yen coins, 100-yen coins, and 500-yen coins in your wallet.
The payment amount is always in units of 10 yen. That is, the one-yen place of the payment amount is always 0. You can also assume that you can only have up to 20 coins of the same type in your wallet. No non-payable cases are given during input.
The end of input is represented by a line containing a single 0.
Output
For each test case, print out the type and number of coins that Mr. Bill should use.
Each line of output contains the two integers ci and ki. This means using ki coins for ci yen when paying. When using multiple types of coins, output as many lines as necessary in order from the smallest ci. Refer to the output example below.
The output must not include extra space. Separate consecutive test cases with a blank line.
Example
Input
160
1 1 2 0
160
1 0 2 10
0
Output
10 1
50 1
100 1
10 1
100 2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int units[4] = {10, 50, 100, 500};
int main() {
int p;
bool first = true;
while(cin >> p, p) {
if(!first) {
cout << endl;
}
first = false;
int c[4];
int sum = 0;
for(int i = 0; i < 4; i++) {cin >> c[i]; sum += units[i]*c[i];}
sum -= p;
for(int i = 3; i >= 0; i--) {
while(sum >= units[i]) {
sum -= units[i]; c[i]--;
}
}
for(int i = 0; i < 4; i++) {
if(c[i] > 0)
cout << units[i] << " " << c[i] << endl;
}
}
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks?
The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE
Input
The first line contains an integer n (1 ≤ n ≤ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators.
Only the drinks from the list given above should be considered alcohol.
Output
Print a single number which is the number of people Vasya should check to guarantee the law enforcement.
Examples
Input
5
18
VODKA
COKE
19
17
Output
2
Note
In the sample test the second and fifth clients should be checked.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
string trollface[29] = {"ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN",
"RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY",
"WINE", "0", "1", "2", "3",
"4", "5", "6", "7", "8",
"9", "10", "11", "12", "13",
"14", "15", "16", "17"};
int troll(string s) {
for (int i = 0; i < 29; i++) {
if (s == trollface[i]) return 1;
}
return 0;
}
int main() {
int n, ans = 0;
string s;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> s;
if (troll(s)) ans++;
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
On his free time, Chouti likes doing some housework. He has got one new task, paint some bricks in the yard.
There are n bricks lined in a row on the ground. Chouti has got m paint buckets of different colors at hand, so he painted each brick in one of those m colors.
Having finished painting all bricks, Chouti was satisfied. He stood back and decided to find something fun with these bricks. After some counting, he found there are k bricks with a color different from the color of the brick on its left (the first brick is not counted, for sure).
So as usual, he needs your help in counting how many ways could he paint the bricks. Two ways of painting bricks are different if there is at least one brick painted in different colors in these two ways. Because the answer might be quite big, you only need to output the number of ways modulo 998 244 353.
Input
The first and only line contains three integers n, m and k (1 ≤ n,m ≤ 2000, 0 ≤ k ≤ n-1) — the number of bricks, the number of colors, and the number of bricks, such that its color differs from the color of brick to the left of it.
Output
Print one integer — the number of ways to color bricks modulo 998 244 353.
Examples
Input
3 3 0
Output
3
Input
3 2 1
Output
4
Note
In the first example, since k=0, the color of every brick should be the same, so there will be exactly m=3 ways to color the bricks.
In the second example, suppose the two colors in the buckets are yellow and lime, the following image shows all 4 possible colorings.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline long long min2(long long a, long long b) {
return (a) < (b) ? (a) : (b);
}
inline long long max2(long long a, long long b) {
return (a) > (b) ? (a) : (b);
}
inline long long max3(long long a, long long b, long long c) {
return (a) > (b) ? ((a) > (c) ? (a) : (c)) : ((b) > (c) ? (b) : (c));
}
inline long long min3(long long a, long long b, long long c) {
return (a) < (b) ? ((a) < (c) ? (a) : (c)) : ((b) < (c) ? (b) : (c));
}
using namespace std::chrono;
long long int n, m, k;
long long int dp[2001][2001];
long long int fun(long long int i, long long int c) {
if (i == n + 1) {
if (c == k)
return 1;
else
return 0;
}
if (dp[i][c] != -1) return dp[i][c];
if (i == 1)
dp[i][c] = (m * fun(i + 1, c)) % 998244353;
else
dp[i][c] = (((m - 1) * fun(i + 1, c + 1)) % 998244353 +
(1 * fun(i + 1, c)) % 998244353) %
998244353;
return dp[i][c];
}
void process() {
cin >> n >> m >> k;
memset(dp, -1, sizeof(dp));
cout << fun(1, 0) << endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
;
process();
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Gildong is experimenting with an interesting machine Graph Traveler. In Graph Traveler, there is a directed graph consisting of n vertices numbered from 1 to n. The i-th vertex has m_i outgoing edges that are labeled as e_i[0], e_i[1], …, e_i[m_i-1], each representing the destination vertex of the edge. The graph can have multiple edges and self-loops. The i-th vertex also has an integer k_i written on itself.
A travel on this graph works as follows.
1. Gildong chooses a vertex to start from, and an integer to start with. Set the variable c to this integer.
2. After arriving at the vertex i, or when Gildong begins the travel at some vertex i, add k_i to c.
3. The next vertex is e_i[x] where x is an integer 0 ≤ x ≤ m_i-1 satisfying x ≡ c \pmod {m_i}. Go to the next vertex and go back to step 2.
It's obvious that a travel never ends, since the 2nd and the 3rd step will be repeated endlessly.
For example, assume that Gildong starts at vertex 1 with c = 5, and m_1 = 2, e_1[0] = 1, e_1[1] = 2, k_1 = -3. Right after he starts at vertex 1, c becomes 2. Since the only integer x (0 ≤ x ≤ 1) where x ≡ c \pmod {m_i} is 0, Gildong goes to vertex e_1[0] = 1. After arriving at vertex 1 again, c becomes -1. The only integer x satisfying the conditions is 1, so he goes to vertex e_1[1] = 2, and so on.
Since Gildong is quite inquisitive, he's going to ask you q queries. He wants to know how many distinct vertices will be visited infinitely many times, if he starts the travel from a certain vertex with a certain value of c. Note that you should not count the vertices that will be visited only finite times.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 1000), the number of vertices in the graph.
The second line contains n integers. The i-th integer is k_i (-10^9 ≤ k_i ≤ 10^9), the integer written on the i-th vertex.
Next 2 ⋅ n lines describe the edges of each vertex. The (2 ⋅ i + 1)-st line contains an integer m_i (1 ≤ m_i ≤ 10), the number of outgoing edges of the i-th vertex. The (2 ⋅ i + 2)-nd line contains m_i integers e_i[0], e_i[1], …, e_i[m_i-1], each having an integer value between 1 and n, inclusive.
Next line contains an integer q (1 ≤ q ≤ 10^5), the number of queries Gildong wants to ask.
Next q lines contains two integers x and y (1 ≤ x ≤ n, -10^9 ≤ y ≤ 10^9) each, which mean that the start vertex is x and the starting value of c is y.
Output
For each query, print the number of distinct vertices that will be visited infinitely many times, if Gildong starts at vertex x with starting integer y.
Examples
Input
4
0 0 0 0
2
2 3
1
2
3
2 4 1
4
3 1 2 1
6
1 0
2 0
3 -1
4 -2
1 1
1 5
Output
1
1
2
1
3
2
Input
4
4 -5 -3 -1
2
2 3
1
2
3
2 4 1
4
3 1 2 1
6
1 0
2 0
3 -1
4 -2
1 1
1 5
Output
1
1
1
3
1
1
Note
The first example can be shown like the following image:
<image>
Three integers are marked on i-th vertex: i, k_i, and m_i respectively. The outgoing edges are labeled with an integer representing the edge number of i-th vertex.
The travel for each query works as follows. It is described as a sequence of phrases, each in the format "vertex (c after k_i added)".
* 1(0) → 2(0) → 2(0) → …
* 2(0) → 2(0) → …
* 3(-1) → 1(-1) → 3(-1) → …
* 4(-2) → 2(-2) → 2(-2) → …
* 1(1) → 3(1) → 4(1) → 1(1) → …
* 1(5) → 3(5) → 1(5) → …
The second example is same as the first example, except that the vertices have non-zero values. Therefore the answers to the queries also differ from the first example.
<image>
The queries for the second example works as follows:
* 1(4) → 2(-1) → 2(-6) → …
* 2(-5) → 2(-10) → …
* 3(-4) → 1(0) → 2(-5) → 2(-10) → …
* 4(-3) → 1(1) → 3(-2) → 4(-3) → …
* 1(5) → 3(2) → 1(6) → 2(1) → 2(-4) → …
* 1(9) → 3(6) → 2(1) → 2(-4) → …
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 10;
const int M = 1e9 + 7;
const int inf = 1e9 + 7;
const long long INF = 1e18;
int n;
int a[N];
int d[N];
vector<int> b[N];
int vis[N][2550];
pair<int, int> his[N * 2550];
long long ans[N][2550];
int num[N];
int cur, top;
int solve(int x, int y) {
if (ans[x][y]) return ans[x][y];
++cur;
his[top = 1] = {x, y};
vis[x][y] = cur;
while (1) {
x = b[x][y % d[x]];
y += a[x];
if (y < 0) {
y = -y;
y %= 2520;
y = 2520 - y;
} else {
y %= 2520;
}
if (vis[x][y]) break;
vis[x][y] = cur;
his[++top] = {x, y};
}
if (vis[x][y] != cur) {
for (int k = 1; k <= top; k++) {
ans[his[k].first][his[k].second] = ans[x][y];
}
} else {
int sz = 0;
for (int k = top; k >= 1; k--) {
if (num[his[k].first] != cur) {
num[his[k].first] = cur;
sz++;
}
if (his[k].first == x && his[k].second == y) break;
}
for (int k = 1; k <= top; k++) {
ans[his[k].first][his[k].second] = sz;
}
}
return ans[x][y];
}
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
for (int i = 1; i <= n; i++) {
cin >> d[i];
b[i].resize(d[i]);
for (int j = 0; j < d[i]; j++) {
cin >> b[i][j];
}
}
for (int i = 1; i <= n; i++)
for (int j = 0; j < 2520; j++) {
vis[i][j] = 0;
}
int q;
cin >> q;
int x, y;
cur = 0;
while (q--) {
cin >> x >> y;
y += a[x];
if (y < 0) {
y = -y;
y %= 2520;
y = 2520 - y;
} else {
y %= 2520;
}
cout << solve(x, y) << "\n";
}
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Let's assume that set S consists of m distinct intervals [l1, r1], [l2, r2], ..., [lm, rm] (1 ≤ li ≤ ri ≤ n; li, ri are integers).
Let's assume that f(S) is the maximum number of intervals that you can choose from the set S, such that every two of them do not intersect. We assume that two intervals, [l1, r1] and [l2, r2], intersect if there is an integer x, which meets two inequalities: l1 ≤ x ≤ r1 and l2 ≤ x ≤ r2.
Sereja wonders, how many sets S are there, such that f(S) = k? Count this number modulo 1000000007 (109 + 7).
Input
The first line contains integers n, k (1 ≤ n ≤ 500; 0 ≤ k ≤ 500).
Output
In a single line, print the answer to the problem modulo 1000000007 (109 + 7).
Examples
Input
3 1
Output
23
Input
3 2
Output
32
Input
2 0
Output
1
Input
2 2
Output
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int modulo = 1e9 + 7;
long long int eleva(long long int b, long long int e) {
if (e == 0) return 1;
if (e % 2 == 0) return eleva(b * b % modulo, e / 2);
return b * eleva(b * b % modulo, e / 2) % modulo;
}
long long int memcomputa[1000][1000];
int calculado[1000][1000];
long long int computa(int n, int k) {
if (n < k) return 0;
if (k == 0) return 1;
long long int &mem = memcomputa[n][k];
if (calculado[n][k]) return mem;
calculado[n][k] = 1;
mem = 0;
for (int i = 1; i <= n; i++)
mem = (mem + (eleva(2, i) - 1 + modulo) * eleva(2, i * (n - i)) % modulo *
computa(n - i, k - 1)) %
modulo;
return mem;
}
int main() {
int n, k;
cin >> n >> k;
cout << computa(n, k) << endl;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
For given n points in metric space, find the distance of the closest points.
Constraints
* 2 ≤ n ≤ 100,000
* -100 ≤ x, y ≤ 100
Input
n
x0 y0
x1 y1
:
xn-1 yn-1
The first integer n is the number of points.
In the following n lines, the coordinate of the i-th point is given by two real numbers xi and yi. Each value is a real number with at most 6 digits after the decimal point.
Output
Print the distance in a line. The output values should be in a decimal fraction with an error less than 0.000001.
Examples
Input
2
0.0 0.0
1.0 0.0
Output
1.000000
Input
3
0.0 0.0
2.0 0.0
1.0 1.0
Output
1.41421356237
### Response
```cpp
#include<iostream>
using namespace std;
#include<utility>
#include<algorithm>
#include<cstdio>
#include<cmath>
typedef pair<double, double> point;
typedef point* data;
inline double dist(const point &a, const point &b)
{
double dx = a.first - b.first, dy = a.second - b.second;
return sqrt(dx * dx + dy * dy);
}
bool y_less(const point &P1, const point &P2){ return P1.second < P2.second; }
bool y_greater(const point &P1, const point &P2){ return P1.second > P2.second; }
double closest(data P, int n)
{
if(n <= 1) return 1000;
if(n == 2) return dist(P[0], P[1]);
int m = n / 2;
sort(P, P + n, y_less); // y_sort, down to up.
double median = P[m].second;
double d = min(closest(P, m), closest(P + m, n - m));
sort(P, P + m, y_less);
sort(P + m, P + n, y_greater);
int a, b;
for(a = m - 1; a > 0; a--){ if(P[a].second < median - d) break; }
for(b = n - 1; b > m; b--){ if(P[b].second > median + d) break; }
sort(P + a, P + m);
sort(P + b, P + n);
// x_sort, left to right.
int u, v, i, j;
u = i = a, v = j = b;
while(i < m && j < n){
if(P[u].first < P[v].first){
for(i = a; i < m; i++){
if(P[i].first >= P[v].first){ u = i; break; }
if(P[v].first - P[i].first >= d){ a++; }
else{
d = min(d, dist(P[v], P[i]));
}
}
}else{
for(j = b; j < n; j++){
if(P[j].first > P[u].first){ v = j; break; }
if(P[u].first - P[j].first >= d){ b++; }
else{
d = min(d, dist(P[u], P[j]));
}
}
}
};
return d;
}
int main()
{
int i, n;
double x, y;
scanf("%d", &n);
data P;
P = new point [n];
for(i = 0; i < n; i++){
scanf("%lf %lf", &x, &y);
P[i] = make_pair(x, y);
}
printf("%.12f\n", closest(P, n));
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Levko loves array a1, a2, ... , an, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types:
1. Increase all elements from li to ri by di. In other words, perform assignments aj = aj + di for all j that meet the inequation li ≤ j ≤ ri.
2. Find the maximum of elements from li to ri. That is, calculate the value <image>.
Sadly, Levko has recently lost his array. Fortunately, Levko has records of all operations he has performed on array a. Help Levko, given the operation records, find at least one suitable array. The results of all operations for the given array must coincide with the record results. Levko clearly remembers that all numbers in his array didn't exceed 109 in their absolute value, so he asks you to find such an array.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 5000) — the size of the array and the number of operations in Levko's records, correspondingly.
Next m lines describe the operations, the i-th line describes the i-th operation. The first integer in the i-th line is integer ti (1 ≤ ti ≤ 2) that describes the operation type. If ti = 1, then it is followed by three integers li, ri and di (1 ≤ li ≤ ri ≤ n, - 104 ≤ di ≤ 104) — the description of the operation of the first type. If ti = 2, then it is followed by three integers li, ri and mi (1 ≤ li ≤ ri ≤ n, - 5·107 ≤ mi ≤ 5·107) — the description of the operation of the second type.
The operations are given in the order Levko performed them on his array.
Output
In the first line print "YES" (without the quotes), if the solution exists and "NO" (without the quotes) otherwise.
If the solution exists, then on the second line print n integers a1, a2, ... , an (|ai| ≤ 109) — the recovered array.
Examples
Input
4 5
1 2 3 1
2 1 2 8
2 3 4 7
1 1 3 3
2 3 4 8
Output
YES
4 7 4 7
Input
4 5
1 2 3 1
2 1 2 8
2 3 4 7
1 1 3 3
2 3 4 13
Output
NO
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#pragma comment(linker, "/STACK:102400000,102400000")
int n, m, a[10000], sum[10000], op[10000], l[10000], r[10000], num[10000],
b[10000];
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) a[i] = 999999999;
memset(sum, 0, sizeof(sum));
for (int i = 1; i <= m; i++) {
scanf("%d%d%d%d", &op[i], &l[i], &r[i], &num[i]);
if (op[i] == 1) {
for (int j = l[i]; j <= r[i]; j++) sum[j] += num[i];
} else {
for (int j = l[i]; j <= r[i]; j++)
if (a[j] + sum[j] > num[i]) a[j] = num[i] - sum[j];
}
}
memcpy(b, a, sizeof(a));
for (int i = 1; i <= m; i++) {
if (op[i] == 1) {
for (int j = l[i]; j <= r[i]; j++) b[j] += num[i];
} else {
int m = -0x3f3f3f3f;
for (int j = l[i]; j <= r[i]; j++) m = max(m, b[j]);
if (m != num[i]) {
cout << "NO" << endl;
return 0;
}
}
}
cout << "YES" << endl;
cout << a[1];
for (int i = 2; i <= n; i++) cout << " " << a[i];
cout << endl;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.
He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position x, and the shorter rabbit is currently on position y (x < y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by a, and the shorter rabbit hops to the negative direction by b.
<image>
For example, let's say x=0, y=10, a=2, and b=3. At the 1-st second, each rabbit will be at position 2 and 7. At the 2-nd second, both rabbits will be at position 4.
Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000).
Each test case contains exactly one line. The line consists of four integers x, y, a, b (0 ≤ x < y ≤ 10^9, 1 ≤ a,b ≤ 10^9) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.
Output
For each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.
If the two rabbits will never be at the same position simultaneously, print -1.
Example
Input
5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
Output
2
-1
10
-1
1
Note
The first case is explained in the description.
In the second case, each rabbit will be at position 3 and 7 respectively at the 1-st second. But in the 2-nd second they will be at 6 and 4 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.
### Response
```cpp
#include <bits/stdc++.h>
int main() {
int x, y, a, b, n;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d%d%d%d", &x, &y, &a, &b);
y -= x, a += b;
printf("%d\n", y % a == 0 ? y / a : -1);
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
The only difference between easy and hard versions is constraints.
You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i.
The integer point is called bad if it is covered by strictly more than k segments.
Your task is to remove the minimum number of segments so that there are no bad points at all.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 200) — the number of segments and the maximum number of segments by which each integer point can be covered.
The next n lines contain segments. The i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 200) — the endpoints of the i-th segment.
Output
In the first line print one integer m (0 ≤ m ≤ n) — the minimum number of segments you need to remove so that there are no bad points.
In the second line print m distinct integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ n) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.
Examples
Input
7 2
11 11
9 11
7 8
8 9
7 8
9 11
7 9
Output
3
1 4 7
Input
5 1
29 30
30 30
29 29
28 30
30 30
Output
3
1 2 4
Input
6 1
2 3
3 3
2 3
2 2
2 3
2 3
Output
4
1 3 5 6
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 2e5 + 10;
int l[maxn], r[maxn];
int n, k;
vector<int> node[maxn];
set<pair<int, int> > s;
int main() {
ios::sync_with_stdio(false);
cin >> n >> k;
for (int i = 1; i <= n; i++) {
cin >> l[i] >> r[i];
node[l[i]].push_back(i);
node[r[i] + 1].push_back(-i);
}
vector<int> ans;
for (int i = 1; i <= 2e5; i++) {
for (int j = 0; j < node[i].size(); j++) {
int u = node[i][j];
if (u > 0) {
s.insert(make_pair(r[u], u));
} else
s.erase(make_pair(r[-u], -u));
}
while (s.size() > k) {
set<pair<int, int> >::iterator it = s.end();
--it;
ans.push_back(it->second);
s.erase(*it);
}
}
cout << ans.size() << endl;
for (int i = 0; i < ans.size(); i++) {
cout << abs(ans[i]) << " ";
}
cout << endl;
return 0;
}
``` |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.