text
stringlengths 424
69.5k
|
---|
### Prompt
Please provide a CPP coded solution to the problem described below:
It's been long after the events of the previous problems, and Karen has now moved on from student life and is looking to relocate to a new neighborhood.
<image>
The neighborhood consists of n houses in a straight line, labelled 1 to n from left to right, all an equal distance apart.
Everyone in this neighborhood loves peace and quiet. Because of this, whenever a new person moves into the neighborhood, he or she always chooses the house whose minimum distance to any occupied house is maximized. If there are multiple houses with the maximum possible minimum distance, he or she chooses the leftmost one.
Note that the first person to arrive always moves into house 1.
Karen is the k-th person to enter this neighborhood. If everyone, including herself, follows this rule, which house will she move into?
Input
The first and only line of input contains two integers, n and k (1 β€ k β€ n β€ 1018), describing the number of houses in the neighborhood, and that Karen was the k-th person to move in, respectively.
Output
Output a single integer on a line by itself, the label of the house Karen will move into.
Examples
Input
6 4
Output
2
Input
39 3
Output
20
Note
In the first test case, there are 6 houses in the neighborhood, and Karen is the fourth person to move in:
1. The first person moves into house 1.
2. The second person moves into house 6.
3. The third person moves into house 3.
4. The fourth person moves into house 2.
In the second test case, there are 39 houses in the neighborhood, and Karen is the third person to move in:
1. The first person moves into house 1.
2. The second person moves into house 39.
3. The third person moves into house 20.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename T, typename U>
inline void chkmax(T& x, U y) {
if (x < y) x = y;
}
template <typename T, typename U>
inline void chkmin(T& x, U y) {
if (y < x) x = y;
}
long long p, q;
int b;
long long get(long long st, long long en, long long cnt) {
for (int i = b - 1; i >= 0; i--) {
long long mid = st + en >> 1;
if ((1LL << (i)) >= cnt) {
en = mid;
} else {
cnt -= (1LL << (i));
st = mid;
}
}
return (st + en) / 2;
}
long long query(long long st, long long en, int f, long long cnt) {
long long ans = 0;
for (int i = b - 1; i >= 0; i--) {
long long mid = st + en >> 1;
long long del = mid - st - p * (1LL << (i));
if (!f) del = (1LL << (i)) - del;
if (del >= cnt) {
en = mid;
} else {
cnt -= del;
st = mid;
ans += (1LL << (i));
}
}
return ans + 1;
}
int main() {
long long n, m;
cin >> n >> m;
if (m == 1) {
puts("1");
return 0;
}
if (m == 2) {
cout << n << endl;
return 0;
}
p = n - 1, q = n;
for (int i = 1; i <= 60; i++) {
if ((1LL << (i)) < m - 1) {
p = p >> 1, q = (q + 1) >> 1;
long long y = n - 1 - (1LL << (i)) * p;
long long t = (y == 0 ? p / 2 : q / 2);
if (p == 3 && y > 0) {
long long st = 1, en = n, cnt = m - 1 - (1LL << (i));
if (m - 1 - (1LL << (i)) > y) {
long long cnt = m - 1 - (1LL << (i)) - y;
for (int j = i - 1; j >= 0; j--) {
long long mid = st + en >> 1;
long long del = (1LL << (j + 1));
if (del >= cnt)
en = mid;
else
cnt -= del, st = mid;
}
if (cnt == 2) cout << en - 1 << endl;
if (cnt == 1) cout << st + 1 << endl;
return 0;
}
} else if (t == 1) {
long long st = 1, en = n, cnt = m - 1 - (1LL << (i));
for (int j = i - 1; j >= 0; j--) {
long long mid = st + en >> 1;
if (mid - st - (1LL << (j)) >= cnt)
en = mid;
else
cnt -= mid - st - (1LL << (j)), st = mid;
}
while (cnt--) st = st + en >> 1;
cout << st << endl;
return 0;
}
} else {
b = i - 1;
if (p / 2 == q / 2) {
cout << get(1, n, m - 1 - (1LL << (b))) << endl;
} else {
long long y = n - 1 - p * (1LL << (b));
if (m - 1 - (1LL << (b)) <= y) {
cout << get(1, n, query(1, n, 1, m - 1 - (1LL << (b)))) << endl;
} else {
cout << get(1, n, query(1, n, 0, m - 1 - (1LL << (b)) - y)) << endl;
}
}
return 0;
}
}
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Snuke got an integer sequence from his mother, as a birthday present. The sequence has N elements, and the i-th of them is i. Snuke performs the following Q operations on this sequence. The i-th operation, described by a parameter q_i, is as follows:
* Take the first q_i elements from the sequence obtained by concatenating infinitely many copy of the current sequence, then replace the current sequence with those q_i elements.
After these Q operations, find how many times each of the integers 1 through N appears in the final sequence.
Constraints
* 1 β¦ N β¦ 10^5
* 0 β¦ Q β¦ 10^5
* 1 β¦ q_i β¦ 10^{18}
* All input values are integers.
Input
The input is given from Standard Input in the following format:
N Q
q_1
:
q_Q
Output
Print N lines. The i-th line (1 β¦ i β¦ N) should contain the number of times integer i appears in the final sequence after the Q operations.
Examples
Input
5 3
6
4
11
Output
3
3
3
2
0
Input
10 10
9
13
18
8
10
10
9
19
22
27
Output
7
4
4
3
3
2
2
2
0
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int MaxN(100003);
int n, tot;
ll a[MaxN], F[MaxN], Ans[MaxN], Tag[MaxN];
int main()
{
int n, Q;
scanf("%d%d", &n, &Q);
a[++tot] = n;
for(ll x; Q--; )
{
scanf("%lld", &x);
while(tot && a[tot] >= x) --tot;
a[++tot] = x;
}
F[tot] = 1;
for(int i = tot; i > 1; i--)
{
while(a[i] >= a[1])
{
int j = upper_bound(a + 1, a + i, a[i]) - a - 1;
F[j] += F[i] * (a[i] / a[j]), a[i] %= a[j];
}
if(a[i]) Ans[a[i]] += F[i];
}
if(a[1]) Ans[a[1]] += F[1];
for(int i = n; i; i--)
Ans[i] += Ans[i + 1];
for(int i = 1; i <= n; i++)
printf("%lld\n", Ans[i]);
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS:
You are given two integers d, m, find the number of arrays a, satisfying the following constraints:
* The length of a is n, n β₯ 1
* 1 β€ a_1 < a_2 < ... < a_n β€ d
* Define an array b of length n as follows: b_1 = a_1, β i > 1, b_i = b_{i - 1} β a_i, where β is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold.
Since the number of possible arrays may be too large, you need to find the answer modulo m.
Input
The first line contains an integer t (1 β€ t β€ 100) denoting the number of test cases in the input.
Each of the next t lines contains two integers d, m (1 β€ d, m β€ 10^9).
Note that m is not necessary the prime!
Output
For each test case, print the number of arrays a, satisfying all given constrains, modulo m.
Example
Input
10
1 1000000000
2 999999999
3 99999998
4 9999997
5 999996
6 99995
7 9994
8 993
9 92
10 1
Output
1
3
5
11
17
23
29
59
89
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
vector<long long> mult(32, 1);
for (int i = 0; i < 32; i++) mult[i] = (1 << i) + 1;
int t;
cin >> t;
while (t--) {
long long d, m, final = 1;
cin >> d >> m;
d++;
int x = logb(d);
for (int i = 0; i < x; i++) {
final *= (mult[i]) % m;
final %= m;
}
final *= (d - ((1 << (x))) + 1) % m;
cout << (final % m - 1 + m) % m << endl;
}
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
You are going out for a walk, when you suddenly encounter N monsters. Each monster has a parameter called health, and the health of the i-th monster is h_i at the moment of encounter. A monster will vanish immediately when its health drops to 0 or below.
Fortunately, you are a skilled magician, capable of causing explosions that damage monsters. In one explosion, you can damage monsters as follows:
* Select an alive monster, and cause an explosion centered at that monster. The health of the monster at the center of the explosion will decrease by A, and the health of each of the other monsters will decrease by B. Here, A and B are predetermined parameters, and A > B holds.
At least how many explosions do you need to cause in order to vanish all the monsters?
Constraints
* All input values are integers.
* 1 β€ N β€ 10^5
* 1 β€ B < A β€ 10^9
* 1 β€ h_i β€ 10^9
Input
Input is given from Standard Input in the following format:
N A B
h_1
h_2
:
h_N
Output
Print the minimum number of explosions that needs to be caused in order to vanish all the monsters.
Examples
Input
4 5 3
8
7
4
2
Output
2
Input
2 10 4
20
20
Output
4
Input
5 2 1
900000000
900000000
1000000000
1000000000
1000000000
Output
800000000
### Response
```cpp
#include <iostream>
#include <string.h>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
typedef long long ll;
const ll INF=10000000000000000LL;
int n,a,b,h[100001];
bool cheak(ll c){
ll s=0;
for(int i=0;i<n;++i){
if(h[i]>b*c){
s+=(h[i]-b*c)/(a-b);
if((h[i]-b*c)%(a-b))++s;
}
}
if(s<=c)return true;
return false;
}
ll reg(int l,int r){
if(l==r)return l;
ll c=(l+r)/2;
if(cheak(c)){
if(l+1==r)return l;
return reg(l,c);
}else{
return reg(c+1,r);
}
}
int main() {
cin>>n>>a>>b;
for(int i=0;i<n;++i)cin>>h[i];
cout<<reg(0,1000000000)<<endl;
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consisting of n characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.
Usually, we can install the pipeline along the road on height of 1 unit with supporting pillars in each integer point (so, if we are responsible for [0, n] road, we must install n + 1 pillars). But on crossroads we should lift the pipeline up to the height 2, so the pipeline won't obstruct the way for cars.
We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment [x, x + 1] with integer x consisting of three parts: 0.5 units of horizontal pipe + 1 unit of vertical pipe + 0.5 of horizontal. Note that if pipeline is currently on height 2, the pillars that support it should also have length equal to 2 units.
<image>
Each unit of gas pipeline costs us a bourles, and each unit of pillar β b bourles. So, it's not always optimal to make the whole pipeline on the height 2. Find the shape of the pipeline with minimum possible cost and calculate that cost.
Note that you must start and finish the pipeline on height 1 and, also, it's guaranteed that the first and last characters of the input string are equal to 0.
Input
The fist line contains one integer T (1 β€ T β€ 100) β the number of queries. Next 2 β
T lines contain independent queries β one query per two lines.
The first line contains three integers n, a, b (2 β€ n β€ 2 β
10^5, 1 β€ a β€ 10^8, 1 β€ b β€ 10^8) β the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.
The second line contains binary string s (|s| = n, s_i β \{0, 1\}, s_1 = s_n = 0) β the description of the road.
It's guaranteed that the total length of all strings s doesn't exceed 2 β
10^5.
Output
Print T integers β one per query. For each query print the minimum possible cost of the constructed pipeline.
Example
Input
4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
Output
94
25
2900000000
13
Note
The optimal pipeline for the first query is shown at the picture above.
The optimal pipeline for the second query is pictured below:
<image>
The optimal (and the only possible) pipeline for the third query is shown below:
<image>
The optimal pipeline for the fourth query is shown below:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long int N = 2e5 + 5, mod = (long long int)1e9 + 7, bit = 31;
signed main() {
ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
long long int pro = 1, temp, t, m, n, k, i, j, l, r, mid, x, y, z, rem,
carry = 0, ind, ans = 0, mx = -LONG_LONG_MAX,
mn = LONG_LONG_MAX, cnt = 0, curr = 0, prev, nxt, sum = 0,
flag = 1, i1 = -1, i2 = -1;
cin >> t;
while (t--) {
cin >> n >> x >> y;
string s;
cin >> s;
long long int a[n];
flag = 0;
for (i = 0; i <= n - 1; i++) {
a[i] = s[i] - '0' + 1;
flag |= (s[i] - '0');
}
ans = (n + 1) * y + n * x;
if (!flag) {
cout << ans << '\n';
continue;
}
for (i = 0; i <= n - 1; i++) {
j = i;
cnt = 0;
while (j < n && s[j] == '1') {
j++;
cnt++;
}
if (cnt) {
ans += (cnt + 1) * y;
}
i = max(i, j - 1);
}
for (ind = 0; s[ind] == '0'; ind++)
;
ans += x;
for (; ind < n; ind++) {
while (ind < n && s[ind] == '1') {
ind++;
}
j = ind;
cnt = -1;
while (j < n && s[j] == '0') {
cnt++;
j++;
}
if (j == n) {
ans += x;
break;
} else {
ans += min(cnt * y, 2 * x);
ind = j;
}
}
cout << ans << '\n';
}
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
Input
The first line contains a single integer h (2 β€ h β€ 105) β the height of the tree.
The second line contains h + 1 integers β the sequence a0, a1, ..., ah (1 β€ ai β€ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence.
Output
If there is only one tree matching this sequence, print "perfect".
Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.
These treese should be non-isomorphic and should match the given sequence.
Examples
Input
2
1 1 1
Output
perfect
Input
2
1 2 2
Output
ambiguous
0 1 1 3 3
0 1 1 3 2
Note
The only tree in the first example and the two printed trees from the second example are shown on the picture:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using VI = vector<int>;
void fastio() {
cin.sync_with_stdio(0);
cin.tie(0);
}
void print_dense(VI &v) {
cout << 0 << ' ';
int father = 1;
for (int i = 1; i < v.size(); i++) {
for (int j = 0; j < v[i]; j++) cout << father << ' ';
father += v[i];
}
cout << '\n';
}
void print_sparse(VI &v) {
cout << 0 << ' ';
VI fathers{1};
int cont = 2;
for (int i = 1; i < v.size(); i++) {
VI next;
for (int j = 0; j < v[i]; j++)
cout << fathers[j % fathers.size()] << ' ', next.push_back(cont++);
fathers = next;
}
cout << '\n';
}
int main() {
fastio();
int n;
cin >> n;
n++;
VI v(n);
for (int &i : v) cin >> i;
bool ok = 1;
for (int h = 2; h < n; h++) {
if (v[h] == 1) continue;
if (v[h - 1] == 1) continue;
ok = 0;
break;
}
if (ok) return cout << "perfect", 0;
cout << "ambiguous\n";
print_dense(v);
print_sparse(v);
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Snuke is introducing a robot arm with the following properties to his factory:
* The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i.
* For each section, its mode can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)):
* (x_0, y_0) = (0, 0).
* If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}).
* If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}).
* If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}).
* If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}).
Snuke would like to introduce a robot arm so that the position of Joint m can be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by properly specifying the modes of the sections. Is this possible? If so, find such a robot arm and how to bring Joint m to each point (X_j, Y_j).
Constraints
* All values in input are integers.
* 1 \leq N \leq 1000
* -10^9 \leq X_i \leq 10^9
* -10^9 \leq Y_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
X_1 Y_1
X_2 Y_2
:
X_N Y_N
Output
If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print `-1`.
m
d_1 d_2 ... d_m
w_1
w_2
:
w_N
m and d_i are the configurations of the robot arm. Refer to the problem statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i \leq 10^{12} must hold. Also, m and d_i must all be integers.
w_j is a string of length m that represents the way to bring Joint m of the robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the letters `L`, `R`, `D` and `U`, representing the mode of Section i.
Examples
Input
3
-1 0
0 3
2 -1
Output
2
1 2
RL
UU
DR
Input
5
0 0
1 0
2 0
3 0
4 0
Output
-1
Input
2
1 1
1 1
Output
2
1 1
RU
UR
Input
3
-7 -3
7 3
-3 -7
Output
5
3 1 4 1 5
LRDUL
RDULR
DULRD
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int tx[]={0,0,1,-1};
const int ty[]={1,-1,0,0};
int getd(int a,int b,int x,int y){
return abs(a-x)+abs(b-y);
}
char getc(int &a,int &b,int d,int x,int y){
int Mn=2e9,op=-1;
for (int i=0;i<4;i++){
int xx=a+tx[i]*d,yy=b+ty[i]*d;
int dis=getd(xx,yy,x,y);
if (dis<Mn) {Mn=dis; op=i;}
}
a=a+tx[op]*d; b=b+ty[op]*d;
if (op==0) return 'U';
if (op==1) return 'D';
if (op==2) return 'R';
return 'L';
}
int x[1111],y[1111],d[222],cnt[2],m;
signed main(){
int T; scanf("%lld",&T);
for (int i=1;i<=T;i++){
scanf("%lld%lld",&x[i],&y[i]);
cnt[(x[i]+y[i])%2]++;
}
if (cnt[1]&& cnt[0]) return puts("-1"),0;
for (int i=0;i<=30;i++) d[i+1]=1<<(30-i);
if (cnt[0]) d[32]=1,m=32; else m=31;
printf("%lld\n",m);
for (int i=1;i<=m;i++) printf("%lld ",d[i]); puts("");
for (int i=1;i<=T;i++){
int a=0,b=0;
for (int j=1;j<=m;j++)
putchar(getc(a,b,d[j],x[i],y[i]));
puts("");
}
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Let's introduce the designation <image>, where x is a string, n is a positive integer and operation " + " is the string concatenation operation. For example, [abc, 2] = abcabc.
We'll say that string s can be obtained from string t, if we can remove some characters from string t and obtain string s. For example, strings ab and aΡba can be obtained from string xacbac, and strings bx and aaa cannot be obtained from it.
Sereja has two strings, w = [a, b] and q = [c, d]. He wants to find such maximum integer p (p > 0), that [q, p] can be obtained from string w.
Input
The first line contains two integers b, d (1 β€ b, d β€ 107). The second line contains string a. The third line contains string c. The given strings are not empty and consist of lowercase English letters. Their lengths do not exceed 100.
Output
In a single line print an integer β the largest number p. If the required value of p doesn't exist, print 0.
Examples
Input
10 3
abab
bab
Output
3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int b, d, lena, lenc;
char a[200], c[200];
int nxt[200], cnt[200];
int main() {
scanf("%d%d", &b, &d);
scanf("%s", a);
scanf("%s", c);
lena = strlen(a);
lenc = strlen(c);
for (int i = 0; i < lenc; i++) {
int x = i;
for (int j = 0; j < lena; j++) {
if (a[j] == c[x]) {
x++;
if (x == lenc) cnt[i]++, x = 0;
}
}
nxt[i] = x;
}
long long ans = 0;
int x = 0;
for (int i = 0; i < b; i++) {
ans += cnt[x];
x = nxt[x];
}
printf("%lld\n", ans / d);
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Drazil created a following problem about putting 1 Γ 2 tiles into an n Γ m grid:
"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 Γ 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."
But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".
Drazil found that the constraints for this task may be much larger than for the original task!
Can you solve this new problem?
Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task.
Input
The first line contains two integers n and m (1 β€ n, m β€ 2000).
The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied.
Output
If there is no solution or the solution is not unique, you should print the string "Not unique".
Otherwise you should print how to cover all empty cells with 1 Γ 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example.
Examples
Input
3 3
...
.*.
...
Output
Not unique
Input
4 4
..**
*...
*.**
....
Output
<>**
*^<>
*v**
<><>
Input
2 4
*..*
....
Output
*<>*
<><>
Input
1 1
.
Output
Not unique
Input
1 1
*
Output
*
Note
In the first case, there are indeed two solutions:
<>^
^*v
v<>
and
^<>
v*^
<>v
so the answer is "Not unique".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m;
string s[2005];
vector<pair<short, short> > v[2005][2005];
pair<short, short> q[2005 * 2005];
int xd[4];
int yd[4];
bool used[2005][2005];
char ans[2005][2005];
int sz;
short cnt[2005][2005];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
xd[0] = -1;
yd[0] = 0;
xd[1] = 0;
yd[1] = 1;
xd[2] = 1;
yd[2] = 0;
xd[3] = 0;
yd[3] = -1;
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
cin >> s[i];
s[i] = "#" + s[i];
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j)
if (s[i][j] != '*') {
for (int k = 0; k < 4; ++k) {
int xx = i + xd[k];
int yy = j + yd[k];
if (xx == 0 || xx > n || yy == 0 || yy > m) continue;
if (s[xx][yy] == '*') continue;
v[i][j].push_back(make_pair(xx, yy));
++cnt[i][j];
}
if (cnt[i][j] == 1) q[++sz] = make_pair(i, j);
}
}
for (int i = 1; i <= sz; ++i) {
int x = q[i].first;
int y = q[i].second;
if (used[x][y]) continue;
used[x][y] = true;
for (int i = 0; i < v[x][y].size(); ++i) {
int xx = v[x][y][i].first;
int yy = v[x][y][i].second;
if (used[xx][yy]) continue;
for (int j = 0; j < v[xx][yy].size(); ++j) {
int xx2 = v[xx][yy][j].first;
int yy2 = v[xx][yy][j].second;
if (used[xx2][yy2] == false) {
--cnt[xx2][yy2];
if (cnt[xx2][yy2] == 1) {
q[++sz] = make_pair(xx2, yy2);
}
}
}
used[xx][yy] = true;
if (xx == x) {
ans[x][y] = '<';
ans[xx][yy] = '>';
if (yy < y) swap(ans[x][y], ans[xx][yy]);
} else {
ans[x][y] = '^';
ans[xx][yy] = 'v';
if (xx < x) swap(ans[x][y], ans[xx][yy]);
}
}
}
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j)
if (s[i][j] == '.' && !ans[i][j]) {
cout << "Not unique";
return 0;
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) cout << (ans[i][j] ? ans[i][j] : '*');
cout << '\n';
}
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Karl is developing a key storage service. Each user has a positive integer key.
Karl knows that storing keys in plain text is bad practice. So, instead of storing a key, he decided to store a fingerprint of a key. However, using some existing fingerprint algorithm looked too boring to him, so he invented his own one.
Karl's fingerprint is calculated by the following process: divide the given integer by 2, then divide the result by 3, then divide the result by 4, and so on, until we get a result that equals zero (we are speaking about integer division each time). The fingerprint is defined as the multiset of the remainders of these divisions.
For example, this is how Karl's fingerprint algorithm is applied to the key 11: 11 divided by 2 has remainder 1 and result 5, then 5 divided by 3 has remainder 2 and result 1, and 1 divided by 4 has remainder 1 and result 0. Thus, the key 11 produces the sequence of remainders [1, 2, 1] and has the fingerprint multiset \{1, 1, 2\}.
Ksenia wants to prove that Karl's fingerprint algorithm is not very good. For example, she found that both keys 178800 and 123456 produce the fingerprint of \{0, 0, 0, 0, 2, 3, 3, 4\}. Thus, users are at risk of fingerprint collision with some commonly used and easy to guess keys like 123456.
Ksenia wants to make her words more persuasive. She wants to calculate the number of other keys that have the same fingerprint as the keys in the given list of some commonly used keys. Your task is to help her.
Input
The first line contains an integer t (1 β€ t β€ 50 000) β the number of commonly used keys to examine. Each of the next t lines contains one integer k_i (1 β€ k_i β€ 10^{18}) β the key itself.
Output
For each of the keys print one integer β the number of other keys that have the same fingerprint.
Example
Input
3
1
11
123456
Output
0
1
127
Note
The other key with the same fingerprint as 11 is 15. 15 produces a sequence of remainders [1, 1, 2]. So both numbers have the fingerprint multiset \{1, 1, 2\}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long dp[21][21];
int arr[21];
int main() {
int t;
long long k;
scanf("%d", &t);
for (int i = 0; i <= 20; i++) dp[0][i] = dp[i][0] = 1;
for (int i = 1; i <= 20; i++)
for (int j = 1; j <= 20; j++) dp[i][j] = dp[i][j - 1] + dp[i - 1][j];
while (t--) {
scanf("%lld", &k);
memset(arr, 0, sizeof(arr));
int cnt = 0, tmp;
for (int n = 2;; n++) {
arr[k % n]++;
cnt++;
k /= n;
if (!k) break;
}
long long ans = 1;
tmp = cnt;
for (int i = 20; i >= 0; i--) {
if (!arr[i]) continue;
cnt -= arr[i];
ans *= dp[cnt - i + (i != 0)][arr[i]];
}
if (arr[0]) {
long long mn = 1;
arr[0]--;
cnt = tmp - 1;
for (int i = 20; i >= 0; i--) {
if (!arr[i]) continue;
cnt -= arr[i];
if (cnt - i + (i != 0) < 0) {
mn = 0;
break;
}
mn *= dp[cnt - i + (i != 0)][arr[i]];
}
ans -= mn;
}
printf("%lld\n", ans - 1);
}
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 β€ u, v β€ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
Input
The first line of the input contains two space-separated integers n and m (1 β€ n, m β€ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 β€ a, b β€ n and a β b).
Output
Print one number β the brain latency.
Examples
Input
4 3
1 2
1 3
1 4
Output
2
Input
5 4
1 2
2 3
3 4
3 5
Output
3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100010;
int n, m;
vector<int> vec[MAXN];
bool mark[MAXN];
int dis[MAXN];
void bfs(int x) {
queue<int> que;
que.push(x);
dis[x] = 0;
mark[x] = 1;
while (!que.empty()) {
int z = que.front();
for (int i = 0; i < vec[z].size(); i++) {
if (!mark[vec[z][i]]) {
mark[vec[z][i]] = 1;
dis[vec[z][i]] = dis[z] + 1;
que.push(vec[z][i]);
}
}
que.pop();
}
}
int main() {
cin >> n >> m;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
a--;
b--;
vec[a].push_back(b);
vec[b].push_back(a);
}
bfs(0);
int index = -1, max = -1;
for (int i = 0; i < n; i++) {
if (dis[i] > max) {
max = dis[i];
index = i;
}
}
for (int i = 0; i < MAXN; i++) {
mark[i] = 0;
dis[i] = 0;
}
bfs(index);
max = -1;
for (int i = 0; i < n; i++) {
if (dis[i] > max) {
max = dis[i];
}
}
cout << max << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Ori and Sein have overcome many difficult challenges. They finally lit the Shrouded Lantern and found Gumon Seal, the key to the Forlorn Ruins. When they tried to open the door to the ruins... nothing happened.
Ori was very surprised, but Sein gave the explanation quickly: clever Gumon decided to make an additional defence for the door.
There are n lamps with Spirit Tree's light. Sein knows the time of turning on and off for the i-th lamp β l_i and r_i respectively. To open the door you have to choose k lamps in such a way that there will be a moment of time when they all will be turned on.
While Sein decides which of the k lamps to pick, Ori is interested: how many ways there are to pick such k lamps that the door will open? It may happen that Sein may be wrong and there are no such k lamps. The answer might be large, so print it modulo 998 244 353.
Input
First line contains two integers n and k (1 β€ n β€ 3 β
10^5, 1 β€ k β€ n) β total number of lamps and the number of lamps that must be turned on simultaneously.
Next n lines contain two integers l_i ans r_i (1 β€ l_i β€ r_i β€ 10^9) β period of time when i-th lamp is turned on.
Output
Print one integer β the answer to the task modulo 998 244 353.
Examples
Input
7 3
1 7
3 8
4 5
6 7
1 3
5 10
8 9
Output
9
Input
3 1
1 1
2 2
3 3
Output
3
Input
3 2
1 1
2 2
3 3
Output
0
Input
3 3
1 3
2 3
3 3
Output
1
Input
5 2
1 3
2 4
3 5
4 6
5 7
Output
7
Note
In first test case there are nine sets of k lamps: (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 3, 6), (1, 4, 6), (2, 3, 6), (2, 4, 6), (2, 6, 7).
In second test case k=1, so the answer is 3.
In third test case there are no such pairs of lamps.
In forth test case all lamps are turned on in a time 3, so the answer is 1.
In fifth test case there are seven sets of k lamps: (1, 2), (1, 3), (2, 3), (2, 4), (3, 4), (3, 5), (4, 5).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long mod = 998244353;
long long N = 100311;
long long fact[300005], inv[300005];
long long inverse(long long a) {
long long ret = 1;
for (long long b = mod - 2; b > 0; b /= 2) {
if (b % 2) ret = ret * a % mod;
a = a * a % mod;
}
return ret;
}
long long C(long long n, long long k) {
if (n < k) return 0;
return fact[n] * inv[k] % mod * inv[n - k] % mod;
}
long long binpow(long long x, long long y) {
if (y == 0) return 1;
if (y == 1)
return x % mod;
else if (y % 2 == 0) {
long long w = binpow(x, y / 2) % mod;
return (w * w) % mod;
} else
return ((x % mod) * (binpow(x, y - 1) % mod)) % mod;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long t = 1;
while (t--) {
long long n, k;
cin >> n >> k;
vector<pair<long long, long long>> v;
for (long long i = 1; i <= n; i++) {
long long l, r;
cin >> l >> r;
v.push_back({l, 1});
v.push_back({r + 1, -1});
}
fact[0] = inv[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = fact[i - 1] * i % mod;
inv[i] = inverse(fact[i]);
}
sort(v.begin(), v.end());
long long ans = 0;
long long total = 0, nw = 0;
for (long long i = 0; i < 2 * n; i++) {
if (v[i].second == -1)
total--;
else {
total++;
nw++;
}
nw = min(nw, total);
if (total >= k) {
ans += (C(total, k) - C(total - nw, k) + mod);
ans %= mod;
nw = 0;
}
}
cout << ans % mod;
}
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Vasya has gotten interested in programming contests in TCMCF+++ rules. On the contest n problems were suggested and every problem had a cost β a certain integral number of points (perhaps, negative or even equal to zero). According to TCMCF+++ rules, only accepted problems can earn points and the overall number of points of a contestant was equal to the product of the costs of all the problems he/she had completed. If a person didn't solve anything, then he/she didn't even appear in final standings and wasn't considered as participant. Vasya understood that to get the maximal number of points it is not always useful to solve all the problems. Unfortunately, he understood it only after the contest was finished. Now he asks you to help him: find out what problems he had to solve to earn the maximal number of points.
Input
The first line contains an integer n (1 β€ n β€ 100) β the number of the suggested problems. The next line contains n space-separated integers ci ( - 100 β€ ci β€ 100) β the cost of the i-th task. The tasks' costs may coinΡide.
Output
Print space-separated the costs of the problems that needed to be solved to get the maximal possible number of points. Do not forget, please, that it was necessary to solve at least one problem. If there are several solutions to that problem, print any of them.
Examples
Input
5
1 2 -3 3 3
Output
3 1 2 3
Input
13
100 100 100 100 100 100 100 100 100 100 100 100 100
Output
100 100 100 100 100 100 100 100 100 100 100 100 100
Input
4
-2 -2 -2 -2
Output
-2 -2 -2 -2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n;
int otri[103];
int c_otri;
int tem[103];
void mergesort(int *a, int *b, int n) {
int i, i0, i1, iRight, iEnd, width, j;
for (width = 1; width < n; width *= 2)
for (i = 0; i + width < n; i += width * 2) {
i0 = i;
i1 = iRight = i + width;
iEnd = min(i + width * 2, n);
for (j = i; i0 < iRight; j++)
if (i1 == iEnd || a[i0] < a[i1])
b[j] = a[i0++];
else
b[j] = a[i1++];
for (j = i; j < i1; j++) a[j] = b[j];
}
}
int main() {
scanf("%d", &n);
int i;
bool zero = false;
int ans[103];
int coun = 0;
int x;
for (i = 0; i < n; i++) {
scanf("%d", &x);
if (x == 0) zero = true;
if (x > 0) ans[coun++] = x;
if (x < 0) otri[c_otri++] = x;
}
mergesort(otri, tem, c_otri);
if (c_otri & 1) c_otri--;
for (i = 0; i < c_otri; i++) ans[coun++] = otri[i];
if (coun == 0) {
if (zero)
ans[coun++] = 0;
else
ans[coun++] = otri[0];
}
printf("%d", ans[0]);
for (i = 1; i < coun; i++) printf(" %d", ans[i]);
printf("\n");
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
There is a road with length l meters. The start of the road has coordinate 0, the end of the road has coordinate l.
There are two cars, the first standing at the start of the road and the second standing at the end of the road. They will start driving simultaneously. The first car will drive from the start to the end and the second car will drive from the end to the start.
Initially, they will drive with a speed of 1 meter per second. There are n flags at different coordinates a_1, a_2, β¦, a_n. Each time when any of two cars drives through a flag, the speed of that car increases by 1 meter per second.
Find how long will it take for cars to meet (to reach the same coordinate).
Input
The first line contains one integer t (1 β€ t β€ 10^4): the number of test cases.
The first line of each test case contains two integers n, l (1 β€ n β€ 10^5, 1 β€ l β€ 10^9): the number of flags and the length of the road.
The second line contains n integers a_1, a_2, β¦, a_n in the increasing order (1 β€ a_1 < a_2 < β¦ < a_n < l).
It is guaranteed that the sum of n among all test cases does not exceed 10^5.
Output
For each test case print a single real number: the time required for cars to meet.
Your answer will be considered correct, if its absolute or relative error does not exceed 10^{-6}. More formally, if your answer is a and jury's answer is b, your answer will be considered correct if \frac{|a-b|}{max{(1, b)}} β€ 10^{-6}.
Example
Input
5
2 10
1 9
1 10
1
5 7
1 2 3 4 6
2 1000000000
413470354 982876160
9 478
1 10 25 33 239 445 453 468 477
Output
3.000000000000000
3.666666666666667
2.047619047619048
329737645.750000000000000
53.700000000000000
Note
In the first test case cars will meet in the coordinate 5.
The first car will be in the coordinate 1 in 1 second and after that its speed will increase by 1 and will be equal to 2 meters per second. After 2 more seconds it will be in the coordinate 5. So, it will be in the coordinate 5 in 3 seconds.
The second car will be in the coordinate 9 in 1 second and after that its speed will increase by 1 and will be equal to 2 meters per second. After 2 more seconds it will be in the coordinate 5. So, it will be in the coordinate 5 in 3 seconds.
In the second test case after 1 second the first car will be in the coordinate 1 and will have the speed equal to 2 meters per second, the second car will be in the coordinate 9 and will have the speed equal to 1 meter per second. So, they will meet after (9-1)/(2+1) = 8/3 seconds. So, the answer is equal to 1 + 8/3 = 11/3.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int A[100005];
int n, l;
double findCoordinate1(double t) {
for (int i = 1; i <= n + 1; i++) {
double t_taken = (double)abs(A[i] - A[i - 1]) / i;
if (t >= t_taken) {
t -= t_taken;
} else {
return A[i - 1] + i * t;
}
}
return l;
}
double findCoordinate2(double t) {
for (int i = n; i >= 0; i--) {
double t_taken = (double)abs(A[i] - A[i + 1]) / (n + 1 - i);
if (t >= t_taken) {
t -= t_taken;
} else {
return A[i + 1] - (n + 1 - i) * t;
}
}
return 0;
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
scanf("%d%d", &n, &l);
for (int i = 1; i <= n; i++) {
scanf("%d", &A[i]);
}
A[0] = 0;
A[n + 1] = l;
double lo = 0;
double hi = 1.01e9;
for (int k = 0; k < 100; k++) {
double mid = (lo + hi) / 2;
double pos1 = findCoordinate1(mid);
double pos2 = findCoordinate2(mid);
if (pos1 < pos2) {
lo = mid;
} else {
hi = mid;
}
}
printf("%.10f\n", (lo + hi) / 2);
}
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Valera considers a number beautiful, if it equals 2k or -2k for some integer k (k β₯ 0). Recently, the math teacher asked Valera to represent number n as the sum of beautiful numbers. As Valera is really greedy, he wants to complete the task using as few beautiful numbers as possible.
Help Valera and find, how many numbers he is going to need. In other words, if you look at all decompositions of the number n into beautiful summands, you need to find the size of the decomposition which has the fewest summands.
Input
The first line contains string s (1 β€ |s| β€ 106), that is the binary representation of number n without leading zeroes (n > 0).
Output
Print a single integer β the minimum amount of beautiful numbers that give a total of n.
Examples
Input
10
Output
1
Input
111
Output
2
Input
1101101
Output
4
Note
In the first sample n = 2 is a beautiful number.
In the second sample n = 7 and Valera can decompose it into sum 23 + ( - 20).
In the third sample n = 109 can be decomposed into the sum of four summands as follows: 27 + ( - 24) + ( - 22) + 20.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
char st[1000009];
int main() {
scanf("%s", st);
int l = strlen(st);
int ans = 0;
for (int i = l - 1; i >= 0; i--)
if (st[i] == '1') {
ans++;
st[i] = '0';
if (i) {
int j = i - 1;
bool flag = false;
while (j >= 0 && st[j] == '1') {
flag = true;
st[j] = '0';
j--;
}
if (j == -1) {
ans++;
break;
} else if (flag)
st[j] = '1';
i = j + 1;
}
}
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Example
Input
R?????,2?)
Output
29
### Response
```cpp
#include <bits/stdc++.h>
#define syosu(x) fixed<<setprecision(x)
using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef pair<int,int> P;
typedef pair<double,double> pdd;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<string> vs;
typedef vector<P> vp;
typedef vector<vp> vvp;
typedef vector<pll> vpll;
typedef pair<int,P> pip;
typedef vector<pip> vip;
const int inf=1<<29;
const ll INF=1ll<<60;
const double pi=acos(-1);
const double eps=1e-9;
const ll mod=1e9+7;
const int dx[4]={-1,0,1,0},dy[4]={0,-1,0,1};
string g(string s,string t){
int n=s.size(),m=t.size();
if(s=="invalid") return t;
if(t=="invalid") return s;
if(n>m) return s;
if(n<m) return t;
for(int i=0;i<n;i++){
if(s[i]<t[i]) return t;
if(s[i]>t[i]) return s;
}
return s;
}
int n;
string s;
vector<vs> dp;
string f(int l,int r){
if(dp[l][r]!="") return dp[l][r];
bool B=1;
for(int i=l;i<=r;i++) if(!isdigit(s[i])&&s[i]!='?') B=0;
if(B){
if(s[l]=='0'&&l<r) return dp[l][r]="invalid";
string t;
for(int i=l;i<=r;i++){
if(s[i]=='?') t+='9';
else t+=s[i];
}
return dp[l][r]=t;
}
if(r-l+1<=5) return dp[l][r]="invalid";
if(isdigit(s[l])||s[l]==','||s[l]=='('||s[l]==')') return dp[l][r]="invalid";
if(isdigit(s[l+1])||isalpha(s[l+1])||s[l+1]==','||s[l+1]==')') return dp[l][r]="invalid";
if(isdigit(s[r])||isalpha(s[r])||s[r]==','||s[r]=='(') return dp[l][r]="invalid";
dp[l][r]="invalid";
if(s[l]=='L'||s[l]=='?'){
for(int i=l+2;i<r-2;i++) if(s[i+1]=='?'||s[i+1]==','){
auto lt=f(l+2,i),rt=f(i+2,r-1);
if(lt!="invalid"&&rt!="invalid"){
dp[l][r]=g(dp[l][r],lt);
}
}
}
if(s[l]=='R'||s[l]=='?'){
for(int i=l+2;i<r-2;i++) if(s[i+1]=='?'||s[i+1]==','){
auto lt=f(l+2,i),rt=f(i+2,r-1);
if(lt!="invalid"&&rt!="invalid"){
dp[l][r]=g(dp[l][r],rt);
}
}
}
return dp[l][r];
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cin>>s;
n=s.size();
dp=vector<vs>(n,vs(n,""));
cout<<f(0,n-1)<<endl;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Little girl Susie accidentally found her elder brother's notebook. She has many things to do, more important than solving problems, but she found this problem too interesting, so she wanted to know its solution and decided to ask you about it. So, the problem statement is as follows.
Let's assume that we are given a connected weighted undirected graph G = (V, E) (here V is the set of vertices, E is the set of edges). The shortest-path tree from vertex u is such graph G1 = (V, E1) that is a tree with the set of edges E1 that is the subset of the set of edges of the initial graph E, and the lengths of the shortest paths from u to any vertex to G and to G1 are the same.
You are given a connected weighted undirected graph G and vertex u. Your task is to find the shortest-path tree of the given graph from vertex u, the total weight of whose edges is minimum possible.
Input
The first line contains two numbers, n and m (1 β€ n β€ 3Β·105, 0 β€ m β€ 3Β·105) β the number of vertices and edges of the graph, respectively.
Next m lines contain three integers each, representing an edge β ui, vi, wi β the numbers of vertices connected by an edge and the weight of the edge (ui β vi, 1 β€ wi β€ 109). It is guaranteed that graph is connected and that there is no more than one edge between any pair of vertices.
The last line of the input contains integer u (1 β€ u β€ n) β the number of the start vertex.
Output
In the first line print the minimum total weight of the edges of the tree.
In the next line print the indices of the edges that are included in the tree, separated by spaces. The edges are numbered starting from 1 in the order they follow in the input. You may print the numbers of the edges in any order.
If there are multiple answers, print any of them.
Examples
Input
3 3
1 2 1
2 3 1
1 3 2
3
Output
2
1 2
Input
4 4
1 2 1
2 3 1
3 4 1
4 1 2
4
Output
4
2 3 4
Note
In the first sample there are two possible shortest path trees:
* with edges 1 β 3 and 2 β 3 (the total weight is 3);
* with edges 1 β 2 and 2 β 3 (the total weight is 2);
And, for example, a tree with edges 1 β 2 and 1 β 3 won't be a shortest path tree for vertex 3, because the distance from vertex 3 to vertex 2 in this tree equals 3, and in the original graph it is 1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<pair<long long, long long> > g[300007];
vector<pair<pair<long long, long long>, long long> > edge[300007];
long long dist[300007], par[300007], visit[300007], e[300007], src[300007],
dest[300007];
map<pair<long long, long long>, long long> ma;
void djikstra(long long s, long long n) {
long long i;
for (i = 1; i <= n; i++) {
dist[i] = 999999999999999;
visit[i] = 0;
}
priority_queue<pair<long long, long long>,
vector<pair<long long, long long> >,
greater<pair<long long, long long> > >
q;
q.push(make_pair(0, s));
dist[s] = 0;
e[s] = 0;
pair<long long, long long> top;
long long u;
while (!q.empty()) {
top = q.top();
q.pop();
u = top.second;
for (i = 0; i < g[u].size(); i++) {
if (g[u][i].second + top.first < dist[g[u][i].first]) {
dist[g[u][i].first] = g[u][i].second + top.first;
e[g[u][i].first] = g[u][i].second;
par[g[u][i].first] = u;
q.push(make_pair(dist[g[u][i].first], g[u][i].first));
} else if (g[u][i].second + top.first == dist[g[u][i].first]) {
if (g[u][i].second < e[g[u][i].first]) {
e[g[u][i].first] = g[u][i].second;
par[g[u][i].first] = u;
}
}
}
}
}
int main() {
long long n, m, i, x, y, w, s;
cin >> n >> m;
for (i = 1; i <= m; i++) {
cin >> x >> y >> w;
g[x].push_back(make_pair(y, w));
g[y].push_back(make_pair(x, w));
src[i] = x;
dest[i] = y;
}
for (i = 1; i <= n; i++) par[i] = i;
cin >> s;
djikstra(s, n);
long long c = 0;
for (i = 1; i <= n; i++) c += e[i];
cout << c << endl;
for (i = 1; i <= m; i++) {
if (par[src[i]] == dest[i] || par[dest[i]] == src[i]) cout << i << " ";
}
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Takahashi loves numbers divisible by 2.
You are given a positive integer N. Among the integers between 1 and N (inclusive), find the one that can be divisible by 2 for the most number of times. The solution is always unique.
Here, the number of times an integer can be divisible by 2, is how many times the integer can be divided by 2 without remainder.
For example,
* 6 can be divided by 2 once: 6 -> 3.
* 8 can be divided by 2 three times: 8 -> 4 -> 2 -> 1.
* 3 can be divided by 2 zero times.
Constraints
* 1 β€ N β€ 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer.
Examples
Input
7
Output
4
Input
32
Output
32
Input
1
Output
1
Input
100
Output
64
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main()
{int x,s=1;
cin>>x;
while(s<=x)
s*=2;
cout<<s/2;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
In the year 30XX, an expedition team reached a planet and found a warp machine suggesting the existence of a mysterious supercivilization. When you go through one of its entrance gates, you can instantaneously move to the exit irrespective of how far away it is. You can move even to the end of the universe at will with this technology!
The scientist team started examining the machine and successfully identified all the planets on which the entrances to the machine were located. Each of these N planets (identified by an index from $1$ to $N$) has an entrance to, and an exit from the warp machine. Each of the entrances and exits has a letter inscribed on it.
The mechanism of spatial mobility through the warp machine is as follows:
* If you go into an entrance gate labeled with c, then you can exit from any gate with label c.
* If you go into an entrance located on the $i$-th planet, then you can exit from any gate located on the $j$-th planet where $i < j$.
Once you have reached an exit of the warp machine on a planet, you can continue your journey by entering into the warp machine on the same planet. In this way, you can reach a faraway planet. Our human race has decided to dispatch an expedition to the star $N$, starting from Star $1$ and using the warp machine until it reaches Star $N$. To evaluate the possibility of successfully reaching the destination. it is highly desirable for us to know how many different routes are available for the expedition team to track.
Given information regarding the stars, make a program to enumerate the passages from Star $1$ to Star $N$.
Input
The input is given in the following format.
$N$
$s$
$t$
The first line provides the number of the stars on which the warp machine is located $N$ ($2 \leq N \leq 100,000$). The second line provides a string $s$ of length $N$, each component of which represents the letter inscribed on the entrance of the machine on the star. By the same token, the third line provides a string $t$ of length $N$ consisting of the letters inscribed on the exit of the machine. Two strings $s$ and $t$ consist all of lower-case alphabetical letters, and the $i$-th letter of these strings corresponds respectively to the entrance and exit of Star $i$ machine.
Output
Divide the number of possible routes from Star $1$ to Star $N$ obtained above by 1,000,000,007, and output the remainder.
Examples
Input
6
abbaba
baabab
Output
5
Input
25
neihsokcpuziafoytisrevinu
universityofaizupckoshien
Output
4
### Response
```cpp
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<string.h>
using namespace std;
const int M=1000000007;
const int N_MAX=100000;
int n,dp[N_MAX+1][26];
string s,t;
int main(){
cin>>n;
cin>>s>>t;
dp[0][s[0]-'a']=1;
for(int i=1;i<n;i++){
dp[i][s[i]-'a']=(dp[i][s[i]-'a']+dp[i-1][t[i]-'a'])%M;
for(int j=0;j<26;j++)dp[i][j]=(dp[i][j]+dp[i-1][j])%M;
}
cout<<dp[n-2][t[n-1]-'a']<<endl;
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Euler is a little, cute squirrel. When the autumn comes, he collects some reserves for winter. The interesting fact is that Euler likes to collect acorns in a specific way. A tree can be described as n acorns connected by n - 1 branches, such that there is exactly one way between each pair of acorns. Let's enumerate the acorns from 1 to n.
The squirrel chooses one acorn (not necessary with number 1) as a start, and visits them in a way called "Euler tour" (see notes), collecting each acorn when he visits it for the last time.
Today morning Kate was observing Euler. She took a sheet of paper and wrote down consecutive indices of acorns on his path. Unfortunately, during her way to home it started raining and some of numbers became illegible. Now the girl is very sad, because she has to present the observations to her teacher.
"Maybe if I guess the lacking numbers, I'll be able to do it!" she thought. Help her and restore any valid Euler tour of some tree or tell that she must have made a mistake.
Input
The first line contains a single integer n (1 β€ n β€ 5 β
10^5), denoting the number of acorns in the tree.
The second line contains 2n - 1 integers a_1, a_2, β¦, a_{2n-1} (0 β€ a_i β€ n) β the Euler tour of the tree that Kate wrote down. 0 means an illegible number, which has to be guessed.
Output
If there is no Euler tour satisfying the given description, output "no" in the first line.
Otherwise, on the first line output "yes", and then in the second line print the Euler tour which satisfy the given description.
Any valid Euler tour will be accepted, since the teacher doesn't know how exactly the initial tree looks.
Examples
Input
2
1 0 0
Output
yes
1 2 1
Input
4
1 0 3 2 0 0 0
Output
yes
1 4 3 2 3 4 1
Input
5
0 1 2 3 4 1 0 0 0
Output
no
Note
An Euler tour of a tree with n acorns is a sequence of 2n - 1 indices of acorns. such that each acorn occurs at least once, the first and the last acorns are same and each two consecutive acorns are directly connected with a branch.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int RLEN = 1 << 18 | 1;
inline char nc() {
static char ibuf[RLEN], *ib, *ob;
(ib == ob) && (ob = (ib = ibuf) + fread(ibuf, 1, RLEN, stdin));
return (ib == ob) ? -1 : *ib++;
}
inline int rd() {
char ch = nc();
int i = 0, f = 1;
while (!isdigit(ch)) {
if (ch == '-') f = -1;
ch = nc();
}
while (isdigit(ch)) {
i = (i << 1) + (i << 3) + ch - '0';
ch = nc();
}
return i * f;
}
const int N = 1e6 + 50, L = 21;
int n, a[N], c[N], li[N], ri[N], pre[N], lst[N], mn[N][21];
vector<int> unvis;
inline int ga(int *anc, int x) {
return (anc[x] == x) ? x : (anc[x] = ga(anc, anc[x]));
}
inline void solve(int l, int r) {
vector<int> vec;
int p = -1;
for (int i = ga(ri, l); i <= r; i = ga(ri, i + 1)) {
vec.push_back(i);
++p;
while (vec.size() >= 3) {
if (((!a[vec[p - 2]] && a[i]) || (a[vec[p - 2]] && !a[i]) ||
(a[vec[p - 2]] && (a[vec[p - 2]] == a[i]))) &&
a[vec[p - 1]]) {
if (a[vec[p - 2]] != a[vec[p]])
a[vec[p - 2]] = a[i] = a[vec[p - 2]] + a[i];
vec.pop_back();
vec.pop_back();
p -= 2;
} else
break;
}
}
for (int j = 1; j < vec.size(); ++j)
if (a[vec[j]] && a[vec[j - 1]]) {
puts("no");
exit(0);
}
deque<int> q;
int nowl = vec[0];
for (int j = 1; j < vec.size() - 1; ++j) q.push_back(vec[j]);
while (!q.empty()) {
int u = q.front(), v = q.back();
if (q.size() == 1) {
if (!a[u]) {
if (unvis.empty()) {
puts("no");
exit(0);
}
a[u] = unvis.back();
unvis.pop_back();
}
break;
} else {
if (!a[u] && !a[v]) {
if (unvis.empty()) {
puts("no");
exit(0);
}
a[u] = a[v] = unvis.back();
unvis.pop_back();
nowl = a[u];
q.pop_front();
q.pop_back();
} else if (a[u]) {
a[q[1]] = nowl;
q.pop_front();
q.pop_front();
} else {
a[q[q.size() - 2]] = nowl;
q.pop_back();
q.pop_back();
}
}
}
for (int i = ga(ri, l); i <= r; i = ga(ri, i + 1))
if (i != l) ri[i] = r + 1;
li[r] = l;
}
inline void solve2() {
if (unvis.size()) {
a[1] = a[2 * n - 1] = unvis.back();
unvis.pop_back();
solve(1, 2 * n - 1);
return;
}
vector<int> vec;
int p = -1;
for (int i = 1; i < 2 * n; i = ga(ri, i + 1)) {
vec.push_back(i);
++p;
}
int c0 = 0, c1 = 0;
for (int j = 0; j < vec.size(); ++j)
if (a[vec[j]]) ++c1;
for (int j = 1; j < p; j++) {
if (!a[vec[j]]) continue;
--c1;
if (vec[j] & 1) {
if (j >= 2 * c0 && p - j >= 2 * c1) {
a[1] = a[2 * n - 1] = a[vec[j]];
solve(1, 2 * n - 1);
return;
}
}
++c0;
}
puts("no");
exit(0);
}
int main() {
n = rd();
for (int i = 1; i < 2 * n; i++) {
a[i] = rd();
++c[a[i]];
}
for (int i = 1; i <= n; i++)
if (!c[i]) unvis.push_back(i);
if (a[1] && a[2 * n - 1] && a[1] != a[2 * n - 1]) {
puts("no");
return 0;
} else if ((a[1] || a[2 * n - 1]) && (a[1] != a[2 * n - 1])) {
a[1] = a[2 * n - 1] = a[1] + a[2 * n - 1];
}
for (int i = 1; i < 2 * n; i++) {
if (!a[i]) continue;
pre[i] = (lst[a[i]] ? lst[a[i]] : i);
lst[a[i]] = i;
}
for (int i = 1; i < 2 * n; i++) {
mn[i][0] = (pre[i] ? pre[i] : i);
if (a[i] && ((i - pre[i]) % 2)) {
puts("no");
return 0;
}
for (int j = 1; j < L && (i >= (1 << j)); j++)
mn[i][j] = min(mn[i][j - 1], mn[i - (1 << (j - 1))][j - 1]);
if (a[i] && pre[i] < i) {
int mx = i, pos = i - 1;
for (int j = L - 1; ~j; j--)
if (pos - (1 << j) + 1 > pre[i])
mx = min(mx, mn[pos][j]), pos -= (1 << j);
if (mx <= pre[i]) {
puts("no");
return 0;
}
}
}
for (int i = 1; i <= 2 * n; i++) ri[i] = i, li[i] = i;
for (int i = 2; i < 2 * n; i++)
if (a[i] && ga(li, pre[i]) < i) solve(ga(li, pre[i]), i);
if (!a[1] && !a[2 * n - 1]) solve2();
puts("yes");
for (int i = 1; i < 2 * n; i++) printf("%d ", a[i]);
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Niwango-kun, an employee of Dwango Co., Ltd., likes Niconico TV-chan, so he collected a lot of soft toys of her and spread them on the floor.
Niwango-kun has N black rare soft toys of Niconico TV-chan and they are spread together with ordinary ones. He wanted these black rare soft toys to be close together, so he decided to rearrange them.
In an infinitely large two-dimensional plane, every lattice point has a soft toy on it. The coordinates (x_i,y_i) of N black rare soft toys are given. All soft toys are considered to be points (without a length, area, or volume).
He may perform the following operation arbitrarily many times:
* Put an axis-aligned square with side length D, rotate the square by 90 degrees with four soft toys on the four corners of the square. More specifically, if the left bottom corner's coordinate is (x, y), rotate four points (x,y) \rightarrow (x+D,y) \rightarrow (x+D,y+D) \rightarrow (x,y+D) \rightarrow (x,y) in this order. Each of the four corners of the square must be on a lattice point.
Let's define the scatteredness of an arrangement by the minimum side length of an axis-aligned square enclosing all black rare soft toys. Black rare soft toys on the edges or the vertices of a square are considered to be enclosed by the square.
Find the minimum scatteredness after he performs arbitrarily many operations.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq D \leq 1000
* 0 \leq x_i, y_i \leq 10^9
* Given coordinates are pairwise distinct
* All numbers given in input are integers
Input
Input is given from Standard Input in the following format:
N D
x_1 y_1
:
x_N y_N
Output
Print the answer.
Examples
Input
3 1
0 0
1 0
2 0
Output
1
Input
19 2
1 3
2 3
0 1
1 1
2 1
3 1
4 4
5 4
6 4
7 4
8 4
8 3
8 2
8 1
8 0
7 0
6 0
5 0
4 0
Output
4
Input
8 3
0 0
0 3
3 0
3 3
2 2
2 5
5 2
5 5
Output
4
### Response
```cpp
#if 1
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <stack>
#include <array>
#include <deque>
#include <algorithm>
#include <utility>
#include <cstdint>
#include <functional>
#include <iomanip>
#include <numeric>
#include <assert.h>
#include <bitset>
#include <list>
auto& in = std::cin;
auto& out = std::cout;
#define all_range(C) std::begin(C), std::end(C)
const double PI = 3.141592653589793238462643383279502884197169399375105820974944;
int32_t N, D;
int32_t num[1000][1000];
int32_t square[1000][1000];
int32_t num_one[2100][2100];
int32_t num_error[2100][2100];
using INT_T = int32_t;
template<typename ARR>
inline void add_full(ARR& v1, ARR& v2)
{
v1 += v2;
}
template<typename ARR, size_t N>
inline void add_full(ARR(&v1)[N], ARR(&v2)[N])
{
auto iter1 = v1, iter2 = v2, iter1end = v1 + N;
while (iter1 != iter1end) {
add_full(*iter1++, *iter2++);
}
}
//1-indexedη΄―η©ε
template<size_t N>void CuSum(INT_T(&arr)[N])
{
for (size_t i = 2; i < N; i++)
{
arr[i] += arr[i - 1];
}
}
template<typename ARR, size_t N>void CuSum(ARR(&arr)[N])
{
for (auto& arr2 : arr) {
CuSum(arr2);
}
for (size_t i = 2; i < N; i++)
{
add_full(arr[i], arr[i - 1]);
}
}
#if 0
template<size_t N, size_t M>void CuSum(INT_T(&arr)[N][M])
{
for (auto& arr2 : arr) {
CuSum(arr2);
}
for (size_t i = 2; i < N; i++)
{
add_full(arr[i], arr[i - 1]);
}
}
template<size_t N, size_t M, size_t O>void CuSum(INT_T(&arr)[N][M][O])
{
for (auto& arr2 : arr) {
CuSum(arr2);
}
for (size_t i = 2; i < N; i++)
{
add_full(arr[i], arr[i - 1]);
}
}
#endif
//1-indexedγ(]εΊι
template<size_t N> INT_T get_sum(INT_T(&arr)[N], int x, int x2)
{
return (arr[x2] - arr[x]);
}
//1-indexedγ(]εΊι
template<size_t N, size_t M> INT_T get_sum(INT_T(&arr)[N][M], int x, int y, int x2, int y2)
{
return (arr[y2][x2] - arr[y][x2] - arr[y2][x] + arr[y][x]);
}
//1-indexedγ(]εΊι
template<size_t N, size_t M, size_t O> INT_T get_sum(INT_T(&arr)[N][M][O], int x, int y, int z, int x2, int y2, int z2)
{
return arr(arr[z2][y2][x2] - arr[z][y2][x2] - arr[z2][y][x2] - arr[z2][y2][x] + arr[z2][y][x] + arr[z2][y][x] + arr[z][y][x2] - arr[z][y][x]);
}
int main()
{
using std::get;
using std::endl;
in.sync_with_stdio(false);
out.sync_with_stdio(false);
in.tie(nullptr);
out.tie(nullptr);
in >> N >> D;
for (size_t i = 0; i < N; i++)
{
int x, y;
in >> x >> y;
x %= D;
y %= D;
num[x][y]++;
}
int32_t max_square = -1;
std::vector<std::tuple<int, int, int>> max_list;
for (int32_t i = 0; i < D; i++)
{
for (int32_t j = 0; j < D; j++)
{
auto s = (int32_t)std::sqrt(square[i][j]);
while ((s*s) < num[i][j]) {
++s;
}
square[i][j] = s;
int min_size = ((s*(s-1)) >= num[i][j])?1:0;
if (max_square < s) {
max_square = s;
max_list.clear();
max_list.emplace_back(i, j, min_size);
}
else if(max_square == s){
max_list.emplace_back(i, j, min_size);
}
}
}
if (max_list.size() == 1)
{
out << (max_square - 1)*D << endl;
return 0;
}
for (auto& i : max_list)
{
if (get<2>(i) == 1)
{
num_one[1+get<0>(i)][1+get<1>(i)]++;
num_one[1+get<0>(i)][1+get<1>(i) + D]++;
num_one[1+get<0>(i) + D][1 + get<1>(i)]++;
num_one[1+get<0>(i)+D][1 + get<1>(i)+D]++;
}
else
{
num_error[1+get<0>(i)][1 + get<1>(i)]++;
num_error[1+get<0>(i)][1 + get<1>(i) + D]++;
num_error[1+get<0>(i) + D][1 + get<1>(i)]++;
num_error[1+get<0>(i) + D][1 + get<1>(i) + D]++;
}
}
CuSum(num_one);
CuSum(num_error);
using BS_INT = int32_t;
BS_INT ok_range = D, ng_range = -1;
while (std::abs(ok_range - ng_range) > 1) {
BS_INT mid = (ok_range + ng_range) / 2;
bool is_ok = false;
for (int32_t i = 1-1; i <= D - 1; i++)
{
for (int32_t j = 1-1; j <= D - 1; j++)
{
if (get_sum(num_one, i + mid, j + mid, i + D, j + D) == 0 &&
get_sum(num_error,i,j, i + D, j + D) - get_sum(num_error, i, j, i + mid, j + mid) == 0
)
{
is_ok = true;
goto break_2;
}
}
}
break_2:;
//γγγ«ζΈγ
if (is_ok) {
ok_range = mid;
}
else {
ng_range = mid;
}
}
out << (max_square - 1)*D+ok_range-1 << endl;
#if 0
std::vector<std::tuple<int, int, int>> max_list2;
max_list2.reserve(max_list.size());
for (auto& i : max_list) {
max_list2.emplace_back(std::get<1>(i), std::get<0>(i), get<2>(i));
}
std::sort(max_list2.begin(), max_list2.end());
int32_t min_diff = D;
for (size_t i = 0; i < max_list.size(); i++)
{
if (i > 0 && get<0>(max_list[i]) == get<0>(max_list2[i-1])) { continue; }
for (size_t j = 0; j < max_list2.size(); j++)
{
if (j > 0 && get<0>(max_list2[j]) == get<0>(max_list2[j-1])) { continue; }
//for (auto& k : max_list)
//{
// used[get<0>(k)][get<1>(k)] = false;
//}
auto cir_dec = [&max_list](size_t index) {if (index == 0) { return max_list.size() - 1; } else { return index - 1; }};
auto cir_inc = [&max_list](size_t index) {if ((++index) == max_list.size()) { return (size_t)0; } else { return index; }};
size_t k = cir_dec(i);
for (; k != i; k = cir_dec(k))
{
if (get<2>(max_list[k]) == 0) {
break;
}
used[get<0>(max_list[k])][get<1>(max_list[k])] = true;
}
size_t l = cir_dec(j);
for (; k != i; k = cir_inc(k))
{
int32_t x_diff = get<0>(max_list[k]) - get<0>(max_list[i]);
if (x_diff < 0) { x_diff += D; }
while (get<2>(max_list2[l]) == 1 && used[get<1>(max_list2[l])][get<0>(max_list2[l])] == false && l != j);
int32_t y_diff = get<0>(max_list[l]) - get<0>(max_list[j]);
if (y_diff < 0) { y_diff += D; }
min_diff = std::min(x_diff, y_diff);
used[get<0>(max_list[k])][get<1>(max_list[k])] = false;
}
#if 0
for (size_t k = cir_dec(i); k != i; k= cir_dec(k))
{
int32_t x_diff = get<0>(max_list[k]) - get<0>(max_list[i]);
if (x_diff < 0) { x_diff += D; }
int32_t y_diff = 0;
size_t l = cir_dec(j);
while (get<2>(max_list2[l]) == 1 && used[get<1>(max_list2[l])][get<0>(max_list2[l])]==false && l != j);
int32_t y_diff = get<0>(max_list[l]) - get<0>(max_list[l]);
if (y_diff < 0) { y_diff += D; }
if (get<2>(max_list[k]) == 0) {
break;
}
used[get<0>(max_list[k])][get<1>(max_list[k])] = true;
}
#endif
}
}
out << (max_square - 1)*D + min_diff << endl;
#endif
return 0;
}
#endif
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Aizu is famous for its buckwheat. There are many people who make buckwheat noodles by themselves.
One day, you went shopping to buy buckwheat flour. You can visit three shops, A, B and C. The amount in a bag and its unit price for each shop is determined by the follows table. Note that it is discounted when you buy buckwheat flour in several bags.
| Shop A | Shop B | Shop C
---|---|---|---
Amount in a bag | 200g| 300g| 500g
Unit price for a bag (nominal cost)| 380 yen | 550 yen | 850 yen
Discounted units | per 5 bags | per 4 bags | per 3 bags
Discount rate| reduced by 20 %| reduced by 15 %| reduced by 12 %
For example, when you buy 12 bags of flour at shop A, the price is reduced by 20 % for 10 bags, but not for other 2 bags. So, the total amount shall be (380 Γ 10) Γ 0.8 + 380 Γ 2 = 3,800 yen.
Write a program which reads the amount of flour, and prints the lowest cost to buy them. Note that you should buy the flour of exactly the same amount as the given input.
Input
The input consists of multiple datasets. For each dataset, an integer a (500 β€ a β€ 5000, a is divisible by 100) which represents the amount of flour is given in a line.
The input ends with a line including a zero. Your program should not process for the terminal symbol. The number of datasets does not exceed 50.
Output
For each dataset, print an integer which represents the lowest cost.
Example
Input
500
2200
0
Output
850
3390
### Response
```cpp
#include<iostream>
#include<algorithm>
#define INF 1<<28
using namespace std;
int memo[10000];
int solve(int n){
if(!n) return 0;
if(n < 0) return INF;
if(memo[n]) return memo[n];
return memo[n] = min(INF, min(solve(n-1000)+1520, min(solve(n-1200)+1870, min(solve(n-1500)+2244, min(solve(n-200)+380, min(solve(n-300)+550, solve(n-500)+850))))));
}
int main(){
int n;
for(int i=0;i<5001;i+=100) solve(i);
while(cin >> n, n) cout << memo[n] << endl;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
You have A 500-yen coins, B 100-yen coins and C 50-yen coins (yen is the currency of Japan). In how many ways can we select some of these coins so that they are X yen in total?
Coins of the same kind cannot be distinguished. Two ways to select coins are distinguished when, for some kind of coin, the numbers of that coin are different.
Constraints
* 0 \leq A, B, C \leq 50
* A + B + C \geq 1
* 50 \leq X \leq 20 000
* A, B and C are integers.
* X is a multiple of 50.
Input
Input is given from Standard Input in the following format:
A
B
C
X
Output
Print the number of ways to select coins.
Examples
Input
2
2
2
100
Output
2
Input
5
1
0
150
Output
0
Input
30
40
50
6000
Output
213
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int a,b,c,n,ans=0;
cin>>a>>b>>c>>n;
for(int i=0;i<=a;++i)
for(int j=0;j<=b;++j)
for(int k=0;k<=c;++k)
if(500*i+100*j+50*k==n)ans++;
cout << ans << endl;
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
During a break in the buffet of the scientific lyceum of the Kingdom of Kremland, there was formed a queue of n high school students numbered from 1 to n. Initially, each student i is on position i. Each student i is characterized by two numbers β a_i and b_i. Dissatisfaction of the person i equals the product of a_i by the number of people standing to the left of his position, add the product b_i by the number of people standing to the right of his position. Formally, the dissatisfaction of the student i, which is on the position j, equals a_i β
(j-1) + b_i β
(n-j).
The director entrusted Stas with the task: rearrange the people in the queue so that minimize the total dissatisfaction.
Although Stas is able to solve such problems, this was not given to him. He turned for help to you.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of people in the queue.
Each of the following n lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ 10^8) β the characteristic of the student i, initially on the position i.
Output
Output one integer β minimum total dissatisfaction which can be achieved by rearranging people in the queue.
Examples
Input
3
4 2
2 3
6 1
Output
12
Input
4
2 4
3 3
7 1
2 3
Output
25
Input
10
5 10
12 4
31 45
20 55
30 17
29 30
41 32
7 1
5 5
3 15
Output
1423
Note
In the first example it is optimal to put people in this order: (3, 1, 2). The first person is in the position of 2, then his dissatisfaction will be equal to 4 β
1+2 β
1=6. The second person is in the position of 3, his dissatisfaction will be equal to 2 β
2+3 β
0=4. The third person is in the position of 1, his dissatisfaction will be equal to 6 β
0+1 β
2=2. The total dissatisfaction will be 12.
In the second example, you need to put people in this order: (3, 2, 4, 1). The total dissatisfaction will be 25.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool cmp(pair<long long int, long long int>& a,
pair<long long int, long long int>& b) {
return (a.first - a.second) > (b.first - b.second);
}
int main() {
long long int n, p, q, i, j;
cin >> n;
vector<pair<long long int, long long int>> v;
for (i = 1; i <= n; i++) {
cin >> p >> q;
v.push_back({p, q});
}
sort(v.begin(), v.end(), cmp);
long long int ans = 0;
for (i = 0; i < v.size(); i++) {
ans = ans + (v[i].first * (i)) + v[i].second * (n - i - 1);
}
cout << ans;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Given is a positive integer L. Find the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L.
Constraints
* 1 β€ L β€ 1000
* L is an integer.
Input
Input is given from Standard Input in the following format:
L
Output
Print the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L. Your output is considered correct if its absolute or relative error from our answer is at most 10^{-6}.
Examples
Input
3
Output
1.000000000000
Input
999
Output
36926037.000000000000
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
double l;
cin>>l;
printf("%.12f\n",pow(l/3,3.0));
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Dr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go.
Dr. Evil is interested in sets, He has a set of n integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly x. the MEX of a set of integers is the minimum non-negative integer that doesn't exist in it. For example, the MEX of the set {0, 2, 4} is 1 and the MEX of the set {1, 2, 3} is 0 .
Dr. Evil is going to make his set evil. To do this he can perform some operations. During each operation he can add some non-negative integer to his set or erase some element from it. What is the minimal number of operations Dr. Evil has to perform to make his set evil?
Input
The first line contains two integers n and x (1 β€ n β€ 100, 0 β€ x β€ 100) β the size of the set Dr. Evil owns, and the desired MEX.
The second line contains n distinct non-negative integers not exceeding 100 that represent the set.
Output
The only line should contain one integer β the minimal number of operations Dr. Evil should perform.
Examples
Input
5 3
0 4 5 6 7
Output
2
Input
1 0
0
Output
1
Input
5 0
1 2 3 4 5
Output
0
Note
For the first test case Dr. Evil should add 1 and 2 to the set performing 2 operations.
For the second test case Dr. Evil should erase 0 from the set. After that, the set becomes empty, so the MEX of it is 0.
In the third test case the set is already evil.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, x, temp;
int frequency[101] = {0};
int counter = 0;
cin >> n >> x;
for (int i = 0; i < n; i++) {
cin >> temp;
frequency[temp]++;
}
for (int i = 0; i < x; i++) {
if (frequency[i] == 0) {
counter++;
}
}
if (frequency[x] >= 1) {
counter++;
}
cout << counter << endl;
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Vasya will fancy any number as long as it is an integer power of two. Petya, on the other hand, is very conservative and only likes a single integer p (which may be positive, negative, or zero). To combine their tastes, they invented p-binary numbers of the form 2^x + p, where x is a non-negative integer.
For example, some -9-binary ("minus nine" binary) numbers are: -8 (minus eight), 7 and 1015 (-8=2^0-9, 7=2^4-9, 1015=2^{10}-9).
The boys now use p-binary numbers to represent everything. They now face a problem: given a positive integer n, what's the smallest number of p-binary numbers (not necessarily distinct) they need to represent n as their sum? It may be possible that representation is impossible altogether. Help them solve this problem.
For example, if p=0 we can represent 7 as 2^0 + 2^1 + 2^2.
And if p=-9 we can represent 7 as one number (2^4-9).
Note that negative p-binary numbers are allowed to be in the sum (see the Notes section for an example).
Input
The only line contains two integers n and p (1 β€ n β€ 10^9, -1000 β€ p β€ 1000).
Output
If it is impossible to represent n as the sum of any number of p-binary numbers, print a single integer -1. Otherwise, print the smallest possible number of summands.
Examples
Input
24 0
Output
2
Input
24 1
Output
3
Input
24 -1
Output
4
Input
4 -7
Output
2
Input
1 1
Output
-1
Note
0-binary numbers are just regular binary powers, thus in the first sample case we can represent 24 = (2^4 + 0) + (2^3 + 0).
In the second sample case, we can represent 24 = (2^4 + 1) + (2^2 + 1) + (2^0 + 1).
In the third sample case, we can represent 24 = (2^4 - 1) + (2^2 - 1) + (2^2 - 1) + (2^2 - 1). Note that repeated summands are allowed.
In the fourth sample case, we can represent 4 = (2^4 - 7) + (2^1 - 7). Note that the second summand is negative, which is allowed.
In the fifth sample case, no representation is possible.
### Response
```cpp
#include <bits/stdc++.h>
const long long INF = 2000000005;
const long long BIG_INF = 2000000000000000005;
const long long mod = 1000000007;
const long long P = 31;
const long double PI = 3.141592653589793238462643;
const double eps = 1e-9;
using namespace std;
vector<pair<long long, long long> > dir = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
bool valid(long long x, long long y, long long n, long long m) {
return x >= 0 && y >= 0 && x < n && y < m;
}
mt19937 rng(1999999973);
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
long long n, p;
cin >> n >> p;
for (long long i = 1; i < 100; i++) {
if (n - p * i > 0 && __builtin_popcountll(n - p * i) <= i &&
n - p * i >= i) {
cout << i;
return 0;
}
}
cout << -1;
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Vasya's got a birthday coming up and his mom decided to give him an array of positive integers a of length n.
Vasya thinks that an array's beauty is the greatest common divisor of all its elements. His mom, of course, wants to give him as beautiful an array as possible (with largest possible beauty). Unfortunately, the shop has only one array a left. On the plus side, the seller said that he could decrease some numbers in the array (no more than by k for each number).
The seller can obtain array b from array a if the following conditions hold: bi > 0; 0 β€ ai - bi β€ k for all 1 β€ i β€ n.
Help mom find the maximum possible beauty of the array she will give to Vasya (that seller can obtain).
Input
The first line contains two integers n and k (1 β€ n β€ 3Β·105; 1 β€ k β€ 106). The second line contains n integers ai (1 β€ ai β€ 106) β array a.
Output
In the single line print a single number β the maximum possible beauty of the resulting array.
Examples
Input
6 1
3 6 10 12 13 16
Output
3
Input
5 3
8 21 52 15 77
Output
7
Note
In the first sample we can obtain the array:
3 6 9 12 12 15
In the second sample we can obtain the next array:
7 21 49 14 77
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <class T>
inline bool read(T &x) {
int c = getchar();
int sgn = 1;
while ((~c && c < '0') || c > '9') {
if (c == '-') sgn = -1;
c = getchar();
}
for (x = 0; ~c && '0' <= c && c <= '9'; c = getchar()) x = x * 10 + c - '0';
x *= sgn;
return ~c;
}
int X[] = {-1, 0, 1, 0};
int Y[] = {0, 1, 0, -1};
int n, k, arr[300010];
bool isInside(int r, int div) { return (r % div <= k); }
int main() {
read(n);
read(k);
for (int i = 0; i < n; i++) {
read(arr[i]);
}
sort(arr, arr + n);
int ans = arr[0];
while (true) {
bool flag = false;
for (int i = 0; i < n; i++) {
while (!isInside(arr[i], ans)) ans--, flag = true;
}
if (!flag) break;
}
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
A team of students from the city S is sent to the All-Berland Olympiad in Informatics. Traditionally, they go on the train. All students have bought tickets in one carriage, consisting of n compartments (each compartment has exactly four people). We know that if one compartment contain one or two students, then they get bored, and if one compartment contain three or four students, then the compartment has fun throughout the entire trip.
The students want to swap with other people, so that no compartment with students had bored students. To swap places with another person, you need to convince him that it is really necessary. The students can not independently find the necessary arguments, so they asked a sympathetic conductor for help. The conductor can use her life experience to persuade any passenger to switch places with some student.
However, the conductor does not want to waste time persuading the wrong people, so she wants to know what is the minimum number of people necessary to persuade her to change places with the students. Your task is to find the number.
After all the swaps each compartment should either have no student left, or have a company of three or four students.
Input
The first line contains integer n (1 β€ n β€ 106) β the number of compartments in the carriage. The second line contains n integers a1, a2, ..., an showing how many students ride in each compartment (0 β€ ai β€ 4). It is guaranteed that at least one student is riding in the train.
Output
If no sequence of swapping seats with other people leads to the desired result, print number "-1" (without the quotes). In another case, print the smallest number of people you need to persuade to swap places.
Examples
Input
5
1 2 2 4 3
Output
2
Input
3
4 1 1
Output
2
Input
4
0 3 0 4
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(void) {
int cnt[5] = {0};
int n = 0;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int x = 0;
scanf("%d", &x);
cnt[x]++;
}
bool fail = false;
int ans = 0;
while (cnt[1]) {
if (cnt[2] > 0) {
cnt[2]--;
cnt[1]--;
cnt[3]++;
ans++;
} else if (cnt[1] >= 3) {
cnt[2]++;
cnt[1] -= 2;
ans++;
} else if (cnt[1] <= cnt[3]) {
cnt[3] -= cnt[1];
cnt[4] += cnt[1];
ans += cnt[1];
cnt[1] = 0;
} else if (cnt[1] >= 2) {
cnt[2]++;
cnt[1] = 0;
ans++;
} else if (cnt[1] == 1) {
if (cnt[4] < 2) {
fail = true;
break;
}
cnt[4] -= 2;
cnt[1] = 0;
cnt[3] += 2 + 1;
ans += 2;
}
}
while (cnt[2]) {
if (cnt[2] >= 3) {
cnt[2] -= 3;
cnt[3] += 3;
ans += 2;
} else if (cnt[2] == 2) {
cnt[4]++;
cnt[2] -= 2;
ans += 2;
} else if (cnt[4]) {
cnt[4]--;
cnt[2]--;
cnt[3] += 1 + 1;
ans++;
} else if (cnt[3] < 2) {
fail = true;
break;
} else {
cnt[3] -= 2;
cnt[4] += 2;
cnt[2]--;
ans += 2;
}
}
if (fail) ans = -1;
printf("%d\n", ans);
while (getchar() != EOF)
;
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for every node $i$ other than the root, $A[i] \leq A[parent(i)]$, that is, the value of a node is at most the value of its parent. The largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values no larger than that contained at the node itself.
Here is an example of a max-heap.
<image>
Write a program which reads an array and constructs a max-heap from the array based on the following pseudo code.
$maxHeapify(A, i)$ move the value of $A[i]$ down to leaves to make a sub-tree of node $i$ a max-heap. Here, $H$ is the size of the heap.
1 maxHeapify(A, i)
2 l = left(i)
3 r = right(i)
4 // select the node which has the maximum value
5 if l β€ H and A[l] > A[i]
6 largest = l
7 else
8 largest = i
9 if r β€ H and A[r] > A[largest]
10 largest = r
11
12 if largest β iγ// value of children is larger than that of i
13 swap A[i] and A[largest]
14 maxHeapify(A, largest) // call recursively
The following procedure buildMaxHeap(A) makes $A$ a max-heap by performing maxHeapify in a bottom-up manner.
1 buildMaxHeap(A)
2 for i = H/2 downto 1
3 maxHeapify(A, i)
Input
In the first line, an integer $H$ is given. In the second line, $H$ integers which represent elements in the binary heap are given in order of node id (from $1$ to $H$).
Output
Print values of nodes in the max-heap in order of their id (from $1$ to $H$). Print a single space character before each value.
Example
Input
10
4 1 3 2 16 9 10 14 8 7
Output
16 14 10 8 7 9 3 2 4 1
### Response
```cpp
#include <stdio.h>
#define N 5000000
int n;
int A[N];
void maxHeap(int i){
int l = i*2;
int r = i*2 + 1;
int largest = i;
int tmp;
if(l <= n && A[l]>A[i]) largest = l;
else largest = i;
if(r <= n && A[r]>A[largest]) largest = r;
if(largest != i) {
tmp = A[i];
A[i] = A[largest];
A[largest] = tmp;
maxHeap(largest);
}
}
void buildHeap(){
int i;
for(i=n/2;i>0;i--){
maxHeap(i);
}
}
int main(){
scanf("%d",&n);
int i;
for(i=1;i<=n;i++){
scanf("%d",&A[i]);
}
buildHeap();
for(i=1;i<=n;i++){
printf(" %d",A[i]);
}
printf("\n");
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 β€ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 β€ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 200 000) β the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line β "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m;
struct ac {
int x, y;
} t[202400];
bool cmp(const ac &a, const ac &b) {
if (a.x != b.x) {
return a.x < b.x;
} else {
return a.y < b.y;
}
}
bool wfHas(int x, int y) {
int l = 0, r = m - 1, mid;
while (l < r) {
mid = (l + r) / 2;
if (t[mid].x == x && t[mid].y == y) {
return true;
}
if (x < t[mid].x || x == t[mid].x && y < t[mid].y) {
r = mid;
} else {
l = mid + 1;
}
}
return (t[l].x == x && t[l].y == y);
}
bool wf(int k) {
int i, x, y;
for (i = 0; i < m; i++) {
x = t[i].x + k;
y = t[i].y + k;
if (x > n) x -= n;
if (y > n) y -= n;
if (x > y) {
x ^= y;
y ^= x;
x ^= y;
}
if (!wfHas(x, y)) {
return false;
}
}
return true;
}
void solve() {
int i, k;
int x, y;
for (i = 0; i < m; i++) {
scanf("%d %d", &x, &y);
if (x > y) {
k = x;
x = y;
y = k;
}
t[i].x = x;
t[i].y = y;
}
sort(t, t + m, cmp);
if (wf(1)) {
printf("Yes\n");
return;
}
for (i = 2; i * i <= n; i++) {
if (n % i == 0) {
if (wf(i) || wf(n / i)) {
printf("Yes\n");
return;
}
}
}
printf("No\n");
}
int main() {
while (scanf("%d %d", &n, &m) != EOF) {
solve();
}
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
As you very well know, the whole Universe traditionally uses three-dimensional Cartesian system of coordinates. In this system each point corresponds to three real coordinates (x, y, z). In this coordinate system, the distance between the center of the Universe and the point is calculated by the following formula: <image>. Mushroom scientists that work for the Great Mushroom King think that the Universe isn't exactly right and the distance from the center of the Universe to a point equals xaΒ·ybΒ·zc.
To test the metric of mushroom scientists, the usual scientists offered them a task: find such x, y, z (0 β€ x, y, z; x + y + z β€ S), that the distance between the center of the Universe and the point (x, y, z) is maximum possible in the metric of mushroom scientists. The mushroom scientists aren't good at maths, so they commissioned you to do the task.
Note that in this problem, it is considered that 00 = 1.
Input
The first line contains a single integer S (1 β€ S β€ 103) β the maximum sum of coordinates of the sought point.
The second line contains three space-separated integers a, b, c (0 β€ a, b, c β€ 103) β the numbers that describe the metric of mushroom scientists.
Output
Print three real numbers β the coordinates of the point that reaches maximum value in the metrics of mushroom scientists. If there are multiple answers, print any of them that meets the limitations.
A natural logarithm of distance from the center of the Universe to the given point in the metric of mushroom scientists shouldn't differ from the natural logarithm of the maximum distance by more than 10 - 6. We think that ln(0) = - β.
Examples
Input
3
1 1 1
Output
1.0 1.0 1.0
Input
3
2 0 0
Output
3.0 0.0 0.0
### Response
```cpp
#include <bits/stdc++.h>
int fix(double x) {
if (fabs(x) <= 1e-9)
return 0;
else if (x > 1e-9)
return 1;
else
return -1;
}
int main() {
double s;
while (scanf("%lf", &s) != EOF) {
double num[4];
double ans[4];
for (int i = 1; i <= 3; i++) scanf("%lf", &num[i]);
num[0] = 0;
for (int i = 1; i <= 3; i++) num[0] += num[i];
if (fix(num[0]) == 0)
for (int i = 1; i <= 3; i++) ans[i] = s / 3;
else
for (int i = 1; i <= 3; i++) ans[i] = s * num[i] / num[0];
for (int i = 1; i <= 3; i++)
if (i == 3)
printf("%.12f\n", ans[i]);
else
printf("%.12f ", ans[i]);
}
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher:
You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type:
1. For given numbers xi and vi assign value vi to element axi.
2. For given numbers li and ri you've got to calculate sum <image>, where f0 = f1 = 1 and at i β₯ 2: fi = fi - 1 + fi - 2.
3. For a group of three numbers li ri di you should increase value ax by di for all x (li β€ x β€ ri).
Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem.
Input
The first line contains two integers n and m (1 β€ n, m β€ 2Β·105) β the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 β€ ai β€ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 β€ ti β€ 3) β the operation type:
* if ti = 1, then next follow two integers xi vi (1 β€ xi β€ n, 0 β€ vi β€ 105);
* if ti = 2, then next follow two integers li ri (1 β€ li β€ ri β€ n);
* if ti = 3, then next follow three integers li ri di (1 β€ li β€ ri β€ n, 0 β€ di β€ 105).
The input limits for scoring 30 points are (subproblem E1):
* It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type.
The input limits for scoring 70 points are (subproblems E1+E2):
* It is guaranteed that there will be queries of the 1-st and 2-nd type only.
The input limits for scoring 100 points are (subproblems E1+E2+E3):
* No extra limitations.
Output
For each query print the calculated sum modulo 1000000000 (109).
Examples
Input
5 5
1 3 1 2 4
2 1 4
2 1 5
2 2 4
1 3 10
2 1 5
Output
12
32
8
50
Input
5 4
1 3 1 2 4
3 1 4 1
2 2 4
1 2 10
2 1 5
Output
12
45
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long inf = INT_MAX, df = 3e5 + 7, mod = 1e9;
long long i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, a[df], f[df],
sum[df], tag[df * 20];
struct node {
long long sum1, sum2, siz;
} ma[df * 20];
inline long long read() {
long long x = 0, y = 1;
char ch = getchar();
while (ch > '9' || ch < '0') y = (ch == '-') ? -1 : 1, ch = getchar();
while (ch >= '0' && ch <= '9')
x = (x << 3) + (x << 1) + ch - '0', ch = getchar();
return x * y;
}
void pushdown(long long num, long long le, long long rig) {
if (!tag[num]) return;
ma[num].sum1 = ma[num].sum2 = 0;
tag[(num << 1)] += tag[num] % mod, tag[(num << 1)] %= mod,
tag[(num << 1 | 1)] += tag[num] % mod, tag[(num << 1 | 1)] %= mod;
ma[(num << 1)].sum1 =
(ma[(num << 1)].sum1 + tag[num] * sum[ma[(num << 1)].siz - 1] % mod) %
mod,
ma[(num << 1)].sum2 =
(ma[(num << 1)].sum2 +
tag[num] * (sum[ma[(num << 1)].siz] - sum[0]) % mod) %
mod;
ma[(num << 1 | 1)].sum1 = (ma[(num << 1 | 1)].sum1 +
tag[num] * sum[ma[(num << 1 | 1)].siz - 1] % mod) %
mod,
ma[(num << 1 | 1)].sum2 =
(ma[(num << 1 | 1)].sum2 +
tag[num] * (sum[ma[(num << 1 | 1)].siz] - sum[0]) % mod) %
mod;
tag[num] = 0;
}
node operator+(node st, node ch) {
node tr;
tr.sum1 = (st.sum1 + f[st.siz - 1] * ch.sum2 % mod +
(st.siz >= 2) * f[st.siz - 2] * ch.sum1 % mod) %
mod;
tr.sum2 =
(st.sum2 + f[st.siz] * ch.sum2 % mod + f[st.siz - 1] * ch.sum1 % mod) %
mod;
tr.siz = st.siz + ch.siz;
return tr;
}
void build(long long num, long long le, long long rig) {
if (le == rig) {
ma[num].sum1 = a[le] * f[0] % mod, ma[num].sum2 = a[le] * f[1] % mod,
ma[num].siz = 1;
return;
}
build((num << 1), le, ((le + rig) >> 1)),
build((num << 1 | 1), ((le + rig) >> 1) + 1, rig),
ma[num] = ma[(num << 1)] + ma[(num << 1 | 1)];
return;
}
void cov(long long num, long long le, long long rig, long long p, long long x) {
if (le > p || rig < p) return;
if (le == p && rig == p) {
ma[num].sum1 = x * f[0] % mod, ma[num].sum2 = x * f[1] % mod,
ma[num].siz = 1;
return;
}
pushdown(num, le, rig), cov((num << 1), le, ((le + rig) >> 1), p, x),
cov((num << 1 | 1), ((le + rig) >> 1) + 1, rig, p, x),
ma[num] = ma[(num << 1)] + ma[(num << 1 | 1)];
}
void upd(long long num, long long le, long long rig, long long l, long long r,
long long x) {
if (le > r || rig < l) return;
if (le >= l && rig <= r)
ma[num].sum1 = (ma[num].sum1 % mod + x * sum[ma[num].siz - 1] % mod) % mod,
ma[num].sum2 = (ma[num].sum2 + x * (sum[ma[num].siz] - sum[0]) % mod) % mod,
tag[num] += x % mod, tag[num] %= mod;
else
pushdown(num, le, rig), upd((num << 1), le, ((le + rig) >> 1), l, r, x),
upd((num << 1 | 1), ((le + rig) >> 1) + 1, rig, l, r, x),
ma[num] = ma[(num << 1)] + ma[(num << 1 | 1)];
}
node qry(long long num, long long le, long long rig, long long l, long long r) {
if (le >= l && rig <= r)
return ma[num];
else {
pushdown(num, le, rig);
node ty;
if (((le + rig) >> 1) >= l && r >= ((le + rig) >> 1) + 1)
ty = qry((num << 1), le, ((le + rig) >> 1), l, r) +
qry((num << 1 | 1), ((le + rig) >> 1) + 1, rig, l, r);
else if (((le + rig) >> 1) >= l)
ty = qry((num << 1), le, ((le + rig) >> 1), l, r);
else if (r >= ((le + rig) >> 1) + 1)
ty = qry((num << 1 | 1), ((le + rig) >> 1) + 1, rig, l, r);
ma[num] = ma[(num << 1)] + ma[(num << 1 | 1)];
return ty;
}
}
int main() {
n = read(), m = read();
f[0] = 1, sum[0] = 1;
f[1] = 1, sum[1] = 2;
for (long long i = (2); i <= (n + 7); ++i)
f[i] = (f[i - 1] + f[i - 2]) % mod, sum[i] = (sum[i - 1] + f[i]) % mod;
for (long long i = (1); i <= (n); ++i) a[i] = read() % mod;
build(1, 1, n);
for (long long i = (1); i <= (m); ++i) {
long long op = read(), x = read(), y = read();
if (op == 1) cov(1, 1, n, x, y);
if (op == 2) {
printf("%lld\n", (qry(1, 1, n, x, y).sum1 % mod + mod) % mod);
}
if (op == 3) {
long long d = read();
upd(1, 1, n, x, y, d % mod);
}
}
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Dima came to the horse land. There are n horses living in the land. Each horse in the horse land has several enemies (enmity is a symmetric relationship). The horse land isn't very hostile, so the number of enemies of each horse is at most 3.
Right now the horse land is going through an election campaign. So the horses trusted Dima to split them into two parts. At that the horses want the following condition to hold: a horse shouldn't have more than one enemy in its party.
Help Dima split the horses into parties. Note that one of the parties can turn out to be empty.
Input
The first line contains two integers n, m <image> β the number of horses in the horse land and the number of enemy pairs.
Next m lines define the enemy pairs. The i-th line contains integers ai, bi (1 β€ ai, bi β€ n; ai β bi), which mean that horse ai is the enemy of horse bi.
Consider the horses indexed in some way from 1 to n. It is guaranteed that each horse has at most three enemies. No pair of enemies occurs more than once in the input.
Output
Print a line, consisting of n characters: the i-th character of the line must equal "0", if the horse number i needs to go to the first party, otherwise this character should equal "1".
If there isn't a way to divide the horses as required, print -1.
Examples
Input
3 3
1 2
3 2
3 1
Output
100
Input
2 1
2 1
Output
00
Input
10 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
0110000000
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename T>
T in() {
char ch;
T n = 0;
bool ng = false;
while (1) {
ch = getchar();
if (ch == '-') {
ng = true;
ch = getchar();
break;
}
if (ch >= '0' && ch <= '9') break;
}
while (1) {
n = n * 10 + (ch - '0');
ch = getchar();
if (ch < '0' || ch > '9') break;
}
return (ng ? -n : n);
}
vector<int> G[300005 + 5];
bool col[300005 + 5];
int n;
void Dfs(int u) {
int i, sz = G[u].size(), cnt = 0;
for (i = 0; i <= sz - 1; i++) {
int v = G[u][i];
cnt += (col[u] == col[v]);
}
if (cnt > 1) {
col[u] ^= 1;
for (i = 0; i <= sz - 1; i++) {
int v = G[u][i];
Dfs(v);
}
}
}
int main() {
int m, i, j, k, x, y;
n = in<int>();
m = in<int>();
for (i = 1; i <= m; i++) {
x = in<int>();
y = in<int>();
G[x].push_back(y);
G[y].push_back(x);
}
for (i = 1; i <= n; i++) {
Dfs(i);
}
for (i = 1; i <= n; i++) printf("%d", col[i]);
puts("");
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Gildong is now developing a puzzle game. The puzzle consists of n platforms numbered from 1 to n. The player plays the game as a character that can stand on each platform and the goal of the game is to move the character from the 1-st platform to the n-th platform.
The i-th platform is labeled with an integer a_i (0 β€ a_i β€ n-i). When the character is standing on the i-th platform, the player can move the character to any of the j-th platforms where i+1 β€ j β€ i+a_i. If the character is on the i-th platform where a_i=0 and i β n, the player loses the game.
Since Gildong thinks the current game is not hard enough, he wants to make it even harder. He wants to change some (possibly zero) labels to 0 so that there remains exactly one way to win. He wants to modify the game as little as possible, so he's asking you to find the minimum number of platforms that should have their labels changed. Two ways are different if and only if there exists a platform the character gets to in one way but not in the other way.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 500).
Each test case contains two lines. The first line of each test case consists of an integer n (2 β€ n β€ 3000) β the number of platforms of the game.
The second line of each test case contains n integers. The i-th integer is a_i (0 β€ a_i β€ n-i) β the integer of the i-th platform.
It is guaranteed that:
* For each test case, there is at least one way to win initially.
* The sum of n in all test cases doesn't exceed 3000.
Output
For each test case, print one integer β the minimum number of different labels that should be changed to 0 so that there remains exactly one way to win.
Example
Input
3
4
1 1 1 0
5
4 3 2 1 0
9
4 1 4 2 1 0 2 1 0
Output
0
3
2
Note
In the first case, the player can only move to the next platform until they get to the 4-th platform. Since there is already only one way to win, the answer is zero.
In the second case, Gildong can change a_2, a_3, and a_4 to 0 so that the game becomes 4 0 0 0 0. Now the only way the player can win is to move directly from the 1-st platform to the 5-th platform.
In the third case, Gildong can change a_2 and a_8 to 0, then the only way to win is to move in the following way: 1 β 3 β 7 β 9.
### Response
```cpp
#include<cstdio>
#include<iostream>
#include<queue>
#include<cmath>
#include<cstring>
#include<algorithm>
#define ll long long
#define go(i,x,a) for(int i=a;i<x;i++)
#define inf 0x3f3f3f3f
#define INF 0x7fffffff
#define lowbit(x) (x&(-x))
using namespace std;
const int maxn=3e3+5;
int n,m,p[maxn],f[maxn][maxn],t[maxn];
inline int rd(){
int ret=0,af=1; char gc=getchar();
while(gc < '0' || gc > '9'){ if(gc == '-') af=-af; gc=getchar(); }
while(gc >= '0' && gc <= '9') ret=ret*10+gc-'0',gc=getchar();
return ret*af;
}
inline void gmax(int &a,int b){
if(a < b) a=b; return ;
}
inline void gmin(int &a,int b){
if(a > b) a=b; return ;
}
inline void add(int x){
for(int i=x;i<=n;i+=lowbit(i)) t[i]++;
return ;
}
inline int query(int x){
int ss=0;
for(int i=x;i>0;i-=lowbit(i)) ss+=t[i];
return ss;
}
int main(){
int T=rd();
while(T--){
n=rd(); int ans=0,ss=0;
go(i,n+5,1) go(j,n+5,1) f[i][j]=0;
go(i,n+1,1){
p[i]=rd(); ss+=p[i] > 0;
if(i != n) gmin(p[i],n-i);
}
//if(p[n] == 0) p[n]=1,ss++;
go(i,n+1,1) t[i]=0;
f[n][n+1]=1;
for(int i=n-1;i>=1;i--)
if(p[i]){
int ls=i+p[i];
go(j,ls+1,i+1)
if(f[j][ls+1]) gmax(f[i][j],f[j][ls+1]+1+query(j-1));
for(int j=n;j>=i+1;j--) gmax(f[i][j],f[i][j+1]);
add(ls);
}
go(i,n+1,2) gmax(ans,f[1][i]);
printf("%d\n",ss-ans+1);
}
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Jamie is preparing a Codeforces round. He has got an idea for a problem, but does not know how to solve it. Help him write a solution to the following problem:
Find k integers such that the sum of two to the power of each number equals to the number n and the largest integer in the answer is as small as possible. As there may be multiple answers, you are asked to output the lexicographically largest one.
To be more clear, consider all integer sequence with length k (a1, a2, ..., ak) with <image>. Give a value <image> to each sequence. Among all sequence(s) that have the minimum y value, output the one that is the lexicographically largest.
For definitions of powers and lexicographical order see notes.
Input
The first line consists of two integers n and k (1 β€ n β€ 1018, 1 β€ k β€ 105) β the required sum and the length of the sequence.
Output
Output "No" (without quotes) in a single line if there does not exist such sequence. Otherwise, output "Yes" (without quotes) in the first line, and k numbers separated by space in the second line β the required sequence.
It is guaranteed that the integers in the answer sequence fit the range [ - 1018, 1018].
Examples
Input
23 5
Output
Yes
3 3 2 1 0
Input
13 2
Output
No
Input
1 2
Output
Yes
-1 -1
Note
Sample 1:
23 + 23 + 22 + 21 + 20 = 8 + 8 + 4 + 2 + 1 = 23
Answers like (3, 3, 2, 0, 1) or (0, 1, 2, 3, 3) are not lexicographically largest.
Answers like (4, 1, 1, 1, 0) do not have the minimum y value.
Sample 2:
It can be shown there does not exist a sequence with length 2.
Sample 3:
<image>
Powers of 2:
If x > 0, then 2x = 2Β·2Β·2Β·...Β·2 (x times).
If x = 0, then 2x = 1.
If x < 0, then <image>.
Lexicographical order:
Given two different sequences of the same length, (a1, a2, ... , ak) and (b1, b2, ... , bk), the first one is smaller than the second one for the lexicographical order, if and only if ai < bi, for the first i where ai and bi differ.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
srand(time(NULL));
;
long long n, k;
cin >> n >> k;
multiset<long long> s;
long long c = 0;
long long check = 0;
map<long long, long long> freq;
while (n) {
if (n % 2 == 1) {
freq[check]++;
c++;
}
check++;
n /= 2;
}
if (c > k) {
cout << "NO" << endl;
return 0;
}
for (long long i = 66; i >= -66; i--) {
if (c + freq[i] <= k) {
c += freq[i];
freq[i - 1] += 2 * freq[i];
freq[i] = 0;
} else {
break;
}
}
for (long long i = 65; i >= -65; i--) {
for (long long j = 0; j < freq[i]; j++) {
s.insert(i);
}
}
while (s.size() != k) {
auto itr = s.begin();
long long x = *itr;
s.erase(itr);
s.insert(x - 1);
s.insert(x - 1);
}
cout << "Yes" << endl;
for (auto itr = s.rbegin(); itr != s.rend(); itr++) cout << *itr << " ";
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Peter had a cube with non-zero length of a side. He put the cube into three-dimensional space in such a way that its vertices lay at integer points (it is possible that the cube's sides are not parallel to the coordinate axes). Then he took a piece of paper and wrote down eight lines, each containing three integers β coordinates of cube's vertex (a single line contains coordinates of a single vertex, each vertex is written exactly once), put the paper on the table and left. While Peter was away, his little brother Nick decided to play with the numbers on the paper. In one operation Nick could swap some numbers inside a single line (Nick didn't swap numbers from distinct lines). Nick could have performed any number of such operations.
When Peter returned and found out about Nick's mischief, he started recollecting the original coordinates. Help Peter restore the original position of the points or else state that this is impossible and the numbers were initially recorded incorrectly.
Input
Each of the eight lines contains three space-separated integers β the numbers written on the piece of paper after Nick's mischief. All numbers do not exceed 106 in their absolute value.
Output
If there is a way to restore the cube, then print in the first line "YES". In each of the next eight lines print three integers β the restored coordinates of the points. The numbers in the i-th output line must be a permutation of the numbers in i-th input line. The numbers should represent the vertices of a cube with non-zero length of a side. If there are multiple possible ways, print any of them.
If there is no valid way, print "NO" (without the quotes) in the first line. Do not print anything else.
Examples
Input
0 0 0
0 0 1
0 0 1
0 0 1
0 1 1
0 1 1
0 1 1
1 1 1
Output
YES
0 0 0
0 0 1
0 1 0
1 0 0
0 1 1
1 0 1
1 1 0
1 1 1
Input
0 0 0
0 0 0
0 0 0
0 0 0
1 1 1
1 1 1
1 1 1
1 1 1
Output
NO
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using namespace std;
const int n = 8;
int a[n][3];
void yes() {
cout << "YES\n";
for (int i = 0; i < n; i++, cout << '\n')
for (int j = 0; j < 3; j++) cout << a[i][j] << " ";
exit(0);
}
long long get(int i, int j) {
long long ret = 0;
for (int k = 0; k < 3; k++) {
ret += (a[i][k] - a[j][k]) * 1LL * (a[i][k] - a[j][k]);
}
return ret;
}
bool check() {
long long s = LLONG_MAX;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) s = min(s, get(i, j));
static vector<int> goal = {3, 3, 1};
for (int i = 0; i < n; i++) {
vector<int> cnt(3);
for (int j = 0; j < n; j++) {
if (j == i) continue;
if (get(i, j) == s)
cnt[0]++;
else if (get(i, j) == s + s)
cnt[1]++;
else
cnt[2]++;
}
if (cnt != goal) return 0;
}
return 1;
}
void find(int i) {
if (i == n) {
if (check()) yes();
return;
}
sort(a[i], a[i] + 3);
do {
find(i + 1);
} while (next_permutation(a[i], a[i] + 3));
}
int main() {
for (int i = 0; i < n; i++)
for (int j = 0; j < 3; j++) cin >> a[i][j];
find(0);
puts("NO\n");
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
You are given a positive integer D. Let's build the following graph from it:
* each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included);
* two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime;
* the weight of an edge is the number of divisors of x that are not divisors of y.
For example, here is the graph for D=12:
<image>
Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 β [3,6,12].
There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because 12/3=4 is not a prime.
Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0.
So the shortest path between two vertices v and u is the path that has the minimal possible length.
Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges.
You are given q queries of the following form:
* v u β calculate the number of the shortest paths between vertices v and u.
The answer for each query might be large so print it modulo 998244353.
Input
The first line contains a single integer D (1 β€ D β€ 10^{15}) β the number the graph is built from.
The second line contains a single integer q (1 β€ q β€ 3 β
10^5) β the number of queries.
Each of the next q lines contains two integers v and u (1 β€ v, u β€ D). It is guaranteed that D is divisible by both v and u (both v and u are divisors of D).
Output
Print q integers β for each query output the number of the shortest paths between the two given vertices modulo 998244353.
Examples
Input
12
3
4 4
12 1
3 4
Output
1
3
1
Input
1
1
1 1
Output
1
Input
288807105787200
4
46 482955026400
12556830686400 897
414 12556830686400
4443186242880 325
Output
547558588
277147129
457421435
702277623
Note
In the first example:
* The first query is only the empty path β length 0;
* The second query are paths [(12, 4), (4, 2), (2, 1)] (length 3+1+1=5), [(12, 6), (6, 2), (2, 1)] (length 2+2+1=5) and [(12, 6), (6, 3), (3, 1)] (length 2+2+1=5).
* The third query is only the path [(3, 1), (1, 2), (2, 4)] (length 1+1+1=3).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long inf = 1e15;
const long long MOD = 998244353;
struct th {
vector<int> arr;
list<pair<int, char>> dist;
};
map<long long, long long> fake;
map<long long, long long> mp;
vector<pair<long long, long long>> dv;
long long gcd(int a, int b) { return b ? gcd(b, a % b) : a; }
void rec(int ind, long long prev, long long mn) {
if (ind >= dv.size()) return;
for (int i = 0; i < (int)dv[ind].second; ++i) {
if (i) mp[prev] = mn;
rec(ind + 1, prev, mn);
prev *= dv[ind].first;
}
mp[prev] = mn;
rec(ind + 1, prev, mn);
}
void firstRec(int ind) {
long long cur = dv[ind].first;
mp[cur] = 1;
for (int i = 0; i < dv[ind].second; ++i) {
rec(ind + 1, cur, dv[ind].first);
cur *= dv[ind].first;
mp[cur] = dv[ind].first;
}
}
long long binpow(long long a, long long p) {
long long ans = 1;
while (p != 0) {
if (p % 2 == 1) {
ans *= a;
ans %= MOD;
}
a *= a;
a %= MOD;
p /= 2;
}
return ans;
}
long long get(long long u, long long v) {
if (u < v) swap(u, v);
if (u % v != 0) {
auto gc = gcd(u, v);
long long ans = get(u, gc);
ans *= get(v, gc);
ans %= MOD;
return ans;
}
u /= v;
map<long long, long long> div;
long long cnt = 0;
while (u != 1) {
if (mp[u] == 1) {
++div[u];
u = 1;
} else {
++div[mp[u]];
u /= mp[u];
}
++cnt;
}
long long ans = 1;
for (long long i = 2; i <= cnt; ++i) {
ans *= i;
ans %= MOD;
}
for (auto &i : div) {
long long fact = 1;
for (long long j = 2; j <= i.second; ++j) {
fact *= j;
fact %= MOD;
}
ans *= binpow(fact, MOD - 2);
ans %= MOD;
}
return ans;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cout << setprecision(30);
long long d, q;
cin >> d >> q;
long long cur = 2;
long long temp = d;
while (cur * cur <= temp) {
while (temp % cur == 0) {
temp /= cur;
if (dv.empty() || dv.back().first != cur)
dv.emplace_back(cur, 1);
else
++dv.back().second;
}
++cur;
}
if (temp != 1) dv.emplace_back(temp, 1);
mp[1] = 1;
cur = 1;
for (int i = 0; i < dv.size(); ++i) {
firstRec(i);
}
while (q--) {
long long u, v;
cin >> u >> v;
cout << get(u, v) << '\n';
}
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
problem
AOR Ika-chan, who loves feasts, defined "the number of feasts". A feast number is a natural number that includes "$ 51-3 $" in $ 10 $ decimal notation.
$? $ Can be any number from $ 0 $ to $ 9 $.
Find the number of feasts out of the natural numbers below $ N $.
input
$ N $
output
Output the number of feasts in one line. Also, output a line break at the end.
Example
Input
5124
Output
3
### Response
```cpp
#include <bits/stdc++.h>
#define int long long
using namespace std;
#define rep(i, n) for (int i = 0; i < n; ++i)
string s;
int len;
enum Ord {
Le, Eq, Gt,
};
int dp[20][2][2][10000];
bool is_gochiusa(int x) {
if (x / 1000 % 10 != 5) return false;
if (x / 100 % 10 != 1) return false;
if (x / 1 % 10 != 3) return false;
return true;
}
int rec(int k, Ord ord, bool done, int tail) {
int &ans = dp[k][ord][done][tail];
if (ans != -1) return ans;
ans = 0;
if (k == len) {
ans = done ? 1 : 0;
} else {
int d = s[k] - '0';
rep(nd, 10) {
Ord nord;
if (ord == Le || ord == Gt) {
nord = ord;
} else {
nord = nd < d ? Le : nd == d ? Eq : Gt;
}
if (nord == Gt) continue;
int ntail = (tail * 10 + nd) % 10000;
bool ndone = done || is_gochiusa(ntail);
ans += rec(k + 1, nord, ndone, ntail);
}
}
return ans;
}
signed main() {
cin >> s;
len = s.size();
memset(dp, -1, sizeof dp);
cout << rec(0, Eq, false, 0) << endl;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to answer the questions like that: if the questionβs last letter is a vowel, they answer "Yes" and if the last letter is a consonant, they answer "No". Of course, the sleuth knows nothing about it and his task is to understand that.
Unfortunately, Vasya is not very smart. After 5 hours of endless stupid questions everybody except Vasya got bored. Thatβs why Vasyaβs friends ask you to write a program that would give answers instead of them.
The English alphabet vowels are: A, E, I, O, U, Y
The English alphabet consonants are: B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, Z
Input
The single line contains a question represented by a non-empty line consisting of large and small Latin letters, spaces and a question mark. The line length does not exceed 100. It is guaranteed that the question mark occurs exactly once in the line β as the last symbol and that the line contains at least one letter.
Output
Print answer for the question in a single line: YES if the answer is "Yes", NO if the answer is "No".
Remember that in the reply to the question the last letter, not the last character counts. I. e. the spaces and the question mark do not count as letters.
Examples
Input
Is it a melon?
Output
NO
Input
Is it an apple?
Output
YES
Input
Is it a banana ?
Output
YES
Input
Is it an apple and a banana simultaneouSLY?
Output
YES
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string thing;
getline(cin, thing);
int iter = thing.length() - 1;
while (thing[iter] == '?' || thing[iter] == ' ') {
iter--;
}
char inv = thing[iter];
if (inv == 'a' || inv == 'A' || inv == 'i' || inv == 'I' || inv == 'u' ||
inv == 'U' || inv == 'e' || inv == 'E' || inv == 'o' || inv == 'O' ||
inv == 'y' || inv == 'Y') {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Quick sort is based on the Divide-and-conquer approach. In QuickSort(A, p, r), first, a procedure Partition(A, p, r) divides an array A[p..r] into two subarrays A[p..q-1] and A[q+1..r] such that each element of A[p..q-1] is less than or equal to A[q], which is, inturn, less than or equal to each element of A[q+1..r]. It also computes the index q.
In the conquer processes, the two subarrays A[p..q-1] and A[q+1..r] are sorted by recursive calls of QuickSort(A, p, q-1) and QuickSort(A, q+1, r).
Your task is to read a sequence A and perform the Partition based on the following pseudocode:
Partition(A, p, r)
1 x = A[r]
2 i = p-1
3 for j = p to r-1
4 do if A[j] <= x
5 then i = i+1
6 exchange A[i] and A[j]
7 exchange A[i+1] and A[r]
8 return i+1
Note that, in this algorithm, Partition always selects an element A[r] as a pivot element around which to partition the array A[p..r].
Constraints
* 1 β€ n β€ 100,000
* 0 β€ Ai β€ 100,000
Input
The first line of the input includes an integer n, the number of elements in the sequence A.
In the second line, Ai (i = 1,2,...,n), elements of the sequence are given separated by space characters.
Output
Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character. The element which is selected as the pivot of the partition should be indicated by [ ].
Example
Input
12
13 19 9 5 12 8 7 4 21 2 6 11
Output
9 5 8 7 4 2 6 [11] 21 13 19 12
### Response
```cpp
#include<iostream>
using namespace std;
int main()
{
int n;
int A[100000];
cin>>n;
for(int i=0;i<n;i++) cin>>A[i];
int r=n-1;
int i=0;
int j=0;
for(i=0;i<n-1;i++){
if(A[i]<=A[r]){
swap(A[i],A[j++]);
}
}
if(A[j]>A[r]) swap(A[j],A[r]);
for(i=0;i<n;i++){
if(i) cout<<" ";
if(j==i){
cout<<"["<<A[i]<<"]";
}else{
cout<<A[i];
}
}
cout<<endl;
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
"Pizza At", a fast food chain, offers three kinds of pizza: "A-pizza", "B-pizza" and "AB-pizza". A-pizza and B-pizza are completely different pizzas, and AB-pizza is one half of A-pizza and one half of B-pizza combined together. The prices of one A-pizza, B-pizza and AB-pizza are A yen, B yen and C yen (yen is the currency of Japan), respectively.
Nakahashi needs to prepare X A-pizzas and Y B-pizzas for a party tonight. He can only obtain these pizzas by directly buying A-pizzas and B-pizzas, or buying two AB-pizzas and then rearrange them into one A-pizza and one B-pizza. At least how much money does he need for this? It is fine to have more pizzas than necessary by rearranging pizzas.
Constraints
* 1 β€ A, B, C β€ 5000
* 1 β€ X, Y β€ 10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B C X Y
Output
Print the minimum amount of money required to prepare X A-pizzas and Y B-pizzas.
Examples
Input
1500 2000 1600 3 2
Output
7900
Input
1500 2000 1900 3 2
Output
8500
Input
1500 2000 500 90000 100000
Output
100000000
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int a,b,c,x,y;
cin>>a>>b>>c>>x>>y;
cout<<min({a*x+b*y,c*max(x,y)*2,c*x*2+max(0,(y-x)*b),c*y*2+max(0,(x-y)*a)})<<endl;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
For each positive integer n consider the integer Ο(n) which is obtained from n by replacing every digit a in the decimal notation of n with the digit (9 - a). We say that Ο(n) is the reflection of n. For example, reflection of 192 equals 807. Note that leading zeros (if any) should be omitted. So reflection of 9 equals 0, reflection of 91 equals 8.
Let us call the weight of the number the product of the number and its reflection. Thus, the weight of the number 10 is equal to 10Β·89 = 890.
Your task is to find the maximum weight of the numbers in the given range [l, r] (boundaries are included).
Input
Input contains two space-separated integers l and r (1 β€ l β€ r β€ 109) β bounds of the range.
Output
Output should contain single integer number: maximum value of the product nΒ·Ο(n), where l β€ n β€ r.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d).
Examples
Input
3 7
Output
20
Input
1 1
Output
8
Input
8 10
Output
890
Note
In the third sample weight of 8 equals 8Β·1 = 8, weight of 9 equals 9Β·0 = 0, weight of 10 equals 890.
Thus, maximum value of the product is equal to 890.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long cal(long long n) {
long long m = n;
long long x = 1, res = 0;
while (m) {
long long tmp = m % 10;
tmp = 9 - tmp;
res += (x * tmp);
m /= 10;
x *= 10;
}
return n * res;
}
long long magic(long long n) {
long long m = n;
long long x = 1, res = 0;
while (m > 9) {
res += (x * 9);
m /= 10;
x *= 10;
}
res += (x * 4);
return res;
}
int main() {
long long l, r;
cin >> l >> r;
long long m = magic(r);
cout << cal(min(max(l, m), r)) << endl;
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
You are given a sequence with N integers: A = \\{ A_1, A_2, \cdots, A_N \\}. For each of these N integers, we will choose a color and paint the integer with that color. Here the following condition must be satisfied:
* If A_i and A_j (i < j) are painted with the same color, A_i < A_j.
Find the minimum number of colors required to satisfy the condition.
Constraints
* 1 \leq N \leq 10^5
* 0 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1
:
A_N
Output
Print the minimum number of colors required to satisfy the condition.
Examples
Input
5
2
1
4
5
3
Output
2
Input
4
0
0
0
0
Output
4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
int t;
multiset<int> ms;
cin >> t;
ms.insert(t);
for (int i = 1; i < n; ++i) {
cin >> t;
if (*ms.begin() >= t) ms.insert(t);
else {
auto it = ms.lower_bound(t);
it--;
ms.erase(it);
ms.insert(t);
}
}
cout << ms.size() << '\n';
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Let p (i) be the i-th prime number from the smallest. For example, 7 is the fourth prime number from the smallest, 2, 3, 5, 7, so p (4) = 7.
Given n, the sum of p (i) from i = 1 to n s
s = p (1) + p (2) + .... + p (n)
Create a program that outputs. For example, when n = 9, s = 2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23 = 100.
Input
Given multiple datasets. Each dataset is given the integer n (n β€ 10000). When n is 0, it is the last input. The number of datasets does not exceed 50.
Output
For n in each dataset, print s on one line.
Example
Input
2
9
0
Output
5
100
### Response
```cpp
#include<iostream>
int p[1<<17],n,s,i;
int main(){p[1]=1;for(i=2;i*i<1<<17;i++)if(!p[i])for(s=2;i*s<1<<17;s++)p[i*s]++;for(;std::cin>>n,n;){for(i=2,s=0;n;i++)if(!p[i])s+=i,n--;std::cout<<s<<"\n";}}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!
Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour si, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c β Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.
For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.
But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer mi and a lowercase letter ci, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan.
Input
The first line of input contains a positive integer n (1 β€ n β€ 1 500) β the length of the garland.
The second line contains n lowercase English letters s1s2... sn as a string β the initial colours of paper pieces on the garland.
The third line contains a positive integer q (1 β€ q β€ 200 000) β the number of plans Nadeko has.
The next q lines describe one plan each: the i-th among them contains an integer mi (1 β€ mi β€ n) β the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter ci β Koyomi's possible favourite colour.
Output
Output q lines: for each work plan, output one line containing an integer β the largest Koyomity achievable after repainting the garland according to it.
Examples
Input
6
koyomi
3
1 o
4 o
4 m
Output
3
6
5
Input
15
yamatonadeshiko
10
1 a
2 a
3 a
4 a
5 a
1 b
2 b
3 b
4 b
5 b
Output
3
4
5
7
8
1
2
3
4
5
Input
10
aaaaaaaaaa
2
10 b
10 z
Output
10
10
Note
In the first sample, there are three plans:
* In the first plan, at most 1 piece can be repainted. Repainting the "y" piece to become "o" results in "kooomi", whose Koyomity of 3 is the best achievable;
* In the second plan, at most 4 pieces can be repainted, and "oooooo" results in a Koyomity of 6;
* In the third plan, at most 4 pieces can be repainted, and "mmmmmi" and "kmmmmm" both result in a Koyomity of 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 3e5 + 10;
const int maxm = 4e5 + 10;
const int maxb = 26;
const int sigma_size = 62;
const double eps = 1e-8;
const long long mod = 1e9 + 7;
const double pi = acos(-1.0);
const int Ha = 2333;
const long long Linf = 3e12 + 10;
const int inf = 1e9 + 7;
const double Dinf = 1000000007.0;
char s[1510];
int main() {
int n, Q;
while (~scanf("%d%s%d", &n, s, &Q)) {
while (Q--) {
int m;
char op[2];
scanf("%d%s", &m, op);
char c = op[0];
int ans = 0, cnt = m;
int l = 0, r = 0;
while (r < n) {
if (s[r] != c) cnt--;
r++;
if (cnt < 0) {
ans = max(ans, r - l - 1);
while (s[l] == c) l++;
l++;
cnt++;
}
}
ans = max(ans, r - l);
printf("%d\n", ans);
}
}
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
The Little Elephant loves sortings.
He has an array a consisting of n integers. Let's number the array elements from 1 to n, then the i-th element will be denoted as ai. The Little Elephant can make one move to choose an arbitrary pair of integers l and r (1 β€ l β€ r β€ n) and increase ai by 1 for all i such that l β€ i β€ r.
Help the Little Elephant find the minimum number of moves he needs to convert array a to an arbitrary array sorted in the non-decreasing order. Array a, consisting of n elements, is sorted in the non-decreasing order if for any i (1 β€ i < n) ai β€ ai + 1 holds.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the size of array a. The next line contains n integers, separated by single spaces β array a (1 β€ ai β€ 109). The array elements are listed in the line in the order of their index's increasing.
Output
In a single line print a single integer β the answer to the problem.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2 3
Output
0
Input
3
3 2 1
Output
2
Input
4
7 4 1 47
Output
6
Note
In the first sample the array is already sorted in the non-decreasing order, so the answer is 0.
In the second sample you need to perform two operations: first increase numbers from second to third (after that the array will be: [3, 3, 2]), and second increase only the last element (the array will be: [3, 3, 3]).
In the third sample you should make at least 6 steps. The possible sequence of the operations is: (2; 3), (2; 3), (2; 3), (3; 3), (3; 3), (3; 3). After that the array converts to [7, 7, 7, 47].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
const int inf = 0x3f3f3f3f;
const long long llinf = 0x3f3f3f3f3f3f3f3f;
const long long mod = 1000000007;
int vis[maxn];
long long b[maxn];
struct node {
long long a;
int id;
} a[maxn];
bool cmp(node a, node b) { return a.a < b.a; }
int main() {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) vis[i] = 0;
long long maxx = 0;
int index = 0;
for (int i = 1; i <= n; i++) {
scanf("%I64d", &a[i].a);
b[i] = a[i].a;
if (maxx <= a[i].a || a[i].a > a[i - 1].a) {
maxx = a[i].a;
index = i;
}
a[i].id = index;
}
sort(a + 1, a + 1 + n, cmp);
long long ans = 0;
for (int i = 1; i <= n; i++) {
int tem = a[i].id;
if (a[i].a < b[tem] && vis[tem] == 0) {
vis[tem] = 1;
ans += b[tem] - a[i].a;
}
}
printf("%I64d\n", ans);
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
There are n cities on a two dimensional Cartesian plane. The distance between two cities is equal to the Manhattan distance between them (see the Notes for definition). A Hamiltonian cycle of the cities is defined as a permutation of all n cities. The length of this Hamiltonian cycle is defined as the sum of the distances between adjacent cities in the permutation plus the distance between the first and final city in the permutation. Please compute the longest possible length of a Hamiltonian cycle of the given cities.
Input
The first line contains an integer n (3 β€ n β€ 105). Then n lines follow, each consisting of two integers xi and yi (0 β€ xi, yi β€ 109), denoting the coordinates of a city. All given points will be distinct.
Output
A single line denoting the longest possible length of a Hamiltonian cycle of the given cities. You should not output the cycle, only its length.
Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
4
1 1
1 2
2 1
2 2
Output
6
Note
In the example, one of the possible Hamiltonian cycles with length 6 is (1, 1) (1, 2) (2, 1) (2, 2). There does not exist any other Hamiltonian cycle with a length greater than 6.
The Manhattan distance between two cities (xi, yi) and (xj, yj) is |xi - xj| + |yi - yj|.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
class point {
public:
int x, y;
} p[100010], q[100010];
int cmp1(const point &A, const point &B) {
return A.x < B.x || (A.x == B.x && A.y < B.y);
}
int cmp2(const point &A, const point &B) {
return A.y < B.y || (A.y == B.y && A.x < B.x);
}
int n, col[100010];
long long solve() {
copy(p, p + n, q);
sort(q, q + n, cmp2);
long long ret = 0;
for (int i = 1; i < n; i++)
ret += 2ll * min(i, n - i) * (q[i].y - q[i - 1].y);
int mid = n >> 1;
if (n & 1) {
for (int i = 0; i < n; i++) {
if (q[i].x < p[mid].x)
col[i] = 0;
else if (q[i].x > p[mid].x)
col[i] = 1;
else
col[i] = -1;
}
int it;
int cur = -1;
for (it = 0; it < mid; it++) {
if (col[it] != -1) {
if (cur != -1 && cur != col[it]) break;
cur = col[it];
}
}
if (it < mid) goto cont;
++it;
for (; it < n; it++) {
if (col[it] != -1) {
if (cur != -1 && col[it] == cur) break;
cur = !col[it];
}
}
cont:
if (!(it == n || col[mid] != -1))
ret += 2ll * max(q[mid - 1].y - q[mid].y, q[mid].y - q[mid + 1].y);
return ret;
} else {
for (int i = 0; i < n; i++) {
if (q[i].x < p[mid].x)
col[i] = 0;
else if (q[i].x > p[mid - 1].x)
col[i] = 1;
else
col[i] = -1;
}
int cur = -1, it;
for (it = 0; it < mid; it++) {
if (col[it] != -1) {
if (cur != -1 && cur != col[it]) break;
cur = col[it];
}
}
if (it < mid) goto cont2;
for (; it < n; it++) {
if (col[it] != -1) {
if (cur != -1 && cur == col[it]) break;
cur = !col[it];
}
}
cont2:
if (it != n) ret += 2ll * (q[mid - 1].y - q[mid].y);
return ret;
}
}
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d%d", &p[i].x, &p[i].y);
sort(p, p + n, cmp1);
long long ans = 0;
long long cur = 0;
for (int i = 1; i < n; i++)
cur += 2ll * min(i, n - i) * (p[i].x - p[i - 1].x);
ans = cur + solve();
for (int i = 0; i < n; i++) swap(p[i].x, p[i].y);
sort(p, p + n, cmp1);
cur = 0;
for (int i = 1; i < n; i++)
cur += 2ll * min(i, n - i) * (p[i].x - p[i - 1].x);
ans = max(ans, cur + solve());
printf("%lld\n", ans);
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Molly Hooper has n different kinds of chemicals arranged in a line. Each of the chemicals has an affection value, The i-th of them has affection value ai.
Molly wants Sherlock to fall in love with her. She intends to do this by mixing a contiguous segment of chemicals together to make a love potion with total affection value as a non-negative integer power of k. Total affection value of a continuous segment of chemicals is the sum of affection values of each chemical in that segment.
Help her to do so in finding the total number of such segments.
Input
The first line of input contains two integers, n and k, the number of chemicals and the number, such that the total affection value is a non-negative power of this number k. (1 β€ n β€ 105, 1 β€ |k| β€ 10).
Next line contains n integers a1, a2, ..., an ( - 109 β€ ai β€ 109) β affection values of chemicals.
Output
Output a single integer β the number of valid segments.
Examples
Input
4 2
2 2 2 2
Output
8
Input
4 -3
3 -6 -3 12
Output
3
Note
Do keep in mind that k0 = 1.
In the first sample, Molly can get following different affection values:
* 2: segments [1, 1], [2, 2], [3, 3], [4, 4];
* 4: segments [1, 2], [2, 3], [3, 4];
* 6: segments [1, 3], [2, 4];
* 8: segments [1, 4].
Out of these, 2, 4 and 8 are powers of k = 2. Therefore, the answer is 8.
In the second sample, Molly can choose segments [1, 2], [3, 3], [3, 4].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100005;
using ll = long long;
ll a[maxn], pref[maxn];
int n;
ll get(ll k) {
ll ret = 0;
map<ll, int> mp;
mp[0] = 1;
for (int i = 1; i <= n; ++i) {
ret += mp[pref[i] - k];
mp[pref[i]]++;
}
return ret;
}
int main(int argc, char const *argv[]) {
ll k;
scanf("%d %lld", &n, &k);
int pos = 0, neg = 0;
for (int i = 1; i <= n; ++i) {
scanf("%lld", &a[i]);
if (a[i] >= 1) {
pos = 1;
}
if (a[i] <= -1) {
neg = 1;
}
pref[i] = pref[i - 1] + a[i];
}
if (llabs(k) == 1) {
ll ans = 0;
if (k == 1) {
cout << get(1) << endl;
} else {
ans += get(1);
ans += get(-1);
cout << ans << endl;
}
} else {
ll ans = get(1);
ll kk = k;
while (llabs(kk) <= 100000000000000LL) {
ans += get(kk);
kk *= k;
}
cout << ans << endl;
}
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Takahashi has a water bottle with the shape of a rectangular prism whose base is a square of side a~\mathrm{cm} and whose height is b~\mathrm{cm}. (The thickness of the bottle can be ignored.)
We will pour x~\mathrm{cm}^3 of water into the bottle, and gradually tilt the bottle around one of the sides of the base.
When will the water be spilled? More formally, find the maximum angle in which we can tilt the bottle without spilling any water.
Constraints
* All values in input are integers.
* 1 \leq a \leq 100
* 1 \leq b \leq 100
* 1 \leq x \leq a^2b
Input
Input is given from Standard Input in the following format:
a b x
Output
Print the maximum angle in which we can tilt the bottle without spilling any water, in degrees. Your output will be judged as correct when the absolute or relative error from the judge's output is at most 10^{-6}.
Examples
Input
2 2 4
Output
45.0000000000
Input
12 21 10
Output
89.7834636934
Input
3 1 8
Output
4.2363947991
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
int main(){
double a,b,x,i;
double theta;
cin>>a>>b>>x;
if(a*a*b/2>=x){
i = a-2*x/(a*b);
theta = atan(b/(a-i));
}
else{
i = 2*b-2*x/(a*a);
theta = atan(i/a);
}
cout<<std::setprecision(11)<<theta/M_PI*180<<endl;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
The Berland Forest can be represented as an infinite cell plane. Every cell contains a tree. That is, contained before the recent events.
A destructive fire raged through the Forest, and several trees were damaged by it. Precisely speaking, you have a n Γ m rectangle map which represents the damaged part of the Forest. The damaged trees were marked as "X" while the remaining ones were marked as ".". You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged.
The firemen quickly extinguished the fire, and now they are investigating the cause of it. The main version is that there was an arson: at some moment of time (let's consider it as 0) some trees were set on fire. At the beginning of minute 0, only the trees that were set on fire initially were burning. At the end of each minute, the fire spread from every burning tree to each of 8 neighboring trees. At the beginning of minute T, the fire was extinguished.
The firemen want to find the arsonists as quickly as possible. The problem is, they know neither the value of T (how long the fire has been raging) nor the coordinates of the trees that were initially set on fire. They want you to find the maximum value of T (to know how far could the arsonists escape) and a possible set of trees that could be initially set on fire.
Note that you'd like to maximize value T but the set of trees can be arbitrary.
Input
The first line contains two integer n and m (1 β€ n, m β€ 10^6, 1 β€ n β
m β€ 10^6) β the sizes of the map.
Next n lines contain the map. The i-th line corresponds to the i-th row of the map and contains m-character string. The j-th character of the i-th string is "X" if the corresponding tree is burnt and "." otherwise.
It's guaranteed that the map contains at least one "X".
Output
In the first line print the single integer T β the maximum time the Forest was on fire. In the next n lines print the certificate: the map (n Γ m rectangle) where the trees that were set on fire are marked as "X" and all other trees are marked as ".".
Examples
Input
3 6
XXXXXX
XXXXXX
XXXXXX
Output
1
......
.X.XX.
......
Input
10 10
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
..........
Output
2
..........
..........
...XX.....
..........
..........
..........
.....XX...
..........
..........
..........
Input
4 5
X....
..XXX
..XXX
..XXX
Output
0
X....
..XXX
..XXX
..XXX
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int m, n;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> m >> n;
vector<vector<int>> a(m + 5, vector<int>(n + 5)),
s(m + 5, vector<int>(n + 5)), atam(m + 5, vector<int>(n + 5));
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++) {
char x;
cin >> x;
if (x == 'X')
a[i][j] = 0;
else
a[i][j] = 1;
}
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + a[i][j];
int mn = 1e9;
int left = 0, right = min(n, m) / 2;
while (left <= right) {
int mid = (left + right) >> 1;
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++) atam[i][j] = 0;
queue<pair<int, int>> qu;
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++) {
bool ok = 1;
int u = i - mid, d = i + mid, l = j - mid, r = j + mid;
if (u < 1 || d > m || l < 1 || r > n)
ok = 0;
else if (s[d][r] + s[u - 1][l - 1] - s[d][l - 1] - s[u - 1][r])
ok = 0;
if (ok) qu.push(make_pair(i, j)), atam[i][j] = 1;
}
while (!qu.empty()) {
pair<int, int> res = qu.front();
qu.pop();
for (int i = -1; i <= 1; i++)
for (int j = -1; j <= 1; j++) {
if (res == make_pair(res.first + i, res.second + j)) continue;
int x = res.first + i, y = res.second + j;
if (x < 1 || x > m || y < 1 || y > n || atam[x][y]) continue;
if (atam[res.first][res.second] > mid) continue;
atam[x][y] = atam[res.first][res.second] + 1;
qu.push(make_pair(x, y));
}
}
bool ok = 1;
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
if ((!a[i][j]) ^ bool(atam[i][j])) ok = 0;
if (ok)
left = mid + 1;
else
right = mid - 1;
}
cout << right << "\n";
for (int i = 1; i <= m; i++, cout << "\n")
for (int j = 1; j <= n; j++) {
bool ok = 1;
int u = i - right, d = i + right, l = j - right, r = j + right;
if (u < 1 || d > m || l < 1 || r > n)
ok = 0;
else if (s[d][r] + s[u - 1][l - 1] - s[d][l - 1] - s[u - 1][r])
ok = 0;
if (ok)
cout << 'X';
else
cout << '.';
}
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Once, during a lesson, Sasha got bored and decided to talk with his friends. Suddenly, he saw Kefa. Since we can talk endlessly about Kefa, we won't even start doing that. The conversation turned to graphs. Kefa promised Sasha to tell him about one interesting fact from graph theory if Sasha helps Kefa to count the number of beautiful trees.
In this task, a tree is a weighted connected graph, consisting of n vertices and n-1 edges, and weights of edges are integers from 1 to m. Kefa determines the beauty of a tree as follows: he finds in the tree his two favorite vertices β vertices with numbers a and b, and counts the distance between them. The distance between two vertices x and y is the sum of weights of edges on the simple path from x to y. If the distance between two vertices a and b is equal to m, then the tree is beautiful.
Sasha likes graph theory, and even more, Sasha likes interesting facts, that's why he agreed to help Kefa. Luckily, Sasha is familiar with you the best programmer in Byteland. Help Sasha to count the number of beautiful trees for Kefa. Two trees are considered to be distinct if there is an edge that occurs in one of them and doesn't occur in the other one. Edge's weight matters.
Kefa warned Sasha, that there can be too many beautiful trees, so it will be enough to count the number modulo 10^9 + 7.
Input
The first line contains four integers n, m, a, b (2 β€ n β€ 10^6, 1 β€ m β€ 10^6, 1 β€ a, b β€ n, a β b) β the number of vertices in the tree, the maximum weight of an edge and two Kefa's favorite vertices.
Output
Print one integer β the number of beautiful trees modulo 10^9+7.
Examples
Input
3 2 1 3
Output
5
Input
3 1 1 2
Output
2
Input
5 15 1 5
Output
345444
Note
There are 5 beautiful trees in the first example:
<image>
In the second example the following trees are beautiful:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void solve();
mt19937 rnd(2007);
signed main() {
mt19937 rrnd(
std::chrono::high_resolution_clock::now().time_since_epoch().count());
swap(rrnd, rnd);
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
solve();
}
const long long mod = (long long)1e9 + 7;
const long long maxn = (long long)1e6 + 7;
long long fact0[maxn], fact_[maxn], pwn[maxn], pwm[maxn];
long long C(long long n, long long k) {
return ((fact0[n] * fact_[k]) % mod * fact_[n - k]) % mod;
}
long long binpow(long long a, long long n) {
long long res = 1;
while (n) {
if (n & 1) {
res *= a;
res %= mod;
}
a *= a;
a %= mod;
n >>= 1;
}
return res;
}
void solve() {
long long n, m;
cin >> n >> m;
fact0[0] = 1;
for (long long(i) = 0; (i) < (maxn - 1); ++(i))
fact0[i + 1] = (fact0[i] * (i + 1)) % mod;
for (long long(i) = 0; (i) < (maxn); ++(i))
fact_[i] = binpow(fact0[i], mod - 2);
pwn[0] = 1;
for (long long(i) = 0; (i) < (maxn - 1); ++(i))
pwn[i + 1] = (pwn[i] * n) % mod;
pwm[0] = 1;
for (long long(i) = 0; (i) < (maxn - 1); ++(i))
pwm[i + 1] = (pwm[i] * m) % mod;
long long ans = 0;
for (long long l = 1; l < n; ++l) {
if (l > m) break;
long long cur = 1;
long long cnt_trees;
if (n - l - 2 == -1)
cnt_trees = ((l + 1) * binpow(n, mod - 2)) % mod;
else {
cnt_trees = ((l + 1) * pwn[(n - l - 2)]) % mod;
}
cur *= C(m - 1, l - 1);
cur %= mod;
cur *= pwm[n - 1 - l];
cur %= mod;
cur *= cnt_trees;
cur %= mod;
cur *= fact0[n - 2];
cur %= mod;
cur *= fact_[n - 1 - l];
cur %= mod;
ans += cur;
ans %= mod;
}
cout << ans << '\n';
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i.
The N players will arrive at the place one by one in some order. To make sure nobody gets lost, you have set the following rule: players who have already arrived there should form a circle, and a player who has just arrived there should cut into the circle somewhere.
When each player, except the first one to arrive, arrives at the place, the player gets comfort equal to the smaller of the friendliness of the clockwise adjacent player and that of the counter-clockwise adjacent player. The first player to arrive there gets the comfort of 0.
What is the maximum total comfort the N players can get by optimally choosing the order of arrivals and the positions in the circle to cut into?
Constraints
* All values in input are integers.
* 2 \leq N \leq 2 \times 10^5
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 \dots A_N
Output
Print the maximum total comfort the N players can get.
Examples
Input
4
2 2 1 3
Output
7
Input
7
1 1 1 1 1 1 1
Output
6
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
#define rep(i,m,n) for(int i=m;i<n;i++)
ll mod=1e9+7;
int main(){
int n;
cin>>n;
int a[n];
rep(i,0,n) cin>>a[i];
sort(a,a+n);
reverse(a,a+n);
ll ans=a[0];
rep(i,2,n){
ans+=a[i/2];
}
cout<<ans<<endl;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
You play the game with your friend. The description of this game is listed below.
Your friend creates n distinct strings of the same length m and tells you all the strings. Then he randomly chooses one of them. He chooses strings equiprobably, i.e. the probability of choosing each of the n strings equals <image>. You want to guess which string was chosen by your friend.
In order to guess what string your friend has chosen, you are allowed to ask him questions. Each question has the following form: Β«What character stands on position pos in the string you have chosen?Β» A string is considered guessed when the answers to the given questions uniquely identify the string. After the string is guessed, you stop asking questions.
You do not have a particular strategy, so as each question you equiprobably ask about a position that hasn't been yet mentioned. Your task is to determine the expected number of questions needed to guess the string chosen by your friend.
Input
The first line contains a single integer n (1 β€ n β€ 50) β the number of strings your friend came up with.
The next n lines contain the strings that your friend has created. It is guaranteed that all the strings are distinct and only consist of large and small English letters. Besides, the lengths of all strings are the same and are between 1 to 20 inclusive.
Output
Print the single number β the expected value. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 9.
Examples
Input
2
aab
aac
Output
2.000000000000000
Input
3
aaA
aBa
Caa
Output
1.666666666666667
Input
3
aca
vac
wqq
Output
1.000000000000000
Note
In the first sample the strings only differ in the character in the third position. So only the following situations are possible:
* you guess the string in one question. The event's probability is <image>;
* you guess the string in two questions. The event's probability is <image> Β· <image> = <image> (as in this case the first question should ask about the position that is other than the third one);
* you guess the string in three questions. The event's probability is <image> Β· <image> Β· <image> = <image>;
Thus, the expected value is equal to <image>
In the second sample we need at most two questions as any pair of questions uniquely identifies the string. So the expected number of questions is <image>.
In the third sample whatever position we ask about in the first question, we immediately identify the string.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename T>
void get_int(T &x) {
char t = getchar();
bool neg = false;
x = 0;
for (; (t > '9' || t < '0') && t != '-'; t = getchar())
;
if (t == '-') neg = true, t = getchar();
for (; t <= '9' && t >= '0'; t = getchar()) x = x * 10 + t - '0';
if (neg) x = -x;
}
template <typename T>
void print_int(T x) {
if (x < 0) putchar('-'), x = -x;
short a[20] = {}, sz = 0;
while (x > 0) a[sz++] = x % 10, x /= 10;
if (sz == 0) putchar('0');
for (int i = sz - 1; i >= 0; i--) putchar('0' + a[i]);
}
const int inf = 0x3f3f3f3f;
const long long Linf = 1ll << 61;
const double pi = acos(-1.0);
int n, m, one[1 << 20], cnt[25], c[25][25];
char s[55][25];
long long msk[25], all[1 << 20];
double calc(int x) {
memset(cnt, 0, sizeof(cnt));
for (int i = 0; i < m; i++) {
msk[i] = 0;
for (int j = 0; j < n; j++)
if (j != x && s[j][i] == s[x][i]) msk[i] |= 1ll << j;
}
all[0] = (1ll << n) - 1;
for (int i = 0; i < (1 << m); i++) {
for (int j = 0; j < m; j++) {
if ((i >> j) & 1) {
all[i] = all[i ^ (1 << j)] & msk[j];
break;
}
}
if (all[i]) cnt[one[i]]++;
}
double ret = 0.0, sum = 0.0;
for (int i = 0; i < m; i++) {
cnt[i] = cnt[i] * (m - i) - cnt[i + 1] * (i + 1);
ret += 1.0 * (i + 1) * cnt[i] / c[m][i] / (m - i);
sum += 1.0 * cnt[i] / c[m][i] / (m - i);
}
return ret;
}
int main() {
for (int i = 0; i < 25; i++) {
c[i][0] = 1;
for (int j = 1; j <= i; j++) c[i][j] = c[i - 1][j] + c[i - 1][j - 1];
}
for (int i = 1; i < (1 << 20); i++) one[i] = (one[i >> 1] + (i & 1));
get_int(n);
if (n == 1) {
printf("0.00000000000\n");
return 0;
}
for (int i = 0; i < n; i++) scanf("%s", s[i]);
m = strlen(s[0]);
double ans = 0.0;
for (int i = 0; i < n; i++) ans += calc(i);
printf("%.10lf\n", ans / n);
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
This problem is different with hard version only by constraints on total answers length
It is an interactive problem
Venya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string s of length n, consisting only of lowercase English letters. The player can ask two types of queries:
* ? l r β ask to list all substrings of s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled.
* ! s β guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses.
The player can ask no more than 3 queries of the first type.
To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)^2.
Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.
Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.
Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.
Input
First line contains number n (1 β€ n β€ 100) β the length of the picked string.
Interaction
You start the interaction by reading the number n.
To ask a query about a substring from l to r inclusively (1 β€ l β€ r β€ n), you should output
? l r
on a separate line. After this, all substrings of s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.
In the case, if you ask an incorrect query, ask more than 3 queries of the first type or there will be more than (n+1)^2 substrings returned in total, you will receive verdict Wrong answer.
To guess the string s, you should output
! s
on a separate line.
After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.
Hack format
To hack a solution, use the following format:
The first line should contain one integer n (1 β€ n β€ 100) β the length of the string, and the following line should contain the string s.
Example
Input
4
a
aa
a
cb
b
c
c
Output
? 1 2
? 3 4
? 4 4
! aabc
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 110000;
const int M = 1100000;
const long long mod = 1e9 + 7;
int n;
string s[N], t[N];
char ans[N];
int num1, num2;
struct node {
string s;
int len;
friend bool operator<(node a, node b) { return a.len < b.len; }
} a[N];
int nn;
int nu[110];
int nu2[110];
int main() {
cin.sync_with_stdio(false);
cin >> n;
printf("? 1 %d\n", n);
fflush(stdout);
num1 = n * (n + 1) / 2;
for (int i = 1; i <= num1; i++) {
cin >> s[i];
sort(s[i].begin(), s[i].end());
}
if (n == 1) {
printf("! %c\n", s[1][0]);
fflush(stdout);
return 0;
}
num2 = n * (n - 1) / 2;
printf("? 1 %d\n", n - 1);
fflush(stdout);
for (int i = 1; i <= num2; i++) {
cin >> t[i];
sort(t[i].begin(), t[i].end());
}
sort(s + 1, s + 1 + num1);
sort(t + 1, t + 1 + num2);
int head = 1;
for (int i = 1; i <= num1; i++) {
if (s[i] == t[head])
head++;
else {
nn++;
a[nn].s = s[i], a[nn].len = s[i].size();
}
}
sort(a + 1, a + 1 + nn);
for (int i = 1; i <= nn; i++) {
memset(nu2, 0, sizeof(nu2));
for (int j = 0; j < a[i].len; j++) nu2[a[i].s[j] - 'a']++;
for (int j = 0; j < 26; j++)
if (nu2[j] > nu[j]) {
nu[j] = nu2[j];
ans[nn - i] = j + 'a';
break;
}
}
printf("! %s\n", ans);
fflush(stdout);
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Akaki, a patissier, can make N kinds of doughnut using only a certain powder called "Okashi no Moto" (literally "material of pastry", simply called Moto below) as ingredient. These doughnuts are called Doughnut 1, Doughnut 2, ..., Doughnut N. In order to make one Doughnut i (1 β€ i β€ N), she needs to consume m_i grams of Moto. She cannot make a non-integer number of doughnuts, such as 0.5 doughnuts.
The recipes of these doughnuts are developed by repeated modifications from the recipe of Doughnut 1. Specifically, the recipe of Doughnut i (2 β€ i β€ N) is a direct modification of the recipe of Doughnut p_i (1 β€ p_i < i).
Now, she has X grams of Moto. She decides to make as many doughnuts as possible for a party tonight. However, since the tastes of the guests differ, she will obey the following condition:
* Let c_i be the number of Doughnut i (1 β€ i β€ N) that she makes. For each integer i such that 2 β€ i β€ N, c_{p_i} β€ c_i β€ c_{p_i} + D must hold. Here, D is a predetermined value.
At most how many doughnuts can be made here? She does not necessarily need to consume all of her Moto.
Constraints
* 2 β€ N β€ 50
* 1 β€ X β€ 10^9
* 0 β€ D β€ 10^9
* 1 β€ m_i β€ 10^9 (1 β€ i β€ N)
* 1 β€ p_i < i (2 β€ i β€ N)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N X D
m_1
m_2 p_2
:
m_N p_N
Output
Print the maximum number of doughnuts that can be made under the condition.
Examples
Input
3 100 1
15
10 1
20 1
Output
7
Input
3 100 10
15
10 1
20 1
Output
10
Input
5 1000000000 1000000
123
159 1
111 1
135 3
147 3
Output
7496296
### Response
```cpp
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
const int N=55;
int n,m,d,sz[N],id[N],sum,q[N*N*N],ans;
long long val[N],f[N*N*N],g[N*N*N];
vector<int>E[N];
void dfs(int u){
sz[u]=1;id[u]=u;
for(int v:E[u])dfs(v),sz[u]+=sz[v],val[u]+=val[v];
sum+=sz[u];
}
bool cmp(int x,int y){
return val[x]*sz[y]<val[y]*sz[x]||val[x]*sz[y]==val[y]*sz[x]&&sz[x]>sz[y];
}
int greedy(int x){
// printf("greedy x=%d ",x);
int res=0;
for(int i=1;i<=n;++i){
int y=min(x/val[id[i]],(long long)d);
if(id[i]==1)y=x/val[id[i]];
res+=y*sz[id[i]];x-=y*val[id[i]];
}
// printf("res=%d\n",res);
return res;
}
int main(){
scanf("%d%d%d%lld",&n,&m,&d,&val[1]);
for(int i=2,x;i<=n;++i){
scanf("%lld%d",&val[i],&x);
E[x].push_back(i);
}
dfs(1);sort(id+1,id+n+1,cmp);
sum*=min(n,d);
memset(f,63,sizeof(f));f[0]=0;
for(int i=1;i<=n;++i){
for(int j=0;j<sz[i];++j)
for(int k=j,hd=1,tl=0;k<=sum;k+=sz[i]){
while(hd<=tl&&q[hd]<k-sz[i]*min(n,d))++hd;
while(hd<=tl&&f[q[tl]]-val[i]*(q[tl]/sz[i])>f[k]-val[i]*(k/sz[i]))--tl;
q[++tl]=k;g[k]=f[q[hd]]+val[i]*((k-q[hd])/sz[i]);
// printf("k=%d g[k]=%lld\n",k,g[k]);
// for(int x=hd;x<=tl;++x)
// printf("%d ",q[x]);puts("");
}
for(int j=0;j<=sum;++j)f[j]=g[j];
}
// for(int i=0;i<=sum;++i)printf("%lld ",f[i]);puts("");
d-=min(n,d);
// printf("d=%d\n",d);
for(int i=0;i<=sum;++i)if(f[i]<=m)ans=max(ans,i+greedy(m-f[i]));
printf("%d\n",ans);return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Luba is surfing the Internet. She currently has n opened tabs in her browser, indexed from 1 to n from left to right. The mouse cursor is currently located at the pos-th tab. Luba needs to use the tabs with indices from l to r (inclusive) for her studies, and she wants to close all the tabs that don't belong to this segment as fast as possible.
Each second Luba can either try moving the cursor to the left or to the right (if the cursor is currently at the tab i, then she can move it to the tab max(i - 1, a) or to the tab min(i + 1, b)) or try closing all the tabs to the left or to the right of the cursor (if the cursor is currently at the tab i, she can close all the tabs with indices from segment [a, i - 1] or from segment [i + 1, b]). In the aforementioned expressions a and b denote the minimum and maximum index of an unclosed tab, respectively. For example, if there were 7 tabs initially and tabs 1, 2 and 7 are closed, then a = 3, b = 6.
What is the minimum number of seconds Luba has to spend in order to leave only the tabs with initial indices from l to r inclusive opened?
Input
The only line of input contains four integer numbers n, pos, l, r (1 β€ n β€ 100, 1 β€ pos β€ n, 1 β€ l β€ r β€ n) β the number of the tabs, the cursor position and the segment which Luba needs to leave opened.
Output
Print one integer equal to the minimum number of seconds required to close all the tabs outside the segment [l, r].
Examples
Input
6 3 2 4
Output
5
Input
6 3 1 3
Output
1
Input
5 2 1 5
Output
0
Note
In the first test Luba can do the following operations: shift the mouse cursor to the tab 2, close all the tabs to the left of it, shift the mouse cursor to the tab 3, then to the tab 4, and then close all the tabs to the right of it.
In the second test she only needs to close all the tabs to the right of the current position of the cursor.
In the third test Luba doesn't need to do anything.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, p, l, r;
cin >> n >> p >> l >> r;
int sec = 0;
int a = 0;
int b = 0;
if (l == 1) {
if (r == n) {
cout << 0;
exit(0);
}
sec = abs(r - p);
sec++;
} else if (r == n) {
sec = abs(p - l);
sec++;
} else {
sec = r - l;
sec += 2;
sec += min(abs(p - l), abs(r - p));
}
cout << sec;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Example
Input
4 3
1000 1
2000 2
3000 3
Output
2 3 4 4
### Response
```cpp
#include<iostream>
#include<algorithm>
#include<vector>
#define REP(i, N) for(ll i = 0; i < N; ++i)
#define ALL(a) (a).begin(),(a).end()
using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
int main(void) {
int n, m;
cin>>n>>m;
vector<P> arm(m);
REP(i, m) {
cin>>arm[i].first>>arm[i].second;
--arm[i].second;
}
sort(ALL(arm));
vector<P> rng(n);
REP(i, n) {
rng[i].first = i;
rng[i].second = i;
}
REP(i, m) {
rng[arm[i].second].second = max(rng[arm[i].second].second, rng[arm[i].second + 1].second);
rng[arm[i].second + 1].first = min(rng[arm[i].second + 1].first, rng[arm[i].second].first);
}
REP(i, n) {
cout<<rng[i].second - rng[i].first + 1;
if(i != n - 1) cout<<' ';
else cout<<endl;
}
}
``` |
### Prompt
Generate a cpp solution to the following problem:
In the last mission, MDCS has successfully shipped N AI robots to Mars. Before they start exploring, system initialization is required so they are arranged in a line. Every robot can be described with three numbers: position (x_i), radius of sight (r_i) and IQ (q_i).
Since they are intelligent robots, some of them will talk if they see each other. Radius of sight is inclusive, so robot can see other all robots in range [x_i - r_i, x_i + r_i]. But they don't walk to talk with anybody, but only with robots who have similar IQ. By similar IQ we mean that their absolute difference isn't more than K.
Help us and calculate how many pairs of robots are going to talk with each other, so we can timely update their software and avoid any potential quarrel.
Input
The first line contains two integers, numbers N (1 β€ N β€ 10^5) and K (0 β€ K β€ 20).
Next N lines contain three numbers each x_i, r_i, q_i (0 β€ x_i,r_i,q_i β€ 10^9) β position, radius of sight and IQ of every robot respectively.
Output
Output contains only one number β solution to the problem.
Example
Input
3 2
3 6 1
7 3 10
10 5 8
Output
1
Note
The first robot can see the second, but not vice versa. The first robot can't even see the third. The second and the third robot can see each other and their IQs don't differ more than 2 so only one conversation will happen.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool comp(array<int, 3> a, array<int, 3> b) { return a[1] > b[1]; }
const int SZ = (1 << 30);
template <class T>
struct node {
vector<array<int, 2>> c;
vector<int> val;
int cur;
node() {
c.push_back({-1, -1});
cur = 1;
val.push_back(0);
}
void upd(int nd, int ind, T v, int L = 0, int R = SZ - 1) {
if (L == ind && R == ind) {
val[nd] += v;
return;
}
int M = (L + R) / 2;
if (ind <= M) {
if (c[nd][0] == -1) {
c[nd][0] = cur++;
c.push_back({-1, -1});
val.push_back(0);
}
upd(c[nd][0], ind, v, L, M);
} else {
if (c[nd][1] == -1) {
c[nd][1] = cur++;
c.push_back({-1, -1});
val.push_back(0);
}
upd(c[nd][1], ind, v, M + 1, R);
}
val[nd] = 0;
for (int i = 0; i < 2; ++i)
if (c[nd][i] != -1) val[nd] += val[c[nd][i]];
}
T query(int nd, int lo, int hi, int L = 0, int R = SZ - 1) {
if (hi < L || R < lo) return 0;
if (lo <= L && R <= hi) return val[nd];
int M = (L + R) / 2;
T res = 0;
if (c[nd][0] != -1) res += query(c[nd][0], lo, hi, L, M);
if (c[nd][1] != -1) res += query(c[nd][1], lo, hi, M + 1, R);
return res;
}
};
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, k;
cin >> n >> k;
vector<array<int, 3>> a(n);
for (int i = 0; i < n; ++i) {
int x, r, q;
cin >> x >> r >> q;
a[i] = {x, r, q};
}
sort((a).begin(), (a).end(), comp);
map<int, int> exist;
map<int, node<int>> segs;
long long ans = 0;
for (auto [x, r, q] : a) {
for (int i = q - k; i <= q + k; ++i) {
if (!exist[i]) continue;
ans += segs[i].query(0, max(x - r, 0), x + r);
}
if (!exist[q]) {
segs[q] = node<int>();
}
segs[q].upd(0, x, 1);
exist[q] = 1;
}
cout << ans << "\n";
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Slime has a sequence of positive integers a_1, a_2, β¦, a_n.
In one operation Orac can choose an arbitrary subsegment [l β¦ r] of this sequence and replace all values a_l, a_{l + 1}, β¦, a_r to the value of median of \\{a_l, a_{l + 1}, β¦, a_r\}.
In this problem, for the integer multiset s, the median of s is equal to the β (|s|+1)/(2)β-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5.
Slime wants Orac to make a_1 = a_2 = β¦ = a_n = k using these operations.
Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times.
Input
The first line of the input is a single integer t: the number of queries.
The first line of each query contains two integers n\ (1β€ nβ€ 100 000) and k\ (1β€ kβ€ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1β€ a_iβ€ 10^9)
The total sum of n is at most 100 000.
Output
The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase.
Example
Input
5
5 3
1 5 2 6 1
1 6
6
3 2
1 2 3
4 3
3 1 2 3
10 3
1 2 3 4 5 6 7 8 9 10
Output
no
yes
yes
no
yes
Note
In the first query, Orac can't turn all elements into 3.
In the second query, a_1=6 is already satisfied.
In the third query, Orac can select the complete array and turn all elements into 2.
In the fourth query, Orac can't turn all elements into 3.
In the fifth query, Orac can select [1,6] at first and then select [2,10].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
bool nw = 0;
while (t--) {
if (nw) cout << '\n';
nw = 1;
int n, k;
cin >> n >> k;
vector<int> a(n);
for (int& x : a) cin >> x;
string ac;
if (n == 1 && a[0] == k) {
cout << "yes";
continue;
}
bool flg = 0;
for (int i = 0; i < n; i++) {
flg |= (a[i] == k);
ac += (char)('0' + (a[i] >= k));
}
if (flg ^ 1) {
cout << "no";
continue;
}
flg = 0;
for (int i = 0; i < n; i++) {
if (i + 1 < n) {
if (ac[i] == ac[i + 1] && ac[i] == '1') flg = 1;
}
if (i + 2 < n) {
int hw = 0;
hw = (ac[i] - '0') + (ac[i + 2] - '0') + (ac[i + 1] - '0');
flg |= (hw > 1);
}
}
if (flg)
cout << "yes";
else
cout << "no";
}
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
In the game Lizard Era: Beginning the protagonist will travel with three companions: Lynn, Meliana and Worrigan. Overall the game has n mandatory quests. To perform each of them, you need to take exactly two companions.
The attitude of each of the companions to the hero is an integer. Initially, the attitude of each of them to the hero of neutral and equal to 0. As the hero completes quests, he makes actions that change the attitude of the companions, whom he took to perform this task, in positive or negative direction.
Tell us what companions the hero needs to choose to make their attitude equal after completing all the quests. If this can be done in several ways, choose the one in which the value of resulting attitude is greatest possible.
Input
The first line contains positive integer n (1 β€ n β€ 25) β the number of important tasks.
Next n lines contain the descriptions of the tasks β the i-th line contains three integers li, mi, wi β the values by which the attitude of Lynn, Meliana and Worrigan respectively will change towards the hero if the hero takes them on the i-th task. All the numbers in the input are integers and do not exceed 107 in absolute value.
Output
If there is no solution, print in the first line "Impossible".
Otherwise, print n lines, two characters is each line β in the i-th line print the first letters of the companions' names that hero should take to complete the i-th task ('L' for Lynn, 'M' for Meliana, 'W' for Worrigan). Print the letters in any order, if there are multiple solutions, print any of them.
Examples
Input
3
1 0 0
0 1 0
0 0 1
Output
LM
MW
MW
Input
7
0 8 9
5 9 -2
6 -8 -7
9 4 5
-4 -9 9
-4 5 2
-6 8 -7
Output
LM
MW
LM
LW
MW
LM
LW
Input
2
1 0 0
1 1 0
Output
Impossible
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct State {
long long x, y, a;
int trace;
bool operator<(const State &state) const {
if (x == state.x) return y < state.y;
return x < state.x;
}
};
int n, m, a[50], b[50], c[50];
set<State> states;
long long maxA;
int trace1, trace2;
void gen(int i, int hi, long long sa, long long sb, long long sc, int trace) {
if (i >= hi) {
State t;
t.x = sa - sb;
t.y = sb - sc;
t.a = sa;
t.trace = trace;
set<State>::iterator it = states.find(t);
if (it != states.end()) {
if (it->a < t.a) {
states.erase(it);
states.insert(t);
}
} else {
states.insert(t);
}
return;
}
gen(i + 1, hi, sa, sb + b[i], sc + c[i], trace * 3);
gen(i + 1, hi, sa + a[i], sb, sc + c[i], trace * 3 + 1);
gen(i + 1, hi, sa + a[i], sb + b[i], sc, trace * 3 + 2);
}
void rec(int i, int hi, long long sa, long long sb, long long sc, int trace) {
if (i >= hi) {
State t;
t.x = sb - sa;
t.y = sc - sb;
set<State>::iterator it = states.find(t);
if (it != states.end() && it->a + sa > maxA) {
maxA = it->a + sa;
trace1 = it->trace;
trace2 = trace;
}
return;
}
rec(i + 1, hi, sa, sb + b[i], sc + c[i], trace * 3);
rec(i + 1, hi, sa + a[i], sb, sc + c[i], trace * 3 + 1);
rec(i + 1, hi, sa + a[i], sb + b[i], sc, trace * 3 + 2);
}
void printTrace(int trace) {
vector<int> ds;
while (trace > 1) {
ds.push_back(trace % 3);
trace /= 3;
}
for (int i = (ds.size()) - 1; i >= 0; i--) {
if (ds[i] == 0)
puts("MW");
else if (ds[i] == 1)
puts("LW");
else
puts("LM");
}
}
bool solve() {
m = min(n / 2, 11);
maxA = -10001112221000000LL;
gen(0, m, 0, 0, 0, 1);
rec(m, n, 0, 0, 0, 1);
if (maxA == -10001112221000000LL) return false;
printTrace(trace1);
printTrace(trace2);
return true;
}
int main() {
scanf("%d", &n);
for (int i = 0, _n = (n); i < _n; i++) scanf("%d %d %d", &a[i], &b[i], &c[i]);
if (!solve()) puts("Impossible");
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
E869120's and square1001's 16-th birthday is coming soon.
Takahashi from AtCoder Kingdom gave them a round cake cut into 16 equal fan-shaped pieces.
E869120 and square1001 were just about to eat A and B of those pieces, respectively,
when they found a note attached to the cake saying that "the same person should not take two adjacent pieces of cake".
Can both of them obey the instruction in the note and take desired numbers of pieces of cake?
Constraints
* A and B are integers between 1 and 16 (inclusive).
* A+B is at most 16.
Input
Input is given from Standard Input in the following format:
A B
Output
If both E869120 and square1001 can obey the instruction in the note and take desired numbers of pieces of cake, print `Yay!`; otherwise, print `:(`.
Examples
Input
5 4
Output
Yay!
Input
8 8
Output
Yay!
Input
11 4
Output
:(
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int x,y;
cin>>x>>y;
if(x>=16||y>=16||x>=9||y>=9)
cout<<":(";
else
cout<<"Yay!";
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
To become the king of Codeforces, Kuroni has to solve the following problem.
He is given n numbers a_1, a_2, ..., a_n. Help Kuroni to calculate β_{1β€ i<jβ€ n} |a_i - a_j|. As result can be very big, output it modulo m.
If you are not familiar with short notation, β_{1β€ i<jβ€ n} |a_i - a_j| is equal to |a_1 - a_2|β
|a_1 - a_3|β
... β
|a_1 - a_n|β
|a_2 - a_3|β
|a_2 - a_4|β
... β
|a_2 - a_n| β
... β
|a_{n-1} - a_n|. In other words, this is the product of |a_i - a_j| for all 1β€ i < j β€ n.
Input
The first line contains two integers n, m (2β€ n β€ 2β
10^5, 1β€ m β€ 1000) β number of numbers and modulo.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 10^9).
Output
Output the single number β β_{1β€ i<jβ€ n} |a_i - a_j| mod m.
Examples
Input
2 10
8 5
Output
3
Input
3 12
1 4 5
Output
0
Input
3 7
1 4 9
Output
1
Note
In the first sample, |8 - 5| = 3 β‘ 3 mod 10.
In the second sample, |1 - 4|β
|1 - 5|β
|4 - 5| = 3β
4 β
1 = 12 β‘ 0 mod 12.
In the third sample, |1 - 4|β
|1 - 9|β
|4 - 9| = 3 β
8 β
5 = 120 β‘ 1 mod 7.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long a[210000];
long long te[1100];
long long f[1100] = {0};
int main() {
long long n, i, j;
long long m;
scanf("%lld%lld", &n, &m);
for (i = 1; i <= n; i++) scanf("%lld", &a[i]);
if (n > m)
printf("0\n");
else {
long long ans = 1;
for (i = 1; i <= n; i++) {
for (j = i + 1; j <= n; j++) {
ans = ans * abs(a[i] - a[j]) % m;
}
}
printf("%lld\n", ans);
}
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
You are given a table consisting of n rows and m columns. Each cell of the table contains either 0 or 1. In one move, you are allowed to pick any row or any column and invert all values, that is, replace 0 by 1 and vice versa.
What is the minimum number of cells with value 1 you can get after applying some number of operations?
Input
The first line of the input contains two integers n and m (1 β€ n β€ 20, 1 β€ m β€ 100 000) β the number of rows and the number of columns, respectively.
Then n lines follows with the descriptions of the rows. Each line has length m and contains only digits '0' and '1'.
Output
Output a single integer β the minimum possible number of ones you can get after applying some sequence of operations.
Example
Input
3 4
0110
1010
0111
Output
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
long long powmod(long long a, long long b) {
long long res = 1;
a %= mod;
assert(b >= 0);
for (; b; b >>= 1) {
if (b & 1) res = res * a % mod;
a = a * a % mod;
}
return res % mod;
}
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 / gcd(a, b) * b; }
const std::vector<std::pair<int, int>> moves{{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
inline int bitCount(long long x) { return __builtin_popcountll(x); }
inline long long highestOneBit(long long x) {
return 1LL << (63 - __builtin_clzll(x | 1LL));
}
inline int binaryDigits(long long x) { return 64 - __builtin_clzll(x | 1LL); }
template <typename A>
string to_string(A* ptr) {
stringstream ss;
ss << "0x" << std::setw(16) << std::setfill('0') << std::hex
<< (uint64_t)(uintptr_t)ptr;
return ss.str();
}
template <typename A, typename B>
string to_string(pair<A, B> p);
template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p);
template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p);
string to_string(const string& s) { return '"' + s + '"'; }
string to_string(const char* s) { return to_string((string)s); }
string to_string(bool b) { return (b ? "true" : "false"); }
string to_string(vector<bool> v) {
bool first = true;
string res = "{";
for (int i = 0; i < static_cast<int>(v.size()); i++) {
if (!first) {
res += ", ";
}
first = false;
res += to_string(v[i]);
}
res += "}";
return res;
}
template <size_t N>
string to_string(bitset<N> v) {
string res = "";
for (size_t i = 0; i < N; i++) {
res += static_cast<char>('0' + v[i]);
}
return res;
}
template <typename A>
string to_string(A v) {
bool first = true;
string res = "{";
for (const auto& x : v) {
if (!first) {
res += ", ";
}
first = false;
res += to_string(x);
}
res += "}";
return res;
}
template <typename A, typename B>
string to_string(pair<A, B> p) {
return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}
template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p) {
return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " +
to_string(get<2>(p)) + ")";
}
template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p) {
return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " +
to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")";
}
void debug_out() { cerr << '\n'; }
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
cerr << " " << to_string(H);
debug_out(T...);
}
namespace fwht {
template <typename T>
void hadamard(vector<T>& a) {
int n = a.size();
for (int k = 1; k < n; k <<= 1) {
for (int i = 0; i < n; i += 2 * k) {
for (int j = 0; j < k; j++) {
T x = a[i + j];
T y = a[i + j + k];
a[i + j] = x + y;
a[i + j + k] = x - y;
}
}
}
}
template <typename T>
vector<T> multiply(vector<T> a, vector<T> b) {
int eq = (a == b);
int n = 1;
while (n < (int)max(a.size(), b.size())) {
n <<= 1;
}
a.resize(n);
b.resize(n);
hadamard(a);
if (eq)
b = a;
else
hadamard(b);
for (int i = 0; i < n; i++) {
a[i] *= b[i];
}
hadamard(a);
T q = static_cast<T>(n);
for (int i = 0; i < n; i++) {
a[i] /= q;
}
return a;
}
} // namespace fwht
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
vector<string> s(n);
for (int i = 0; i < n; i++) cin >> s[i];
vector<long long> cost(1 << n, 0);
for (int mask = 0; mask < 1 << n; mask++) {
int count = bitCount(mask);
cost[mask] = min(count, n - count);
}
vector<long long> freq(1 << n, 0);
for (int col = 0; col < m; col++) {
int mask = 0;
for (int i = 0; i < n; i++) mask |= (s[i][col] - '0') << i;
freq[mask]++;
}
auto ans = fwht::multiply(freq, cost);
cout << *min_element(ans.begin(), ans.end()) << '\n';
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Let's consider the following game. We have a rectangular field n Γ m in size. Some squares of the field contain chips.
Each chip has an arrow painted on it. Thus, each chip on the field points in one of the following directions: up, down, left or right.
The player may choose a chip and make a move with it.
The move is the following sequence of actions. The chosen chip is marked as the current one. After that the player checks whether there are more chips in the same row (or in the same column) with the current one that are pointed by the arrow on the current chip. If there is at least one chip then the closest of them is marked as the new current chip and the former current chip is removed from the field. After that the check is repeated. This process can be repeated several times. If a new chip is not found, then the current chip is removed from the field and the player's move ends.
By the end of a move the player receives several points equal to the number of the deleted chips.
By the given initial chip arrangement determine the maximum number of points that a player can receive during one move. Also determine the number of such moves.
Input
The first line contains two integers n and m (1 β€ n, m, n Γ m β€ 5000). Then follow n lines containing m characters each β that is the game field description. "." means that this square is empty. "L", "R", "U", "D" mean that this square contains a chip and an arrow on it says left, right, up or down correspondingly.
It is guaranteed that a field has at least one chip.
Output
Print two numbers β the maximal number of points a player can get after a move and the number of moves that allow receiving this maximum number of points.
Examples
Input
4 4
DRLD
U.UL
.UUR
RDDL
Output
10 1
Input
3 5
.D...
RRRLL
.U...
Output
6 2
Note
In the first sample the maximum number of points is earned by the chip in the position (3, 3). You can see its progress at the following picture:
<image>
All other chips earn fewer points.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int N, M, best, curr, cnt;
char A[5005][5005], B[5005][5005];
int P[4][4 * 5005], up, dp, lp, rp;
int pos(int x, int y) {
if (x < 1 || x > N || y < 1 || y > M) return 0;
return (x - 1) * M + y;
}
int X(int p) {
p--;
return (p / M) + 1;
}
int Y(int p) {
int ret = (p % M);
if (ret == 0) ret = M;
return ret;
}
void init() {
for (int I = 1; I <= N; I++)
for (int K = 1; K <= M; K++) B[I][K] = A[I][K];
for (int I = 1; I <= N; I++)
for (int K = 1; K <= M; K++) {
int p = pos(I, K);
P[0][p] = pos(I - 1, K);
P[1][p] = pos(I + 1, K);
P[2][p] = pos(I, K - 1);
P[3][p] = pos(I, K + 1);
}
}
int setof(int p, int id) {
if (p == 0 || (B[X(p)][Y(p)] != '.')) return p;
return P[id][p] = setof(P[id][p], id);
}
int DFS(int x, int y) {
int p = pos(x, y), np = -1;
char tmp = B[x][y];
B[x][y] = '.';
if (tmp == 'U')
np = setof(p, 0);
else if (tmp == 'D')
np = setof(p, 1);
else if (tmp == 'L')
np = setof(p, 2);
else if (tmp == 'R')
np = setof(p, 3);
else
assert(false);
assert(np != -1);
if (np == 0) return 1;
return 1 + DFS(X(np), Y(np));
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> N >> M;
for (int I = 1; I <= N; I++) cin >> A[I] + 1;
for (int I = 1; I <= N; I++)
for (int K = 1; K <= M; K++) {
int p = pos(I, K);
}
for (int I = 1; I <= N; I++)
for (int K = 1; K <= M; K++)
if (A[I][K] != '.') {
init();
curr = DFS(I, K);
if (curr > best) {
best = curr;
cnt = 1;
} else if (curr == best) {
cnt++;
}
}
cout << best << " " << cnt << endl;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Tsuruga Castle, a symbol of Aizuwakamatsu City, was named "Tsuruga Castle" after Gamo Ujisato built a full-scale castle tower. You can overlook the Aizu basin from the castle tower. On a clear day, you can see Tsuruga Castle from the summit of Mt. Iimori, which is famous for Byakkotai.
<image>
We decided to conduct a dating survey of visitors to Tsuruga Castle to use as a reference for future public relations activities in Aizuwakamatsu City. Please create a program that inputs the age of visitors and outputs the number of people by age group below.
Category | Age
--- | ---
Under 10 years old | 0 ~ 9
Teens | 10 ~ 19
20s | 20 ~ 29
30s | 30 ~ 39
40s | 40 ~ 49
50s | 50 ~ 59
Over 60 years old | 60 ~
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
a1
a2
::
an
The first line gives the number of visitors n (1 β€ n β€ 1000000), and the following n lines give the age of the i-th visitor ai (0 β€ ai β€ 120).
Output
The number of people is output in the following format for each data set.
Line 1: Number of people under 10
Line 2: Number of teens
Line 3: Number of people in their 20s
Line 4: Number of people in their 30s
Line 5: Number of people in their 40s
Line 6: Number of people in their 50s
Line 7: Number of people over 60
Example
Input
8
71
34
65
11
41
39
6
5
4
67
81
78
65
0
Output
2
1
0
2
1
0
2
0
0
0
0
0
0
4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(v) (v).begin(),(v).end()
#define fi first
#define se second
template<typename A, typename B> inline bool chmax(A &a, B b) { if (a<b) { a=b; return 1; } return 0; }
template<typename A, typename B> inline bool chmin(A &a, B b) { if (a>b) { a=b; return 1; } return 0; }
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<int, pll> pip;
const ll INF = 1ll<<60;
const ll MOD = 1000000007;
const double EPS = 1e-9;
int main() {
int n;
while (cin >> n, n) {
int cnt[7] = {};
REP(i, n) {
int a;
scanf("%d", &a);
a /= 10;
if (a >= 6) cnt[6]++;
else cnt[a]++;
}
REP(i, 7) cout << cnt[i] << endl;
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Snuke lives in another world, where slimes are real creatures and kept by some people. Slimes come in N colors. Those colors are conveniently numbered 1 through N. Snuke currently has no slime. His objective is to have slimes of all the colors together.
Snuke can perform the following two actions:
* Select a color i (1β€iβ€N), such that he does not currently have a slime in color i, and catch a slime in color i. This action takes him a_i seconds.
* Cast a spell, which changes the color of all the slimes that he currently has. The color of a slime in color i (1β€iβ€N-1) will become color i+1, and the color of a slime in color N will become color 1. This action takes him x seconds.
Find the minimum time that Snuke needs to have slimes in all N colors.
Constraints
* 2β€Nβ€2,000
* a_i are integers.
* 1β€a_iβ€10^9
* x is an integer.
* 1β€xβ€10^9
Input
The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N
Output
Find the minimum time that Snuke needs to have slimes in all N colors.
Examples
Input
2 10
1 100
Output
12
Input
3 10
100 1 100
Output
23
Input
4 10
1 2 3 4
Output
10
### Response
```cpp
#include <iostream>
using namespace std;
int a[2010], b[2010][2010];
int main()
{
cin.sync_with_stdio(0);
cin.tie(0);
long n, x; cin>>n>>x;
for(int i=0; i<n; ++i) cin>>a[i];
for(int i=0; i<n; ++i) {
b[i][0]=a[i];
for(int k=1; k<n; ++k)
b[i][k]=min(b[i][k-1], a[(i-k+n)%n]);
}
long res=1L<<62;
for(int k=0; k<n; ++k) {
long t=0;
for(int i=0; i<n; ++i)
t+=b[i][k];
res=min(res, t+k*x);
}
cout<<res<<endl;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
You are given a regular polygon with n vertices labeled from 1 to n in counter-clockwise order. The triangulation of a given polygon is a set of triangles such that each vertex of each triangle is a vertex of the initial polygon, there is no pair of triangles such that their intersection has non-zero area, and the total area of all triangles is equal to the area of the given polygon. The weight of a triangulation is the sum of weigths of triangles it consists of, where the weight of a triagle is denoted as the product of labels of its vertices.
Calculate the minimum weight among all triangulations of the polygon.
Input
The first line contains single integer n (3 β€ n β€ 500) β the number of vertices in the regular polygon.
Output
Print one integer β the minimum weight among all triangulations of the given polygon.
Examples
Input
3
Output
6
Input
4
Output
18
Note
According to Wiki: polygon triangulation is the decomposition of a polygonal area (simple polygon) P into a set of triangles, i. e., finding a set of triangles with pairwise non-intersecting interiors whose union is P.
In the first example the polygon is a triangle, so we don't need to cut it further, so the answer is 1 β
2 β
3 = 6.
In the second example the polygon is a rectangle, so it should be divided into two triangles. It's optimal to cut it using diagonal 1-3 so answer is 1 β
2 β
3 + 1 β
3 β
4 = 6 + 12 = 18.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int dp[502];
int main() {
dp[0] = 0;
dp[1] = 0;
dp[2] = 0;
dp[3] = 6;
for (int i = 4; i <= 500; i++) {
dp[i] = dp[i - 1] + (i * (i - 1));
}
int n;
cin >> n;
cout << dp[n] << endl;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".
To play Mau-Mau, you need a pack of 52 cards. Each card has a suit (Diamonds β D, Clubs β C, Spades β S, or Hearts β H), and a rank (2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, or A).
At the start of the game, there is one card on the table and you have five cards in your hand. You can play a card from your hand if and only if it has the same rank or the same suit as the card on the table.
In order to check if you'd be a good playing partner, Gennady has prepared a task for you. Given the card on the table and five cards in your hand, check if you can play at least one card.
Input
The first line of the input contains one string which describes the card on the table. The second line contains five strings which describe the cards in your hand.
Each string is two characters long. The first character denotes the rank and belongs to the set \{{\tt 2}, {\tt 3}, {\tt 4}, {\tt 5}, {\tt 6}, {\tt 7}, {\tt 8}, {\tt 9}, {\tt T}, {\tt J}, {\tt Q}, {\tt K}, {\tt A}\}. The second character denotes the suit and belongs to the set \{{\tt D}, {\tt C}, {\tt S}, {\tt H}\}.
All the cards in the input are different.
Output
If it is possible to play a card from your hand, print one word "YES". Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Examples
Input
AS
2H 4C TH JH AD
Output
YES
Input
2H
3D 4C AC KD AS
Output
NO
Input
4D
AS AC AD AH 5H
Output
YES
Note
In the first example, there is an Ace of Spades (AS) on the table. You can play an Ace of Diamonds (AD) because both of them are Aces.
In the second example, you cannot play any card.
In the third example, you can play an Ace of Diamonds (AD) because it has the same suit as a Four of Diamonds (4D), which lies on the table.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(void) {
char c[3], d[16];
cin >> c;
char ch = getchar();
cin.get(d, 15);
if (c[0] == d[0] || c[0] == d[3] || c[0] == d[6] || c[0] == d[9] ||
c[0] == d[12])
cout << "Yes";
else if (c[1] == d[1] || c[1] == d[4] || c[1] == d[7] || c[1] == d[10] ||
c[1] == d[13])
cout << "Yes";
else
cout << "No";
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
In AtCoder, a person who has participated in a contest receives a color, which corresponds to the person's rating as follows:
* Rating 1-399 : gray
* Rating 400-799 : brown
* Rating 800-1199 : green
* Rating 1200-1599 : cyan
* Rating 1600-1999 : blue
* Rating 2000-2399 : yellow
* Rating 2400-2799 : orange
* Rating 2800-3199 : red
Other than the above, a person whose rating is 3200 or higher can freely pick his/her color, which can be one of the eight colors above or not.
Currently, there are N users who have participated in a contest in AtCoder, and the i-th user has a rating of a_i.
Find the minimum and maximum possible numbers of different colors of the users.
Constraints
* 1 β€ N β€ 100
* 1 β€ a_i β€ 4800
* a_i is an integer.
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum possible number of different colors of the users, and the maximum possible number of different colors, with a space in between.
Examples
Input
4
2100 2500 2700 2700
Output
2 2
Input
5
1100 1900 2800 3200 3200
Output
3 5
Input
20
800 810 820 830 840 850 860 870 880 890 900 910 920 930 940 950 960 970 980 990
Output
1 1
### Response
```cpp
#include <iostream>
using namespace std;
int main(void){
int n,col[9]={};
cin>>n;
for(int i=0;i<n;i++){
int a;
cin>>a;
if(a>3200) a=3200;
col[a/400] ++;
}
int ans=0;
for(int i=0;i<8;i++){
ans += (col[i]>0);
}
cout<<(ans>0?ans:1)<<" "<<(ans+col[8])<<endl;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.
The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean.
The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help.
Input
The first line contains two integers n and q (2 β€ n β€ 105, 1 β€ q β€ 105) β the number of stations and the number of days.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi β€ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.
The next q lines contains three integers a, b and c each (1 β€ a, b, c β€ n) β the ids of stations chosen by boys for some day. Note that some of these ids could be same.
Output
Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.
Examples
Input
3 2
1 1
1 2 3
2 3 3
Output
2
3
Input
4 1
1 2 3
1 2 3
Output
2
Note
In the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1 <image> 2, and Grisha would go on the route 3 <image> 1 <image> 2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3 <image> 1 <image> 2. Grisha would see the text at 3 stations.
In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1 <image> 2 <image> 3, and Grisha would go on the route 2 <image> 3 and would see the text at both stations.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 110000;
struct LCA {
int p[maxn][20], n, q, cnt[maxn], deep[maxn];
vector<int> G[maxn];
int dfs(int u, int _p) {
p[u][0] = _p;
cnt[u] = 1;
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if (v == _p) continue;
deep[v] = deep[u] + 1;
cnt[u] += dfs(v, u);
}
return cnt[u];
}
int dis(int x, int y) { return deep[x] + deep[y] - 2 * deep[Lca(x, y)]; }
void Lca_init() {
scanf("%d%d", &n, &q);
for (int i = 0; i < maxn; i++) G[i].clear();
for (int i = 2; i <= n; i++) {
int v;
scanf("%d", &v);
G[v].push_back(i), G[i].push_back(v);
}
deep[1] = 0;
dfs(1, -1);
for (int j = 1; j < 20; j++)
for (int i = 1; i <= n; i++) {
if (p[i][j - 1] == -1)
p[i][j] = -1;
else
p[i][j] = p[p[i][j - 1]][j - 1];
}
for (int i = 1; i <= q; i++) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
int ab = dis(a, b), bc = dis(b, c), ac = dis(a, c);
int sum = ab + bc + ac;
sum /= 2;
int ans = 0;
ans = 1 + max(ans, max(sum - ab, max(sum - bc, sum - ac)));
printf("%d\n", ans);
}
}
int Lca_up(int u, int len) {
for (int i = 0; i < 20; i++)
if (u != -1 && len & (1 << i)) u = p[u][i];
return u;
}
int Lca(int u, int v) {
if (deep[u] < deep[v]) swap(u, v);
u = Lca_up(u, deep[u] - deep[v]);
if (u == v) return u;
for (int i = 19; i >= 0; i--) {
if (p[u][i] == p[v][i]) continue;
u = p[u][i];
v = p[v][i];
}
return p[u][0];
}
} solver;
int main() {
solver.Lca_init();
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
One day Ms Swan bought an orange in a shop. The orange consisted of nΒ·k segments, numbered with integers from 1 to nΒ·k.
There were k children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote the number of the segment that he would like to get: the i-th (1 β€ i β€ k) child wrote the number ai (1 β€ ai β€ nΒ·k). All numbers ai accidentally turned out to be different.
Now the children wonder, how to divide the orange so as to meet these conditions:
* each child gets exactly n orange segments;
* the i-th child gets the segment with number ai for sure;
* no segment goes to two children simultaneously.
Help the children, divide the orange and fulfill the requirements, described above.
Input
The first line contains two integers n, k (1 β€ n, k β€ 30). The second line contains k space-separated integers a1, a2, ..., ak (1 β€ ai β€ nΒ·k), where ai is the number of the orange segment that the i-th child would like to get.
It is guaranteed that all numbers ai are distinct.
Output
Print exactly nΒ·k distinct integers. The first n integers represent the indexes of the segments the first child will get, the second n integers represent the indexes of the segments the second child will get, and so on. Separate the printed numbers with whitespaces.
You can print a child's segment indexes in any order. It is guaranteed that the answer always exists. If there are multiple correct answers, print any of them.
Examples
Input
2 2
4 1
Output
2 4
1 3
Input
3 1
2
Output
3 2 1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[10000], b[10000], i, j, k, l, n, m;
int main() {
cin >> n >> k;
for (i = 1; i <= k; i++) {
cin >> b[i];
a[b[i]] = 1;
}
for (i = 1; i <= k; i++) {
cout << b[i] << " ";
l = 1;
for (j = 1; j <= n * k; j++)
if (a[j] == 0) {
cout << j << " ";
a[j] = 1;
l++;
if (l == n) break;
}
cout << endl;
}
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Students Vasya and Petya are studying at the BSU (Byteland State University). At one of the breaks they decided to order a pizza. In this problem pizza is a circle of some radius. The pizza was delivered already cut into n pieces. The i-th piece is a sector of angle equal to ai. Vasya and Petya want to divide all pieces of pizza into two continuous sectors in such way that the difference between angles of these sectors is minimal. Sector angle is sum of angles of all pieces in it. Pay attention, that one of sectors can be empty.
Input
The first line contains one integer n (1 β€ n β€ 360) β the number of pieces into which the delivered pizza was cut.
The second line contains n integers ai (1 β€ ai β€ 360) β the angles of the sectors into which the pizza was cut. The sum of all ai is 360.
Output
Print one integer β the minimal difference between angles of sectors that will go to Vasya and Petya.
Examples
Input
4
90 90 90 90
Output
0
Input
3
100 100 160
Output
40
Input
1
360
Output
360
Input
4
170 30 150 10
Output
0
Note
In first sample Vasya can take 1 and 2 pieces, Petya can take 3 and 4 pieces. Then the answer is |(90 + 90) - (90 + 90)| = 0.
In third sample there is only one piece of pizza that can be taken by only one from Vasya and Petya. So the answer is |360 - 0| = 360.
In fourth sample Vasya can take 1 and 4 pieces, then Petya will take 2 and 3 pieces. So the answer is |(170 + 10) - (30 + 150)| = 0.
Picture explaning fourth sample:
<image>
Both red and green sectors consist of two adjacent pieces of pizza. So Vasya can take green sector, then Petya will take red sector.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
scanf("%d", &n);
vector<int> v(n);
for (int i = 0; i < n; ++i) cin >> v[i];
int res = 360;
for (int i = 0; i < n; ++i) {
int cur = 0;
for (int j = 0; j < n; ++j) {
cur += v[(i + j) % n];
res = min(res, abs(cur - (360 - cur)));
}
}
cout << res << endl;
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Let us define a magic grid to be a square matrix of integers of size n Γ n, satisfying the following conditions.
* All integers from 0 to (n^2 - 1) inclusive appear in the matrix exactly once.
* [Bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of all elements in a row or a column must be the same for each row and column.
You are given an integer n which is a multiple of 4. Construct a magic grid of size n Γ n.
Input
The only line of input contains an integer n (4 β€ n β€ 1000). It is guaranteed that n is a multiple of 4.
Output
Print a magic grid, i.e. n lines, the i-th of which contains n space-separated integers, representing the i-th row of the grid.
If there are multiple answers, print any. We can show that an answer always exists.
Examples
Input
4
Output
8 9 1 13
3 12 7 5
0 2 4 11
6 10 15 14
Input
8
Output
19 55 11 39 32 36 4 52
51 7 35 31 12 48 28 20
43 23 59 15 0 8 16 44
3 47 27 63 24 40 60 56
34 38 6 54 17 53 9 37
14 50 30 22 49 5 33 29
2 10 18 46 41 21 57 13
26 42 62 58 1 45 25 61
Note
In the first example, XOR of each row and each column is 13.
In the second example, XOR of each row and each column is 60.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long INF = 10E16;
const long long mask = (1 << 9) - 1;
const long long base = 100000000000;
const long double eps = 0.0000001;
struct pp {
long long fi, sc;
bool const operator<(const pp& b) {
if (fi == b.fi) return sc < b.sc;
return fi < b.fi;
}
bool const operator>(const pp& b) {
if (fi == b.fi) return sc > b.sc;
return fi > b.fi;
}
bool const operator==(const pp& b) {
if (fi == b.fi && sc == b.sc) return 1;
return 0;
}
};
bool const operator<(const pp& a, const pp& b) {
if (a.fi == b.fi) return a.sc < b.sc;
return a.fi < b.fi;
}
long long n, A[2007][2007];
set<long long> S;
int main() {
ios_base::sync_with_stdio(NULL);
cin.tie(NULL);
cout.tie(NULL);
cin >> n;
long long r = 0;
for (long long i = 1; i <= n; i += 4) {
for (long long j = 1; j <= n; j += 4) {
for (long long ii = i; ii < i + 4; ii++) {
for (long long jj = j; jj < j + 4; jj++) {
A[ii][jj] = r;
r++;
}
}
}
}
for (long long i = 1; i <= n; i++) {
for (long long j = 1; j <= n; j++) {
cout << A[i][j] << ' ';
}
cout << endl;
}
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
There have recently been elections in the zoo. Overall there were 7 main political parties: one of them is the Little Elephant Political Party, 6 other parties have less catchy names.
Political parties find their number in the ballot highly important. Overall there are m possible numbers: 1, 2, ..., m. Each of these 7 parties is going to be assigned in some way to exactly one number, at that, two distinct parties cannot receive the same number.
The Little Elephant Political Party members believe in the lucky digits 4 and 7. They want to evaluate their chances in the elections. For that, they need to find out, how many correct assignments are there, such that the number of lucky digits in the Little Elephant Political Party ballot number is strictly larger than the total number of lucky digits in the ballot numbers of 6 other parties.
Help the Little Elephant Political Party, calculate this number. As the answer can be rather large, print the remainder from dividing it by 1000000007 (109 + 7).
Input
A single line contains a single positive integer m (7 β€ m β€ 109) β the number of possible numbers in the ballot.
Output
In a single line print a single integer β the answer to the problem modulo 1000000007 (109 + 7).
Examples
Input
7
Output
0
Input
8
Output
1440
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long M = 1000000007;
int m;
long long sum = 0;
int cnt[20];
long long dp[15][2][15];
void DP() {
int digit[15];
memset(digit, 0, sizeof(digit));
int mm = m;
int index = 1;
while (mm > 0) {
digit[index++] = mm % 10;
mm /= 10;
}
memset(dp, 0, sizeof(dp));
dp[0][0][0] = 1;
for (int i = 1; i <= 10; i++) {
for (int j = 0; j <= i; j++) {
dp[i][0][j] = 8 * dp[i - 1][0][j];
if (j > 0) dp[i][0][j] += dp[i - 1][0][j - 1] * 2;
for (int k = 0; k < digit[i]; k++) {
if (k == 4 || k == 7)
dp[i][1][j] += dp[i - 1][0][j - 1];
else
dp[i][1][j] += dp[i - 1][0][j];
}
if (digit[i] == 4 || digit[i] == 7)
dp[i][1][j] += dp[i - 1][1][j - 1];
else
dp[i][1][j] += dp[i - 1][1][j];
}
}
for (int i = 0; i <= 10; i++) {
cnt[i] = dp[10][1][i];
}
cnt[0]--;
}
void Search(int depth, int left, long long ways) {
ways %= M;
if (depth == 0) {
sum += ways;
sum %= M;
return;
}
for (int i = 0; i <= left; i++) {
if (cnt[i] > 0) {
Search(depth - 1, left - i, ways * cnt[i]--);
cnt[i]++;
}
}
}
int main() {
scanf("%d", &m);
m++;
DP();
for (int i = 10; i > 0; i--) {
if (cnt[i] == 0) continue;
Search(6, i - 1, cnt[i]);
}
cout << sum << endl;
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
A year ago on the bench in public park Leha found an array of n numbers. Leha believes that permutation p is right if for all 1 β€ i < n condition, that apiΒ·api + 1 is not perfect square, holds. Leha wants to find number of right permutations modulo 109 + 7.
Input
First line of input data contains single integer n (1 β€ n β€ 300) β length of the array.
Next line contains n integers a1, a2, ... , an (1 β€ ai β€ 109) β found array.
Output
Output single integer β number of right permutations modulo 109 + 7.
Examples
Input
3
1 2 4
Output
2
Input
7
5 2 4 2 4 1 1
Output
144
Note
For first example:
[1, 2, 4] β right permutation, because 2 and 8 are not perfect squares.
[1, 4, 2] β wrong permutation, because 4 is square of 2.
[2, 1, 4] β wrong permutation, because 4 is square of 2.
[2, 4, 1] β wrong permutation, because 4 is square of 2.
[4, 1, 2] β wrong permutation, because 4 is square of 2.
[4, 2, 1] β right permutation, because 8 and 2 are not perfect squares.
### Response
```cpp
#include <bits/stdc++.h>
const int INF = 1e9 + 1;
const double PI = acos(-1.0);
const double EPS = 1e-9;
using namespace std;
template <typename F, typename S>
ostream &operator<<(ostream &os, const pair<F, S> &p) {
return os << "(" << p.first << ", " << p.second << ")";
}
template <typename T>
ostream &operator<<(ostream &os, const vector<T> &v) {
os << "{";
typename vector<T>::const_iterator it;
for (it = v.begin(); it != v.end(); it++) {
if (it != v.begin()) os << ", ";
os << *it;
}
return os << "}";
}
template <typename T>
ostream &operator<<(ostream &os, const set<T> &v) {
os << "[";
typename set<T>::const_iterator it;
for (it = v.begin(); it != v.end(); it++) {
if (it != v.begin()) os << ", ";
os << *it;
}
return os << "]";
}
template <typename F, typename S>
ostream &operator<<(ostream &os, const map<F, S> &v) {
os << "[";
typename map<F, S>::const_iterator it;
for (it = v.begin(); it != v.end(); it++) {
if (it != v.begin()) os << ", ";
os << it->first << " = " << it->second;
}
return os << "]";
}
template <class T>
void deb_array(T *arr, int length) {
for (int i = 0; i < length; i++) {
cout << arr[i] << ' ';
}
cout << '\n';
}
const int maxn = 305;
const long long mod = 1e9 + 7;
int n;
long long a[maxn], fac[maxn];
long long comb[maxn][maxn], dp[maxn][maxn];
vector<int> group;
map<int, int> mp;
void calc() {
for (int i = 0; i < maxn; i++) {
for (int j = 0; j <= i; j++) {
if (i == j || j == 0)
comb[i][j] = 1;
else
comb[i][j] = (comb[i - 1][j - 1] + comb[i - 1][j]) % mod;
}
}
fac[0] = 1;
for (int i = 1; i < maxn; i++) {
fac[i] = fac[i - 1] * i;
fac[i] %= mod;
}
}
int main() {
ios_base::sync_with_stdio(0);
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
int b = a[i], num;
for (int j = 2; j * j <= b; j++) {
num = 0;
while (b % j == 0) {
num++;
b /= j;
}
if (num & 1) {
b *= j;
}
}
mp[b]++;
}
for (auto it = mp.begin(); it != mp.end(); it++) {
group.push_back(it->second);
}
calc();
dp[0][group[0] - 1] = fac[group[0]];
int sum = group[0] + 1;
for (int x = 1; x < group.size(); x++) {
for (int y = 0; y <= sum; y++) {
for (int ij = 1; ij <= group[x]; ij++) {
for (int j = 0; j <= min(ij, y); j++) {
long long cur = dp[x - 1][y];
if (cur == 0) continue;
cur *= fac[group[x]];
cur %= mod;
cur *= comb[y][j];
cur %= mod;
cur *= comb[sum - y][ij - j];
cur %= mod;
cur *= comb[group[x] - 1][ij - 1];
dp[x][y - j + group[x] - ij] += cur;
dp[x][y - j + group[x] - ij] %= mod;
}
}
}
sum += group[x];
}
cout << dp[group.size() - 1][0] << '\n';
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Rainbow built h cells in a row that are numbered from 1 to h from left to right. There are n cells with treasure. We call each of these n cells "Treasure Cell". The i-th "Treasure Cell" is the ai-th cell and the value of treasure in it is ci dollars.
Then, Freda went in the first cell. For now, she can go just k cells forward, or return to the first cell. That means Freda was able to reach the 1st, (k + 1)-th, (2Β·k + 1)-th, (3Β·k + 1)-th cells and so on.
Then Rainbow gave Freda m operations. Each operation is one of the following three types:
1. Add another method x: she can also go just x cells forward at any moment. For example, initially she has only one method k. If at some moment she has methods a1, a2, ..., ar then she can reach all the cells with number in form <image>, where vi β some non-negative integer.
2. Reduce the value of the treasure in the x-th "Treasure Cell" by y dollars. In other words, to apply assignment cx = cx - y.
3. Ask the value of the most valuable treasure among the cells Freda can reach. If Freda cannot reach any cell with the treasure then consider the value of the most valuable treasure equal to 0, and do nothing. Otherwise take the most valuable treasure away. If several "Treasure Cells" have the most valuable treasure, take the "Treasure Cell" with the minimum number (not necessarily with the minimum number of cell). After that the total number of cells with a treasure is decreased by one.
As a programmer, you are asked by Freda to write a program to answer each query.
Input
The first line of the input contains four integers: h (1 β€ h β€ 1018), n, m (1 β€ n, m β€ 105) and k (1 β€ k β€ 104).
Each of the next n lines contains two integers: ai (1 β€ ai β€ h), ci (1 β€ ci β€ 109). That means the i-th "Treasure Cell" is the ai-th cell and cost of the treasure in that cell is ci dollars. All the ai are distinct.
Each of the next m lines is in one of the three following formats:
* "1 x" β an operation of type 1, 1 β€ x β€ h;
* "2 x y" β an operation of type 2, 1 β€ x β€ n, 0 β€ y < cx;
* "3" β an operation of type 3.
There are at most 20 operations of type 1. It's guaranteed that at any moment treasure in each cell has positive value. It's guaranteed that all operations is correct (no operation can decrease the value of the taken tresure).
Please, do not use the %lld specifier to read 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
For each operation of type 3, output an integer indicates the value (in dollars) of the most valuable treasure among the "Treasure Cells" Freda can reach. If there is no such treasure, output 0.
Examples
Input
10 3 5 2
5 50
7 60
8 100
2 2 5
3
1 3
3
3
Output
55
100
50
Note
In the sample, there are 10 cells and 3 "Treasure Cells". The first "Treasure Cell" is cell 5, having 50 dollars tresure in it. The second "Treasure Cell" is cell 7, having 60 dollars tresure in it. The third "Treasure Cell" is cell 8, having 100 dollars tresure in it.
At first, Freda can only reach cell 1, 3, 5, 7 and 9. In the first operation, we reduce the value in the second "Treasure Cell" from 60 to 55. Then the most valuable treasure among the "Treasure Cells" she can reach is max(50, 55) = 55. After the third operation, she can also go 3 cells forward each step, being able to reach cell 1, 3, 4, 5, 6, 7, 8, 9, 10. So the most valuable tresure is 100.
Noticed that she took the 55 dollars and 100 dollars treasure away, so the last answer is 50.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int inf = 2000000000;
static inline int Rint() {
struct X {
int dig[256];
X() {
for (int i = '0'; i <= '9'; ++i) dig[i] = 1;
dig['-'] = 1;
}
};
static X fuck;
int s = 1, v = 0, c;
for (; !fuck.dig[c = getchar()];)
;
if (c == '-')
s = 0;
else if (fuck.dig[c])
v = c ^ 48;
for (; fuck.dig[c = getchar()]; v = v * 10 + (c ^ 48))
;
return s ? v : -v;
}
template <typename T>
static inline void cmax(T& a, const T& b) {
if (b > a) a = b;
}
template <typename T>
static inline void cmin(T& a, const T& b) {
if (b < a) a = b;
}
const int maxn = 100005;
long long h;
int n, m, k;
long long pos[maxn];
int treasure[maxn];
int flag[maxn];
long long D[10005];
long long allk[32];
int top;
struct Pt {
long long t, p, id;
int operator<(const Pt& o) const {
if (t != o.t) return t < o.t;
return id > o.id;
}
};
void fix(priority_queue<Pt>& pq) {
set<pair<long long, int> > st;
for (int i = 0; i < k; ++i)
if (D[i] != -1) st.insert({D[i], i});
while (!st.empty()) {
auto where = st.begin();
auto curr = *where;
st.erase(where);
if (D[curr.second] != curr.first) continue;
for (int i = 0; i < top; ++i) {
{
const long long val = curr.first + allk[i];
if (val > h) continue;
int next = val % k;
if (next == curr.second) {
continue;
}
if (D[next] == -1) {
D[next] = val;
st.insert({D[next], next});
} else if (D[next] > val) {
D[next] = val;
st.insert({D[next], next});
}
}
}
}
for (int i = 1; i <= n; ++i)
if (flag[i] == 0) {
const int bucket = pos[i] % k;
if (D[bucket] != -1) {
if (pos[i] >= D[bucket]) {
pq.push({treasure[i], pos[i], i});
flag[i] = 1;
}
}
}
}
int main() {
scanf("%I64d", &h);
n = Rint(), m = Rint(), k = Rint();
for (int i = 1; i <= n; ++i) scanf("%I64d %d", pos + i, treasure + i);
memset(D, -1, sizeof D);
D[1 % k] = 1;
priority_queue<Pt> pq;
for (int i = 1; i <= n; ++i) {
const int bucket = pos[i] % k;
if (D[bucket] != -1) {
if (pos[i] >= D[bucket]) {
pq.push({treasure[i], pos[i], i});
flag[i] = 1;
}
}
}
for (int id = 0; id < m; ++id) {
const int cmd = Rint();
if (cmd == 3) {
while (!pq.empty()) {
auto curr = pq.top();
if (treasure[curr.id] != curr.t) {
pq.pop();
} else {
break;
}
}
long long ans = 0;
if (!pq.empty()) {
ans = pq.top().t;
treasure[pq.top().id] = -1;
flag[pq.top().id] = 2;
pq.pop();
}
printf("%I64d\n", ans);
} else if (cmd == 2) {
const int x = Rint();
const int c = Rint();
treasure[x] -= c;
if (c != 0 && flag[x]) {
if (flag[x] == 1) {
pq.push({treasure[x], pos[x], x});
}
}
} else {
long long x;
scanf("%I64d", &x);
int ok = 1;
if (ok) {
allk[top++] = x;
fix(pq);
}
}
}
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
In this task you need to process a set of stock exchange orders and use them to create order book.
An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price pi, direction di β buy or sell, and integer qi. This means that the participant is ready to buy or sell qi stocks at price pi for one stock. A value qi is also known as a volume of an order.
All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders.
An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.
An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book.
You are given n stock exhange orders. Your task is to print order book of depth s for these orders.
Input
The input starts with two positive integers n and s (1 β€ n β€ 1000, 1 β€ s β€ 50), the number of orders and the book depth.
Next n lines contains a letter di (either 'B' or 'S'), an integer pi (0 β€ pi β€ 105) and an integer qi (1 β€ qi β€ 104) β direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order.
Output
Print no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input.
Examples
Input
6 2
B 10 3
S 50 2
S 40 1
S 50 6
B 20 4
B 25 10
Output
S 50 8
S 40 1
B 25 10
B 20 4
Note
Denote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two sell orders (50, 8), (40, 1) in the sample.
You need to print no more than two best orders for each direction, so you shouldn't print the order (10 3) having the worst price among buy orders.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n, s, p, q;
char d;
vector<tuple<char, long long, long long>> b;
cin >> n >> s;
while (n--) {
cin >> d >> p >> q;
b.push_back(make_tuple(d, p, q));
}
sort(b.begin(), b.end(),
[](const tuple<char, long long, long long> &left,
const tuple<char, long long, long long> &right) {
return get<0>(left) > get<0>(right);
});
vector<tuple<char, long long, long long>>::iterator i = b.begin(), j;
i = find_if(b.begin(), b.end(),
[](const tuple<char, long long, long long> &e) {
return get<0>(e) == 'B';
});
sort(b.begin(), i,
[](const tuple<char, long long, long long> &left,
const tuple<char, long long, long long> &right) {
return get<1>(left) < get<1>(right);
});
sort(i, b.end(),
[](const tuple<char, long long, long long> &left,
const tuple<char, long long, long long> &right) {
return get<1>(left) > get<1>(right);
});
for (j = b.begin() + 1; j < i; j++)
if (get<1>(*j) == get<1>(*(j - 1))) {
get<2>(*j) += get<2>(*(j - 1));
b.erase(j - 1);
i--;
j--;
}
for (j = i + 1; j < b.end(); j++)
if (get<1>(*j) == get<1>(*(j - 1))) {
get<2>(*j) += get<2>(*(j - 1));
b.erase(j - 1);
j--;
}
for (j = b.begin(), n = 0; j != i && n < s; j++, n++)
;
for (j = j - 1; j >= b.begin(); j--)
cout << get<0>(*j) << " " << get<1>(*j) << " " << get<2>(*j) << "\n";
for (j = i, n = 0; j != b.end() && n < s; j++, n++)
cout << get<0>(*j) << " " << get<1>(*j) << " " << get<2>(*j) << "\n";
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
You have a password which you often type β a string s of length n. Every character of this string is one of the first m lowercase Latin letters.
Since you spend a lot of time typing it, you want to buy a new keyboard.
A keyboard is a permutation of the first m Latin letters. For example, if m = 3, then there are six possible keyboards: abc, acb, bac, bca, cab and cba.
Since you type your password with one finger, you need to spend time moving your finger from one password character to the next. The time to move from character s_i to character s_{i+1} is equal to the distance between these characters on keyboard. The total time you have to spend typing the password with a keyboard is called the slowness of this keyboard.
More formaly, the slowness of keyboard is equal to β_{i=2}^{n} |pos_{s_{i-1}} - pos_{s_i} |, where pos_x is position of letter x in keyboard.
For example, if s is aacabc and the keyboard is bac, then the total time of typing this password is |pos_a - pos_a| + |pos_a - pos_c| + |pos_c - pos_a| + |pos_a - pos_b| + |pos_b - pos_c| = |2 - 2| + |2 - 3| + |3 - 2| + |2 - 1| + |1 - 3| = 0 + 1 + 1 + 1 + 2 = 5.
Before buying a new keyboard you want to know the minimum possible slowness that the keyboard can have.
Input
The first line contains two integers n and m (1 β€ n β€ 10^5, 1 β€ m β€ 20).
The second line contains the string s consisting of n characters. Each character is one of the first m Latin letters (lowercase).
Output
Print one integer β the minimum slowness a keyboard can have.
Examples
Input
6 3
aacabc
Output
5
Input
6 4
aaaaaa
Output
0
Input
15 4
abacabadabacaba
Output
16
Note
The first test case is considered in the statement.
In the second test case the slowness of any keyboard is 0.
In the third test case one of the most suitable keyboards is bacd.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long MAXN = 2e5 + 5;
const long long N = 20;
const long long INF = 1e18;
long long n, m, dp[1 << N], times[N + 1][N + 1];
char str[MAXN];
long long cost(long long s) {
long long ret = 0;
for (long long i = 1; i <= m; i++) {
if (s & (1 << (i - 1))) {
for (long long j = 1; j <= m; j++) {
if (!(s & (1 << (j - 1)))) {
ret += times[i][j];
}
}
}
}
return ret;
}
void solve() {
for (long long i = 2; i <= n; i++) {
long long u = str[i] - 'a' + 1;
long long v = str[i - 1] - 'a' + 1;
if (u == v) continue;
times[u][v]++;
times[v][u]++;
}
for (long long s = 1; s < (1 << m); s++) {
dp[s] = INF;
}
dp[0] = 0;
for (long long s = 0; s < (1 << m); s++) {
long long c = cost(s);
for (long long i = 1; i <= m; i++) {
if (!(s & (1 << (i - 1)))) {
dp[s | (1 << (i - 1))] = min(dp[s | (1 << (i - 1))], dp[s] + c);
}
}
}
printf("%lld\n", dp[(1 << m) - 1]);
}
int main() {
scanf("%lld %lld", &n, &m);
scanf("%s", str + 1);
solve();
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Nezzar has a binary string s of length n that he wants to share with his best friend, Nanako. Nanako will spend q days inspecting the binary string. At the same time, Nezzar wants to change the string s into string f during these q days, because it looks better.
It is known that Nanako loves consistency so much. On the i-th day, Nanako will inspect a segment of string s from position l_i to position r_i inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string.
After this inspection, at the i-th night, Nezzar can secretly change strictly less than half of the characters in the segment from l_i to r_i inclusive, otherwise the change will be too obvious.
Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string f at the end of these q days and nights.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each test case contains two integers n,q (1 β€ n β€ 2 β
10^5, 0 β€ q β€ 2 β
10^5).
The second line of each test case contains a binary string s of length n.
The third line of each test case contains a binary string f of length n.
Then q lines follow, i-th of them contains two integers l_i,r_i (1 β€ l_i β€ r_i β€ n) β bounds of the segment, that Nanako will inspect on the i-th day.
It is guaranteed that the sum of n for all test cases doesn't exceed 2 β
10^5, and the sum of q for all test cases doesn't exceed 2 β
10^5.
Output
For each test case, print "YES" on the single line if it is possible to avoid Nanako being unhappy and have the string f at the end of q days and nights. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
4
5 2
00000
00111
1 5
1 3
2 1
00
01
1 2
10 6
1111111111
0110001110
1 10
5 9
7 10
1 7
3 5
6 10
5 2
10000
11000
2 5
1 3
Output
YES
NO
YES
NO
Note
In the first test case, \underline{00000} β \underline{000}11 β 00111 is one of the possible sequences of string changes.
In the second test case, it can be shown that it is impossible to have the string f at the end.
### Response
```cpp
#include <bits/stdc++.h>
#define endl '\n'
#define SZ(x) ((int)x.size())
#define ALL(V) V.begin(), V.end()
#define L_B lower_bound
#define U_B upper_bound
#define pb push_back
using namespace std;
template<class T, class T1> int chkmin(T &x, const T1 &y) { return x > y ? x = y, 1 : 0; }
template<class T, class T1> int chkmax(T &x, const T1 &y) { return x < y ? x = y, 1 : 0; }
const int MAXN = (1 << 20);
string t;
struct node
{
int sum, lazy;
node() {sum = 0; lazy = -1;}
node(int val)
{
sum = val;
lazy = -1;
}
};
node temp, broken;
node merge(node l, node r)
{
temp.sum = l.sum + r.sum;
temp.lazy = -1;
return temp;
}
struct segment_tree
{
node tr[4 * MAXN];
void push(int l, int r, int idx)
{
if(tr[idx].lazy != -1)
{
tr[idx].sum = (r - l + 1) * tr[idx].lazy;
if(l != r)
{
tr[2 * idx + 1].lazy = tr[idx].lazy;
tr[2 * idx + 2].lazy = tr[idx].lazy;
}
tr[idx].lazy = -1;
}
}
void init(int l, int r, int idx)
{
if(l == r)
{
tr[idx] = node(t[l] - '0');
return;
}
int mid = (l + r) >> 1;
init(l, mid, 2 * idx + 1);
init(mid + 1, r, 2 * idx + 2);
tr[idx] = merge(tr[2 * idx + 1], tr[2 * idx + 2]);
}
void update(int qL, int qR, int val, int l, int r, int idx)
{
push(l, r, idx);
if(qL > r || l > qR)
return;
if(qL <= l && r <= qR)
{
tr[idx].lazy = val;
push(l, r, idx);
return;
}
int mid = (l + r) >> 1;
update(qL, qR, val, l, mid, 2 * idx + 1);
update(qL, qR, val, mid + 1, r, 2 * idx + 2);
tr[idx] = merge(tr[2 * idx + 1], tr[2 * idx + 2]);
}
node query(int qL, int qR, int l, int r, int idx)
{
push(l, r, idx);
if(l > qR || r < qL)
return broken;
if(qL <= l && r <= qR)
return tr[idx];
int mid = (l + r) >> 1;
return merge(query(qL, qR, l, mid, 2 * idx + 1), query(qL, qR, mid + 1, r, 2 * idx + 2));
}
} tr;
int n, q;
string s;
pair<int, int> que[MAXN];
void read() {
cin >> n >> q;
cin >> s >> t;
for(int i = 0; i < q; i++) {
cin >> que[i].first >> que[i].second;
que[i].first--;
que[i].second--;
}
}
void solve() {
tr.init(0, n - 1, 0);
for(int i = q - 1; i >= 0; i--) {
int l = que[i].first, r = que[i].second, cnt = r - l + 1;
auto nd = tr.query(l, r, 0, n - 1, 0);
int cnt1 = nd.sum;
int cnt0 = cnt - cnt1;
if(cnt1 <= (cnt - 1) / 2) {
tr.update(l, r, 0, 0, n - 1, 0);
} else if(cnt0 <= (cnt - 1) / 2) {
tr.update(l, r, 1, 0, n - 1, 0);
} else {
cout << "NO" << endl;
return;
}
}
for(int i = 0; i < n; i++) {
if(s[i] - '0' != tr.query(i, i, 0, n - 1, 0).sum) {
cout << "NO" << endl;
return;
}
}
cout << "YES" << endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int T;
cin >> T;
while(T--) {
read();
solve();
}
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
As a German University in Cairo (GUC) student and a basketball player, Herr Wafa was delighted once he heard the news. GUC is finally participating in the Annual Basketball Competition (ABC).
A team is to be formed of n players, all of which are GUC students. However, the team might have players belonging to different departments. There are m departments in GUC, numbered from 1 to m. Herr Wafa's department has number h. For each department i, Herr Wafa knows number si β how many students who play basketball belong to this department.
Herr Wafa was also able to guarantee a spot on the team, using his special powers. But since he hates floating-point numbers, he needs your help at finding the probability that he will have at least one teammate belonging to his department.
Note that every possible team containing Herr Wafa is equally probable. Consider all the students different from each other.
Input
The first line contains three integers n, m and h (1 β€ n β€ 100, 1 β€ m β€ 1000, 1 β€ h β€ m) β the number of players on the team, the number of departments in GUC and Herr Wafa's department, correspondingly.
The second line contains a single-space-separated list of m integers si (1 β€ si β€ 100), denoting the number of students in the i-th department. Note that sh includes Herr Wafa.
Output
Print the probability that Herr Wafa will have at least one teammate from his department. If there is not enough basketball players in GUC to participate in ABC, print -1. The answer will be accepted if it has absolute or relative error not exceeding 10 - 6.
Examples
Input
3 2 1
2 1
Output
1
Input
3 2 1
1 1
Output
-1
Input
3 2 1
2 2
Output
0.666667
Note
In the first example all 3 players (2 from department 1 and 1 from department 2) must be chosen for the team. Both players from Wafa's departments will be chosen, so he's guaranteed to have a teammate from his department.
In the second example, there are not enough players.
In the third example, there are three possibilities to compose the team containing Herr Wafa. In two of them the other player from Herr Wafa's department is part of the team.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m, h;
cin >> n >> m >> h;
h--;
int sum = 0;
int Q = 0;
for (int i = (0); i < (m); ++i) {
int t;
cin >> t;
if (i == h) Q = t;
sum += t;
}
if (sum < n) {
cout << "-1\n";
return 0;
}
sum--;
Q--;
n--;
double ans = 1.0;
int it1 = sum - Q - n + 1;
int up1 = sum - n;
int it2 = sum - Q + 1;
int up2 = sum;
double eps = 1e-15;
bool bx = true;
while ((it1 <= up1 || it2 <= up2) && bx) {
bx = false;
if (ans < eps) {
while (it1 <= up1 && ans < 1e9) {
ans *= it1;
it1++;
bx = true;
}
}
while (it2 <= up2 && ans > 1e-9) {
ans = 1.0 * ans / it2;
it2++;
bx = true;
}
}
while (it1 <= up1) {
ans *= 1.0 * it1;
it1++;
}
while (it2 <= up2) {
ans = 1.0 * ans / it2;
it2++;
}
printf("%.8f\n", 1.0 - ans);
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters. The length of the word will not exceed 103.
Output
Output the given word after capitalization.
Examples
Input
ApPLe
Output
ApPLe
Input
konjac
Output
Konjac
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
char word[1001];
scanf("%s", &word);
if (word[0] >= 'a' && word[0] <= 'z') {
word[0] = word[0] - 32;
}
printf("%s\n", word);
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.
Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.
Peter decided to tie his car to point P and now he is wondering what is the area of ββthe region that will be cleared from snow. Help him.
Input
The first line of the input contains three integers β the number of vertices of the polygon n (<image>), and coordinates of point P.
Each of the next n lines contains two integers β coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line.
All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
Output
Print a single real value number β the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
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
3 0 0
0 1
-1 2
1 2
Output
12.566370614359172464
Input
4 1 -1
0 0
1 2
2 0
1 1
Output
21.991148575128551812
Note
In the first sample snow will be removed from that area:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long t = 1;
long double dis(pair<long long, long long> x, pair<long long, long long> y) {
return (x.first - y.first) * (x.first - y.first) +
(x.second - y.second) * (x.second - y.second);
}
bool check(pair<long long, long long> x, pair<long long, long long> y,
pair<long long, long long> z) {
if (x.first == y.first) {
if ((x.second - z.second) * (y.second - z.second) <= 0)
return true;
else
return false;
}
if (x.second == y.second) {
if ((x.first - z.first) * (y.first - z.first) <= 0)
return true;
else
return false;
}
long double m = (x.second - y.second) / (x.first - y.first + 0.0);
long double m1 = -1 / (m);
if ((m1 * (x.first - z.first) - x.second + z.second) *
(m1 * (y.first - z.first) - y.second + z.second) <=
0)
return true;
else
return false;
}
long double shorestdis(pair<long long, long long> x,
pair<long long, long long> y,
pair<long long, long long> z) {
if (check(x, y, z) == false) {
return min(dis(x, z), dis(y, z));
}
if (x.first == y.first) {
return (z.first - x.first) * (z.first - x.first);
} else {
long double m = (x.second - y.second) / (x.first - y.first + 0.0);
long double d1 = m * z.first - z.second - m * x.first + x.second;
d1 = d1 * d1;
long double d2 = m * m + 1;
return d1 / (d2 + 0.0);
}
}
void solve() {
long long n, x, y;
pair<long long, long long> z;
vector<pair<long long, long long> > vv;
cin >> n >> z.first >> z.second;
for (long long i = 1; i < n + 1; i += 1) {
cin >> x >> y;
vv.push_back(make_pair(x, y));
}
long double r = 1e18, R = 0;
for (long long i = 0; i < n; i += 1) {
pair<long long, long long> x, y;
x = vv[i];
y = vv[(i + 1) % n];
r = min(r, shorestdis(x, y, z));
R = max(R, dis(x, z));
}
cout << setprecision(20) << 3.14159265358979323846 * (R - r);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
while (t--) solve();
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
DO YOU EXPECT ME TO FIND THIS OUT?
WHAT BASE AND/XOR LANGUAGE INCLUDES string?
DON'T BYTE OF MORE THAN YOU CAN CHEW
YOU CAN ONLY DISTORT THE LARGEST OF MATHEMATICS SO FAR
SAYING "ABRACADABRA" WITHOUT A MAGIC AND WON'T DO YOU ANY GOOD
THE LAST STACK RUPTURES. ALL DIE. OH, THE EMBARRASSMENT!
I HAVE NO ARRAY AND I MUST SCREAM
ELEMENTS MAY NOT BE STORED IN WEST HYPERSPACE
Input
The first line of input data contains a single integer n (1 β€ n β€ 10).
The second line of input data contains n space-separated integers ai (1 β€ ai β€ 11).
Output
Output a single integer.
Example
Input
4
2 5 3 1
Output
4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, MAX = -1, i;
scanf("%d", &n);
int a;
for (i = 1; i <= n; i++) {
scanf("%d", &a);
MAX = max(a, MAX);
}
printf("%d\n", a ^ MAX);
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
We consider a positive integer perfect, if and only if the sum of its digits is exactly 10. Given a positive integer k, your task is to find the k-th smallest perfect positive integer.
Input
A single line with a positive integer k (1 β€ k β€ 10 000).
Output
A single number, denoting the k-th smallest perfect integer.
Examples
Input
1
Output
19
Input
2
Output
28
Note
The first perfect integer is 19 and the second one is 28.
### 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, m, i = 18, j, temp, sum = 0;
cin >> n;
while (n) {
i++;
temp = i;
sum = 0;
while (temp) {
sum += temp % 10;
temp /= 10;
}
if (sum == 10) n--;
}
cout << i;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
There is a sequence of length 2N: A_1, A_2, ..., A_{2N}. Each A_i is either -1 or an integer between 1 and 2N (inclusive). Any integer other than -1 appears at most once in {A_i}.
For each i such that A_i = -1, Snuke replaces A_i with an integer between 1 and 2N (inclusive), so that {A_i} will be a permutation of 1, 2, ..., 2N. Then, he finds a sequence of length N, B_1, B_2, ..., B_N, as B_i = min(A_{2i-1}, A_{2i}).
Find the number of different sequences that B_1, B_2, ..., B_N can be, modulo 10^9 + 7.
Constraints
* 1 \leq N \leq 300
* A_i = -1 or 1 \leq A_i \leq 2N.
* If A_i \neq -1, A_j \neq -1, then A_i \neq A_j. (i \neq j)
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_{2N}
Output
Print the number of different sequences that B_1, B_2, ..., B_N can be, modulo 10^9 + 7.
Examples
Input
3
1 -1 -1 3 6 -1
Output
5
Input
4
7 1 8 3 5 2 6 4
Output
1
Input
10
7 -1 -1 -1 -1 -1 -1 6 14 12 13 -1 15 -1 -1 -1 -1 20 -1 -1
Output
9540576
Input
20
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 6 -1 -1 -1 -1 -1 7 -1 -1 -1 -1 -1 -1 -1 -1 -1 34 -1 -1 -1 -1 31 -1 -1 -1 -1 -1 -1 -1 -1
Output
374984201
### Response
```cpp
/* --- author: dxm --- */
#include<bits/stdc++.h>
using namespace std;
#define INF 1e9
#define Inf 1e18
#define rep(i,n) for(int (i)=0;(i)<n;i++)
#define REP(i,n) for(int (i)=1;(i)<=n;i++)
#define mp make_pair
#define pb push_back
#define fst first
#define snd second
typedef long long ll;
typedef double db;
typedef long double ldb;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<long long,long long> pll;
void qread(int &x){
int neg=1;x=0;
char c=getchar();
while(c<'0'||c>'9'){if(c=='-')neg=-1;c=getchar();}
while(c>='0'&&c<='9')x=10*x+c-'0',c=getchar();
x*=neg;
}
const int maxn=605;
const int mod=1e9+7;
int n,k;
int a[maxn],dp[2][maxn][maxn];
bool del[maxn],done[maxn];
void Add(int &a,int b){a+=b;if(a>=mod)a-=mod;}
int main(){
#ifdef FILE
freopen("FILE.in","r",stdin);
freopen("FILE.out","w",stdout);
#endif
scanf("%d",&n);
REP(i,n){
scanf("%d%d",&a[2*i-1],&a[2*i]);
if(a[2*i-1]<0&&a[2*i]<0)k++;
else if(a[2*i-1]>0&&a[2*i]>0)del[a[2*i-1]]=del[a[2*i]]=true;
else if(a[2*i-1]>0)done[a[2*i-1]]=true;
else done[a[2*i]]=true;
}
int z=0;
dp[z][0][0]=1;
REP(i,2*n){
if(del[i])continue;
rep(j,2*n+1)rep(k,n+1)dp[z^1][j][k]=0;
rep(j,2*n+1)rep(k,n+1){
int cur=dp[z][j][k];
if(!cur)continue;
if(!done[i]){
if(k)Add(dp[z^1][j][k-1],cur);
Add(dp[z^1][j][k+1],cur);
Add(dp[z^1][j+1][k],cur);
}
else{
if(j)Add(dp[z^1][j-1][k],1LL*cur*j%mod);
Add(dp[z^1][j][k+1],cur);
}
}
z^=1;
}
int ans=dp[z][0][0];
REP(i,k)ans=1LL*ans*i%mod;
printf("%d\n",ans);
#ifdef TIME
printf("Running Time = %d ms\n",int(clock()*1000.0/CLOCKS_PER_SEC));
#endif
return 0;
}
/*
Input:
-----------------
Output:
*/
``` |
### Prompt
Please formulate a cpp solution to the following problem:
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<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll memo[2020][2020];
int n;
vector<ll> a;
ll rec(int l, int len){
if(memo[l][len]>=0)return memo[l][len];
if(len <= 1)return 0;
int L = l, R = (l+len-1)%n;
if(a[L]<a[R])R = (R+n-1)%n;
else L = (L+1)%n;
return memo[l][len] = max(a[L]+rec((L+1)%n,len-2) , a[R]+rec(L,len-2));
}
int main(){
cin >> n;
a.resize(n);
for(int i=0;i<n;i++)cin >> a[i];
memset(memo,-1,sizeof(memo));
ll res = 0;
for(int i=0;i<n;i++){
res = max( res, rec((i+1)%n,n-1) + a[i] );
}
cout << res << endl;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
When the river brought Gerda to the house of the Old Lady who Knew Magic, this lady decided to make Gerda her daughter. She wants Gerda to forget about Kay, so she puts all the roses from the garden underground.
Mole, who lives in this garden, now can watch the roses without going up to the surface. Typical mole is blind, but this mole was granted as special vision by the Old Lady. He can watch any underground objects on any distance, even through the obstacles and other objects. However, the quality of the picture depends on the Manhattan distance to object being observed.
Mole wants to find an optimal point to watch roses, that is such point with integer coordinates that the maximum Manhattan distance to the rose is minimum possible.
As usual, he asks you to help.
Manhattan distance between points (x1, y1, z1) and (x2, y2, z2) is defined as |x1 - x2| + |y1 - y2| + |z1 - z2|.
Input
The first line of the input contains an integer t t (1 β€ t β€ 100 000) β the number of test cases. Then follow exactly t blocks, each containing the description of exactly one test.
The first line of each block contains an integer ni (1 β€ ni β€ 100 000) β the number of roses in the test. Then follow ni lines, containing three integers each β the coordinates of the corresponding rose. Note that two or more roses may share the same position.
It's guaranteed that the sum of all ni doesn't exceed 100 000 and all coordinates are not greater than 1018 by their absolute value.
Output
For each of t test cases print three integers β the coordinates of the optimal point to watch roses. If there are many optimal answers, print any of them.
The coordinates of the optimal point may coincide with the coordinates of any rose.
Examples
Input
1
5
0 0 4
0 0 -4
0 4 0
4 0 0
1 1 1
Output
0 0 0
Input
2
1
3 5 9
2
3 5 9
3 5 9
Output
3 5 9
3 5 9
Note
In the first sample, the maximum Manhattan distance from the point to the rose is equal to 4.
In the second sample, the maximum possible distance is 0. Note that the positions of the roses may coincide with each other and with the position of the optimal point.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const double PI = 4 * atan(1);
int T, N;
long long X[100013], Y[100013], Z[100013];
long long xmi, xma, ymi, yma, zmi, zma, smi, sma;
long long ansx, ansy, ansz;
inline bool is(long long x, int p) { return (((x % 2) + 2) % 2) == p; }
bool go(long long d) {
xmi = -8.1e18, xma = 8.1e18, ymi = -8.1e18, yma = 8.1e18, zmi = -8.1e18,
zma = 8.1e18, smi = -8.1e18, sma = 8.1e18;
for (int i = 0; i < N; i++) {
xmi = max(xmi, Y[i] + Z[i] - X[i] - d);
xma = min(xma, Y[i] + Z[i] - X[i] + d);
ymi = max(ymi, -Y[i] + Z[i] + X[i] - d);
yma = min(yma, -Y[i] + Z[i] + X[i] + d);
zmi = max(zmi, Y[i] - Z[i] + X[i] - d);
zma = min(zma, Y[i] - Z[i] + X[i] + d);
smi = max(smi, Y[i] + Z[i] + X[i] - d);
sma = min(sma, Y[i] + Z[i] + X[i] + d);
}
if (smi > sma || xmi > xma || ymi > yma || zmi > zma) return false;
for (int p = 0; p < 2; p++) {
if (smi == sma && is(smi, !p) || xmi == xma && is(xmi, !p) ||
ymi == yma && is(ymi, !p) || zmi == zma && is(zmi, !p))
continue;
long long qmi = 0;
qmi += (is(xmi, p) ? xmi : xmi + 1);
qmi += (is(ymi, p) ? ymi : ymi + 1);
qmi += (is(zmi, p) ? zmi : zmi + 1);
long long qma = 0;
qma += (is(xma, p) ? xma : xma - 1);
qma += (is(yma, p) ? yma : yma - 1);
qma += (is(zma, p) ? zma : zma - 1);
if (qmi <= qma && qmi <= sma && qma >= smi) {
if (qmi >= smi) {
ansx = (is(xmi, p) ? xmi : xmi + 1);
ansy = (is(ymi, p) ? ymi : ymi + 1);
ansz = (is(zmi, p) ? zmi : zmi + 1);
} else if (qma <= sma) {
ansx = (is(xma, p) ? xma : xma - 1);
ansy = (is(yma, p) ? yma : yma - 1);
ansz = (is(zma, p) ? zma : zma - 1);
} else {
xmi += is(xmi, !p);
xma -= is(xma, !p);
ymi += is(ymi, !p);
yma -= is(yma, !p);
zmi += is(zmi, !p);
zma -= is(zma, !p);
smi += is(smi, !p);
sma -= is(sma, !p);
if (xma + ymi + zmi < smi) {
if (xma + yma + zmi < smi) {
ansx = xma;
ansy = yma;
ansz = smi - ansx - ansy;
} else {
ansx = xma;
ansz = zmi;
ansy = smi - ansx - ansz;
}
} else {
ansy = ymi;
ansz = zmi;
ansx = smi - ymi - zmi;
}
}
return true;
}
}
return false;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> T;
while (T--) {
cin >> N;
for (int i = 0; i < N; i++) {
cin >> X[i] >> Y[i] >> Z[i];
}
long long lo = 0;
long long hi = 3.1e18;
while (lo != hi) {
long long mid = (lo + hi) / 2;
if (go(mid)) {
hi = mid;
} else {
lo = mid + 1;
}
}
go(lo);
cout << (ansy + ansz) / 2 << ' ' << (ansx + ansz) / 2 << ' '
<< (ansx + ansy) / 2 << '\n';
}
cout.flush();
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
At an arcade, Takahashi is playing a game called RPS Battle, which is played as follows:
* The player plays N rounds of Rock Paper Scissors against the machine. (See Notes for the description of Rock Paper Scissors. A draw also counts as a round.)
* Each time the player wins a round, depending on which hand he/she uses, he/she earns the following score (no points for a draw or a loss):
* R points for winning with Rock;
* S points for winning with Scissors;
* P points for winning with Paper.
* However, in the i-th round, the player cannot use the hand he/she used in the (i-K)-th round. (In the first K rounds, the player can use any hand.)
Before the start of the game, the machine decides the hand it will play in each round. With supernatural power, Takahashi managed to read all of those hands.
The information Takahashi obtained is given as a string T. If the i-th character of T (1 \leq i \leq N) is `r`, the machine will play Rock in the i-th round. Similarly, `p` and `s` stand for Paper and Scissors, respectively.
What is the maximum total score earned in the game by adequately choosing the hand to play in each round?
Constraints
* 2 \leq N \leq 10^5
* 1 \leq K \leq N-1
* 1 \leq R,S,P \leq 10^4
* N,K,R,S, and P are all integers.
* |T| = N
* T consists of `r`, `p`, and `s`.
Input
Input is given from Standard Input in the following format:
N K
R S P
T
Output
Print the maximum total score earned in the game.
Examples
Input
5 2
8 7 6
rsrpr
Output
27
Input
7 1
100 10 1
ssssppr
Output
211
Input
30 5
325 234 123
rspsspspsrpspsppprpsprpssprpsr
Output
4996
### Response
```cpp
#include"bits/stdc++.h"
using namespace std;
int main()
{
int N, K, R, S, P; string T;
cin >> N >> K >> R >> S >> P >> T;
long sum = 0;
bool isLose[100010] = { false };
for (int i = 1; i <= N; i++) {
if (isLose[i]) continue;
int next = i + K;
if (next <= N && T[i-1] == T[next-1]) isLose[next] = true;
if (T[i-1] == 'r') sum += P;
else if (T[i-1] == 's') sum += R;
else sum += S;
}
cout << sum << endl;
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game.
Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, Bob computes the values of n variables. Each variable is assigned either a constant m-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values.
Bob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose.
Input
The first line contains two integers n and m, the number of variables and bit depth, respectively (1 β€ n β€ 5000; 1 β€ m β€ 1000).
The following n lines contain descriptions of the variables. Each line describes exactly one variable. Description has the following format: name of a new variable, space, sign ":=", space, followed by one of:
1. Binary number of exactly m bits.
2. The first operand, space, bitwise operation ("AND", "OR" or "XOR"), space, the second operand. Each operand is either the name of variable defined before or symbol '?', indicating the number chosen by Peter.
Variable names are strings consisting of lowercase Latin letters with length at most 10. All variable names are different.
Output
In the first line output the minimum number that should be chosen by Peter, to make the sum of all variable values minimum possible, in the second line output the minimum number that should be chosen by Peter, to make the sum of all variable values maximum possible. Both numbers should be printed as m-bit binary numbers.
Examples
Input
3 3
a := 101
b := 011
c := ? XOR b
Output
011
100
Input
5 1
a := 1
bb := 0
cx := ? OR a
d := ? XOR ?
e := d AND bb
Output
0
0
Note
In the first sample if Peter chooses a number 0112, then a = 1012, b = 0112, c = 0002, the sum of their values is 8. If he chooses the number 1002, then a = 1012, b = 0112, c = 1112, the sum of their values is 15.
For the second test, the minimum and maximum sum of variables a, bb, cx, d and e is 2, and this sum doesn't depend on the number chosen by Peter, so the minimum Peter can choose is 0.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxN = 5005;
struct Node {
int x, y, op;
} a[maxN + 1];
int n, m;
int c1, c2;
int val[maxN + 1];
string b[maxN + 1], r1, r2;
map<string, int> id;
pair<int, int> num[maxN + 1];
inline int calc(int k, int v) {
val[0] = v;
int sum = 0;
for (int i = 1; i <= n; i++) {
int op = num[i].first, id = num[i].second;
if (!op) {
int x = val[a[id].x], y = val[a[id].y];
if (a[id].op == 0) val[i] = x | y;
if (a[id].op == 1) val[i] = x & y;
if (a[id].op == 2) val[i] = x ^ y;
} else
val[i] = b[id][m - k] - '0';
sum += val[i];
}
return sum;
}
int main() {
cin >> n >> m;
m--;
string s = "?";
id[s] = 0;
for (int i = 1; i <= n; i++) {
cin >> s;
id[s] = i;
cin >> s >> s;
if (s[0] == '0' || s[0] == '1') {
c2++;
b[c2] = s;
num[i] = make_pair(1, c2);
} else {
c1++;
a[c1].x = id[s];
cin >> s;
if (s == "OR") a[c1].op = 0;
if (s == "AND") a[c1].op = 1;
if (s == "XOR") a[c1].op = 2;
cin >> s;
a[c1].y = id[s];
num[i] = make_pair(0, c1);
}
}
for (int i = m; i >= 0; i--) {
int x = calc(i, 0), y = calc(i, 1);
if (x <= y)
r1 += '0';
else
r1 += '1';
if (x >= y)
r2 += '0';
else
r2 += '1';
}
cout << r1 << endl;
cout << r2 << endl;
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.
The game consists of m steps. On each step the current leader with index i counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.
You are given numbers l1, l2, ..., lm β indices of leaders in the beginning of each step. Child with number l1 is the first leader in the game.
Write a program which will restore a possible permutation a1, a2, ..., an. If there are multiple solutions then print any of them. If there is no solution then print -1.
Input
The first line contains two integer numbers n, m (1 β€ n, m β€ 100).
The second line contains m integer numbers l1, l2, ..., lm (1 β€ li β€ n) β indices of leaders in the beginning of each step.
Output
Print such permutation of n numbers a1, a2, ..., an that leaders in the game will be exactly l1, l2, ..., lm if all the rules are followed. If there are multiple solutions print any of them.
If there is no permutation which satisfies all described conditions print -1.
Examples
Input
4 5
2 3 1 4 4
Output
3 1 2 4
Input
3 3
3 1 2
Output
-1
Note
Let's follow leadership in the first example:
* Child 2 starts.
* Leadership goes from 2 to 2 + a2 = 3.
* Leadership goes from 3 to 3 + a3 = 5. As it's greater than 4, it's going in a circle to 1.
* Leadership goes from 1 to 1 + a1 = 4.
* Leadership goes from 4 to 4 + a4 = 8. Thus in circle it still remains at 4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int n, m, a[102], pos = 1, t[102], l[102], ans;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
memset(a, -1, sizeof a);
cin >> n >> m;
for (int i = 0; i < m; i++) cin >> l[i];
for (int i = 1; i < m; i++) {
if (l[i] > l[i - 1])
ans = l[i] - l[i - 1];
else
ans = n - (l[i - 1] - l[i]);
if (a[l[i - 1]] != -1 && a[l[i - 1]] != ans) {
cout << -1 << "\n";
return 0;
}
a[l[i - 1]] = ans;
}
for (int i = 1; i <= n; i++) t[a[i]]++;
for (int i = 1; i <= n; i++) {
while (t[pos] != 0) pos++;
if (a[i] == -1) a[i] = pos, pos++;
if (t[i] > 1) {
cout << -1 << "\n";
return 0;
}
}
for (int i = 1; i <= n; i++) cout << a[i] << " ";
cout << "\n";
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Shichi-Go-San (literally "Seven-Five-Three") is a traditional event in a certain country to celebrate the growth of seven-, five- and three-year-old children.
Takahashi is now X years old. Will his growth be celebrated in Shichi-Go-San this time?
Constraints
* 1 β€ X β€ 9
* X is an integer.
Input
Input is given from Standard Input in the following format:
X
Output
If Takahashi's growth will be celebrated, print `YES`; if it will not, print `NO`.
Examples
Input
5
Output
YES
Input
6
Output
NO
### Response
```cpp
#include<cstdio>
int main() {
int x;
scanf("%d",&x);
if(x==7||x==5||x==3) puts("YES");
else puts("NO");
}
``` |
### Prompt
Generate a cpp solution to the following problem:
After getting kicked out of her reporting job for not knowing the alphabet, Bessie has decided to attend school at the Fillet and Eggs Eater Academy. She has been making good progress with her studies and now knows the first k English letters.
Each morning, Bessie travels to school along a sidewalk consisting of m + n tiles. In order to help Bessie review, Mr. Moozing has labeled each of the first m sidewalk tiles with one of the first k lowercase English letters, spelling out a string t. Mr. Moozing, impressed by Bessie's extensive knowledge of farm animals, plans to let her finish labeling the last n tiles of the sidewalk by herself.
Consider the resulting string s (|s| = m + n) consisting of letters labeled on tiles in order from home to school. For any sequence of indices p1 < p2 < ... < pq we can define subsequence of the string s as string sp1sp2... spq. Two subsequences are considered to be distinct if they differ as strings. Bessie wants to label the remaining part of the sidewalk such that the number of distinct subsequences of tiles is maximum possible. However, since Bessie hasn't even finished learning the alphabet, she needs your help!
Note that empty subsequence also counts.
Input
The first line of the input contains two integers n and k (0 β€ n β€ 1 000 000, 1 β€ k β€ 26).
The second line contains a string t (|t| = m, 1 β€ m β€ 1 000 000) consisting of only first k lowercase English letters.
Output
Determine the maximum number of distinct subsequences Bessie can form after labeling the last n sidewalk tiles each with one of the first k lowercase English letters. Since this number can be rather large, you should print it modulo 109 + 7.
Please note, that you are not asked to maximize the remainder modulo 109 + 7! The goal is to maximize the initial value and then print the remainder.
Examples
Input
1 3
ac
Output
8
Input
0 2
aaba
Output
10
Note
In the first sample, the optimal labeling gives 8 different subsequences: "" (the empty string), "a", "c", "b", "ac", "ab", "cb", and "acb".
<image>
In the second sample, the entire sidewalk is already labeled. The are 10 possible different subsequences: "" (the empty string), "a", "b", "aa", "ab", "ba", "aaa", "aab", "aba", and "aaba". Note that some strings, including "aa", can be obtained with multiple sequences of tiles, but are only counted once.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int modx = 1e9 + 7;
long long f[2000010];
char s[1000010];
int pos[200];
int i, j, k, n, m, len, x, p;
int main() {
scanf("%d%d", &n, &m);
scanf("%s", s + 1);
len = strlen(s + 1);
f[0] = 1;
for (i = 1; i <= len; i++) {
if (pos[s[i]] == 0)
f[i] = (f[i - 1] * 2) % modx;
else
f[i] = (f[i - 1] * 2 - f[pos[s[i]] - 1] + modx) % modx;
pos[s[i]] = i;
}
for (i = len + 1; i <= len + n; i++) {
f[i] = (f[i - 1] * 2) % modx;
x = 0;
p = i;
for (j = 'a'; j < 'a' + m; j++)
if (pos[j] < p) {
p = pos[j];
x = j;
}
if (p > 0) f[i] -= f[p - 1];
f[i] = (f[i] + modx) % modx;
pos[x] = i;
}
printf("%I64d\n", f[len + n] % modx);
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
In some other world, today is the day before Christmas Eve.
Mr. Takaha is buying N items at a department store. The regular price of the i-th item (1 \leq i \leq N) is p_i yen (the currency of Japan).
He has a discount coupon, and can buy one item with the highest price for half the regular price. The remaining N-1 items cost their regular prices. What is the total amount he will pay?
Constraints
* 2 \leq N \leq 10
* 100 \leq p_i \leq 10000
* p_i is an even number.
Input
Input is given from Standard Input in the following format:
N
p_1
p_2
:
p_N
Output
Print the total amount Mr. Takaha will pay.
Examples
Input
3
4980
7980
6980
Output
15950
Input
4
4320
4320
4320
4320
Output
15120
### Response
```cpp
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N;
int sum = 0, max = 0, tmp;
for (int i = 0; i < N; ++i)
{
cin >> tmp;
sum += tmp;
if (tmp > max) max = tmp;
}
cout << sum - max / 2;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
N cells are arranged in a row. Some of them may contain tokens. You are given a string s that consists of `0`s and `1`s. If the i-th character of s is `1`, the i-th cell (from left) contains a token. Otherwise, it doesn't contain a token.
Snuke wants to perform the following operation as many times as possible. In each operation, he chooses three consecutive cells. Let's call the cells X, Y, Z from left to right. In order for the operation to be valid, both X and Z must contain tokens and Y must not contain a token. Then, he removes these two tokens and puts a new token on Y.
How many operations can he perform if he performs operations in the optimal way?
Constraints
* 1 \leq N \leq 500,000
* |s| = N
* Each character in s is either `0` or `1`.
Input
Input is given from Standard Input in the following format:
N
s
Output
Print the answer.
Examples
Input
7
1010101
Output
2
Input
50
10101000010011011110001001111110000101010111100110
Output
10
### Response
```cpp
#include <bits/stdc++.h>
#define ll long long
#define mk make_pair
using namespace std;
const int inf = 1e9;
const int N = 5e5 + 5;
char s[N];
int n, cnt, dp[N], pre[N];
int main() {
scanf("%d", &n);
scanf("%s", s + 1);
for (int i = 1; i <= n; i++) dp[i] = inf;
for (int i = 1, p = 0; i <= n; i++) {
if (s[i] == '1') cnt++;
if (s[i] == '0') p = i;
pre[i] = p;
}
for (int i = 1; i <= n; i++) {
if (s[i] == '0') dp[i] = dp[i - 1];
if (s[i] == '1') {
dp[i] = dp[i - 1] + 1;
if (s[i - 1] == '0' && i > 1) {
dp[i] = min(dp[i], dp[pre[i - 2]] + 1);
dp[i] = min(dp[i], dp[pre[i - 2] + 1] + 1);
}
if (pre[i] && s[pre[i] - 1] == '1')
dp[i] = min(dp[i], dp[pre[i] - 2] + 1);
}
}
cout << cnt - dp[n];
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Sometimes one has to spell email addresses over the phone. Then one usually pronounces a dot as dot, an at sign as at. As a result, we get something like vasyaatgmaildotcom. Your task is to transform it into a proper email address ([email protected]).
It is known that a proper email address contains only such symbols as . @ and lower-case Latin letters, doesn't start with and doesn't end with a dot. Also, a proper email address doesn't start with and doesn't end with an at sign. Moreover, an email address contains exactly one such symbol as @, yet may contain any number (possible, zero) of dots.
You have to carry out a series of replacements so that the length of the result was as short as possible and it was a proper email address. If the lengths are equal, you should print the lexicographically minimal result.
Overall, two variants of replacement are possible: dot can be replaced by a dot, at can be replaced by an at.
Input
The first line contains the email address description. It is guaranteed that that is a proper email address with all the dots replaced by dot an the at signs replaced by at. The line is not empty and its length does not exceed 100 symbols.
Output
Print the shortest email address, from which the given line could be made by the described above replacements. If there are several solutions to that problem, print the lexicographically minimal one (the lexicographical comparison of the lines are implemented with an operator < in modern programming languages).
In the ASCII table the symbols go in this order: . @ ab...z
Examples
Input
vasyaatgmaildotcom
Output
[email protected]
Input
dotdotdotatdotdotat
Output
[email protected]
Input
aatt
Output
a@t
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string w, s;
cin >> w;
char l, ll;
cout << w[0];
int a, d;
bool b = true;
a = d = 0;
for (int i = 1; i < w.length(); i++) {
if (w[i] == 'd') {
if (i + 3 != w.length()) {
s = w.substr(i, 3);
if (s.compare("dot") == 0) {
i = i + 2;
cout << '.';
} else {
cout << 'd';
}
} else {
cout << 'd';
}
} else if (b && w[i] == 'a') {
s = w.substr(i, 2);
if (s == "at") {
i += 1;
cout << '@';
b = false;
} else {
cout << 'a';
}
} else {
cout << w[i];
}
}
}
``` |
### Prompt
Create a solution in cpp for the following problem:
In order to pass the entrance examination tomorrow, Taro has to study for T more hours.
Fortunately, he can leap to World B where time passes X times as fast as it does in our world (World A).
While (X \times t) hours pass in World B, t hours pass in World A.
How many hours will pass in World A while Taro studies for T hours in World B?
Constraints
* All values in input are integers.
* 1 \leq T \leq 100
* 1 \leq X \leq 100
Input
Input is given from Standard Input in the following format:
T X
Output
Print the number of hours that will pass in World A.
The output will be regarded as correct when its absolute or relative error from the judge's output is at most 10^{-3}.
Examples
Input
8 3
Output
2.6666666667
Input
99 1
Output
99.0000000000
Input
1 100
Output
0.0100000000
### Response
```cpp
#include<stdio.h>
int main()
{
float t,x;
scanf("%d %d",&t,&x);
printf("%f\n",t/x);
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Roma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.
Roma has a choice to buy exactly one of n different weapons and exactly one of m different armor sets. Weapon i has attack modifier a_i and is worth ca_i coins, and armor set j has defense modifier b_j and is worth cb_j coins.
After choosing his equipment Roma can proceed to defeat some monsters. There are p monsters he can try to defeat. Monster k has defense x_k, attack y_k and possesses z_k coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster k can be defeated with a weapon i and an armor set j if a_i > x_k and b_j > y_k. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.
Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.
Help Roma find the maximum profit of the grind.
Input
The first line contains three integers n, m, and p (1 β€ n, m, p β€ 2 β
10^5) β the number of available weapons, armor sets and monsters respectively.
The following n lines describe available weapons. The i-th of these lines contains two integers a_i and ca_i (1 β€ a_i β€ 10^6, 1 β€ ca_i β€ 10^9) β the attack modifier and the cost of the weapon i.
The following m lines describe available armor sets. The j-th of these lines contains two integers b_j and cb_j (1 β€ b_j β€ 10^6, 1 β€ cb_j β€ 10^9) β the defense modifier and the cost of the armor set j.
The following p lines describe monsters. The k-th of these lines contains three integers x_k, y_k, z_k (1 β€ x_k, y_k β€ 10^6, 1 β€ z_k β€ 10^3) β defense, attack and the number of coins of the monster k.
Output
Print a single integer β the maximum profit of the grind.
Example
Input
2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
Output
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct T {
long long x, y, z;
bool operator<(const T &q) const {
if (x != q.x) return x < q.x;
if (y != q.y) return y < q.y;
return z < q.z;
}
bool operator>(const T &q) const {
if (x != q.x) return x > q.x;
if (y != q.y) return y > q.y;
return z > q.z;
}
};
struct SEG {
long long seg[1 << 19], la[1 << 19];
void ini(void) {
for (int i = 0; i < 1 << 19; i++) seg[i] = -100000000000000000, la[i] = 0;
}
void up(int a, long long x) {
a += (1 << 18) - 1;
seg[a] = max(seg[a], x);
while (a > 0) {
a = (a - 1) / 2;
seg[a] = max(seg[a * 2 + 1], seg[a * 2 + 2]);
}
}
void lazy(int k, int r, int l) {
seg[k] += la[k];
if (l - r > 0) {
la[k * 2 + 1] += la[k];
la[k * 2 + 2] += la[k];
}
la[k] = 0;
}
void add(int a, int b, int r, int l, int k, long long p) {
lazy(k, r, l);
if (a > l || b < r) return;
if (a <= r && l <= b) {
la[k] += p;
lazy(k, r, l);
return;
}
add(a, b, r, (r + l - 1) / 2, k * 2 + 1, p);
add(a, b, (r + l + 1) / 2, l, k * 2 + 2, p);
seg[k] = max(seg[k * 2 + 1], seg[k * 2 + 2]);
}
long long sm(void) {
lazy(0, 0, (1 << 18) - 1);
return seg[0];
}
};
long long n, m, p, ans = -100000000000000000;
pair<long long, long long> a[200005], b[200005];
T c[200005];
vector<long long> cm;
SEG seg;
int main(void) {
scanf("%lld%lld%lld", &n, &m, &p);
for (int i = 0; i < n; i++) scanf("%lld%lld", &a[i].first, &a[i].second);
for (int i = 0; i < m; i++) scanf("%lld%lld", &b[i].first, &b[i].second);
for (int i = 0; i < p; i++) scanf("%lld%lld%lld", &c[i].x, &c[i].y, &c[i].z);
sort(a, a + n);
sort(b, b + m);
sort(c, c + p);
for (int i = 0; i < m; i++) {
cm.push_back(b[i].first);
}
sort(cm.begin(), cm.end());
seg.ini();
for (int i = 0; i < m; i++) seg.up(i, -b[i].second);
int t = 0;
for (int i = 0; i < n; i++) {
while (t < p && c[t].x < a[i].first) {
if (cm.back() > c[t].y)
seg.add(upper_bound(cm.begin(), cm.end(), c[t].y) - cm.begin(), m - 1,
0, (1 << 18) - 1, 0, c[t].z);
t++;
}
ans = max(ans, seg.sm() - a[i].second);
}
printf("%lld\n", ans);
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: <image>.
The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.
You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 β€ l < r β€ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].
Note that as all numbers in sequence s are distinct, all the given definitions make sence.
Input
The first line contains integer n (1 < n β€ 105). The second line contains n distinct integers s1, s2, ..., sn (1 β€ si β€ 109).
Output
Print a single integer β the maximum lucky number among all lucky numbers of sequences s[l..r].
Examples
Input
5
5 2 1 4 3
Output
7
Input
5
9 8 3 5 7
Output
15
Note
For the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].
For the second sample you must choose s[2..5] = {8, 3, 5, 7}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long arr[100005], nxt[100005];
long long n;
void nxt_greater() {
stack<long long> s;
s.push(0);
for (long long i = 1; i < n; i++) {
while (!s.empty() && arr[s.top()] < arr[i]) {
nxt[s.top()] = i;
s.pop();
}
s.push(i);
}
while (!s.empty()) {
nxt[s.top()] = -1;
s.pop();
}
}
int main() {
cin >> n;
for (long long i = 0; i < n; i++) cin >> arr[i];
nxt_greater();
long long max_xor = 0;
for (long long i = 0; i < n; i++) {
if (nxt[i] >= 0) {
max_xor = max(max_xor, arr[i] ^ arr[nxt[i]]);
}
}
reverse(arr, arr + n);
nxt_greater();
for (long long i = 0; i < n; i++) {
if (nxt[i] >= 0) {
max_xor = max(max_xor, arr[i] ^ arr[nxt[i]]);
}
}
cout << max_xor << endl;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Joisino has a lot of red and blue bricks and a large box. She will build a tower of these bricks in the following manner.
First, she will pick a total of N bricks and put them into the box. Here, there may be any number of bricks of each color in the box, as long as there are N bricks in total. Particularly, there may be zero red bricks or zero blue bricks. Then, she will repeat an operation M times, which consists of the following three steps:
* Take out an arbitrary brick from the box.
* Put one red brick and one blue brick into the box.
* Take out another arbitrary brick from the box.
After the M operations, Joisino will build a tower by stacking the 2 \times M bricks removed from the box, in the order they are taken out. She is interested in the following question: how many different sequences of colors of these 2 \times M bricks are possible? Write a program to find the answer. Since it can be extremely large, print the count modulo 10^9+7.
Constraints
* 1 \leq N \leq 3000
* 1 \leq M \leq 3000
Input
Input is given from Standard Input in the following format:
N M
Output
Print the count of the different possible sequences of colors of 2 \times M bricks that will be stacked, modulo 10^9+7.
Examples
Input
2 3
Output
56
Input
1000 10
Output
1048576
Input
1000 3000
Output
693347555
### Response
```cpp
#include<bits/stdc++.h>
#define L long long
using namespace std;
const int q=1000000007;
int n,m,f[3010][3010][2],p;
int main()
{
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
int i,j,k;
scanf("%d%d",&n,&m);
n--;
m--;
for(i=1;i<=n;i++)
f[0][i][0]=1;
f[0][0][1]=1;
for(i=1;i<=m;i++)
{
for(j=0;j<=n;j++)
for(k=0;k<=1;k++)
f[i][j][k]=(f[i-1][j][k]*2ll+f[i-1][j+1][k]+(j?f[i-1][j-1][k]:0))%q;
f[i][0][1]=(f[i][0][1]+f[i][0][0])%q;
f[i][0][0]=0;
}
for(i=0;i<=n;i++)
p=(p+f[m][i][1])%q;
p=p*4ll%q;
printf("%d\n",p);
return 0;
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.