text
stringlengths 424
69.5k
|
---|
### Prompt
In CPP, your task is to solve the following problem:
There is a knight - the chess piece - at the origin (0, 0) of a two-dimensional grid.
When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1).
In how many ways can the knight reach the square (X, Y)?
Find the number of ways modulo 10^9 + 7.
Constraints
* 1 \leq X \leq 10^6
* 1 \leq Y \leq 10^6
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
Print the number of ways for the knight to reach (X, Y) from (0, 0), modulo 10^9 + 7.
Examples
Input
3 3
Output
2
Input
2 2
Output
0
Input
999999 999999
Output
151840682
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
long long m=1000000007,ans;
int x,y,a,b;cin>>x>>y;
if((x+y)%3==0){
a=(2*y-x)/3;b=(2*x-y)/3;
if(a<0||b<0)cout<<0<<endl;
else{
long long p=1,q=1;
for(int i=a+b;i>a;i--){
p*=i;
p=p%m;
q*=i-a;
q=q%m;
}
for(int i=0;i<m;i++){
if(i*q%m==p){ans=i;break;}
}
cout<<ans<<endl;
}
}
else cout<<0<<endl;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string s, consisting of characters "x" and "y", and uses two following operations at runtime:
1. Find two consecutive characters in the string, such that the first of them equals "y", and the second one equals "x" and swap them. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string.
2. Find in the string two consecutive characters, such that the first of them equals "x" and the second one equals "y". Remove these characters from the string. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string.
The input for the new algorithm is string s, and the algorithm works as follows:
1. If you can apply at least one of the described operations to the string, go to step 2 of the algorithm. Otherwise, stop executing the algorithm and print the current string.
2. If you can apply operation 1, then apply it. Otherwise, apply operation 2. After you apply the operation, go to step 1 of the algorithm.
Now Vitaly wonders, what is going to be printed as the result of the algorithm's work, if the input receives string s.
Input
The first line contains a non-empty string s.
It is guaranteed that the string only consists of characters "x" and "y". It is guaranteed that the string consists of at most 106 characters. It is guaranteed that as the result of the algorithm's execution won't be an empty string.
Output
In the only line print the string that is printed as the result of the algorithm's work, if the input of the algorithm input receives string s.
Examples
Input
x
Output
x
Input
yxyxy
Output
y
Input
xxxxxy
Output
xxxx
Note
In the first test the algorithm will end after the first step of the algorithm, as it is impossible to apply any operation. Thus, the string won't change.
In the second test the transformation will be like this:
1. string "yxyxy" transforms into string "xyyxy";
2. string "xyyxy" transforms into string "xyxyy";
3. string "xyxyy" transforms into string "xxyyy";
4. string "xxyyy" transforms into string "xyy";
5. string "xyy" transforms into string "y".
As a result, we've got string "y".
In the third test case only one transformation will take place: string "xxxxxy" transforms into string "xxxx". Thus, the answer will be string "xxxx".
### Response
```cpp
#include <bits/stdc++.h>
int main() {
int num_x = 0, num_y = 0;
char c;
while ((c = getchar()) != '\n') {
if (c == 'x') {
++num_x;
} else if (c == 'y') {
++num_y;
}
}
if (num_y > num_x) {
for (int i = 0; i < (int)(num_y - num_x); ++i) {
putchar('y');
}
} else {
for (int i = 0; i < (int)(num_x - num_y); ++i) {
putchar('x');
}
}
putchar('\n');
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
You are given two arrays a and b of positive integers, with length n and m respectively.
Let c be an n Γ m matrix, where c_{i,j} = a_i β
b_j.
You need to find a subrectangle of the matrix c such that the sum of its elements is at most x, and its area (the total number of elements) is the largest possible.
Formally, you need to find the largest number s such that it is possible to choose integers x_1, x_2, y_1, y_2 subject to 1 β€ x_1 β€ x_2 β€ n, 1 β€ y_1 β€ y_2 β€ m, (x_2 - x_1 + 1) Γ (y_2 - y_1 + 1) = s, and $$$β_{i=x_1}^{x_2}{β_{j=y_1}^{y_2}{c_{i,j}}} β€ x.$$$
Input
The first line contains two integers n and m (1 β€ n, m β€ 2000).
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 2000).
The third line contains m integers b_1, b_2, β¦, b_m (1 β€ b_i β€ 2000).
The fourth line contains a single integer x (1 β€ x β€ 2 β
10^{9}).
Output
If it is possible to choose four integers x_1, x_2, y_1, y_2 such that 1 β€ x_1 β€ x_2 β€ n, 1 β€ y_1 β€ y_2 β€ m, and β_{i=x_1}^{x_2}{β_{j=y_1}^{y_2}{c_{i,j}}} β€ x, output the largest value of (x_2 - x_1 + 1) Γ (y_2 - y_1 + 1) among all such quadruplets, otherwise output 0.
Examples
Input
3 3
1 2 3
1 2 3
9
Output
4
Input
5 1
5 4 2 4 5
2
5
Output
1
Note
Matrix from the first sample and the chosen subrectangle (of blue color):
<image>
Matrix from the second sample and the chosen subrectangle (of blue color):
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2005;
const long long inf = 1e18 + 5;
long long n, m, x;
long long a[maxn], b[maxn];
long long ma[maxn * maxn], mb[maxn * maxn];
void input() {
cin >> n >> m;
for (long long i = 1; i <= n; ++i) {
cin >> a[i];
a[i] += a[i - 1];
ma[i] = inf;
}
for (long long i = 1; i <= m; ++i) {
cin >> b[i];
b[i] += b[i - 1];
mb[i] = inf;
}
cin >> x;
}
void slove() {
for (long long i = 1; i <= n; ++i) {
for (long long j = 0; j < i; ++j) {
ma[i - j] = min(ma[i - j], a[i] - a[j]);
}
}
for (long long i = 1; i <= m; ++i) {
for (long long j = 0; j < i; ++j) {
mb[i - j] = min(mb[i - j], b[i] - b[j]);
}
}
long long ans = 0;
for (long long i = 1; i <= n; ++i) {
for (long long j = 1; j <= m; ++j) {
if (ma[i] * mb[j] <= x) {
ans = max(ans, i * j);
}
}
}
cout << ans << endl;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
input();
slove();
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Once upon a time in the galaxy of far, far away...
Darth Wader found out the location of a rebels' base. Now he is going to destroy the base (and the whole planet that the base is located at), using the Death Star.
When the rebels learnt that the Death Star was coming, they decided to use their new secret weapon β space mines. Let's describe a space mine's build.
Each space mine is shaped like a ball (we'll call it the mine body) of a certain radius r with the center in the point O. Several spikes protrude from the center. Each spike can be represented as a segment, connecting the center of the mine with some point P, such that <image> (transporting long-spiked mines is problematic), where |OP| is the length of the segment connecting O and P. It is convenient to describe the point P by a vector p such that P = O + p.
The Death Star is shaped like a ball with the radius of R (R exceeds any mine's radius). It moves at a constant speed along the v vector at the speed equal to |v|. At the moment the rebels noticed the Star of Death, it was located in the point A.
The rebels located n space mines along the Death Star's way. You may regard the mines as being idle. The Death Star does not know about the mines' existence and cannot notice them, which is why it doesn't change the direction of its movement. As soon as the Star of Death touched the mine (its body or one of the spikes), the mine bursts and destroys the Star of Death. A touching is the situation when there is a point in space which belongs both to the mine and to the Death Star. It is considered that Death Star will not be destroyed if it can move infinitely long time without touching the mines.
Help the rebels determine whether they will succeed in destroying the Death Star using space mines or not. If they will succeed, determine the moment of time when it will happen (starting from the moment the Death Star was noticed).
Input
The first input data line contains 7 integers Ax, Ay, Az, vx, vy, vz, R. They are the Death Star's initial position, the direction of its movement, and its radius ( - 10 β€ vx, vy, vz β€ 10, |v| > 0, 0 < R β€ 100).
The second line contains an integer n, which is the number of mines (1 β€ n β€ 100). Then follow n data blocks, the i-th of them describes the i-th mine.
The first line of each block contains 5 integers Oix, Oiy, Oiz, ri, mi, which are the coordinates of the mine centre, the radius of its body and the number of spikes (0 < ri < 100, 0 β€ mi β€ 10). Then follow mi lines, describing the spikes of the i-th mine, where the j-th of them describes the i-th spike and contains 3 integers pijx, pijy, pijz β the coordinates of the vector where the given spike is directed (<image>).
The coordinates of the mines' centers and the center of the Death Star are integers, their absolute value does not exceed 10000. It is guaranteed that R > ri for any 1 β€ i β€ n. For any mines i β j the following inequality if fulfilled: <image>. Initially the Death Star and the mines do not have common points.
Output
If the rebels will succeed in stopping the Death Star using space mines, print the time from the moment the Death Star was noticed to the blast.
If the Death Star will not touch a mine, print "-1" (without quotes).
For the answer the absolute or relative error of 10 - 6 is acceptable.
Examples
Input
0 0 0 1 0 0 5
2
10 8 0 2 2
0 -3 0
2 2 0
20 0 0 4 3
2 4 0
-4 3 0
1 -5 0
Output
10.0000000000
Input
8 8 4 4 4 2 6
1
-2 -2 -1 3 0
Output
-1
Input
30 30 2 1 2 1 20
3
0 0 40 5 1
1 4 4
-10 -40 -5 7 0
100 200 95 8 1
-10 0 0
Output
74.6757620881
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1000;
const double eps = 1e-8;
const double PI = atan2(0.0, -1.0);
inline double sqr(double x) { return x * x; }
inline bool zero(double x) { return (x > 0 ? x : -x) < eps; }
inline int sgn(double x) { return (x > eps ? 1 : (x + eps < 0 ? -1 : 0)); }
struct point3 {
double x, y, z;
point3(double x, double y, double z) : x(x), y(y), z(z) {}
point3() {}
bool operator==(const point3& a) const {
return sgn(x - a.x) == 0 && sgn(y - a.y) == 0 && sgn(z - a.z) == 0;
}
bool operator!=(const point3& a) const {
return sgn(x - a.x) != 0 || sgn(y - a.y) != 0 || sgn(z - a.z) != 0;
}
bool operator<(const point3& a) const {
return sgn(x - a.x) < 0 || sgn(x - a.x) == 0 && sgn(y - a.y) < 0 ||
sgn(x - a.x) == 0 && sgn(y - a.y) == 0 && sgn(z - a.z) < 0;
}
point3 operator+(const point3& a) const {
return point3(x + a.x, y + a.y, z + a.z);
}
point3 operator-(const point3& a) const {
return point3(x - a.x, y - a.y, z - a.z);
}
point3 operator*(const double& a) const {
return point3(x * a, y * a, z * a);
}
point3 operator/(const double& a) const {
return point3(x / a, y / a, z / a);
}
point3 operator*(const point3& a) const {
return point3(y * a.z - z * a.y, z * a.x - x * a.z, x * a.y - y * a.x);
}
double operator^(const point3& a) const {
return x * a.x + y * a.y + z * a.z;
}
double sqrlen() const { return sqr(x) + sqr(y) + sqr(z); }
double length() const { return sqrt(sqrlen()); }
point3 trunc(double a) const { return (*this) * (a / length()); }
point3 rotate(const point3& a, const point3& b, const point3& c) const {
return point3(a ^ (*this), b ^ (*this), c ^ (*this));
}
};
inline point3 pvec(const point3& a, const point3& b, const point3& c) {
return (a - b) * (b - c);
}
inline bool dotsInline(const point3& a, const point3& b, const point3& c) {
return zero(((a - b) * (b - c)).length());
}
inline bool dotOnlineIn(const point3& p, const point3& l1, const point3& l2) {
return zero(((p - l1) * (p - l2)).length()) &&
(l1.x - p.x) * (l2.x - p.x) < eps &&
(l1.y - p.y) * (l2.y - p.y) < eps && (l1.z - p.z) * (l2.z - p.z) < eps;
}
inline int decideSide(const point3& p1, const point3& p2, const point3& l1,
const point3& l2) {
return sgn(((l1 - l2) * (p1 - l2)) ^ ((l1 - l2) * (p2 - l2)));
}
inline int decideSide(const point3& p1, const point3& p2, const point3& a,
const point3& b, const point3& c) {
return sgn((pvec(a, b, c) ^ (p1 - a)) * (pvec(a, b, c) ^ (p2 - a)));
}
inline bool parallel(const point3& u1, const point3& u2, const point3& v1,
const point3& v2) {
return zero(((u1 - u2) * (v1 - v2)).length());
}
inline bool parallel(const point3& a, const point3& b, const point3& c,
const point3& d, const point3& e, const point3& f) {
return zero((pvec(a, b, c) * pvec(d, e, f)).length());
}
inline bool parallel(const point3& l1, const point3& l2, const point3& a,
const point3& b, const point3& c) {
return zero((l1 - l2) ^ pvec(a, b, c));
}
point3 intersection(const point3& l1, const point3& l2, const point3& a,
const point3& b, const point3& c) {
point3 temp = pvec(a, b, c);
return l1 + (l2 - l1) * ((temp ^ (a - l1)) / (temp ^ (l2 - l1)));
}
void intersection(const point3& a, const point3& b, const point3& c,
const point3& d, const point3& e, const point3& f, point3& p1,
point3& p2) {
p1 = parallel(d, e, a, b, c) ? intersection(e, f, a, b, c)
: intersection(d, e, a, b, c);
p2 = parallel(f, d, a, b, c) ? intersection(e, f, a, b, c)
: intersection(f, d, a, b, c);
}
inline point3 ptoline(const point3& p, const point3& l1, const point3& l2) {
point3 temp = l2 - l1;
return l1 + temp * ((p - l1) ^ temp) / (temp ^ temp);
}
inline point3 ptoplane(const point3& p, const point3& a, const point3& b,
const point3& c) {
return intersection(p, p + pvec(a, b, c), a, b, c);
}
inline double dislinetoline(const point3& u1, const point3& u2,
const point3& v1, const point3& v2) {
point3 temp = (u1 - u2) * (v1 - v2);
return fabs((u1 - v1) ^ temp) / temp.length();
}
void linetoline(const point3& u1, const point3& u2, const point3& v1,
const point3& v2, point3& p1, point3& p2) {
point3 ab = u2 - u1, cd = v2 - v1, ac = v1 - u1;
p2 = v1 + cd * (((ab ^ cd) * (ac ^ ab) - (ab ^ ab) * (ac ^ cd)) /
((ab ^ ab) * (cd ^ cd) - sqr(ab ^ cd)));
p1 = ptoline(p2, u1, u2);
}
const double EPS = 1e-8;
const double INF = 1e6;
double gao(const point3& u, const point3& v, double r) {
double a = (v ^ v);
double b = 2 * (u ^ v);
double c = (u ^ u) - r * r;
double d = b * b - 4 * a * c;
if (d < -EPS) {
return INF;
}
d = sqrt(max(0.0, d));
double t1 = (-b - d) / (2 * a);
double t2 = (-b + d) / (2 * a);
if (t1 > t2) {
swap(t1, t2);
}
if (t1 > -EPS) {
return t1;
} else if (t2 > -EPS) {
return t2;
} else {
return INF;
}
}
double dis(const point3& a, const point3& b, const point3& c) {
if (dotOnlineIn(c, a, b)) {
return 0.0;
} else {
return min((c - a).length(), (c - b).length());
}
}
double gao(point3 a, point3 b, point3 c, point3 d) {
double ret = min(min((c - a).length(), (d - a).length()),
min((c - b).length(), (d - b).length()));
double tmp = dislinetoline(a, b, c, d);
if (parallel(a, b, c, d)) {
c = ptoline(c, a, b);
d = ptoline(d, a, b);
ret = min(ret, hypot(tmp, dis(a, b, c)));
ret = min(ret, hypot(tmp, dis(a, b, d)));
ret = min(ret, hypot(tmp, dis(c, d, a)));
ret = min(ret, hypot(tmp, dis(c, d, b)));
} else {
point3 u, v;
linetoline(a, b, c, d, u, v);
if (dotOnlineIn(u, a, b) && dotOnlineIn(v, c, d)) {
ret = min(ret, dislinetoline(a, b, c, d));
}
u = ptoline(a, c, d);
if (dotOnlineIn(u, c, d)) {
ret = min(ret, (a - u).length());
}
u = ptoline(b, c, d);
if (dotOnlineIn(u, c, d)) {
ret = min(ret, (b - u).length());
}
u = ptoline(c, a, b);
if (dotOnlineIn(u, a, b)) {
ret = min(ret, (c - u).length());
}
u = ptoline(d, a, b);
if (dotOnlineIn(u, a, b)) {
ret = min(ret, (d - u).length());
}
}
return ret;
}
int main() {
int n, m, p;
point3 a[200], b[10000], c[1000], v;
double r[200], lo = 0, up = INF;
scanf("%lf%lf%lf%lf%lf%lf%lf", &a[0].x, &a[0].y, &a[0].z, &v.x, &v.y, &v.z,
&r[0]);
scanf("%d", &n);
m = 0;
for (int i = 1; i <= n; ++i) {
scanf("%lf%lf%lf%lf%d", &a[i].x, &a[i].y, &a[i].z, &r[i], &p);
up = min(up, gao(a[0] - a[i], v, r[0] + r[i]));
for (int j = 0; j < p; ++j) {
scanf("%lf%lf%lf", &c[m].x, &c[m].y, &c[m].z);
b[m] = a[i];
c[m] = b[m] + c[m];
++m;
}
}
for (int tt = 0; tt < 1000; ++tt) {
double mid = (lo + up) / 2;
point3 aa = a[0] + v * mid;
bool flag = true;
for (int i = 0; flag && i < m; ++i) {
if (gao(a[0], aa, b[i], c[i]) <= r[0]) {
flag = false;
}
}
if (flag) {
lo = mid;
} else {
up = mid;
}
}
lo = (lo + up) / 2;
if (lo > INF / 2) {
puts("-1");
} else {
printf("%.10lf\n", lo);
}
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
C*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this (expression is the main term):
* expression ::= summand | expression + summand | expression - summand
* summand ::= increment | coefficient*increment
* increment ::= a++ | ++a
* coefficient ::= 0|1|2|...|1000
For example, "5*a++-3*++a+a++" is a valid expression in C*++.
Thus, we have a sum consisting of several summands divided by signs "+" or "-". Every summand is an expression "a++" or "++a" multiplied by some integer coefficient. If the coefficient is omitted, it is suggested being equal to 1.
The calculation of such sum in C*++ goes the following way. First all the summands are calculated one after another, then they are summed by the usual arithmetic rules. If the summand contains "a++", then during the calculation first the value of the "a" variable is multiplied by the coefficient, then value of "a" is increased by 1. If the summand contains "++a", then the actions on it are performed in the reverse order: first "a" is increased by 1, then β multiplied by the coefficient.
The summands may be calculated in any order, that's why sometimes the result of the calculation is completely unpredictable! Your task is to find its largest possible value.
Input
The first input line contains an integer a ( - 1000 β€ a β€ 1000) β the initial value of the variable "a". The next line contains an expression in C*++ language of the described type. The number of the summands in the expression does not exceed 1000. It is guaranteed that the line describing the expression contains no spaces and tabulation.
Output
Output a single number β the maximal possible value of the expression.
Examples
Input
1
5*a++-3*++a+a++
Output
11
Input
3
a+++++a
Output
8
Note
Consider the second example. Initially a = 3. Suppose that at first the first summand is calculated, and then the second one is. The first summand gets equal to 3, and the value of a is increased by 1. At the calculation of the second summand a is increased once more (gets equal to 5). The value of the second summand is 5, and together they give 8. If we calculate the second summand first and the first summand later, then the both summands equals to 4, and the result is 8, too.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int eprintf(const char *format, ...) { return 0; }
char buf[65536];
int pos;
enum Ty { PREFIX, POSTFIX };
struct Sum {
int k;
Ty ty;
Sum() { k = 0; }
Sum(int _k, Ty _ty) {
k = _k;
ty = _ty;
}
bool operator<(const Sum &b) const {
if (k < b.k) return true;
if (k > b.k) return false;
return !ty < !b.ty;
}
};
Sum parseSum(int sgn) {
bool wasK = false;
int k = 0;
while (buf[pos] >= '0' && buf[pos] <= '9') {
wasK = true;
k = k * 10 + buf[pos] - '0';
pos++;
}
if (wasK)
assert(buf[pos++] == '*');
else
k = 1;
k *= sgn;
if (buf[pos] == 'a') {
pos++;
assert(buf[pos++] == '+');
assert(buf[pos++] == '+');
return Sum(k, POSTFIX);
} else {
assert(buf[pos++] == '+');
assert(buf[pos++] == '+');
assert(buf[pos++] == 'a');
return Sum(k, PREFIX);
}
}
int main() {
int a;
while (scanf("%d%s", &a, buf) >= 2) {
pos = 0;
vector<Sum> expr;
while (buf[pos]) {
int sgn = 1;
if (pos) {
assert(buf[pos] == '+' || buf[pos] == '-');
if (buf[pos] == '-') sgn = -1;
pos++;
}
expr.push_back(parseSum(sgn));
}
sort(expr.begin(), expr.end());
int res = 0;
for (int i = 0; i < expr.size(); i++) {
eprintf("%d (%d)\n", expr[i].k, expr[i].ty);
switch (expr[i].ty) {
case PREFIX:
res += ++a * expr[i].k;
break;
case POSTFIX:
res += a++ * expr[i].k;
break;
}
}
eprintf("---\n");
printf("%d\n", res);
break;
}
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
There are lots of theories concerning the origin of moon craters. Most scientists stick to the meteorite theory, which says that the craters were formed as a result of celestial bodies colliding with the Moon. The other version is that the craters were parts of volcanoes.
An extraterrestrial intelligence research specialist professor Okulov (the namesake of the Okulov, the author of famous textbooks on programming) put forward an alternate hypothesis. Guess what kind of a hypothesis it was ββ sure, the one including extraterrestrial mind involvement. Now the professor is looking for proofs of his hypothesis.
Professor has data from the moon robot that moves linearly in one direction along the Moon surface. The moon craters are circular in form with integer-valued radii. The moon robot records only the craters whose centers lay on his path and sends to the Earth the information on the distance from the centers of the craters to the initial point of its path and on the radii of the craters.
According to the theory of professor Okulov two craters made by an extraterrestrial intelligence for the aims yet unknown either are fully enclosed one in the other or do not intersect at all. Internal or external tangency is acceptable. However the experimental data from the moon robot do not confirm this theory! Nevertheless, professor Okulov is hopeful. He perfectly understands that to create any logical theory one has to ignore some data that are wrong due to faulty measuring (or skillful disguise by the extraterrestrial intelligence that will be sooner or later found by professor Okulov!) Thatβs why Okulov wants to choose among the available crater descriptions the largest set that would satisfy his theory.
Input
The first line has an integer n (1 β€ n β€ 2000) β the number of discovered craters. The next n lines contain crater descriptions in the "ci ri" format, where ci is the coordinate of the center of the crater on the moon robotβs path, ri is the radius of the crater. All the numbers ci and ri are positive integers not exceeding 109. No two craters coincide.
Output
In the first line output the number of craters in the required largest set. In the next line output space-separated numbers of craters that this set consists of. The craters are numbered from 1 to n in the order in which they were given in the input data. The numbers may be output in any order. If the result is not unique, output any.
Examples
Input
4
1 1
2 2
4 1
5 1
Output
3
1 2 4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 2005;
int n, m;
int low[N], high[N];
int id[2 * N][2 * N];
vector<int> v[2 * N];
map<int, int> mp;
int dp[2 * N][2 * N];
vector<int> ansv;
int dfs(int l, int r) {
int i;
if (dp[l][r] != -1) return dp[l][r];
if (l == r) return dp[l][r] = 0;
int cur = 0;
if (id[l][r] != -1) cur = 1;
int ans = cur + dfs(l, r - 1);
for (int i = 0; i < v[r].size(); i++) {
int x = low[v[r][i]];
if (x <= l) continue;
int tmp = cur + dfs(l, x) + dfs(x, r);
ans = max(ans, tmp);
}
return dp[l][r] = ans;
}
void path(int l, int r) {
int i;
if (l == r) return;
int cur = 0;
if (id[l][r] != -1) {
cur = 1;
ansv.push_back(id[l][r]);
}
if (dp[l][r] == cur + dp[l][r - 1]) {
path(l, r - 1);
return;
}
for (int i = 0; i < v[r].size(); i++) {
int x = low[v[r][i]];
if (x <= l) continue;
if (dp[l][r] == cur + dp[l][x] + dp[x][r]) {
path(l, x);
path(x, r);
return;
}
}
}
int main() {
int i, j, c, r;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> c >> r;
low[i] = c - r;
high[i] = c + r;
mp[low[i]] = mp[high[i]] = 0;
}
for (auto itr = mp.begin(); itr != mp.end(); itr++) {
(itr->second) = m;
m++;
}
for (int i = 0; i < n; i++) {
low[i] = mp[low[i]];
high[i] = mp[high[i]];
v[high[i]].push_back(i);
}
for (int i = 0; i < m; i++)
for (int j = 0; j < m; j++) id[i][j] = -1;
for (int i = 0; i < n; i++) id[low[i]][high[i]] = i;
for (int i = 0; i < m; i++)
for (int j = 0; j < m; j++) dp[i][j] = -1;
int ans = dfs(0, m - 1);
cout << ans << endl;
path(0, m - 1);
for (int i = 0; i < ansv.size(); i++) cout << ansv[i] + 1 << ' ';
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Piegirl found the red button. You have one last chance to change the inevitable end.
The circuit under the button consists of n nodes, numbered from 0 to n - 1. In order to deactivate the button, the n nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node i, the next node to be disarmed must be either node (2Β·i) modulo n or node (2Β·i) + 1 modulo n. The last node to be disarmed must be node 0. Node 0 must be disarmed twice, but all other nodes must be disarmed exactly once.
Your task is to find any such order and print it. If there is no such order, print -1.
Input
Input consists of a single integer n (2 β€ n β€ 105).
Output
Print an order in which you can to disarm all nodes. If it is impossible, print -1 instead. If there are multiple orders, print any one of them.
Examples
Input
2
Output
0 1 0
Input
3
Output
-1
Input
4
Output
0 1 3 2 0
Input
16
Output
0 1 2 4 9 3 6 13 10 5 11 7 15 14 12 8 0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <class T>
T abs(T x) {
return x > 0 ? x : -x;
}
int n;
int m;
int q[100001];
int was[100001];
int w[100001];
int p[100001];
int bad = 0;
int go(int x, int y) {
q[y] = x;
if (y + 1 == n && (2 * x) % n == 0) {
for (int i = 0; i <= y; i++) printf("%d ", q[i]);
printf("0\n");
return 1;
}
was[x] = 1;
p[x] = rand() & 1;
int a = (2 * x + p[x]) % n;
int b = (2 * x + 1 - p[x]) % n;
if (!was[a] && go(a, y + 1) || was[a] && !was[b] && go(b, y + 1)) return 1;
if (!was[a] && !was[b] && bad) {
bad--;
if (go(b, y + 1)) return 1;
}
was[x] = 0;
return 0;
}
int main() {
scanf("%d", &n);
if (n & 1)
printf("-1");
else {
do {
bad = 20;
if (go(0, 0)) return 0;
} while (true);
}
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Fennec and Snuke are playing a board game.
On the board, there are N cells numbered 1 through N, and N-1 roads, each connecting two cells. Cell a_i is adjacent to Cell b_i through the i-th road. Every cell can be reached from every other cell by repeatedly traveling to an adjacent cell. In terms of graph theory, the graph formed by the cells and the roads is a tree.
Initially, Cell 1 is painted black, and Cell N is painted white. The other cells are not yet colored. Fennec (who goes first) and Snuke (who goes second) alternately paint an uncolored cell. More specifically, each player performs the following action in her/his turn:
* Fennec: selects an uncolored cell that is adjacent to a black cell, and paints it black.
* Snuke: selects an uncolored cell that is adjacent to a white cell, and paints it white.
A player loses when she/he cannot paint a cell. Determine the winner of the game when Fennec and Snuke play optimally.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq a_i, b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
If Fennec wins, print `Fennec`; if Snuke wins, print `Snuke`.
Examples
Input
7
3 6
1 2
3 1
7 4
5 7
1 4
Output
Fennec
Input
4
1 4
4 2
2 3
Output
Snuke
### Response
```cpp
#include<cstdio>
#include<vector>
using namespace std;
int n, m;
int depth[100010];
int sz[100010];
int parse[100010];
vector<vector<int>> vt;
void dfs(int here, int de)
{
depth[here] = de;
sz[here] = 1;
for (int i = 0; i < vt[here].size(); i++)
{
int next = vt[here][i];
if (!depth[next])
{
parse[next] = here;
dfs(next, de + 1);
sz[here] += sz[next];
}
}
}
int main()
{
scanf("%d", &n);
int sum = n;
vt.resize(n + 1);
for (int i = 0; i < n - 1; i++)
{
int q, w;
scanf("%d %d", &q, &w);
vt[q].push_back(w);
vt[w].push_back(q);
}
dfs(1, 1);
int ch = depth[n]-depth[1] - 1;
int ch1 = 0, ch2 = 0;
ch /= 2;
while (ch--) {
n = parse[n];
}
ch1 = sz[n];
ch2 = sum - sz[n];
if (ch1 >= ch2)
puts("Snuke");
else
puts("Fennec");
}
``` |
### Prompt
Generate a CPP solution to the following problem:
The king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square t. As the king is not in habit of wasting his time, he wants to get from his current position s to square t in the least number of moves. Help him to do this.
<image>
In one move the king can get to the square that has a common side or a common vertex with the square the king is currently in (generally there are 8 different squares he can move to).
Input
The first line contains the chessboard coordinates of square s, the second line β of square t.
Chessboard coordinates consist of two characters, the first one is a lowercase Latin letter (from a to h), the second one is a digit from 1 to 8.
Output
In the first line print n β minimum number of the king's moves. Then in n lines print the moves themselves. Each move is described with one of the 8: L, R, U, D, LU, LD, RU or RD.
L, R, U, D stand respectively for moves left, right, up and down (according to the picture), and 2-letter combinations stand for diagonal moves. If the answer is not unique, print any of them.
Examples
Input
a8
h1
Output
7
RD
RD
RD
RD
RD
RD
RD
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct Move {
int x, y, step;
string mv;
};
int d[8][2] = {-1, 0, 1, 0, 0, -1, 0, 1, -1, -1, -1, 1, 1, 1, 1, -1};
string dirs[8] = {"L\n", "R\n", "D\n", "U\n", "LD\n", "LU\n", "RU\n", "RD\n"};
int main() {
int sx, ex, sy, ey;
string s, e;
cin >> s >> e;
sx = s[0] - 'a';
sy = s[1] - '1';
ex = e[0] - 'a';
ey = e[1] - '1';
int visit[10][10];
memset(visit, 0, sizeof(visit));
Move tmp;
tmp.x = sx, tmp.y = sy, tmp.step = 0, tmp.mv = "";
queue<Move> qu;
qu.push(tmp);
while (!qu.empty()) {
tmp = qu.front();
qu.pop();
if (tmp.x == ex && tmp.y == ey) {
cout << tmp.step << endl;
cout << tmp.mv;
return 0;
}
Move q;
for (int i = 0; i < 8; i++) {
q = tmp;
q.x += d[i][0];
q.y += d[i][1];
if (q.x < 0 || q.y < 0 || q.x > 7 || q.y > 7 || visit[q.x][q.y]) continue;
visit[q.x][q.y] = true;
++q.step;
q.mv += dirs[i];
qu.push(q);
}
}
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Write a program which manipulates a sequence $A$ = {$a_0, a_1, ..., a_{n-1}$} with the following operations:
* $add(s, t, x)$ : add $x$ to $a_s, a_{s+1}, ..., a_t$.
* $find(s, t)$ : report the minimum value in $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 $add(s, t, x)$ and '1' denotes $find(s, t)$.
Output
For each $find$ query, print the minimum value.
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
-2
0
1
-1
### Response
```cpp
#include "bits/stdc++.h"
using namespace std;
long long INF = (1 << 31) - 1;
class LazySegmentTree {
private:
long long Size;
vector<long long> Node, Lazy;
public:
LazySegmentTree(long long N) {
Size = 1;
while (Size < N) Size <<= 1;
Node.assign(Size * 2, 0);
Lazy.assign(Size * 2, 0);
}
void Eval(long long K, long long L, long long R) {
if (Lazy[K] != 0) {
Node[K] += Lazy[K];
if (R - L > 1) {
Lazy[K * 2] += Lazy[K];
Lazy[K * 2 + 1] += Lazy[K];
}
Lazy[K] = 0;
}
}
void Update(long long A, long long B, long long X, long long K, long long L, long long R) {
Eval(K, L, R);
if (B <= L || R <= A) return;
if (A <= L && R <= B) {
Lazy[K] += X;
Eval(K, L, R);
return;
}
Update(A, B, X, K * 2, L, (L + R) / 2);
Update(A, B, X, K * 2 + 1, (L + R) / 2, R);
Node[K] = min(Node[K * 2], Node[K * 2 + 1]);
}
void Update(long long A, long long B, long long X) {
Update(A, B, X, 1, 0, Size);
return;
}
long long Query(long long A, long long B, long long K, long long L, long long R) {
Eval(K, L, R);
if (B <= L || R <= A) return INF;
if (A <= L && R <= B) return Node[K];
return min(Query(A, B, K * 2, L, (L + R) / 2), Query(A, B, K * 2 + 1, (L + R) / 2, R));
}
long long Query(long long A, long long B) {
return Query(A, B, 1, 0, Size);
}
};
int main() {
long long N, Q;
cin >> N >> Q;
LazySegmentTree Seg(N);
for (int i = 0; i < Q; i++) {
long long Mode;
cin >> Mode;
if (Mode == 0) {
long long A, B, X;
cin >> A >> B >> X;
Seg.Update(A, B + 1, X);
}
else {
long long A, B;
cin >> A >> B;
cout << Seg.Query(A, B + 1) << endl;
}
}
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Sherlock Holmes found a mysterious correspondence of two VIPs and made up his mind to read it. But there is a problem! The correspondence turned out to be encrypted. The detective tried really hard to decipher the correspondence, but he couldn't understand anything.
At last, after some thought, he thought of something. Let's say there is a word s, consisting of |s| lowercase Latin letters. Then for one operation you can choose a certain position p (1 β€ p < |s|) and perform one of the following actions:
* either replace letter sp with the one that alphabetically follows it and replace letter sp + 1 with the one that alphabetically precedes it;
* or replace letter sp with the one that alphabetically precedes it and replace letter sp + 1 with the one that alphabetically follows it.
Let us note that letter "z" doesn't have a defined following letter and letter "a" doesn't have a defined preceding letter. That's why the corresponding changes are not acceptable. If the operation requires performing at least one unacceptable change, then such operation cannot be performed.
Two words coincide in their meaning iff one of them can be transformed into the other one as a result of zero or more operations.
Sherlock Holmes needs to learn to quickly determine the following for each word: how many words can exist that coincide in their meaning with the given word, but differs from the given word in at least one character? Count this number for him modulo 1000000007 (109 + 7).
Input
The input data contains several tests. The first line contains the only integer t (1 β€ t β€ 104) β the number of tests.
Next t lines contain the words, one per line. Each word consists of lowercase Latin letters and has length from 1 to 100, inclusive. Lengths of words can differ.
Output
For each word you should print the number of different other words that coincide with it in their meaning β not from the words listed in the input data, but from all possible words. As the sought number can be very large, print its value modulo 1000000007 (109 + 7).
Examples
Input
1
ab
Output
1
Input
1
aaaaaaaaaaa
Output
0
Input
2
ya
klmbfxzb
Output
24
320092793
Note
Some explanations about the operation:
* Note that for each letter, we can clearly define the letter that follows it. Letter "b" alphabetically follows letter "a", letter "c" follows letter "b", ..., "z" follows letter "y".
* Preceding letters are defined in the similar manner: letter "y" precedes letter "z", ..., "a" precedes letter "b".
* Note that the operation never changes a word's length.
In the first sample you can obtain the only other word "ba". In the second sample you cannot obtain any other word, so the correct answer is 0.
Consider the third sample. One operation can transform word "klmbfxzb" into word "klmcexzb": we should choose p = 4, and replace the fourth letter with the following one ("b" β "c"), and the fifth one β with the preceding one ("f" β "e"). Also, we can obtain many other words from this one. An operation can transform word "ya" only into one other word "xb".
Word "ya" coincides in its meaning with words "xb", "wc", "vd", ..., "ay" (overall there are 24 other words). The word "klmbfxzb has many more variants β there are 3320092814 other words that coincide with in the meaning. So the answer for the first word equals 24 and for the second one equals 320092793 β the number 3320092814 modulo 109 + 7
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
int dp[105][2700];
int t;
string s;
void solve() {
dp[0][0] = 1;
for (int i = 0; i < 101; i++)
for (int j = 0; j <= 25 * i; j++) {
for (int k = 0; k < 26; k++) {
dp[i + 1][j + k] += dp[i][j];
dp[i + 1][j + k] %= MOD;
}
}
}
int main() {
solve();
cin >> t;
while (t--) {
cin >> s;
int sum = 0;
for (int i = 0; i < s.size(); i++) sum += s[i] - 'a';
cout << dp[s.size()][sum] - 1 << endl;
}
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the winner is the photo that gets this number first.
Help guys determine the winner photo by the records of likes.
Input
The first line of the input contains a single integer n (1 β€ n β€ 1000) β the total likes to the published photoes.
The second line contains n positive integers a1, a2, ..., an (1 β€ ai β€ 1 000 000), where ai is the identifier of the photo which got the i-th like.
Output
Print the identifier of the photo which won the elections.
Examples
Input
5
1 3 2 2 1
Output
2
Input
9
100 200 300 200 100 300 300 100 200
Output
300
Note
In the first test sample the photo with id 1 got two likes (first and fifth), photo with id 2 got two likes (third and fourth), and photo with id 3 got one like (second).
Thus, the winner is the photo with identifier 2, as it got:
* more likes than the photo with id 3;
* as many likes as the photo with id 1, but the photo with the identifier 2 got its second like earlier.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1005;
int n, a, ans;
int b[1000005];
int main() {
cin >> n;
for (int i = 1; i <= n; ++i) {
int a;
cin >> a;
b[a]++;
if (b[a] > b[ans]) ans = a;
}
cout << ans << endl;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly n characters.
<image>
Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested that the i-th letter of her name should be 'O' (uppercase) if i is a member of Fibonacci sequence, and 'o' (lowercase) otherwise. The letters in the name are numbered from 1 to n. Fibonacci sequence is the sequence f where
* f1 = 1,
* f2 = 1,
* fn = fn - 2 + fn - 1 (n > 2).
As her friends are too young to know what Fibonacci sequence is, they asked you to help Eleven determine her new name.
Input
The first and only line of input contains an integer n (1 β€ n β€ 1000).
Output
Print Eleven's new name on the first and only line of output.
Examples
Input
8
Output
OOOoOooO
Input
15
Output
OOOoOooOooooOoo
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int check(int k, int a[10000], int n) {
for (int i = 1; i <= n + 1; i++) {
if (k == a[i]) return 1;
}
return 0;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, c = 0;
cin >> n;
int a[n + 1];
a[1] = 1;
a[2] = 1;
for (int i = 3; i <= n + 1; i++) {
a[i] = a[i - 1] + a[i - 2];
}
for (int i = 1; i <= n; i++) {
if (check(i, a, n) == 1)
cout << "O";
else
cout << "o";
}
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Takahashi is participating in a programming contest called AXC002, and he has just submitted his code to Problem A.
The problem has N test cases.
For each test case i (1\leq i \leq N), you are given a string S_i representing the verdict for that test case. Find the numbers of test cases for which the verdict is `AC`, `WA`, `TLE`, and `RE`, respectively.
See the Output section for the output format.
Constraints
* 1 \leq N \leq 10^5
* S_i is `AC`, `WA`, `TLE`, or `RE`.
Input
Input is given from Standard Input in the following format:
N
S_1
\vdots
S_N
Output
Let C_0, C_1, C_2, and C_3 be the numbers of test cases for which the verdict is `AC`, `WA`, `TLE`, and `RE`, respectively. Print the following:
AC x C_0
WA x C_1
TLE x C_2
RE x C_3
Output
Let C_0, C_1, C_2, and C_3 be the numbers of test cases for which the verdict is `AC`, `WA`, `TLE`, and `RE`, respectively. Print the following:
AC x C_0
WA x C_1
TLE x C_2
RE x C_3
Examples
Input
6
AC
TLE
AC
AC
WA
TLE
Output
AC x 3
WA x 1
TLE x 2
RE x 0
Input
10
AC
AC
AC
AC
AC
AC
AC
AC
AC
AC
Output
AC x 10
WA x 0
TLE x 0
RE x 0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin>>n;
string s;
map <string,int> mp;
while(n--)
{
cin>>s;
mp[s]++;
}
cout<<"AC x "<<mp["AC"]<<endl;
cout<<"WA x "<<mp["WA"]<<endl;
cout<<"TLE x "<<mp["TLE"]<<endl;
cout<<"RE x "<<mp["RE"]<<endl;
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly H centimeters above the water surface. Inessa grabbed the flower and sailed the distance of L centimeters. Exactly at this point the flower touched the water surface.
<image>
Suppose that the lily grows at some point A on the lake bottom, and its stem is always a straight segment with one endpoint at point A. Also suppose that initially the flower was exactly above the point A, i.e. its stem was vertical. Can you determine the depth of the lake at point A?
Input
The only line contains two integers H and L (1 β€ H < L β€ 10^{6}).
Output
Print a single number β the depth of the lake at point A. The absolute or relative error should not exceed 10^{-6}.
Formally, let your answer be A, and the jury's answer be B. Your answer is accepted if and only if \frac{|A - B|}{max{(1, |B|)}} β€ 10^{-6}.
Examples
Input
1 2
Output
1.5000000000000
Input
3 5
Output
2.6666666666667
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
double H, L;
cin >> H >> L;
cout.precision(13);
cout << fixed << (L * L - H * H) / (2 * H);
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Lenny had an n Γ m matrix of positive integers. He loved the matrix so much, because each row of the matrix was sorted in non-decreasing order. For the same reason he calls such matrices of integers lovely.
One day when Lenny was at school his little brother was playing with Lenny's matrix in his room. He erased some of the entries of the matrix and changed the order of some of its columns. When Lenny got back home he was very upset. Now Lenny wants to recover his matrix.
Help him to find an order for the columns of the matrix so that it's possible to fill in the erased entries of the matrix to achieve a lovely matrix again. Note, that you can fill the erased entries of the matrix with any integers.
Input
The first line of the input contains two positive integers n and m (1 β€ nΒ·m β€ 105). Each of the next n lines contains m space-separated integers representing the matrix. An integer -1 shows an erased entry of the matrix. All other integers (each of them is between 0 and 109 inclusive) represent filled entries.
Output
If there exists no possible reordering of the columns print -1. Otherwise the output should contain m integers p1, p2, ..., pm showing the sought permutation of columns. So, the first column of the lovely matrix will be p1-th column of the initial matrix, the second column of the lovely matrix will be p2-th column of the initial matrix and so on.
Examples
Input
3 3
1 -1 -1
1 2 1
2 -1 1
Output
3 1 2
Input
2 3
1 2 2
2 5 4
Output
1 3 2
Input
2 3
1 2 3
3 2 1
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
const int MAXM = 200005;
int n, m, deg[MAXM];
vector<int> a[MAXN], G[MAXM];
int main() {
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++) {
a[i].resize(m);
for (int j = 0; j < m; j++) scanf("%d", &a[i][j]);
}
int s = m;
for (int i = 0; i < n; i++) {
vector<pair<int, int> > p;
for (int j = 0; j < m; j++)
if (a[i][j] != -1) p.push_back({a[i][j], j});
sort(p.begin(), p.end());
for (int i = 0; i < p.size();) {
int j = i + 1;
while (j < p.size() && p[j].first == p[i].first) j++;
int k = j + 1;
while (k < p.size() && p[k].first == p[j].first) k++;
if (j < p.size()) {
for (int z = i; z < j; z++) {
G[p[z].second].push_back(s);
deg[s]++;
}
for (int z = j; z < k; z++) {
G[s].push_back(p[z].second);
deg[p[z].second]++;
}
s++;
i = j;
} else
break;
}
}
queue<int> q;
for (int i = 0; i < s; i++)
if (deg[i] == 0) q.push(i);
vector<int> p;
while (!q.empty()) {
int u = q.front();
q.pop();
if (u < m) p.push_back(u);
for (int v : G[u]) {
deg[v]--;
if (deg[v] == 0) q.push(v);
}
}
if (p.size() < m)
printf("-1\n");
else {
for (int i = 0; i < p.size(); i++) {
if (i > 0) printf(" ");
printf("%d", p[i] + 1);
}
printf("\n");
}
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows.
1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used.
2. Extract a vertex v from the head of the queue q.
3. Print the index of vertex v.
4. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q.
5. If the queue is not empty, continue from step 2.
6. Otherwise finish.
Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print.
In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The [tree](http://gg.gg/tree_en) is an undirected graph, such that there is exactly one simple path between any two vertices.
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) which denotes the number of nodes in the tree.
The following n - 1 lines describe the edges of the tree. Each of them contains two integers x and y (1 β€ x, y β€ n) β the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree.
The last line contains n distinct integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n) β the sequence to check.
Output
Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
4
1 2
1 3
2 4
1 2 3 4
Output
Yes
Input
4
1 2
1 3
2 4
1 2 4 3
Output
No
Note
Both sample tests have the same tree in them.
In this tree, there are two valid BFS orderings:
* 1, 2, 3, 4,
* 1, 3, 2, 4.
The ordering 1, 2, 4, 3 doesn't correspond to any valid BFS order.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int n;
long long int a[200005];
vector<long long int> adj[200005];
set<long long int> nei[200005];
queue<long long int> q;
bool vis[200005];
void dfs(long long int i, long long int p) {
for (auto j : adj[i])
if (j != p) {
nei[i].insert(j);
dfs(j, i);
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 1; i < n; i++) {
long long int x, y;
cin >> x >> y;
adj[x].push_back(y), adj[y].push_back(x);
}
dfs(1, 1);
for (int i = 1; i <= n; i++) cin >> a[i];
if (a[1] != 1) return cout << "No" << '\n', 0;
q.push(1);
long long int cur = 2;
vis[1] = 1;
while (q.size()) {
long long int i = q.front();
q.pop();
for (int j = 1; j < adj[i].size() + (i == 1); j++) {
if (nei[i].find(a[cur]) == nei[i].end()) return cout << "No" << '\n', 0;
vis[a[cur]] = 1;
q.push(a[cur]);
cur++;
}
}
cout << "Yes" << '\n';
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.
There are n different topics, numbered from 1 to n sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most n - 1 neighbors.
For example, if already written neighbors of the current blog have topics number 1, 3, 1, 5, and 2, Johnny will choose the topic number 4 for the current blog, because topics number 1, 2 and 3 are already covered by neighbors and topic number 4 isn't covered.
As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
Input
The first line contains two integers n (1 β€ n β€ 5 β
10^5) and m (0 β€ m β€ 5 β
10^5) β the number of blogs and references, respectively.
Each of the following m lines contains two integers a and b (a β b; 1 β€ a, b β€ n), which mean that there is a reference between blogs a and b. It's guaranteed that the graph doesn't contain multiple edges.
The last line contains n integers t_1, t_2, β¦, t_n, i-th of them denotes desired topic number of the i-th blog (1 β€ t_i β€ n).
Output
If the solution does not exist, then write -1. Otherwise, output n distinct integers p_1, p_2, β¦, p_n (1 β€ p_i β€ n), which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.
Examples
Input
3 3
1 2
2 3
3 1
2 1 3
Output
2 1 3
Input
3 3
1 2
2 3
3 1
1 1 1
Output
-1
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
Output
2 5 1 3 4
Note
In the first example, Johnny starts with writing blog number 2, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number 1, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number 3, it has references to blogs number 1 and 2 so it receives the third topic.
Second example: There does not exist any permutation fulfilling given conditions.
Third example: First Johnny writes blog 2, it receives the topic 1. Then he writes blog 5, it receives the topic 1 too because it doesn't have reference to single already written blog 2. Then he writes blog number 1, it has reference to blog number 2 with topic 1, so it receives the topic 2. Then he writes blog number 3 which has reference to blog 2, so it receives the topic 2. Then he ends with writing blog number 4 which has reference to blog 5 and receives the topic 2.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<int> g[n];
vector<pair<int, int>> top;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
a--;
b--;
g[a].push_back(b);
g[b].push_back(a);
}
int val[n];
for (int i = 0; i < n; i++) {
int a;
cin >> a;
val[i] = -1;
top.push_back({a, i});
}
sort(top.begin(), top.end());
for (int i = 0; i < n; i++) {
int idx = top[i].first;
int a = top[i].second;
bool mark[idx];
for (int i = 0; i < idx; i++) {
mark[i] = 0;
}
for (int j = 0; j < g[a].size(); j++) {
if (val[g[a][j]] == idx) {
cout << -1;
return 0;
}
if (val[g[a][j]] > 0) mark[val[g[a][j]]] = 1;
}
for (int i = 1; i < idx; i++) {
if (!mark[i]) {
cout << -1;
return 0;
}
}
val[a] = idx;
}
for (int i = 0; i < n; i++) {
cout << top[i].second + 1 << " ";
}
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
We often go to supermarkets to buy some fruits or vegetables, and on the tag there prints the price for a kilo. But in some supermarkets, when asked how much the items are, the clerk will say that a yuan for b kilos (You don't need to care about what "yuan" is), the same as a/b yuan for a kilo.
Now imagine you'd like to buy m kilos of apples. You've asked n supermarkets and got the prices. Find the minimum cost for those apples.
You can assume that there are enough apples in all supermarkets.
Input
The first line contains two positive integers n and m (1 β€ n β€ 5 000, 1 β€ m β€ 100), denoting that there are n supermarkets and you want to buy m kilos of apples.
The following n lines describe the information of the supermarkets. Each line contains two positive integers a, b (1 β€ a, b β€ 100), denoting that in this supermarket, you are supposed to pay a yuan for b kilos of apples.
Output
The only line, denoting the minimum cost for m kilos of apples. Please make sure that the absolute or relative error between your answer and the correct answer won't exceed 10^{-6}.
Formally, let your answer be x, and the jury's answer be y. Your answer is considered correct if \frac{|x - y|}{max{(1, |y|)}} β€ 10^{-6}.
Examples
Input
3 5
1 2
3 4
1 3
Output
1.66666667
Input
2 1
99 100
98 99
Output
0.98989899
Note
In the first sample, you are supposed to buy 5 kilos of apples in supermarket 3. The cost is 5/3 yuan.
In the second sample, you are supposed to buy 1 kilo of apples in supermarket 2. The cost is 98/99 yuan.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
double n, m, mn = 101;
cin >> n >> m;
for (int i = 0; i < n; i++) {
double a, b;
cin >> a >> b;
double c = a / b;
mn = min(mn, c);
}
printf("%.8f\n", (m * mn) * 1.00);
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l β€ r).
He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].
The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj β€ x β€ rj.
Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k.
Input
The first line contains two integers n and k (1 β€ n, k β€ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 β€ li β€ ri β€ 105), separated by a space.
It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 β€ i < j β€ n) the following inequality holds, min(ri, rj) < max(li, lj).
Output
In a single line print a single integer β the answer to the problem.
Examples
Input
2 3
1 2
3 4
Output
2
Input
3 7
1 2
3 3
4 7
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long s = 0, n, k, x, y;
cin >> n >> k;
for (int i = 1; i <= n; i++) {
cin >> x >> y;
s += y - x + 1;
}
long long h = k - (s % k);
if (h == k) h = 0;
cout << h;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Problem
Chocolate company Chinor Choco has decided to build n new stores.
For each store, ask each store manager to prepare two candidates for the place you want to build, and build it in either place.
Chinor Choco sells m types of chocolate, each manufactured at a different factory.
All types of chocolate are sold at all stores.
Chinor Choco owns only one truck to transport chocolate, and one truck can only carry one store's worth of chocolate.
Therefore, trucks need to go around all factories when moving from one store to another.
Find the maximum travel distance when the stores are arranged so that the maximum minimum travel distance when moving from one store to another is the minimum.
There can be multiple stores and factories in the same location.
Constraints
The input satisfies the following conditions.
* 2 β€ n β€ 200
* 1 β€ m β€ 15
* 0 β€ ai, bi, ci, di, xi, yi β€ 1000
Input
The input is given in the following format.
n m
a0 b0 c0 d0
...
anβ1 bnβ1 cnβ1 dnβ1
x0 y0
...
xmβ1 ymβ1
All inputs are given as integers.
On the first line, the number of Chinor chocolate shops n and the number of chocolate manufacturing factories m are given, separated by blanks.
From the second line to the nth line, the coordinates (ai, bi), (ci, di) of the candidate places to build each store are given separated by blanks.
2 & plus; Factory coordinates (xi, yi) are given from the nth line to the mth line, separated by blanks.
Output
Output the maximum travel distance when the store is arranged so that the maximum of the minimum travel distance is minimized.
The error should not exceed 10-6.
Examples
Input
2 1
0 0 5 5
3 3 6 6
2 2
Output
4.2426406871
Input
2 2
0 0 6 0
7 0 3 0
4 0
5 0
Output
3.0000000000
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
struct StronglyConnectedComponents
{
vector< vector< int > > gg, rg;
vector< pair< int, int > > edges;
vector< int > comp, order, used;
StronglyConnectedComponents(size_t v) : gg(v), rg(v), comp(v, -1), used(v, 0) {}
void add_edge(int x, int y)
{
gg[x].push_back(y);
rg[y].push_back(x);
edges.emplace_back(x, y);
}
int operator[](int k)
{
return (comp[k]);
}
void dfs(int idx)
{
if(used[idx]) return;
used[idx] = true;
for(int to : gg[idx]) dfs(to);
order.push_back(idx);
}
void rdfs(int idx, int cnt)
{
if(comp[idx] != -1) return;
comp[idx] = cnt;
for(int to : rg[idx]) rdfs(to, cnt);
}
void build(vector< vector< int > > &t)
{
for(int i = 0; i < gg.size(); i++) dfs(i);
reverse(begin(order), end(order));
int ptr = 0;
for(int i : order) if(comp[i] == -1) rdfs(i, ptr), ptr++;
t.resize(ptr);
set< pair< int, int > > connect;
for(auto &e : edges) {
int x = comp[e.first], y = comp[e.second];
if(x == y) continue;
if(connect.count({x, y})) continue;
t[x].push_back(y);
connect.emplace(x, y);
}
}
};
int N, M;
int A[200][2], B[200][2];
int X[15], Y[15];
double g[200][2][200][2];
int main()
{
cin >> N >> M;
for(int i = 0; i < N; i++) {
for(int j = 0; j < 2; j++) {
cin >> A[i][j] >> B[i][j];
}
}
for(int i = 0; i < M; i++) {
cin >> X[i] >> Y[i];
}
fill_n(***g, 200 * 2 * 200 * 2, 1e9);
for(int i = 0; i < M; i++) {
vector< vector< double > > dp(M, vector< double >(1 << M, 1e9));
dp[i][1 << i] = 0.0;
for(int j = 0; j < (1 << M); j++) {
for(int k = 0; k < M; k++) {
for(int l = 0; l < M; l++) {
dp[l][j | (1 << l)] = min(dp[l][j | (1 << l)], dp[k][j] + sqrt(pow(X[k] - X[l], 2) + pow(Y[k] - Y[l], 2)));
}
}
}
for(int z = 0; z < M; z++) {
for(int j = 0; j < N; j++) {
for(int k = 0; k < 2; k++) {
for(int l = 0; l < N; l++) {
for(int m = 0; m < 2; m++) {
double latte = sqrt(pow(A[j][k] - X[i], 2) + pow(B[j][k] - Y[i], 2));
double malta = sqrt(pow(A[l][m] - X[z], 2) + pow(B[l][m] - Y[z], 2));
g[j][k][l][m] = min(g[j][k][l][m], latte + malta + dp[z].back());
}
}
}
}
}
}
auto check = [&](double dist)
{
StronglyConnectedComponents scc(N + N);
for(int i = 0; i < N; i++) {
for(int j = i + 1; j < N; j++) {
bool b1 = g[i][0][j][0] > dist;
bool b2 = g[i][0][j][1] > dist;
bool b3 = g[i][1][j][0] > dist;
bool b4 = g[i][1][j][1] > dist;
if(b1) scc.add_edge(i << 1, (j << 1) | 1), scc.add_edge(j << 1, (i << 1) | 1);
if(b2) scc.add_edge(i << 1, j << 1), scc.add_edge((j << 1) | 1, (i << 1) | 1);
if(b3) scc.add_edge((i << 1) | 1, (j << 1) | 1), scc.add_edge(j << 1, i << 1);
if(b4) scc.add_edge((i << 1) | 1, j << 1), scc.add_edge((j << 1) | 1, i << 1);
}
}
vector< vector< int > > g;
scc.build(g);
for(int i = 0; i < N; i += 2) if(scc[i] == scc[i + 1]) return (false);
return (true);
};
double low = 0, high = 1e6;
for(int i = 0; i < 40; i++) {
double mid = (low + high) * 0.5;
if(check(mid)) high = mid;
else low = mid;
}
cout << fixed << setprecision(10) << high << endl;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
Input
The first line contains two integers a, b (1 β€ a, b β€ 1000), separated by a single space.
Output
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
Examples
Input
1 1
Output
NO
Input
5 5
Output
YES
2 1
5 5
-2 4
Input
5 10
Output
YES
-10 4
-2 -2
1 2
### Response
```cpp
#include <bits/stdc++.h>
#pragma hdrstop
#pragma argsused
using namespace std;
int main(int argc, char* argv[]) {
int a, b;
cin >> a >> b;
vector<pair<int, int> > spli_a;
vector<pair<int, int> > spli_b;
int sqa = a * a;
int sqb = b * b;
map<int, int> squarez;
for (int i = 1; i < 2000; ++i) {
squarez[i * i] = i;
}
for (int i = 1; i * i < sqa; ++i) {
int ii = i * i;
int dsq = sqa - ii;
if (squarez.count(dsq) > 0) {
spli_a.push_back(make_pair(i, squarez[dsq]));
spli_a.push_back(make_pair(squarez[dsq], i));
}
}
for (int i = 1; i * i < sqb; ++i) {
int ii = i * i;
int dsq = sqb - ii;
if (squarez.count(dsq) > 0) {
spli_b.push_back(make_pair(i, squarez[dsq]));
spli_b.push_back(make_pair(squarez[dsq], i));
}
}
for (int i = 0; i < spli_a.size(); ++i) {
for (int j = 0; j < spli_b.size(); ++j) {
if (spli_a[i].first != spli_b[j].first) {
int vx1 = spli_a[i].first, vy1 = -spli_a[i].second;
int vx2 = spli_b[j].first, vy2 = spli_b[j].second;
if (0 == vx1 * vx2 + vy1 * vy2) {
cout << "YES" << endl;
cout << 0 << " " << 0 << endl;
cout << vx1 << " " << vy1 << endl;
cout << vx2 << " " << vy2 << endl;
return 0;
}
}
}
}
cout << "NO" << endl;
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Let us call a pair of integer numbers m-perfect, if at least one number in the pair is greater than or equal to m. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not.
Two integers x, y are written on the blackboard. It is allowed to erase one of them and replace it with the sum of the numbers, (x + y).
What is the minimum number of such operations one has to perform in order to make the given pair of integers m-perfect?
Input
Single line of the input contains three integers x, y and m ( - 1018 β€ x, y, m β€ 1018).
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preffered to use the cin, cout streams or the %I64d specifier.
Output
Print the minimum number of operations or "-1" (without quotes), if it is impossible to transform the given pair to the m-perfect one.
Examples
Input
1 2 5
Output
2
Input
-1 4 15
Output
4
Input
0 -1 5
Output
-1
Note
In the first sample the following sequence of operations is suitable: (1, 2) <image> (3, 2) <image> (5, 2).
In the second sample: (-1, 4) <image> (3, 4) <image> (7, 4) <image> (11, 4) <image> (15, 4).
Finally, in the third sample x, y cannot be made positive, hence there is no proper sequence of operations.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long x, y, m;
long long ans;
cin >> x >> y >> m;
ans = 0;
if (x > y) swap(x, y);
if (m <= y)
cout << ans << endl;
else if (x + y <= x)
cout << -1 << endl;
else {
if (x < 0 && y > 0) {
ans = -x / y + 1;
x += y * ans;
}
if (x > y) swap(x, y);
while (m > y) {
long long t = x + y;
x = y;
y = t;
ans++;
}
cout << ans << endl;
}
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
Niwango created a playlist of N songs. The title and the duration of the i-th song are s_i and t_i seconds, respectively. It is guaranteed that s_1,\ldots,s_N are all distinct.
Niwango was doing some work while playing this playlist. (That is, all the songs were played once, in the order they appear in the playlist, without any pause in between.) However, he fell asleep during his work, and he woke up after all the songs were played. According to his record, it turned out that he fell asleep at the very end of the song titled X.
Find the duration of time when some song was played while Niwango was asleep.
Constraints
* 1 \leq N \leq 50
* s_i and X are strings of length between 1 and 100 (inclusive) consisting of lowercase English letters.
* s_1,\ldots,s_N are distinct.
* There exists an integer i such that s_i = X.
* 1 \leq t_i \leq 1000
* t_i is an integer.
Input
Input is given from Standard Input in the following format:
N
s_1 t_1
\vdots
s_{N} t_N
X
Output
Print the answer.
Examples
Input
3
dwango 2
sixth 5
prelims 25
dwango
Output
30
Input
1
abcde 1000
abcde
Output
0
Input
15
ypnxn 279
kgjgwx 464
qquhuwq 327
rxing 549
pmuduhznoaqu 832
dagktgdarveusju 595
wunfagppcoi 200
dhavrncwfw 720
jpcmigg 658
wrczqxycivdqn 639
mcmkkbnjfeod 992
htqvkgkbhtytsz 130
twflegsjz 467
dswxxrxuzzfhkp 989
szfwtzfpnscgue 958
pmuduhznoaqu
Output
6348
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin >>N;
string s[N+1];
int t[N+1];
for(int i=1;i<=N;i++){
cin >>s[i]>>t[i];
}
string X;
cin >>X;
int c,d;
c=0;
d=0;
for(int i=1;i<=N;i++){
c=c+d*t[i];
if(X==s[i]){
d=1;
}
}
cout <<c<<endl;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling the cubes downwards. When Chris switches the gravity, it begins to pull all the cubes to the right side of the box. The figure shows the initial and final configurations of the cubes in the box: the cubes that have changed their position are highlighted with orange.
<image>
Given the initial configuration of the toy cubes in the box, find the amounts of cubes in each of the n columns after the gravity switch!
Input
The first line of input contains an integer n (1 β€ n β€ 100), the number of the columns in the box. The next line contains n space-separated integer numbers. The i-th number ai (1 β€ ai β€ 100) denotes the number of cubes in the i-th column.
Output
Output n integer numbers separated by spaces, where the i-th number is the amount of cubes in the i-th column after the gravity switch.
Examples
Input
4
3 2 1 2
Output
1 2 2 3
Input
3
2 3 8
Output
2 3 8
Note
The first example case is shown on the figure. The top cube of the first column falls to the top of the last column; the top cube of the second column falls to the top of the third column; the middle cube of the first column falls to the top of the second column.
In the second example case the gravity switch does not change the heights of the columns.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
sort(a, a + n);
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Artsem is on vacation and wants to buy souvenirs for his two teammates. There are n souvenir shops along the street. In i-th shop Artsem can buy one souvenir for ai dollars, and he cannot buy more than one souvenir in one shop. He doesn't want to introduce envy in his team, so he wants to buy two souvenirs with least possible difference in price.
Artsem has visited the shopping street m times. For some strange reason on the i-th day only shops with numbers from li to ri were operating (weird? yes it is, but have you ever tried to come up with a reasonable legend for a range query problem?). For each visit, Artsem wants to know the minimum possible difference in prices of two different souvenirs he can buy in the opened shops.
In other words, for each Artsem's visit you should find the minimum possible value of |as - at| where li β€ s, t β€ ri, s β t.
Input
The first line contains an integer n (2 β€ n β€ 105).
The second line contains n space-separated integers a1, ..., an (0 β€ ai β€ 109).
The third line contains the number of queries m (1 β€ m β€ 3Β·105).
Next m lines describe the queries. i-th of these lines contains two space-separated integers li and ri denoting the range of shops working on i-th day (1 β€ li < ri β€ n).
Output
Print the answer to each query in a separate line.
Example
Input
8
3 1 4 1 5 9 2 6
4
1 8
1 3
4 8
5 7
Output
0
1
1
3
### Response
```cpp
#include <bits/stdc++.h>
clock_t t = clock();
namespace my_std {
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template <typename T>
inline T rnd(T l, T r) {
return uniform_int_distribution<T>(l, r)(rng);
}
template <typename T>
inline bool chkmax(T &x, T y) {
return x < y ? x = y, 1 : 0;
}
template <typename T>
inline bool chkmin(T &x, T y) {
return x > y ? x = y, 1 : 0;
}
template <typename T>
inline void read(T &t) {
t = 0;
char f = 0, ch = getchar();
double d = 0.1;
while (ch > '9' || ch < '0') f |= (ch == '-'), ch = getchar();
while (ch <= '9' && ch >= '0') t = t * 10 + ch - 48, ch = getchar();
if (ch == '.') {
ch = getchar();
while (ch <= '9' && ch >= '0') t += d * (ch ^ 48), d *= 0.1, ch = getchar();
}
t = (f ? -t : t);
}
template <typename T, typename... Args>
inline void read(T &t, Args &...args) {
read(t);
read(args...);
}
char sr[1 << 21], z[20];
int C = -1, Z = 0;
inline void Ot() { fwrite(sr, 1, C + 1, stdout), C = -1; }
inline void print(register int x) {
if (C > 1 << 20) Ot();
if (x < 0) sr[++C] = '-', x = -x;
while (z[++Z] = x % 10 + 48, x /= 10)
;
while (sr[++C] = z[Z], --Z)
;
sr[++C] = '\n';
}
void file() {}
inline void chktime() {}
long long ksm(long long x, int y) {
long long ret = 1;
for (; y; y >>= 1, x = x * x)
if (y & 1) ret = ret * x;
return ret;
}
} // namespace my_std
using namespace my_std;
int n, m;
pair<int, int> a[402200];
int aa[402200];
int pre[402200], suf[402200];
void add(int p) { suf[pre[p]] = pre[suf[p]] = p; }
void del(int p) {
suf[pre[p]] = suf[p];
pre[suf[p]] = pre[p];
}
int Ans[402200];
int pos[402200], blo, num;
void init() {
blo = sqrt(n);
for (int i = (1); i <= (n); i++) pos[i] = (i - 1) / blo + 1;
num = pos[n];
}
struct hh {
int l, r, id;
} q[402200];
inline bool cmp(const hh &x, const hh &y) {
return pos[x.l] == pos[y.l] ? x.r < y.r : pos[x.l] < pos[y.l];
}
int Lans[402200];
int update(int x) {
int ret = 1e9;
if (pre[x]) chkmin(ret, aa[x] - aa[pre[x]]);
if (suf[x] != n + 1) chkmin(ret, aa[suf[x]] - aa[x]);
return ret;
}
int main() {
file();
read(n);
for (int i = (1); i <= (n); i++)
read(a[i].first), a[i].second = i, aa[i] = a[i].first;
sort(a + 1, a + n + 1);
read(m);
init();
int x, y;
for (int i = (1); i <= (m); i++) read(x, y), q[i] = (hh){x, y, i};
sort(q + 1, q + m + 1, cmp);
int p = 1;
for (int _ = (1); _ <= (num); _++) {
int L = (_ - 1) * blo + 1, R = min(_ * blo, n), posR = R;
for (int i = (1); i <= (n); i++) Lans[i] = 1e9;
int lst = 0;
for (int i = (0); i <= (n + 1); i++) pre[i] = suf[i] = 0;
for (int i = (1); i <= (n); i++)
suf[lst] = a[i].second, pre[a[i].second] = lst, lst = a[i].second;
pre[suf[lst] = n + 1] = lst;
for (int i = (1); i <= (R); i++) del(i);
for (int i = (n); i >= (R + 1); i--) del(i);
for (int i = (R + 1); i <= (n); i++)
add(i), Lans[i] = min(Lans[i - 1], update(i));
for (int i = (R); i >= (L); i--) add(i);
for (int i = (n); i >= (R + 1); i--) del(i);
for (; p <= m && pos[q[p].l] == _; p++) {
int ans = 1e9;
if (q[p].r <= R) {
for (int i = (L); i <= (q[p].l - 1); i++) del(i);
for (int i = (R); i >= (q[p].l); i--) del(i);
for (int i = (q[p].l); i <= (q[p].r); i++)
add(i), chkmin(ans, update(i));
for (int i = (q[p].r); i <= (R); i++) add(i);
for (int i = (q[p].l - 1); i >= (L); i--) add(i);
Ans[q[p].id] = ans;
} else {
while (posR < q[p].r) ++posR, add(posR);
for (int i = (L); i <= (R); i++) del(i);
for (int i = (R); i >= (q[p].l); i--) add(i), chkmin(ans, update(i));
for (int i = (q[p].l - 1); i >= (L); i--) add(i);
Ans[q[p].id] = min(ans, Lans[posR]);
}
}
}
for (int i = (1); i <= (m); i++) printf("%d\n", Ans[i]);
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
There are n bears in the inn and p places to sleep. Bears will party together for some number of nights (and days).
Bears love drinking juice. They don't like wine but they can't distinguish it from juice by taste or smell.
A bear doesn't sleep unless he drinks wine. A bear must go to sleep a few hours after drinking a wine. He will wake up many days after the party is over.
Radewoosh is the owner of the inn. He wants to put some number of barrels in front of bears. One barrel will contain wine and all other ones will contain juice. Radewoosh will challenge bears to find a barrel with wine.
Each night, the following happens in this exact order:
1. Each bear must choose a (maybe empty) set of barrels. The same barrel may be chosen by many bears.
2. Each bear drinks a glass from each barrel he chose.
3. All bears who drink wine go to sleep (exactly those bears who chose a barrel with wine). They will wake up many days after the party is over. If there are not enough places to sleep then bears lose immediately.
At the end, if it's sure where wine is and there is at least one awake bear then bears win (unless they have lost before because of the number of places to sleep).
Radewoosh wants to allow bears to win. He considers q scenarios. In the i-th scenario the party will last for i nights. Then, let Ri denote the maximum number of barrels for which bears surely win if they behave optimally. Let's define <image>. Your task is to find <image>, where <image> denotes the exclusive or (also denoted as XOR).
Note that the same barrel may be chosen by many bears and all of them will go to sleep at once.
Input
The only line of the input contains three integers n, p and q (1 β€ n β€ 109, 1 β€ p β€ 130, 1 β€ q β€ 2 000 000) β the number of bears, the number of places to sleep and the number of scenarios, respectively.
Output
Print one integer, equal to <image>.
Examples
Input
5 1 3
Output
32
Input
1 100 4
Output
4
Input
3 2 1
Output
7
Input
100 100 100
Output
381863924
Note
In the first sample, there are 5 bears and only 1 place to sleep. We have R1 = 6, R2 = 11, R3 = 16 so the answer is <image>. Let's analyze the optimal strategy for scenario with 2 days. There are R2 = 11 barrels and 10 of them contain juice.
* In the first night, the i-th bear chooses a barrel i only.
* If one of the first 5 barrels contains wine then one bear goes to sleep. Then, bears win because they know where wine is and there is at least one awake bear.
* But let's say none of the first 5 barrels contains wine. In the second night, the i-th bear chooses a barrel 5 + i.
* If one of barrels 6 β 10 contains wine then one bear goes to sleep. And again, bears win in such a situation.
* If nobody went to sleep then wine is in a barrel 11.
In the second sample, there is only one bear. He should choose an empty set of barrels in each night. Otherwise, he would maybe get wine and bears would lose (because there must be at least one awake bear). So, for any number of days we have Ri = 1. The answer is <image>.
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize(2)
const int maxn = 1e5 + 5, maxm = 135;
int Okabe[maxm], Rintaro[maxm];
unsigned Chris[maxm], Tina[maxm];
int n, p, q;
unsigned answer = 0;
unsigned fastpow(unsigned x, unsigned y) {
if (y == 0) return 1;
unsigned tmp = fastpow(x, y >> 1);
return y & 1 ? tmp * tmp * x : tmp * tmp;
}
int main() {
scanf("%d%d%d", &n, &p, &q);
if (p >= n) p = n - 1;
for (int i = 0; i <= p; i++) {
int now = i;
while (now && now % 2 == 0) {
Okabe[i]++;
now >>= 1;
}
now = n - i;
while (now && now % 2 == 0) {
Rintaro[i]++;
now >>= 1;
}
}
for (int i = 0; i <= p; i++) {
Chris[i] = 1;
for (int k = 1; k <= i; k++) Chris[i] *= k / (1 << Okabe[k]);
Chris[i] = fastpow(Chris[i], (1u << 31) - 1);
int cnt = 0;
Tina[i] = 1;
for (int k = 1; k <= i; k++)
cnt += Rintaro[k - 1] - Okabe[k],
Tina[i] *= (n - k + 1) / (1 << Rintaro[k - 1]);
Tina[i] *= 1u << cnt;
}
for (int i = 1; i <= q; i++) {
unsigned now = 0, base = 1;
for (int j = 0; j <= p; j++, base *= i) now += Chris[j] * Tina[j] * base;
answer ^= ((unsigned)i * now);
}
printf("%u\n", answer);
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
You have n devices that you want to use simultaneously.
The i-th device uses ai units of power per second. This usage is continuous. That is, in λ seconds, the device will use λ·ai units of power. The i-th device currently has bi units of power stored. All devices can store an arbitrary amount of power.
You have a single charger that can plug to any single device. The charger will add p units of power per second to a device. This charging is continuous. That is, if you plug in a device for λ seconds, it will gain λ·p units of power. You can switch which device is charging at any arbitrary unit of time (including real numbers), and the time it takes to switch is negligible.
You are wondering, what is the maximum amount of time you can use the devices until one of them hits 0 units of power.
If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power.
Input
The first line contains two integers, n and p (1 β€ n β€ 100 000, 1 β€ p β€ 109) β the number of devices and the power of the charger.
This is followed by n lines which contain two integers each. Line i contains the integers ai and bi (1 β€ ai, bi β€ 100 000) β the power of the device and the amount of power stored in the device in the beginning.
Output
If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power.
Your answer will be considered correct if its absolute or relative error does not exceed 10 - 4.
Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if <image>.
Examples
Input
2 1
2 2
2 1000
Output
2.0000000000
Input
1 100
1 1
Output
-1
Input
3 5
4 3
5 2
6 1
Output
0.5000000000
Note
In sample test 1, you can charge the first device for the entire time until it hits zero power. The second device has enough power to last this time without being charged.
In sample test 2, you can use the device indefinitely.
In sample test 3, we can charge the third device for 2 / 5 of a second, then switch to charge the second device for a 1 / 10 of a second.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long double a[1000000];
long double b[1000000];
int main() {
long double n, p;
cin >> n >> p;
long double saving = 0;
for (int i = 0; i < n; i++) {
cin >> a[i];
cin >> b[i];
saving += a[i];
}
if (saving <= p) {
cout << -1 << endl;
} else {
long double l = 0, mid = 0, r = 1e14;
while (r - l >= 0.00001) {
mid = l + ((r - l) / 2);
long double run = 0.0;
for (int i = 0; i < n; i++) {
long double x;
if (a[i] * mid - b[i] >= 0.0) {
x = a[i] * mid - b[i];
} else {
x = 0.0;
}
run += x;
}
if (run < (p * mid)) {
l = mid;
}
if (run > (p * mid)) {
r = mid;
}
if (run == (p * mid)) {
break;
}
}
cout << mid << endl;
}
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Alice and Bob play a game. Alice has got n treasure chests (the i-th of which contains a_i coins) and m keys (the j-th of which she can sell Bob for b_j coins).
Firstly, Alice puts some locks on the chests. There are m types of locks, the locks of the j-th type can only be opened with the j-th key. To put a lock of type j on the i-th chest, Alice has to pay c_{i,j} dollars. Alice can put any number of different types of locks on each chest (possibly, zero).
Then, Bob buys some of the keys from Alice (possibly none, possibly all of them) and opens each chest he can (he can open a chest if he has the keys for all of the locks on this chest). Bob's profit is the difference between the total number of coins in the opened chests and the total number of coins he spends buying keys from Alice. If Bob's profit is strictly positive (greater than zero), he wins the game. Otherwise, Alice wins the game.
Alice wants to put some locks on some chests so no matter which keys Bob buys, she always wins (Bob cannot get positive profit). Of course, she wants to spend the minimum possible number of dollars on buying the locks. Help her to determine whether she can win the game at all, and if she can, how many dollars she has to spend on the locks.
Input
The first line contains two integers n and m (1 β€ n, m β€ 6) β the number of chests and the number of keys, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 4), where a_i is the number of coins in the i-th chest.
The third line contains m integers b_1, b_2, ..., b_m (1 β€ b_j β€ 4), where b_j is the number of coins Bob has to spend to buy the j-th key from Alice.
Then n lines follow. The i-th of them contains m integers c_{i,1}, c_{i,2}, ..., c_{i,m} (1 β€ c_{i,j} β€ 10^7), where c_{i,j} is the number of dollars Alice has to spend to put a lock of the j-th type on the i-th chest.
Output
If Alice cannot ensure her victory (no matter which locks she puts on which chests, Bob always has a way to gain positive profit), print -1.
Otherwise, print one integer β the minimum number of dollars Alice has to spend to win the game regardless of Bob's actions.
Examples
Input
2 3
3 3
1 1 4
10 20 100
20 15 80
Output
205
Input
2 3
3 3
2 1 4
10 20 100
20 15 80
Output
110
Input
2 3
3 4
1 1 4
10 20 100
20 15 80
Output
-1
Note
In the first example, Alice should put locks of types 1 and 3 on the first chest, and locks of type 2 and 3 on the second chest.
In the second example, Alice should put locks of types 1 and 2 on the first chest, and a lock of type 3 on the second chest.
### Response
```cpp
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#define ll long long
#define MAXN 100005
#define uns unsigned
#define INF 0x3f3f3f3f
using namespace std;
inline ll read(){
ll x=0;bool f=1;char s=getchar();
while((s<'0'||s>'9')&&s>0){if(s=='-')f^=1;s=getchar();}
while(s>='0'&&s<='9')x=(x<<1)+(x<<3)+s-'0',s=getchar();
return f?x:-x;
}
int n,m,a[10],b[10];
int c[10][10];
int dp[15630][7][7][5],ans=INF;
struct itn{int sk[7];};
inline int getcd(itn a){
int code=0;
for(int i=1;i<=n;i++)code=code*5+a.sk[i];
return code;
}
inline itn getst(int c){
itn state={0,0,0,0,0,0,0};
for(int i=n;i>0;i--)state.sk[i]=c%5,c/=5;
return state;
}
inline bool check(itn s){
for(int i=1;i<=n;i++)
if(s.sk[i]<a[i])return 0;
return 1;
}
int main()
{
n=read(),m=read();
for(int i=1;i<=n;i++)a[i]=read();
for(int i=1;i<=m;i++)b[i]=read();
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
c[i][j]=read();
memset(dp,0x3f,sizeof(dp));
dp[0][1][1][0]=0;
int M=pow(5,n);
for(int S=0;S<M;S++){
itn s=getst(S);bool ok=1;
for(int i=1;i<=n;i++)if(s.sk[i]>a[i])ok=0;
for(int j=1;ok&&j<=m;j++)
for(int i=1;i<=n;i++)
for(int r=0;r<5;r++){
if(r>b[j])break;
for(int f=0;f<5;f++){
if(s.sk[i]+f>a[i]||r+f>b[j])break;
itn nw=s;
nw.sk[i]+=f;
int ad=(f?c[i][j]:0),ni=i,nj=j,nr=r+f;
if(i==n)ni=1,nj++,nr=0;
else ni++;
if(check(nw))ans=min(ans,dp[S][i][j][r]+ad);
if(nj<=m){
int cd=getcd(nw);
dp[cd][ni][nj][nr]=min(dp[cd][ni][nj][nr],dp[S][i][j][r]+ad);
}
}
}
}
if(ans>=INF)ans=-1;
printf("%d\n",ans);
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Shinya watched a program on TV called "Maya's Great Prophecy! Will the World End in 2012?" After all, I wasn't sure if the world would end, but I was interested in Maya's "long-term calendar," which was introduced in the program. The program explained as follows.
The Maya long-term calendar is a very long calendar consisting of 13 Baktuns (1872,000 days) in total, consisting of the units shown in the table on the right. One calculation method believes that the calendar begins on August 11, 3114 BC and ends on December 21, 2012, which is why the world ends on December 21, 2012. .. However, there is also the idea that 13 Baktun will be one cycle, and when the current calendar is over, a new cycle will be started.
| 1 kin = 1 day
1 winal = 20 kin
1 tun = 18 winals
1 Katun = 20 tons
1 Baktun = 20 Katun |
--- | --- | ---
"How many days will my 20th birthday be in the Maya calendar?" Shinya wanted to express various days in the Maya long-term calendar.
Now, instead of Shinya, create a program that converts between the Christian era and the Maya long-term calendar.
input
The input consists of multiple datasets. The end of the input is indicated by # 1 line. Each dataset is given in the following format:
b.ka.t.w.ki
Or
y.m.d
The dataset consists of one line containing one character string. b.ka.t.w.ki is the Mayan long-term date and y.m.d is the Christian era date. The units given are as follows.
Maya long calendar
b | Baktun | (0 β€ b <13)
--- | --- | ---
ka | Katun | (0 β€ ka <20)
t | Tun | (0 β€ t <20)
w | Winal | (0 β€ w <18)
ki | kin | (0 β€ ki <20)
Year
y | year | (2012 β€ y β€ 10,000,000)
--- | --- | ---
m | month | (1 β€ m β€ 12)
d | day | (1 β€ d β€ 31)
The maximum value for a day in the Christian era depends on whether it is a large month, a small month, or a leap year (a leap year is a multiple of 4 that is not divisible by 100 or divisible by 400). The range of dates in the Maya long calendar is from 0.0.0.0.0 to 12.19.19.17.19. However, 0.0.0.0.0.0 of the Maya long-term calendar corresponds to 2012.12.21 of the Christian era. The range of dates in the Christian era is from 2012.12.21 to 10000000.12.31.
The number of datasets does not exceed 500.
output
When the input is the Western calendar, the Maya long calendar is output, and when the input is the Maya long calendar, the Western calendar is output in the same format as the input. As a result of converting the input year, even if the next cycle of the Maya long calendar is entered, it may be output in the format of b.ka.t.w.ki.
Example
Input
2012.12.31
2.12.16.14.14
7138.5.13
10.5.2.1.5
10000000.12.31
#
Output
0.0.0.0.10
3054.8.15
0.0.0.0.10
6056.2.29
8.19.3.13.2
### Response
```cpp
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <sstream>
#include <vector>
#include <map>
#include <cassert>
using namespace std;
static long long getDays(long long y, long long m, long long d)
{
if(m <= 2){
--y;
m += 12;
}
long long dy = 365 * (y - 1);
long long c = y / 100;
long long dl = (y >> 2) - c + (c >> 2);
long long dm = (m * 979 - 1033) >> 5;
return dy + dl + dm + d - 1;
}
int main(){
string s;
while(cin >> s && s != "#"){
if( count(s.begin(),s.end(),'.') == 2 ){
// seireki
int y,m,d;
sscanf(s.c_str(),"%d.%d.%d",&y,&m,&d);
long long days = getDays(y,m,d) - getDays(2012,12,21);
days %= 20 * 18 * 20 * 20 * 13;
int b,ka,t,w,ki; int wei = 20 * 18 * 20 * 20;
b = days / wei; days %= wei; wei /= 20;
ka= days / wei; days %= wei; wei /= 20;
t = days / wei; days %= wei; wei /= 18;
w = days / wei; days %= wei; wei /= 20;
ki = days / wei; days %= wei;
cout << b << "." << ka << "." << t << "." << w << "." << ki << endl;
}else{
// maya
int b,ka,t,w,ki;
sscanf(s.c_str(),"%d.%d.%d.%d.%d",&b,&ka,&t,&w,&ki);
int days = 0;
int wei = 1;
days += wei * ki; wei *= 20;
days += wei * w; wei *= 18;
days += wei * t; wei *= 20;
days += wei * ka; wei *= 20;
days += wei * b; wei * 13;
int y = 2012 , m = 12 , d = 21;
int table[] = {-1,31,28,31,30,31,30,31,31,30,31,30,31};
while(days--){
d++;
if( d > table[m] + (m == 2 && ( y % 400 == 0 || (y % 4 == 0 && y % 100 != 0)) ) ){
m++;
d = 1;
}
if( m > 12 ){
y++;
m = 1;
}
}
cout << y << "." << m << "." << d << endl;
}
}
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Sereja owns a restaurant for n people. The restaurant hall has a coat rack with n hooks. Each restaurant visitor can use a hook to hang his clothes on it. Using the i-th hook costs ai rubles. Only one person can hang clothes on one hook.
Tonight Sereja expects m guests in the restaurant. Naturally, each guest wants to hang his clothes on an available hook with minimum price (if there are multiple such hooks, he chooses any of them). However if the moment a guest arrives the rack has no available hooks, Sereja must pay a d ruble fine to the guest.
Help Sereja find out the profit in rubles (possibly negative) that he will get tonight. You can assume that before the guests arrive, all hooks on the rack are available, all guests come at different time, nobody besides the m guests is visiting Sereja's restaurant tonight.
Input
The first line contains two integers n and d (1 β€ n, d β€ 100). The next line contains integers a1, a2, ..., an (1 β€ ai β€ 100). The third line contains integer m (1 β€ m β€ 100).
Output
In a single line print a single integer β the answer to the problem.
Examples
Input
2 1
2 1
2
Output
3
Input
2 1
2 1
10
Output
-5
Note
In the first test both hooks will be used, so Sereja gets 1 + 2 = 3 rubles.
In the second test both hooks will be used but Sereja pays a fine 8 times, so the answer is 3 - 8 = - 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, d, m, i;
cin >> n;
cin >> d;
int a[n];
for (i = 0; i < n; i++) cin >> a[i];
cin >> m;
int ans = 0;
if (n > m) {
sort(a, a + n);
ans = 0;
for (i = 0; i < m; i++) {
ans += a[i];
}
} else {
ans = 0;
for (i = 0; i < n; i++) ans += a[i];
ans -= d * (m - n);
}
cout << ans;
cout << "\n";
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Joisino the magical girl has decided to turn every single digit that exists on this world into 1.
Rewriting a digit i with j (0β€i,jβ€9) costs c_{i,j} MP (Magic Points).
She is now standing before a wall. The wall is divided into HW squares in H rows and W columns, and at least one square contains a digit between 0 and 9 (inclusive).
You are given A_{i,j} that describes the square at the i-th row from the top and j-th column from the left, as follows:
* If A_{i,j}β -1, the square contains a digit A_{i,j}.
* If A_{i,j}=-1, the square does not contain a digit.
Find the minimum total amount of MP required to turn every digit on this wall into 1 in the end.
Constraints
* 1β€H,Wβ€200
* 1β€c_{i,j}β€10^3 (iβ j)
* c_{i,j}=0 (i=j)
* -1β€A_{i,j}β€9
* All input values are integers.
* There is at least one digit on the wall.
Input
Input is given from Standard Input in the following format:
H W
c_{0,0} ... c_{0,9}
:
c_{9,0} ... c_{9,9}
A_{1,1} ... A_{1,W}
:
A_{H,1} ... A_{H,W}
Output
Print the minimum total amount of MP required to turn every digit on the wall into 1 in the end.
Examples
Input
2 4
0 9 9 9 9 9 9 9 9 9
9 0 9 9 9 9 9 9 9 9
9 9 0 9 9 9 9 9 9 9
9 9 9 0 9 9 9 9 9 9
9 9 9 9 0 9 9 9 9 2
9 9 9 9 9 0 9 9 9 9
9 9 9 9 9 9 0 9 9 9
9 9 9 9 9 9 9 0 9 9
9 9 9 9 2 9 9 9 0 9
9 2 9 9 9 9 9 9 9 0
-1 -1 -1 -1
8 1 1 8
Output
12
Input
5 5
0 999 999 999 999 999 999 999 999 999
999 0 999 999 999 999 999 999 999 999
999 999 0 999 999 999 999 999 999 999
999 999 999 0 999 999 999 999 999 999
999 999 999 999 0 999 999 999 999 999
999 999 999 999 999 0 999 999 999 999
999 999 999 999 999 999 0 999 999 999
999 999 999 999 999 999 999 0 999 999
999 999 999 999 999 999 999 999 0 999
999 999 999 999 999 999 999 999 999 0
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
0
Input
3 5
0 4 3 6 2 7 2 5 3 3
4 0 5 3 7 5 3 7 2 7
5 7 0 7 2 9 3 2 9 1
3 6 2 0 2 4 6 4 2 3
3 5 7 4 0 6 9 7 6 7
9 8 5 2 2 0 4 7 6 5
5 4 6 3 2 3 0 5 4 3
3 6 2 3 4 2 4 0 8 9
4 6 5 4 3 5 3 2 0 8
2 1 3 4 5 7 8 6 4 0
3 5 2 6 1
2 5 3 2 1
6 9 2 5 6
Output
47
### Response
```cpp
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int a[10][10];
int h,w;
cin>>h>>w;
for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
cin>>a[i][j];
for(int k=0;k<10;k++)
for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
a[i][j]=min(a[i][j],a[i][k]+a[k][j]);
int s=0;
for(int i=0;i<h;i++){
for(int j=0;j<w;j++){
int x;
cin>>x;
if(x==-1)
continue;
s+=a[x][1];
}
}
cout<<s;
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Vasily the Bear loves beautiful strings. String s is beautiful if it meets the following criteria:
1. String s only consists of characters 0 and 1, at that character 0 must occur in string s exactly n times, and character 1 must occur exactly m times.
2. We can obtain character g from string s with some (possibly, zero) number of modifications. The character g equals either zero or one.
A modification of string with length at least two is the following operation: we replace two last characters from the string by exactly one other character. This character equals one if it replaces two zeros, otherwise it equals zero. For example, one modification transforms string "01010" into string "0100", two modifications transform it to "011". It is forbidden to modify a string with length less than two.
Help the Bear, count the number of beautiful strings. As the number of beautiful strings can be rather large, print the remainder after dividing the number by 1000000007 (109 + 7).
Input
The first line of the input contains three space-separated integers n, m, g (0 β€ n, m β€ 105, n + m β₯ 1, 0 β€ g β€ 1).
Output
Print a single integer β the answer to the problem modulo 1000000007 (109 + 7).
Examples
Input
1 1 0
Output
2
Input
2 2 0
Output
4
Input
1 1 1
Output
0
Note
In the first sample the beautiful strings are: "01", "10".
In the second sample the beautiful strings are: "0011", "1001", "1010", "1100".
In the third sample there are no beautiful strings.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int mat[210000];
const long long mod = 1000000007;
long long cp(long long a, long long b) {
long long ret = 1;
while (b) {
if (b & 1) {
ret *= a;
ret %= mod;
}
a = a * a % mod;
b /= 2;
}
return ret;
}
long long fac[210000], rev[210000];
int main() {
fac[0] = rev[0] = 1;
for (int i = 1; i <= 200000; i++) {
fac[i] = fac[i - 1] * i % mod;
rev[i] = cp(fac[i], mod - 2);
}
int n, m, g;
while (scanf("%d%d%d", &n, &m, &g) != EOF) {
if (m == 0) {
for (int i = 0; i < n; i++) {
mat[i] = 0;
}
for (int i = n - 1; i; i--) {
if (mat[i - 1] == 0 && mat[i] == 0) {
mat[i - 1] = 1;
} else {
mat[i - 1] = 0;
}
}
if (mat[0] == g) {
printf("1\n");
} else {
printf("0\n");
}
continue;
} else if (n == 0) {
for (int i = 0; i < m; i++) {
mat[i] = 1;
}
for (int i = m - 1; i; i--) {
if (mat[i - 1] == 0 && mat[i] == 0) {
mat[i - 1] = 1;
} else {
mat[i - 1] = 0;
}
}
if (mat[0] == g) {
printf("1\n");
} else {
printf("0\n");
}
continue;
}
long long ans = 0;
for (int i = min(n, n + m - 2); i >= 0; i--) {
long long tmp = fac[n + m - i - 1];
tmp *= rev[m - 1];
tmp %= mod;
tmp *= rev[n - i];
tmp %= mod;
if ((i & 1) == g) {
ans += tmp;
ans %= mod;
}
}
if (m == 1) {
n += 2;
for (int i = 0; i < n; i++) {
mat[i] = 0;
}
for (int i = n - 1; i; i--) {
if (mat[i - 1] == 0 && mat[i] == 0) {
mat[i - 1] = 1;
} else {
mat[i - 1] = 0;
}
}
if (mat[0] == g) {
ans++;
ans %= mod;
}
}
cout << ans << endl;
}
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Nearly each project of the F company has a whole team of developers working on it. They often are in different rooms of the office in different cities and even countries. To keep in touch and track the results of the project, the F company conducts shared online meetings in a Spyke chat.
One day the director of the F company got hold of the records of a part of an online meeting of one successful team. The director watched the record and wanted to talk to the team leader. But how can he tell who the leader is? The director logically supposed that the leader is the person who is present at any conversation during a chat meeting. In other words, if at some moment of time at least one person is present on the meeting, then the leader is present on the meeting.
You are the assistant director. Given the 'user logged on'/'user logged off' messages of the meeting in the chronological order, help the director determine who can be the leader. Note that the director has the record of only a continuous part of the meeting (probably, it's not the whole meeting).
Input
The first line contains integers n and m (1 β€ n, m β€ 105) β the number of team participants and the number of messages. Each of the next m lines contains a message in the format:
* '+ id': the record means that the person with number id (1 β€ id β€ n) has logged on to the meeting.
* '- id': the record means that the person with number id (1 β€ id β€ n) has logged off from the meeting.
Assume that all the people of the team are numbered from 1 to n and the messages are given in the chronological order. It is guaranteed that the given sequence is the correct record of a continuous part of the meeting. It is guaranteed that no two log on/log off events occurred simultaneously.
Output
In the first line print integer k (0 β€ k β€ n) β how many people can be leaders. In the next line, print k integers in the increasing order β the numbers of the people who can be leaders.
If the data is such that no member of the team can be a leader, print a single number 0.
Examples
Input
5 4
+ 1
+ 2
- 2
- 1
Output
4
1 3 4 5
Input
3 2
+ 1
- 2
Output
1
3
Input
2 4
+ 1
- 1
+ 2
- 2
Output
0
Input
5 6
+ 1
- 1
- 3
+ 3
+ 4
- 4
Output
3
2 3 5
Input
2 4
+ 1
- 2
+ 2
- 1
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
char logs[100100];
int lgr[100100];
int main() {
int n, m, i, j, k;
char c;
set<int> login, possibles, ans, seenlogin;
while (cin >> n >> m) {
login.clear();
possibles.clear();
ans.clear();
seenlogin.clear();
for (i = 1; i <= n; i++) ans.insert(i);
for (i = 0; i < m; i++) {
cin >> c >> k;
lgr[i] = k;
logs[i] = c;
ans.erase(k);
if (c == '-' && seenlogin.find(k) == seenlogin.end()) login.insert(k);
if (c == '+') seenlogin.insert(k);
}
for (auto x : login) possibles.insert(x);
for (i = 0; i < m; i++) {
if (logs[i] == '+') {
if (login.size()) possibles.erase(lgr[i]);
if (i >= 1 && !(logs[i - 1] == '-' && lgr[i - 1] == lgr[i]))
possibles.erase(lgr[i]);
if (i == 0 && login.empty()) possibles.insert(lgr[i]);
login.insert(lgr[i]);
} else {
if (login.size() > 1) possibles.erase(lgr[i]);
if (i < m - 1 && login.size() == 1 &&
!(logs[i + 1] == '+' && lgr[i + 1] == lgr[i]))
possibles.erase(lgr[i]);
login.erase(lgr[i]);
}
}
for (auto x : possibles) ans.insert(x);
cout << ans.size() << endl;
for (auto x : ans) cout << x << " ";
cout << endl;
}
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Andrewid the Android is a galaxy-famous detective. Now he is busy with a top secret case, the details of which are not subject to disclosure.
However, he needs help conducting one of the investigative experiment. There are n pegs put on a plane, they are numbered from 1 to n, the coordinates of the i-th of them are (xi, 0). Then, we tie to the bottom of one of the pegs a weight on a tight rope of length l (thus, its coordinates will be equal to (xi, - l), where i is the number of the used peg). Then the weight is pushed to the right, so that it starts to rotate counterclockwise. At the same time, if the weight during rotation touches some of the other pegs, it then begins to rotate around that peg. Suppose that each peg itself is very thin and does not affect the rope length while weight is rotating around it.
<image>
More formally, if at some moment the segment of the rope contains one or more pegs in addition to the peg around which the weight is rotating, the weight will then rotate around the farthermost one of them on a shorter segment of a rope. In particular, if the segment of the rope touches some peg by its endpoint, it is considered that the weight starts to rotate around that peg on a segment of the rope of length 0.
At some moment the weight will begin to rotate around some peg, without affecting the rest of the pegs. Andrewid interested in determining the number of this peg.
Andrewid prepared m queries containing initial conditions for pushing the weight, help him to determine for each of them, around what peg the weight will eventually rotate.
Input
The first line contains integers n and m (1 β€ n, m β€ 2Β·105) β the number of pegs and queries.
The next line contains n integers x1, x2, ..., xn ( - 109 β€ xi β€ 109) β the coordinates of the pegs. It is guaranteed that the coordinates of all the pegs are distinct integers.
Next m lines contain the descriptions of the queries of pushing the weight, each consists of two integers ai (1 β€ ai β€ n) and li (1 β€ li β€ 109) β the number of the starting peg and the length of the rope.
Output
Print m lines, the i-th line should contain the number of the peg around which the weight will eventually rotate after the i-th push.
Examples
Input
3 2
0 3 5
2 3
1 8
Output
3
2
Input
4 4
1 5 7 15
1 4
2 15
3 16
1 28
Output
2
4
3
1
Note
Picture to the first sample test:
<image>
Picture to the second sample test:
<image>
Note that in the last query weight starts to rotate around the peg 1 attached to a rope segment of length 0.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 500000;
int n, q, nxt, pos, tmp[N], a[N];
long long l;
pair<int, int> p[N];
int main() {
scanf("%d %d", &n, &q);
for (int i = 0; i < n; i++) {
scanf("%d", &p[i].first);
p[i].second = i + 1;
tmp[i] = p[i].first;
}
sort(p, p + n);
for (int i = 0; i < n; i++) {
a[i] = p[i].first;
}
for (int i = 0; i < q; i++) {
int dir = 1;
int prv = -1;
scanf("%d %I64d", &pos, &l);
pos = lower_bound(a, a + n, tmp[pos - 1]) - a;
while (true) {
if (dir == 1) {
nxt = upper_bound(a + pos, a + n, a[pos] + l) - 1 - a;
} else {
nxt = lower_bound(a, a + pos, a[pos] - l) - a;
}
if (nxt == pos && pos == prv) {
break;
}
long long d = a[nxt] - a[pos];
if (d < 0) {
d = -d;
}
l -= d;
if (nxt == prv) {
l %= 2 * d;
}
prv = pos;
pos = nxt;
dir ^= 1;
}
printf("%d\n", p[pos].second);
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Given is a string S consisting of `0` and `1`. Find the number of strings, modulo 998244353, that can result from applying the following operation on S zero or more times:
* Remove the two characters at the beginning of S, erase one of them, and reinsert the other somewhere in S. This operation can be applied only when S has two or more characters.
Constraints
* 1 \leq |S| \leq 300
* S consists of `0` and `1`.
Input
Input is given from Standard Input in the following format:
S
Output
Print the number of strings, modulo 998244353, that can result from applying the operation on S zero or more times.
Examples
Input
0001
Output
8
Input
110001
Output
24
Input
11101111011111000000000110000001111100011111000000001111111110000000111111111
Output
697354558
### Response
```cpp
#include<cstdio>
#include<cstring>
#define RI register int
#define CI const int&
using namespace std;
const int N=305,mod=998244353;
char s[N]; int n,f[N][N][N],ans; bool vis[N][N][N]; // f[i][j][k]: length i; j 0s to add; k 1s to add
inline void inc(int& x,CI y)
{
if ((x+=y)>=mod) x-=mod;
}
int main()
{
RI i,j,k; scanf("%s",s+1); n=strlen(s+1); s[0]='2';
for (f[0][0][0]=1,i=0;i<n;++i) for (j=0;j<=i;++j)
for (k=0;j+k<=i;++k) if (f[i][j][k])
{
int c=s[n-(i-j-k)]-'0'; inc(f[i+1][j][k],f[i][j][k]);
if (c) inc(f[i+1][j+1][k],f[i][j][k]); else inc(f[i+1][j][k+1],f[i][j][k]);
}
for (vis[0][0][0]=vis[n][0][0]=1,i=n-1;i;--i)
for (j=0;j<=i;++j) for (k=0;j+k<=i;++k)
{
int c1=s[n-(i-j-k)]-'0',c2=s[n-(i-j-k)-1]-'0',t[3]; t[2]=0;
if (t[0]=j,t[1]=k,++t[0],t[c1])
{
if (--t[c1],t[c2]&&(c1==0||c2==0)) --t[c2];
}
vis[i][j][k]|=vis[i+1][t[0]][t[1]];
if (t[0]=j,t[1]=k,++t[1],t[c1])
{
if (--t[c1],t[c2]&&(c1==1||c2==1)) --t[c2];
}
vis[i][j][k]|=vis[i+1][t[0]][t[1]];
}
for (i=1;i<=n;++i) for (j=0;j<=i;++j) for (k=0;j+k<=i;++k)
if (vis[i][j][k]) inc(ans,f[i][j][k]); return printf("%d",ans),0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
It has been noted that if some ants are put in the junctions of the graphene integer lattice then they will act in the following fashion: every minute at each junction (x, y) containing at least four ants a group of four ants will be formed, and these four ants will scatter to the neighbouring junctions (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1) β one ant in each direction. No other ant movements will happen. Ants never interfere with each other.
Scientists have put a colony of n ants into the junction (0, 0) and now they wish to know how many ants will there be at some given junctions, when the movement of the ants stops.
Input
First input line contains integers n (0 β€ n β€ 30000) and t (1 β€ t β€ 50000), where n is the number of ants in the colony and t is the number of queries. Each of the next t lines contains coordinates of a query junction: integers xi, yi ( - 109 β€ xi, yi β€ 109). Queries may coincide.
It is guaranteed that there will be a certain moment of time when no possible movements can happen (in other words, the process will eventually end).
Output
Print t integers, one per line β the number of ants at the corresponding junctions when the movement of the ants stops.
Examples
Input
1 3
0 1
0 0
0 -1
Output
0
1
0
Input
6 5
0 -2
0 -1
0 0
0 1
0 2
Output
0
1
2
1
0
Note
In the first sample the colony consists of the one ant, so nothing happens at all.
In the second sample the colony consists of 6 ants. At the first minute 4 ants scatter from (0, 0) to the neighbouring junctions. After that the process stops.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int tab[1000][1000];
void generate_map(int ants) {
tab[500][500] = ants;
queue<pair<int, int> > queue;
if (ants >= 4) queue.push(make_pair(500, 500));
while (!queue.empty()) {
pair<int, int> p = queue.front();
queue.pop();
int v = tab[p.first][p.second];
if (v < 4) continue;
int add = v / 4;
tab[p.first][p.second] = v % 4;
tab[p.first + 1][p.second] += add;
tab[p.first - 1][p.second] += add;
tab[p.first][p.second + 1] += add;
tab[p.first][p.second - 1] += add;
if (tab[p.first - 1][p.second] >= 4)
queue.push(make_pair(p.first - 1, p.second));
if (tab[p.first + 1][p.second] >= 4)
queue.push(make_pair(p.first + 1, p.second));
if (tab[p.first][p.second + 1] >= 4)
queue.push(make_pair(p.first, p.second + 1));
if (tab[p.first][p.second - 1] >= 4)
queue.push(make_pair(p.first, p.second - 1));
}
}
int main() {
int ants, query, x, y;
scanf("%d %d", &ants, &query);
generate_map(ants);
for (int i = 0; i < query; ++i) {
scanf("%d %d", &x, &y);
if (x >= 500 || y >= 500 || x <= -500 || y <= -500) {
cout << 0 << endl;
} else {
cout << tab[x + 500][y + 500] << endl;
}
}
return 0;
};
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Little Elephant loves Furik and Rubik, who he met in a small city Kremenchug.
The Little Elephant has two strings of equal length a and b, consisting only of uppercase English letters. The Little Elephant selects a pair of substrings of equal length β the first one from string a, the second one from string b. The choice is equiprobable among all possible pairs. Let's denote the substring of a as x, and the substring of b β as y. The Little Elephant gives string x to Furik and string y β to Rubik.
Let's assume that f(x, y) is the number of such positions of i (1 β€ i β€ |x|), that xi = yi (where |x| is the length of lines x and y, and xi, yi are the i-th characters of strings x and y, correspondingly). Help Furik and Rubik find the expected value of f(x, y).
Input
The first line contains a single integer n (1 β€ n β€ 2Β·105) β the length of strings a and b. The second line contains string a, the third line contains string b. The strings consist of uppercase English letters only. The length of both strings equals n.
Output
On a single line print a real number β the answer to the problem. The answer will be considered correct if its relative or absolute error does not exceed 10 - 6.
Examples
Input
2
AB
BA
Output
0.400000000
Input
3
AAB
CAA
Output
0.642857143
Note
Let's assume that we are given string a = a1a2... a|a|, then let's denote the string's length as |a|, and its i-th character β as ai.
A substring a[l... r] (1 β€ l β€ r β€ |a|) of string a is string alal + 1... ar.
String a is a substring of string b, if there exists such pair of integers l and r (1 β€ l β€ r β€ |b|), that b[l... r] = a.
Let's consider the first test sample. The first sample has 5 possible substring pairs: ("A", "B"), ("A", "A"), ("B", "B"), ("B", "A"), ("AB", "BA"). For the second and third pair value f(x, y) equals 1, for the rest it equals 0. The probability of choosing each pair equals <image>, that's why the answer is <image> Β· 0 + <image> Β· 1 + <image> Β· 1 + <image> Β· 0 + <image> Β· 0 = <image> = 0.4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
unsigned long long i, j, k, m, n, l;
char s[200000 + 10], t[200000 + 10];
vector<int> a[26 + 10], b[26 + 10];
double x, y;
double f[200000 + 10], g[200000 + 10];
int main() {
scanf("%d", &n);
scanf("%s", s);
scanf("%s", t);
for (int i = 0; i < (n); ++i) a[s[i] - 'A'].push_back(i + 1);
for (int i = 0; i < (n); ++i) b[t[i] - 'A'].push_back(i + 1);
for (int i = (1); i <= (n); ++i) y += (double)i * i;
for (int i = 0; i < (26); ++i) {
if (((int)(a[i]).size()) == 0) continue;
m = ((int)(a[i]).size());
g[m - 1] = n - a[i][m - 1] + 1;
for (int j = (m - 2); j >= (0); --j) g[j] = g[j + 1] + n - a[i][j] + 1;
j = k = 0;
double tot = 0;
while (j < ((int)(a[i]).size()) && k < ((int)(b[i]).size())) {
if (a[i][j] <= b[i][k])
tot += a[i][j++];
else {
x += b[i][k] * g[j];
x += tot * (n - b[i][k++] + 1);
}
}
while (k < ((int)(b[i]).size())) x += tot * (n - b[i][k++] + 1);
}
printf("%.12lf\n", x / y);
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Print all combinations which can be made by $k$ different elements from $0, 1, ..., n-1$. Note that we represent $0, 1, ... n-1$ as 00...0001, 00...0010, 00...0100, ..., 10...0000 in binary respectively and the integer representation of a combination is calculated by bitwise OR of the selected elements.
Constraints
* $1 \leq n \leq 18$
* $k \leq n$
Input
The input is given in the following format.
$n \; k$
Output
Print the combinations ordered by their decimal integers. Print a combination in the following format.
$d$: $e_0$ $e_1$ ...
Print ':' after the integer value $d$, then print elements $e_i$ in the combination in ascending order. Separate two adjacency elements by a space character.
Example
Input
5 3
Output
7: 0 1 2
11: 0 1 3
13: 0 2 3
14: 1 2 3
19: 0 1 4
21: 0 2 4
22: 1 2 4
25: 0 3 4
26: 1 3 4
28: 2 3 4
### Response
```cpp
#include <bitset>
#include <iostream>
using ull = unsigned long long;
int main() {
int n, k;
std::cin >> n >> k;
for (ull d = 0; d < (ull)(1 << n); ++d) {
if (std::bitset<18>(d).count() != (unsigned)k) continue;
std::cout << d << ':';
for (int i = 0; i < n; ++i)
if (d & (1 << i)) std::cout << ' ' << i;
std::cout << std::endl;
}
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to <image>. Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it.
He painted a few lines, parallel to the sides of the hexagon. The lines split the hexagon into regular triangles with sides of 1 centimeter. Now Gerald wonders how many triangles he has got. But there were so many of them that Gerald lost the track of his counting. Help the boy count the triangles.
Input
The first and the single line of the input contains 6 space-separated integers a1, a2, a3, a4, a5 and a6 (1 β€ ai β€ 1000) β the lengths of the sides of the hexagons in centimeters in the clockwise order. It is guaranteed that the hexagon with the indicated properties and the exactly such sides exists.
Output
Print a single integer β the number of triangles with the sides of one 1 centimeter, into which the hexagon is split.
Examples
Input
1 1 1 1 1 1
Output
6
Input
1 2 1 2 1 2
Output
13
Note
This is what Gerald's hexagon looks like in the first sample:
<image>
And that's what it looks like in the second sample:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[7];
long long res;
int main() {
res = 0;
for (int i = 1; i <= 6; i++) cin >> a[i];
res = (a[6]) * (a[6]) + 2 * a[1] * a[6] + 2 * a[1] * a[5] + 2 * a[5] * a[6] -
(a[3]) * (a[3]);
cout << res;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Sonya was unable to think of a story for this problem, so here comes the formal description.
You are given the array containing n positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operations. You are allowed to change elements in any way, they can become negative or equal to 0.
Input
The first line of the input contains a single integer n (1 β€ n β€ 3000) β the length of the array.
Next line contains n integer ai (1 β€ ai β€ 109).
Output
Print the minimum number of operation required to make the array strictly increasing.
Examples
Input
7
2 1 5 11 5 9 11
Output
9
Input
5
5 4 3 2 1
Output
12
Note
In the first sample, the array is going to look as follows:
2 3 5 6 7 9 11
|2 - 2| + |1 - 3| + |5 - 5| + |11 - 6| + |5 - 7| + |9 - 9| + |11 - 11| = 9
And for the second sample:
1 2 3 4 5
|5 - 1| + |4 - 2| + |3 - 3| + |2 - 4| + |1 - 5| = 12
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long d[3333][3333], a[3333], b[3333];
int main() {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", a + i);
a[i] -= i;
b[i] = a[i];
}
sort(b + 1, b + 1 + n);
int bn = unique(b + 1, b + 1 + n) - b - 1;
memset(d, 127, sizeof(d));
for (int i = 1; i <= bn; ++i) {
d[1][i] = min(d[1][i - 1], abs(a[1] - b[i]));
}
for (int i = 2; i <= n; ++i) {
for (int j = 1; j <= bn; ++j) {
d[i][j] = min(d[i][j - 1], d[i - 1][j] + abs(a[i] - b[j]));
}
}
printf("%I64d", d[n][bn]);
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim.
The killer starts with two potential victims on his first day, selects one of these two, kills selected victim and replaces him with a new person. He repeats this procedure each day. This way, each day he has two potential victims to choose from. Sherlock knows the initial two potential victims. Also, he knows the murder that happened on a particular day and the new person who replaced this victim.
You need to help him get all the pairs of potential victims at each day so that Sherlock can observe some pattern.
Input
First line of input contains two names (length of each of them doesn't exceed 10), the two initials potential victims. Next line contains integer n (1 β€ n β€ 1000), the number of days.
Next n lines contains two names (length of each of them doesn't exceed 10), first being the person murdered on this day and the second being the one who replaced that person.
The input format is consistent, that is, a person murdered is guaranteed to be from the two potential victims at that time. Also, all the names are guaranteed to be distinct and consists of lowercase English letters.
Output
Output n + 1 lines, the i-th line should contain the two persons from which the killer selects for the i-th murder. The (n + 1)-th line should contain the two persons from which the next victim is selected. In each line, the two names can be printed in any order.
Examples
Input
ross rachel
4
ross joey
rachel phoebe
phoebe monica
monica chandler
Output
ross rachel
joey rachel
joey phoebe
joey monica
joey chandler
Input
icm codeforces
1
codeforces technex
Output
icm codeforces
icm technex
Note
In first example, the killer starts with ross and rachel.
* After day 1, ross is killed and joey appears.
* After day 2, rachel is killed and phoebe appears.
* After day 3, phoebe is killed and monica appears.
* After day 4, monica is killed and chandler appears.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long inf = 1e15;
long long mod = 1e9 + 7;
string ITS(long long x) {
string s = "";
while (x > 0) {
s += (char)(x % 10 + '0');
x /= 10;
}
string t = "";
for (int i = s.size() - 1; i > -1; i--) t += s[i];
return t;
}
long long bmm(long long a, long long b) {
if (a == 0) return b;
return bmm(b % a, a);
}
bool aval(long long x) {
if (x < 2) return 0;
if (x < 4) return 1;
for (long long i = 2; i * i <= x; i++)
if (x % i == 0) return 0;
return 1;
}
long long power(long long p, long long t) {
if (t == 0) return 1;
long long x = power(p, t / 2);
if (t % 2)
return x * x * p;
else
return x * x;
}
const long long M = 1e2 + 5;
int main() {
std::ios::sync_with_stdio(false);
string s, t;
cin >> s >> t;
long long n;
cin >> n;
cout << s << ' ' << t << '\n';
for (long long i = 0; i < n; i++) {
string u, v;
cin >> u >> v;
if (s == u)
s = v;
else if (t == u)
t = v;
cout << s << ' ' << t << '\n';
}
}
``` |
### Prompt
Create a solution in cpp for the following problem:
The academic year has just begun, but lessons and olympiads have already occupied all the free time. It is not a surprise that today Olga fell asleep on the Literature. She had a dream in which she was on a stairs.
The stairs consists of n steps. The steps are numbered from bottom to top, it means that the lowest step has number 1, and the highest step has number n. Above each of them there is a pointer with the direction (up or down) Olga should move from this step. As soon as Olga goes to the next step, the direction of the pointer (above the step she leaves) changes. It means that the direction "up" changes to "down", the direction "down" β to the direction "up".
Olga always moves to the next step in the direction which is shown on the pointer above the step.
If Olga moves beyond the stairs, she will fall and wake up. Moving beyond the stairs is a moving down from the first step or moving up from the last one (it means the n-th) step.
In one second Olga moves one step up or down according to the direction of the pointer which is located above the step on which Olga had been at the beginning of the second.
For each step find the duration of the dream if Olga was at this step at the beginning of the dream.
Olga's fall also takes one second, so if she was on the first step and went down, she would wake up in the next second.
Input
The first line contains single integer n (1 β€ n β€ 106) β the number of steps on the stairs.
The second line contains a string s with the length n β it denotes the initial direction of pointers on the stairs. The i-th character of string s denotes the direction of the pointer above i-th step, and is either 'U' (it means that this pointer is directed up), or 'D' (it means this pointed is directed down).
The pointers are given in order from bottom to top.
Output
Print n numbers, the i-th of which is equal either to the duration of Olga's dream or to - 1 if Olga never goes beyond the stairs, if in the beginning of sleep she was on the i-th step.
Examples
Input
3
UUD
Output
5 6 3
Input
10
UUDUDUUDDU
Output
5 12 23 34 36 27 18 11 6 1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int Maxn = 1000200;
int n;
char s[Maxn];
long long rep1[Maxn], rep2[Maxn];
int Q[2][Maxn];
long long sta[Maxn];
int cg(char c) {
if (c == 'U') return 0;
return 1;
}
void solve(long long* rep) {
int tot[2] = {0, 0};
int cur[2] = {0, 0};
for (int i = 1; i <= n; i++) tot[cg(s[i])]++;
for (int i = 1; i <= n; i++) {
cur[cg(s[i])]++;
if (s[i] == 'D') continue;
int x = cur[0], y = tot[1] - cur[1];
if (x <= y) {
rep[i] = i;
Q[0][i] = Q[1][i] = x;
} else {
rep[i] = n + 1 + i;
Q[0][i] = y + 1;
Q[1][i] = y;
}
}
int top = 0;
for (int i = 1; i <= n; i++) {
if (s[i] == 'U') {
long long nval = sta[top] + i;
sta[++top] = nval;
}
if (s[i] == 'U') rep[i] -= 2 * (sta[top] - sta[top - Q[0][i]]);
}
top = 0;
for (int i = n; i >= 1; i--) {
if (s[i] == 'D') {
long long nval = sta[top] + i;
sta[++top] = nval;
}
if (s[i] == 'U') rep[i] += 2 * (sta[top] - sta[top - Q[1][i]]);
}
}
int main() {
scanf("%d", &n);
scanf("%s", s + 1);
solve(rep1);
reverse(s + 1, s + n + 1);
for (int i = 1; i <= n; i++)
if (s[i] == 'U')
s[i] = 'D';
else
s[i] = 'U';
solve(rep2);
for (int i = 1; i <= n; i++) {
if (rep2[i]) rep1[n + 1 - i] = rep2[i];
}
for (int i = 1; i <= n; i++) printf("%lld%c", rep1[i], i == n ? '\n' : ' ');
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Harry Potter has a difficult homework. Given a rectangular table, consisting of n Γ m cells. Each cell of the table contains the integer. Harry knows how to use two spells: the first spell change the sign of the integers in the selected row, the second β in the selected column. Harry's task is to make non-negative the sum of the numbers in each row and each column using these spells.
Alone, the boy can not cope. Help the young magician!
Input
The first line contains two integers n and m (1 β€ n, m β€ 100) β the number of rows and the number of columns.
Next n lines follow, each contains m integers: j-th integer in the i-th line is ai, j (|ai, j| β€ 100), the number in the i-th row and j-th column of the table.
The rows of the table numbered from 1 to n. The columns of the table numbered from 1 to m.
Output
In the first line print the number a β the number of required applications of the first spell. Next print a space-separated integers β the row numbers, you want to apply a spell. These row numbers must be distinct!
In the second line print the number b β the number of required applications of the second spell. Next print b space-separated integers β the column numbers, you want to apply a spell. These column numbers must be distinct!
If there are several solutions are allowed to print any of them.
Examples
Input
4 1
-1
-1
-1
-1
Output
4 1 2 3 4
0
Input
2 4
-1 -1 -1 2
1 1 1 1
Output
1 1
1 4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100 + 10;
int t[MAXN][MAXN], n, m, row[MAXN], col[MAXN], minimum;
set<int> rows;
set<int> cols;
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> t[i][j];
row[i] += t[i][j];
col[j] += t[i][j];
}
}
minimum = min(n, m);
for (int k = 0; k < minimum; k++) {
for (int i = 0; i < n; i++) {
if (row[i] < 0) {
if (rows.count(i + 1))
rows.erase(i + 1);
else
rows.insert(i + 1);
row[i] *= (-1);
for (int j = 0; j < m; j++) {
col[j] = col[j] - t[i][j];
t[i][j] *= (-1);
col[j] = col[j] + t[i][j];
}
}
}
for (int i = 0; i < m; i++) {
if (col[i] < 0) {
if (cols.count(i + 1))
cols.erase(i + 1);
else
cols.insert(i + 1);
col[i] *= (-1);
for (int j = 0; j < n; j++) {
row[j] = row[j] - t[j][i];
t[j][i] *= (-1);
row[j] = row[j] + t[j][i];
}
}
}
}
cout << rows.size();
for (auto i : rows) {
cout << ' ' << i;
}
cout << '\n';
cout << cols.size();
for (auto i : cols) {
cout << ' ' << i;
}
cout << '\n';
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Manao has a monitor. The screen of the monitor has horizontal to vertical length ratio a:b. Now he is going to watch a movie. The movie's frame has horizontal to vertical length ratio c:d. Manao adjusts the view in such a way that the movie preserves the original frame ratio, but also occupies as much space on the screen as possible and fits within it completely. Thus, he may have to zoom the movie in or out, but Manao will always change the frame proportionally in both dimensions.
Calculate the ratio of empty screen (the part of the screen not occupied by the movie) to the total screen size. Print the answer as an irreducible fraction p / q.
Input
A single line contains four space-separated integers a, b, c, d (1 β€ a, b, c, d β€ 1000).
Output
Print the answer to the problem as "p/q", where p is a non-negative integer, q is a positive integer and numbers p and q don't have a common divisor larger than 1.
Examples
Input
1 1 3 2
Output
1/3
Input
4 3 2 2
Output
1/4
Note
Sample 1. Manao's monitor has a square screen. The movie has 3:2 horizontal to vertical length ratio. Obviously, the movie occupies most of the screen if the width of the picture coincides with the width of the screen. In this case, only 2/3 of the monitor will project the movie in the horizontal dimension: <image>
Sample 2. This time the monitor's width is 4/3 times larger than its height and the movie's frame is square. In this case, the picture must take up the whole monitor in the vertical dimension and only 3/4 in the horizontal dimension: <image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a, b, c, d, p, q, i;
cin >> a >> b >> c >> d;
if ((a * d) > (b * c)) {
p = a * d - b * c;
q = a * d;
for (i = 2; i <= p && i <= q; i++) {
if (p % i == 0 && q % i == 0) {
p /= i;
q /= i;
i = 2;
}
}
} else if ((a * d) < (b * c)) {
p = b * c - a * d;
q = b * c;
for (i = 2; i <= p && i <= q; i++) {
if (p % i == 0 && q % i == 0) {
p /= i;
q /= i;
i = 1;
}
}
} else {
p = 0;
q = 1;
}
cout << p << "/" << q;
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
There's a famous museum in the city where KleofΓ‘Ε‘ lives. In the museum, n exhibits (numbered 1 through n) had been displayed for a long time; the i-th of those exhibits has value vi and mass wi.
Then, the museum was bought by a large financial group and started to vary the exhibits. At about the same time, KleofΓ‘Ε‘... gained interest in the museum, so to say.
You should process q events of three types:
* type 1 β the museum displays an exhibit with value v and mass w; the exhibit displayed in the i-th event of this type is numbered n + i (see sample explanation for more details)
* type 2 β the museum removes the exhibit with number x and stores it safely in its vault
* type 3 β KleofΓ‘Ε‘ visits the museum and wonders (for no important reason at all, of course): if there was a robbery and exhibits with total mass at most m were stolen, what would their maximum possible total value be?
For each event of type 3, let s(m) be the maximum possible total value of stolen exhibits with total mass β€ m.
Formally, let D be the set of numbers of all exhibits that are currently displayed (so initially D = {1, ..., n}). Let P(D) be the set of all subsets of D and let
<image>
Then, s(m) is defined as
<image>
Compute s(m) for each <image>. Note that the output follows a special format.
Input
The first line of the input contains two space-separated integers n and k (1 β€ n β€ 5000, 1 β€ k β€ 1000) β the initial number of exhibits in the museum and the maximum interesting mass of stolen exhibits.
Then, n lines follow. The i-th of them contains two space-separated positive integers vi and wi (1 β€ vi β€ 1 000 000, 1 β€ wi β€ 1000) β the value and mass of the i-th exhibit.
The next line contains a single integer q (1 β€ q β€ 30 000) β the number of events.
Each of the next q lines contains the description of one event in the following format:
* 1 v w β an event of type 1, a new exhibit with value v and mass w has been added (1 β€ v β€ 1 000 000, 1 β€ w β€ 1000)
* 2 x β an event of type 2, the exhibit with number x has been removed; it's guaranteed that the removed exhibit had been displayed at that time
* 3 β an event of type 3, KleofΓ‘Ε‘ visits the museum and asks his question
There will be at most 10 000 events of type 1 and at least one event of type 3.
Output
As the number of values s(m) can get large, output the answers to events of type 3 in a special format.
For each event of type 3, consider the values s(m) computed for the question that KleofΓ‘Ε‘ asked in this event; print one line containing a single number
<image>
where p = 107 + 19 and q = 109 + 7.
Print the answers to events of type 3 in the order in which they appear in the input.
Examples
Input
3 10
30 4
60 6
5 1
9
3
1 42 5
1 20 3
3
2 2
2 4
3
1 40 6
3
Output
556674384
168191145
947033915
181541912
Input
3 1000
100 42
100 47
400 15
4
2 2
2 1
2 3
3
Output
0
Note
In the first sample, the numbers of displayed exhibits and values s(1), ..., s(10) for individual events of type 3 are, in order:
<image> <image> <image> <image>
The values of individual exhibits are v1 = 30, v2 = 60, v3 = 5, v4 = 42, v5 = 20, v6 = 40 and their masses are w1 = 4, w2 = 6, w3 = 1, w4 = 5, w5 = 3, w6 = 6.
In the second sample, the only question is asked after removing all exhibits, so s(m) = 0 for any m.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline void setmin(T &x, T y) {
if (y < x) x = y;
}
template <typename T>
inline void setmax(T &x, T y) {
if (y > x) x = y;
}
template <typename T>
inline T gcd(T a, T b) {
while (b) swap(a %= b, b);
return a;
}
const int MAX = (1 << 14);
const int INF = 1e9 + 7;
const long long BIG_INF = 1e18 + 5;
int POCZ[MAX], KON[MAX];
long long MOD[MAX];
long long n, k, q;
pair<vector<int>, vector<int> > tree[2 * MAX];
vector<pair<int, int> > tab;
void dodaj(int pocz, int kon, int value) {
pocz += MAX, kon += MAX;
tree[pocz].first.push_back(value);
if (pocz != kon) {
tree[kon].first.push_back(value);
}
while (pocz >> 1 != kon >> 1) {
if (!(pocz & 1)) {
tree[pocz + 1].first.push_back(value);
}
if (kon & 1) {
tree[kon - 1].first.push_back(value);
}
pocz >>= 1;
kon >>= 1;
}
}
vector<int> knapsack(vector<int> base, vector<int> &nowe) {
for (auto u : nowe) {
int koszt = tab[u].first;
int waga = tab[u].second;
for (int i = int((base).size()) - 1; i >= waga; i--) {
base[i] = max(base[i], base[i - waga] + koszt);
}
}
return base;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> k;
MOD[0] = 1;
for (int(i) = (1); (i) < (MAX); (i)++) {
MOD[i] = (MOD[i - 1] * (long long)(1e7 + 19)) % INF;
}
fill(KON, KON + MAX, MAX - 1);
fill(POCZ, POCZ + MAX, MAX);
for (int(i) = (0); (i) < (n); (i)++) {
int a, b;
cin >> a >> b;
tab.push_back({a, b});
POCZ[i] = 0;
}
cin >> q;
int ile_q1 = 0;
int ile_q3 = 0;
vector<int> zapytania;
int pom = 1;
bool czy_zmiana = 1;
for (int(i) = (0); (i) < (q); (i)++) {
int znak;
cin >> znak;
if (znak == 1) {
czy_zmiana = 1;
int a, b;
cin >> a >> b;
POCZ[n + ile_q1] = ile_q3;
tab.push_back({a, b});
ile_q1++;
} else if (znak == 2) {
czy_zmiana = 1;
int a;
cin >> a;
a--;
KON[a] = ile_q3 - 1;
} else {
if (czy_zmiana) {
ile_q3++;
zapytania.push_back(pom);
pom = 1;
czy_zmiana = 0;
} else {
pom++;
}
}
}
zapytania.push_back(pom);
for (int i = 0; i < n + ile_q1; i++) {
if (POCZ[i] > KON[i]) {
continue;
}
dodaj(POCZ[i], KON[i], i);
}
vector<int> temp;
temp.resize(k + 1);
tree[1].second = temp;
for (int(i) = (2); (i) < (2 * MAX); (i)++) {
tree[i].second = knapsack(tree[i / 2].second, tree[i].first);
}
for (int(i) = (MAX); (i) < (MAX + ile_q3); (i)++) {
long long odp = 0;
for (int j = 1; j <= k; j++) {
odp = (odp + tree[i].second[j] * MOD[j - 1]) % INF;
}
cout << odp << '\n';
for (int j = 1; j < zapytania[i - MAX + 1]; j++) cout << odp << '\n';
}
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
On the well-known testing system MathForces, a draw of n rating units is arranged. The rating will be distributed according to the following algorithm: if k participants take part in this event, then the n rating is evenly distributed between them and rounded to the nearest lower integer, At the end of the drawing, an unused rating may remain β it is not given to any of the participants.
For example, if n = 5 and k = 3, then each participant will recieve an 1 rating unit, and also 2 rating units will remain unused. If n = 5, and k = 6, then none of the participants will increase their rating.
Vasya participates in this rating draw but does not have information on the total number of participants in this event. Therefore, he wants to know what different values of the rating increment are possible to get as a result of this draw and asks you for help.
For example, if n=5, then the answer is equal to the sequence 0, 1, 2, 5. Each of the sequence values (and only them) can be obtained as β n/k β for some positive integer k (where β x β is the value of x rounded down): 0 = β 5/7 β, 1 = β 5/5 β, 2 = β 5/2 β, 5 = β 5/1 β.
Write a program that, for a given n, finds a sequence of all possible rating increments.
Input
The first line contains integer number t (1 β€ t β€ 10) β the number of test cases in the input. Then t test cases follow.
Each line contains an integer n (1 β€ n β€ 10^9) β the total number of the rating units being drawn.
Output
Output the answers for each of t test cases. Each answer should be contained in two lines.
In the first line print a single integer m β the number of different rating increment values that Vasya can get.
In the following line print m integers in ascending order β the values of possible rating increments.
Example
Input
4
5
11
1
3
Output
4
0 1 2 5
6
0 1 2 3 5 11
2
0 1
3
0 1 3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> vc;
vc.clear();
for (int i = 1; i <= sqrt(n); i++) {
if (n / i != i) vc.push_back(n / i);
}
int rt = sqrt(n);
cout << rt + vc.size() + 1 << endl;
cout << 0 << ' ';
for (int i = 1; i <= sqrt(n); i++) {
cout << i << ' ';
}
for (int i = vc.size() - 1; i >= 0; i--) cout << vc[i] << ' ';
cout << endl;
}
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
In your garden, there is a long and narrow flowerbed that stretches infinitely to the east. You have decided to plant N kinds of flowers in this empty flowerbed. For convenience, we will call these N kinds of flowers Flower 1, 2, β¦, N. Also, we will call the position that is p centimeters from the west end of the flowerbed Position p.
You will plant Flower i (1 β€ i β€ N) as follows: first, plant one at Position w_i, then plant one every d_i centimeters endlessly toward the east. That is, Flower i will be planted at the positions w_i, w_i + d_i, w_i + 2 d_i, β¦ Note that more than one flower may be planted at the same position.
Find the position at which the K-th flower from the west is planted. If more than one flower is planted at the same position, they are counted individually.
Constraints
* 1 β€ N β€ 10^5
* 1 β€ K β€ 10^9
* 1 β€ w_i β€ 10^{18}
* 1 β€ d_i β€ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N K
w_1 d_1
:
w_N d_N
Output
When the K-th flower from the west is planted at Position X, print the value of X. (The westmost flower is counted as the 1-st flower.)
Examples
Input
2 6
20 10
25 15
Output
50
Input
3 9
10 10
10 10
10 10
Output
30
Input
1 1000000000
1000000000000000000 1000000000
Output
1999999999000000000
### Response
```cpp
#define _USE_MATH_DEFINES
#include <cstdio>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <complex>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include <numeric>
#include <limits>
#include <climits>
#include <cfloat>
#include <functional>
#include <iterator>
using namespace std;
int main()
{
int n, k;
cin >> n >> k;
vector<long long> w(n), d(n);
for(int i=0; i<n; ++i)
cin >> w[i] >> d[i];
long long left = 1;
long long right = 3000000000000000000LL;
while(left < right){
long long mid = (left + right) / 2;
long long cnt = 0;
for(int i=0; i<n; ++i){
if(w[i] <= mid)
cnt += (mid - w[i]) / d[i] + 1;
}
if(cnt < k)
left = mid + 1;
else
right = mid;
}
cout << left << endl;
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
One very well-known internet resource site (let's call it X) has come up with a New Year adventure. Specifically, they decided to give ratings to all visitors.
There are n users on the site, for each user we know the rating value he wants to get as a New Year Present. We know that user i wants to get at least ai rating units as a present.
The X site is administered by very creative and thrifty people. On the one hand, they want to give distinct ratings and on the other hand, the total sum of the ratings in the present must be as small as possible.
Help site X cope with the challenging task of rating distribution. Find the optimal distribution.
Input
The first line contains integer n (1 β€ n β€ 3Β·105) β the number of users on the site. The next line contains integer sequence a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print a sequence of integers b1, b2, ..., bn. Number bi means that user i gets bi of rating as a present. The printed sequence must meet the problem conditions.
If there are multiple optimal solutions, print any of them.
Examples
Input
3
5 1 1
Output
5 1 2
Input
1
1000000000
Output
1000000000
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int gcd(int big, int small) {
if (big % small == 0)
return small;
else
return gcd(small, big % small);
}
int main() {
ios_base::sync_with_stdio(false);
int n;
cin >> n;
vector<pair<int, int>> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i].first;
a[i].second = i;
}
sort(a.begin(), a.end());
for (int i = 1; i < n; ++i) {
if (a[i].first <= a[i - 1].first) a[i].first = a[i - 1].first + 1;
}
vector<int> b(n);
for (int i = 0; i < n; ++i) {
b[a[i].second] = a[i].first;
}
for (int i = 0; i < n; ++i) cout << b[i] << " ";
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly n pixels.
Your task is to determine the size of the rectangular display β the number of lines (rows) of pixels a and the number of columns of pixels b, so that:
* there are exactly n pixels on the display;
* the number of rows does not exceed the number of columns, it means a β€ b;
* the difference b - a is as small as possible.
Input
The first line contains the positive integer n (1 β€ n β€ 106) β the number of pixels display should have.
Output
Print two integers β the number of rows and columns on the display.
Examples
Input
8
Output
2 4
Input
64
Output
8 8
Input
5
Output
1 5
Input
999999
Output
999 1001
Note
In the first example the minimum possible difference equals 2, so on the display should be 2 rows of 4 pixels.
In the second example the minimum possible difference equals 0, so on the display should be 8 rows of 8 pixels.
In the third example the minimum possible difference equals 4, so on the display should be 1 row of 5 pixels.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long int i, j, n, t;
cin >> n;
for (i = 1; i * i <= n; i++)
if (n % i == 0) j = i;
cout << j << " " << n / j;
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
There are N positive integers A_1, A_2, ..., A_N. Takahashi can perform the following operation on these integers any number of times:
* Choose 1 \leq i \leq N and multiply the value of A_i by -2.
Notice that he multiplies it by minus two.
He would like to make A_1 \leq A_2 \leq ... \leq A_N holds. Find the minimum number of operations required. If it is impossible, print `-1`.
Constraints
* 1 \leq N \leq 200000
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the answer.
Examples
Input
4
3 1 4 1
Output
3
Input
5
1 2 3 4 5
Output
0
Input
8
657312726 129662684 181537270 324043958 468214806 916875077 825989291 319670097
Output
7
### Response
```cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
#include <utility>
#define mp make_pair
#define maxn 200005
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int inf = 0x3f3f3f3f;
int n;
ll a[maxn],fir[maxn],lst[maxn];
P pos[maxn];//id,val.
int ta;
int dif(ll x,ll y){
ll cnt = 0;
while(x <= y){
x <<= 2;
cnt++;
}
return cnt - 1;
}
ll mul4(int x){
ll ret = pos[ta].first - x + 1;
pos[ta].second--;
if(pos[ta].second == 0) ta--;
return ret;
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%lld",&a[i]);
lst[n] = 0;
pos[++ta] = mp(n,inf);
for(int i=n - 1;i>=1;i--){
lst[i] = lst[i + 1];
if(a[i] <= a[i + 1]){
int val = dif(a[i],a[i + 1]);
if(val) pos[++ta] = mp(i,val);
}else{
ll tmp = a[i + 1];
while(tmp < a[i]){
lst[i] += mul4(i + 1) * 2;
tmp <<= 2;
}
}
}
for(int i=1;i<=n;i++) a[i] *= 2;
reverse(a + 1,a + n + 1);
// for(int i=1;i<=n;i++){
// cout << a[i] << " ";
// }
// system("pause");
ta = 0;
fir[n] = 0;
pos[++ta] = mp(n,inf);
for(int i=n - 1;i>=1;i--){
fir[i] = fir[i + 1];
if(a[i] <= a[i + 1]){
int val = dif(a[i],a[i + 1]);
if(val) pos[++ta] = mp(i,val);
}else{
ll tmp = a[i + 1];
while(tmp < a[i]){
fir[i] += mul4(i + 1) * 2;
tmp <<= 2;
}
}
}
reverse(fir + 1,fir + n + 1);
for(int i=1;i<=n;i++) fir[i] += i;
ll ans = 0x3f3f3f3f3f3f3f3fll;
for(int i=1;i<=n + 1;i++){
ans = min(ans,fir[i - 1] + lst[i]);
}
printf("%lld\n",ans);
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.
Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.
The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.
Each customer is characterized by three values: t_i β the time (in minutes) when the i-th customer visits the restaurant, l_i β the lower bound of their preferred temperature range, and h_i β the upper bound of their preferred temperature range.
A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the i-th customer is satisfied if and only if the temperature is between l_i and h_i (inclusive) in the t_i-th minute.
Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
Input
Each test contains one or more test cases. The first line contains the number of test cases q (1 β€ q β€ 500). Description of the test cases follows.
The first line of each test case contains two integers n and m (1 β€ n β€ 100, -10^9 β€ m β€ 10^9), where n is the number of reserved customers and m is the initial temperature of the restaurant.
Next, n lines follow. The i-th line of them contains three integers t_i, l_i, and h_i (1 β€ t_i β€ 10^9, -10^9 β€ l_i β€ h_i β€ 10^9), where t_i is the time when the i-th customer visits, l_i is the lower bound of their preferred temperature range, and h_i is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.
The customers are given in non-decreasing order of their visit time, and the current time is 0.
Output
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
Output
YES
NO
YES
NO
Note
In the first case, Gildong can control the air conditioner to satisfy all customers in the following way:
* At 0-th minute, change the state to heating (the temperature is 0).
* At 2-nd minute, change the state to off (the temperature is 2).
* At 5-th minute, change the state to heating (the temperature is 2, the 1-st customer is satisfied).
* At 6-th minute, change the state to off (the temperature is 3).
* At 7-th minute, change the state to cooling (the temperature is 3, the 2-nd customer is satisfied).
* At 10-th minute, the temperature will be 0, which satisfies the last customer.
In the third case, Gildong can change the state to heating at 0-th minute and leave it be. Then all customers will be satisfied. Note that the 1-st customer's visit time equals the 2-nd customer's visit time.
In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int z, x, n, m, w, h, cas, a[1000], b[1000], c[1000];
int main() {
scanf("%d", &cas);
while (cas--) {
scanf("%d%d", &z, &x);
for (int i = 1; i <= z; i++) scanf("%d%d%d", &a[i], &b[i], &c[i]);
n = x;
m = x;
w = 0;
for (int i = 1; i <= z; i++) {
n = n - (a[i] - w);
m = m + (a[i] - w);
if (b[i] > n) n = b[i];
if (c[i] < m) m = c[i];
if (n > m) break;
w = a[i];
}
if (n > m)
printf("NO\n");
else
printf("YES\n");
}
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Amr doesn't like Maths as he finds it really boring, so he usually sleeps in Maths lectures. But one day the teacher suspected that Amr is sleeping and asked him a question to make sure he wasn't.
First he gave Amr two positive integers n and k. Then he asked Amr, how many integer numbers x > 0 exist such that:
* Decimal representation of x (without leading zeroes) consists of exactly n digits;
* There exists some integer y > 0 such that:
* <image>;
* decimal representation of y is a suffix of decimal representation of x.
As the answer to this question may be pretty huge the teacher asked Amr to output only its remainder modulo a number m.
Can you help Amr escape this embarrassing situation?
Input
Input consists of three integers n, k, m (1 β€ n β€ 1000, 1 β€ k β€ 100, 1 β€ m β€ 109).
Output
Print the required number modulo m.
Examples
Input
1 2 1000
Output
4
Input
2 2 1000
Output
45
Input
5 3 1103
Output
590
Note
A suffix of a string S is a non-empty string that can be obtained by removing some number (possibly, zero) of first characters from S.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int INF = 1 << 29;
const long long LINF = 1LL << 60;
const double inf = 1e15;
long long mod = 1e9 + 7;
char READ_DATA;
int SIGNAL_INPUT;
template <typename Type>
inline Type ru(Type &v) {
SIGNAL_INPUT = 1;
while ((READ_DATA = getchar()) < '0' || READ_DATA > '9')
if (READ_DATA == '-')
SIGNAL_INPUT = -1;
else if (READ_DATA == EOF)
return EOF;
v = READ_DATA - '0';
while ((READ_DATA = getchar()) >= '0' && READ_DATA <= '9')
v = v * 10 + READ_DATA - '0';
v *= SIGNAL_INPUT;
return v;
}
inline long long modru(long long &v) {
long long p = 0;
SIGNAL_INPUT = 1;
while ((READ_DATA = getchar()) < '0' || READ_DATA > '9')
if (READ_DATA == '-')
SIGNAL_INPUT = -1;
else if (READ_DATA == EOF)
return EOF;
p = v = READ_DATA - '0';
while ((READ_DATA = getchar()) >= '0' && READ_DATA <= '9') {
v = (v * 10 + READ_DATA - '0') % mod;
p = (p * 10 + READ_DATA - '0') % (mod - 1);
}
v *= SIGNAL_INPUT;
return p;
}
template <typename A, typename B>
inline char ru(A &x, B &y) {
if (ru(x) == EOF) return EOF;
ru(y);
return 2;
}
template <typename A, typename B, typename C>
inline char ru(A &x, B &y, C &z) {
if (ru(x) == EOF) return EOF;
ru(y);
ru(z);
return 3;
}
template <typename A, typename B, typename C, typename D>
inline char ru(A &x, B &y, C &z, D &w) {
if (ru(x) == EOF) return EOF;
ru(y);
ru(z);
ru(w);
return 4;
}
struct Edge {
int u, v, next;
long long w, cap, flow;
Edge(int _u = 0, int _v = 0, int nxt = -1, long long _w = 1,
long long _cap = 0) {
u = _u;
v = _v;
w = _w;
cap = _cap;
flow = 0;
next = nxt;
}
int operator<(const Edge &b) const { return w < b.w; }
};
const int maxn = 1e3 + 10, N = 2e6 + 1;
double eps = 1e-7, pi = acos(-1.0);
unsigned long long seed = 131, smod = (1LL << 32) - 267;
long long n, k, m;
long long f[maxn][100][2];
long long power[maxn];
int main() {
ru(n, k, m);
power[0] = 1 % k;
for (register int i = 1; i <= n; ++i) power[i] = power[i - 1] * 10 % k;
f[0][0][0] = 1;
for (register int i = 0; i < n; ++i)
for (register int j = 0; j < k; ++j) {
for (register int r = (i == n - 1); r < 10; ++r) {
long long tmp = (r * power[i] + j) % k;
if (tmp == 0 && r != 0)
(f[i + 1][tmp][1] += f[i][j][0]) %= m;
else
(f[i + 1][tmp][0] += f[i][j][0]) %= m;
(f[i + 1][tmp][1] += f[i][j][1]) %= m;
}
}
long long ans = 0;
for (register int j = 0; j < k; ++j) (ans += f[n][j][1]) %= m;
cout << ans;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Little girl Masha likes winter sports, today she's planning to take part in slalom skiing.
The track is represented as a grid composed of n Γ m squares. There are rectangular obstacles at the track, composed of grid squares. Masha must get from the square (1, 1) to the square (n, m). She can move from a square to adjacent square: either to the right, or upwards. If the square is occupied by an obstacle, it is not allowed to move to that square.
One can see that each obstacle can actually be passed in two ways: either it is to the right of Masha's path, or to the left. Masha likes to try all ways to do things, so she would like to know how many ways are there to pass the track. Two ways are considered different if there is an obstacle such that it is to the right of the path in one way, and to the left of the path in the other way.
Help Masha to find the number of ways to pass the track. The number of ways can be quite big, so Masha would like to know it modulo 109 + 7.
The pictures below show different ways to pass the track in sample tests. <image> <image> <image>
Input
The first line of input data contains three positive integers: n, m and k (3 β€ n, m β€ 106, 0 β€ k β€ 105) β the size of the track and the number of obstacles.
The following k lines contain four positive integers each: x1, y1, x2, y2 (1 β€ x1 β€ x2 β€ n, 1 β€ y1 β€ y2 β€ m) β coordinates of bottom left, and top right squares of the obstacle.
It is guaranteed that there are no obstacles at squares (1, 1) and (n, m), and no obstacles overlap (but some of them may touch).
Output
Output one integer β the number of ways to pass the track modulo 109 + 7.
Examples
Input
3 3 0
Output
1
Input
4 5 1
2 2 3 4
Output
2
Input
5 5 3
2 2 2 3
4 2 5 2
4 4 4 4
Output
3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int P = 1000000007;
const int maxk = 100010;
const int maxn = 1000010;
int n, m, k, tot;
struct node {
int x, l, r, k;
} p[maxk * 3];
int s[maxn << 2], tag[maxn << 2], siz[maxn << 2];
bool cmp(const node &a, const node &b) {
return (a.x == b.x) ? ((a.k == b.k) ? (a.l > b.l) : (a.k < b.k))
: (a.x < b.x);
}
inline void pushdown(int l, int r, int x) {
if (tag[x] == 1) {
s[x << 1] = s[x << 1 | 1] = 0, tag[x << 1] = tag[x << 1 | 1] = 1;
int mid = (l + r) >> 1;
siz[x << 1] = mid - l + 1, siz[x << 1 | 1] = r - mid, tag[x] = 0;
}
if (tag[x] == 2) {
s[x << 1] = s[x << 1 | 1] = 0, tag[x << 1] = tag[x << 1 | 1] = 2,
siz[x << 1] = siz[x << 1 | 1] = 0, tag[x] = 0;
}
}
inline void pushup(int x) {
s[x] = s[x << 1] + s[x << 1 | 1], siz[x] = siz[x << 1] + siz[x << 1 | 1];
if (s[x] >= P) s[x] -= P;
}
void modify(int l, int r, int x, int a, int b) {
if (l == r) {
s[x] = b;
return;
}
pushdown(l, r, x);
int mid = (l + r) >> 1;
if (a <= mid)
modify(l, mid, x << 1, a, b);
else
modify(mid + 1, r, x << 1 | 1, a, b);
pushup(x);
}
void updata(int l, int r, int x, int a, int b, int c) {
if (a <= l && r <= b) {
if (c == 1)
tag[x] = 1, siz[x] = r - l + 1, s[x] = 0;
else
tag[x] = 2, siz[x] = s[x] = 0;
return;
}
pushdown(l, r, x);
int mid = (l + r) >> 1;
if (a <= mid) updata(l, mid, x << 1, a, b, c);
if (b > mid) updata(mid + 1, r, x << 1 | 1, a, b, c);
pushup(x);
}
int query(int l, int r, int x, int a, int b) {
if (a <= l && r <= b) return s[x];
pushdown(l, r, x);
int mid = (l + r) >> 1, ret = 0;
if (a <= mid) ret += query(l, mid, x << 1, a, b);
if (b > mid) ret += query(mid + 1, r, x << 1 | 1, a, b);
if (ret >= P) ret -= P;
return ret;
}
int count(int l, int r, int x, int a, int b) {
if (a <= l && r <= b) return siz[x];
pushdown(l, r, x);
int mid = (l + r) >> 1;
if (b <= mid) return count(l, mid, x << 1, a, b);
if (a > mid) return count(mid + 1, r, x << 1 | 1, a, b);
return count(l, mid, x << 1, a, b) + count(mid + 1, r, x << 1 | 1, a, b);
}
int find(int l, int r, int x, int a) {
if (l == r) return l;
pushdown(l, r, x);
int mid = (l + r) >> 1;
if (a <= siz[x << 1]) return find(l, mid, x << 1, a);
return find(mid + 1, r, x << 1 | 1, a - siz[x << 1]);
}
inline int rd() {
int ret = 0, f = 1;
char gc = getchar();
while (gc < '0' || gc > '9') {
if (gc == '-') f = -f;
gc = getchar();
}
while (gc >= '0' && gc <= '9') ret = ret * 10 + (gc ^ '0'), gc = getchar();
return ret * f;
}
int main() {
n = rd(), m = rd(), k = rd();
int i, a, b, c, d;
for (i = 1; i <= k; i++) {
a = rd(), b = rd(), c = rd(), d = rd();
p[++tot].x = a, p[tot].l = b, p[tot].r = d, p[tot].k = 2;
p[++tot].x = a + 1, p[tot].l = b, p[tot].r = d, p[tot].k = 1;
p[++tot].x = c + 1, p[tot].l = b, p[tot].r = d, p[tot].k = 3;
}
p[++tot].x = 1, p[tot].l = 2, p[tot].r = m, p[tot].k = 1;
p[++tot].x = 1, p[tot].l = 2, p[tot].r = m, p[tot].k = 3;
p[++tot].x = n + 1, p[tot].l = 1, p[tot].r = m - 1, p[tot].k = 2;
sort(p + 1, p + tot + 1, cmp);
modify(1, m, 1, 1, 1);
for (a = 1; a <= tot; a = b + 1) {
for (b = a; b < tot && p[b + 1].x == p[b].x && p[b + 1].k == p[b].k; b++)
;
if (p[a].k == 2) {
for (i = a; i <= b; i++)
if (p[i].r != m) {
c = count(1, m, 1, 1, p[i].r + 1);
if (!c)
d = 0;
else
d = find(1, m, 1, c);
if (d != p[i].r + 1) {
modify(1, m, 1, p[i].r + 1, query(1, m, 1, d + 1, p[i].r + 1));
}
}
} else if (p[a].k == 1) {
for (i = a; i <= b; i++) updata(1, m, 1, p[i].l, p[i].r, 1);
} else {
for (i = a; i <= b; i++) updata(1, m, 1, p[i].l, p[i].r, 2);
}
}
printf("%d", query(1, m, 1, m, m));
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
In Berland each feudal owns exactly one castle and each castle belongs to exactly one feudal.
Each feudal, except one (the King) is subordinate to another feudal. A feudal can have any number of vassals (subordinates).
Some castles are connected by roads, it is allowed to move along the roads in both ways. Two castles have a road between them if and only if the owner of one of these castles is a direct subordinate to the other owner.
Each year exactly one of these two events may happen in Berland.
1. The barbarians attacked castle c. The interesting fact is, the barbarians never attacked the same castle twice throughout the whole Berlandian history.
2. A noble knight sets off on a journey from castle a to castle b (provided that on his path he encounters each castle not more than once).
Let's consider the second event in detail. As the journey from a to b is not short, then the knight might want to stop at a castle he encounters on his way to have some rest. However, he can't stop at just any castle: his nobility doesn't let him stay in the castle that has been desecrated by the enemy's stench. A castle is desecrated if and only if it has been attacked after the year of y. So, the knight chooses the k-th castle he encounters, starting from a (castles a and b aren't taken into consideration), that hasn't been attacked in years from y + 1 till current year.
The knights don't remember which castles were attacked on what years, so he asked the court scholar, aka you to help them. You've got a sequence of events in the Berland history. Tell each knight, in what city he should stop or else deliver the sad news β that the path from city a to city b has less than k cities that meet his requirements, so the knight won't be able to rest.
Input
The first input line contains integer n (2 β€ n β€ 105) β the number of feudals.
The next line contains n space-separated integers: the i-th integer shows either the number of the i-th feudal's master, or a 0, if the i-th feudal is the King.
The third line contains integer m (1 β€ m β€ 105) β the number of queries.
Then follow m lines that describe the events. The i-th line (the lines are indexed starting from 1) contains the description of the event that occurred in year i. Each event is characterised by type ti (1 β€ ti β€ 2). The description of the first type event looks as two space-separated integers ti ci (ti = 1; 1 β€ ci β€ n), where ci is the number of the castle that was attacked by the barbarians in the i-th year. The description of the second type contains five space-separated integers: ti ai bi ki yi (ti = 2; 1 β€ ai, bi, ki β€ n; ai β bi; 0 β€ yi < i), where ai is the number of the castle from which the knight is setting off, bi is the number of the castle to which the knight is going, ki and yi are the k and y from the second event's description.
You can consider the feudals indexed from 1 to n. It is guaranteed that there is only one king among the feudals. It is guaranteed that for the first type events all values ci are different.
Output
For each second type event print an integer β the number of the castle where the knight must stay to rest, or -1, if he will have to cover the distance from ai to bi without a rest. Separate the answers by whitespaces.
Print the answers in the order, in which the second type events are given in the input.
Examples
Input
3
0 1 2
5
2 1 3 1 0
1 2
2 1 3 1 0
2 1 3 1 1
2 1 3 1 2
Output
2
-1
-1
2
Input
6
2 5 2 2 0 5
3
2 1 6 2 0
1 2
2 4 5 1 0
Output
5
-1
Note
In the first sample there is only castle 2 on the knight's way from castle 1 to castle 3. When the knight covers the path 1 - 3 for the first time, castle 2 won't be desecrated by an enemy and the knight will stay there. In the second year the castle 2 will become desecrated, so the knight won't have anywhere to stay for the next two years (as finding a castle that hasn't been desecrated from years 1 and 2, correspondingly, is important for him). In the fifth year the knight won't consider the castle 2 desecrated, so he will stay there again.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#pragma comment(linker, "/STACK:36777216")
template <class T>
inline void RD(T &);
template <class T>
inline void OT(const T &);
inline long long RD() {
long long x;
RD(x);
return x;
}
template <class T>
inline T &_RD(T &x) {
RD(x);
return x;
}
inline void RC(char &c) { scanf(" %c", &c); }
inline char RC() {
char c;
RC(c);
return c;
}
inline char _RC(char &c) {
RC(c);
return c;
}
inline void RF(double &x) { scanf("%lf", &x); };
inline double RF() {
double x;
RF(x);
return x;
}
inline double _RF(double &x) {
RD(x);
return x;
}
inline void RS(char *s) { scanf("%s", s); }
inline char *_RS(char *s) {
scanf("%s", s);
return s;
}
template <class T0, class T1>
inline void RD(T0 &x0, T1 &x1) {
RD(x0), RD(x1);
}
template <class T0, class T1, class T2>
inline void RD(T0 &x0, T1 &x1, T2 &x2) {
RD(x0), RD(x1), RD(x2);
}
template <class T0, class T1, class T2, class T3>
inline void RD(T0 &x0, T1 &x1, T2 &x2, T3 &x3) {
RD(x0), RD(x1), RD(x2), RD(x3);
}
template <class T0, class T1, class T2, class T3, class T4>
inline void RD(T0 &x0, T1 &x1, T2 &x2, T3 &x3, T4 &x4) {
RD(x0), RD(x1), RD(x2), RD(x3), RD(x4);
}
template <class T0, class T1, class T2, class T3, class T4, class T5>
inline void RD(T0 &x0, T1 &x1, T2 &x2, T3 &x3, T4 &x4, T5 &x5) {
RD(x0), RD(x1), RD(x2), RD(x3), RD(x4), RD(x5);
}
template <class T0, class T1, class T2, class T3, class T4, class T5, class T6>
inline void RD(T0 &x0, T1 &x1, T2 &x2, T3 &x3, T4 &x4, T5 &x5, T6 &x6) {
RD(x0), RD(x1), RD(x2), RD(x3), RD(x4), RD(x5), RD(x6);
}
template <class T0, class T1>
inline void OT(T0 &x0, T1 &x1) {
OT(x0), OT(x1);
}
template <class T0, class T1, class T2>
inline void OT(T0 &x0, T1 &x1, T2 &x2) {
OT(x0), OT(x1), OT(x2);
}
template <class T0, class T1, class T2, class T3>
inline void OT(T0 &x0, T1 &x1, T2 &x2, T3 &x3) {
OT(x0), OT(x1), OT(x2), OT(x3);
}
template <class T0, class T1, class T2, class T3, class T4>
inline void OT(T0 &x0, T1 &x1, T2 &x2, T3 &x3, T4 &x4) {
OT(x0), OT(x1), OT(x2), OT(x3), OT(x4);
}
template <class T0, class T1, class T2, class T3, class T4, class T5>
inline void OT(T0 &x0, T1 &x1, T2 &x2, T3 &x3, T4 &x4, T5 &x5) {
OT(x0), OT(x1), OT(x2), OT(x3), OT(x4), OT(x5);
}
template <class T0, class T1, class T2, class T3, class T4, class T5, class T6>
inline void OT(T0 &x0, T1 &x1, T2 &x2, T3 &x3, T4 &x4, T5 &x5, T6 &x6) {
OT(x0), OT(x1), OT(x2), OT(x3), OT(x4), OT(x5), OT(x6);
}
inline void RF(double &a, double &b) { RF(a), RF(b); }
inline void RF(double &a, double &b, double &c) { RF(a), RF(b), RF(c); }
inline void RS(char *s1, char *s2) { RS(s1), RS(s2); }
inline void RS(char *s1, char *s2, char *s3) { RS(s1), RS(s2), RS(s3); }
template <class T>
inline void RST(T &A) {
memset(A, 0, sizeof(A));
}
template <class T0, class T1>
inline void RST(T0 &A0, T1 &A1) {
RST(A0), RST(A1);
}
template <class T0, class T1, class T2>
inline void RST(T0 &A0, T1 &A1, T2 &A2) {
RST(A0), RST(A1), RST(A2);
}
template <class T0, class T1, class T2, class T3>
inline void RST(T0 &A0, T1 &A1, T2 &A2, T3 &A3) {
RST(A0), RST(A1), RST(A2), RST(A3);
}
template <class T0, class T1, class T2, class T3, class T4>
inline void RST(T0 &A0, T1 &A1, T2 &A2, T3 &A3, T4 &A4) {
RST(A0), RST(A1), RST(A2), RST(A3), RST(A4);
}
template <class T0, class T1, class T2, class T3, class T4, class T5>
inline void RST(T0 &A0, T1 &A1, T2 &A2, T3 &A3, T4 &A4, T5 &A5) {
RST(A0), RST(A1), RST(A2), RST(A3), RST(A4), RST(A5);
}
template <class T0, class T1, class T2, class T3, class T4, class T5, class T6>
inline void RST(T0 &A0, T1 &A1, T2 &A2, T3 &A3, T4 &A4, T5 &A5, T6 &A6) {
RST(A0), RST(A1), RST(A2), RST(A3), RST(A4), RST(A5), RST(A6);
}
template <class T>
inline void CLR(priority_queue<T, vector<T>, less<T> > &Q) {
while (!Q.empty()) Q.pop();
}
template <class T>
inline void CLR(priority_queue<T, vector<T>, greater<T> > &Q) {
while (!Q.empty()) Q.pop();
}
template <class T>
inline void CLR(T &A) {
A.clear();
}
template <class T0, class T1>
inline void CLR(T0 &A0, T1 &A1) {
CLR(A0), CLR(A1);
}
template <class T0, class T1, class T2>
inline void CLR(T0 &A0, T1 &A1, T2 &A2) {
CLR(A0), CLR(A1), CLR(A2);
}
template <class T0, class T1, class T2, class T3>
inline void CLR(T0 &A0, T1 &A1, T2 &A2, T3 &A3) {
CLR(A0), CLR(A1), CLR(A2), CLR(A3);
}
template <class T0, class T1, class T2, class T3, class T4>
inline void CLR(T0 &A0, T1 &A1, T2 &A2, T3 &A3, T4 &A4) {
CLR(A0), CLR(A1), CLR(A2), CLR(A3), CLR(A4);
}
template <class T0, class T1, class T2, class T3, class T4, class T5>
inline void CLR(T0 &A0, T1 &A1, T2 &A2, T3 &A3, T4 &A4, T5 &A5) {
CLR(A0), CLR(A1), CLR(A2), CLR(A3), CLR(A4), CLR(A5);
}
template <class T0, class T1, class T2, class T3, class T4, class T5, class T6>
inline void CLR(T0 &A0, T1 &A1, T2 &A2, T3 &A3, T4 &A4, T5 &A5, T6 &A6) {
CLR(A0), CLR(A1), CLR(A2), CLR(A3), CLR(A4), CLR(A5), CLR(A6);
}
template <class T>
inline void CLR(T &A, int n) {
for (int i = 0; i < int(n); ++i) CLR(A[i]);
}
template <class T>
inline void FLC(T &A, int x) {
memset(A, x, sizeof(A));
}
template <class T0, class T1>
inline void FLC(T0 &A0, T1 &A1, int x) {
FLC(A0, x), FLC(A1, x);
}
template <class T0, class T1, class T2>
inline void FLC(T0 &A0, T1 &A1, T2 &A2) {
FLC(A0), FLC(A1), FLC(A2);
}
template <class T0, class T1, class T2, class T3>
inline void FLC(T0 &A0, T1 &A1, T2 &A2, T3 &A3) {
FLC(A0), FLC(A1), FLC(A2), FLC(A3);
}
template <class T0, class T1, class T2, class T3, class T4>
inline void FLC(T0 &A0, T1 &A1, T2 &A2, T3 &A3, T4 &A4) {
FLC(A0), FLC(A1), FLC(A2), FLC(A3), FLC(A4);
}
template <class T0, class T1, class T2, class T3, class T4, class T5>
inline void FLC(T0 &A0, T1 &A1, T2 &A2, T3 &A3, T4 &A4, T5 &A5) {
FLC(A0), FLC(A1), FLC(A2), FLC(A3), FLC(A4), FLC(A5);
}
template <class T0, class T1, class T2, class T3, class T4, class T5, class T6>
inline void FLC(T0 &A0, T1 &A1, T2 &A2, T3 &A3, T4 &A4, T5 &A5, T6 &A6) {
FLC(A0), FLC(A1), FLC(A2), FLC(A3), FLC(A4), FLC(A5), FLC(A6);
}
template <class T>
inline void SRT(T &A) {
sort(A.begin(), A.end());
}
template <class T, class C>
inline void SRT(T &A, C B) {
sort(A.begin(), A.end(), B);
}
const int MOD = 1000000007;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-9;
const double OO = 1e15;
const double PI = acos(-1.0);
template <class T>
inline void checkMin(T &a, const T b) {
if (b < a) a = b;
}
template <class T>
inline void checkMax(T &a, const T b) {
if (b > a) a = b;
}
template <class T, class C>
inline void checkMin(T &a, const T b, C c) {
if (c(b, a)) a = b;
}
template <class T, class C>
inline void checkMax(T &a, const T b, C c) {
if (c(a, b)) a = b;
}
template <class T>
inline T min(T a, T b, T c) {
return min(min(a, b), c);
}
template <class T>
inline T max(T a, T b, T c) {
return max(max(a, b), c);
}
template <class T>
inline T min(T a, T b, T c, T d) {
return min(min(a, b), min(c, d));
}
template <class T>
inline T max(T a, T b, T c, T d) {
return max(max(a, b), max(c, d));
}
template <class T>
inline T sqr(T a) {
return a * a;
}
template <class T>
inline T cub(T a) {
return a * a * a;
}
int Ceil(int x, int y) { return (x - 1) / y + 1; }
inline bool _1(int x, int i) { return x & 1 << i; }
inline bool _1(long long x, int i) { return x & 1LL << i; }
inline long long _1(int i) { return 1LL << i; }
inline long long _U(int i) { return _1(i) - 1; };
template <class T>
inline T low_bit(T x) {
return x & -x;
}
template <class T>
inline T high_bit(T x) {
T p = low_bit(x);
while (p != x) x -= p, p = low_bit(x);
return p;
}
template <class T>
inline T cover_bit(T x) {
T p = 1;
while (p < x) p <<= 1;
return p;
}
inline int count_bits(int x) {
x = (x & 0x55555555) + ((x & 0xaaaaaaaa) >> 1);
x = (x & 0x33333333) + ((x & 0xcccccccc) >> 2);
x = (x & 0x0f0f0f0f) + ((x & 0xf0f0f0f0) >> 4);
x = (x & 0x00ff00ff) + ((x & 0xff00ff00) >> 8);
x = (x & 0x0000ffff) + ((x & 0xffff0000) >> 16);
return x;
}
inline int count_bits(long long x) {
x = (x & 0x5555555555555555LL) + ((x & 0xaaaaaaaaaaaaaaaaLL) >> 1);
x = (x & 0x3333333333333333LL) + ((x & 0xccccccccccccccccLL) >> 2);
x = (x & 0x0f0f0f0f0f0f0f0fLL) + ((x & 0xf0f0f0f0f0f0f0f0LL) >> 4);
x = (x & 0x00ff00ff00ff00ffLL) + ((x & 0xff00ff00ff00ff00LL) >> 8);
x = (x & 0x0000ffff0000ffffLL) + ((x & 0xffff0000ffff0000LL) >> 16);
x = (x & 0x00000000ffffffffLL) + ((x & 0xffffffff00000000LL) >> 32);
return x;
}
int reverse_bits(int x) {
x = ((x >> 1) & 0x55555555) | ((x << 1) & 0xaaaaaaaa);
x = ((x >> 2) & 0x33333333) | ((x << 2) & 0xcccccccc);
x = ((x >> 4) & 0x0f0f0f0f) | ((x << 4) & 0xf0f0f0f0);
x = ((x >> 8) & 0x00ff00ff) | ((x << 8) & 0xff00ff00);
x = ((x >> 16) & 0x0000ffff) | ((x << 16) & 0xffff0000);
return x;
}
long long reverse_bits(long long x) {
x = ((x >> 1) & 0x5555555555555555LL) | ((x << 1) & 0xaaaaaaaaaaaaaaaaLL);
x = ((x >> 2) & 0x3333333333333333LL) | ((x << 2) & 0xccccccccccccccccLL);
x = ((x >> 4) & 0x0f0f0f0f0f0f0f0fLL) | ((x << 4) & 0xf0f0f0f0f0f0f0f0LL);
x = ((x >> 8) & 0x00ff00ff00ff00ffLL) | ((x << 8) & 0xff00ff00ff00ff00LL);
x = ((x >> 16) & 0x0000ffff0000ffffLL) | ((x << 16) & 0xffff0000ffff0000LL);
x = ((x >> 32) & 0x00000000ffffffffLL) | ((x << 32) & 0xffffffff00000000LL);
return x;
}
inline void INC(int &a, int b) {
a += b;
if (a >= MOD) a -= MOD;
}
inline int sum(int a, int b) {
a += b;
if (a >= MOD) a -= MOD;
return a;
}
inline void DEC(int &a, int b) {
a -= b;
if (a < 0) a += MOD;
}
inline int dff(int a, int b) {
a -= b;
if (a < 0) a += MOD;
return a;
}
inline void MUL(int &a, int b) { a = (long long)a * b % MOD; }
inline int pdt(int a, int b) { return (long long)a * b % MOD; }
inline int sum(int a, int b, int c) { return sum(sum(a, b), c); }
inline int sum(int a, int b, int c, int d) { return sum(sum(a, b), sum(c, d)); }
inline int pow(int a, long long b) {
int c(1);
while (b) {
if (b & 1) MUL(c, a);
MUL(a, a), b >>= 1;
}
return c;
}
template <class T>
inline T pow(T a, long long b) {
T c(1);
while (b) {
if (b & 1) c *= a;
a *= a, b >>= 1;
}
return c;
}
inline int _I(int b) {
int a = MOD, x1 = 0, x2 = 1, q;
while (true) {
q = a / b, a %= b;
if (!a) return (x2 + MOD) % MOD;
DEC(x1, pdt(q, x2));
q = b / a, b %= a;
if (!b) return (x1 + MOD) % MOD;
DEC(x2, pdt(q, x1));
}
}
inline void DIA(int &a, int b) { MUL(a, _I(b)); }
inline int qtt(int a, int b) { return pdt(a, _I(b)); }
inline int phi(int n) {
int res = n;
for (int i = 2; sqr(i) <= n; ++i)
if (!(n % i)) {
DEC(res, qtt(res, i));
do {
n /= i;
} while (!(n % i));
}
if (n != 1) DEC(res, qtt(res, n));
return res;
}
inline int rand32() {
return (bool(rand() & 1) << 30) | (rand() << 15) + rand();
}
inline int random32(int l, int r) { return rand32() % (r - l + 1) + l; }
inline int random(int l, int r) { return rand() % (r - l + 1) + l; }
int dice() { return rand() % 6; }
bool coin() { return rand() % 2; }
template <class T>
inline void RD(T &x) {
char c;
for (c = getchar(); c < '0'; c = getchar())
;
x = c - '0';
for (c = getchar(); c >= '0'; c = getchar()) x = x * 10 + c - '0';
}
int ____Case;
template <class T>
inline void OT(const T &x) {
printf("%d ", x);
}
const int N = 100009, L = 17, NN = N * L * 10;
int n, m, root;
int fa[N][20], dep[N];
vector<int> adj[N];
int a[N], beg[N], en[N], cnt;
int destroy[N];
int l[NN], r[NN], c[NN], total;
int T[N], Null;
int Insert(int y, int p) {
int x = ++total, root = x;
c[x] = c[y] + 1;
int ll = 1, rr = n;
while (ll <= rr) {
if (p <= ((ll + rr) >> 1)) {
l[x] = ++total, r[x] = r[y];
x = l[x], y = l[y], rr = ((ll + rr) >> 1);
} else {
l[x] = l[y], r[x] = ++total;
x = r[x], y = r[y], ll = ((ll + rr) >> 1) + 1;
}
c[x] = c[y] + 1;
}
return root;
}
inline int Sum(int x, int p) {
int ll = 1, rr = n, res = 0;
while (ll <= rr) {
res += c[x];
if (p <= ((ll + rr) >> 1))
x = l[x], rr = ((ll + rr) >> 1);
else
x = r[x], ll = ((ll + rr) >> 1) + 1;
}
return res;
}
inline int Sum(int x, int l, int r) { return Sum(x, r) - Sum(x, l); }
struct Tnode {
Tnode *l, *r;
int segl, segr, val;
Tnode(int _segl = 0, int _segr = 0, int _val = 0)
: l(0), r(0), segl(_segl), segr(_segr), val(_val) {}
} pool[N * 20], *cur = pool, *tree[N];
void insert(Tnode *&root, int segl, int segr, int ql, int qr, int plus) {
*cur = Tnode(segl, segr);
if (root) *cur = *root;
root = cur++;
if (ql <= segl && segr <= qr) {
root->val += plus;
return;
}
int smid = (segl + segr) / 2;
if (ql <= smid) insert(root->l, segl, smid, ql, qr, plus);
if (qr > smid) insert(root->r, smid + 1, segr, ql, qr, plus);
}
int getval(Tnode *t1, int id) {
if (!t1) return 0;
if (id <= (t1->segl + t1->segr) / 2)
return getval(t1->l, id) + t1->val;
else
return getval(t1->r, id) + t1->val;
}
int move_up(int x, int t) {
for (int i = 0; i < L && t; ++i, t >>= 1)
if (t & 1) x = fa[x][i];
return x;
}
inline int lca(int x, int y) {
if (dep[x] > dep[y])
x = move_up(x, dep[x] - dep[y]);
else
y = move_up(y, dep[y] - dep[x]);
if (x == y)
return x;
else {
for (int i = int(L - 1); i >= int(0); --i)
if (fa[x][i] != fa[y][i]) x = fa[x][i], y = fa[y][i];
return fa[x][0];
}
}
int count(int o, int A, int B, int Y) {
return (getval(tree[o], beg[A]) - (beg[B] ? getval(tree[o], beg[B]) : 0)) -
(getval(tree[Y], beg[A]) - (beg[B] ? getval(tree[Y], beg[B]) : 0));
}
void dfs(int u = root) {
a[beg[u] = ++cnt] = u;
for (int i = 0; i < int(int(adj[u].size())); ++i) {
dep[adj[u][i]] = dep[u] + 1;
for (int lv = int(1); lv < int(L); ++lv) {
fa[adj[u][i]][lv] = fa[fa[adj[u][i]][lv - 1]][lv - 1];
if (!fa[adj[u][i]][lv]) break;
}
dfs(adj[u][i]);
}
en[u] = cnt;
}
int main() {
for (int n____ = int(_RD(n)), i = 1; i <= n____; ++i) {
if (!_RD(fa[i][0]))
root = i;
else
adj[fa[i][0]].push_back(i);
}
dep[root] = 1, dfs();
for (int n____ = int(_RD(m)), o = 1; o <= n____; ++o) {
int option, A, B, K, Y, C;
scanf("%d", &option);
tree[o] = tree[o - 1];
if (option == 1) {
scanf("%d", &C);
insert(tree[o], 1, n, beg[C], en[C], 1);
destroy[C] = o;
} else {
RD(A, B, K, Y);
int _A = A, _B = B;
C = lca(A, B);
int cnt_AC = (dep[A] - dep[C] + 1) - count(o, A, fa[C][0], Y),
cnt_CB = (dep[B] - dep[C]) - count(o, B, C, Y);
if (destroy[A] <= Y) K++;
if (cnt_AC + cnt_CB < K) {
puts("-1");
continue;
}
if (cnt_AC >= K) {
B = C;
} else {
A = B;
B = C;
K = cnt_AC + cnt_CB - K + 1;
}
for (int i = int(L - 1); i >= int(0); --i) {
B = fa[A][i];
int cnt = (dep[A] - dep[B]) - count(o, A, B, Y);
if (cnt < K) {
K -= cnt;
A = B;
}
}
if (A == _B)
puts("-1");
else
printf("%d\n", A);
}
}
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Fedor runs for president of Byteland! In the debates, he will be asked how to solve Byteland's transport problem. It's a really hard problem because of Byteland's transport system is now a tree (connected graph without cycles). Fedor's team has found out in the ministry of transport of Byteland that there is money in the budget only for one additional road. In the debates, he is going to say that he will build this road as a way to maximize the number of distinct simple paths in the country. A simple path is a path which goes through every vertex no more than once. Two simple paths are named distinct if sets of their edges are distinct.
But Byteland's science is deteriorated, so Fedor's team hasn't succeeded to find any scientists to answer how many distinct simple paths they can achieve after adding exactly one edge on the transport system?
Help Fedor to solve it.
An edge can be added between vertices that are already connected, but it can't be a loop.
In this problem, we consider only simple paths of length at least two.
Input
The first line contains one integer n (2 β€ n β€ 500\ 000) β number of vertices in Byteland's transport system.
Each of the following n - 1 lines contains two integers v_i and u_i (1 β€ v_i, u_i β€ n). It's guaranteed that the graph is tree.
Output
Print exactly one integer β a maximal number of simple paths that can be achieved after adding one edge.
Examples
Input
2
1 2
Output
2
Input
4
1 2
1 3
1 4
Output
11
Input
6
1 2
1 3
3 4
3 5
4 6
Output
29
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 5e5 + 100;
const int mod = 1e9 + 7;
mt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count());
struct line {
long long k, b;
line() = default;
line(long long kk, long long bb) {
k = kk;
b = bb;
}
long long eval(long long first) { return k * first + b; }
};
long double inter(line f, line s) { return 1.0 * (s.b - f.b) / (f.k - s.k); }
int siz, it;
line hull[maxn];
void add(line a) {
while (siz >= 2 &&
inter(hull[siz - 1], hull[siz - 2]) >= inter(hull[siz - 2], a))
siz--;
hull[siz++] = a;
}
long long get(long long first) {
while (it + 1 < siz && hull[it].eval(first) < hull[it + 1].eval(first)) it++;
return hull[it].eval(first);
}
int n;
long long dp[maxn], sub[maxn];
vector<int> adj[maxn];
long long c2(int N) { return 1ll * N * (N - 1) / 2; }
long long ans = 1e18;
void dfs(int v, int p) {
sub[v] = 1;
int ch = 0;
for (int to : adj[v])
if (to != p) {
dfs(to, v);
ch++;
sub[v] += sub[to];
}
if (ch == 0) return;
dp[v] = 1e18;
for (int to : adj[v]) {
if (to != p)
dp[v] =
min(dp[v], dp[to] + sub[v] - 1 - sub[to] + c2(sub[v] - 1 - sub[to]));
}
siz = 0, it = 0;
sort(adj[v].begin(), adj[v].end(),
[&](int a, int b) { return sub[a] > sub[b]; });
long long S = n - 1;
for (int to : adj[v]) {
if (to != p) {
long long a = sub[to];
if (siz != 0)
ans = min(ans, get(a) + (S * S - S + a * a + a - 2 * S * a) / 2 + S +
dp[to] - a);
add(line(a, (a * a + a - 2 * S * a) / 2 + dp[to] - a));
}
}
}
int main() {
ios_base::sync_with_stdio(false), cin.tie(0);
cin >> n;
for (int i = 0; i < n - 1; i++) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
dfs(1, 0);
ans = min(ans, dp[1]);
cout << 1ll * n * (n - 1) - ans << "\n";
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
You are given string S and T consisting of lowercase English letters.
Determine if S equals T after rotation.
That is, determine if S equals T after the following operation is performed some number of times:
Operation: Let S = S_1 S_2 ... S_{|S|}. Change S to S_{|S|} S_1 S_2 ... S_{|S|-1}.
Here, |X| denotes the length of the string X.
Constraints
* 2 \leq |S| \leq 100
* |S| = |T|
* S and T consist of lowercase English letters.
Input
Input is given from Standard Input in the following format:
S
T
Output
If S equals T after rotation, print `Yes`; if it does not, print `No`.
Examples
Input
kyoto
tokyo
Output
Yes
Input
abc
arc
Output
No
Input
aaaaaaaaaaaaaaab
aaaaaaaaaaaaaaab
Output
Yes
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string S,T;
string ans="No";
cin >> S >> T;
string a,b;
int s=S.size();
int i,j,n,q;
for(i=0;i<s;i++){
if(S==T){ans="Yes";}
S=S.substr(1)+S.at(0);
}
cout << ans << endl;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
You are given n sequences. Each sequence consists of positive integers, not exceeding m. All integers in one sequence are distinct, but the same integer may appear in multiple sequences. The length of the i-th sequence is ki.
Each second integers in each of the sequences are shifted by one to the left, i.e. integers at positions i > 1 go to positions i - 1, while the first integers becomes the last.
Each second we take the first integer of each sequence and write it down to a new array. Then, for each value x from 1 to m we compute the longest segment of the array consisting of element x only.
The above operation is performed for 10100 seconds. For each integer from 1 to m find out the longest segment found at this time.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 100 000) β the number of sequences and the maximum integer that can appear in the sequences.
Then follow n lines providing the sequences. Each of them starts with an integer ki (1 β€ ki β€ 40) β the number of integers in the sequence, proceeded by ki positive integers β elements of the sequence. It's guaranteed that all integers in each sequence are pairwise distinct and do not exceed m.
The total length of all sequences doesn't exceed 200 000.
Output
Print m integers, the i-th of them should be equal to the length of the longest segment of the array with all its values equal to i during the first 10100 seconds.
Examples
Input
3 4
3 3 4 1
4 1 3 4 2
3 3 1 4
Output
2
1
3
2
Input
5 5
2 3 1
4 5 1 3 2
4 2 1 3 5
1 3
2 5 3
Output
3
1
4
0
1
Input
4 6
3 4 5 3
2 6 3
2 3 6
3 3 6 5
Output
0
0
2
1
1
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100000 + 123;
int n, m;
struct data {
int x, k, id;
};
vector<data> con[maxn];
int gcd(int x, int y) {
while (x && y)
if (x >= y)
x %= y;
else
y %= x;
return x + y;
}
int preG[50][50];
void ReadData() {
cin >> n >> m;
for (int i = 1, _b = n; i <= _b; ++i) {
int k;
cin >> k;
for (int j = 0, _b = k - 1; j <= _b; ++j) {
int u;
cin >> u;
con[u].push_back((data){j, k, i});
}
}
}
int cntLen[50];
int rem[50];
bool possible() {
for (int i = 1, _b = 40; i <= _b; ++i)
if (cntLen[i])
for (int j = i + 1, _b = 40; j <= _b; ++j)
if (cntLen[j]) {
if (rem[i] % preG[i][j] != rem[j] % preG[i][j]) return false;
}
return true;
}
int smallSolve(vector<data> &a) {
int j = 0;
int res = 0;
memset(cntLen, 0, sizeof(cntLen));
memset(rem, 0, sizeof(rem));
for (int i = 0, _n = ((int)a.size()); i < _n; ++i) {
while (j < i && cntLen[a[i].k] && rem[a[i].k] != a[i].x) {
cntLen[a[j].k]--;
j++;
}
cntLen[a[i].k]++;
rem[a[i].k] = a[i].x;
while (j < i && !possible()) {
cntLen[a[j].k]--;
j++;
}
res = max(res, i - j + 1);
}
return res;
}
int Solve(vector<data> &a) {
if (!((int)a.size())) return 0;
int j = 0;
vector<data> b;
int res = 0;
for (int i = 0, _n = ((int)a.size()); i < _n; ++i) {
while (j < i && a[i].id - a[j].id != i - j) j++;
if (i == ((int)a.size()) - 1 || a[i].id + 1 != a[i + 1].id) {
b.clear();
for (int f = j, _b = i; f <= _b; ++f) b.push_back(a[f]);
res = max(res, smallSolve(b));
}
}
return res;
}
int res[maxn];
void Process() {
for (int i = 1, _b = 40; i <= _b; ++i)
for (int j = 1, _b = 40; j <= _b; ++j) preG[i][j] = gcd(i, j);
for (int i = 1, _b = m; i <= _b; ++i) res[i] = Solve(con[i]);
for (int i = 1, _b = m; i <= _b; ++i) cout << res[i] << "\n";
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ReadData();
Process();
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n).
<image> An example of a cornfield with n = 7 and d = 2.
Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.
Help Vasya! For each grasshopper determine if it is inside the field (including the border).
Input
The first line contains two integers n and d (1 β€ d < n β€ 100).
The second line contains a single integer m (1 β€ m β€ 100) β the number of grasshoppers.
The i-th of the next m lines contains two integers x_i and y_i (0 β€ x_i, y_i β€ n) β position of the i-th grasshopper.
Output
Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO".
You can print each letter in any case (upper or lower).
Examples
Input
7 2
4
2 4
4 1
6 3
4 5
Output
YES
NO
NO
YES
Input
8 7
4
4 4
2 8
8 1
6 1
Output
YES
NO
YES
YES
Note
The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield.
The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, d, m;
cin >> n >> d >> m;
for (int i = 0; i < m; ++i) {
int x, y;
cin >> x >> y;
bool d1 = (y >= (x - d)), d2 = (y <= (x + d)), d3 = (x + y >= d),
d4 = (x + y <= 2 * n - d);
if (d1 && d2 && d3 && d4)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Tonio has a keyboard with only two letters, "V" and "K".
One day, he has typed out a string s with only these two letters. He really likes it when the string "VK" appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maximum number of times "VK" can appear as a substring (i. e. a letter "K" right after a letter "V") in the resulting string.
Input
The first line will contain a string s consisting only of uppercase English letters "V" and "K" with length not less than 1 and not greater than 100.
Output
Output a single integer, the maximum number of times "VK" can appear as a substring of the given string after changing at most one character.
Examples
Input
VK
Output
1
Input
VV
Output
1
Input
V
Output
0
Input
VKKKKKKKKKVVVVVVVVVK
Output
3
Input
KVKV
Output
1
Note
For the first case, we do not change any letters. "VK" appears once, which is the maximum number of times it could appear.
For the second case, we can change the second character from a "V" to a "K". This will give us the string "VK". This has one occurrence of the string "VK" as a substring.
For the fourth case, we can change the fourth character from a "K" to a "V". This will give us the string "VKKVKKKKKKVVVVVVVVVK". This has three occurrences of the string "VK" as a substring. We can check no other moves can give us strictly more occurrences.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
string s;
inline int sum() {
int i, re = 0;
for (i = 0; i < s.size() - 1; i++) {
if (s.substr(i, 2) == "VK") re++;
}
return re;
}
int main() {
ios_base::sync_with_stdio(false);
cin >> s;
int i, mx = -135;
mx = max(mx, sum());
for (i = 0; i < s.size(); i++) {
if (s[i] == 'V') {
s[i] = 'K';
mx = max(mx, sum());
s[i] = 'V';
} else {
s[i] = 'V';
mx = max(mx, sum());
s[i] = 'K';
}
}
cout << mx << endl;
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
In a small but very proud high school it was decided to win ACM ICPC. This goal requires to compose as many teams of three as possible, but since there were only 6 students who wished to participate, the decision was to build exactly two teams.
After practice competition, participant number i got a score of ai. Team score is defined as sum of scores of its participants. High school management is interested if it's possible to build two teams with equal scores. Your task is to answer that question.
Input
The single line contains six integers a1, ..., a6 (0 β€ ai β€ 1000) β scores of the participants
Output
Print "YES" (quotes for clarity), if it is possible to build teams with equal score, and "NO" otherwise.
You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES").
Examples
Input
1 3 2 1 2 1
Output
YES
Input
1 1 1 1 1 99
Output
NO
Note
In the first sample, first team can be composed of 1st, 2nd and 6th participant, second β of 3rd, 4th and 5th: team scores are 1 + 3 + 1 = 2 + 1 + 2 = 5.
In the second sample, score of participant number 6 is too high: his team score will be definitely greater.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a[6];
double sum = 0;
for (int i = 0; i < 6; i++) cin >> a[i], sum += a[i];
for (int i = 0; i < 6; i++)
for (int j = i + 1; j < 6; j++)
for (int k = j + 1; k < 6; k++)
if (a[i] + a[j] + a[k] == (sum / 2)) return cout << "YES" << endl, 0;
return cout << "NO" << endl, 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Kolya is going to make fresh orange juice. He has n oranges of sizes a1, a2, ..., an. Kolya will put them in the juicer in the fixed order, starting with orange of size a1, then orange of size a2 and so on. To be put in the juicer the orange must have size not exceeding b, so if Kolya sees an orange that is strictly greater he throws it away and continues with the next one.
The juicer has a special section to collect waste. It overflows if Kolya squeezes oranges of the total size strictly greater than d. When it happens Kolya empties the waste section (even if there are no more oranges) and continues to squeeze the juice. How many times will he have to empty the waste section?
Input
The first line of the input contains three integers n, b and d (1 β€ n β€ 100 000, 1 β€ b β€ d β€ 1 000 000) β the number of oranges, the maximum size of the orange that fits in the juicer and the value d, which determines the condition when the waste section should be emptied.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 1 000 000) β sizes of the oranges listed in the order Kolya is going to try to put them in the juicer.
Output
Print one integer β the number of times Kolya will have to empty the waste section.
Examples
Input
2 7 10
5 6
Output
1
Input
1 5 10
7
Output
0
Input
3 10 10
5 7 7
Output
1
Input
1 1 1
1
Output
0
Note
In the first sample, Kolya will squeeze the juice from two oranges and empty the waste section afterwards.
In the second sample, the orange won't fit in the juicer so Kolya will have no juice at all.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, h, d, sum = 0, k = 0;
cin >> n >> h >> d;
int ar[n];
for (int i = 0; i < n; i++) cin >> ar[i];
for (int i = 0; i < n; i++) {
if (ar[i] <= h) {
sum = sum + ar[i];
if (sum > d) {
sum = 0;
k++;
} else
continue;
} else
continue;
}
cout << k << endl;
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Let's call beauty of an array b_1, b_2, β¦, b_n (n > 1) β min_{1 β€ i < j β€ n} |b_i - b_j|.
You're given an array a_1, a_2, β¦ a_n and a number k. Calculate the sum of beauty over all subsequences of the array of length exactly k. As this number can be very large, output it modulo 998244353.
A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements.
Input
The first line contains integers n, k (2 β€ k β€ n β€ 1000).
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^5).
Output
Output one integer β the sum of beauty over all subsequences of the array of length exactly k. As this number can be very large, output it modulo 998244353.
Examples
Input
4 3
1 7 3 5
Output
8
Input
5 5
1 10 100 1000 10000
Output
9
Note
In the first example, there are 4 subsequences of length 3 β [1, 7, 3], [1, 3, 5], [7, 3, 5], [1, 7, 5], each of which has beauty 2, so answer is 8.
In the second example, there is only one subsequence of length 5 β the whole array, which has the beauty equal to |10-1| = 9.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long inf = (long long)2e9;
const long long md = 1000000007;
long long dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
long long power(long long a, long long p, long long md) {
long long ans = 1;
while (p) {
if (p & 1) ans *= a;
p /= 2;
a *= a;
ans %= md;
a %= md;
}
return ans;
}
long long mdinv(long long a) { return power(a, md - 2, md); }
long long arr[1003];
long long n, k;
long long DP[1003][1003];
long long last[1003];
signed main() {
const long long mm = 998244353;
cin >> n >> k;
for (long long i = 0; i < (long long)n; i++) cin >> arr[i];
sort(arr, arr + n);
long long ans = 0;
for (long long diff = 1; diff <= (arr[n - 1]) / (k - 1) + 2; diff++) {
long long first = 0, second = 0;
for (; second < n; second++) {
while (arr[second] - arr[first] >= diff) first++;
last[second] = first - 1;
}
for (long long i = 0; i < (long long)1003; i++) DP[0][i] = 0;
DP[0][1] = 1;
for (long long i = 1; i < n; i++) {
DP[i][1] = i + 1;
for (long long len = 2; len <= k; len++) {
DP[i][len] = DP[i - 1][len];
if (last[i] >= 0) DP[i][len] += DP[last[i]][len - 1];
DP[i][len] %= mm;
}
}
ans += DP[n - 1][k];
ans %= mm;
}
cout << ans;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
A: A-Z-
problem
There is a circular board of 26 squares, each square with one capital letter of the alphabet written clockwise in alphabetical order. That is, the clockwise side of the'A'square is the'B' square, the next side of the'B'square is the'C'square, and ..., the clockwise side of the'Z'square is the'A'. It's a square.
<image>
Also, the board has one piece in the'A'square.
You receive the string S and manipulate the pieces by looking at each character from the beginning of S. The i-th operation is as follows.
* At that point, move the pieces clockwise one by one, aiming at the square of the letter i of the letter S from the square with the piece. At this time, at least one square is assumed to move. So, for example, when moving from an'A'square to an'A' square, you have to go around the board once.
As a result of the above operation, please answer how many times the piece stepped on the'A'square. "Stepping on the'A'square" means advancing the piece from the'Z'square to the'A' square.
Input format
Input is given on one line.
S
S represents the string you receive.
Constraint
* 1 \ leq | S | \ leq 100
* S consists of uppercase letters only.
Output format
Output in one line how many times you stepped on the'A'square.
Input example 1
AIZU
Output example 1
2
* A-> A (once here)
* A-> I (once so far)
* I-> Z (once so far)
* Z-> U (twice so far)
Input example 2
HOKKAIDO
Output example 2
Four
Example
Input
AIZU
Output
2
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
int sum=0;
cin>>s;
for(int i=0; i<(int)s.size(); i++){
int a='A';
if(i)a=s[i-1];
int ju = s[i] - a;
if(ju<=0)ju+=26;
sum+=ju;
//cout<<sum<<endl;
}
cout<<sum/26<<endl;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Two participants are each given a pair of distinct numbers from 1 to 9 such that there's exactly one number that is present in both pairs. They want to figure out the number that matches by using a communication channel you have access to without revealing it to you.
Both participants communicated to each other a set of pairs of numbers, that includes the pair given to them. Each pair in the communicated sets comprises two different numbers.
Determine if you can with certainty deduce the common number, or if you can determine with certainty that both participants know the number but you do not.
Input
The first line contains two integers n and m (1 β€ n, m β€ 12) β the number of pairs the first participant communicated to the second and vice versa.
The second line contains n pairs of integers, each between 1 and 9, β pairs of numbers communicated from first participant to the second.
The third line contains m pairs of integers, each between 1 and 9, β pairs of numbers communicated from the second participant to the first.
All pairs within each set are distinct (in particular, if there is a pair (1,2), there will be no pair (2,1) within the same set), and no pair contains the same number twice.
It is guaranteed that the two sets do not contradict the statements, in other words, there is pair from the first set and a pair from the second set that share exactly one number.
Output
If you can deduce the shared number with certainty, print that number.
If you can with certainty deduce that both participants know the shared number, but you do not know it, print 0.
Otherwise print -1.
Examples
Input
2 2
1 2 3 4
1 5 3 4
Output
1
Input
2 2
1 2 3 4
1 5 6 4
Output
0
Input
2 3
1 2 4 5
1 2 1 3 2 3
Output
-1
Note
In the first example the first participant communicated pairs (1,2) and (3,4), and the second communicated (1,5), (3,4). Since we know that the actual pairs they received share exactly one number, it can't be that they both have (3,4). Thus, the first participant has (1,2) and the second has (1,5), and at this point you already know the shared number is 1.
In the second example either the first participant has (1,2) and the second has (1,5), or the first has (3,4) and the second has (6,4). In the first case both of them know the shared number is 1, in the second case both of them know the shared number is 4. You don't have enough information to tell 1 and 4 apart.
In the third case if the first participant was given (1,2), they don't know what the shared number is, since from their perspective the second participant might have been given either (1,3), in which case the shared number is 1, or (2,3), in which case the shared number is 2. While the second participant does know the number with certainty, neither you nor the first participant do, so the output is -1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m;
vector<pair<int, int>> v1;
vector<pair<int, int>> v2;
int connect(int i, int j) {
int ans = 0;
if (v1[i].first == v2[j].first) {
ans++;
}
if (v1[i].first == v2[j].second) {
ans++;
}
if (v1[i].second == v2[j].first) {
ans++;
}
if (v1[i].second == v2[j].second) {
ans++;
}
return ans;
}
int main() {
scanf("%d %d", &n, &m);
v1.resize(n);
v2.resize(m);
vector<int> ans;
for (int i = 0; i < n; i++) {
scanf("%d %d", &v1[i].first, &v1[i].second);
}
for (int j = 0; j < m; j++) {
scanf("%d %d", &v2[j].first, &v2[j].second);
}
int possible1 = 0;
for (int i = 0; i < n; i++) {
int temp = 0;
bool h1 = false;
bool h2 = false;
for (int j = 0; j < m; j++) {
if (connect(i, j) == 2 || connect(i, j) == 0) continue;
if (v1[i].first == v2[j].first || v1[i].first == v2[j].second)
h1 = true;
else
h2 = true;
}
if (h1 && h2) {
printf("-1");
return 0;
}
if (h1) {
ans.push_back(v1[i].first);
} else if (h2)
ans.push_back(v1[i].second);
}
for (int j = 0; j < m; j++) {
int temp = 0;
bool h1 = false, h2 = false;
for (int i = 0; i < n; i++) {
if (connect(i, j) == 2 || connect(i, j) == 0) continue;
if (v2[j].first == v1[i].first || v2[j].first == v1[i].second)
h1 = true;
else
h2 = true;
}
if (h1 && h2) {
printf("-1");
return 0;
}
if (h1) {
ans.push_back(v2[j].first);
} else if (h2)
ans.push_back(v2[j].second);
}
for (int i = 1; i < ans.size(); i++) {
if (ans[i] != ans[i - 1]) {
printf("0");
return 0;
}
}
printf("%d", ans[0]);
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
We have a grid with H rows and W columns, where all the squares are initially white.
You will perform some number of painting operations on the grid. In one operation, you can do one of the following two actions:
* Choose one row, then paint all the squares in that row black.
* Choose one column, then paint all the squares in that column black.
At least how many operations do you need in order to have N or more black squares in the grid? It is guaranteed that, under the conditions in Constraints, having N or more black squares is always possible by performing some number of operations.
Constraints
* 1 \leq H \leq 100
* 1 \leq W \leq 100
* 1 \leq N \leq H \times W
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H
W
N
Output
Print the minimum number of operations needed.
Examples
Input
3
7
10
Output
2
Input
14
12
112
Output
8
Input
2
100
200
Output
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main()
{
#define int long long
int h,w,n;
float t;
cin>>h>>w>>n;
t = max(h,w);
cout<< ceil(n/t);
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Ivan unexpectedly saw a present from one of his previous birthdays. It is array of n numbers from 1 to 200. Array is old and some numbers are hard to read. Ivan remembers that for all elements at least one of its neighbours ls not less than it, more formally:
a_{1} β€ a_{2},
a_{n} β€ a_{n-1} and
a_{i} β€ max(a_{i-1}, a_{i+1}) for all i from 2 to n-1.
Ivan does not remember the array and asks to find the number of ways to restore it. Restored elements also should be integers from 1 to 200. Since the number of ways can be big, print it modulo 998244353.
Input
First line of input contains one integer n (2 β€ n β€ 10^{5}) β size of the array.
Second line of input contains n integers a_{i} β elements of array. Either a_{i} = -1 or 1 β€ a_{i} β€ 200. a_{i} = -1 means that i-th element can't be read.
Output
Print number of ways to restore the array modulo 998244353.
Examples
Input
3
1 -1 2
Output
1
Input
2
-1 -1
Output
200
Note
In the first example, only possible value of a_{2} is 2.
In the second example, a_{1} = a_{2} so there are 200 different values because all restored elements should be integers between 1 and 200.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline long long power(long long a, long long b) {
long long x = 1;
a = a % 998244353LL;
while (b) {
if (b & 1) x = (x * a) % 998244353LL;
a = (a * a) % 998244353LL;
b >>= 1;
}
return x;
}
inline long long inv(long long a) { return power(a, 998244353LL - 2); }
long long gcd(long long a, long long b) { return a ? gcd(b % a, a) : b; }
const int N = 1e5 + 5;
long long dp[2][205][2];
long long n, a[N];
int main() {
ios_base::sync_with_stdio(false);
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i];
if (n == 2) {
if (a[0] == a[1]) {
if (a[0] == -1)
cout << "200\n";
else
cout << "1\n";
return 0;
} else if (a[0] == -1 || a[1] == -1) {
cout << "1\n";
return 0;
} else {
cout << "0\n";
return 0;
}
}
if (a[0] != -1 && a[1] != -1) {
if (a[0] > a[1]) {
cout << "0\n";
return 0;
}
}
if (a[n - 1] != -1 && a[n - 2] != -1) {
if (a[n - 1] > a[n - 2]) {
cout << "0\n";
return 0;
}
}
for (int i = 1; i < n - 1; i++) {
if (a[i - 1] != -1 && a[i + 1] != -1 && a[i] != -1) {
if (max(a[i - 1], a[i + 1]) < a[i]) {
cout << "0\n";
return 0;
}
}
}
if (a[0] != -1)
dp[0][a[0]][1] = 1;
else {
for (int i = 1; i <= 200; i++) dp[0][i][1] = 1;
}
for (int i = 1; i < n; i++) {
long long sum = 0, sum1 = 0;
for (int j = 1; j <= 200; j++) {
sum1 += (dp[0][j][1] + dp[0][j][0]);
sum += dp[0][j][0];
sum1 %= 998244353LL;
sum %= 998244353LL;
}
for (int j = 200; j > 0; j--) {
sum1 = (sum1 - dp[0][j][1] - dp[0][j][0] + 998244353LL + 998244353LL) %
998244353LL;
dp[1][j][1] = sum1;
}
for (int j = 1; j <= 200; j++) {
dp[1][j][0] = (sum + dp[0][j][1]) % 998244353LL;
sum = (sum + 998244353LL - dp[0][j][0]) % 998244353LL;
}
if (a[i] == -1) {
for (int j = 1; j <= 200; j++) {
dp[0][j][0] = dp[1][j][0];
dp[0][j][1] = dp[1][j][1];
}
} else {
for (int j = 1; j <= 200; j++) {
dp[0][j][0] = 0;
dp[0][j][1] = 0;
}
dp[0][a[i]][0] = dp[1][a[i]][0];
dp[0][a[i]][1] = dp[1][a[i]][1];
}
for (int j = 1; j <= 200; j++) {
dp[1][j][0] = 0;
dp[1][j][1] = 0;
}
}
long long ans = 0;
for (int j = 1; j <= 200; j++) {
ans += dp[0][j][0];
if (ans >= 998244353LL) ans -= 998244353LL;
}
ans %= 998244353LL;
cout << ans << endl;
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Roman planted a tree consisting of n vertices. Each vertex contains a lowercase English letter. Vertex 1 is the root of the tree, each of the n - 1 remaining vertices has a parent in the tree. Vertex is connected with its parent by an edge. The parent of vertex i is vertex pi, the parent index is always less than the index of the vertex (i.e., pi < i).
The depth of the vertex is the number of nodes on the path from the root to v along the edges. In particular, the depth of the root is equal to 1.
We say that vertex u is in the subtree of vertex v, if we can get from u to v, moving from the vertex to the parent. In particular, vertex v is in its subtree.
Roma gives you m queries, the i-th of which consists of two numbers vi, hi. Let's consider the vertices in the subtree vi located at depth hi. Determine whether you can use the letters written at these vertices to make a string that is a palindrome. The letters that are written in the vertexes, can be rearranged in any order to make a palindrome, but all letters should be used.
Input
The first line contains two integers n, m (1 β€ n, m β€ 500 000) β the number of nodes in the tree and queries, respectively.
The following line contains n - 1 integers p2, p3, ..., pn β the parents of vertices from the second to the n-th (1 β€ pi < i).
The next line contains n lowercase English letters, the i-th of these letters is written on vertex i.
Next m lines describe the queries, the i-th line contains two numbers vi, hi (1 β€ vi, hi β€ n) β the vertex and the depth that appear in the i-th query.
Output
Print m lines. In the i-th line print "Yes" (without the quotes), if in the i-th query you can make a palindrome from the letters written on the vertices, otherwise print "No" (without the quotes).
Examples
Input
6 5
1 1 1 3 3
zacccd
1 1
3 3
4 1
6 1
1 2
Output
Yes
No
Yes
Yes
Yes
Note
String s is a palindrome if reads the same from left to right and from right to left. In particular, an empty string is a palindrome.
Clarification for the sample test.
In the first query there exists only a vertex 1 satisfying all the conditions, we can form a palindrome "z".
In the second query vertices 5 and 6 satisfy condititions, they contain letters "Ρ" and "d" respectively. It is impossible to form a palindrome of them.
In the third query there exist no vertices at depth 1 and in subtree of 4. We may form an empty palindrome.
In the fourth query there exist no vertices in subtree of 6 at depth 1. We may form an empty palindrome.
In the fifth query there vertices 2, 3 and 4 satisfying all conditions above, they contain letters "a", "c" and "c". We may form a palindrome "cac".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<int> G[500005];
vector<int> level[500005];
int dp[29][2 * 500005], cnt;
int st[500005], ed[500005], memo[2 * 500005], demo[2 * 500005], val[500005],
LV[500005];
int ar[33];
char str[500005];
void dfs(int x, int lvl) {
st[x] = cnt++;
LV[x] = lvl;
level[lvl].push_back(st[x]);
for (int i = 0; i < G[x].size(); i++) {
int v = G[x][i];
dfs(v, lvl + 1);
}
ed[x] = cnt - 1;
}
int main() {
int n, q, ok = 0;
scanf("%d%d", &n, &q);
for (int i = 2; i <= n; i++) {
int p;
scanf("%d", &p);
G[p].push_back(i);
if (i == 5 && p == 3) ok = 1;
}
scanf("%s", str);
for (int i = 1; i <= n; i++) {
val[i] = (str[i - 1] - 'a') + 1;
}
cnt = 1;
dfs(1, 1);
for (int i = 1; i <= n; i++) {
memo[ed[i]] = i;
demo[st[i]] = i;
}
for (int i = 1; i <= n; i++) {
int sz = level[i].size();
if (sz == 0) break;
for (int j = 1; j <= 26; j++)
dp[j][level[i][0]] = (val[demo[level[i][0]]] == j);
for (int j = 1; j < sz; j++) {
for (int k = 1; k <= 26; k++) {
dp[k][level[i][j]] =
dp[k][level[i][j - 1]] + (val[demo[level[i][j]]] == k);
}
}
}
for (int i = 0; i < q; i++) {
int v, h;
scanf("%d%d", &v, &h);
int d = h - LV[v];
if (d < 0 || (int)level[h].size() == 0) {
puts("Yes");
continue;
}
int vv =
lower_bound(level[h].begin(), level[h].end(), st[v]) - level[h].begin();
if (vv == level[h].size()) vv--;
if (level[h][vv] < st[v]) vv++;
int ee =
lower_bound(level[h].begin(), level[h].end(), ed[v]) - level[h].begin();
if (ee == level[h].size()) ee--;
if (level[h][ee] > ed[v]) ee--;
if (vv > ee) {
puts("Yes");
continue;
}
vv = level[h][vv];
ee = level[h][ee];
for (int j = 1; j <= 26; j++) {
ar[j] = 0;
ar[j] = dp[j][ee] - dp[j][vv];
}
ar[val[demo[vv]]]++;
int odd = 0;
for (int j = 1; j <= 26; j++) {
odd += (ar[j] & 1);
}
if (odd > 1)
puts("No");
else
puts("Yes");
}
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Ivan Anatolyevich's agency is starting to become famous in the town.
They have already ordered and made n TV commercial videos. Each video is made in a special way: the colors and the soundtrack are adjusted to the time of the day and the viewers' mood. That's why the i-th video can only be shown within the time range of [li, ri] (it is not necessary to use the whole segment but the broadcast time should be within this segment).
Now it's time to choose a TV channel to broadcast the commercial. Overall, there are m TV channels broadcasting in the city, the j-th one has cj viewers, and is ready to sell time [aj, bj] to broadcast the commercial.
Ivan Anatolyevich is facing a hard choice: he has to choose exactly one video i and exactly one TV channel j to broadcast this video and also a time range to broadcast [x, y]. At that the time range should be chosen so that it is both within range [li, ri] and within range [aj, bj].
Let's define the efficiency of the broadcast as value (y - x)Β·cj β the total sum of time that all the viewers of the TV channel are going to spend watching the commercial. Help Ivan Anatolyevich choose the broadcast with the maximum efficiency!
Input
The first line contains two integers n and m (1 β€ n, m β€ 2Β·105) β the number of commercial videos and channels, respectively.
Each of the following n lines contains two integers li, ri (0 β€ li β€ ri β€ 109) β the segment of time when it is possible to show the corresponding video.
Each of the following m lines contains three integers aj, bj, cj (0 β€ aj β€ bj β€ 109, 1 β€ cj β€ 109), characterizing the TV channel.
Output
In the first line print an integer β the maximum possible efficiency of the broadcast. If there is no correct way to get a strictly positive efficiency, print a zero.
If the maximum efficiency is strictly positive, in the second line also print the number of the video i (1 β€ i β€ n) and the number of the TV channel j (1 β€ j β€ m) in the most effective broadcast.
If there are multiple optimal answers, you can print any of them.
Examples
Input
2 3
7 9
1 4
2 8 2
0 4 1
8 9 3
Output
4
2 1
Input
1 1
0 0
1 1 10
Output
0
Note
In the first sample test the most optimal solution is to show the second commercial using the first TV channel at time [2, 4]. The efficiency of such solution is equal to (4 - 2)Β·2 = 4.
In the second sample test Ivan Anatolievich's wish does not meet the options of the TV channel, the segments do not intersect, so the answer is zero.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 400005;
struct SegmentTree {
int offset;
vector<pair<int, int> > v;
vector<vector<pair<int, int> > > vals;
void initialize(int n) {
v.clear();
vals.clear();
for (offset = 1; offset < n; offset <<= 1)
;
v.resize(2 * offset, make_pair(-1, -1));
vals.resize(offset);
for (int i = 0; i < offset; i++) {
vals[i].push_back(make_pair(-1, -1));
}
}
void update(int x, int val, int idx) {
vals[x].push_back(make_pair(val, idx));
v[x + offset] = max(v[x + offset], make_pair(val, idx));
for (int i = (x + offset) >> 1; i > 0; i >>= 1) {
v[i] = max(v[i * 2], v[i * 2 + 1]);
}
}
void ssort() {
for (int i = 0; i < offset; i++) {
sort(vals[i].begin(), vals[i].end());
}
}
void erase(int x, int val, int idx) {
vals[x].pop_back();
v[x + offset] = *vals[x].rbegin();
for (int i = (x + offset) >> 1; i > 0; i >>= 1) {
v[i] = max(v[i * 2], v[i * 2 + 1]);
}
}
pair<int, int> query(int x, int lo, int hi, int a, int b) {
if (lo >= b || hi <= a) {
return make_pair(-1, -1);
} else if (lo >= a && hi <= b) {
return v[x];
}
return max(query(x * 2, lo, (lo + hi) / 2, a, b),
query(x * 2 + 1, (lo + hi) / 2, hi, a, b));
}
pair<int, int> query(int a, int b) { return query(1, 0, offset, a, b + 1); }
};
struct Rol {
int x, y;
Rol(int _x = 0, int _y = 0) : x(_x), y(_y) {}
};
struct Can {
int x, y;
long long c;
Can(int _x = 0, int _y = 0, long long _c = 0) : x(_x), y(_y), c(_c) {}
};
int n, m;
vector<int> vals;
Rol rol[MAX_N], trol[MAX_N];
Can can[MAX_N], tcan[MAX_N];
vector<int> rols[2 * MAX_N], cans[2 * MAX_N];
SegmentTree t, t2;
Can solve() {
vals.clear();
for (int i = 0; i < n; i++) {
vals.push_back(rol[i].x);
vals.push_back(rol[i].y);
}
for (int i = 0; i < m; i++) {
vals.push_back(can[i].x);
vals.push_back(can[i].y);
}
sort(vals.begin(), vals.end());
vals.resize(unique(vals.begin(), vals.end()) - vals.begin());
t.initialize(vals.size());
for (int i = 0; i < n; i++) {
rol[i].x = lower_bound(vals.begin(), vals.end(), rol[i].x) - vals.begin();
rol[i].y = lower_bound(vals.begin(), vals.end(), rol[i].y) - vals.begin();
t.update(rol[i].x, rol[i].y, i);
}
long long ans = 0;
int ii = -1, jj = -1;
for (int i = 0; i < m; i++) {
can[i].x = lower_bound(vals.begin(), vals.end(), can[i].x) - vals.begin();
can[i].y = lower_bound(vals.begin(), vals.end(), can[i].y) - vals.begin();
pair<int, int> q = t.query(0, can[i].x);
if (q.first >= can[i].x) {
q.first = min(q.first, can[i].y);
if ((long long)(vals[q.first] - vals[can[i].x]) * can[i].c > ans) {
ans = (long long)(vals[q.first] - vals[can[i].x]) * can[i].c;
jj = i;
ii = q.second;
}
}
}
return Can(ii, jj, ans);
}
Can maxx(Can a, Can b) {
if (a.c > b.c) {
return a;
}
return b;
}
int main() {
cin.sync_with_stdio(false);
cout.sync_with_stdio(false);
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> rol[i].x >> rol[i].y;
trol[i] = rol[i];
}
for (int i = 0; i < m; i++) {
cin >> can[i].x >> can[i].y >> can[i].c;
tcan[i] = can[i];
}
Can a = solve();
for (int i = 0; i < n; i++) {
rol[i] = trol[i];
}
for (int i = 0; i < m; i++) {
can[i] = tcan[i];
}
for (int i = 0; i < n; i++) {
rol[i].x *= -1;
rol[i].y *= -1;
swap(rol[i].x, rol[i].y);
}
for (int i = 0; i < m; i++) {
can[i].x *= -1;
can[i].y *= -1;
swap(can[i].x, can[i].y);
}
Can b = solve();
long long ans = 0;
int ii = -1, jj = -1;
t2.initialize(vals.size());
for (int i = 0; i < n; i++) {
t2.update(rol[i].y, vals[rol[i].y] - vals[rol[i].x], i);
}
for (int i = 0; i < n; i++) {
rols[rol[i].x].push_back(i);
}
for (int i = 0; i < m; i++) {
cans[can[i].x].push_back(i);
}
t2.ssort();
for (int i = 0; i < vals.size(); i++) {
for (int j = 0; j < cans[i].size(); j++) {
int cur = cans[i][j];
pair<int, int> q = t2.query(can[cur].x, can[cur].y);
if (q.first >= 0 && (long long)q.first * can[cur].c > ans) {
ans = (long long)q.first * can[cur].c;
ii = q.second;
jj = cur;
}
}
for (int j = 0; j < rols[i].size(); j++) {
int cur = rols[i][j];
t2.erase(rol[cur].y, vals[rol[cur].y] - vals[rol[cur].x], cur);
}
}
Can c = maxx(a, maxx(b, Can(ii, jj, ans)));
if (c.c) {
cout << c.c << endl << c.x + 1 << " " << c.y + 1 << endl;
} else {
cout << 0 << endl;
}
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
A little bear Limak plays a game. He has five cards. There is one number written on each card. Each number is a positive integer.
Limak can discard (throw out) some cards. His goal is to minimize the sum of numbers written on remaining (not discarded) cards.
He is allowed to at most once discard two or three cards with the same number. Of course, he won't discard cards if it's impossible to choose two or three cards with the same number.
Given five numbers written on cards, cay you find the minimum sum of numbers on remaining cards?
Input
The only line of the input contains five integers t1, t2, t3, t4 and t5 (1 β€ ti β€ 100) β numbers written on cards.
Output
Print the minimum possible sum of numbers written on remaining cards.
Examples
Input
7 3 7 3 20
Output
26
Input
7 9 3 1 8
Output
28
Input
10 10 10 10 10
Output
20
Note
In the first sample, Limak has cards with numbers 7, 3, 7, 3 and 20. Limak can do one of the following.
* Do nothing and the sum would be 7 + 3 + 7 + 3 + 20 = 40.
* Remove two cards with a number 7. The remaining sum would be 3 + 3 + 20 = 26.
* Remove two cards with a number 3. The remaining sum would be 7 + 7 + 20 = 34.
You are asked to minimize the sum so the answer is 26.
In the second sample, it's impossible to find two or three cards with the same number. Hence, Limak does nothing and the sum is 7 + 9 + 1 + 3 + 8 = 28.
In the third sample, all cards have the same number. It's optimal to discard any three cards. The sum of two remaining numbers is 10 + 10 = 20.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(void) {
map<int, int> m;
map<int, int>::iterator it;
int a, sum = 0;
vector<int> s;
for (int i = 0; i < 5; i++) {
cin >> a;
sum += a;
m[a]++;
}
for (it = m.begin(); it != m.end(); it++) {
if (it->second == 2 || it->second == 3)
s.push_back(sum - (it->first * it->second));
else if (it->second == 4)
s.push_back(sum - (it->first * 3));
else if (it->second == 5)
s.push_back(sum - (it->first * 3));
else
s.push_back(sum);
}
cout << *min_element(s.begin(), s.end());
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
We have a grid with A horizontal rows and B vertical columns, with the squares painted white. On this grid, we will repeatedly apply the following operation:
* Assume that the grid currently has a horizontal rows and b vertical columns. Choose "vertical" or "horizontal".
* If we choose "vertical", insert one row at the top of the grid, resulting in an (a+1) \times b grid.
* If we choose "horizontal", insert one column at the right end of the grid, resulting in an a \times (b+1) grid.
* Then, paint one of the added squares black, and the other squares white.
Assume the grid eventually has C horizontal rows and D vertical columns. Find the number of ways in which the squares can be painted in the end, modulo 998244353.
Constraints
* 1 \leq A \leq C \leq 3000
* 1 \leq B \leq D \leq 3000
* A, B, C, and D are integers.
Input
Input is given from Standard Input in the following format:
A B C D
Output
Print the number of ways in which the squares can be painted in the end, modulo 998244353.
Examples
Input
1 1 2 2
Output
3
Input
2 1 3 4
Output
65
Input
31 41 59 265
Output
387222020
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
const long long md=998244353;
long long a,b,c,d,dp[2][3030][3030];
int main()
{
cin>>a>>b>>c>>d;
dp[0][a][b]=1;
for(int i=a;i<=c;i++)
{
for(int j=b;j<=d;j++)
{
if(i==a && j==b)
{
continue;
}
dp[0][i][j]=dp[0][i-1][j]*j+dp[1][i-1][j];
dp[0][i][j]%=md;
dp[1][i][j]=dp[0][i][j-1]*i+dp[1][i][j-1]*i;
dp[1][i][j]%=md;
}
}
cout<<(dp[0][c][d]+dp[1][c][d])%md<<endl;
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
This is an interactive problem. Don't forget to flush output after printing queries using cout.flush() or fflush(stdout) in C++ or similar functions in other programming languages.
There are n gift boxes in a row, numbered from 1 to n from left to right. It's known that exactly k of them contain valuable gifts β other boxes contain just lucky stones. All boxes look the same and differ only in weight. All boxes with stones have the same weight and are strictly heavier than boxes with valuable items. But valuable gifts may be different, so the boxes with valuable items may have different weights.
You can ask no more than 50 queries (printing an answer doesn't count). By each query you can compare total weights of two non-intersecting subsets of boxes a_1, a_2, ..., a_{k_a} and b_1, b_2, ..., b_{k_b}. In return you'll get one of four results:
* FIRST, if subset a_1, a_2, ..., a_{k_a} is strictly heavier;
* SECOND, if subset b_1, b_2, ..., b_{k_b} is strictly heavier;
* EQUAL, if subsets have equal total weights;
* WASTED, if the query is incorrect or the limit of queries is exceeded.
Using such queries (or, maybe, intuition) find the box with a valuable gift with the minimum index.
Input
The input consists of several cases. In the beginning, you receive the integer T (1 β€ T β€ 500) β the number of test cases.
At the beginning of each test case, you receive two integers n and k (2 β€ n β€ 1000, 1 β€ k β€ n/2) β the number of boxes in a row and the number of boxes with valuable gifts.
It's guaranteed that the order of boxes is fixed beforehand and that the sum of n in one test doesn't exceed 1000.
Output
For each test case print the minimum index among all boxes with a valuable gift in the following format: "! x" where x (1 β€ x β€ n) β the index of the box.
Interaction
Print each query in three lines. In the first line print the sizes of subset in the following format: "? k_a k_b" where k_a and k_b (1 β€ k_a, k_b β€ n; k_a + k_b β€ n) β the corresponding sizes.
In the second line print k_a integers a_1, a_2, ..., a_{k_a} (1 β€ a_i β€ n; a_i β a_j if i β j) β indexes of boxes in the first subset.
In the third line print k_b integers b_1, b_2, ..., b_{k_b} (1 β€ b_i β€ n; b_i β b_j if i β j) β indexes of boxes in the second subset.
The subsets shouldn't intersect, i. e. a_i β b_j for all i and j.
You'll receive one of four responses described above. In the case of WASTED stop your program to avoid getting random verdict instead of Wrong Answer.
Example
Input
2
2 1
-
-
-
FIRST
-
5 2
-
-
-
FIRST
-
-
-
SECOND
-
-
-
EQUAL
-
Output
-
-
? 1 1
1
2
-
! 2
-
? 1 1
1
2
-
? 2 3
4 2
1 3 5
-
? 1 1
4
5
-
! 1
Note
Additional separators "β" in the sample are used only to increase the readability of the sample. Don't print any unnecessary symbols or line breaks in your solution when you send it to the system.
Hacks are forbidden in this task.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int get() {
char c;
while (c = getchar(), c != '-' && (c < '0' || c > '9'))
;
bool flag = (c == '-');
if (flag) c = getchar();
int x = 0;
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = getchar();
}
return flag ? -x : x;
}
const int MAXN = 1000;
const int MAXQ = 50;
bool flag[MAXN + 1];
int lis[MAXN];
int main() {
int test;
cin >> test;
while (test--) {
int n, k;
cin >> n >> k;
int num = 0, s = 1;
while (s * 2 <= n - k) {
s *= 2;
num++;
}
num = min(MAXQ - num * 2, n - 1);
int stone = rand() % n + 1;
memset(flag, 0, sizeof(flag));
flag[stone] = true;
for (int i = 0; i < num; i++) {
int x;
while (x = rand() % n + 1, flag[x])
;
flag[x] = true;
printf("? 1 1\n%d\n%d\n", stone, x);
fflush(stdout);
string s;
cin >> s;
if (s == "WASTED") return 0;
if (s == "SECOND") stone = x;
}
lis[0] = stone;
for (int i = 1, cur = 1; i <= n; i++)
if (i != stone) lis[cur++] = i;
num = 1;
int l = -1, r = -1;
while (l == -1) {
string s;
if (num * 2 > n - k)
s = "FIRST";
else {
printf("? %d %d\n", num, num);
for (int i = 0; i < num; i++)
printf("%d%c", lis[i], (i == num - 1) ? '\n' : ' ');
for (int i = 0; i < num; i++)
printf("%d%c", lis[num + i], (i == num - 1) ? '\n' : ' ');
fflush(stdout);
cin >> s;
if (s == "WASTED" || s == "SECOND") return 0;
}
if (s == "EQUAL")
num *= 2;
else {
l = num;
r = min(num * 2 - 1, n - 1);
}
}
while (l < r) {
int len = (r - l + 1) / 2;
printf("? %d %d\n", len, len);
for (int i = 0; i < len; i++)
printf("%d%c", lis[i], (i == len - 1) ? '\n' : ' ');
for (int i = 0; i < len; i++)
printf("%d%c", lis[l + i], (i == len - 1) ? '\n' : ' ');
fflush(stdout);
string s;
cin >> s;
if (s == "WASTED" || s == "SECOND") return 0;
if (s == "EQUAL")
l += len;
else
r -= len;
}
printf("! %d\n", lis[l]);
fflush(stdout);
}
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
You are given an array a consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i β x (β denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion in the b array is a pair of integers i and j such that 1 β€ i < j β€ n and b_i > b_j.
You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x β output the smallest one.
Input
First line contains a single integer n (1 β€ n β€ 3 β
10^5) β the number of elements in a.
Second line contains n space-separated integers a_1, a_2, ..., a_n (0 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.
Examples
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
Note
In the first sample it is optimal to leave the array as it is by choosing x = 0.
In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions:
* i = 2, j = 3;
* i = 2, j = 4;
* i = 3, j = 4;
* i = 8, j = 9.
In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions.
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize(3, "Ofast", "inline")
using namespace std;
const long long INF(0x3f3f3f3f3f3f3f3fll);
const long long inf(0x3f3f3f3f);
template <typename T>
void read(T &res) {
bool flag = false;
char ch;
while (!isdigit(ch = getchar())) (ch == '-') && (flag = true);
for (res = ch - 48; isdigit(ch = getchar());
res = (res << 1) + (res << 3) + ch - 48)
;
flag && (res = -res);
}
template <typename T>
void Out(T x) {
if (x < 0) putchar('-'), x = -x;
if (x > 9) Out(x / 10);
putchar(x % 10 + '0');
}
long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; }
long long lcm(long long a, long long b) { return a * b / gcd(a, b); }
long long pow_mod(long long x, long long n, long long mod) {
long long res = 1;
while (n) {
if (n & 1) res = res * x % mod;
x = x * x % mod;
n >>= 1;
}
return res;
}
long long fact_pow(long long n, long long p) {
long long res = 0;
while (n) {
n /= p;
res += n;
}
return res;
}
long long mult(long long a, long long b, long long p) {
a %= p;
b %= p;
long long r = 0, v = a;
while (b) {
if (b & 1) {
r += v;
if (r > p) r -= p;
}
v <<= 1;
if (v > p) v -= p;
b >>= 1;
}
return r;
}
long long quick_pow(long long a, long long b, long long p) {
long long r = 1, v = a % p;
while (b) {
if (b & 1) r = mult(r, v, p);
v = mult(v, v, p);
b >>= 1;
}
return r;
}
bool CH(long long a, long long n, long long x, long long t) {
long long r = quick_pow(a, x, n);
long long z = r;
for (long long i = 1; i <= t; i++) {
r = mult(r, r, n);
if (r == 1 && z != 1 && z != n - 1) return true;
z = r;
}
return r != 1;
}
bool Miller_Rabin(long long n) {
if (n < 2) return false;
if (n == 2) return true;
if (!(n & 1)) return false;
long long x = n - 1, t = 0;
while (!(x & 1)) {
x >>= 1;
t++;
}
srand(time(NULL));
long long o = 8;
for (long long i = 0; i < o; i++) {
long long a = rand() % (n - 1) + 1;
if (CH(a, n, x, t)) return false;
}
return true;
}
long long exgcd1(long long a, long long b, long long &x, long long &y) {
if (!b) {
x = 1, y = 0;
return a;
}
long long t = exgcd1(b, a % b, y, x);
y -= a / b * x;
return t;
}
long long get_inv(long long a, long long mod) {
long long x, y;
long long d = exgcd1(a, mod, x, y);
return d == 1 ? (x % mod + mod) % mod : -1;
}
void exgcd(long long a, long long b, long long &x, long long &y) {
if (!b) {
x = 1, y = 0;
return;
}
exgcd(b, a % b, x, y);
long long t = x;
x = y, y = t - (a / b) * y;
}
long long INV(long long a, long long b) {
long long x, y;
return exgcd(a, b, x, y), (x % b + b) % b;
}
long long crt(long long x, long long p, long long mod) {
return INV(p / mod, mod) * (p / mod) * x;
}
long long FAC(long long x, long long a, long long b) {
if (!x) return 1;
long long ans = 1;
for (long long i = 1; i <= b; i++)
if (i % a) ans *= i, ans %= b;
ans = pow_mod(ans, x / b, b);
for (long long i = 1; i <= x % b; i++)
if (i % a) ans *= i, ans %= b;
return ans * FAC(x / a, a, b) % b;
}
long long C(long long n, long long m, long long a, long long b) {
long long N = FAC(n, a, b), M = FAC(m, a, b), Z = FAC(n - m, a, b), sum = 0,
i;
for (i = n; i; i = i / a) sum += i / a;
for (i = m; i; i = i / a) sum -= i / a;
for (i = n - m; i; i = i / a) sum -= i / a;
return N * pow_mod(a, sum, b) % b * INV(M, b) % b * INV(Z, b) % b;
}
long long exlucas(long long n, long long m, long long p) {
long long t = p, ans = 0, i;
for (i = 2; i * i <= p; i++) {
long long k = 1;
while (t % i == 0) {
k *= i, t /= i;
}
ans += crt(C(n, m, i, k), p, k), ans %= p;
}
if (t > 1) ans += crt(C(n, m, t, t), p, t), ans %= p;
return ans % p;
}
const long long N = 3e5 + 10;
struct Edge {
long long nex, to;
} edge[N << 1];
long long head[N], TOT;
void add_edge(long long u, long long v) {
edge[++TOT].nex = head[u];
edge[TOT].to = v;
head[u] = TOT;
}
long long cnt[N][2], a[N];
vector<long long> vec;
void dfs(vector<long long> vec, long long i) {
if (i < 0) return;
long long res1 = 0, res2 = 0, cnt1 = 0, cnt2 = 0;
for (auto j : vec) {
long long x = j >> i & 1 ^ 1;
if (!x)
res1 += cnt1;
else
res2 += cnt2;
if (x)
cnt1++;
else
cnt2++;
}
cnt[i][0] += res2, cnt[i][1] += res1;
vector<long long> vec1, vec2;
for (auto j : vec) {
if (j >> i & 1)
vec1.push_back(j);
else
vec2.push_back(j);
}
if (vec1.size()) dfs(vec1, i - 1);
if (vec2.size()) dfs(vec2, i - 1);
}
signed main() {
std::ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
long long n, ans = 0, tot = 0;
cin >> n;
for (long long i = 1; i <= n; i++) cin >> a[i], vec.push_back(a[i]);
dfs(vec, 31);
for (long long i = 31; i >= 0; i--) {
if (cnt[i][0] > cnt[i][1])
ans += 1LL << i, tot += cnt[i][1];
else
tot += cnt[i][0];
}
cout << tot << " " << ans << '\n';
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Carving the cake 2 (Cake 2)
JOI-kun and IOI-chan are twin brothers and sisters. JOI has been enthusiastic about making sweets lately, and JOI tried to bake a cake and eat it today, but when it was baked, IOI who smelled it came, so we decided to divide the cake. became.
The cake is round. We made radial cuts from a point, cut the cake into N pieces, and numbered the pieces counterclockwise from 1 to N. That is, for 1 β€ i β€ N, the i-th piece is adjacent to the i β 1st and i + 1st pieces (though the 0th is considered to be the Nth and the N + 1st is considered to be the 1st). The size of the i-th piece was Ai, but I was so bad at cutting that all Ai had different values.
<image>
Figure 1: Cake example (N = 5, A1 = 2, A2 = 8, A3 = 1, A4 = 10, A5 = 9)
I decided to divide these N pieces by JOI-kun and IOI-chan. I decided to divide it as follows:
1. First, JOI chooses and takes one of N.
2. After that, starting with IOI-chan, IOI-chan and JOI-kun alternately take the remaining pieces one by one. However, if you can only take a piece that has already been taken at least one of the pieces on both sides, and there are multiple pieces that can be taken, IOI will choose the largest one and JOI will take it. You can choose what you like.
JOI wants to maximize the total size of the pieces he will finally take.
Task
Given the number N of cake pieces and the size information of N pieces, create a program to find the maximum value of the total size of pieces that JOI can take.
input
Read the following input from standard input.
* The integer N is written on the first line, which means that the cake is cut into N pieces.
* The integer Ai is written on the i-th line (1 β€ i β€ N) of the following N lines, which indicates that the size of the i-th piece is Ai.
output
Output an integer representing the maximum value of the total size of pieces that JOI can take to the standard output on one line.
Limits
All input data satisfy the following conditions.
* 1 β€ N β€ 20000.
* 1 β€ Ai β€ 1 000 000 000.
* Ai are all different.
Input / output example
Input example 1
Five
2
8
1
Ten
9
Output example 1
18
JOI is best to take the pieces as follows.
1. JOI takes the second piece. The size of this piece is 8.
2. IOI takes the first piece. The size of this piece is 2.
3. JOI takes the 5th piece. The size of this piece is 9.
4. IOI takes the 4th piece. The size of this piece is 10.
5. JOI takes the third piece. The size of this piece is 1.
Finally, the total size of the pieces taken by JOI is 8 + 9 + 1 = 18.
Input example 2
8
1
Ten
Four
Five
6
2
9
3
Output example 2
26
Input example 3
15
182243672
10074562
977552215
122668426
685444213
3784162
463324752
560071245
134465220
21447865
654556327
183481051
20041805
405079805
564327789
Output example 3
3600242976
The question text and the data used for the automatic referee are the question text and the test data for scoring, which are created and published by the Japan Committee for Information Olympics.
Example
Input
5
2
8
1
10
9
Output
18
### Response
```cpp
#include <cstdio>
#include <algorithm>
#include <vector>
#include <deque>
#include <cstdint>
int main() {
int N;
scanf("%d", &N);
std::vector<intmax_t> A(N);
for (int i=0; i<N; ++i)
scanf("%jd", &A[i]);
if (N == 1) {
printf("%jd\n", A[0]);
return 0;
} else if (N == 2) {
printf("%jd\n", std::max(A[0], A[1]));
return 0;
}
std::vector<std::vector<intmax_t>> dp(N, std::vector<intmax_t>(N));
for (int i=0; i<N; ++i) {
dp[i][i] = A[i];
}
// XXX half-open interval is better than this...
for (int i=1; i<N; ++i) {
for (int j=0; j<N; ++j) {
// dp[j][(i+j)%N]; haba: i, hidari: j
// l_next, [l_cur, ..., r_cur], r_next
int l_cur=j, r_cur=(l_cur+i+N-1)%N;
int l_next=(l_cur-1+N)%N, r_next=(r_cur+1)%N;
if (l_cur == r_next) {
continue;
}
if (i % 2 == 0) {
// JOI
dp[l_cur][r_next] = std::max(dp[l_cur][r_next], dp[l_cur][r_cur]+A[r_next]);
dp[l_next][r_cur] = std::max(dp[l_next][r_cur], dp[l_cur][r_cur]+A[l_next]);
} else {
// IOI
if (A[l_next] > A[r_next]) {
// ... eats A[l_next]
dp[l_next][r_cur] = std::max(dp[l_next][r_cur], dp[l_cur][r_cur]);
} else {
dp[l_cur][r_next] = std::max(dp[l_cur][r_next], dp[l_cur][r_cur]);
}
}
}
}
#if 0
for (int i=0; i<N; ++i) {
for (int j=0; j<N; ++j) {
printf("%jd%c", dp[j][(j+i)%N], j+1<N? ' ':'\n');
}
}
#endif
intmax_t res=0;
for (int i=0; i<N; ++i)
res = std::max(res, *std::max_element(dp[i].begin(), dp[i].end()));
printf("%jd\n", res);
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Let's define a balanced multiset the following way. Write down the sum of all elements of the multiset in its decimal representation. For each position of that number check if the multiset includes at least one element such that the digit of the element and the digit of the sum at that position are the same. If that holds for every position, then the multiset is balanced. Otherwise it's unbalanced.
For example, multiset \{20, 300, 10001\} is balanced and multiset \{20, 310, 10001\} is unbalanced:
<image>
The red digits mark the elements and the positions for which these elements have the same digit as the sum. The sum of the first multiset is 10321, every position has the digit required. The sum of the second multiset is 10331 and the second-to-last digit doesn't appear in any number, thus making the multiset unbalanced.
You are given an array a_1, a_2, ..., a_n, consisting of n integers.
You are asked to perform some queries on it. The queries can be of two types:
* 1~i~x β replace a_i with the value x;
* 2~l~r β find the unbalanced subset of the multiset of the numbers a_l, a_{l + 1}, ..., a_r with the minimum sum, or report that no unbalanced subset exists.
Note that the empty multiset is balanced.
For each query of the second type print the lowest sum of the unbalanced subset. Print -1 if no unbalanced subset exists.
Input
The first line contains two integers n and m (1 β€ n, m β€ 2 β
10^5) β the number of elements in the array and the number of queries, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i < 10^9).
Each of the following m lines contains a query of one of two types:
* 1~i~x (1 β€ i β€ n, 1 β€ x < 10^9) β replace a_i with the value x;
* 2~l~r (1 β€ l β€ r β€ n) β find the unbalanced subset of the multiset of the numbers a_l, a_{l + 1}, ..., a_r with the lowest sum, or report that no unbalanced subset exists.
It is guaranteed that there is at least one query of the second type.
Output
For each query of the second type print the lowest sum of the unbalanced subset. Print -1 if no unbalanced subset exists.
Example
Input
4 5
300 10001 20 20
2 1 3
1 1 310
2 1 3
2 3 3
2 3 4
Output
-1
330
-1
40
Note
All the subsets of multiset \{20, 300, 10001\} are balanced, thus the answer is -1.
The possible unbalanced subsets in the third query are \{20, 310\} and \{20, 310, 10001\}. The lowest sum one is \{20, 310\}. Note that you are asked to choose a subset, not a subsegment, thus the chosen elements might not be adjancent in the array.
The fourth query includes only the empty subset and subset \{20\}. Both of them are balanced.
The last query includes the empty subset and the subsets \{20\}, \{20\} and \{20, 20\}. Only \{20, 20\} is unbalanced, its sum is 40. Note that you are asked to choose a multiset, thus it might include equal elements.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
const int inf = 1e9 + 10;
pair<int, int> seg[2 * N][10];
int n, q, x, typ, l, r;
const pair<int, int> def = {inf, inf};
pair<int, int> merge(pair<int, int>& a, pair<int, int>& b) {
pair<int, int> res = def;
res.first = min(a.first, b.first);
if (a.first < b.first)
res.second = min(a.second, b.first);
else
res.second = min(b.second, a.first);
return res;
}
int query(int L, int R) {
pair<int, int> final = def;
for (int i = 0; i < 10; i++) {
pair<int, int> ans = def;
for (int lh = L + n, rh = R + n; lh < rh; lh >>= 1, rh >>= 1) {
if (lh & 1) ans = merge(ans, seg[lh++][i]);
if (rh & 1) ans = merge(ans, seg[--rh][i]);
}
if (ans.first >= inf || ans.second >= inf) continue;
if (ans.first + ans.second < final.first + final.second) final = ans;
}
if (final.first >= inf || final.second >= inf) return -1;
return (final.first + final.second);
}
void update(int id, int val) {
int cop = val, len = 0;
vector<int> digit(10, 0);
id += n;
while (cop) {
digit[len++] = cop % 10;
cop /= 10;
}
for (int i = 0; i < 10; i++) {
seg[id][i] = def;
if (digit[i] > 0) seg[id][i].first = val;
for (int j = id; j >= 1; j >>= 1)
seg[j >> 1][i] = merge(seg[j][i], seg[j ^ 1][i]);
}
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> q;
for (int i = 0; i < n; i++) {
cin >> x;
update(i, x);
}
while (q--) {
cin >> typ >> l >> r;
if (typ == 1)
update(l - 1, r);
else
cout << query(l - 1, r) << "\n";
}
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
You have to organize a wedding party. The program of the party will include a concentration game played by the bride and groom. The arrangement of the concentration game should be easy since this game will be played to make the party fun.
We have a 4x4 board and 8 pairs of cards (denoted by `A' to `H') for the concentration game:
+---+---+---+---+
| | | | | A A B B
+---+---+---+---+ C C D D
| | | | | E E F F
+---+---+---+---+ G G H H
| | | | |
+---+---+---+---+
| | | | |
+---+---+---+---+
To start the game, it is necessary to arrange all 16 cards face down on the board. For example:
+---+---+---+---+
| A | B | A | B |
+---+---+---+---+
| C | D | C | D |
+---+---+---+---+
| E | F | G | H |
+---+---+---+---+
| G | H | E | F |
+---+---+---+---+
The purpose of the concentration game is to expose as many cards as possible by repeatedly performing the following procedure: (1) expose two cards, (2) keep them open if they match or replace them face down if they do not.
Since the arrangements should be simple, every pair of cards on the board must obey the following condition: the relative position of one card to the other card of the pair must be one of 4 given relative positions. The 4 relative positions are different from one another and they are selected from the following 24 candidates:
(1, 0), (2, 0), (3, 0),
(-3, 1), (-2, 1), (-1, 1), (0, 1), (1, 1), (2, 1), (3, 1),
(-3, 2), (-2, 2), (-1, 2), (0, 2), (1, 2), (2, 2), (3, 2),
(-3, 3), (-2, 3), (-1, 3), (0, 3), (1, 3), (2, 3), (3, 3).
Your job in this problem is to write a program that reports the total number of board arrangements which satisfy the given constraint. For example, if relative positions (-2, 1), (-1, 1), (1, 1), (1, 2) are given, the total number of board arrangements is two, where the following two arrangements satisfy the given constraint:
X0 X1 X2 X3 X0 X1 X2 X3
+---+---+---+---+ +---+---+---+---+
Y0 | A | B | C | D | Y0 | A | B | C | D |
+---+---+---+---+ +---+---+---+---+
Y1 | B | A | D | C | Y1 | B | D | E | C |
+---+---+---+---+ +---+---+---+---+
Y2 | E | F | G | H | Y2 | F | A | G | H |
+---+---+---+---+ +---+---+---+---+
Y3 | F | E | H | G | Y3 | G | F | H | E |
+---+---+---+---+ +---+---+---+---+
the relative positions: the relative positions:
A:(1, 1), B:(-1, 1) A:(1, 2), B:(-1, 1)
C:(1, 1), D:(-1, 1) C:(1, 1), D:(-2, 1)
E:(1, 1), F:(-1, 1) E:(1, 2), F:( 1, 1)
G:(1, 1), H:(-1, 1) G:(-2, 1), H:(-1, 1)
Arrangements of the same pattern should be counted only once. Two board arrangements are said to have the same pattern if they are obtained from each other by repeatedly making any two pairs exchange their positions. For example, the following two arrangements have the same pattern:
X0 X1 X2 X3 X0 X1 X2 X3
+---+---+---+---+ +---+---+---+---+
Y0 | H | G | F | E | Y0 | A | B | C | D |
+---+---+---+---+ +---+---+---+---+
Y1 | G | E | D | F | Y1 | B | D | E | C |
+---+---+---+---+ +---+---+---+---+
Y2 | C | H | B | A | Y2 | F | A | G | H |
+---+---+---+---+ +---+---+---+---+
Y3 | B | C | A | D | Y3 | G | F | H | E |
+---+---+---+---+ +---+---+---+---+
where (1) `A' and `H', (2) `B' and `G', (3) `C' and `F', and (4) `D' and `E' exchange their positions respectively.
Input
The input contains multiple data sets, each representing 4 relative positions. A data set is given as a line in the following format.
x1| y1 | x2| y2 | x3| y3 | x4| y4
---|---|---|---|---|---|---|---
The i-th relative position is given by (xi, yi). You may assume that the given relative positions are different from one another and each of them is one of the 24 candidates.
The end of input is indicated by the line which contains a single number greater than 4.
Output
For each data set, your program should output the total number of board arrangements (or more precisely, the total number of patterns).
Each number should be printed in one line. Since your result is checked by an automatic grading program, you should not insert any extra characters nor lines on the output.
Examples
Input
Output
Input
-2 1 -1 1 1 1 1 2
1 0 2 1 2 2 3 3
5
Output
2
15
### Response
```cpp
#define _USE_MATH_DEFINES
#define INF 100000000
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <limits>
#include <map>
#include <string>
#include <cstring>
#include <set>
#include <deque>
#include <bitset>
#include <list>
#include <cctype>
#include <utility>
using namespace std;
typedef long long ll;
typedef pair <string,string> P;
typedef pair <int,P> PP;
static const double EPS = 1e-8;
int tx[4],ty[4];
int dfs(int stage,int c){
if(c==8) return 1;
int res = 0;
int sx = -1;
int sy = -1;
for(int y=0;y<4;y++){
for(int x=0;x<4;x++){
if(~stage & (1<<(y*4+x))){
sx = x;
sy = y;
goto found;
}
}
}
found:;
if(sx == -1) return 0;
for(int i=0;i<4;i++){
int dx = sx + tx[i];
int dy = sy + ty[i];
if(dx < 0 || dx >= 4 || dy < 0 || dy >= 4) continue;
if(stage & (1<<(dy*4+dx))) continue;
stage |= (1<<(dy*4+dx));
stage |= (1<<(sy*4+sx));
res += dfs(stage,c+1);
stage &= ~(1<<(dy*4+dx));
stage &= ~(1<<(sy*4+sx));
}
return res;
}
int main(){
while(~scanf("%d",tx+0)){
if(tx[0] >= 5) break;
scanf("%d %d %d %d %d %d %d",ty+0,tx+1,ty+1,tx+2,ty+2,tx+3,ty+3);
printf("%d\n",dfs(0,0));
}
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.
For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that:
* there wouldn't be a pair of any side-adjacent cards with zeroes in a row;
* there wouldn't be a group of three consecutive cards containing numbers one.
Today Vanya brought n cards with zeroes and m cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.
Input
The first line contains two integers: n (1 β€ n β€ 106) β the number of cards containing number 0; m (1 β€ m β€ 106) β the number of cards containing number 1.
Output
In a single line print the required sequence of zeroes and ones without any spaces. If such sequence is impossible to obtain, print -1.
Examples
Input
1 2
Output
101
Input
4 8
Output
110110110101
Input
4 10
Output
11011011011011
Input
1 5
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
double pi = 3.1415926536;
const int oo = (int)1e9;
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
int di[] = {0, 0, 1, -1, 1, 1, -1, -1};
int dj[] = {1, -1, 0, 0, 1, -1, 1, -1};
int arr[1000001];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, m;
cin >> n >> m;
bool check = true;
string s;
int counter = 0;
while (n--) {
if (check && m >= 2)
s += "101", m -= 2, check = false;
else if (m && !check)
s += "01", m -= 1;
else if (!n)
s += '0';
else
counter++;
}
check = true;
if (counter > 1) check = false;
if (m < 0) {
check = false;
}
bool enter = true;
string final_answer;
if (counter) final_answer += '0';
for (int i = 0; i < ((int)(s).size()); i++) {
if (m && enter) final_answer += '1', m--, enter = false;
final_answer += s[i];
if (s[i] == '0') enter = true;
}
if (m > 0) check = false;
if (!check) {
cout << -1;
} else
cout << final_answer;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
You are given an array s of n non-negative integers.
A 5-tuple of integers (a, b, c, d, e) is said to be valid if it satisfies the following conditions:
* 1 β€ a, b, c, d, e β€ n
* (sa | sb) & sc & (sd ^ se) = 2i for some integer i
* sa & sb = 0
Here, '|' is the bitwise OR, '&' is the bitwise AND and '^' is the bitwise XOR operation.
Find the sum of f(sa|sb) * f(sc) * f(sd^se) over all valid 5-tuples (a, b, c, d, e), where f(i) is the i-th Fibonnaci number (f(0) = 0, f(1) = 1, f(i) = f(i - 1) + f(i - 2)).
Since answer can be is huge output it modulo 109 + 7.
Input
The first line of input contains an integer n (1 β€ n β€ 106).
The second line of input contains n integers si (0 β€ si < 217).
Output
Output the sum as described above, modulo 109 + 7
Examples
Input
2
1 2
Output
32
Input
3
7 4 1
Output
3520
Input
10
1 3 0 7 3 7 6 5 7 5
Output
1235424
Input
10
50 9 11 44 39 40 5 39 23 7
Output
113860062
### Response
```cpp
#include <bits/stdc++.h>
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
const int B = 17;
const int N = 1 << B;
const long long int M = (int)1e9 + 7;
const long long int inv2 = (int)5e8 + 4;
int n;
long long int cnt[N], fib[N], ab[N], Xor[N], And[N];
void transform_xor(long long int x[], bool inv = 0) {
for (int mid = 1, i = 2; i <= N; mid = i, i <<= 1)
for (int j = 0, lo = 0; lo < N; j + 1 == mid ? (lo += i, j = 0) : ++j) {
long long int tw1 = x[lo + j], tw2 = x[lo + j + mid];
if (inv) {
x[lo + j] = (tw1 + tw2) % M * inv2 % M;
x[lo + j + mid] = (tw1 - tw2 + M) % M * inv2 % M;
} else {
x[lo + j] = tw1 + tw2;
if (x[lo + j] >= M) x[lo + j] -= M;
x[lo + j + mid] = tw1 - tw2;
if (x[lo + j + mid] < 0) x[lo + j + mid] += M;
}
}
}
void transform_and(long long int p[], bool inv = 0) {
for (int len = 1; (len << 1) <= N; len <<= 1)
for (int i = 0; i < N; i += (len << 1))
for (int j = 0; j < len; ++j) {
long long int tw1 = p[i + j];
long long int tw2 = p[i + len + j];
if (!inv) {
p[i + j] = tw2;
p[i + len + j] = tw1 + tw2;
if (p[i + len + j] >= M) p[i + len + j] -= M;
} else {
p[i + j] = tw2 - tw1;
if (p[i + j] < 0) p[i + j] += M;
p[i + len + j] = tw1;
}
}
}
void solve(std::istream &in, std::ostream &out) {
fib[0] = 0, fib[1] = 1;
for (int i = 2; i < N; ++i) {
fib[i] = fib[i - 1] + fib[i - 2];
if (fib[i] >= M) fib[i] -= M;
}
in >> n;
for (int i = 1; i <= n; ++i) {
int x;
in >> x;
++cnt[x];
}
for (int i = 0; i < N; ++i) {
ab[i] = 0;
for (int j = (i - 1) & i; j > 0; j = (j - 1) & i) {
ab[i] += cnt[j] * cnt[j ^ i] % M;
if (ab[i] >= M) ab[i] -= M;
}
if (cnt[0] && cnt[i]) {
ab[i] += cnt[0] * cnt[i] * 2 % M;
if (ab[i] >= M) ab[i] -= M;
}
}
memcpy(Xor, cnt, sizeof cnt);
transform_xor(Xor);
for (int i = 0; i < N; ++i) Xor[i] = Xor[i] * Xor[i] % M;
transform_xor(Xor, 1);
for (int i = 0; i < N; ++i)
Xor[i] = Xor[i] * fib[i] % M, ab[i] = ab[i] * fib[i] % M,
cnt[i] = cnt[i] * fib[i] % M;
transform_and(Xor);
transform_and(ab);
transform_and(cnt);
for (int i = 0; i < N; ++i) And[i] = Xor[i] * ab[i] % M * cnt[i] % M;
transform_and(And, 1);
long long int ans = 0;
for (int i = 1; i < N; i <<= 1) ans = (ans + And[i]) % M;
out << ans << '\n';
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
solve(cin, cout);
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
$N$ persons visited a restaurant. The restaurant is open from 0 to $T$. The $i$-th person entered the restaurant at $l_i$ and left at $r_i$. Find the maximum number of persons during the business hours.
Constraints
* $ 1 \leq N \leq 10^5 $
* $ 1 \leq T \leq 10^5 $
* $ 0 \leq l_i < r_i \leq T $
Input
The input is given in the following format.
$N$ $T$
$l_1$ $r_1$
$l_2$ $r_2$
:
$l_N$ $r_N$
Output
Print the maximum number of persons in a line.
Examples
Input
6 10
0 2
1 3
2 6
3 8
4 10
5 10
Output
4
Input
2 2
0 1
1 2
Output
1
### Response
```cpp
#include <iostream>
#include <set>
#include <string>
#include <algorithm>
#include <vector>
#define MAX 1000000001
using namespace std;
#define ll long long
#define dbg if(0)
int main(){
int n,t;
ll ans=-1;
cin>>n>>t;
vector<ll> data(t,0);
for(int i=0;i<n;i++){
int in,out;
cin>> in>>out;
data[in]+=1;
data[out]-=1;
}
ll rui[t+1];
rui[0]=0;
for(int i=1;i<=t;i++){
rui[i]=rui[i-1]+data[i-1];
dbg cout<<rui[i]<<" ";
ans=max(rui[i],ans);
}
cout<<ans<<endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Innopolis University scientists continue to investigate the periodic table. There are nΒ·m known elements and they form a periodic table: a rectangle with n rows and m columns. Each element can be described by its coordinates (r, c) (1 β€ r β€ n, 1 β€ c β€ m) in the table.
Recently scientists discovered that for every four different elements in this table that form a rectangle with sides parallel to the sides of the table, if they have samples of three of the four elements, they can produce a sample of the fourth element using nuclear fusion. So if we have elements in positions (r1, c1), (r1, c2), (r2, c1), where r1 β r2 and c1 β c2, then we can produce element (r2, c2).
<image>
Samples used in fusion are not wasted and can be used again in future fusions. Newly crafted elements also can be used in future fusions.
Innopolis University scientists already have samples of q elements. They want to obtain samples of all nΒ·m elements. To achieve that, they will purchase some samples from other laboratories and then produce all remaining elements using an arbitrary number of nuclear fusions in some order. Help them to find the minimal number of elements they need to purchase.
Input
The first line contains three integers n, m, q (1 β€ n, m β€ 200 000; 0 β€ q β€ min(nΒ·m, 200 000)), the chemical table dimensions and the number of elements scientists already have.
The following q lines contain two integers ri, ci (1 β€ ri β€ n, 1 β€ ci β€ m), each describes an element that scientists already have. All elements in the input are different.
Output
Print the minimal number of elements to be purchased.
Examples
Input
2 2 3
1 2
2 2
2 1
Output
0
Input
1 5 3
1 3
1 1
1 5
Output
2
Input
4 3 6
1 2
1 3
2 2
2 3
3 1
3 3
Output
1
Note
For each example you have a picture which illustrates it.
The first picture for each example describes the initial set of element samples available. Black crosses represent elements available in the lab initially.
The second picture describes how remaining samples can be obtained. Red dashed circles denote elements that should be purchased from other labs (the optimal solution should minimize the number of red circles). Blue dashed circles are elements that can be produced with nuclear fusion. They are numbered in order in which they can be produced.
Test 1
We can use nuclear fusion and get the element from three other samples, so we don't need to purchase anything.
<image>
Test 2
We cannot use any nuclear fusion at all as there is only one row, so we have to purchase all missing elements.
<image>
Test 3
There are several possible solutions. One of them is illustrated below.
Note that after purchasing one element marked as red it's still not possible to immidiately produce the middle element in the bottom row (marked as 4). So we produce the element in the left-top corner first (marked as 1), and then use it in future fusions.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int pa[400001] = {};
int size[400001] = {};
int find_pa(int c) { return pa[c] = pa[c] == c ? c : find_pa(pa[c]); }
void add_edge(int i, int j) {
int p1 = find_pa(i), p2 = find_pa(j);
if (size[p1] < size[p2]) swap(p1, p2);
pa[p2] = p1;
size[p1] += size[p2];
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long int i, n, m, q, r, c, ans = -1;
cin >> n >> m >> q;
for (i = 1; i <= n + m; i++) {
pa[i] = i;
size[i] = 1;
}
for (i = 0; i < q; i++) {
cin >> r >> c;
add_edge(r, n + c);
}
for (i = 1; i <= n + m; i++)
if (pa[i] == i) ans++;
cout << ans;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Roman is a young mathematician, very famous in Uzhland. Unfortunately, Sereja doesn't think so. To make Sereja change his mind, Roman is ready to solve any mathematical problem. After some thought, Sereja asked Roma to find, how many numbers are close to number n, modulo m.
Number x is considered close to number n modulo m, if:
* it can be obtained by rearranging the digits of number n,
* it doesn't have any leading zeroes,
* the remainder after dividing number x by m equals 0.
Roman is a good mathematician, but the number of such numbers is too huge for him. So he asks you to help him.
Input
The first line contains two integers: n (1 β€ n < 1018) and m (1 β€ m β€ 100).
Output
In a single line print a single integer β the number of numbers close to number n modulo m.
Examples
Input
104 2
Output
3
Input
223 4
Output
1
Input
7067678 8
Output
47
Note
In the first sample the required numbers are: 104, 140, 410.
In the second sample the required number is 232.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long dp[(1 << 18)][101], n, m;
long long v[22], gigi;
string str;
int main() {
ios::sync_with_stdio(false);
cin >> str >> m;
n = str.size();
for (int i = str.size() - 1; i >= 0; i--) {
if (i == str.size() - 1)
v[i] = 1;
else
v[i] = v[i + 1] * 10;
}
dp[0][0] = 1;
for (int mask = 0; mask <= (1 << n) - 1; mask++) {
for (int r = 0; r <= m - 1; r++) {
int can[10], p = 0;
for (int i = 0; i <= 9; i++) can[i] = -1;
for (int i = 0; i <= n - 1; i++) {
if (mask & (1 << i)) {
p++;
continue;
}
int c = str[i] - '0';
can[c] = i;
}
for (int i = 0; i <= 9; i++) {
if (!mask && !i) continue;
if (can[i] == -1) continue;
long long newMask = mask | (1 << can[i]), nr = (r + (i * v[p])) % m;
dp[newMask][nr] += dp[mask][r];
}
}
}
cout << dp[(1 << n) - 1][0] << endl;
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
JOI Park
In preparation for the Olympic Games in IOI in 20XX, the JOI Park in IOI will be developed. There are N squares in JOI Park, and the squares are numbered from 1 to N. There are M roads connecting the squares, and the roads are numbered from 1 to M. The road i (1 β€ i β€ M) connects the square Ai and the square Bi in both directions, and the length is Di. You can follow several paths from any square to any square.
In the maintenance plan, first select an integer X of 0 or more, and connect all the squares (including square 1) whose distance from square 1 is X or less to each other by an underpass. However, the distance between the square i and the square j is the minimum value of the sum of the lengths of the roads taken when going from the square i to the square j. In the maintenance plan, the integer C for the maintenance cost of the underpass is fixed. The cost of developing an underpass is C x X.
Next, remove all the roads connecting the plazas connected by the underpass. There is no cost to remove the road. Finally, repair all the roads that remained unremoved. The cost of repairing a road of length d is d. There is no underpass in JOI Park before the implementation of the maintenance plan. Find the minimum sum of the costs of developing the JOI Park.
Task
Given the information on the JOI Park Square and an integer for the underpass maintenance cost, create a program to find the minimum sum of the costs for the JOI Park maintenance.
input
Read the following data from standard input.
* On the first line, the integers N, M, and C are written with blanks as delimiters. This means that there are N squares, M roads, and the integer for the underpass maintenance cost is C.
* On the i-th line (1 β€ i β€ M) of the following M lines, the integers Ai, Bi, and Di are written separated by blanks. This means that the road i connects the square Ai and the square Bi, and the length is Di.
output
Output an integer representing the minimum sum of the costs of developing the JOI park to the standard output on one line.
Limits
All input data satisfy the following conditions.
* 2 β€ N β€ 100 000.
* 1 β€ M β€ 200 000.
* 1 β€ C β€ 100 000.
* 1 β€ Ai β€ N (1 β€ i β€ M).
* 1 β€ Bi β€ N (1 β€ i β€ M).
* Ai β Bi (1 β€ i β€ M).
* (Ai, Bi) β (Aj, Bj) and (Ai, Bi) β (Bj, Aj) (1 β€ i <j β€ M).
* 1 β€ Di β€ 100 000 (1 β€ i β€ M).
* With the input data given, it is guaranteed that you can go from any square to any square by following several paths.
Input / output example
Input example 1
5 5 2
2 3 1
3 1 2
2 4 3
1 2 4
2 5 5
Output example 1
14
In this input example, when X = 3, the sum of the maintenance costs when all the squares (square 1, square 2, square 3) whose distance from square 1 is 3 or less are connected to each other by an underpass. Is 2 Γ 3 + 3 + 5 = 14. This is the minimum value.
Input example 2
5 4 10
one two Three
2 3 4
3 4 3
4 5 5
Output example 2
15
In this input example, the sum of maintenance costs is minimized when X = 0.
Input example 3
6 5 2
1 2 2
1 3 4
1 4 3
1 5 1
1 6 5
Output example 3
Ten
In this input example, when all the squares are connected to each other by an underpass with X = 5, the sum of the maintenance costs is minimized.
The question text and the data used for the automatic referee are the question text and the test data for scoring, which are created and published by the Japan Committee for Information Olympics.
Example
Input
5 5 2
2 3 1
3 1 2
2 4 3
1 2 4
2 5 5
Output
14
### Response
```cpp
#include <cstdio>
#include <algorithm>
#include <queue>
#include <utility>
#include <vector>
#include <iostream>
using namespace std;
typedef long long ll;
typedef pair<ll,int> P;
#define INF 30000000000000000ll
#define fi first
#define sec second
#define pb push_back
ll dist[100100];
ll ava[100100];
vector<P> vec;
int N,M;
ll C;
struct edge
{
int to;
ll cost;
edge(int to,ll cost):to(to),cost(cost){}
};
vector<edge> g[100100];
void dijkstra()
{
for(int i=0;i<N;i++)dist[i]=INF;
dist[0]=0;
priority_queue<P,vector<P>,greater<P> > q;
q.push(P(0ll,0));
while(!q.empty())
{
P a = q.top();
q.pop();
int v = a.sec;
for(int i=0;i<g[v].size();i++)
{
edge e = g[v][i];
if(dist[e.to]>dist[v]+e.cost)
{
dist[e.to]=dist[v]+e.cost;
q.push(P(dist[e.to],e.to));
}
}
}
return;
}
int main()
{
ll sum = 0ll;
scanf("%d %d %lld",&N,&M,&C);
for(int i=0;i<M;i++)
{
int a,b;
ll c;
scanf("%d %d %lld",&a,&b,&c);
a--;b--;
sum+=c;
g[a].pb(edge(b,c));
g[b].pb(edge(a,c));
}
dijkstra();
for(int i=0;i<N;i++)vec.pb(P(dist[i],i));
sort(vec.begin(),vec.end());
ll ans = INF;
for(int i=0;i<N;i++)
{
int v = vec[i].sec;
//cout << v << endl;
sum -= ava[v];
ans = min(C*vec[i].fi+sum,ans);
//cout << C*vec[i].fi << ' ' << sum << endl;
for(int j=0;j<g[v].size();j++)
{
edge e = g[v][j];
ava[e.to]+=e.cost;
}
}
printf("%lld\n",ans);
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Another dull quarantine day was going by when BThero decided to start researching matrices of size n Γ m. The rows are numerated 1 through n from top to bottom, and the columns are numerated 1 through m from left to right. The cell in the i-th row and j-th column is denoted as (i, j).
For each cell (i, j) BThero had two values:
1. The cost of the cell, which is a single positive integer.
2. The direction of the cell, which is one of characters L, R, D, U. Those characters correspond to transitions to adjacent cells (i, j - 1), (i, j + 1), (i + 1, j) or (i - 1, j), respectively. No transition pointed outside of the matrix.
Let us call a cell (i_2, j_2) reachable from (i_1, j_1), if, starting from (i_1, j_1) and repeatedly moving to the adjacent cell according to our current direction, we will, sooner or later, visit (i_2, j_2).
BThero decided to create another matrix from the existing two. For a cell (i, j), let us denote S_{i, j} as a set of all reachable cells from it (including (i, j) itself). Then, the value at the cell (i, j) in the new matrix will be equal to the sum of costs of all cells in S_{i, j}.
After quickly computing the new matrix, BThero immediately sent it to his friends. However, he did not save any of the initial matrices! Help him to restore any two valid matrices, which produce the current one.
Input
The first line of input file contains a single integer T (1 β€ T β€ 100) denoting the number of test cases. The description of T test cases follows.
First line of a test case contains two integers n and m (1 β€ n β
m β€ 10^5).
Each of the following n lines contain exactly m integers β the elements of the produced matrix. Each element belongs to the segment [2, 10^9].
It is guaranteed that β{(n β
m)} over all test cases does not exceed 10^5.
Output
For each test case, if an answer does not exist, print a single word NO. Otherwise, print YES and both matrices in the same format as in the input.
* The first matrix should be the cost matrix and the second matrix should be the direction matrix.
* All integers in the cost matrix should be positive.
* All characters in the direction matrix should be valid. No direction should point outside of the matrix.
Example
Input
2
3 4
7 6 7 8
5 5 4 4
5 7 4 4
1 1
5
Output
YES
1 1 1 1
2 1 1 1
3 2 1 1
R D L L
D R D L
U L R U
NO
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int a[N];
int n, m;
int p[5][2] = {0, 0, -1, 0, 1, 0, 0, 1, 0, -1};
bool lim[N];
int link[N], used[N];
int to[10 * N], lst[N], nxt[10 * N], cnt;
int ans[N];
char d[N];
int C(int x, int y) { return x * m + y; }
pair<int, int> C(int x) {
return x < 0 | x >= n * m ? make_pair(-1, -1) : make_pair(x / m, x % m);
}
bool dfs(int u, int cas) {
for (int k = lst[u]; k != 0; k = nxt[k]) {
int v = to[k];
if (used[v] != cas) {
used[v] = cas;
if (link[v] == -1 || dfs(link[v], cas)) {
link[u] = v;
link[v] = u;
return 1;
} else {
if (lim[link[v]] == 0) {
link[link[v]] = -1;
link[u] = v;
link[v] = u;
return 1;
}
}
}
}
return 0;
}
void Add(int u, int v) {
cnt++, nxt[cnt] = lst[u], to[cnt] = v, lst[u] = cnt;
cnt++, nxt[cnt] = lst[v], to[cnt] = u, lst[v] = cnt;
}
char T(int x, int y, int xx, int yy) {
if (yy == y + 1) return 'R';
if (yy == y - 1) return 'L';
if (xx == x - 1) return 'U';
if (xx == x + 1) return 'D';
}
void Find(int u) {
pair<int, int> cor = C(u);
int x = cor.first, y = cor.second;
if (link[u] == -1) {
for (int k = 1; k <= 4; k++) {
int xx = x + p[k][0], yy = y + p[k][1];
if (xx < 0 || xx >= n || yy < 0 || yy >= m || a[C(xx, yy)] >= a[u])
continue;
d[u] = T(x, y, xx, yy);
ans[u] = a[u] - a[C(xx, yy)];
break;
}
} else {
int xx, yy;
pair<int, int> corr;
corr = C(link[u]);
xx = corr.first, yy = corr.second;
d[u] = T(x, y, xx, yy);
if (ans[link[u]])
ans[u] = a[u] - ans[link[u]];
else
ans[u] = 1;
}
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
scanf("%d %d", &n, &m);
for (int i = 0; i <= n * m - 1; i++) link[i] = -1;
for (int i = 0; i <= n * m - 1; i++) scanf("%d", &a[i]);
bool ok = 1;
for (int i = 0; i <= n * m - 1; i++) {
pair<int, int> xy = C(i);
bool flag = 0;
int num = 0;
for (int k = 1; k <= 4; k++) {
int x = xy.first + p[k][0], y = xy.second + p[k][1];
if (x < 0 || x >= n || y < 0 || y >= m || a[C(x, y)] > a[i]) continue;
flag = 1;
if (a[C(x, y)] == a[i] && C(x, y) < i)
Add(C(x, y), i);
else if (a[C(x, y)] != a[i])
num++;
}
if (!flag) {
ok = 0;
break;
}
if (num == 0) lim[i] = 1;
}
if (!ok) {
printf("NO\n");
continue;
}
int cas = 0;
for (int i = 0; i <= n * m - 1; i++) {
if (!lim[i]) continue;
if (link[i] == -1 && !dfs(i, ++cas)) {
ok = 0;
break;
}
}
if (!ok) {
printf("NO\n");
continue;
}
for (int i = 0; i <= n * m - 1; i++)
if (ans[i] == 0) Find(i);
printf("YES\n");
for (int i = 0; i <= n - 1; i++) {
for (int j = 0; j <= m - 1; j++) printf("%d ", ans[C(i, j)]);
printf("\n");
}
for (int i = 0; i <= n - 1; i++) {
for (int j = 0; j <= m - 1; j++) printf("%c ", d[C(i, j)]);
printf("\n");
}
cnt = 0;
for (int i = 0; i <= n * m - 1; i++)
lim[i] = ans[i] = d[i] = used[i] = lst[i] = 0, link[i] = -1;
}
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
You have a knapsack with the capacity of W. There are also n items, the i-th one has weight w_i.
You want to put some of these items into the knapsack in such a way that their total weight C is at least half of its size, but (obviously) does not exceed it. Formally, C should satisfy: β W/2β β€ C β€ W.
Output the list of items you will put into the knapsack or determine that fulfilling the conditions is impossible.
If there are several possible lists of items satisfying the conditions, you can output any. Note that you don't have to maximize the sum of weights of items in the knapsack.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 10^4). Description of the test cases follows.
The first line of each test case contains integers n and W (1 β€ n β€ 200 000, 1β€ W β€ 10^{18}).
The second line of each test case contains n integers w_1, w_2, ..., w_n (1 β€ w_i β€ 10^9) β weights of the items.
The sum of n over all test cases does not exceed 200 000.
Output
For each test case, if there is no solution, print a single integer -1.
If there exists a solution consisting of m items, print m in the first line of the output and m integers j_1, j_2, ..., j_m (1 β€ j_i β€ n, all j_i are distinct) in the second line of the output β indices of the items you would like to pack into the knapsack.
If there are several possible lists of items satisfying the conditions, you can output any. Note that you don't have to maximize the sum of weights items in the knapsack.
Example
Input
3
1 3
3
6 2
19 8 19 69 9 4
7 12
1 1 1 17 1 1 1
Output
1
1
-1
6
1 2 3 5 6 7
Note
In the first test case, you can take the item of weight 3 and fill the knapsack just right.
In the second test case, all the items are larger than the knapsack's capacity. Therefore, the answer is -1.
In the third test case, you fill the knapsack exactly in half.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct node {
long long int p;
long long int q;
};
vector<long long int> v;
struct node a[200005];
bool ram(struct node x, struct node y) { return x.p < y.p; }
int main() {
long long int b[200005], x, y, z, i, flag, l, j;
cin >> x;
while (x--) {
cin >> y >> z;
a[0].p = 0;
for (i = 1; i <= y; i++) {
cin >> a[i].p;
a[i].q = i;
}
sort(a, a + y + 1, ram);
b[0] = 0;
for (i = 1; i <= y; i++) b[i] = a[i].p + b[i - 1];
i = 0;
j = 1;
while (i < j && j <= y && i <= y) {
if (b[j] - b[i] >= ((z + 1) / 2) && b[j] - b[i] <= z) {
for (int k = i + 1; k <= j; k++) v.push_back(a[k].q);
break;
} else if (b[j] - b[i] > z)
i++;
else if (b[j] - b[i] < (z + 1) / 2)
j++;
}
if (v.size() == 0)
cout << -1 << endl;
else {
cout << v.size() << endl;
for (auto k : v) cout << k << " ";
cout << endl;
}
v.clear();
}
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.
Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army β formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:
* if you are currently in the castle i, you may leave one warrior to defend castle i;
* there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v.
Obviously, when you order your warrior to defend some castle, he leaves your army.
You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.
If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it β your score will be calculated afterwards).
Can you determine an optimal strategy of capturing and defending the castles?
Input
The first line contains three integers n, m and k (1 β€ n β€ 5000, 0 β€ m β€ min((n(n - 1))/(2), 3 β
10^5), 0 β€ k β€ 5000) β the number of castles, the number of portals and initial size of your army, respectively.
Then n lines follow. The i-th line describes the i-th castle with three integers a_i, b_i and c_i (0 β€ a_i, b_i, c_i β€ 5000) β the number of warriors required to capture the i-th castle, the number of warriors available for hire in this castle and its importance value.
Then m lines follow. The i-th line describes the i-th portal with two integers u_i and v_i (1 β€ v_i < u_i β€ n), meaning that the portal leads from the castle u_i to the castle v_i. There are no two same portals listed.
It is guaranteed that the size of your army won't exceed 5000 under any circumstances (i. e. k + β_{i = 1}^{n} b_i β€ 5000).
Output
If it's impossible to capture all the castles, print one integer -1.
Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
Examples
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
Note
The best course of action in the first example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now.
This course of action (and several other ones) gives 5 as your total score.
The best course of action in the second example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now;
8. send one warrior to protect the first castle through the third portal, your army has 11 warriors now.
This course of action (and several other ones) gives 22 as your total score.
In the third example it's impossible to capture the last castle: you need 14 warriors to do so, but you can accumulate no more than 13 without capturing it.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 5005;
int n, m, k, a[N], b[N], c[N], mx[N], dp[N];
vector<int> G[N];
int main() {
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= n; i++) {
scanf("%d%d%d", &a[i], &b[i], &c[i]);
mx[i] = i;
}
for (int i = 1, u, v; i <= m; i++) {
scanf("%d%d", &u, &v);
mx[v] = max(mx[v], u);
}
for (int i = 1; i <= n; i++) G[mx[i]].push_back(c[i]);
for (int i = k + 1; i < N; i++) dp[i] = -1;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < a[i]; j++) dp[j] = -1;
for (int j = N - 1; j >= b[i]; j--) dp[j] = dp[j - b[i]];
for (auto v : G[i]) {
for (int j = 0; j < N - 1; j++) {
if (dp[j + 1] == -1) continue;
dp[j] = max(dp[j], dp[j + 1] + v);
}
}
}
int ans = -1;
for (int i = 0; i < N; i++) ans = max(ans, dp[i]);
printf("%d\n", ans);
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
When Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word "tma" (which now means "too much to be counted") used to stand for a thousand and "tma tmyschaya" (which literally means "the tma of tmas") used to stand for a million.
Petya wanted to modernize the words we use for numbers and invented a word petricium that represents number k. Moreover, petricium la petricium stands for number k2, petricium la petricium la petricium stands for k3 and so on. All numbers of this form are called petriciumus cifera, and the number's importance is the number of articles la in its title.
Petya's invention brought on a challenge that needed to be solved quickly: does some number l belong to the set petriciumus cifera? As Petya is a very busy schoolboy he needs to automate the process, he asked you to solve it.
Input
The first input line contains integer number k, the second line contains integer number l (2 β€ k, l β€ 231 - 1).
Output
You should print in the first line of the output "YES", if the number belongs to the set petriciumus cifera and otherwise print "NO". If the number belongs to the set, then print on the seconds line the only number β the importance of number l.
Examples
Input
5
25
Output
YES
1
Input
3
8
Output
NO
### Response
```cpp
#include <bits/stdc++.h>
int n, k, s;
int main() {
scanf("%d%d", &k, &n);
while (n > k && n % k == 0) {
s++;
n /= k;
}
if (n != k)
printf("NO\n");
else
printf("YES\n%d\n", s);
}
``` |
### Prompt
Create a solution in CPP for the following problem:
For the multiset of positive integers s=\\{s_1,s_2,...,s_k\}, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of s as follow:
* \gcd(s) is the maximum positive integer x, such that all integers in s are divisible on x.
* lcm(s) is the minimum positive integer x, that divisible on all integers from s.
For example, \gcd(\{8,12\})=4,\gcd(\{12,18,6\})=6 and lcm(\{4,6\})=12. Note that for any positive integer x, \gcd(\\{x\})=lcm(\\{x\})=x.
Orac has a sequence a with length n. He come up with the multiset t=\{lcm(\\{a_i,a_j\})\ |\ i<j\}, and asked you to find the value of \gcd(t) for him. In other words, you need to calculate the GCD of LCMs of all pairs of elements in the given sequence.
Input
The first line contains one integer n\ (2β€ nβ€ 100 000).
The second line contains n integers, a_1, a_2, β¦, a_n (1 β€ a_i β€ 200 000).
Output
Print one integer: \gcd(\{lcm(\\{a_i,a_j\})\ |\ i<j\}).
Examples
Input
2
1 1
Output
1
Input
4
10 24 40 80
Output
40
Input
10
540 648 810 648 720 540 594 864 972 648
Output
54
Note
For the first example, t=\{lcm(\{1,1\})\}=\{1\}, so \gcd(t)=1.
For the second example, t=\{120,40,80,120,240,80\}, and it's not hard to see that \gcd(t)=40.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n, i, a[100005], suf[100005];
ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); }
int main() {
scanf("%lld", &n);
for (i = 1; i <= n; i++) scanf("%lld", &a[i]);
for (i = n; i >= 1; i--) suf[i] = gcd(suf[i + 1], a[i]);
ll ans = 0;
for (i = 1; i <= n - 1; i++)
ans = gcd(ans, a[i] / gcd(a[i], suf[i + 1]) * suf[i + 1]);
cout << ans << endl;
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
You are given a sequence of numbers a1, a2, ..., an, and a number m.
Check if it is possible to choose a non-empty subsequence aij such that the sum of numbers in this subsequence is divisible by m.
Input
The first line contains two numbers, n and m (1 β€ n β€ 106, 2 β€ m β€ 103) β the size of the original sequence and the number such that sum should be divisible by it.
The second line contains n integers a1, a2, ..., an (0 β€ ai β€ 109).
Output
In the single line print either "YES" (without the quotes) if there exists the sought subsequence, or "NO" (without the quotes), if such subsequence doesn't exist.
Examples
Input
3 5
1 2 3
Output
YES
Input
1 6
5
Output
NO
Input
4 6
3 1 1 3
Output
YES
Input
6 6
5 5 5 5 5 5
Output
YES
Note
In the first sample test you can choose numbers 2 and 3, the sum of which is divisible by 5.
In the second sample test the single non-empty subsequence of numbers is a single number 5. Number 5 is not divisible by 6, that is, the sought subsequence doesn't exist.
In the third sample test you need to choose two numbers 3 on the ends.
In the fourth sample test you can take the whole subsequence.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b) {
int r, i;
while (b != 0) {
r = a % b;
a = b;
b = r;
}
return a;
}
long long int a[1000100];
long long int b[1000100];
long long int c[10001];
int main() {
long long int i, j, n, m, k, x;
scanf("%lld", &n);
scanf("%lld", &m);
set<long long int> s1;
map<long long int, long long int> mp;
int f = 0;
for (i = (0); i < (n); i++) {
scanf("%lld", &a[i]);
k = a[i] % m;
if (k == 0) {
f = 1;
}
if (f == 0) {
if (i == 0) {
s1.insert(k);
mp[k] = 1;
} else {
long long int ar[1001];
j = 0;
long long int v1 = a[i] % m;
if (v1 == 0) {
f = 1;
} else {
ar[j++] = v1;
}
set<long long int>::iterator it;
for (it = s1.begin(); it != s1.end(); it++) {
long long int po = *it;
long long int vv = (po + a[i]) % m;
if (vv == 0) {
f = 1;
break;
}
ar[j++] = vv;
}
if (f == 0) {
int i1;
for (i1 = 0; i1 < j; i1++) {
s1.insert(ar[i1]);
mp[ar[i1]] = 1;
}
}
}
}
}
if (f == 1)
cout << "YES\n";
else
cout << "NO\n";
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
You have an array a consisting of n integers. Each integer from 1 to n appears exactly once in this array.
For some indices i (1 β€ i β€ n - 1) it is possible to swap i-th element with (i + 1)-th, for other indices it is not possible. You may perform any number of swapping operations any order. There is no limit on the number of times you swap i-th element with (i + 1)-th (if the position is not forbidden).
Can you make this array sorted in ascending order performing some sequence of swapping operations?
Input
The first line contains one integer n (2 β€ n β€ 200000) β the number of elements in the array.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 200000) β the elements of the array. Each integer from 1 to n appears exactly once.
The third line contains a string of n - 1 characters, each character is either 0 or 1. If i-th character is 1, then you can swap i-th element with (i + 1)-th any number of times, otherwise it is forbidden to swap i-th element with (i + 1)-th.
Output
If it is possible to sort the array in ascending order using any sequence of swaps you are allowed to make, print YES. Otherwise, print NO.
Examples
Input
6
1 2 5 3 4 6
01110
Output
YES
Input
6
1 2 5 3 4 6
01010
Output
NO
Note
In the first example you may swap a3 and a4, and then swap a4 and a5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
int v[n];
for (int i = 0; i < n; i++) cin >> v[i];
vector<pair<int, int> > to_sort;
int l = -1;
for (int i = 0; i < n - 1; i++) {
char c;
cin >> c;
if (c == '1') {
if (l == -1) l = i;
} else {
if (l != -1) sort(v + l, v + i + 1);
l = -1;
}
}
if (l != -1 && l < n) sort(v + l, v + n);
bool ordered = true;
for (int i = 1; i < n; i++)
if (v[i - 1] > v[i]) ordered = false;
if (ordered)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Amugae is in a very large round corridor. The corridor consists of two areas. The inner area is equally divided by n sectors, and the outer area is equally divided by m sectors. A wall exists between each pair of sectors of same area (inner or outer), but there is no wall between the inner area and the outer area. A wall always exists at the 12 o'clock position.
<image>
The inner area's sectors are denoted as (1,1), (1,2), ..., (1,n) in clockwise direction. The outer area's sectors are denoted as (2,1), (2,2), ..., (2,m) in the same manner. For a clear understanding, see the example image above.
Amugae wants to know if he can move from one sector to another sector. He has q questions.
For each question, check if he can move between two given sectors.
Input
The first line contains three integers n, m and q (1 β€ n, m β€ 10^{18}, 1 β€ q β€ 10^4) β the number of sectors in the inner area, the number of sectors in the outer area and the number of questions.
Each of the next q lines contains four integers s_x, s_y, e_x, e_y (1 β€ s_x, e_x β€ 2; if s_x = 1, then 1 β€ s_y β€ n, otherwise 1 β€ s_y β€ m; constraints on e_y are similar). Amague wants to know if it is possible to move from sector (s_x, s_y) to sector (e_x, e_y).
Output
For each question, print "YES" if Amugae can move from (s_x, s_y) to (e_x, e_y), and "NO" otherwise.
You can print each letter in any case (upper or lower).
Example
Input
4 6 3
1 1 2 3
2 6 1 2
2 6 2 4
Output
YES
NO
YES
Note
Example is shown on the picture in the statement.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 4e5 + 7;
long long n, m, q;
long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }
int main() {
scanf("%lld%lld%lld", &n, &m, &q);
long long d = gcd(n, m);
long long t1 = n / d;
long long t2 = m / d;
while (q--) {
long long x, y, a, b;
scanf("%lld%lld%lld%lld", &x, &y, &a, &b);
if (n == 1 || m == 1) {
printf("YES\n");
continue;
}
if (x == a) {
if (x == 1) {
if ((y - 1) / t1 == (b - 1) / t1)
printf("YES\n");
else
printf("NO\n");
} else {
if ((y - 1) / t2 == (b - 1) / t2)
printf("YES\n");
else
printf("NO\n");
}
} else {
if (x == 1) {
if ((y - 1) / t1 == (b - 1) / t2)
printf("YES\n");
else
printf("NO\n");
} else {
if ((y - 1) / t2 == (b - 1) / t1)
printf("YES\n");
else
printf("NO\n");
}
}
}
}
``` |
### Prompt
Generate a CPP solution to the following problem:
You are given sequence a1, a2, ..., an and m queries lj, rj (1 β€ lj β€ rj β€ n). For each query you need to print the minimum distance between such pair of elements ax and ay (x β y), that:
* both indexes of the elements lie within range [lj, rj], that is, lj β€ x, y β€ rj;
* the values of the elements are equal, that is ax = ay.
The text above understands distance as |x - y|.
Input
The first line of the input contains a pair of integers n, m (1 β€ n, m β€ 5Β·105) β the length of the sequence and the number of queries, correspondingly.
The second line contains the sequence of integers a1, a2, ..., an ( - 109 β€ ai β€ 109).
Next m lines contain the queries, one per line. Each query is given by a pair of numbers lj, rj (1 β€ lj β€ rj β€ n) β the indexes of the query range limits.
Output
Print m integers β the answers to each query. If there is no valid match for some query, please print -1 as an answer to this query.
Examples
Input
5 3
1 1 2 3 2
1 5
2 4
3 5
Output
1
-1
2
Input
6 5
1 2 1 3 2 3
4 6
1 3
2 5
2 4
1 6
Output
2
2
3
-1
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int inf = (int)1e9, maxn = (int)1e5 + 1;
const double eps = (double)1e-8;
const int mod = (int)1000000009;
int x, l, r, a[1000006], b[1000006], n, m, ans;
vector<pair<int, int> > p[2000006];
map<int, int> ma;
void build(int v, int l, int r) {
if (l == r) {
if (b[l] > 0) p[v].push_back(make_pair(b[l], b[l] - l));
return;
}
int m, to1, to2;
m = (l + r) / 2;
to1 = v * 2;
to2 = v * 2 + 1;
build(to1, l, m);
build(to2, m + 1, r);
for (int i = 0; i < p[to1].size(); i++) p[v].push_back(p[to1][i]);
for (int i = 0; i < p[to2].size(); i++) p[v].push_back(p[to2][i]);
sort(p[v].begin(), p[v].begin() + p[v].size());
for (int i = 1; i < p[v].size(); i++)
p[v][i].second = (min(p[v][i].second, p[v][i - 1].second));
return;
}
void dzen(int v, int l, int r, int tl, int tr) {
if (r < tl || l > tr) return;
int m;
if (l >= tl && r <= tr) {
l = 0;
r = p[v].size() - 1;
if (r == -1) return;
while (l < r) {
m = (l + r) / 2;
if (p[v][m].first >= tr)
r = m;
else
l = m + 1;
}
l = min((int)p[v].size() - 1, l);
if (p[v][l].first > tr) l--;
if (l >= 0) {
x = p[v][l].second;
if (ans == -1 || ans > x) ans = x;
}
return;
}
m = (l + r) / 2;
dzen(2 * v, l, m, tl, tr);
dzen(2 * v + 1, m + 1, r, tl, tr);
return;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
scanf("%d", &(a[i]));
x = ma[a[i]];
if (x > 0) b[x] = i;
ma[a[i]] = i;
}
build(1, 1, n);
while (m--) {
scanf("%d", &(l));
scanf("%d", &(r));
ans = -1;
dzen(1, 1, n, l, r);
cout << ans;
printf("\n");
}
return 0;
}
``` |
### Prompt
Generate 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;
long long t[1000000];
long long a[1000000], f[1000000];
void build(long long v, long long tl, long long tr) {
if (tl == tr) {
t[v] = 0;
} else {
long long tm = (tl + tr) / 2;
build(v * 2, tl, tm);
build(v * 2 + 1, tm + 1, tr);
t[v] = 0;
}
}
void update(long long v, long long tl, long long tr, long long pos,
long long new_val) {
if (tl == tr) {
t[v] = new_val;
} else {
long long tm = (tl + tr) / 2;
if (pos <= tm)
update(v * 2, tl, tm, pos, new_val);
else
update(v * 2 + 1, tm + 1, tr, pos, new_val);
t[v] = max(t[v * 2], t[v * 2 + 1]);
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
long long q, n, i, j, c, k, m, x, y;
cin >> q;
while (q--) {
cin >> n;
for (i = 0; i < n; i++) cin >> x, a[x] = i;
for (i = 0; i < n; i++) {
f[i] = 0;
}
build(1, 0, n - 1);
c = 1;
for (i = 1; i <= n; i++) {
m = t[1];
if (f[a[i]] == m) {
update(1, 0, n - 1, a[i], -1);
if (a[i] != n - 1) {
if (f[a[i] + 1] != -1) {
f[a[i] + 1] = f[a[i]] + 1;
update(1, 0, n - 1, a[i] + 1, f[a[i]] + 1);
}
}
f[a[i]] = -1;
} else {
c = 0;
}
}
if (c)
cout << "Yes\n";
else
cout << "No\n";
}
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Argus was charged with guarding Io, which is not an ordinary cow. Io is quite an explorer, and she wanders off rather frequently, making Argus' life stressful. So the cowherd decided to construct an enclosed pasture for Io.
There are n trees growing along the river, where Argus tends Io. For this problem, the river can be viewed as the OX axis of the Cartesian coordinate system, and the n trees as points with the y-coordinate equal 0. There is also another tree growing in the point (0, 1).
Argus will tie a rope around three of the trees, creating a triangular pasture. Its exact shape doesn't matter to Io, but its area is crucial to her. There may be many ways for Argus to arrange the fence, but only the ones which result in different areas of the pasture are interesting for Io. Calculate the number of different areas that her pasture may have. Note that the pasture must have nonzero area.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 100) β the number of test cases. Then t test cases follow, each one is described in two lines.
In the first line of each test case there is a single integer n (1 β€ n β€ 50) denoting the number of trees growing along the river. Next line contains n distinct integers x_1 < x_2 < β¦ < x_{n - 1} < x_n (1 β€ x_i β€ 50), the x-coordinates of trees growing along the river.
Output
In a single line output an integer, the number of different nonzero areas that triangles with trees as vertices may have.
Example
Input
8
4
1 2 4 5
3
1 3 5
3
2 6 8
2
1 2
1
50
5
3 4 5 6 8
3
1 25 26
6
1 2 4 8 16 32
Output
4
2
3
1
0
5
3
15
Note
In the first test case, we have 6 non-degenerate triangles with the following areas: 0.5, 0.5, 1, 1.5, 1.5 and 2. The pasture can have 4 different areas, and thus 4 is the answer.
In the second test case, we have 3 non-degenerate triangles with the following areas: 1, 1 and 2. The pasture can have 2 different areas, so 2 is the answer.
The following two drawings present the situation in the second test case. The blue triangles in the first drawing have area 1. The red triangle in the second drawing has area 2.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 55;
int T;
int n;
int a[N];
int main() {
scanf("%d", &T);
while (T --) {
scanf("%d", &n);
for (int i = 0; i < n; ++i) scanf("%d", &a[i]);
set<int> ans;
for (int i = 0; i < n - 1; ++i) {
for (int j = i + 1; j < n; ++j) {
ans.insert(a[j] - a[i]);
}
}
printf("%d\n", ans.size());
}
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Grandma Laura came to the market to sell some apples. During the day she sold all the apples she had. But grandma is old, so she forgot how many apples she had brought to the market.
She precisely remembers she had n buyers and each of them bought exactly half of the apples she had at the moment of the purchase and also she gave a half of an apple to some of them as a gift (if the number of apples at the moment of purchase was odd), until she sold all the apples she had.
So each buyer took some integral positive number of apples, but maybe he didn't pay for a half of an apple (if the number of apples at the moment of the purchase was odd).
For each buyer grandma remembers if she gave a half of an apple as a gift or not. The cost of an apple is p (the number p is even).
Print the total money grandma should have at the end of the day to check if some buyers cheated her.
Input
The first line contains two integers n and p (1 β€ n β€ 40, 2 β€ p β€ 1000) β the number of the buyers and the cost of one apple. It is guaranteed that the number p is even.
The next n lines contains the description of buyers. Each buyer is described with the string half if he simply bought half of the apples and with the string halfplus if grandma also gave him a half of an apple as a gift.
It is guaranteed that grandma has at least one apple at the start of the day and she has no apples at the end of the day.
Output
Print the only integer a β the total money grandma should have at the end of the day.
Note that the answer can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.
Examples
Input
2 10
half
halfplus
Output
15
Input
3 10
halfplus
halfplus
halfplus
Output
55
Note
In the first sample at the start of the day the grandma had two apples. First she sold one apple and then she sold a half of the second apple and gave a half of the second apple as a present to the second buyer.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, p;
string a[101000];
cin >> n >> p;
long long num = 0, ans = 0;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = n; i >= 1; i--) {
num *= 2;
if (a[i] == "halfplus") num += 1;
ans += num * p;
}
cout << ans / 2 << endl;
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions:
* The length of t does not exceed the length of s.
* t is a palindrome.
* There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 1000), the number of test cases. The next t lines each describe a test case.
Each test case is a non-empty string s, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed 5000.
Output
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
Example
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
Note
In the first test, the string s = "a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because:
* Its length is 9, which does not exceed the length of the string s, which equals 11.
* It is a palindrome.
* "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool pal(string s) {
string rs = s;
reverse(rs.begin(), rs.end());
return rs == s;
}
int longest_palindrome_prefix(const string &s) {
string kmprev = s;
std::reverse(kmprev.begin(), kmprev.end());
string kmp = s + "#" + kmprev;
vector<int> lps(kmp.size(), 0);
for (int i = 1; i < (int)lps.size(); ++i) {
int prev_idx = lps[i - 1];
while (prev_idx > 0 && kmp[i] != kmp[prev_idx]) {
prev_idx = lps[prev_idx - 1];
}
lps[i] = prev_idx + (kmp[i] == kmp[prev_idx] ? 1 : 0);
}
return lps[lps.size() - 1];
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
string s, res;
cin >> s;
int len = s.length();
if (len == 1) {
cout << s << endl;
continue;
}
int l = 0;
int r = len - 1;
while (l < r) {
if (s[l] == s[r]) {
res += s[l];
l++;
r--;
} else
break;
}
if (l >= r) {
cout << s << endl;
continue;
}
string revres = res;
reverse(revres.begin(), revres.end());
string rem;
for (int i = l; i <= r; i++) rem += s[i];
string revrem = rem;
reverse(revrem.begin(), revrem.end());
int l1 = longest_palindrome_prefix(rem);
int l2 = longest_palindrome_prefix(revrem);
string the_rest;
string ans;
if (l1 >= l2) {
the_rest = rem.substr(0, l1);
ans = res + the_rest + revres;
} else {
the_rest = revrem.substr(0, l2);
reverse(the_rest.begin(), the_rest.end());
ans = res + the_rest + revres;
}
cout << ans << endl;
}
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
It is the year 2969. 1000 years have passed from the moon landing. Meanwhile, the humanity colonized the Hyperspaceβ’ and lived in harmony.
Until we realized that we were not alone.
Not too far away from the Earth, the massive fleet of aliens' spaceships is preparing to attack the Earth. For the first time in a while, the humanity is in real danger. Crisis and panic are everywhere. The scientists from all around the solar system have met and discussed the possible solutions. However, no progress has been made.
The Earth's last hope is YOU!
Fortunately, the Earth is equipped with very powerful defense systems made by MDCS. There are N aliens' spaceships which form the line. The defense system consists of three types of weapons:
* SQL rockets β every SQL rocket can destroy at most one spaceship in the given set.
* Cognition beams β every Cognition beam has an interval [l,r] and can destroy at most one spaceship in that interval.
* OMG bazooka β every OMG bazooka has three possible targets, however, each bazooka can destroy either zero or exactly two spaceships. In addition, due to the smart targeting system, the sets of the three possible targets of any two different OMG bazookas are disjoint (that means that every ship is targeted with at most one OMG bazooka).
Your task is to make a plan of the attack which will destroy the largest possible number of spaceships. Every destroyed spaceship should be destroyed with exactly one weapon.
Input
The first line contains two integers: the number of your weapons N (1β€ Nβ€ 5000) and the number of spaceships M (1β€ Mβ€ 5000).
In the next N lines, each line starts with one integer that represents type (either 0, 1 or 2). If the type is 0, then the weapon is SQL rocket, the rest of the line contains strictly positive number K (β{K} β€ 100 000) and array k_i (1β€ k_iβ€ M) of K integers. If the type is 1, then the weapon is Cognition beam, the rest of the line contains integers l and r (1β€ lβ€ rβ€ M). If the type is 2 then the weapon is OMG bazooka, the rest of the line contains distinct numbers a, b and c (1 β€ a,b,c β€ M).
Output
The first line should contain the maximum number of destroyed spaceships β X.
In the next X lines, every line should contain two numbers A and B, where A is an index of the weapon and B is an index of the spaceship which was destroyed by the weapon A.
Example
Input
3 5
0 1 4
2 5 4 1
1 1 4
Output
4
2 1
3 2
1 4
2 5
Note
SQL rocket can destroy only 4th spaceship. OMG Bazooka can destroy two of 1st, 4th or 5th spaceship, and Cognition beam can destroy any spaceship from the interval [1,4]. The maximum number of destroyed spaceship is 4, and one possible plan is that SQL rocket should destroy 4th spaceship, OMG bazooka should destroy 1st and 5th spaceship and Cognition beam should destroy 2nd spaceship.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int iinf = 1 << 29;
const int inf = iinf;
const long long mod = 1e9 + 7;
const int maxn = 5005;
void GG() {
cout << "No\n";
exit(0);
}
long long mpow(long long a, long long n, long long mo = mod) {
long long re = 1;
while (n > 0) {
if (n & 1) re = re * a % mo;
a = a * a % mo;
n >>= 1;
}
return re;
}
long long inv(long long b, long long mo = mod) {
if (b == 1) return b;
return (mo - mo / b) * inv(mo % b) % mo;
}
struct Edge {
int to, rev;
long long cap, flow = 0;
Edge(int to, int rev, long long cap) : to(to), rev(rev), cap(cap) {}
};
struct Dinic {
vector<vector<Edge> > g;
int n;
int second, t;
vector<int> level, ptr;
Dinic(int n, int second, int t) : n(n), second(second), t(t) {
level.resize(n, -1);
ptr.resize(n);
g.resize(n);
}
void add(int v, int u, long long cap) {
g[v].push_back({u, (int)g[u].size(), cap});
g[u].push_back({v, (int)g[v].size() - 1, 0});
}
bool bfs() {
queue<int> q({second});
level[second] = 0;
while (!q.empty() && level[t] == -1) {
int v = q.front();
q.pop();
for (auto &e : g[v]) {
if (e.cap - e.flow == 0) continue;
int u = e.to;
if (level[u] == -1) {
level[u] = level[v] + 1;
q.push(u);
}
}
}
return level[t] != -1;
}
long long dfs(int v, long long amt) {
if (amt == 0 || v == t) return amt;
for (; ptr[v] < (int)g[v].size(); ptr[v]++) {
Edge &e = g[v][ptr[v]];
int u = e.to;
if (level[u] == level[v] + 1) {
long long tt = dfs(u, min(amt, e.cap - e.flow));
if (tt == 0) continue;
e.flow += tt;
g[e.to][e.rev].flow -= tt;
return tt;
}
}
return 0;
}
long long mf() {
long long re = 0;
while (bfs()) {
while (long long amt = dfs(second, inf)) re += amt;
fill(level.begin(), level.end(), -1);
fill(ptr.begin(), ptr.end(), 0);
}
return re;
}
};
int seg[maxn];
int dmax = 5e4 + 10;
int sgst = 1e4 + 5;
int S = dmax - 1, T = dmax - 2;
Dinic dd(dmax, S, T);
void BUILD(int o, int l, int r) {
int mid = (l + r) / 2;
if (l > r) return;
if (l == r) {
dd.add(o / 2 + sgst, l + 5000, inf);
return;
} else if (o != 1) {
dd.add(o / 2 + sgst, o + sgst, inf);
}
BUILD(o * 2, l, mid);
BUILD(o * 2 + 1, mid + 1, r);
}
int from = -1;
void ADD(int o, int l, int r, int L, int R) {
if (l > R || r < L) return;
if (l >= L && r <= R) {
if (l == r) {
dd.add(from, l + 5000, 1);
return;
}
dd.add(from, o + sgst, 1);
return;
}
int mid = (l + r) / 2;
ADD(o * 2, l, mid, L, R);
ADD(o * 2 + 1, mid + 1, r, L, R);
}
int TOP[maxn];
bool cancel[maxn * 3];
int dofe(int at, int p) {
if (at <= sgst && at >= 5000) return at;
for (Edge &e : dd.g[at]) {
if (e.flow >= 1 && e.to != p) {
int mo = dofe(e.to, at);
if (mo != -1) {
e.flow--;
return mo;
}
}
}
return -1;
}
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int n, m;
cin >> n >> m;
BUILD(1, 0, m - 1);
for (int i = 0; i < (n); i++) {
int TP;
cin >> TP;
TOP[i] = TP;
if (TP == 0) {
dd.add(S, i, 1);
int K;
cin >> K;
for (int j = 0; j < (K); j++) {
int to;
cin >> to;
dd.add(i, to - 1 + 5000, 1);
}
}
if (TP == 1) {
int l, r;
cin >> l >> r;
from = i;
dd.add(S, i, 1);
ADD(1, 0, m - 1, l - 1, r - 1);
}
if (TP == 2) {
int a, b, c;
cin >> a >> b >> c;
dd.add(S, i, 2);
dd.add(i, a + 5000 - 1, 1);
dd.add(i, b + 5000 - 1, 1);
dd.add(i, c + 5000 - 1, 1);
}
}
for (int i = 0; i < (m); i++) {
dd.add(i + 5000, T, 1);
}
cout << dd.mf() << '\n';
for (Edge &e : dd.g[S]) {
if (TOP[e.to] == 2) {
for (Edge &e2 : dd.g[e.to]) {
if (e2.to != S && e2.flow == 1) {
cout << e.to + 1 << ' ' << e2.to + 1 - 5000 << '\n';
} else if (e2.to != S && e.flow == 1 && e2.flow != 1) {
e.flow++;
cout << e.to + 1 << ' ' << e2.to + 1 - 5000 << '\n';
cancel[e2.to] = 1;
}
}
}
}
for (Edge &e : dd.g[S]) {
if (TOP[e.to] == 0) {
for (Edge &e2 : dd.g[e.to]) {
if (e2.to != S && e2.flow == 1 && !cancel[e2.to]) {
cout << e.to + 1 << ' ' << e2.to + 1 - 5000 << '\n';
}
}
} else if (TOP[e.to] == 1) {
int endp = dofe(e.to, S);
if (endp != S && endp != -1 && !cancel[endp]) {
cout << e.to + 1 << ' ' << endp + 1 - 5000 << '\n';
}
}
}
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has n buses and m trolleys, the buses are numbered by integers from 1 to n, the trolleys are numbered by integers from 1 to m.
Public transport is not free. There are 4 types of tickets:
1. A ticket for one ride on some bus or trolley. It costs c1 burles;
2. A ticket for an unlimited number of rides on some bus or on some trolley. It costs c2 burles;
3. A ticket for an unlimited number of rides on all buses or all trolleys. It costs c3 burles;
4. A ticket for an unlimited number of rides on all buses and trolleys. It costs c4 burles.
Vasya knows for sure the number of rides he is going to make and the transport he is going to use. He asked you for help to find the minimum sum of burles he will have to spend on the tickets.
Input
The first line contains four integers c1, c2, c3, c4 (1 β€ c1, c2, c3, c4 β€ 1000) β the costs of the tickets.
The second line contains two integers n and m (1 β€ n, m β€ 1000) β the number of buses and trolleys Vasya is going to use.
The third line contains n integers ai (0 β€ ai β€ 1000) β the number of times Vasya is going to use the bus number i.
The fourth line contains m integers bi (0 β€ bi β€ 1000) β the number of times Vasya is going to use the trolley number i.
Output
Print a single number β the minimum sum of burles Vasya will have to spend on the tickets.
Examples
Input
1 3 7 19
2 3
2 5
4 4 4
Output
12
Input
4 3 2 1
1 3
798
1 2 3
Output
1
Input
100 100 8 100
3 5
7 94 12
100 1 47 0 42
Output
16
Note
In the first sample the profitable strategy is to buy two tickets of the first type (for the first bus), one ticket of the second type (for the second bus) and one ticket of the third type (for all trolleys). It totals to (2Β·1) + 3 + 7 = 12 burles.
In the second sample the profitable strategy is to buy one ticket of the fourth type.
In the third sample the profitable strategy is to buy two tickets of the third type: for all buses and for all trolleys.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using namespace std;
long long powm(long long base, long long exp, long long mod = 1000000007) {
long long ans = 1;
while (exp) {
if (exp & 1) ans = (ans * base) % mod;
exp >>= 1, base = (base * base) % mod;
}
return ans;
}
long long a[100005], b[100005];
int main() {
long long c1, c2, c3, c4, n, m;
cin >> c1 >> c2 >> c3 >> c4 >> n >> m;
for (long long i = 1; i < n + 1; i++) cin >> a[i];
for (long long i = 1; i < m + 1; i++) cin >> b[i];
long long ans = c4, ans1 = 0, ans2 = 0;
for (long long i = 1; i < n + 1; i++) ans1 += min(c1 * a[i], c2);
for (long long i = 1; i < m + 1; i++) ans2 += min(c1 * b[i], c2);
ans = min(ans, ans1 + ans2);
ans = min(ans, ans1 + c3);
ans = min(ans, ans2 + c3);
ans = min(ans, c3 + c3);
cout << ans;
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
Input
The first input line contains two integers n and k (1 β€ n β€ 5Β·105; 2 β€ k β€ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
Output
Print a single integer β the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
Examples
Input
6 3
ABBACC
Output
2
ABCACA
Input
3 2
BBB
Output
1
BAB
### Response
```cpp
#include <bits/stdc++.h>
const int inf = 1500000000;
const int d = 1e9 + 7;
using namespace std;
int main() {
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t = 1;
while (t--) {
int n;
cin >> n;
int k;
cin >> k;
string s;
cin >> s;
if (k == 2) {
int c1, c2;
c1 = c2 = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] != 'A' + (i % 2)) {
c1++;
}
if (s[i] != 'A' + (1 - (i % 2))) {
c2++;
}
}
cout << min(c1, c2) << endl;
if (c1 < c2) {
for (int i = 0; i < s.size(); i++) {
cout << (char)('A' + (i % 2));
}
} else {
for (int i = 0; i < s.size(); i++) {
cout << (char)('A' + (1 - i % 2));
}
}
continue;
}
int ctr = 0;
for (int i = 0; i < s.size() - 1; i++) {
if (s[i] == s[i + 1]) {
ctr++;
bool choice[26];
for (int i = 0; i < 26; i++) {
choice[i] = true;
}
choice[s[i] - 'A'] = false;
if (i + 2 < s.size()) choice[s[i + 2] - 'A'] = false;
for (int j = 0; j < 3; j++) {
if (choice[j] == true) {
s[i + 1] = 'A' + j;
break;
}
}
}
}
cout << ctr << endl;
cout << s << endl;
}
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.
The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.
A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of 7 because its subribbon a appears 7 times, and the ribbon abcdabc has the beauty of 2 because its subribbon abc appears twice.
The rules are simple. The game will have n turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after n turns wins the treasure.
Could you find out who is going to be the winner if they all play optimally?
Input
The first line contains an integer n (0 β€ n β€ 10^{9}) β the number of turns.
Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than 10^{5} uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors.
Output
Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw".
Examples
Input
3
Kuroo
Shiro
Katie
Output
Kuro
Input
7
treasurehunt
threefriends
hiCodeforces
Output
Shiro
Input
1
abcabc
cbabac
ababca
Output
Katie
Input
15
foPaErcvJ
mZaxowpbt
mkuOlaHRE
Output
Draw
Note
In the first example, after 3 turns, Kuro can change his ribbon into ooooo, which has the beauty of 5, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most 4, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.
In the fourth example, since the length of each of the string is 9 and the number of turn is 15, everyone can change their ribbons in some way to reach the maximal beauty of 9 by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n;
string a, b, c;
vector<vector<long long> > arr(3, vector<long long>((26 * 2) + 1, 0));
cin >> n;
cin >> a >> b >> c;
long long len = a.length();
for (long long i = 0; i < len; i++) {
char cur = a[i];
if (cur >= 'a') {
arr[0][cur - 97]++;
} else {
arr[0][cur - 65 + 26]++;
}
}
for (long long i = 0; i < len; i++) {
char cur = b[i];
if (cur >= 'a') {
arr[1][cur - 97]++;
} else {
arr[1][cur - 65 + 26]++;
}
}
for (long long i = 0; i < len; i++) {
char cur = c[i];
if (cur >= 'a') {
arr[2][cur - 97]++;
} else {
arr[2][cur - 65 + 26]++;
}
}
for (long long i = 0; i < 52; i++) {
if (arr[0][i] > arr[0][52]) {
arr[0][52] = arr[0][i];
}
if (arr[1][i] > arr[1][52]) {
arr[1][52] = arr[1][i];
}
if (arr[2][i] > arr[2][52]) {
arr[2][52] = arr[2][i];
}
}
long long x = arr[0][52], y = arr[1][52], z = arr[2][52];
if (n == 1 && x == len) {
x = len - 1;
} else if (x + n >= len) {
x = len;
} else {
x += n;
}
if (n == 1 && y == len) {
y = len - 1;
} else if (y + n >= len) {
y = len;
} else {
y += n;
}
if (n == 1 && z == len) {
z = len - 1;
} else if (z + n >= len) {
z = len;
} else {
z += n;
}
if (x > y && x > z) {
cout << "Kuro\n";
} else if (y > x && y > z) {
cout << "Shiro\n";
} else if (z > x && z > y) {
cout << "Katie\n";
} else {
cout << "Draw\n";
}
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
We have N cards. A number a_i is written on the i-th card.
Alice and Bob will play a game using these cards. In this game, Alice and Bob alternately take one card. Alice goes first.
The game ends when all the cards are taken by the two players, and the score of each player is the sum of the numbers written on the cards he/she has taken. When both players take the optimal strategy to maximize their scores, find Alice's score minus Bob's score.
Constraints
* N is an integer between 1 and 100 (inclusive).
* a_i \ (1 \leq i \leq N) is an integer between 1 and 100 (inclusive).
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 a_3 ... a_N
Output
Print Alice's score minus Bob's score when both players take the optimal strategy to maximize their scores.
Examples
Input
2
3 1
Output
2
Input
3
2 7 4
Output
5
Input
4
20 18 2 18
Output
18
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin >> N;
vector<int> a(N);
for(int i=0;i<N;i++)cin >> a[i];
sort(a.rbegin(),a.rend());
int sum=0;
for(int i=0;i<N;i++){
if(i%2==0){
sum+=a[i];
}
else sum-=a[i];
}
cout << sum;
}
``` |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.