text
stringlengths 424
69.5k
|
---|
### Prompt
Please create a solution in cpp to the following problem:
You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer q. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circles around the hotel. Let us remind you that a number's divisor is called non-trivial if it is different from one and from the divided number itself.
The first person who can't make a move wins as he continues to lie in his warm bed under three blankets while the other one keeps running. Determine which player wins considering that both players play optimally. If the first player wins, print any winning first move.
Input
The first line contains the only integer q (1 β€ q β€ 1013).
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.
Output
In the first line print the number of the winning player (1 or 2). If the first player wins then the second line should contain another integer β his first move (if the first player can't even make the first move, print 0). If there are multiple solutions, print any of them.
Examples
Input
6
Output
2
Input
30
Output
1
6
Input
1
Output
1
0
Note
Number 6 has only two non-trivial divisors: 2 and 3. It is impossible to make a move after the numbers 2 and 3 are written, so both of them are winning, thus, number 6 is the losing number. A player can make a move and write number 6 after number 30; 6, as we know, is a losing number. Thus, this move will bring us the victory.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<int> factors(long long x) {
vector<int> ret;
for (long long i = 2; i * i <= x; i++) {
while (x % i == 0) {
x /= i;
ret.push_back(i);
}
}
if (x > 1) ret.push_back(x);
return ret;
}
int main() {
ios_base::sync_with_stdio(0);
long long x;
cin >> x;
vector<int> v = factors(x);
if (x == 1 || v.size() == 1) {
cout << 1 << endl;
cout << 0 << endl;
} else if (v.size() == 2) {
cout << 2 << endl;
} else {
cout << 1 << endl;
cout << v[0] * v[1] << endl;
}
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
There are n integers b1, b2, ..., bn written in a row. For all i from 1 to n, values ai are defined by the crows performing the following procedure:
* The crow sets ai initially 0.
* The crow then adds bi to ai, subtracts bi + 1, adds the bi + 2 number, and so on until the n'th number. Thus, ai = bi - bi + 1 + bi + 2 - bi + 3....
Memory gives you the values a1, a2, ..., an, and he now wants you to find the initial numbers b1, b2, ..., bn written in the row? Can you do it?
Input
The first line of the input contains a single integer n (2 β€ n β€ 100 000) β the number of integers written in the row.
The next line contains n, the i'th of which is ai ( - 109 β€ ai β€ 109) β the value of the i'th number.
Output
Print n integers corresponding to the sequence b1, b2, ..., bn. It's guaranteed that the answer is unique and fits in 32-bit integer type.
Examples
Input
5
6 -4 8 -2 3
Output
2 4 6 1 3
Input
5
3 -2 -1 5 6
Output
1 -3 4 11 6
Note
In the first sample test, the crows report the numbers 6, - 4, 8, - 2, and 3 when he starts at indices 1, 2, 3, 4 and 5 respectively. It is easy to check that the sequence 2 4 6 1 3 satisfies the reports. For example, 6 = 2 - 4 + 6 - 1 + 3, and - 4 = 4 - 6 + 1 - 3.
In the second sample test, the sequence 1, - 3, 4, 11, 6 satisfies the reports. For example, 5 = 11 - 6 and 6 = 6.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
;
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) cin >> a[i];
vector<int> b(n);
b[n - 1] = a[n - 1];
long long sum1 = b[n - 1], sum2 = -b[n - 1];
for (int i = n - 2; i >= 0; --i) {
if ((n - i) % 2 == 0) {
b[i] = a[i] - sum2;
sum2 += b[i];
sum1 -= b[i];
} else {
b[i] = a[i] - sum1;
sum1 += b[i];
sum2 -= b[i];
}
}
for (auto elem : b) cout << elem << " ";
cout << endl;
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state).
You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A).
You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007.
Input
The first line of input will contain two integers n, m (3 β€ n β€ 100 000, 0 β€ m β€ 100 000).
The next m lines will contain the description of the known relationships. The i-th line will contain three integers ai, bi, ci. If ci is 1, then ai and bi are in love, otherwise, they hate each other (1 β€ ai, bi β€ n, ai β bi, <image>).
Each pair of people will be described no more than once.
Output
Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007.
Examples
Input
3 0
Output
4
Input
4 4
1 2 1
2 3 1
3 4 0
4 1 0
Output
1
Input
4 4
1 2 1
2 3 1
3 4 0
4 1 1
Output
0
Note
In the first sample, the four ways are to:
* Make everyone love each other
* Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this).
In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other.
### Response
```cpp
#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:1000000000")
using namespace std;
const int maxn = (int)1e5 + 10;
int p[maxn];
int xorrrr[maxn];
int d[maxn];
vector<int> ed[maxn];
int get_parent(int v) {
if (v == p[v]) {
return v;
}
int par = get_parent(p[v]);
d[v] += d[p[v]];
d[v] %= 2;
xorrrr[v] ^= xorrrr[p[v]];
p[v] = par;
return par;
}
bool used[maxn];
const int q = (int)1e9 + 7;
void dfs(int v) {
used[v] = true;
for (int i = 0; i < (int)ed[v].size(); i++) {
int u = ed[v][i];
if (!used[u]) {
dfs(u);
}
}
}
int main() {
int n, m;
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; i++) {
p[i] = i;
xorrrr[i] = 0;
d[i] = 0;
}
for (int i = 0; i < m; i++) {
int x, y, tp;
scanf("%d %d %d", &x, &y, &tp);
ed[x].push_back(y);
ed[y].push_back(x);
int p_x = get_parent(x);
int p_y = get_parent(y);
if (p_x == p_y) {
if ((d[x] + d[y]) % 2 == 0) {
if ((xorrrr[x] ^ xorrrr[y] ^ tp) == 0) {
printf("0");
return 0;
}
} else {
if ((xorrrr[x] ^ xorrrr[y] ^ tp) == 1) {
printf("0");
return 0;
}
}
} else {
p[p_x] = p_y;
d[p_x] = (d[x] + d[y] + 1) % 2;
xorrrr[p_x] = xorrrr[x] ^ xorrrr[y] ^ tp;
}
}
int cnt = 0;
for (int i = 1; i <= n; i++) {
if (!used[i]) {
cnt++;
dfs(i);
}
}
int ans = 1;
for (int i = 1; i < cnt; i++) {
ans *= 2;
ans %= q;
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meets some condition. Let cnt(x) be the number of occurrences of number x in number d as a substring. For example, if d = 747747, then cnt(4) = 2, cnt(7) = 4, cnt(47) = 2, cnt(74) = 2. Petya wants the following condition to fulfil simultaneously: cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. Petya is not interested in the occurrences of other numbers. Help him cope with this task.
Input
The single line contains four integers a1, a2, a3 and a4 (1 β€ a1, a2, a3, a4 β€ 106).
Output
On the single line print without leading zeroes the answer to the problem β the minimum lucky number d such, that cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. If such number does not exist, print the single number "-1" (without the quotes).
Examples
Input
2 2 1 1
Output
4774
Input
4 7 3 1
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int M = 100100, mod = 1000000007;
string ans;
int main() {
int a, b, ab, ba, i, j, k, temp;
scanf("%d%d", &a, &b);
scanf("%d%d", &ab, &ba);
if (abs(ab - ba) > 1) {
printf("%s\n", "-1");
return 0;
};
if (ab > ba) {
if (a < ab || b < ab) {
printf("%s\n", "-1");
return 0;
};
for (i = 0; i < ab; i++) {
ans += '4';
a--;
ans += '7';
b--;
}
for (i = 0; i < a; i++) cout << '4';
cout << ans;
for (i = 0; i < b; i++) cout << '7';
cout << endl;
} else if (ba > ab) {
if (a < ba || b < ba) {
printf("%s\n", "-1");
return 0;
};
a--;
b--;
for (i = 0; i < ab; i++) {
ans += '4';
a--;
ans += '7';
b--;
}
cout << '7';
for (i = 0; i < a; i++) cout << '4';
cout << ans;
for (i = 0; i < b; i++) cout << '7';
cout << '4';
cout << endl;
} else {
if (a < ab || b < ab) {
printf("%s\n", "-1");
return 0;
};
if (a == ab) {
if (b == a) {
printf("%s\n", "-1");
return 0;
};
for (i = 0; i < ba; i++) cout << "74";
for (i = 0; i < b - ab; i++) cout << '7';
{
printf("%s\n", "");
return 0;
};
} else {
a--;
for (i = 0; i < a - ab; i++) cout << '4';
for (i = 0; i < ab; i++) cout << "47";
for (i = 0; i < b - ab; i++) cout << '7';
cout << '4';
}
}
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Consider a following game between two players:
There is an array b_1, b_2, ..., b_k, consisting of positive integers. Initially a chip is placed into the first cell of the array, and b_1 is decreased by 1. Players move in turns. Each turn the current player has to do the following: if the index of the cell where the chip is currently placed is x, then he or she has to choose an index y β [x, min(k, x + m)] such that b_y > 0, move the chip to the cell y and decrease b_y by 1. If it's impossible to make a valid move, the current player loses the game.
Your task is the following: you are given an array a consisting of n positive integers, and q queries to it. There are two types of queries:
* 1 l r d β for every i β [l, r] increase a_i by d;
* 2 l r β tell who is the winner of the game that is played on the subarray of a from index l to index r inclusive. Assume both players choose an optimal strategy.
Input
The first line contains three integers n, m and q (1 β€ n, q β€ 2 β
10^5, 1 β€ m β€ 5) β the number of elements in a, the parameter described in the game and the number of queries, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{12}) β the elements of array a.
Then q lines follow, each containing a query. There are two types of queries. The query of the first type is denoted by a line 1 l r d (1 β€ l β€ r β€ n, 1 β€ d β€ 10^{12}) and means that for every i β [l, r] you should increase a_i by d. The query of the second type is denoted by a line 2 l r (1 β€ l β€ r β€ n) and means that you have to determine who will win the game if it is played on the subarray of a from index l to index r (inclusive).
There is at least one query of type 2.
Output
For each query of type 2 print 1 if the first player wins in the corresponding game, or 2 if the second player wins.
Examples
Input
5 2 4
1 2 3 4 5
1 3 5 6
2 2 5
1 1 2 3
2 1 5
Output
1
1
Input
5 1 3
1 1 3 3 4
2 1 5
2 2 5
2 3 5
Output
1
2
1
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC target("avx2")
#pragma GCC optimization("O3")
#pragma GCC optimization("unroll-loops")
using namespace std;
const int N = (int)2e5 + 7;
const int K = 60;
int n, m, q;
int a[N], bl_id[N];
struct block {
int L, R;
int id;
pair<int, int> dp[2][1 << 5];
inline void build() {
if (id) {
for (int i = L; i <= R; i++) a[i] ^= 1;
}
for (int rv = 0; rv <= 1; rv++) {
for (int mask = 0; mask < (1 << m); mask++) {
int last_dp = mask, cur_ans = 0;
for (int i = R; i >= L; i--) {
if (__builtin_popcount(last_dp) < m)
cur_ans = 1;
else
cur_ans = a[i] ^ 1 ^ rv;
last_dp >>= 1;
if (cur_ans) last_dp |= 1 << (m - 1);
}
dp[rv][mask] = {cur_ans, last_dp};
}
}
id = 0;
}
int new_dp(int last_dp) { return dp[id][last_dp].second; }
} t[N / K + 1];
inline pair<int, int> slow(int l, int r, int last_dp) {
int cur_ans = 0;
for (int i = r; i >= l; i--) {
if (__builtin_popcount(last_dp) < m)
cur_ans = 1;
else
cur_ans = a[i] ^ 1 ^ t[bl_id[i]].id;
last_dp >>= 1;
if (cur_ans) last_dp |= 1 << (m - 1);
}
return {2 - cur_ans, last_dp};
}
inline int query(int l, int r) {
if (bl_id[r] - bl_id[l] <= 1) return slow(l, r, (1 << m) - 1).first;
int last_dp = slow(bl_id[r] * K, r, (1 << m) - 1).second;
for (int i = bl_id[r] - 1; i > bl_id[l]; i--) {
last_dp = t[i].new_dp(last_dp);
}
return slow(l, t[bl_id[l]].R, last_dp).first;
}
inline void update(int l, int r) {
if (bl_id[l] == bl_id[r]) {
for (int i = l; i <= r; i++) a[i] ^= 1;
t[bl_id[l]].build();
return;
}
for (int i = l; i <= t[bl_id[l]].R; i++) a[i] ^= 1;
t[bl_id[l]].build();
for (int i = t[bl_id[r]].L; i <= r; i++) a[i] ^= 1;
t[bl_id[r]].build();
for (int i = bl_id[l] + 1; i < bl_id[r]; i++) t[i].id ^= 1;
}
inline long long get_int() {
char x = getchar();
while (!isdigit(x)) x = getchar();
long long res = 0;
while (isdigit(x)) res = res * 10 + x - '0', x = getchar();
return res;
}
int main() {
n = get_int(), m = get_int(), q = get_int();
for (int i = 1; i <= n; i++) {
a[i] = get_int() & 1;
}
for (int i = 1; i <= n; i++) {
bl_id[i] = i / K;
if (!t[bl_id[i]].L) t[bl_id[i]].L = i;
t[bl_id[i]].R = i;
}
for (int i = 0; i <= n / K; i++) {
t[i].build();
}
for (int i = 1; i <= q; i++) {
int t = get_int(), l = get_int(), r = get_int();
long long x;
if (t == 1) {
x = get_int() & 1;
if (!x) continue;
update(l, r);
} else {
putchar(query(l, r) + '0');
putchar('\n');
}
}
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.
At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later.
Your task is to find the minimum number of days Arya needs to give Bran k candies before the end of the n-th day. Formally, you need to output the minimum day index to the end of which k candies will be given out (the days are indexed from 1 to n).
Print -1 if she can't give him k candies during n given days.
Input
The first line contains two integers n and k (1 β€ n β€ 100, 1 β€ k β€ 10000).
The second line contains n integers a1, a2, a3, ..., an (1 β€ ai β€ 100).
Output
If it is impossible for Arya to give Bran k candies within n days, print -1.
Otherwise print a single integer β the minimum number of days Arya needs to give Bran k candies before the end of the n-th day.
Examples
Input
2 3
1 2
Output
2
Input
3 17
10 10 10
Output
3
Input
1 9
10
Output
-1
Note
In the first sample, Arya can give Bran 3 candies in 2 days.
In the second sample, Arya can give Bran 17 candies in 3 days, because she can give him at most 8 candies per day.
In the third sample, Arya can't give Bran 9 candies, because she can give him at most 8 candies per day and she must give him the candies within 1 day.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
template <typename T, typename U>
inline void amin(T& x, U y) {
if (y < x) x = y;
}
template <typename T, typename U>
inline void amax(T& x, U y) {
if (x < y) x = y;
}
template <typename T>
inline void write(T x) {
int i = 20;
char buf[21];
buf[20] = '\n';
do {
buf[--i] = x % 10 + '0';
x /= 10;
} while (x);
do {
putchar(buf[i]);
} while (buf[i++] != '\n');
}
template <typename T>
inline T readInt() {
T n = 0, s = 1;
char p = getchar();
if (p == '-') s = -1;
while ((p < '0' || p > '9') && p != EOF && p != '-') p = getchar();
if (p == '-') s = -1, p = getchar();
while (p >= '0' && p <= '9') {
n = (n << 3) + (n << 1) + (p - '0');
p = getchar();
}
return n * s;
}
class Debugger {
public:
Debugger(const std::string& _separator = " - ")
: first(true), separator(_separator) {}
template <typename ObjectType>
Debugger& operator,(const ObjectType& v) {
if (!first)
std:
cerr << separator;
std::cerr << v;
first = false;
return *this;
}
~Debugger() {
std:
cerr << endl;
}
private:
bool first;
std::string separator;
};
template <typename T>
void write_vector(const vector<T>& V) {
cout << "The numbers in the vector are: " << endl;
for (int i = 0; i < V.size(); i++) cout << V[i] << " ";
}
int main() {
int n, k;
cin >> n >> k;
unsigned long long int leftover = 0;
int cand;
int days = 0;
for (int i = 0; i < n; i++) {
cin >> cand;
if (k > 0) {
days++;
if (cand > 8) {
leftover += (cand - 8);
k -= 8;
} else {
k = k - cand;
if (leftover > 0) {
int left = 8 - cand;
if (leftover > left) {
leftover -= left;
k -= left;
} else {
k -= leftover;
leftover -= leftover;
}
}
}
}
}
if (k > 0)
cout << "-1";
else
cout << days;
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
A sequence of non-negative integers a1, a2, ..., an of length n is called a wool sequence if and only if there exists two integers l and r (1 β€ l β€ r β€ n) such that <image>. In other words each wool sequence contains a subsequence of consecutive elements with xor equal to 0.
The expression <image> means applying the operation of a bitwise xor to numbers x and y. The given operation exists in all modern programming languages, for example, in languages C++ and Java it is marked as "^", in Pascal β as "xor".
In this problem you are asked to compute the number of sequences made of n integers from 0 to 2m - 1 that are not a wool sequence. You should print this number modulo 1000000009 (109 + 9).
Input
The only line of input contains two space-separated integers n and m (1 β€ n, m β€ 105).
Output
Print the required number of sequences modulo 1000000009 (109 + 9) on the only line of output.
Examples
Input
3 2
Output
6
Note
Sequences of length 3 made of integers 0, 1, 2 and 3 that are not a wool sequence are (1, 3, 1), (1, 2, 1), (2, 1, 2), (2, 3, 2), (3, 1, 3) and (3, 2, 3).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int const nMax = 1010;
int const base = 10;
long long mod = 1000000009;
long long exp(int n) {
if (n == 0) return 1;
long long d = exp(n / 2);
d = d * d;
d %= mod;
if (n & 1)
return d * 2 % mod;
else
return d % mod;
}
long long n, m;
int main() {
cin >> n >> m;
long long ans = 1;
long long p = exp(m);
p--;
if (p < 0) p += mod;
while (n--) {
ans *= p;
ans %= mod;
p--;
if (p < 0) p += mod;
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
In this task you have to write a program dealing with nonograms on fields no larger than 5 Γ 20.
Simplified nonogram is a task where you have to build such field (each cell is either white or black) that satisfies the given information about rows and columns. For each row and each column the number of contiguous black segments is specified.
For example if size of the field is n = 3, m = 5, Π°nd numbers of contiguous black segments in rows are: [2, 3, 2] and in columns are: [1, 0, 1, 2, 1] then the solution may look like:
<image>
It is guaranteed that on each test in the testset there exists at least one solution.
Input
In the first line there follow two integers n, m (1 β€ n β€ 5, 1 β€ m β€ 20) β number of rows and number of columns respectively.
Second line contains n integers a1, a2, ..., an where ai is the number of contiguous black segments in i-th row of the field.
Similarly, third line contains m integers b1, b2, ..., bm where bi is the number of contiguous black segments in the i-th column of the field.
It is guaranteed that there exists at least one solution.
Output
Output any possible solution. Output should consist of n lines each containing m characters. Denote white cell as "." and black cell as "*".
Examples
Input
3 5
2 3 2
1 0 1 2 1
Output
*.**.
*.*.*
*..**
Input
3 3
2 1 2
2 1 2
Output
*.*
.*.
*.*
Input
3 3
1 0 1
2 2 2
Output
***
...
***
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m;
vector<int> ans;
int row[5], col[20];
vector<int> v[3];
bool vis[20][11][11][11][11][11][1 << 5];
bool solve(int x, int r1, int r2, int r3, int r4, int r5, int mask) {
if (x == m) {
if (r1 + r2 + r3 + r4 + r5) return false;
return true;
}
bool &ret = vis[x][r1][r2][r3][r4][r5][mask];
if (ret) return false;
ret = true;
int a[5];
a[0] = r1, a[1] = r2, a[2] = r3, a[3] = r4, a[4] = r5;
int h = col[x];
for (int i = 0; i < v[h].size(); i++) {
int b[5] = {0};
int now = v[h][i];
for (int j = 0; j < n; j++) b[j] = a[j];
bool flag = true;
for (int j = 0; j < n; j++) {
if ((mask & (1 << j)) == 0 && now & (1 << j)) b[j]--;
if (b[j] < 0) {
flag = false;
break;
}
}
if (flag) {
if (solve(x + 1, b[0], b[1], b[2], b[3], b[4], now)) {
ans.push_back(now);
return true;
}
}
}
return false;
}
int main() {
scanf("%d", &n);
;
scanf("%d", &m);
;
for (int i = 0; i < n; i++) scanf("%d", &row[i]);
;
for (int i = 0; i < m; i++) scanf("%d", &col[i]);
;
for (int i = 0; i < 1 << n; i++) {
int c = 0, pre = 0;
for (int j = 0; j < n; j++) {
if (i & (1 << j) && !pre) {
pre = 1;
c++;
} else
pre = bool(i & (1 << j));
}
v[c].push_back(i);
}
solve(0, row[0], row[1], row[2], row[3], row[4], 0);
reverse(ans.begin(), ans.end());
for (int i = 0; i < n; i++) {
for (int j = 0; j < ans.size(); j++) {
if (ans[j] & (1 << i))
cout << '*';
else
cout << '.';
}
cout << "\n";
}
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
You are given an array a of length n, and an integer x. You can perform the following operation as many times as you would like (possibly zero): replace two adjacent elements of the array by their sum. For example, if the initial array was [3, 6, 9], in a single operation one can replace the last two elements by their sum, yielding an array [3, 15], or replace the first two elements to get an array [9, 9]. Note that the size of the array decreases after each operation.
The beauty of an array b=[b_1, β¦, b_k] is defined as β_{i=1}^k \leftβ (b_i)/(x) \rightβ, which means that we divide each element by x, round it up to the nearest integer, and sum up the resulting values. For example, if x = 3, and the array is [4, 11, 6], the beauty of the array is equal to \leftβ 4/3 \rightβ + \leftβ 11/3 \rightβ + \leftβ 6/3 \rightβ = 2 + 4 + 2 = 8.
Please determine the minimum and the maximum beauty you can get by performing some operations on the original array.
Input
The first input line contains a single integer t β the number of test cases (1 β€ t β€ 1000).
The first line of each test case contains two integers n and x (1 β€ n β€ 10^5, 1 β€ x β€ 10^9).
The next line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9), the elements of the array a.
It is guaranteed that the sum of values of n over all test cases does not exceed 10^5.
Output
For each test case output two integers β the minimal and the maximal possible beauty.
Example
Input
2
3 3
3 6 9
3 3
6 4 11
Output
6 6
7 8
Note
In the first test case the beauty of the array does not change if we perform any operations.
In the second example we can leave the array unchanged to attain the maximum beauty, and to get the minimum beauty one can replace two elements 4 and 11 with their sum, yielding an array [6, 15], which has its beauty equal to 7.
### Response
```cpp
//BISMILLAHIR RAHMANIR RAHIM
#include<bits/stdc++.h>
//Solution Idea
//
using namespace std;
typedef long long int ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
typedef pair<int,int> pii;
typedef pair <pii , int> piii;
typedef pair<double, int > pdi;
typedef pair<ll, ll> pll;
typedef vector<pii> vii;
typedef vector<pll> vll;
typedef pair < ll , pll > plll;
typedef pair < pll , pll > pllll;
#define all(v) (v).begin(), (v).end()
#define KeepUnique(v) (v).erase( unique(all(v)), v.end() )
#define PB push_back
#define F first
#define S second
#define MP make_pair
#define endl '\n'
#define mx 100005
#define mx1 100005
#define mx2 200005
#define mx3 300005
#define WHITE 0
#define RED 1
#define BLACK 2
#define bp __builtin_popcountll
#define fraction() cout.unsetf(ios::floatfield); cout.precision(20); cout.setf(ios::fixed,ios::floatfield);
#define hi cout<<"Dhukse " << endl;
#define si(x) scanf("%d",&x)
#define sii(x,y) scanf("%d %d",&x,&y)
#define siii(x,y,z) scanf("%d %d %d",&x,&y,&z)
#define sl(x) scanf("%lld",&x)
#define sll(x,y) scanf("%lld %lld",&x,&y)
#define slll(x,y,z) scanf("%lld %lld %lld",&x,&y,&z)
const double PI = acos(-1);
const double eps = 1e-12;
const int inf = 2000000000;
const ll infLL = (ll)1e18;
ll MOD = 1000000007;
int MOD1 = 1000000007;
int MOD2 = 1000000009;
#define harmonic(n) 0.57721566490153286l(Eulers-Mascharoni constant)+log(n) ( 1/1 + 1/2 + .... + 1/n );
#define mem(a,b) memset(a, b, sizeof(a) )
#define gcd(a,b) __gcd(a,b)
#define lcm(a,b) (a*(b/gcd(a,b)))
#define sqr(a) ((a) * (a))
#define optimize() ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
typedef vector<int>::iterator vit;
typedef set<int>::iterator sit;
inline bool checkBit(ll n, ll i) { return n&(1LL<<i); }
inline ll setBit(ll n, ll i) { return n|(1LL<<i);; }
inline ll resetBit(ll n, ll i) { return n&(~(1LL<<i)); }
#define LSBIT(X) ((X) & (-(X)))
#define CLEARLSBIT(X) ((X) & ((X) - 1))
int dx[] = {0, 0, +1, -1};
int dy[] = {+1, -1, 0, 0};
//int dx[] = {+1, 0, -1, 0, +1, +1, -1, -1};
//int dy[] = {0, +1, 0, -1, +1, -1, +1, -1};
inline bool EQ(double a, double b) { return fabs(a-b) < 1e-9; }
inline bool isLeapYear(ll year) { return (year%400==0) || (year%4==0 && year%100!=0); }
inline void normal(ll &a) { a %= MOD; (a < 0) && (a += MOD); }
inline ll modMul(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); return (a*b)%MOD; }
inline ll modAdd(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); return (a+b)%MOD; }
inline ll modSub(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); a -= b; normal(a); return a; }
inline ll modPow(ll b, ll p) { ll r = 1LL; while(p) { if(p&1) r = modMul(r, b); b = modMul(b, b); p >>= 1LL; } return r; }
inline ll modDiv(ll a, ll b) { return modMul(a, modPow(b, MOD-2)); }
bool comp( const pair < ll , pll > &p1 , const pair < ll , pll > &p2 ){ return p1.F > p2.F ;}
bool comp1( const pll &p1 , const pll &p2 ){
if( p1.F == p2.F ){
return p1.S > p2.S;
}
return p1.F < p2.F ;
}
ll converter( string a ){
ll i , mul = 1LL , r , t ,ans = 0LL;if( a.length() == 0 )return 0;for( i = a.length() - 1 ; i >= 0 ; i-- ){
t = a[i] - '0';r = t%10;ans += (mul*r);mul = mul*10;
}
return ans;
}
int msb(unsigned x) {
union { double a; int b[2]; };
a = x;
return (b[1] >> 20) - 1023;
}
//
//debug
#ifndef ONLINE_JUDGE
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 << "{";
for(auto 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 << "[";
for(auto it = v.begin(); it != v.end(); ++it) {
if( it != v.begin() ) os << ", ";
os << *it;
}
return os << "]";
}
template < typename T >
ostream &operator << ( ostream & os, const multiset< T > &v ) {
os << "[";
for(auto 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 << "[";
for(auto it = v.begin(); it != v.end(); ++it) {
if( it != v.begin() ) os << ", ";
os << it -> first << " = " << it -> second ;
}
return os << "]";
}
#define dbg(args...) do {cerr << #args << " : "; faltu(args); } while(0)
void faltu () {
cerr << endl;
}
template <typename T>
void faltu( T a[], int n ) {
for(int i = 0; i < n; ++i) cerr << a[i] << ' ';
cerr << endl;
}
template <typename T, typename ... hello>
void faltu( T arg, const hello &... rest) {
cerr << arg << ' ';
faltu(rest...);
}
#else
#define dbg(args...)
#endif
const int MAX = 100005;
ll n, x , a[MAX];
int main() {
optimize();
fraction();
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin) ;
freopen("output.txt","w",stdout);
#endif
int t;
cin >> t;
while(t--) {
cin >> n >> x;
ll sum = 0;
ll a1 = 0 , a2 = 0;
for(int i = 1 ; i <= n; ++i) {
cin >> a[i];
sum += a[i];
a1 += ((a[i] + (x-1))/x);
}
cout << (sum + x - 1)/x << " " << a1 << endl;
}
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Olya wants to buy a custom wardrobe. It should have n boxes with heights a1, a2, ..., an, stacked one on another in some order. In other words, we can represent each box as a vertical segment of length ai, and all these segments should form a single segment from 0 to <image> without any overlaps.
Some of the boxes are important (in this case bi = 1), others are not (then bi = 0). Olya defines the convenience of the wardrobe as the number of important boxes such that their bottom edge is located between the heights l and r, inclusive.
You are given information about heights of the boxes and their importance. Compute the maximum possible convenience of the wardrobe if you can reorder the boxes arbitrarily.
Input
The first line contains three integers n, l and r (1 β€ n β€ 10 000, 0 β€ l β€ r β€ 10 000) β the number of boxes, the lowest and the highest heights for a bottom edge of an important box to be counted in convenience.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 10 000) β the heights of the boxes. It is guaranteed that the sum of height of all boxes (i. e. the height of the wardrobe) does not exceed 10 000: Olya is not very tall and will not be able to reach any higher.
The second line contains n integers b1, b2, ..., bn (0 β€ bi β€ 1), where bi equals 1 if the i-th box is important, and 0 otherwise.
Output
Print a single integer β the maximum possible convenience of the wardrobe.
Examples
Input
5 3 6
3 2 5 1 2
1 1 0 1 0
Output
2
Input
2 2 5
3 6
1 1
Output
1
Note
In the first example you can, for example, first put an unimportant box of height 2, then put an important boxes of sizes 1, 3 and 2, in this order, and then the remaining unimportant boxes. The convenience is equal to 2, because the bottom edges of important boxes of sizes 3 and 2 fall into the range [3, 6].
In the second example you have to put the short box under the tall box.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = (int)1e4 + 1, maxd = 1 << 16 | 1;
int n, m, L, R, a[maxn], b[maxn], s[maxn], lbt[maxd], mx;
bitset<maxn> msk;
int lowBit(bitset<maxn> const &msk, size_t const &low, size_t const &upp) {
unsigned long long *seq = (unsigned long long *)&msk;
size_t pL = low >> 6, pR = upp >> 6;
size_t qL = low & 63, qR = upp & 63;
for (size_t i = pL; i <= pR; ++i) {
unsigned long long val = seq[i];
if (i == pR && qR < 63)
val &= (static_cast<unsigned long long>(1) << (qR + 1)) - 1;
if (i == pL) val = (val >> qL) << qL;
if (val != static_cast<unsigned long long>(0)) {
size_t ret = i << 6;
if ((val & ((static_cast<unsigned long long>(1) << 32) - 1)) ==
static_cast<unsigned long long>(0)) {
val >>= 32;
ret |= 32;
}
if ((val & ((static_cast<unsigned long long>(1) << 16) - 1)) ==
static_cast<unsigned long long>(0)) {
val >>= 16;
ret |= 16;
}
return ret + lbt[static_cast<int>(
val & ((static_cast<unsigned long long>(1) << 16) - 1))];
}
}
return -1;
}
int main() {
lbt[0] = -1;
for (int i = 1; i < maxd; ++i) lbt[i] = i & 1 ? 0 : lbt[i >> 1] + 1;
scanf("%d%d%d", &n, &L, &R);
for (int i = 1; i <= n; ++i) scanf("%d", a + i);
int tp = n;
n = 0;
msk.set(0);
for (int i = 1, typ; i <= tp; ++i) {
scanf("%d", &typ);
if (typ) {
a[++n] = a[i];
} else {
b[++m] = a[i];
msk |= msk << a[i];
}
}
sort(a + 1, a + n + 1);
for (int i = 1; i <= n; ++i) s[i] = s[i - 1] + a[i];
for (int i = n; i > mx; --i) {
int pos = lowBit(msk, L, R);
if (pos != -1) {
int idx = upper_bound(s, s + i + 1, R - pos) - s - 1;
mx = max(mx, idx);
}
msk |= msk << a[i];
}
msk.reset();
msk.set(0);
for (int i = mx + 1; i <= n; ++i) msk |= msk << a[i];
msk.reset(s[n] - s[mx]);
for (int i = 1; i <= m; ++i) msk |= msk << b[i];
if (lowBit(msk, L, R - s[mx]) != -1) ++mx;
printf("%d\n", mx);
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that:
1. choose any non-empty string from strings s1, s2, ..., sn;
2. choose an arbitrary character from the chosen string and write it on a piece of paper;
3. remove the chosen character from the chosen string.
Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.
There are other limitations, though. For each string si you know number ai β the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).
Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
Input
The first line of the input contains string t β the string that you need to build.
The second line contains a single integer n (1 β€ n β€ 100) β the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 β€ ai β€ 100). Number ai represents the maximum number of characters that can be deleted from string si.
All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
Output
Print a single number β the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
Examples
Input
bbaze
3
bzb 2
aeb 3
ba 10
Output
8
Input
abacaba
4
aba 2
bcc 1
caa 2
bbb 5
Output
18
Input
xyz
4
axx 8
za 1
efg 4
t 1
Output
-1
Note
Notes to the samples:
In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" ΠΈ "b" with price 2 rubles. The price of the string t in this case is 2Β·1 + 3Β·2 = 8.
In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2Β·1 + 1Β·2 + 2Β·3 + 2Β·4 = 18.
In the third sample the solution doesn't exist because there is no character "y" in given strings.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int ar[128][128], n, ans, N, mark[128], b = 1;
int path(int node, int flow) {
if (node == N - 1) return flow;
mark[node] = b;
for (int i = 0; i < N; i++)
if (mark[i] < b && ar[node][i]) {
int tmp = path(i, min(flow, ar[node][i]));
if (tmp) {
ar[node][i] -= tmp;
ar[i][node] += tmp;
return tmp;
}
}
return 0;
}
int main() {
char s[256];
cin >> s >> n;
N = n + 28;
int len = strlen(s);
for (int i = 0; i < len; i++) ar[n + 1 + s[i] - 'a'][N - 1]++;
for (int i = 0; i < n; i++) {
cin >> s >> ar[0][i + 1];
len = strlen(s);
for (int j = 0; j < len; j++) ar[i + 1][n + 1 + s[j] - 'a']++;
}
while (true) {
if (!path(0, 1 << 30)) break;
b++;
}
for (int i = 0; i < n; i++)
for (int j = 0; j < 26; j++) ans += (i + 1) * ar[n + 1 + j][i + 1];
for (int i = n + 1; i <= n + 26; i++)
if (ar[i][N - 1]) ans = -1;
cout << ans;
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β
LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 β€ n, m β€ 5000) β lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters β string A.
The third line contains a string consisting of m lowercase Latin letters β string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 β
|abb|) - |abb| - |abab| = 4 β
3 - 3 - 4 = 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m;
long long dp[5001][5001];
string a, b;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
cin >> a >> b;
long long ans = 0;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
if (a[i - 1] == b[j - 1])
dp[i][j] = dp[i - 1][j - 1] + 2;
else
dp[i][j] = max({0LL, dp[i - 1][j] - 1, dp[i][j - 1] - 1});
ans = max(ans, dp[i][j]);
}
cout << ans;
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
Petya studies at university. The current academic year finishes with n special days. Petya needs to pass m exams in those special days. The special days in this problem are numbered from 1 to n.
There are three values about each exam:
* s_i β the day, when questions for the i-th exam will be published,
* d_i β the day of the i-th exam (s_i < d_i),
* c_i β number of days Petya needs to prepare for the i-th exam. For the i-th exam Petya should prepare in days between s_i and d_i-1, inclusive.
There are three types of activities for Petya in each day: to spend a day doing nothing (taking a rest), to spend a day passing exactly one exam or to spend a day preparing for exactly one exam. So he can't pass/prepare for multiple exams in a day. He can't mix his activities in a day. If he is preparing for the i-th exam in day j, then s_i β€ j < d_i.
It is allowed to have breaks in a preparation to an exam and to alternate preparations for different exams in consecutive days. So preparation for an exam is not required to be done in consecutive days.
Find the schedule for Petya to prepare for all exams and pass them, or report that it is impossible.
Input
The first line contains two integers n and m (2 β€ n β€ 100, 1 β€ m β€ n) β the number of days and the number of exams.
Each of the following m lines contains three integers s_i, d_i, c_i (1 β€ s_i < d_i β€ n, 1 β€ c_i β€ n) β the day, when questions for the i-th exam will be given, the day of the i-th exam, number of days Petya needs to prepare for the i-th exam.
Guaranteed, that all the exams will be in different days. Questions for different exams can be given in the same day. It is possible that, in the day of some exam, the questions for other exams are given.
Output
If Petya can not prepare and pass all the exams, print -1. In case of positive answer, print n integers, where the j-th number is:
* (m + 1), if the j-th day is a day of some exam (recall that in each day no more than one exam is conducted),
* zero, if in the j-th day Petya will have a rest,
* i (1 β€ i β€ m), if Petya will prepare for the i-th exam in the day j (the total number of days Petya prepares for each exam should be strictly equal to the number of days needed to prepare for it).
Assume that the exams are numbered in order of appearing in the input, starting from 1.
If there are multiple schedules, print any of them.
Examples
Input
5 2
1 3 1
1 5 1
Output
1 2 3 0 3
Input
3 2
1 3 1
1 2 1
Output
-1
Input
10 3
4 7 2
1 10 3
8 9 1
Output
2 2 2 1 1 0 4 3 4 4
Note
In the first example Petya can, for example, prepare for exam 1 in the first day, prepare for exam 2 in the second day, pass exam 1 in the third day, relax in the fourth day, and pass exam 2 in the fifth day. So, he can prepare and pass all exams.
In the second example, there are three days and two exams. So, Petya can prepare in only one day (because in two other days he should pass exams). Then Petya can not prepare and pass all exams.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct node {
int s, d, c;
int pos;
} dat[105];
int vis[105];
bool cmp(node a, node b) { return a.s > b.s; }
int main() {
int n, m, flag = 0;
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &dat[i].s, &dat[i].d, &dat[i].c);
dat[i].pos = i;
vis[dat[i].d] = m + 1;
}
sort(dat + 1, dat + m + 1, cmp);
for (int i = 1; i <= m; i++) {
int x = dat[i].d - 1, y = dat[i].c;
while (y && x) {
if (vis[x] == 0) {
vis[x] = dat[i].pos;
y--;
}
x--;
}
if (y != 0 || x + 1 < dat[i].s) {
flag = 1;
break;
}
}
if (flag)
printf("-1\n");
else {
for (int i = 1; i <= n; i++) {
printf("%d ", vis[i]);
}
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters.
For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store).
Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance.
Input
First line contains an integer n (1 β€ n β€ 100) β number of visits.
Second line contains an integer a (1 β€ a β€ 100) β distance between Rabbit's and Owl's houses.
Third line contains an integer b (1 β€ b β€ 100) β distance between Rabbit's and Eeyore's houses.
Fourth line contains an integer c (1 β€ c β€ 100) β distance between Owl's and Eeyore's houses.
Output
Output one number β minimum distance in meters Winnie must go through to have a meal n times.
Examples
Input
3
2
3
1
Output
3
Input
1
2
3
5
Output
0
Note
In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3.
In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, a, b, c, d;
scanf("%d%d%d%d", &n, &a, &b, &c);
if (n == 1)
printf("0");
else if (c > a || c > b) {
printf("%d", (n - 1) * min(a, b));
} else {
printf("%d", min(a, b) + c * (n - 2));
}
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Wilbur the pig is tinkering with arrays again. He has the array a1, a2, ..., an initially consisting of n zeros. At one step, he can choose any index i and either add 1 to all elements ai, ai + 1, ... , an or subtract 1 from all elements ai, ai + 1, ..., an. His goal is to end up with the array b1, b2, ..., bn.
Of course, Wilbur wants to achieve this goal in the minimum number of steps and asks you to compute this value.
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the length of the array ai. Initially ai = 0 for every position i, so this array is not given in the input.
The second line of the input contains n integers b1, b2, ..., bn ( - 109 β€ bi β€ 109).
Output
Print the minimum number of steps that Wilbur needs to make in order to achieve ai = bi for all i.
Examples
Input
5
1 2 3 4 5
Output
5
Input
4
1 2 2 1
Output
3
Note
In the first sample, Wilbur may successively choose indices 1, 2, 3, 4, and 5, and add 1 to corresponding suffixes.
In the second sample, Wilbur first chooses indices 1 and 2 and adds 1 to corresponding suffixes, then he chooses index 4 and subtract 1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n, x = 0, k, o = 0;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> k;
o += abs(k - x);
x = k;
}
cout << o << endl;
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
You are given n strings s_1, s_2, β¦, s_n consisting of lowercase Latin letters.
In one operation you can remove a character from a string s_i and insert it to an arbitrary position in a string s_j (j may be equal to i). You may perform this operation any number of times. Is it possible to make all n strings equal?
Input
The first line contains t (1 β€ t β€ 10): the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 1000): the number of strings.
n lines follow, the i-th line contains s_i (1 β€ \lvert s_i \rvert β€ 1000).
The sum of lengths of all strings in all test cases does not exceed 1000.
Output
If it is possible to make the strings equal, print "YES" (without quotes).
Otherwise, print "NO" (without quotes).
You can output each character in either lowercase or uppercase.
Example
Input
4
2
caa
cbb
3
cba
cba
cbb
4
ccab
cbac
bca
acbcc
4
acb
caf
c
cbafc
Output
YES
NO
YES
NO
Note
In the first test case, you can do the following:
* Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively.
* Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab".
In the second test case, it is impossible to make all n strings equal.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void swap(int &a, int &b) {
int temp = a;
a = b;
b = a;
}
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
map<char, int> m;
for (int i = 0; i < n; i++) {
string s;
cin >> s;
for (int j = 0; j < s.length(); j++) m[s[j]]++;
}
bool yes = 1;
for (auto x : m) {
if (x.second % n != 0) {
yes = 0;
break;
}
}
if (yes)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
There are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that:
* Alice will get a (a > 0) candies;
* Betty will get b (b > 0) candies;
* each sister will get some integer number of candies;
* Alice will get a greater amount of candies than Betty (i.e. a > b);
* all the candies will be given to one of two sisters (i.e. a+b=n).
Your task is to calculate the number of ways to distribute exactly n candies between sisters in a way described above. Candies are indistinguishable.
Formally, find the number of ways to represent n as the sum of n=a+b, where a and b are positive integers and a>b.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The only line of a test case contains one integer n (1 β€ n β€ 2 β
10^9) β the number of candies you have.
Output
For each test case, print the answer β the number of ways to distribute exactly n candies between two sisters in a way described in the problem statement. If there is no way to satisfy all the conditions, print 0.
Example
Input
6
7
1
2
3
2000000000
763243547
Output
3
0
0
1
999999999
381621773
Note
For the test case of the example, the 3 possible ways to distribute candies are:
* a=6, b=1;
* a=5, b=2;
* a=4, b=3.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
long long t;
cin >> t;
while (t--) {
long long n;
cin >> n;
if (n <= 2)
cout << 0 << endl;
else {
if (n % 2 == 0)
cout << n / 2 - 1 << endl;
else
cout << n / 2 << endl;
}
}
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Everything is great about Ilya's city, except the roads. The thing is, the only ZooVille road is represented as n holes in a row. We will consider the holes numbered from 1 to n, from left to right.
Ilya is really keep on helping his city. So, he wants to fix at least k holes (perharps he can fix more) on a single ZooVille road.
The city has m building companies, the i-th company needs ci money units to fix a road segment containing holes with numbers of at least li and at most ri. The companies in ZooVille are very greedy, so, if they fix a segment containing some already fixed holes, they do not decrease the price for fixing the segment.
Determine the minimum money Ilya will need to fix at least k holes.
Input
The first line contains three integers n, m, k (1 β€ n β€ 300, 1 β€ m β€ 105, 1 β€ k β€ n). The next m lines contain the companies' description. The i-th line contains three integers li, ri, ci (1 β€ li β€ ri β€ n, 1 β€ ci β€ 109).
Output
Print a single integer β the minimum money Ilya needs to fix at least k holes.
If it is impossible to fix at least k holes, print -1.
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
10 4 6
7 9 11
6 9 13
7 7 7
3 5 6
Output
17
Input
10 7 1
3 4 15
8 9 8
5 6 8
9 10 6
1 4 2
1 4 10
8 10 13
Output
2
Input
10 1 9
5 10 14
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 320;
const long long INF = 0x0123456789ABCDEFLL;
long long d[MAXN][MAXN], dp[MAXN][MAXN];
int main() {
int n, m, k, a, b, c;
long long ans;
scanf("%d%d%d", &n, &m, &k);
fill(d[0], d[n + 1], INF);
for (int i = 0; i < m; ++i) {
scanf("%d%d%d", &a, &b, &c);
--a;
d[a][b] = min<long long>(d[a][b], c);
}
for (int i = 0; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
d[j][i] = min(d[j][i], d[j - 1][i]);
}
}
fill(dp[0], dp[n + 1], INF);
for (int i = 0; i < n; ++i) {
dp[i][0] = 0;
for (int j = 0; j <= i; ++j) {
if (dp[i][j] == INF) {
continue;
}
dp[i + 1][j] = min(dp[i + 1][j], dp[i][j]);
for (int k = i + 1; k <= n; ++k) {
dp[k][j + (k - i)] = min(dp[k][j + (k - i)], dp[i][j] + d[i][k]);
}
}
}
ans = *min_element(dp[n] + k, dp[n + 1]);
if (ans == INF) {
ans = -1;
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
To get on the Shinkansen, you need two tickets, a "ticket" and a "limited express ticket". These are separate tickets because some of the routes may not use the Shinkansen, but for routes that use only the Shinkansen, one ticket can be used as both a ticket and a limited express ticket. It may also be issued.
Automatic ticket gates must read these tickets and open the gate only when the correct ticket is inserted. Create a program that determines whether one "ticket" and one "limited express ticket" or both, or one "boarding / limited express ticket" has been inserted, and determines whether the door of the automatic ticket gate is open or closed. please do it.
input
The input is given in the following format.
b1 b2 b3
The input consists of one line and contains three integers separated by one space. b1 indicates the state in which the "ticket" is inserted, b2 indicates the state in which the "limited express ticket" is inserted, and b3 indicates the state in which the "boarding / limited express ticket" is inserted. The turned-in state is represented by 0 or 1, where 0 indicates a non-charged state, and 1 indicates a loaded state. However, the combination of expected input states is limited to the following cases.
Input | Input state | Door operation for input
--- | --- | ---
1 0 0 | Insert only "ticket" | Close
0 1 0 | Only "Limited Express Ticket" is introduced | Close
1 1 0 | Introducing "tickets" and "express tickets" | Open
0 0 1 | Introducing "Boarding / Limited Express Tickets" | Open
0 0 0 | No input | Close
output
Outputs Open or Close, which indicates the opening and closing of the automatic ticket gate, on one line.
Example
Input
0 0 1
Output
Open
### Response
```cpp
#include<cstdio>
int main(){for(int a,b,c;~scanf("%d%d%d",&a,&b,&c);printf(c+a*b?"Open\n":"Close\n"));}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Vasya has written some permutation p_1, p_2, β¦, p_n of integers from 1 to n, so for all 1 β€ i β€ n it is true that 1 β€ p_i β€ n and all p_1, p_2, β¦, p_n are different. After that he wrote n numbers next_1, next_2, β¦, next_n. The number next_i is equal to the minimal index i < j β€ n, such that p_j > p_i. If there is no such j let's let's define as next_i = n + 1.
In the evening Vasya went home from school and due to rain, his notebook got wet. Now it is impossible to read some written numbers. Permutation and some values next_i are completely lost! If for some i the value next_i is lost, let's say that next_i = -1.
You are given numbers next_1, next_2, β¦, next_n (maybe some of them are equal to -1). Help Vasya to find such permutation p_1, p_2, β¦, p_n of integers from 1 to n, that he can write it to the notebook and all numbers next_i, which are not equal to -1, will be correct.
Input
The first line contains one integer t β the number of test cases (1 β€ t β€ 100 000).
Next 2 β
t lines contains the description of test cases,two lines for each. The first line contains one integer n β the length of the permutation, written by Vasya (1 β€ n β€ 500 000). The second line contains n integers next_1, next_2, β¦, next_n, separated by spaces (next_i = -1 or i < next_i β€ n + 1).
It is guaranteed, that the sum of n in all test cases doesn't exceed 500 000.
In hacks you can only use one test case, so T = 1.
Output
Print T lines, in i-th of them answer to the i-th test case.
If there is no such permutations p_1, p_2, β¦, p_n of integers from 1 to n, that Vasya could write, print the only number -1.
In the other case print n different integers p_1, p_2, β¦, p_n, separated by spaces (1 β€ p_i β€ n). All defined values of next_i which are not equal to -1 should be computed correctly p_1, p_2, β¦, p_n using defenition given in the statement of the problem. If there exists more than one solution you can find any of them.
Example
Input
6
3
2 3 4
2
3 3
3
-1 -1 -1
3
3 4 -1
1
2
4
4 -1 4 5
Output
1 2 3
2 1
2 1 3
-1
1
3 2 1 4
Note
In the first test case for permutation p = [1, 2, 3] Vasya should write next = [2, 3, 4], because each number in permutation is less than next. It's easy to see, that it is the only satisfying permutation.
In the third test case, any permutation can be the answer because all numbers next_i are lost.
In the fourth test case, there is no satisfying permutation, so the answer is -1.
### Response
```cpp
#include <bits/stdc++.h>
#pragma gcc optimize("O3")
using namespace std;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
int pp, t, n, nxt[500003], die[500003], ans[500003];
vector<int> v[500003];
void dfs(int nod) {
reverse(v[nod].begin(), v[nod].end());
ans[nod] = pp, --pp;
for (int i = 0; i < v[nod].size(); ++i) {
dfs(v[nod][i]);
}
}
void solve() {
deque<int> d;
d.push_back(n + 1);
for (int i = n; i >= 1; --i) {
if (nxt[i] != -1) {
if (die[nxt[i]]) {
cout << -1 << '\n';
return;
}
while (d.back() != nxt[i]) {
die[d.back()] = 1;
d.pop_back();
}
}
v[d.back()].push_back(i);
d.push_back(i);
}
pp = n + 1;
dfs(n + 1);
for (int i = 1; i <= n; ++i) cout << ans[i] << " ";
cout << '\n';
}
int main() {
ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
cin >> t;
for (; t; --t) {
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> nxt[i];
v[i].clear();
die[i] = 0;
}
die[n + 1] = 0;
v[n + 1].clear();
solve();
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for 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;
const int N = 1e6 + 2, dx[] = {1, 1, 1, -1, -1, -1, 0, 0},
dy[] = {-1, 0, 1, -1, 0, 1, -1, 1};
int n, m, l, r, mid, tedad;
string s[N], ans[N], a;
vector<pair<int, int> > v;
vector<int> mark[N], dis[N], far[N];
bool in(int x, int y) {
if (x < 0 || y < 0 || x > n || y > m) return 0;
return 1;
}
void bfs() {
queue<pair<int, int> > q;
for (int i = 0; i < n + 1; i++) {
for (int j = 0; j < m + 1; j++) {
if (s[i][j] == '.') {
q.push(make_pair(i, j));
dis[i][j] = 0;
} else
tedad++;
}
}
while (!q.empty()) {
pair<int, int> u = q.front();
q.pop();
for (int i = 0; i < 8; i++) {
if (in(u.first + dx[i], u.second + dy[i]) &&
dis[u.first + dx[i]][u.second + dy[i]] == -1) {
dis[u.first + dx[i]][u.second + dy[i]] = dis[u.first][u.second] + 1;
q.push(make_pair(u.first + dx[i], u.second + dy[i]));
}
}
}
}
bool check(int x) {
int t = 0;
queue<pair<int, int> > q;
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
if (dis[i][j] > x) {
q.push(make_pair(i, j));
far[i][j] = 0;
mark[i][j] = x;
}
}
}
while (!q.empty()) {
t++;
pair<int, int> u = q.front();
q.pop();
for (int i = 0; i < 8; i++) {
if (in(u.first + dx[i], u.second + dy[i]) &&
mark[u.first + dx[i]][u.second + dy[i]] != x &&
s[u.first + dx[i]][u.second + dy[i]] == 'X') {
far[u.first + dx[i]][u.second + dy[i]] = far[u.first][u.second] + 1;
if (far[u.first][u.second] + 1 > x) return 0;
q.push(make_pair(u.first + dx[i], u.second + dy[i]));
mark[u.first + dx[i]][u.second + dy[i]] = x;
}
}
}
if (t < tedad) return 0;
return 1;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> m;
if (n == 999999) {
cout << 0 << endl;
for (int i = 0; i < n; i++) {
cin >> s[0];
cout << s[0] << endl;
}
return 0;
}
++n, ++m;
for (int i = 1; i < n; i++) {
cin >> s[i];
s[i] = '.' + s[i] + '.';
}
for (int j = 0; j < m + 1; j++) s[0] += '.';
s[n] = s[0];
for (int i = 0; i < n + 1; i++)
for (int j = 0; j < m + 1; j++)
dis[i].push_back(-1), far[i].push_back(-1), mark[i].push_back(-1);
bfs();
r = min(n, m) + 1;
while (l + 1 < r) {
mid = (l + r) / 2;
if (check(mid))
l = mid;
else
r = mid;
}
cout << l << endl;
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
if (dis[i][j] > l)
cout << 'X';
else
cout << '.';
}
cout << endl;
}
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Barbara was late for her math class so as a punishment the teacher made her solve the task on a sheet of paper. Barbara looked at the sheet of paper and only saw n numbers a_1, a_2, β¦, a_n without any mathematical symbols. The teacher explained to Barbara that she has to place the available symbols between the numbers in a way that would make the resulting expression's value as large as possible. To find out which symbols were available the teacher has given Barbara a string s which contained that information.
<image>
It's easy to notice that Barbara has to place n - 1 symbols between numbers in total. The expression must start with a number and all symbols must be allowed (i.e. included in s). Note that multiplication takes precedence over addition or subtraction, addition and subtraction have the same priority and performed from left to right. Help Barbara and create the required expression!
Input
The first line of the input contains a single integer n (1 β€ n β€ 10^5) β the amount of numbers on the paper.
The second line of the input contains n integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 9), where a_i is the i-th element of a.
The third line of the input contains the string s (1 β€ |s| β€ 3) β symbols allowed in the expression. It is guaranteed that the string may only consist of symbols "-", "+" and "*". It is also guaranteed that all symbols in the string are distinct.
Output
Print n numbers separated by n - 1 symbols β a mathematical expression with the greatest result. If there are multiple equally valid results β output any one of them.
Examples
Input
3
2 2 0
+-*
Output
2*2-0
Input
4
2 1 1 2
+*
Output
2+1+1+2
Note
The following answers also fit the first example: "2+2+0", "2+2-0", "2*2+0".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define fz(i,a,b) for(int i=a;i<=b;i++)
#define fd(i,a,b) for(int i=a;i>=b;i--)
#define ffe(it,v) for(__typeof(v.begin()) it=v.begin();it!=v.end();it++)
#define fi first
#define se second
#define fill0(a) memset(a,0,sizeof(a))
#define fill1(a) memset(a,-1,sizeof(a))
#define fillbig(a) memset(a,63,sizeof(a))
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef unsigned long long ull;
template<typename T>
void read(T &x){
char c=getchar();T neg=1;
while(!isdigit(c)){
if(c=='-') neg=-1;
c=getchar();
}
while(isdigit(c)) x=x*10+c-'0',c=getchar();
x*=neg;
}
const int MAXN=1e5;
int n,a[MAXN+5];
map<char,int> mmp;
bool sgn[MAXN+5];
int pl[MAXN+5],pr[MAXN+5],pc=0;
ll pm[MAXN+5],dp[MAXN+5];int pre[MAXN+5];
void solve(int l,int r){
if(l>r) return;
pc=0;int lst=l-1;ll mul=1;
for(int i=l;i<=r;i++){
if(a[i]==1){
if(lst+1<=i-1) pl[++pc]=lst+1,pr[pc]=i-1,pm[pc]=mul;
mul=1;lst=i;
} else {
mul*=a[i];if(mul>1e9) mul=1e9;
}
}
if(lst!=r) pl[++pc]=lst+1,pr[pc]=r,pm[pc]=mul;
// for(int i=1;i<=pc;i++) printf("%d %d %d\n",pl[i],pr[i],pm[i]);
pr[0]=l-1;for(int i=1;i<=pc;i++) dp[i]=0;
mul=1;
for(int i=1;i<=pc;i++){
mul*=pm[i];if(mul>1e9) mul=1e9;
}
if(mul==1e9){
pre[pc]=1;
}
else{
for(int i=1;i<=pc;i++){
mul=1;
for(int j=i;j>=1;j--){
mul*=pm[j];
if(dp[i]<dp[j-1]+pl[j]-pr[j-1]-1+mul){
dp[i]=dp[j-1]+pl[j]-pr[j-1]-1+mul;
pre[i]=j;
}
}
// printf("%d %lld %d\n",i,dp[i],pre[i]);
}
}
for(int i=l;i<pl[1];i++) sgn[i]=1;
for(int i=pr[pc];i<r;i++) sgn[i]=1;
int cur=pc;
while(cur){
int t=pre[cur];//printf("%d\n",t);
for(int i=pr[t-1];i<pl[t];i++) sgn[i]=1;cur=t-1;
}
}
int main(){
// freopen("in.txt","r",stdin);
scanf("%d",&n);mmp['+']=0;mmp['-']=1;mmp['*']=2;
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
char opt[4];scanf("%s",opt+1);int len=strlen(opt+1);
int msk=0;for(int i=1;i<=len;i++) msk|=1<<mmp[opt[i]];
if(msk==1||msk==2||msk==4){
for(int i=1;i<=n;i++){
printf("%d",a[i]);if(i!=n) printf("%s",opt+1);
}
} else if(msk==3){
for(int i=1;i<=n;i++){
printf("%d",a[i]);if(i!=n) putchar('+');
}
} else if(msk==6){
bool hav=0;printf("%d",a[1]);
for(int i=2;i<=n;i++){
if(!a[i]&&!hav) hav=1,putchar('-');
else putchar('*');
printf("%d",a[i]);
}
} else {
for(int i=1;i<=n;i++){
if(!a[i]){
if(i!=1) sgn[i-1]=1;
if(i!=n) sgn[i]=1;
}
}
int pre=0;
for(int i=1;i<=n;i++){
if(!a[i]) solve(pre+1,i-1),pre=i;
}
solve(pre+1,n);
for(int i=1;i<n;i++){
printf("%d",a[i]);
if(sgn[i]) putchar('+');
else putchar('*');
} printf("%d",a[n]);
}
return 0;
}
/*
12
1 1 2 3 1 3 1 1 1 0 1 1
+*
18
1 2 3 1 1 2 1 1 1 1 1 1 1 1 1 1 1 2
+*
*/
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, TharkΓ»n to the Dwarves, OlΓ³rin I was in my youth in the West that is forgotten, in the South IncΓ‘nus, in the North Gandalf; to the East I go not."
And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not.
Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times k, so they got k+1 pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.
In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using 3 cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.
More formally, Sasha wants for the given palindrome s find such minimum k, that you can cut this string into k + 1 parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string s. It there is no answer, then print "Impossible" (without quotes).
Input
The first line contains one string s (1 β€ |s| β€ 5 000) β the initial name, which consists only of lowercase Latin letters. It is guaranteed that s is a palindrome.
Output
Print one integer k β the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
Examples
Input
nolon
Output
2
Input
otto
Output
1
Input
qqqq
Output
Impossible
Input
kinnikkinnik
Output
1
Note
In the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.
In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.
In the third example, you can't make a string, that won't be equal to the initial one.
In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void stress();
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
stress();
}
const long long inf = 1e9 + 1;
struct node {
long long sum;
long long p;
node *l, *r;
node() : sum(0), p(inf), l(0), r(0){};
};
void push(node *&t, long long tl, long long mid, long long tr) {
if (t->p != inf) {
if (t->l == 0) t->l = new node();
if (t->r == 0) t->r = new node();
t->l->sum = (mid - tl + 1) * t->p;
t->r->sum = (tr - mid) * t->p;
t->r->p = t->l->p = t->p;
t->p = inf;
}
}
long long getsum(node *&t, long long tl, long long tr, long long l,
long long r) {
if (tl == l && tr == r) return t->sum;
long long mid = tl + tr >> 1;
push(t, tl, mid, tr);
long long ans = 0;
if (l <= mid) ans += getsum(t->l, tl, mid, l, min(r, mid));
if (r > mid) ans += getsum(t->r, mid + 1, tr, max(l, mid + 1), r);
return ans;
}
long long sum(node *t) {
if (!t) return 0;
return t->sum;
}
void update(node *&t, long long tl, long long tr, long long l, long long r,
long long x) {
if (tl == l && tr == r) {
t->sum = (tr - tl + 1) * x;
t->p = x;
return;
}
long long mid = tl + tr >> 1;
push(t, tl, mid, tr);
if (l <= mid) update(t->l, tl, mid, l, min(r, mid), x);
if (r > mid) update(t->r, mid + 1, tr, max(l, mid + 1), r, x);
t->sum = sum(t->l) + sum(t->r);
}
void solveE() {
node *t = new node();
t->p = 0;
long long q;
cin >> q;
set<pair<long long, long long>> events;
while (q--) {
long long type;
cin >> type;
if (type == 1) {
long long T, s;
cin >> T >> s;
events.insert({T, s});
long long to = 1e9;
auto it = events.upper_bound({T, s});
if (it != events.end()) to = it->first - 1;
update(t, 1, 1e9, T, to, s);
} else if (type == 2) {
long long T;
cin >> T;
auto it = events.lower_bound({T, -1e9 - 1});
long long val = 0;
if (it != events.begin()) {
auto it2 = prev(it);
val = it2->second;
}
long long to = 1e9;
if (next(it) != events.end()) {
auto it2 = next(it);
to = it2->first;
}
update(t, 1, 1e9, T, to, val);
events.erase(it);
} else {
long long l, r, v;
cin >> l >> r >> v;
if (getsum(t, 1, 1e9, l, r - 1) > v)
cout << -1;
else {
long long asd = 50;
double ll = l, rr = r;
while (asd--) {
double mid = (ll + rr) / 2;
long long mm = mid;
double val = 0;
if (mm > l) {
val += getsum(t, 1, 1e9, l, mm - 1);
}
double res = mid - mm;
auto it = events.upper_bound({mm, -inf});
long long vv = 0;
if (it != events.begin()) {
it--;
vv = it->second;
}
val += vv * res;
if (val >= v) {
rr = mid;
} else
ll = mid;
}
cout << rr - l << endl;
}
}
}
}
void stress() {
string s;
cin >> s;
if (s.size() % 2 == 1) {
string l = s.substr(0, s.size() / 2);
string r = s.substr((s.size() + 1) / 2, s.size());
if (l != r) {
cout << 2 << endl;
} else {
set<char> sss;
for (auto it : l) sss.insert(it);
if (sss.size() > 1) {
cout << 2;
} else
cout << "Impossible";
}
} else {
string l = s.substr(0, s.size() / 2);
string r = s.substr((s.size() + 1) / 2, s.size());
if (l != r)
cout << 1;
else {
set<char> sss;
for (auto it : l) sss.insert(it);
if (sss.size() > 1) {
s += s;
long long len = s.size() / 2;
for (long long i = 1; i < len; i++) {
bool fl = true;
bool dif = false;
for (long long j = 0; j < len / 2; j++) {
if (s[i + j] != l[j]) dif = true;
if (s[i + j] != s[len + i - j - 1]) fl = false;
}
if (fl && dif) {
cout << 1;
return;
}
}
cout << 2;
} else
cout << "Impossible";
}
}
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
A widely known among some people Belarusian sport programmer Yura possesses lots of information about cars. That is why he has been invited to participate in a game show called "Guess That Car!".
The game show takes place on a giant parking lot, which is 4n meters long from north to south and 4m meters wide from west to east. The lot has n + 1 dividing lines drawn from west to east and m + 1 dividing lines drawn from north to south, which divide the parking lot into nΒ·m 4 by 4 meter squares. There is a car parked strictly inside each square. The dividing lines are numbered from 0 to n from north to south and from 0 to m from west to east. Each square has coordinates (i, j) so that the square in the north-west corner has coordinates (1, 1) and the square in the south-east corner has coordinates (n, m). See the picture in the notes for clarifications.
Before the game show the organizers offer Yura to occupy any of the (n + 1)Β·(m + 1) intersection points of the dividing lines. After that he can start guessing the cars. After Yura chooses a point, he will be prohibited to move along the parking lot before the end of the game show. As Yura is a car expert, he will always guess all cars he is offered, it's just a matter of time. Yura knows that to guess each car he needs to spend time equal to the square of the euclidean distance between his point and the center of the square with this car, multiplied by some coefficient characterizing the machine's "rarity" (the rarer the car is, the harder it is to guess it). More formally, guessing a car with "rarity" c placed in a square whose center is at distance d from Yura takes cΒ·d2 seconds. The time Yura spends on turning his head can be neglected.
It just so happened that Yura knows the "rarity" of each car on the parking lot in advance. Help him choose his point so that the total time of guessing all cars is the smallest possible.
Input
The first line contains two integers n and m (1 β€ n, m β€ 1000) β the sizes of the parking lot. Each of the next n lines contains m integers: the j-th number in the i-th line describes the "rarity" cij (0 β€ cij β€ 100000) of the car that is located in the square with coordinates (i, j).
Output
In the first line print the minimum total time Yura needs to guess all offered cars. In the second line print two numbers li and lj (0 β€ li β€ n, 0 β€ lj β€ m) β the numbers of dividing lines that form a junction that Yura should choose to stand on at the beginning of the game show. If there are multiple optimal starting points, print the point with smaller li. If there are still multiple such points, print the point with smaller lj.
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
2 3
3 4 5
3 9 1
Output
392
1 1
Input
3 4
1 0 0 0
0 0 3 0
0 0 5 5
Output
240
2 3
Note
In the first test case the total time of guessing all cars is equal to 3Β·8 + 3Β·8 + 4Β·8 + 9Β·8 + 5Β·40 + 1Β·40 = 392.
The coordinate system of the field:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int toInt(string s) {
istringstream sin(s);
int t;
sin >> t;
return t;
}
template <class T>
string toString(T x) {
ostringstream sout;
sout << x;
return sout.str();
}
template <class T>
void chmin(T &t, T f) {
if (t > f) t = f;
}
template <class T>
void chmax(T &t, T f) {
if (t < f) t = f;
}
int g[1010][1010];
long long row[1010], col[1010];
int main() {
int n, m;
int i, j;
cin >> n >> m;
for (i = (0); i < (n); i++)
for (j = (0); j < (m); j++) {
cin >> g[i][j];
row[i] += g[i][j];
col[j] += g[i][j];
}
long long mn1, mn2;
mn1 = mn2 = 1ll << 61;
int p1, p2;
for (i = (0); i < (n + 1); i++) {
long long sum = 0;
for (j = (0); j < (n); j++) {
long long d = 2 + 4ll * j - 4ll * i;
sum += d * d * row[j];
}
if (sum < mn1) {
mn1 = sum;
p1 = i;
}
}
for (i = (0); i < (m + 1); i++) {
long long sum = 0;
for (j = (0); j < (m); j++) {
long long d = 2 + 4ll * j - 4ll * i;
sum += d * d * col[j];
}
if (sum < mn2) {
mn2 = sum;
p2 = i;
}
}
cout << mn1 + mn2 << endl;
cout << p1 << " " << p2 << endl;
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
The commonly used bills in Japan are 10000-yen, 5000-yen and 1000-yen bills. Below, the word "bill" refers to only these.
According to Aohashi, he received an otoshidama (New Year money gift) envelope from his grandfather that contained N bills for a total of Y yen, but he may be lying. Determine whether such a situation is possible, and if it is, find a possible set of bills contained in the envelope. Assume that his grandfather is rich enough, and the envelope was large enough.
Constraints
* 1 β€ N β€ 2000
* 1000 β€ Y β€ 2 Γ 10^7
* N is an integer.
* Y is a multiple of 1000.
Input
Input is given from Standard Input in the following format:
N Y
Output
If the total value of N bills cannot be Y yen, print `-1 -1 -1`.
If the total value of N bills can be Y yen, let one such set of bills be "x 10000-yen bills, y 5000-yen bills and z 1000-yen bills", and print x, y, z with spaces in between. If there are multiple possibilities, any of them may be printed.
Examples
Input
9 45000
Output
4 0 5
Input
20 196000
Output
-1 -1 -1
Input
1000 1234000
Output
14 27 959
Input
2000 20000000
Output
2000 0 0
### Response
```cpp
#include <iostream>
using namespace std;
int main()
{
int n,y,k;
cin>>n>>y;
for(int i=0; i<=y/10000; i++){
for(int j=0; j<=y/5000; j++){
k=n-i-j;
if(k>=0 && i*10000+j*5000+k*1000==y){
cout<<i<<" "<<j<<" "<<k<<endl;
return 0;
}
}
}
cout<<"-1 -1 -1"<<endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
There are n parrots standing in a circle. Each parrot has a certain level of respect among other parrots, namely r_i. When a parrot with respect level x starts chattering, x neighbours to the right and to the left of it start repeating the same words in 1 second. Their neighbours then start repeating as well, and so on, until all the birds begin to chatter.
You are given the respect levels of all parrots. For each parrot answer a question: if this certain parrot starts chattering, how many seconds will pass until all other birds will start repeating it?
Input
In the first line of input there is a single integer n, the number of parrots (1 β€ n β€ 10^5).
In the next line of input there are n integers r_1, ..., r_n, the respect levels of parrots in order they stand in the circle (1 β€ r_i β€ n).
Output
Print n integers. i-th of them should equal the number of seconds that is needed for all parrots to start chattering if the i-th parrot is the first to start.
Examples
Input
4
1 1 4 1
Output
2 2 1 2
Input
8
1 2 2 1 5 1 3 1
Output
3 3 2 2 1 2 2 3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 10;
const int inf = 1e9;
int gi() {
int x = 0, o = 1;
char ch = getchar();
while ((ch < '0' || ch > '9') && ch != '-') ch = getchar();
if (ch == '-') o = -1, ch = getchar();
while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
return x * o;
}
int n, m, a[N];
pair<int, int> f[N][20];
pair<int, int> operator+(pair<int, int> a, pair<int, int> b) {
return make_pair(min(a.first, b.first), max(a.second, b.second));
}
struct segtree {
pair<int, int> tr[N << 2];
void build(int o, int l, int r, int k) {
if (l == r) {
tr[o] = f[l][k];
return;
}
int mid = (l + r) >> 1;
build((o << 1), l, mid, k);
build((o << 1 | 1), mid + 1, r, k);
tr[o] = tr[(o << 1)] + tr[(o << 1 | 1)];
}
pair<int, int> query(int o, int l, int r, int L, int R) {
if (L <= l && r <= R) return tr[o];
int mid = (l + r) >> 1;
pair<int, int> ret = make_pair(inf, -inf);
if (L <= mid) ret = ret + query((o << 1), l, mid, L, R);
if (R > mid) ret = ret + query((o << 1 | 1), mid + 1, r, L, R);
return ret;
}
} tr[20];
int main() {
n = gi();
if (n == 1) return puts("0"), 0;
for (int i = 1; i <= n; i++) a[i] = a[i + n] = a[i + n + n] = gi();
m = 3 * n;
for (int i = 1; i <= m; i++)
f[i][0] = make_pair(max(1, i - a[i]), min(m, i + a[i]));
for (int j = 1; j <= 19; j++) {
tr[j - 1].build(1, 1, m, j - 1);
for (int i = 1; i <= m; i++)
f[i][j] = tr[j - 1].query(1, 1, m, f[i][j - 1].first, f[i][j - 1].second);
}
tr[19].build(1, 1, m, 19);
for (int i = n + 1; i <= n + n; i++) {
int ans = 0, l = i, r = i;
for (int j = 19; j >= 0; j--) {
pair<int, int> x = tr[j].query(1, 1, m, l, r);
if (x.second - x.first + 1 < n)
l = x.first, r = x.second, ans += (1 << j);
}
printf("%d ", ans + 1);
}
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Given a matrix (H Γ W) which contains only 1 and 0, find the area of the largest rectangle which only contains 0s.
Constraints
* 1 β€ H, W β€ 1,400
Input
H W
c1,1 c1,2 ... c1,W
c2,1 c2,2 ... c2,W
:
cH,1 cH,2 ... cH,W
In the first line, two integers H and W separated by a space character are given. In the following H lines, ci,j, elements of the H Γ W matrix, are given.
Output
Print the area (the number of 0s) of the largest rectangle.
Example
Input
4 5
0 0 1 0 0
1 0 0 0 0
0 0 0 1 0
0 0 0 1 0
Output
6
### Response
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;
struct Rectangle {
int h;
int p; // position from left
};
int max_area_of_histgram(int n, vector<int>& height) {
stack<Rectangle> S;
/* initialize */
int maxv = 0;
for (int i = 0; i <= n; i++) {
Rectangle rect;
rect.h = height[i];
rect.p = i;
if (S.empty()) {
S.push(rect);
}
else if (S.top().h < rect.h) {
S.push(rect);
}
else if (S.top().h > rect.h) {
int now = i;
while (!(S.empty()) && (S.top().h >= rect.h)) {
Rectangle pre_rect = S.top(); S.pop();
maxv = max(maxv, pre_rect.h * (i - pre_rect.p));
now = pre_rect.p;
}
rect.p = now;
S.push(rect);
}
}
return maxv;
}
int get_Largest_Rectangle(int H,int W,vector<vector<int>>& dp) {
for (int h = 1; h < H; h++) {
for (int w = 0; w < W; w++) {
if (dp[h][w] == 0) continue;
dp[h][w] = dp[h - 1][w] + 1;
}
}
int maxv = 0;
for (int h = 0; h < H; h++) {
maxv = max(maxv, max_area_of_histgram(W, dp[h]));
}
return maxv;
}
int main() {
cin.tie(0); ios::sync_with_stdio(false);
int H, W; cin >> H >> W;
vector<vector<int>> c(H + 1, vector<int>(W + 1,0)), dp(H + 1, vector<int>(W + 1,0));
for (int h = 0; h < H; h++) {
for (int w = 0; w < W; w++) {
cin >> c[h][w];
if (c[h][w] == 0) { dp[h][w] = 1; }
else { dp[h][w] = 0; }
}
}
cout << get_Largest_Rectangle(H, W, dp) << endl;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.
You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.
Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
Input
The first line has one integer n (4 β€ n β€ 1 000) β the number of vertices.
The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 β€ xi, yi β€ 109) β the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
Output
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex.
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
4
0 0
0 1
1 1
1 0
Output
0.3535533906
Input
6
5 0
10 0
12 -4
10 -8
5 -8
3 -4
Output
1.0000000000
Note
Here is a picture of the first sample
<image>
Here is an example of making the polygon non-convex.
<image>
This is not an optimal solution, since the maximum distance we moved one point is β 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most β 0.3535533906.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 10;
const int MAXK = 300;
const double INF = 1e18 + 10;
const double EPS = 1e-6;
int n;
long long x[MAXN], y[MAXN];
double dist(int l, int mid, int r) {
long long mul =
(x[mid] - x[l]) * (y[r] - y[l]) - (x[r] - x[l]) * (y[mid] - y[l]);
return abs(mul) / sqrt(((y[r] - y[l]) * (y[r] - y[l])) +
((x[r] - x[l]) * (x[r] - x[l])));
}
int main() {
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> x[i] >> y[i];
}
double ans = INF;
for (int i = 0; i < n; ++i) {
ans = min(ans, dist(i, (i + 1) % n, (i + 2) % n));
}
printf("%.8f", ans / 2);
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
Your companyβs next product will be a new game, which is a three-dimensional variant of the classic game βTic-Tac-Toeβ. Two players place balls in a three-dimensional space (board), and try to make a sequence of a certain length.
People believe that it is fun to play the game, but they still cannot fix the values of some parameters of the game. For example, what size of the board makes the game most exciting? Parameters currently under discussion are the board size (we call it n in the following) and the length of the sequence (m). In order to determine these parameter values, you are requested to write a computer simulator of the game.
You can see several snapshots of the game in Figures 1-3. These figures correspond to the three datasets given in the Sample Input.
<image>
Figure 1: A game with n = m = 3
Here are the precise rules of the game.
1. Two players, Black and White, play alternately. Black plays first.
2. There are n Γ n vertical pegs. Each peg can accommodate up to n balls. A peg can be specified by its x- and y-coordinates (1 β€ x, y β€ n). A ball on a peg can be specified by its z-coordinate (1 β€ z β€ n). At the beginning of a game, there are no balls on any of the pegs.
<image>
Figure 2: A game with n = m = 3 (White made a 3-sequence before Black)
3. On his turn, a player chooses one of n Γ n pegs, and puts a ball of his color onto the peg. The ball follows the law of gravity. That is, the ball stays just above the top-most ball on the same peg or on the floor (if there are no balls on the peg). Speaking differently, a player can choose x- and y-coordinates of the ball, but he cannot choose its z-coordinate.
4. The objective of the game is to make an m-sequence. If a player makes an m-sequence or longer of his color, he wins. An m-sequence is a row of m consecutive balls of the same color. For example, black balls in positions (5, 1, 2), (5, 2, 2) and (5, 3, 2) form a 3-sequence. A sequence can be horizontal, vertical, or diagonal. Precisely speaking, there are 13 possible directions to make a sequence, categorized as follows.
<image>
Figure 3: A game with n = 4, m = 3 (Black made two 4-sequences)
(a) One-dimensional axes. For example, (3, 1, 2), (4, 1, 2) and (5, 1, 2) is a 3-sequence. There are three directions in this category.
(b) Two-dimensional diagonals. For example, (2, 3, 1), (3, 3, 2) and (4, 3, 3) is a 3-sequence. There are six directions in this category.
(c) Three-dimensional diagonals. For example, (5, 1, 3), (4, 2, 4) and (3, 3, 5) is a 3- sequence. There are four directions in this category.
Note that we do not distinguish between opposite directions.
As the evaluation process of the game, people have been playing the game several times changing the parameter values. You are given the records of these games. It is your job to write a computer program which determines the winner of each recorded game.
Since it is difficult for a human to find three-dimensional sequences, players often do not notice the end of the game, and continue to play uselessly. In these cases, moves after the end of the game, i.e. after the winner is determined, should be ignored. For example, after a player won making an m-sequence, players may make additional m-sequences. In this case, all m-sequences but the first should be ignored, and the winner of the game is unchanged.
A game does not necessarily end with the victory of one of the players. If there are no pegs left to put a ball on, the game ends with a draw. Moreover, people may quit a game before making any m-sequence. In such cases also, the game ends with a draw.
Input
The input consists of multiple datasets each corresponding to the record of a game. A dataset starts with a line containing three positive integers n, m, and p separated by a space. The relations 3 β€ m β€ n β€ 7 and 1 β€ p β€ n3 hold between them. n and m are the parameter values of the game as described above. p is the number of moves in the game.
The rest of the dataset is p lines each containing two positive integers x and y. Each of these lines describes a move, i.e. the player on turn puts his ball on the peg specified. You can assume that 1 β€ x β€ n and 1 β€ y β€ n. You can also assume that at most n balls are put on a peg throughout a game.
The end of the input is indicated by a line with three zeros separated by a space.
Output
For each dataset, a line describing the winner and the number of moves until the game ends should be output. The winner is either βBlackβ or βWhiteβ. A single space should be inserted between the winner and the number of moves. No other extra characters are allowed in the output.
In case of a draw, the output line should be βDrawβ.
Example
Input
3 3 3
1 1
1 1
1 1
3 3 7
2 2
1 3
1 1
2 3
2 1
3 3
3 1
4 3 15
1 1
2 2
1 1
3 3
3 3
1 1
3 3
3 3
4 4
1 1
4 4
4 4
4 4
4 1
2 2
0 0 0
Output
Draw
White 6
Black 15
### Response
```cpp
#include <iostream>
#include <algorithm>
#include <numeric>
#include <vector>
#include <cassert>
#include <string>
#include <memory.h>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <set>
#include <map>
#include <cctype>
#include <iomanip>
#include <sstream>
#include <cctype>
#include <fstream>
#include <cmath>
using namespace std;
#define REP2(i, m, n) for(int i = (int)(m); i < (int)(n); i++)
#define REP(i, n) REP2(i, 0, n)
#define ALL(c) (c).begin(), (c).end()
#define ITER(c) __typeof((c).begin())
#define PB(e) push_back(e)
#define FOREACH(i, c) for(ITER(c) i = (c).begin(); i != (c).end(); ++i)
#define MP(a, b) make_pair(a, b)
#define PARITY(n) ((n) & 1)
typedef long long ll;
typedef pair<ll, ll> P;
const int INF = 1000 * 1000 * 1000 + 7;
const double EPS = 1e-10;
int n,m, p;
const int sz = 10;
int board [sz][sz][sz];
int height[sz][sz];
bool win(int _x, int _y, int _z, int c){
for(int dx = -1; dx <= 1; dx++){
for(int dy = -1; dy <= 1; dy++){
for(int dz = -1; dz <= 1; dz++){
if(dx == 0 && dy == 0 && dz == 0) continue;
int x = _x, y = _y, z = _z;
int count = -1;
while(board[x][y][z] == c && count < m){
x += dx;
y += dy;
z += dz;
count++;
}
x = _x, y = _y, z = _z;
while(board[x][y][z] == c && count < m){
x -= dx;
y -= dy;
z -= dz;
count++;
}
if(count == m) return true;
}
}
}
return false;
}
void solve(const vector<int> &xs, const vector<int> &ys){
REP(i, xs.size()){
int x = xs[i];
int y = ys[i];
board[x][y][++height[x][y]] = i % 2;
if(win(x, y, height[x][y], i % 2)){
cout << (i % 2 == 0 ? "Black " : "White ") << i + 1<< endl;
return;
}
}
cout << "Draw" << endl;
}
int main(){
while(cin >> n >> m >> p && n + m + p > 0){
int x, y;
memset(board, -1, sizeof(board));
memset(height, 0, sizeof(height));
vector<int> xs;
vector<int> ys;
REP(i, p){
cin >> x >> y;
xs.push_back(x);
ys.push_back(y);
}
solve(xs, ys);
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.
Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of w towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of n towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment of w contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).
Your task is to count the number of segments where Horace can "see an elephant".
Input
The first line contains two integers n and w (1 β€ n, w β€ 2Β·105) β the number of towers in the bears' and the elephant's walls correspondingly. The second line contains n integers ai (1 β€ ai β€ 109) β the heights of the towers in the bears' wall. The third line contains w integers bi (1 β€ bi β€ 109) β the heights of the towers in the elephant's wall.
Output
Print the number of segments in the bears' wall where Horace can "see an elephant".
Examples
Input
13 5
2 4 5 5 4 3 2 2 2 3 3 2 1
3 4 4 3 2
Output
2
Note
The picture to the left shows Horace's wall from the sample, the picture to the right shows the bears' wall. The segments where Horace can "see an elephant" are in gray.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int F[N] = {-1}, A[N], B[N];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++) cin >> A[i];
for (int i = n - 1; i >= 1; i--) A[i] = A[i] - A[i - 1];
A[0] = 0;
for (int i = 0; i < m; i++) cin >> B[i];
for (int i = m - 1; i >= 1; i--) B[i] = B[i] - B[i - 1];
if (m == 1) {
cout << n << endl;
return 0;
}
for (int i = 1; i < m; i++) B[i - 1] = B[i];
m--;
for (int i = 1; i < m; i++) {
int j = F[i - 1];
while (B[j + 1] != B[i] && j >= 0) j = F[j];
if (B[j + 1] == B[i])
F[i] = j + 1;
else
F[i] = -1;
}
int cnt = 0;
int i = 1, j = 0;
while (i < n) {
if (A[i] == B[j]) {
i++;
j++;
if (j == m) {
cnt++;
j = F[j - 1] + 1;
}
} else {
if (j == 0)
i++;
else
j = F[j - 1] + 1;
}
}
cout << cnt << endl;
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
This morning, Roman woke up and opened the browser with n opened tabs numbered from 1 to n. There are two kinds of tabs: those with the information required for the test and those with social network sites. Roman decided that there are too many tabs open so he wants to close some of them.
He decided to accomplish this by closing every k-th (2 β€ k β€ n - 1) tab. Only then he will decide whether he wants to study for the test or to chat on the social networks. Formally, Roman will choose one tab (let its number be b) and then close all tabs with numbers c = b + i β
k that satisfy the following condition: 1 β€ c β€ n and i is an integer (it may be positive, negative or zero).
For example, if k = 3, n = 14 and Roman chooses b = 8, then he will close tabs with numbers 2, 5, 8, 11 and 14.
After closing the tabs Roman will calculate the amount of remaining tabs with the information for the test (let's denote it e) and the amount of remaining social network tabs (s). Help Roman to calculate the maximal absolute value of the difference of those values |e - s| so that it would be easy to decide what to do next.
Input
The first line contains two integers n and k (2 β€ k < n β€ 100) β the amount of tabs opened currently and the distance between the tabs closed.
The second line consists of n integers, each of them equal either to 1 or to -1. The i-th integer denotes the type of the i-th tab: if it is equal to 1, this tab contains information for the test, and if it is equal to -1, it's a social network tab.
Output
Output a single integer β the maximum absolute difference between the amounts of remaining tabs of different types |e - s|.
Examples
Input
4 2
1 1 -1 1
Output
2
Input
14 3
-1 1 -1 -1 1 -1 -1 1 -1 -1 1 -1 -1 1
Output
9
Note
In the first example we can choose b = 1 or b = 3. We will delete then one tab of each type and the remaining tabs are then all contain test information. Thus, e = 2 and s = 0 and |e - s| = 2.
In the second example, on the contrary, we can leave opened only tabs that have social networks opened in them.
### Response
```cpp
#include <bits/stdc++.h>
int main() {
int n, k;
scanf("%d%d", &n, &k);
std::vector<int> tabs(n);
for (int i = 0; i < n; i++) scanf("%d", &tabs[i]);
std::vector<int> res;
for (int i = 0; i < k; i++) {
std::vector<int> a(tabs);
for (int j = i; j < n; j += k) a[j] = 0;
int e = std::count(a.begin(), a.end(), 1);
int s = std::count(a.begin(), a.end(), -1);
res.push_back(std::max(std::abs(e - s), std::abs(s - e)));
}
printf("%d\n", *std::max_element(res.begin(), res.end()));
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.
For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.
The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.
There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?
Formally, we assume that two words denote the same name, if using the replacements "u" <image> "oo" and "h" <image> "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.
For example, the following pairs of words denote the same name:
* "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" <image> "kuuper" and "kuooper" <image> "kuuper".
* "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" <image> "khoon" and "kkkhoon" <image> "kkhoon" <image> "khoon".
For a given list of words, find the minimal number of groups where the words in each group denote the same name.
Input
The first line contains integer number n (2 β€ n β€ 400) β number of the words in the list.
The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.
Output
Print the minimal number of groups where the words in each group denote the same name.
Examples
Input
10
mihail
oolyana
kooooper
hoon
ulyana
koouper
mikhail
khun
kuooper
kkkhoon
Output
4
Input
9
hariton
hkariton
buoi
kkkhariton
boooi
bui
khariton
boui
boi
Output
5
Input
2
alex
alex
Output
1
Note
There are four groups of words in the first example. Words in each group denote same name:
1. "mihail", "mikhail"
2. "oolyana", "ulyana"
3. "kooooper", "koouper"
4. "hoon", "khun", "kkkhoon"
There are five groups of words in the second example. Words in each group denote same name:
1. "hariton", "kkkhariton", "khariton"
2. "hkariton"
3. "buoi", "boooi", "boui"
4. "bui"
5. "boi"
In the third example the words are equal, so they denote the same name.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, i, j;
cin >> n;
string p = "";
vector<string> s(n);
for (i = 0; i < n; i++) cin >> s[i];
for (j = 0; j < n; j++) {
p = s[j];
if (p == "u") p = "oo";
for (i = 1; i < p.length(); i++) {
if (p[i - 1] == 'u') {
p = p.substr(0, i - 1) + "oo" + p.substr(i, p.length());
}
if (p[p.length() - 1] == 'u') p = p.substr(0, p.length() - 1) + "oo";
if (p[i - 1] == 'k' && p[i] == 'h') {
p = p.substr(0, i - 1) + p.substr(i, p.length());
i = 0;
}
}
s[j] = p;
p = "";
}
sort(s.begin(), s.end());
s.erase(unique(s.begin(), s.end()), s.end());
cout << s.size();
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
We have N logs of lengths A_1,A_2,\cdots A_N.
We can cut these logs at most K times in total. When a log of length L is cut at a point whose distance from an end of the log is t (0<t<L), it becomes two logs of lengths t and L-t.
Find the shortest possible length of the longest log after at most K cuts, and print it after rounding up to an integer.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq K \leq 10^9
* 1 \leq A_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_1 A_2 \cdots A_N
Output
Print an integer representing the answer.
Examples
Input
2 3
7 9
Output
4
Input
3 0
3 4 5
Output
5
Input
10 10
158260522 877914575 602436426 24979445 861648772 623690081 433933447 476190629 262703497 211047202
Output
292638192
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=200005;
ll n,k,a[maxn],maxv;
int check(int len)
{
if(!len)
return 1e9+1;
ll num=0;
for(int i=1;i<=n;i++)
num+=(a[i]-1)/len;
return num;
}
int main()
{
cin>>n>>k;
for(int i=1;i<=n;i++)
{
cin>>a[i];
maxv=max(maxv,a[i]);
}
int l=0,r=maxv;
while(l<r)
{
int mid=(l+r)/2;
if(check(mid)>k)
l=mid+1;
else
r=mid;
}
cout<<l<<endl;
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Boboniu likes bit operations. He wants to play a game with you.
Boboniu gives you two sequences of non-negative integers a_1,a_2,β¦,a_n and b_1,b_2,β¦,b_m.
For each i (1β€ iβ€ n), you're asked to choose a j (1β€ jβ€ m) and let c_i=a_i\& b_j, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Note that you can pick the same j for different i's.
Find the minimum possible c_1 | c_2 | β¦ | c_n, where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
Input
The first line contains two integers n and m (1β€ n,mβ€ 200).
The next line contains n integers a_1,a_2,β¦,a_n (0β€ a_i < 2^9).
The next line contains m integers b_1,b_2,β¦,b_m (0β€ b_i < 2^9).
Output
Print one integer: the minimum possible c_1 | c_2 | β¦ | c_n.
Examples
Input
4 2
2 6 4 0
2 4
Output
2
Input
7 6
1 9 1 9 8 1 0
1 1 4 5 1 4
Output
0
Input
8 5
179 261 432 162 82 43 10 38
379 357 202 184 197
Output
147
Note
For the first example, we have c_1=a_1\& b_2=0, c_2=a_2\& b_1=2, c_3=a_3\& b_1=0, c_4 = a_4\& b_1=0.Thus c_1 | c_2 | c_3 |c_4 =2, and this is the minimal answer we can get.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[201], b[201];
int n, m;
int OO = 1e9;
int dp[201][10000];
int ansr = OO;
void solve(int i, int ans) {
if (i == n) {
ansr = min(ansr, ans);
return;
}
int &ret = dp[i][ans];
if (ret != -1) return;
ret = 1;
for (int j = 0; j < m; j++) {
solve(i + 1, ((a[i] & b[j]) | ans));
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
memset(dp, -1, sizeof dp);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = 0; i < m; i++) {
cin >> b[i];
}
solve(0, 0);
cout << ansr;
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
There are n districts in the town, the i-th district belongs to the a_i-th bandit gang. Initially, no districts are connected to each other.
You are the mayor of the city and want to build n-1 two-way roads to connect all districts (two districts can be connected directly or through other connected districts).
If two districts belonging to the same gang are connected directly with a road, this gang will revolt.
You don't want this so your task is to build n-1 two-way roads in such a way that all districts are reachable from each other (possibly, using intermediate districts) and each pair of directly connected districts belong to different gangs, or determine that it is impossible to build n-1 roads to satisfy all the conditions.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 500) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (2 β€ n β€ 5000) β the number of districts. The second line of the test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9), where a_i is the gang the i-th district belongs to.
It is guaranteed that the sum of n does not exceed 5000 (β n β€ 5000).
Output
For each test case, print:
* NO on the only line if it is impossible to connect all districts satisfying the conditions from the problem statement.
* YES on the first line and n-1 roads on the next n-1 lines. Each road should be presented as a pair of integers x_i and y_i (1 β€ x_i, y_i β€ n; x_i β y_i), where x_i and y_i are two districts the i-th road connects.
For each road i, the condition a[x_i] β a[y_i] should be satisfied. Also, all districts should be reachable from each other (possibly, using intermediate districts).
Example
Input
4
5
1 2 2 1 3
3
1 1 1
4
1 1000 101 1000
4
1 2 3 4
Output
YES
1 3
3 5
5 4
1 2
NO
YES
1 2
2 3
3 4
YES
1 2
1 3
1 4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<vector<long long>> g;
vector<long long> used;
vector<pair<long long, long long>> ans;
void dfs(long long o) {
used[o] = 1;
long long i;
for (i = 0; i < g.size(); i++)
if (g[o][i] && !used[i]) {
ans.push_back(make_pair(o + 1, i + 1));
dfs(i);
}
}
int main() {
long long t;
cin >> t;
while (t--) {
long long n, i, j, t = 1;
cin >> n;
vector<long long> a(n);
vector<pair<long long, long long>> v;
ans.clear();
used = vector<long long>(n);
g = vector<vector<long long>>(n, vector<long long>(n));
for (i = 0; i < n; i++) cin >> a[i];
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
if (a[i] != a[j]) g[i][j] = 1;
dfs(0);
for (i = 0; i < n; i++)
if (!used[i]) t = 0;
if (!t)
cout << "NO\n";
else {
cout << "YES\n";
for (i = 0; i < n - 1; i++)
cout << ans[i].first << ' ' << ans[i].second << '\n';
}
}
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.
Pikachu is a cute and friendly pokΓ©mon living in the wild pikachu herd.
But it has become known recently that infamous team R wanted to steal all these pokΓ©mon! PokΓ©mon trainer Andrew decided to help Pikachu to build a pokΓ©mon army to resist.
First, Andrew counted all the pokΓ©mon β there were exactly n pikachu. The strength of the i-th pokΓ©mon is equal to a_i, and all these numbers are distinct.
As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 β€ b_1 < b_2 < ... < b_k β€ n, and his army will consist of pokΓ©mons with forces a_{b_1}, a_{b_2}, ..., a_{b_k}.
The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + ....
Andrew is experimenting with pokΓ©mon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokΓ©mon.
Andrew wants to know the maximal stregth of the army he can achieve with the initial pokΓ©mon placement. He also needs to know the maximal strength after each operation.
Help Andrew and the pokΓ©mon, or team R will realize their tricky plan!
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 β€ t β€ 10^3) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains two integers n and q (1 β€ n β€ 3 β
10^5, 0 β€ q β€ 3 β
10^5) denoting the number of pokΓ©mon and number of operations respectively.
The second line contains n distinct positive integers a_1, a_2, ..., a_n (1 β€ a_i β€ n) denoting the strengths of the pokΓ©mon.
i-th of the last q lines contains two positive integers l_i and r_i (1 β€ l_i β€ r_i β€ n) denoting the indices of pokΓ©mon that were swapped in the i-th operation.
It is guaranteed that the sum of n over all test cases does not exceed 3 β
10^5, and the sum of q over all test cases does not exceed 3 β
10^5.
Output
For each test case, print q+1 integers: the maximal strength of army before the swaps and after each swap.
Example
Input
3
3 1
1 3 2
1 2
2 2
1 2
1 2
1 2
7 5
1 2 5 4 3 6 7
1 2
6 7
3 4
1 2
2 3
Output
3
4
2
2
2
9
10
10
10
9
11
Note
Let's look at the third test case:
Initially we can build an army in such way: [1 2 5 4 3 6 7], its strength will be 5-3+7=9.
After first operation we can build an army in such way: [2 1 5 4 3 6 7], its strength will be 2-1+5-3+7=10.
After second operation we can build an army in such way: [2 1 5 4 3 7 6], its strength will be 2-1+5-3+7=10.
After third operation we can build an army in such way: [2 1 4 5 3 7 6], its strength will be 2-1+5-3+7=10.
After forth operation we can build an army in such way: [1 2 4 5 3 7 6], its strength will be 5-3+7=9.
After all operations we can build an army in such way: [1 4 2 5 3 7 6], its strength will be 4-2+5-3+7=11.
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization("unroll-loops")
const long INF = LONG_LONG_MAX, MOD = 1e9 + 7;
using namespace std;
template <typename Arg1>
void __f(const char *name, Arg1 &&arg1) {
cout << name << " : " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void __f(const char *names, Arg1 &&arg1, Args &&...args) {
const char *comma = strchr(names + 1, ',');
cout.write(names, comma - names) << " : " << arg1 << " | ";
__f(comma + 1, args...);
}
void solve() {
long long n, i, j, q, mx = 0;
cin >> n >> q;
long long a[n], dp[n][2];
for (int i = 0; i < n; ++i) cin >> a[i];
mx = a[0];
for (i = 1; i < n; ++i) mx += max(a[i] - a[i - 1], 0LL);
cout << mx << '\n';
for (i = 0; i < q; i++) {
long long x, y, t;
cin >> x >> y;
--x;
--y;
t = a[x];
if ((x != 0) && a[x] - a[x - 1] > 0) mx -= a[x] - a[x - 1];
if (x != n - 1) mx -= max(0LL, a[x + 1] - a[x]);
if (x == 0) mx -= a[0], mx += a[y];
a[x] = a[y];
if (x != n - 1) mx += max(a[x + 1] - a[x], 0LL);
if (x != 0) {
mx += max(0LL, a[x] - a[x - 1]);
}
x = y;
if ((x != 0) && a[x] - a[x - 1] > 0) mx -= a[x] - a[x - 1];
if (x != n - 1) mx -= max(0LL, a[x + 1] - a[x]);
if (x == 0) mx -= a[0], mx += t;
a[x] = t;
if (x != n - 1) mx += max(a[x + 1] - a[x], 0LL);
if (x != 0) {
mx += max(0LL, a[x] - a[x - 1]);
}
cout << mx << '\n';
}
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cout << fixed << setprecision(11);
long long t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
The official capital and the cultural capital of Berland are connected by a single road running through n regions. Each region has a unique climate, so the i-th (1 β€ i β€ n) region has a stable temperature of ti degrees in summer.
This summer a group of m schoolchildren wants to get from the official capital to the cultural capital to visit museums and sights. The trip organizers transport the children between the cities in buses, but sometimes it is very hot. Specifically, if the bus is driving through the i-th region and has k schoolchildren, then the temperature inside the bus is ti + k degrees.
Of course, nobody likes it when the bus is hot. So, when the bus drives through the i-th region, if it has more than Ti degrees inside, each of the schoolchild in the bus demands compensation for the uncomfortable conditions. The compensation is as large as xi rubles and it is charged in each region where the temperature in the bus exceeds the limit.
To save money, the organizers of the trip may arbitrarily add or remove extra buses in the beginning of the trip, and between regions (of course, they need at least one bus to pass any region). The organizers can also arbitrarily sort the children into buses, however, each of buses in the i-th region will cost the organizers costi rubles. Please note that sorting children into buses takes no money.
Your task is to find the minimum number of rubles, which the organizers will have to spend to transport all schoolchildren.
Input
The first input line contains two integers n and m (1 β€ n β€ 105; 1 β€ m β€ 106) β the number of regions on the way and the number of schoolchildren in the group, correspondingly. Next n lines contain four integers each: the i-th line contains ti, Ti, xi and costi (1 β€ ti, Ti, xi, costi β€ 106). The numbers in the lines are separated by single spaces.
Output
Print the only integer β the minimum number of roubles the organizers will have to spend to transport all schoolchildren.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
2 10
30 35 1 100
20 35 10 10
Output
120
Input
3 100
10 30 1000 1
5 10 1000 3
10 40 1000 100000
Output
200065
Note
In the first sample the organizers will use only one bus to travel through the first region. However, the temperature in the bus will equal 30 + 10 = 40 degrees and each of 10 schoolchildren will ask for compensation. Only one bus will transport the group through the second region too, but the temperature inside won't exceed the limit. Overall, the organizers will spend 100 + 10 + 10 = 120 rubles.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
long long ans = 0;
for (int i = (0); i < (n); ++i) {
long long t, T, x, cost;
cin >> t >> T >> x >> cost;
if (t >= T) {
ans += cost + m * x;
continue;
}
long long aux1 = cost;
if (m > (T - t)) aux1 += m * x;
long long aux2 = (long long)ceil((double)(m - (T - t)) / (T - t)) + 1;
aux2 *= cost;
ans += min(aux1, aux2);
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
There are N cities numbered 1 to N, connected by M railroads.
You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.
The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes. You cannot use gold coins to pay the fare.
There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin. The transaction takes D_i minutes for each gold coin you give. You can exchange any number of gold coins at each exchange counter.
For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.
Constraints
* 2 \leq N \leq 50
* N-1 \leq M \leq 100
* 0 \leq S \leq 10^9
* 1 \leq A_i \leq 50
* 1 \leq B_i,C_i,D_i \leq 10^9
* 1 \leq U_i < V_i \leq N
* There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).
* Each city t=2,...,N can be reached from City 1 with some number of railroads.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N
Output
For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.
Examples
Input
3 2 1
1 2 1 2
1 3 2 4
1 11
1 2
2 5
Output
2
14
Input
4 4 1
1 2 1 5
1 3 4 4
2 4 2 2
3 4 1 1
3 1
3 1
5 2
6 4
Output
5
5
7
Input
6 5 1
1 2 1 1
1 3 2 1
2 4 5 1
3 5 11 1
1 6 50 1
1 10000
1 3000
1 700
1 100
1 1
100 1
Output
1
9003
14606
16510
16576
Input
4 6 1000000000
1 2 50 1
1 3 50 5
1 4 50 7
2 3 50 2
2 4 50 4
3 4 50 3
10 2
4 4
5 5
7 7
Output
1
3
5
Input
2 1 0
1 2 1 1
1 1000000000
1 1
Output
1000000001
### Response
```cpp
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=59,M=109;
struct edge{int to,nxt,a,w;}e[M*2]; int hd[N],tot;
void add(int u,int v,int a,int w){e[++tot]=(edge){v,hd[u],a,w};hd[u]=tot;}
int n,m,s; int maxs; int c[N],d[N]; int dis[N][N*N],ans[N];
struct node{
int u,sil,f;
bool operator < (const node b)const{return f>b.f;}
bool operator > (const node b)const{return f<b.f;}
};
void dijkstra(){
memset(dis,0x3f,sizeof(dis)); memset(ans,0x3f,sizeof(ans));
priority_queue<node>q; q.push((node){1,s}); dis[1][s]=0;
while(!q.empty()){
int u=q.top().u,sil=q.top().sil; q.pop();
ans[u]=min(ans[u],dis[u][sil]);
for(int i=hd[u],v;i;i=e[i].nxt){
if(e[i].a<=sil&&dis[v=e[i].to][sil-e[i].a]>dis[u][sil]+e[i].w)
q.push((node){v,sil-e[i].a,dis[v][sil-e[i].a]=dis[u][sil]+e[i].w});
}
if(sil<maxs&&dis[u][min(sil+c[u],maxs)]>dis[u][sil]+d[u])
q.push((node){u,min(maxs,sil+c[u]),dis[u][min(sil+c[u],maxs)]=dis[u][sil]+d[u]});
}
}
signed main(){
scanf("%lld%lld%lld",&n,&m,&s);
for(int i=1,u,v,a,w;i<=m;i++)
scanf("%lld%lld%lld%lld",&u,&v,&a,&w),add(u,v,a,w),add(v,u,a,w),maxs+=a;
s=min(s,maxs);
for(int i=1;i<=n;i++)
scanf("%lld%lld",&c[i],&d[i]);
dijkstra();
for(int i=2;i<=n;i++) printf("%lld\n",ans[i]);
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
A restaurant received n orders for the rental. Each rental order reserve the restaurant for a continuous period of time, the i-th order is characterized by two time values β the start time li and the finish time ri (li β€ ri).
Restaurant management can accept and reject orders. What is the maximal number of orders the restaurant can accept?
No two accepted orders can intersect, i.e. they can't share even a moment of time. If one order ends in the moment other starts, they can't be accepted both.
Input
The first line contains integer number n (1 β€ n β€ 5Β·105) β number of orders. The following n lines contain integer values li and ri each (1 β€ li β€ ri β€ 109).
Output
Print the maximal number of orders that can be accepted.
Examples
Input
2
7 11
4 7
Output
1
Input
5
1 2
2 3
3 4
4 5
5 6
Output
3
Input
6
4 8
1 5
4 7
2 5
1 3
6 8
Output
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, ans = 1;
pair<int, int> p[500000];
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> p[i].second >> p[i].first;
}
sort(p, p + n);
int r = p[0].first;
for (int i = 1; i < n; i++) {
if (p[i].second > r) {
ans++;
r = p[i].first;
}
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
We have N balls. The i-th ball has an integer A_i written on it.
For each k=1, 2, ..., N, solve the following problem and print the answer.
* Find the number of ways to choose two distinct balls (disregarding order) from the N-1 balls other than the k-th ball so that the integers written on them are equal.
Constraints
* 3 \leq N \leq 2 \times 10^5
* 1 \leq A_i \leq N
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
For each k=1,2,...,N, print a line containing the answer.
Examples
Input
5
1 1 2 1 2
Output
2
2
3
2
3
Input
4
1 2 3 4
Output
0
0
0
0
Input
5
3 3 3 3 3
Output
6
6
6
6
6
Input
8
1 2 1 4 2 1 4 1
Output
5
7
5
7
7
5
7
5
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> a(n);
for (auto&& e : a)
cin >> e;
vector<int64_t> c(n + 1);
for (const auto& e : a)
c[e]++;
int64_t ans = 0;
for (const auto& e : c)
ans += e * (e - 1) / 2;
for (const auto& e : a)
cout << ans - (c[e] - 1) << endl;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character.
You are playing the game on the new generation console so your gamepad have 26 buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons are pairwise distinct.
You are given a sequence of hits, the i-th hit deals a_i units of damage to the opponent's character. To perform the i-th hit you have to press the button s_i on your gamepad. Hits are numbered from 1 to n.
You know that if you press some button more than k times in a row then it'll break. You cherish your gamepad and don't want to break any of its buttons.
To perform a brutality you have to land some of the hits of the given sequence. You are allowed to skip any of them, however changing the initial order of the sequence is prohibited. The total damage dealt is the sum of a_i over all i for the hits which weren't skipped.
Note that if you skip the hit then the counter of consecutive presses the button won't reset.
Your task is to skip some hits to deal the maximum possible total damage to the opponent's character and not break your gamepad buttons.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of hits and the maximum number of times you can push the same button in a row.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the damage of the i-th hit.
The third line of the input contains the string s consisting of exactly n lowercase Latin letters β the sequence of hits (each character is the letter on the button you need to press to perform the corresponding hit).
Output
Print one integer dmg β the maximum possible damage to the opponent's character you can deal without breaking your gamepad buttons.
Examples
Input
7 3
1 5 16 18 7 2 10
baaaaca
Output
54
Input
5 5
2 4 1 3 1000
aaaaa
Output
1010
Input
5 4
2 4 1 3 1000
aaaaa
Output
1009
Input
8 1
10 15 2 1 4 8 15 16
qqwweerr
Output
41
Input
6 3
14 18 9 19 2 15
cccccc
Output
52
Input
2 1
10 10
qq
Output
10
Note
In the first example you can choose hits with numbers [1, 3, 4, 5, 6, 7] with the total damage 1 + 16 + 18 + 7 + 2 + 10 = 54.
In the second example you can choose all hits so the total damage is 2 + 4 + 1 + 3 + 1000 = 1010.
In the third example you can choose all hits expect the third one so the total damage is 2 + 4 + 3 + 1000 = 1009.
In the fourth example you can choose hits with numbers [2, 3, 6, 8]. Only this way you can reach the maximum total damage 15 + 2 + 8 + 16 = 41.
In the fifth example you can choose only hits with numbers [2, 4, 6] with the total damage 18 + 19 + 15 = 52.
In the sixth example you can change either first hit or the second hit (it does not matter) with the total damage 10.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
const long long INF = 2e18;
void print(int a[], int n) {
for (int i = 0; i < n; i++) cout << a[i] << " ";
cout << "\n";
}
void printll(long long a[], long long n) {
for (int i = 0; i < n; i++) cout << a[i] << " ";
cout << "\n";
}
void _print(long long t) { cerr << t; }
void _print(int t) { cerr << t; }
void _print(string t) { cerr << t; }
void _print(char t) { cerr << t; }
void _print(double t) { cerr << t; }
void _print(unsigned long long t) { cerr << t; }
template <class T, class V>
void _print(pair<T, V> p);
template <class T>
void _print(vector<T> v);
template <class T>
void _print(set<T> v);
template <class T, class V>
void _print(map<T, V> v);
template <class T>
void _print(multiset<T> v);
template <class T, class V>
void _print(pair<T, V> p) {
cerr << "{";
_print(p.first);
cerr << ",";
_print(p.second);
cerr << "}";
}
template <class T>
void _print(vector<T> v) {
cerr << "[ ";
for (T i : v) {
_print(i);
cerr << " ";
}
cerr << "]";
}
template <class T>
void _print(set<T> v) {
cerr << "[ ";
for (T i : v) {
_print(i);
cerr << " ";
}
cerr << "]";
}
template <class T>
void _print(multiset<T> v) {
cerr << "[ ";
for (T i : v) {
_print(i);
cerr << " ";
}
cerr << "]";
}
template <class T, class V>
void _print(map<T, V> v) {
cerr << "[ ";
for (auto i : v) {
_print(i);
cerr << " ";
}
cerr << "]";
}
vector<int> primes;
void sieve() {
bool isPrime[10000 + 5];
memset(isPrime, true, sizeof(isPrime));
for (int i = 3; i * i <= 10000 + 5; i += 2) {
if (isPrime[i]) {
for (int j = i * i; j <= 10000 + 5; j += 2 * i) {
isPrime[j] = false;
}
}
}
primes.push_back(2);
for (int i = 3; i < 10000 + 5; i += 2) {
if (isPrime[i]) primes.push_back(i);
}
}
vector<long long> findPrimeFactors(long long n) {
vector<long long> primeFactors;
while (n % 2 == 0) primeFactors.push_back(2), n = n / 2;
for (long long i = 3; i * i <= n; i = i + 2) {
while (n % i == 0) {
primeFactors.push_back(i);
n = n / i;
}
}
if (n > 2) primeFactors.push_back(n);
return primeFactors;
}
vector<long long> allDivisiors(long long n) {
vector<long long> divisors;
long long limit = sqrt(n + 1);
for (long long i = 1; i <= limit; i++) {
if (n % i == 0) {
if (n / i == i)
divisors.push_back(i);
else
divisors.push_back(i), divisors.push_back(n / i);
}
}
return divisors;
}
bool isPrime(long long n) {
if (n == 2 or n == 3) return true;
if (n % 2 == 0) return false;
for (long long i = 3; i * i <= n; i += 2)
if (n % i == 0) return false;
return true;
}
long long nsum(long long n) { return (n * (n + 1)) / 2; }
long long power(long long n, long long p) {
if (p == 0) return 1;
if (p == 1) return n;
long long ans = 1;
while (p) {
if (p & 1) ans = ans * n;
n = n * n;
p = p / 2;
}
return ans;
}
long long mpower(long long n, long long p, long long mod) {
if (p == -1) p = mod - 2;
if (p == 0) return 1;
if (p == 1) return n;
long long ans = 1;
while (p) {
if (p & 1) ans = (ans * n) % mod;
n = (n * n) % mod;
p = p / 2;
}
return ans;
}
bool isPalindrome(string s) {
int N = s.size();
for (int i = 0; i < (N / 2); i++) {
if (s[i] != s[N - 1 - i]) return 0;
}
return 1;
}
long long mod = 1e9 + 7;
void solve() {
long long n;
cin >> n;
long long k;
cin >> k;
long long a[n];
for (int i = 0; i < (n); i++) cin >> a[i];
string s;
cin >> s;
long long mx = 2e5 + 5;
vector<vector<long long>> v(mx);
v[0].push_back(a[0]);
long long j = 0;
for (int i = 1; i <= (n - 1); i++) {
if (s[i] == s[i - 1]) {
v[j].push_back(a[i]);
} else {
j++;
v[j].push_back(a[i]);
}
}
long long sum = 0;
for (int i = 0; i < (mx); i++) {
long long x = v[i].size();
if (x == 0) break;
sort(v[i].begin(), v[i].end(), greater<int>());
x = min(k, x);
for (int j = 0; j < (x); j++) {
sum += v[i][j];
}
}
cout << sum << "\n";
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int tc = 1;
for (int i = 1; i <= tc; i++) {
solve();
}
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
This time Baby Ehab will only cut and not stick. He starts with a piece of paper with an array a of length n written on it, and then he does the following:
* he picks a range (l, r) and cuts the subsegment a_l, a_{l + 1}, β¦, a_r out, removing the rest of the array.
* he then cuts this range into multiple subranges.
* to add a number theory spice to it, he requires that the elements of every subrange must have their product equal to their [least common multiple (LCM)](https://en.wikipedia.org/wiki/Least_common_multiple).
Formally, he partitions the elements of a_l, a_{l + 1}, β¦, a_r into contiguous subarrays such that the product of every subarray is equal to its LCM. Now, for q independent ranges (l, r), tell Baby Ehab the minimum number of subarrays he needs.
Input
The first line contains 2 integers n and q (1 β€ n,q β€ 10^5) β the length of the array a and the number of queries.
The next line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^5) β the elements of the array a.
Each of the next q lines contains 2 integers l and r (1 β€ l β€ r β€ n) β the endpoints of this query's interval.
Output
For each query, print its answer on a new line.
Example
Input
6 3
2 3 10 7 5 14
1 6
2 4
3 5
Output
3
1
2
Note
The first query asks about the whole array. You can partition it into [2], [3,10,7], and [5,14]. The first subrange has product and LCM equal to 2. The second has product and LCM equal to 210. And the third has product and LCM equal to 70. Another possible partitioning is [2,3], [10,7], and [5,14].
The second query asks about the range (2,4). Its product is equal to its LCM, so you don't need to partition it further.
The last query asks about the range (3,5). You can partition it into [10,7] and [5].
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N = 100001;
#define maxINF 1e18
#define minINF 1e-18
#define FASTIO ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
#define pri(a,s,n) for(int i = s; i < n; i++) cout<<a[i]<<" "; cout << endl
int main()
{
FASTIO;
int t = 1; //cin >> t;
int sieve[N] = {0};
for(int i = 2; i < N; i++){
if(sieve[i] == 0){
for(int j = 1; j*i < N; j++) sieve[j*i] = i;
}
}
sieve[1] = 1;
for(int qw = 1; qw <= t; qw++){
int n,q; cin >> n >> q;
vector<int> a(n),last(n),primes(N,0);
vector<vector<int>> pr(n);
for(int i = 0; i < n; i++){
cin >> a[i];
int s = sieve[a[i]], o = a[i];
pr[i].push_back(s);
while(o != 1){
if(sieve[o] != s){
s = sieve[o];
pr[i].push_back(s);
}
o /= s;
}
}
int l = 0, r = 1;
for(int i = 0; i < pr[l].size(); i++) primes[pr[l][i]] = 1;
while(r < n){
int i;
if(a[r] == 1){r++; continue;}
for(i = 0; i < pr[r].size(); i++){
if(primes[pr[r][i]] == 1){
last[l] = r-1;
for(int i = 0; i < pr[l].size(); i++) primes[pr[l][i]] = 0;
l++;
i--;
}
else primes[pr[r][i]] = 1;
}
r++;
}
while(l < n){
last[l] = r-1; l++;
}
//pri(last,0,n);
vector<vector<ll>> dp(n);
for(int i = 0; (1<<i) <= n; i++){
for(int j = 0; j < n; j++){
if(i == 0) dp[j].push_back(last[j]);
else if(dp[j][dp[j].size()-1] == n-1) continue;
else if(dp[dp[j][dp[j].size()-1]+1].size() < i) continue;
else dp[j].push_back(dp[dp[j][dp[j].size()-1]+1][i-1]);
//if(i > 0) cout<<i<<" "<<j<<" "<<dp[j][dp[j].size()-1] <<" "<< dp[dp[j][dp[j].size()-1]+1][i-1] << endl;
}
}
// for(int i = 0; i < n; i++){
// for(int j = 0; j < dp[i].size(); j++) cout << dp[i][j]<<" ";
// cout << endl;
// }
// q=0;
while(q--){
cin >> l >> r;
int c = 0,i = 0,p=1;
l--;r--;
while(dp[l][0] < r){
//cout<<l<<" "<<i<<" "<<dp[l][i]<<" ";
if(dp[l].size() > i && dp[l][i] < r) {i++;}
else if(dp[l].size() > i && dp[l][i] == r) {c += (1<<i);p=0; break;}
else {c += (1<<(i-1)); l = dp[l][i-1]+1; i = 0;}
//cout << c << endl;
}
cout << c + p << endl;
}
}
}
/*10 6
1 1 1 1 3 1 1 6 1 1*/
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest.
In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the rating of i-th student as ai. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings.
He thinks that each student will take place equal to <image>. In particular, if student A has rating strictly lower then student B, A will get the strictly better position than B, and if two students have equal ratings, they will share the same position.
GukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.
Input
The first line contains integer n (1 β€ n β€ 2000), number of GukiZ's students.
The second line contains n numbers a1, a2, ... an (1 β€ ai β€ 2000) where ai is the rating of i-th student (1 β€ i β€ n).
Output
In a single line, print the position after the end of the contest for each of n students in the same order as they appear in the input.
Examples
Input
3
1 3 3
Output
3 1 1
Input
1
1
Output
1
Input
5
3 5 3 4 5
Output
4 1 4 3 1
Note
In the first sample, students 2 and 3 are positioned first (there is no other student with higher rating), and student 1 is positioned third since there are two students with higher rating.
In the second sample, first student is the only one on the contest.
In the third sample, students 2 and 5 share the first position with highest rating, student 4 is next with third position, and students 1 and 3 are the last sharing fourth position.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
int n;
cin >> n;
vector<pair<int, int> > A;
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
A.push_back(make_pair(x, i));
}
sort(A.rbegin(), A.rend());
int ans[n];
ans[A[0].second] = 1;
for (int i = 1; i < A.size(); ++i) {
if (A[i].first == A[i - 1].first)
ans[A[i].second] = ans[A[i - 1].second];
else
ans[A[i].second] = i + 1;
}
for (int i = 0; i < n; ++i) {
cout << ans[i] << " ";
}
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Problem statement
There is a town with a size of H in the north-south direction and W in the east-west direction. In the town, square plots with a side length of 1 are maintained without gaps, and one house is built in each plot.
A typhoon broke out over a section of the town, causing damage and then changing to an extratropical cyclone over a section. No damage is done after the change. As shown in the figure below, a typhoon is a square with a height of 3 and a width of 3, and the square with a star is called the center. The typhoon moves to the vicinity of 8 in units of sections. In other words, the center of the typhoon moves with the whole so that it moves to the section that shares the sides or vertices (including the current section). However, the typhoon does not protrude outside the town, and the center of the typhoon is the 0th and H-1st sections from the north and the 0th and W-1st sections from the west, as shown in the shaded area in the figure below. Move so that it does not pass.
<image>
Once a typhoon hits the sky, the degree of damage to the house changes as follows.
> No damage β Partially damaged β Half destroyed β Completely destroyed β No trace
Fortunately, however, there seems to be no house that has become a trace pear. Since the damage situation of each house is given, find the point where the typhoon occurred and the point where it changed to an extratropical cyclone. However, if the generated section is s_ith from the north, s_jth from the west, and the section changed to an extratropical cyclone is t_ith from the north and t_jth from the west, the two points are 10000 t_i + t_j β€ 10000 s_i + s_j. Determined to meet.
input
H \ W
D_ {11} \β¦ \ D_ {1W}
D_ {21} \β¦ \ D_ {2W}
...
D_ {H1} \β¦ \ D_ {HW}
D_ {ij} is an integer that expresses the degree of damage to the i-th house from the north and the j-th house from the west as follows.
* 0: No damage
* 1: Partially damaged
* 2: Half destroyed
* 3: Completely destroyed
Constraint
* An integer
* Input is given only if the answer is uniquely determined
* 3 β€ H, W β€ 500
* 0 β€ D_ {ij} β€ 3
output
Output the answer in one line as follows.
s_i \ s_j \ t_i \ t_j
sample
Sample input 1
7 5
0 0 0 0 0
0 1 1 1 0
0 2 2 2 0
0 3 3 3 0
0 2 2 2 0
0 1 1 1 0
0 0 0 0 0
Sample output 1
4 2 2 2
Sample input 2
6 6
0 0 0 1 1 1
0 0 0 2 2 2
0 0 1 3 3 2
1 2 3 3 2 1
1 2 3 2 1 0
1 2 2 1 0 0
Sample output 2
4 1 1 4
Sample input 3
4 4
2 2 2 0
2 2 2 0
2 2 2 0
0 0 0 0
Sample output 3
1 1 1 1
Example
Input
7 5
0 0 0 0 0
0 1 1 1 0
0 2 2 2 0
0 3 3 3 0
0 2 2 2 0
0 1 1 1 0
0 0 0 0 0
Output
4 2 2 2
### Response
```cpp
#include "bits/stdc++.h"
using namespace std;
//#define int long long
#define DEBUG 0
#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define rrep(i,a,b) for(int i=(b)-1;i>=(a);i--)
#define all(a) (a).begin(),(a).end()
#define dump(o) if(DEBUG){cerr<<#o<<" "<<o<<endl;}
#define dumpc(o) if(DEBUG){cerr<<#o; for(auto &e:(o))cerr<<" "<<e;cerr<<endl;}
using ll = long long; using ull = unsigned long long; using pii = pair<int, int>;
static const int INF = 0x3f3f3f3f; static const long long INFL = 0x3f3f3f3f3f3f3f3fLL;
static const int MOD = 1e9 + 7;
#if DEBUG
const int MAX = 10;
#else
const int MAX = 510;
#endif
int D[MAX][MAX] = {};
int H, W;
bool A[MAX][MAX] = {};
signed main() {
cin >> H >> W;
rep(i, 0, H)rep(j, 0, W) {
cin >> D[i][j];
}
rep(i, 0, H)rep(j, 0, W) {
if (D[i][j]) {
A[i + 1][j + 1] = true;
int d = D[i][j];
rep(ii, i, i + 3)rep(jj, j, j + 3) {
D[ii][jj] -= d;
}
}
}
rep(i, 0, H)dumpc(A[i]);
vector<pii> v;
rep(i, 0, H)rep(j, 0, W) {
if (!A[i][j])continue;
int cnt = 0;
rep(ii, i - 1, i + 2)rep(jj, j - 1, j + 2) {
if (A[ii][jj])cnt++;
}
if (cnt == 2)v.emplace_back(pii(i, j));
if (cnt == 1) {
v.emplace_back(pii(i, j));
v.emplace_back(pii(i, j));
}
}
dump(v.size());
sort(all(v));
cout << v[1].first << " " << v[1].second << " " << v[0].first << " " << v[0].second << endl;
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* It visits each vertex exactly once.
Constraints
* 2 β€ |V| β€ 15
* 0 β€ di β€ 1,000
* There are no multiedge
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target vertices of i-th edge (directed) and di represents the distance between si and ti (the i-th edge).
Output
Print the shortest distance in a line. If there is no solution, print -1.
Examples
Input
4 6
0 1 2
1 2 3
1 3 9
2 0 1
2 3 6
3 2 4
Output
16
Input
3 3
0 1 1
1 2 1
0 2 1
Output
-1
### Response
```cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int INF = 100000;
const int MAX_V = 15;
int d[MAX_V][MAX_V];
int V;
int dp[1 << MAX_V][MAX_V];
int solve(int S, int v)
{
if(dp[S][v] >= 0) return dp[S][v];
if(S == (1 << V) - 1 && v == 0) return dp[S][v] = 0;
int ans = INF;
for(int u = 0; u < V; u++)
if(!(S >> u & 1))
ans = min(ans, solve(S | 1 << u, u) + d[v][u]);
return dp[S][v] = ans;
}
int main()
{
int E;
scanf("%d %d", &V, &E);
fill(&d[0][0], &d[MAX_V][0], INF);
for(int i = 0; i < E; i++){
int s, t, c;
scanf("%d %d %d", &s, &t, &c);
d[s][t] = c;
}
fill(&dp[0][0], &dp[1 << MAX_V][0], -1);
int ans = solve(0, 0);
if(ans != INF)
printf("%d\n", ans);
else
printf("-1\n");
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Levko loves tables that consist of n rows and n columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals k.
Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.
Input
The single line contains two integers, n and k (1 β€ n β€ 100, 1 β€ k β€ 1000).
Output
Print any beautiful table. Levko doesn't like too big numbers, so all elements of the table mustn't exceed 1000 in their absolute value.
If there are multiple suitable tables, you are allowed to print any of them.
Examples
Input
2 4
Output
1 3
3 1
Input
4 7
Output
2 1 0 4
4 0 2 1
1 3 3 0
0 3 2 2
Note
In the first sample the sum in the first row is 1 + 3 = 4, in the second row β 3 + 1 = 4, in the first column β 1 + 3 = 4 and in the second column β 3 + 1 = 4. There are other beautiful tables for this sample.
In the second sample the sum of elements in each row and each column equals 7. Besides, there are other tables that meet the statement requirements.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int gcd(long long int a, long long int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
int main() {
long long int n, k, i, j;
cin >> n >> k;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (i == j)
cout << k << " ";
else
cout << "0 ";
}
cout << endl;
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
You are given an undirected graph with N vertices and M edges. Here, N-1β€Mβ€N holds and the graph is connected. There are no self-loops or multiple edges in this graph.
The vertices are numbered 1 through N, and the edges are numbered 1 through M. Edge i connects vertices a_i and b_i.
The color of each vertex can be either white or black. Initially, all the vertices are white. Snuke is trying to turn all the vertices black by performing the following operation some number of times:
* Select a pair of adjacent vertices with the same color, and invert the colors of those vertices. That is, if the vertices are both white, then turn them black, and vice versa.
Determine if it is possible to turn all the vertices black. If the answer is positive, find the minimum number of times the operation needs to be performed in order to achieve the objective.
Constraints
* 2β€Nβ€10^5
* N-1β€Mβ€N
* 1β€a_i,b_iβ€N
* There are no self-loops or multiple edges in the given graph.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1
a_2 b_2
:
a_M b_M
Output
If it is possible to turn all the vertices black, print the minimum number of times the operation needs to be performed in order to achieve the objective. Otherwise, print `-1` instead.
Examples
Input
6 5
1 2
1 3
1 4
2 5
2 6
Output
5
Input
3 2
1 2
2 3
Output
-1
Input
4 4
1 2
2 3
3 4
4 1
Output
2
Input
6 6
1 2
2 3
3 1
1 4
1 5
1 6
Output
7
### Response
```cpp
#include <bits/stdc++.h>
#define N 100005
#define ll long long
#define NoSolution return puts("-1"),0
#define For(i,x,y) for(int i=(x);i<=(y);++i)
#define Rof(i,x,y) for(int i=(x);i>=(y);--i)
#define Edge(x) for(int i=head[x];i;i=e[i].nxt)
#define mset(x,y) memset(x,y,sizeof(x))
#define p_b push_back
using namespace std;
int f[N],fa[N],dep[N],cnt=0,b[N],_u,_v;
vector<int> g[N];
void dfs(int x,int v){
f[x]=v;
for(auto to:g[x]){
if(!dep[to]){
fa[to]=x,dep[to]=dep[x]+1;
dfs(to,-v);
f[x]+=f[to];
} else if(to!=fa[x]){
_u=x,_v=to;
}
}
}
int main(){
int n,m,u,v,ans=INT_MAX,mid,tmp,cnt;
dep[1]=1;
scanf("%d%d",&n,&m);
For(i,1,m){
scanf("%d%d",&u,&v);
g[u].p_b(v),g[v].p_b(u);
}
dfs(1,1);
if(m==n-1){
ans=0;
if(f[1]) NoSolution;
For(i,1,n) ans+=abs(f[i]);
printf("%d\n",ans);
} else{
if((dep[_v]-dep[_u]+1)%2==0){
if(f[1]) NoSolution;
tmp=0,cnt=0;
For(i,1,n) tmp+=abs(f[i]);
ans=min(ans,tmp);
for(int i=_v;i!=_u;i=fa[i]) tmp-=abs(f[i]),b[++cnt]=f[i];
sort(b+1,b+cnt+1);
cnt&1?mid=b[(cnt+1)/2]:mid=(b[cnt/2]+b[cnt/2+1])/2;
tmp+=abs(mid);
for(int i=_v;i!=_u;i=fa[i]) tmp+=abs(f[i]-mid);
ans=min(ans,tmp);
printf("%d\n",ans);
} else{
if(f[1]%2) NoSolution;
int tmp=f[1]/2;ans=abs(tmp);
for(int i=_u;i;i=fa[i]) f[i]-=tmp;
for(int i=_v;i;i=fa[i]) f[i]-=tmp;
For(i,1,n) ans+=abs(f[i]);
printf("%d\n",ans);
}
}
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Diameter of a Tree
Given a tree T with non-negative weight, find the diameter of the tree.
The diameter of a tree is the maximum distance between two nodes in a tree.
Constraints
* 1 β€ n β€ 100,000
* 0 β€ wi β€ 1,000
Input
n
s1 t1 w1
s2 t2 w2
:
sn-1 tn-1 wn-1
The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively.
In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge.
Output
Print the diameter of the tree in a line.
Examples
Input
4
0 1 2
1 2 1
1 3 3
Output
5
Input
4
0 1 1
1 2 2
2 3 4
Output
7
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
const int SIZE = 100001;
vector<pair<int, int>> A[SIZE];
int max_distance = 0, farthest;
bool color[SIZE];
void dfs(int x = 0, int dist = 0){
color[x] = true;
for (int i = 0; i < A[x].size(); i++){
if (max_distance < dist){
farthest = x;
max_distance = dist;
}
if (color[A[x][i].first]) continue;
dfs(A[x][i].first, dist + A[x][i].second);
}
}
int main(){
int n, s, t, w;
cin >> n;
for (int i = 1; i < n; i++){
cin >> s >> t >> w;
A[s].push_back(make_pair(t, w));
A[t].push_back(make_pair(s, w));
}
dfs();
for (int i = 0; i < SIZE; i++)color[i] = false;
dfs(farthest);
cout << max_distance << endl;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Input
The input contains two integers a1, a2 (0 β€ ai β€ 109), separated by a single space.
Output
Output a single integer.
Examples
Input
3 14
Output
44
Input
27 12
Output
48
Input
100 200
Output
102
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a, b;
string s1, s2;
cin >> a >> s1;
for (int i = 0; i <= (int)s1.length() - 1; i++) {
s2 = s1[i] + s2;
}
sscanf(s2.c_str(), "%d", &b);
cout << a + b << endl;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
There are N people numbered 1 to N. Each person wears a red hat or a blue hat.
You are given a string s representing the colors of the people. Person i wears a red hat if s_i is `R`, and a blue hat if s_i is `B`.
Determine if there are more people wearing a red hat than people wearing a blue hat.
Constraints
* 1 \leq N \leq 100
* |s| = N
* s_i is `R` or `B`.
Input
Input is given from Standard Input in the following format:
N
s
Output
If there are more people wearing a red hat than there are people wearing a blue hat, print `Yes`; otherwise, print `No`.
Examples
Input
4
RRBR
Output
Yes
Input
4
BRBR
Output
No
### Response
```cpp
#include <bits/stdc++.h>
int main() {
int N; std::cin >> N;
std::string s; std::cin >> s;
int r = std::count(s.begin(), s.end(), 'R');
std::cout << ((r + r > s.length()) ? "Yes" : "No") << std::endl;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Takahashi's house has only one socket.
Takahashi wants to extend it with some number of power strips, each with A sockets, into B or more empty sockets.
One power strip with A sockets can extend one empty socket into A empty sockets.
Find the minimum number of power strips required.
Constraints
* All values in input are integers.
* 2 \leq A \leq 20
* 1 \leq B \leq 20
Input
Input is given from Standard Input in the following format:
A B
Output
Print the minimum number of power strips required.
Examples
Input
4 10
Output
3
Input
8 9
Output
2
Input
8 8
Output
1
### Response
```cpp
#include<stdio.h>
int main()
{
int A,B;
scanf("%d%d",&A,&B);
printf("%d\n",(A+B-3)/(A-1));
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet:
* has at least one red bean (or the number of red beans r_i β₯ 1);
* has at least one blue bean (or the number of blue beans b_i β₯ 1);
* the number of red and blue beans should differ in no more than d (or |r_i - b_i| β€ d)
Can you distribute all beans?
Input
The first line contains the single integer t (1 β€ t β€ 1000) β the number of test cases.
The first and only line of each test case contains three integers r, b, and d (1 β€ r, b β€ 10^9; 0 β€ d β€ 10^9) β the number of red and blue beans and the maximum absolute difference in each packet.
Output
For each test case, if you can distribute all beans, print YES. Otherwise, print NO.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
4
1 1 0
2 7 3
6 1 4
5 4 0
Output
YES
YES
NO
NO
Note
In the first test case, you can form one packet with 1 red and 1 blue bean. The absolute difference |1 - 1| = 0 β€ d.
In the second test case, you can form two packets: 1 red and 4 blue beans in the first packet and 1 red and 3 blue beans in the second one.
In the third test case, since b = 1, you can form only one packet with 6 red and 1 blue beans. The absolute difference |6 - 1| = 5 > d.
In the fourth test case, since d = 0 so each packet should contain the same number of red and blue beans, but r β b.
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main()
{
long long int n,r,b,d,minn=0,maxn;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>r>>b>>d;
if(abs(r-b)>d)
{
minn=min(r,b);
maxn=abs(r-b)/minn;
if(maxn>d)
{
printf("NO\n");
}
if(maxn==d)
{
if(abs(r-b)%minn==0)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
if(maxn<d)
{
printf("YES\n");
}
}
else
{
printf("YES\n");
}
}
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
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 main() {
int n;
cin >> n;
int minCost = 0;
for (int i = 1; i < n - 1; i++) {
minCost += 1 * (i + 1) * (i + 2);
}
cout << minCost << endl;
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
"The Chamber of Secrets has been opened again" β this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anybody to be able to enter the chamber. The Dark Lord is going to be busy sucking life out of Ginny.
The Chamber of Secrets is an n Γ m rectangular grid in which some of the cells are columns. A light ray (and a basilisk's gaze) passes through the columns without changing its direction. But with some spell we can make a column magic to reflect the light ray (or the gaze) in all four directions when it receives the ray. This is shown in the figure below.
<image> The left light ray passes through a regular column, and the right ray β through the magic column.
The basilisk is located at the right side of the lower right cell of the grid and is looking to the left (in the direction of the lower left cell). According to the legend, anyone who meets a basilisk's gaze directly dies immediately. But if someone meets a basilisk's gaze through a column, this person will get petrified. We know that the door to the Chamber is located on the left side of the upper left corner of the grid and anyone who wants to enter will look in the direction of its movement (in the direction of the upper right cell) from that position.
<image> This figure illustrates the first sample test.
Given the dimensions of the chamber and the location of regular columns, Lord Voldemort has asked you to find the minimum number of columns that we need to make magic so that anyone who wants to enter the chamber would be petrified or just declare that it's impossible to secure the chamber.
Input
The first line of the input contains two integer numbers n and m (2 β€ n, m β€ 1000). Each of the next n lines contains m characters. Each character is either "." or "#" and represents one cell of the Chamber grid. It's "." if the corresponding cell is empty and "#" if it's a regular column.
Output
Print the minimum number of columns to make magic or -1 if it's impossible to do.
Examples
Input
3 3
.#.
...
.#.
Output
2
Input
4 3
##.
...
.#.
.#.
Output
2
Note
The figure above shows the first sample test. In the first sample we should make both columns magic. The dragon figure represents the basilisk and the binoculars represent the person who will enter the Chamber of secrets. The black star shows the place where the person will be petrified. Yellow lines represent basilisk gaze moving through columns.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e3 + 10;
int n, m, d[maxn][maxn], val[maxn][maxn];
string s[maxn];
vector<int> rows[maxn], cols[maxn];
bool marked[maxn][maxn];
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> s[i];
for (int j = 0; j < m; j++) {
if (s[i][j] == '#') {
rows[i].push_back(j);
cols[j].push_back(i);
}
}
}
queue<pair<int, int>> q;
q.push(make_pair(n - 1, m));
val[n - 1][m] = 1;
while (!q.empty()) {
auto v = q.front();
q.pop();
if (val[v.first][v.second]) {
for (int c : rows[v.first]) {
if (!marked[v.first][c]) {
d[v.first][c] = d[v.first][v.second] + 1;
q.push(make_pair(v.first, c));
marked[v.first][c] = true;
val[v.first][c] = 0;
}
}
} else {
for (int r : cols[v.second]) {
if (!marked[r][v.second]) {
d[r][v.second] = d[v.first][v.second] + 1;
q.push(make_pair(r, v.second));
marked[r][v.second] = true;
val[r][v.second] = 1;
}
}
}
}
int ans = 1e9;
for (int i = 0; i < m; i++) {
if (s[0][i] == '#' && marked[0][i]) ans = min(ans, d[0][i]);
}
if (ans == 1e9)
cout << -1 << endl;
else
cout << ans << endl;
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Princess Heidi decided to give orders to all her K Rebel ship commanders in person. Unfortunately, she is currently travelling through hyperspace, and will leave it only at N specific moments t1, t2, ..., tN. The meetings with commanders must therefore start and stop at those times. Namely, each commander will board her ship at some time ti and disembark at some later time tj. Of course, Heidi needs to meet with all commanders, and no two meetings can be held during the same time. Two commanders cannot even meet at the beginnings/endings of the hyperspace jumps, because too many ships in one position could give out their coordinates to the enemy.
Your task is to find minimum time that Princess Heidi has to spend on meetings, with her schedule satisfying the conditions above.
Input
The first line contains two integers K, N (2 β€ 2K β€ N β€ 500000, K β€ 5000). The second line contains N distinct integers t1, t2, ..., tN (1 β€ ti β€ 109) representing the times when Heidi leaves hyperspace.
Output
Output only one integer: the minimum time spent on meetings.
Examples
Input
2 5
1 4 6 7 12
Output
4
Input
3 6
6 3 4 2 5 1
Output
3
Input
4 12
15 7 4 19 3 30 14 1 5 23 17 25
Output
6
Note
In the first example, there are five valid schedules: [1, 4], [6, 7] with total time 4, [1, 4], [6, 12] with total time 9, [1, 4], [7, 12] with total time 8, [1, 6], [7, 12] with total time 10, and [4, 6], [7, 12] with total time 7. So the answer is 4.
In the second example, there is only 1 valid schedule: [1, 2], [3, 4], [5, 6].
For the third example, one possible schedule with total time 6 is: [1, 3], [4, 5], [14, 15], [23, 25].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 7;
const int K = 5e3 + 3;
const int INF = 4e9;
int k, n;
int t[N], a[N];
vector<pair<int, int> > z;
vector<int> id;
int dp[2][K][2];
void minimize(int &x, int y) {
if (y < x) x = y;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> k >> n;
for (int i = 1; i <= n; ++i) cin >> t[i];
sort(t + 1, t + n + 1);
for (int i = 1; i <= n - 1; ++i) z.push_back(make_pair(t[i + 1] - t[i], i));
sort(z.begin(), z.end());
for (int i = 0; i < min((int)z.size(), k << 2); ++i) {
id.push_back(z[i].second);
id.push_back(z[i].second + 1);
}
sort(id.begin(), id.end());
id.erase(unique(id.begin(), id.end()), id.end());
sort(id.begin(), id.end());
id.resize(unique(id.begin(), id.end()) - id.begin());
n = 0;
for (int i = 0; i < id.size(); ++i) a[++n] = t[id[i]];
for (int i = 0; i < 2; ++i) {
for (int j = 0; j <= min(n >> 1, k); ++j) {
for (int last = 0; last < 2; ++last) {
dp[i][j][last] = INF;
}
}
}
dp[0][0][0] = 0;
for (int i = 2; i <= n; ++i) {
for (int j = 0; j <= min(i >> 1, k); ++j) {
for (int last = 0; last < 2; ++last) {
if (dp[0][j][last] == INF) {
continue;
}
for (int chosen = 0; chosen < 2; ++chosen) {
if (last && chosen) continue;
minimize(dp[1][j + chosen][chosen],
dp[0][j][last] + (chosen ? (a[i] - a[i - 1]) : 0));
}
}
}
for (int j = 0; j <= min(i >> 1, k); ++j)
for (int last = 0; last < 2; ++last) {
dp[0][j][last] = dp[1][j][last];
dp[1][j][last] = INF;
}
}
cout << min(dp[0][k][0], dp[0][k][1]) << endl;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Given the string S and m queries. The i-th query is given by the two strings xi and yi.
For each query, answer the longest substring of the string S, starting with xi and ending with yi.
For the string S, | S | represents the length of S. Also, the fact that the character string T is a substring of the character string S means that a certain integer i exists and Tj = Si + j is satisfied for 1 β€ j β€ | T |. Where Tj represents the jth character of T.
Constraints
* 1 β€ | S | β€ 2 x 105
* 1 β€ m β€ 105
* 1 β€ | xi |, | yi |
* $ \ sum ^ m_ {i = 1} $ (| xi | + | yi |) β€ 2 x 105
* S and xi, yi consist only of half-width lowercase letters.
Input
The input is given in the following format.
S
m
x1 y1
x2 y2
::
xm ym
* The character string S is given on the first line.
* The number of queries m is given in the second line.
* Of the m lines from the 3rd line, the i-th query string xi, yi is given on the i-th line, separated by spaces.
Output
Answer the maximum substring length in the following format.
len1
len2
::
lenm
Output the longest substring length leni that satisfies the condition for the i-th query on the i-th line of the m lines from the first line. If there is no such substring, output 0.
Examples
Input
abracadabra
5
ab a
a a
b c
ac ca
z z
Output
11
11
4
3
0
Input
howistheprogress
4
ist prog
s ss
how is
the progress
Output
9
12
5
11
Input
icpcsummertraining
9
mm m
icpc summer
train ing
summer mm
i c
i i
g g
train i
summer er
Output
2
10
8
0
4
16
1
6
6
### Response
```cpp
#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
using namespace std;
using ll = long long;
class SuffixArray
{
public:
SuffixArray(const string& s) : s{s}, index1{static_cast<int>(s.size())}, suffix_array(index1 + 1), rank(index1 + 1), lcp(index1 + 1), buf(index1 + 1)
{
for (int i = 0; i <= index1; i++) {
suffix_array[i] = i;
rank[i] = i < index1 ? s[i] : -1;
}
auto comp = [&](const int i, const int j) {
if (rank[i] != rank[j]) {
return rank[i] < rank[j];
} else {
const int ri = (i + index2 <= index1) ? rank[i + index2] : -1;
const int rj = (j + index2 <= index1) ? rank[j + index2] : -1;
return ri < rj;
}
};
for (index2 = 1; index2 <= index1; index2 *= 2) {
sort(suffix_array.begin(), suffix_array.end(), comp);
buf[suffix_array[0]] = 0;
for (int i = 1; i <= index1; i++) {
buf[suffix_array[i]] = buf[suffix_array[i - 1]] + (comp(suffix_array[i - 1], suffix_array[i]) ? 1 : 0);
}
for (int i = 0; i <= index1; i++) {
rank[i] = buf[i];
}
}
for (int i = 0; i <= index1; i++) {
rank[suffix_array[i]] = i;
}
int h = 0;
lcp[0] = 0;
for (int i = 0; i < index1; i++) {
{
const int j = suffix_array[rank[i] - 1];
if (h > 0) {
h--;
}
for (; j + h < index1 and i + h < index1; h++) {
if (s[j + h] != s[i + h]) {
break;
}
}
lcp[rank[i] - 1] = h;
}
}
}
bool contain(const string& t) const
{
int a = 0;
int b = s.size();
while (b - a > 1) {
const int c = (a + b) / 2;
if (s.compare(suffix_array[c], t.size(), t) < 0) {
a = c;
} else {
b = c;
}
}
return s.compare(suffix_array[b], t.size(), t) == 0;
}
int lower_bound(const string& suffix) const
{
int a = 0;
int b = s.size() + 1;
while (b - a > 1) {
const int c = (a + b) / 2;
if (s.compare(suffix_array[c], string::npos, suffix) < 0) {
a = c;
} else {
b = c;
}
}
return b;
}
int upper_bound(const string& suffix) const
{
int a = 0;
int b = s.size() + 1;
while (b - a > 1) {
const int c = (a + b) / 2;
if (s.compare(suffix_array[c], suffix.size(), suffix) <= 0) {
a = c;
} else {
b = c;
}
}
return b;
}
const vector<int>& getArray() const
{
return suffix_array;
}
private:
const string s;
const int index1;
int index2;
vector<int> suffix_array;
vector<int> rank;
vector<int> lcp;
vector<int> buf;
};
template <typename Base>
class SparseTable
{
public:
using T = typename Base::T;
using SemiLattice = Base;
SparseTable(const vector<T>& val) : size(val.size()), lg2(size + 1, 0)
{
for (int i = 2; i <= size; i++) {
lg2[i] = lg2[i / 2] + 1;
}
table.resize(size, vector<T>(lg2[size] + 1));
for (int i = 0; i < size; i++) {
table[i][0] = val[i];
}
for (int j = 0; j < lg2[size]; j++) {
const int w = 1 << j;
for (int i = 0; i <= size - (w << 1); i++) {
T tl = table[i][j], tr = table[i + w][j];
table[i][j + 1] = op(tl, tr);
}
}
}
T accumulate(const int l, const int r) const
{
assert(0 <= l and l < r and r <= size);
const int j = lg2[r - l];
return op(table[l][j], table[r - (1 << j)][j]);
}
private:
const int size;
vector<int> lg2;
vector<vector<T>> table;
const SemiLattice op{};
};
struct Min {
using T = int;
T operator()(const T& a, const T& b) const
{
return min(a, b);
}
};
struct Max {
using T = int;
T operator()(const T& a, const T& b) const
{
return max(a, b);
}
};
int main()
{
string s;
cin >> s;
SuffixArray sa(s);
// for (const int i : sa.getArray()) {
// cerr << s.substr(i, s.size() - i) << endl;
// }
SparseTable<Min> stmin{sa.getArray()};
SparseTable<Max> stmax{sa.getArray()};
int m;
cin >> m;
for (int i = 0; i < m; i++) {
string x, y;
cin >> x >> y;
const int xl = sa.lower_bound(x);
const int xr = sa.upper_bound(x);
const int yl = sa.lower_bound(y);
const int yr = sa.upper_bound(y);
if (xl < xr and yl < yr) {
const int lower = stmin.accumulate(xl, xr);
const int upper = stmax.accumulate(yl, yr);
if (lower + x.size() <= upper + y.size()) {
cout << upper - lower + y.size() << endl;
} else {
cout << 0 << endl;
}
} else {
cout << 0 << endl;
}
}
return 0;
}
``` |
### 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;
long long v[100005][3];
long long a, b, c, sum, dif, x, ansx, ansy, ansz;
long long a1, a2, b1, b2, c1, c2, s1, s2;
long long l, r, mid;
int n;
const long long inf = 1ll << 62;
long long div2(long long x) {
if (x < 0)
return (x - 1) / 2;
else
return x / 2;
}
int main() {
int tc;
scanf("%d", &tc);
while (tc--) {
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%I64d%I64d%I64d", &v[i][0], &v[i][1], &v[i][2]);
l = 0, r = inf;
while (l <= r) {
mid = (l + r) / 2;
a1 = b1 = c1 = s1 = -inf;
a2 = b2 = c2 = s2 = inf;
for (int i = 1; i <= n; i++) {
a1 = max(v[i][1] + v[i][2] - v[i][0] - mid, a1);
a2 = min(v[i][1] + v[i][2] - v[i][0] + mid, a2);
b1 = max(v[i][0] + v[i][2] - v[i][1] - mid, b1);
b2 = min(v[i][0] + v[i][2] - v[i][1] + mid, b2);
c1 = max(v[i][0] + v[i][1] - v[i][2] - mid, c1);
c2 = min(v[i][0] + v[i][1] - v[i][2] + mid, c2);
s1 = max(v[i][0] + v[i][1] + v[i][2] - mid, s1);
s2 = min(v[i][0] + v[i][1] + v[i][2] + mid, s2);
}
if (a1 > a2 || b1 > b2 || c1 > c2 || s1 > s2) {
l = mid + 1;
continue;
}
long long xmn = max(div2(s1 - a2 + 1), div2(b1 + c1 + 1));
long long xmx = min(div2(s2 - a1), div2(b2 + c2));
for (x = xmn; x <= xmx; x++) {
for (sum = max(a1 + x, s1 - x); sum <= min(a2 + x, s2 - x); sum++) {
for (dif = max(x - b2, c1 - x); dif <= min(x - b1, c2 - x); dif++)
if ((sum + dif) % 2 == 0) break;
if (dif <= min(x - b1, c2 - x)) break;
}
if (sum <= min(a2 + x, s2 - x)) break;
}
if (x <= xmx) {
ansx = x;
ansy = div2(sum + dif);
ansz = div2(sum - dif);
r = mid - 1;
} else
l = mid + 1;
}
printf("%I64d %I64d %I64d\n", ansx, ansy, ansz);
}
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
You are given a string s, consisting of lowercase Latin letters. While there is at least one character in the string s that is repeated at least twice, you perform the following operation:
* you choose the index i (1 β€ i β€ |s|) such that the character at position i occurs at least two times in the string s, and delete the character at position i, that is, replace s with s_1 s_2 β¦ s_{i-1} s_{i+1} s_{i+2} β¦ s_n.
For example, if s="codeforces", then you can apply the following sequence of operations:
* i=6 β s="codefrces";
* i=1 β s="odefrces";
* i=7 β s="odefrcs";
Given a given string s, find the lexicographically maximum string that can be obtained after applying a certain sequence of operations after which all characters in the string become unique.
A string a of length n is lexicographically less than a string b of length m, if:
* there is an index i (1 β€ i β€ min(n, m)) such that the first i-1 characters of the strings a and b are the same, and the i-th character of the string a is less than i-th character of string b;
* or the first min(n, m) characters in the strings a and b are the same and n < m.
For example, the string a="aezakmi" is lexicographically less than the string b="aezus".
Input
The first line contains one integer t (1 β€ t β€ 10^4). Then t test cases follow.
Each test case is characterized by a string s, consisting of lowercase Latin letters (1 β€ |s| β€ 2 β
10^5).
It is guaranteed that the sum of the lengths of the strings in all test cases does not exceed 2 β
10^5.
Output
For each test case, output the lexicographically maximum string that can be obtained after applying a certain sequence of operations after which all characters in the string become unique.
Example
Input
6
codeforces
aezakmi
abacaba
convexhull
swflldjgpaxs
myneeocktxpqjpz
Output
odfrces
ezakmi
cba
convexhul
wfldjgpaxs
myneocktxqjpz
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
/*
find my code templates at https://github.com/galencolin/cp-templates
also maybe subscribe please thanks
*/
#define send {ios_base::sync_with_stdio(false);}
#define help {cin.tie(NULL);}
#define f first
#define s second
#define getunique(v) {sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end());}
typedef long long ll;
typedef long double lld;
typedef unsigned long long ull;
template<typename A> ostream& operator<<(ostream &cout, vector<A> const &v);
template<typename A, typename B> ostream& operator<<(ostream &cout, pair<A, B> const &p) { return cout << "(" << p.f << ", " << p.s << ")"; }
template<typename A> ostream& operator<<(ostream &cout, vector<A> const &v) {
cout << "["; for(int i = 0; i < v.size(); i++) {if (i) cout << ", "; cout << v[i];} return cout << "]";
}
template<typename A, typename B> istream& operator>>(istream& cin, pair<A, B> &p) {
cin >> p.first;
return cin >> p.second;
}
mt19937_64 rng(std::chrono::steady_clock::now().time_since_epoch().count());
// mt19937_64 rng(61378913);
/* usage - just do rng() */
void usaco(string filename) {
// #pragma message("be careful, freopen may be wrong")
freopen((filename + ".in").c_str(), "r", stdin);
freopen((filename + ".out").c_str(), "w", stdout);
}
// #include <atcoder/all>
// using namespace atcoder;
const lld pi = 3.14159265358979323846;
// const ll mod = 1000000007;
// const ll mod = 998244353;
// ll mod;
ll n, m, q, k, l, r, x, y, z;
const ll template_array_size = 1e6 + 14342;
ll a[template_array_size];
ll b[template_array_size];
ll c[template_array_size];
string s, t;
ll ans = 0;
void solve(int tc = 0) {
cin >> s;
n = s.length();
ll vis[26];
ll cnt[26] = {0};
for (char c: s) ++cnt[c - 'a'];
for (ll i = 0; i < 26; i++) vis[i] = !cnt[i];
vector<ll> inds;
inds.push_back(-1);
for (ll i = 0; i < 26; i++) {
bool pos = 0;
for (ll j = 25; j >= 0; j--) {
if (!vis[j]) {
for (ll k = inds.back() + 1; k < n; k++) {
if (s[k] - 'a' == j) {
for (ll l = inds.back() + 1; l < k; l++) {
--cnt[s[l] - 'a'];
}
bool can = 1;
for (ll v = 0; v < 26; v++) {
if (!vis[v] && cnt[v] == 0) {
can = 0;
break;
}
}
if (can) {
pos = 1;
inds.push_back(k);
vis[j] = 1;
} else {
for (ll l = inds.back() + 1; l < k; l++) {
++cnt[s[l] - 'a'];
}
}
break;
}
}
if (pos) break;
}
}
}
for (ll x: inds) if (x != -1) cout << s[x];
cout << '\n';
}
int main() {
#ifdef galen_colin_local
auto begin = std::chrono::high_resolution_clock::now();
#endif
send help
#ifndef galen_colin_local
// usaco("code");
#endif
// usaco("cowland");
// freopen("tc.cpp", "r", stdin);
// freopen("tc2.cpp", "w", stdout);
cout << setprecision(15) << fixed;
int tc = 1;
cin >> tc;
for (int t = 0; t < tc; t++) solve(t);
#ifdef galen_colin_local
auto end = std::chrono::high_resolution_clock::now();
cerr << setprecision(4) << fixed;
// cerr << "Execution time: " << std::chrono::duration_cast<std::chrono::duration<double>>(end - begin).count() << " seconds" << endl;
#endif
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Your favorite shop sells n Kinder Surprise chocolate eggs. You know that exactly s stickers and exactly t toys are placed in n eggs in total.
Each Kinder Surprise can be one of three types:
* it can contain a single sticker and no toy;
* it can contain a single toy and no sticker;
* it can contain both a single sticker and a single toy.
But you don't know which type a particular Kinder Surprise has. All eggs look identical and indistinguishable from each other.
What is the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and at least one toy?
Note that you do not open the eggs in the purchasing process, that is, you just buy some number of eggs. It's guaranteed that the answer always exists.
Input
The first line contains the single integer T (1 β€ T β€ 100) β the number of queries.
Next T lines contain three integers n, s and t each (1 β€ n β€ 10^9, 1 β€ s, t β€ n, s + t β₯ n) β the number of eggs, stickers and toys.
All queries are independent.
Output
Print T integers (one number per query) β the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and one toy
Example
Input
3
10 5 7
10 10 10
2 1 1
Output
6
1
2
Note
In the first query, we have to take at least 6 eggs because there are 5 eggs with only toy inside and, in the worst case, we'll buy all of them.
In the second query, all eggs have both a sticker and a toy inside, that's why it's enough to buy only one egg.
In the third query, we have to buy both eggs: one with a sticker and one with a toy.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long int n, s, t, q, i, z, x;
cin >> q;
for (i = 0; i < q; i++) {
cin >> n >> s >> t;
if (n - s >= n - t && s + t >= n) {
cout << n - s + 1 << endl;
} else if (n - t >= n - s && s + t >= n) {
cout << n - t + 1 << endl;
}
}
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Sometime the classic solution are not powerful enough and we have to design our own. For the purpose of this problem you have to implement the part of the system of task scheduling.
Each task should be executed at some particular moments of time. In our system you may set the exact value for the second, minute, hour, day of the week, day and month, when the task should be executed. Moreover, one can set a special value -1 that means any value of this parameter is valid.
For example, if the parameter string is -1 59 23 -1 -1 -1, the problem will be executed every day at 23:59:00, 23:59:01, 23:59:02, ..., 23:59:59 (60 times in total).
Seconds, minutes and hours are numbered starting from zero, while day, months and days of the week are numbered starting from one. The first day of the week is Monday.
There is one special case that is treated separately. If both day of the week and day are given (i.e. differ from -1) to execute the task only one of these two (at least one, if both match this is fine too) parameters should match the current time (of course, all other parameters should match too). For example, the string of parameters 0 0 12 6 3 7 means that the task will be executed both on Saturday, July 2nd, 2016 and on Sunday, July 3rd, 2016 at noon.
One should not forget about the existence of the leap years. The year is leap if it's number is divisible by 400, or is not divisible by 100, but is divisible by 4. Each leap year has 366 days instead of usual 365, by extending February to 29 days rather than the common 28.
The current time is represented as the number of seconds passed after 00:00:00 January 1st, 1970 (Thursday).
You are given the string of six parameters, describing the moments of time the task should be executed. You are also given a number of moments of time. For each of them you have to find the first moment of time strictly greater than the current when the task will be executed.
Input
The first line of the input contains six integers s, m, h, day, date and month (0 β€ s, m β€ 59, 0 β€ h β€ 23, 1 β€ day β€ 7, 1 β€ date β€ 31, 1 β€ month β€ 12). Each of the number can also be equal to - 1. It's guaranteed, that there are infinitely many moments of time when this task should be executed.
Next line contains the only integer n (1 β€ n β€ 1000) β the number of moments of time you have to solve the problem for. Each of the next n lines contains a single integer ti (0 β€ ti β€ 1012).
Output
Print n lines, the i-th of them should contain the first moment of time strictly greater than ti, when the task should be executed.
Examples
Input
-1 59 23 -1 -1 -1
6
1467372658
1467417540
1467417541
1467417598
1467417599
1467417600
Output
1467417540
1467417541
1467417542
1467417599
1467503940
1467503940
Input
0 0 12 6 3 7
3
1467372658
1467460810
1467547200
Output
1467460800
1467547200
1468065600
Note
The moment of time 1467372658 after the midnight of January 1st, 1970 is 11:30:58 July 1st, 2016.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int sec[86500], cs, day[150000], ds, cur;
int s, m, h, d, dt, mt, T;
long long perioid, dd, ss, x, ans;
bool leap(int y) {
if (y % 4) return false;
if (y % 100) return true;
if (y % 400) return false;
return true;
}
int leap_month(int y, int m) { return (leap(y) && m == 1); }
bool valid(int _mt, int _dt, int _d) {
if (mt != -1 && mt != _mt) return false;
if ((dt == -1 && d == -1) || dt == _dt || d == _d) return true;
return false;
}
const int dmon[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
void prepare() {
for (int i = 0; i < 24; i++)
if (h == -1 || h == i)
for (int j = 0; j < 60; j++)
if (m == -1 || m == j)
for (int k = 0; k < 60; k++)
if (s == -1 || s == k) sec[cs++] = i * 3600 + j * 60 + k;
for (int i = 0; i < 400; i++) {
for (int j = 0; j < 12; j++) {
int tot = dmon[j] + leap_month(i + 1970, j);
for (int k = 0; k < tot; k++) {
if (valid(j, k, (cur + 3) % 7)) day[ds++] = cur;
cur++;
}
}
}
perioid = cur * 86400ll;
}
int main() {
scanf("%d %d %d %d %d %d", &s, &m, &h, &d, &dt, &mt);
if (d > 0) d--;
if (dt > 0) dt--;
if (mt > 0) mt--;
prepare();
for (scanf("%d", &T); T--;) {
scanf("%I64d", &x);
ans = x - x % perioid;
x = x - ans;
dd = x / 86400;
ss = x % 86400;
int it = lower_bound(day, day + ds, dd) - day;
if (it == ds)
ans += perioid + day[0] * 86400ll + sec[0];
else if (day[it] > dd)
ans += day[it] * 86400ll + sec[0];
else {
int id = upper_bound(sec, sec + cs, ss) - sec;
if (id < cs)
ans += day[it] * 86400ll + sec[id];
else {
it++;
if (it == ds)
ans += perioid + day[0] * 86400ll + sec[0];
else
ans += day[it] * 86400ll + sec[0];
}
}
printf("%I64d\n", ans);
}
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.
The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.
Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.
If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
Input
The first line of input contains n β a positive integer number without leading zeroes (1 β€ n < 10100000).
Output
Print one number β any beautiful number obtained by erasing as few as possible digits. If there is no answer, print - 1.
Examples
Input
1033
Output
33
Input
10
Output
0
Input
11
Output
-1
Note
In the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n[100005];
char in[100005];
vector<int> m[3];
void print(int l, int p = -1, int q = -1) {
bool flag = false;
int c = (p < 0 ? 0 : 1) + (q < 0 ? 0 : 1);
for (int i = 0; i < l; i++) {
if (i != p && i != q) {
if (!(n[i] == 0 && !flag)) {
printf("%d", n[i]);
flag = true;
}
}
}
if (!flag) printf("%s", l <= c ? "-1" : "0");
puts("");
}
int main() {
scanf("%s", in);
int l = strlen(in), t = 0;
for (int i = 0; i < l; i++) {
n[i] = in[i] - '0';
t = (t + n[i]) % 3;
if (n[i] % 3 == 1) m[1].push_back(i);
if (n[i] % 3 == 2) m[2].push_back(i);
}
if (t == 0)
print(l);
else {
if (m[t].size() > 0) {
if (m[t].size() == 1 && m[t][0] == 0 && n[1] == 0 &&
m[t == 1 ? 2 : 1].size() >= 2)
print(l, m[t == 1 ? 2 : 1][m[t == 1 ? 2 : 1].size() - 2],
m[t == 1 ? 2 : 1].back());
else
print(l, m[t].back());
} else if (m[t == 1 ? 2 : 1].size() >= 2)
print(l, m[t == 1 ? 2 : 1][m[t == 1 ? 2 : 1].size() - 2],
m[t == 1 ? 2 : 1].back());
else
puts("-1");
}
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
You are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S.
Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from n given points.
Input
In the first line of the input two integers n and S (3 β€ n β€ 5000, 1 β€ S β€ 1018) are given β the number of points given and the upper bound value of any triangle's area, formed by any three of given n points.
The next n lines describes given points: ith of them consists of two integers xi and yi ( - 108 β€ xi, yi β€ 108) β coordinates of ith point.
It is guaranteed that there is at least one triple of points not lying on the same line.
Output
Print the coordinates of three points β vertices of a triangle which contains all n points and which area doesn't exceed 4S.
Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value.
It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.
Example
Input
4 1
0 0
1 0
0 1
1 1
Output
-1 0
2 0
0 2
Note
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline void read(int &x) {
int v = 0, f = 1;
char c = getchar();
while (!isdigit(c) && c != '-') c = getchar();
if (c == '-')
f = -1;
else
v = (c & 15);
while (isdigit(c = getchar())) v = (v << 1) + (v << 3) + (c & 15);
x = v * f;
}
inline void read(long long &x) {
long long v = 0ll, f = 1ll;
char c = getchar();
while (!isdigit(c) && c != '-') c = getchar();
if (c == '-')
f = -1;
else
v = (c & 15);
while (isdigit(c = getchar())) v = (v << 1) + (v << 3) + (c & 15);
x = v * f;
}
inline void readc(char &x) {
char c;
while (((c = getchar()) == ' ') || c == '\n')
;
x = c;
}
long long m, res;
int n, i, j, k, cnt, tp;
struct ii {
int x, y;
} a[5005], stk[5005], b[5005], s1, s2, s3, sm;
bool cmp(ii x, ii y) {
if (x.x == y.x) return x.y > y.y;
return x.x < y.x;
}
ii operator-(ii x, ii y) { return (ii){x.x - y.x, x.y - y.y}; }
ii operator+(ii x, ii y) { return (ii){x.x + y.x, x.y + y.y}; }
long long crs(ii x, ii y) { return 1ll * x.x * y.y - 1ll * x.y * y.x; }
int main() {
read(n);
read(m);
for (((i)) = (1); ((i)) <= ((n)); ((i))++) {
read(a[i].x);
read(a[i].y);
}
sort(a + 1, a + n + 1, cmp);
for (((i)) = (1); ((i)) <= ((n)); ((i))++) {
while (tp > 1 && crs(stk[tp] - stk[tp - 1], a[i] - stk[tp]) >= 0) {
tp--;
}
stk[++tp] = a[i];
}
for (((i)) = (1); ((i)) <= ((tp - 1)); ((i))++) b[++cnt] = stk[i];
tp = 0;
for (((i)) = ((n)); ((i)) >= (1); ((i))--) {
while (tp > 1 && crs(stk[tp] - stk[tp - 1], a[i] - stk[tp]) >= 0) {
tp--;
}
stk[++tp] = a[i];
}
for (((i)) = (1); ((i)) <= ((tp - 1)); ((i))++) b[++cnt] = stk[i];
b[cnt + 1] = b[1];
for (((i)) = (1); ((i)) <= ((cnt - 2)); ((i))++) {
k = i + 2;
for (j = i + 1; j <= cnt - 1; j++) {
while (k <= cnt && crs(b[k] - b[i], b[j] - b[i]) <=
crs(b[k + 1] - b[i], b[j] - b[i])) {
k++;
}
if (crs(b[k] - b[i], b[j] - b[i]) > res) {
res = crs(b[k] - b[i], b[j] - b[i]);
s1 = b[i];
s2 = b[j];
s3 = b[k];
}
}
}
sm = s1 + s2 + s3;
s1 = sm - s1 - s1;
s2 = sm - s2 - s2;
s3 = sm - s3 - s3;
printf("%d %d\n", s1.x, s1.y);
printf("%d %d\n", s2.x, s2.y);
printf("%d %d\n", s3.x, s3.y);
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Snuke lives at position x on a number line. On this line, there are two stores A and B, respectively at position a and b, that offer food for delivery.
Snuke decided to get food delivery from the closer of stores A and B. Find out which store is closer to Snuke's residence.
Here, the distance between two points s and t on a number line is represented by |s-t|.
Constraints
* 1 \leq x \leq 1000
* 1 \leq a \leq 1000
* 1 \leq b \leq 1000
* x, a and b are pairwise distinct.
* The distances between Snuke's residence and stores A and B are different.
Input
Input is given from Standard Input in the following format:
x a b
Output
If store A is closer, print `A`; if store B is closer, print `B`.
Examples
Input
5 2 7
Output
B
Input
1 999 1000
Output
A
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main()
{
int x,a,b; cin>>x>>a>>b;
if(abs(x-a)<abs(x-b))
cout<<"A"<<"\n";
else cout<<"B"<<"\n";
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Gennady is one of the best child dentists in Berland. Today n children got an appointment with him, they lined up in front of his office.
All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to n in the order they go in the line. Every child is associated with the value of his cofidence pi. The children take turns one after another to come into the office; each time the child that is the first in the line goes to the doctor.
While Gennady treats the teeth of the i-th child, the child is crying with the volume of vi. At that the confidence of the first child in the line is reduced by the amount of vi, the second one β by value vi - 1, and so on. The children in the queue after the vi-th child almost do not hear the crying, so their confidence remains unchanged.
If at any point in time the confidence of the j-th child is less than zero, he begins to cry with the volume of dj and leaves the line, running towards the exit, without going to the doctor's office. At this the confidence of all the children after the j-th one in the line is reduced by the amount of dj.
All these events occur immediately one after the other in some order. Some cries may lead to other cries, causing a chain reaction. Once in the hallway it is quiet, the child, who is first in the line, goes into the doctor's office.
Help Gennady the Dentist to determine the numbers of kids, whose teeth he will cure. Print their numbers in the chronological order.
Input
The first line of the input contains a positive integer n (1 β€ n β€ 4000) β the number of kids in the line.
Next n lines contain three integers each vi, di, pi (1 β€ vi, di, pi β€ 106) β the volume of the cry in the doctor's office, the volume of the cry in the hall and the confidence of the i-th child.
Output
In the first line print number k β the number of children whose teeth Gennady will cure.
In the second line print k integers β the numbers of the children who will make it to the end of the line in the increasing order.
Examples
Input
5
4 2 2
4 1 2
5 2 4
3 3 5
5 1 2
Output
2
1 3
Input
5
4 5 1
5 3 9
4 1 2
2 1 8
4 1 9
Output
4
1 2 4 5
Note
In the first example, Gennady first treats the teeth of the first child who will cry with volume 4. The confidences of the remaining children will get equal to - 2, 1, 3, 1, respectively. Thus, the second child also cries at the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 0, 2, 0. Then the third child will go to the office, and cry with volume 5. The other children won't bear this, and with a loud cry they will run to the exit.
In the second sample, first the first child goes into the office, he will cry with volume 4. The confidence of the remaining children will be equal to 5, - 1, 6, 8. Thus, the third child will cry with the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 5, 5, 7. After that, the second child goes to the office and cry with the volume of 5. The confidences of the remaining children will be equal to 0, 3. Then the fourth child will go into the office and cry with the volume of 2. Because of this the confidence of the fifth child will be 1, and he will go into the office last.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void itval(istream_iterator<string> it) {}
template <typename T, typename... Args>
void itval(istream_iterator<string> it, T a, Args... args) {
cerr << *it << " = " << a << endl;
itval(++it, args...);
}
const long long int MOD = 1e9 + 7;
template <typename T>
inline void print(T x) {
cout << x << "\n";
}
template <typename T>
inline void printvec(T x) {
for (auto a : x) cout << a << ' ';
cout << '\n';
}
struct custom {
bool operator()(const pair<long long int, long long int> &p1,
const pair<long long int, long long int> &p2) const {
if (p1.first == p2.first) return p2.second < p1.second;
return p1.first < p2.first;
}
};
long long int get_pow(long long int a, long long int b) {
long long int res = 1;
while (b) {
if (b & 1) res = (res * a) % MOD;
a = (a * a) % MOD;
b >>= 1;
}
return res;
}
const long long int N = 1e3 + 10, inf = 1e17;
void solve() {
int n;
cin >> n;
std::vector<long long int> v(n), p(n), d(n);
for (long long int i = (long long int)0; i < (long long int)(n); i++) {
cin >> v[i] >> d[i] >> p[i];
}
vector<long long> ans;
vector<bool> used(n, false);
for (long long int i = (long long int)0; i < (long long int)(n); i++) {
if (used[i]) continue;
long long int now = v[i];
ans.push_back(i + 1);
queue<int> q;
for (int j = i + 1; j < n && now > 0; j++) {
if (used[j]) continue;
p[j] -= now;
if (p[j] < 0) {
q.push(j);
used[j] = 1;
}
now--;
}
while (!q.empty()) {
int t = q.front();
q.pop();
for (long long int j = (long long int)t + 1; j < (long long int)(n);
j++) {
if (!used[j]) {
p[j] -= d[t];
if (p[j] < 0) {
used[j] = 1;
q.push(j);
}
}
}
}
}
cout << ans.size() << '\n';
printvec(ans);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int test = 1;
clock_t z = clock();
for (long long int tes = (long long int)0; tes < (long long int)(test);
tes++) {
solve();
}
fprintf(stderr, "Total Time:%.4f\n", (double)(clock() - z) / CLOCKS_PER_SEC),
fflush(stderr);
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Recently, the bear started studying data structures and faced the following problem.
You are given a sequence of integers x1, x2, ..., xn of length n and m queries, each of them is characterized by two integers li, ri. Let's introduce f(p) to represent the number of such indexes k, that xk is divisible by p. The answer to the query li, ri is the sum: <image>, where S(li, ri) is a set of prime numbers from segment [li, ri] (both borders are included in the segment).
Help the bear cope with the problem.
Input
The first line contains integer n (1 β€ n β€ 106). The second line contains n integers x1, x2, ..., xn (2 β€ xi β€ 107). The numbers are not necessarily distinct.
The third line contains integer m (1 β€ m β€ 50000). Each of the following m lines contains a pair of space-separated integers, li and ri (2 β€ li β€ ri β€ 2Β·109) β the numbers that characterize the current query.
Output
Print m integers β the answers to the queries on the order the queries appear in the input.
Examples
Input
6
5 5 7 10 14 15
3
2 11
3 12
4 4
Output
9
7
0
Input
7
2 3 5 7 11 4 8
2
8 10
2 123
Output
0
7
Note
Consider the first sample. Overall, the first sample has 3 queries.
1. The first query l = 2, r = 11 comes. You need to count f(2) + f(3) + f(5) + f(7) + f(11) = 2 + 1 + 4 + 2 + 0 = 9.
2. The second query comes l = 3, r = 12. You need to count f(3) + f(5) + f(7) + f(11) = 1 + 4 + 2 + 0 = 7.
3. The third query comes l = 4, r = 4. As this interval has no prime numbers, then the sum equals 0.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long d[10000005];
int snt[664600], dem;
bool p[10000005];
void sieve() {
int i, j;
snt[0] = 2, dem = 1;
p[0] = p[1] = true;
for (i = 4; i <= 1e7; i += 2) p[i] = true;
for (i = 3; i <= 3163; i += 2)
if (!p[i]) {
snt[dem++] = i;
for (j = i * i; j <= 1e7; j += i) p[j] = true;
}
for (; i <= 1e7; i += 2)
if (!p[i]) snt[dem++] = i;
}
void factor(int x) {
int i;
if (!p[x]) {
d[x]++;
return;
}
for (i = 0; i < dem && snt[i] * snt[i] <= x; i++)
if (x % snt[i] == 0) {
d[snt[i]]++;
while (x % snt[i] == 0) x /= snt[i];
}
if (x != 1) d[x]++;
}
void input() {
int i, n, l, r, x, nq;
sieve();
scanf("%d", &n);
for ((i) = 0; (i) < (n); (i)++) scanf("%d", &x), factor(x);
for ((i) = (3); (i) <= (10000000); (i)++) d[i] += d[i - 1];
scanf("%d", &nq);
while (nq--) {
scanf("%d %d", &l, &r);
l = ((l) < (10000000) ? (l) : (10000000));
r = ((r) < (10000000) ? (r) : (10000000));
printf("%I64d\n", d[r] - d[l - 1]);
}
}
int main() {
input();
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
You were dreaming that you are traveling to a planet named Planetforces on your personal spaceship. Unfortunately, its piloting system was corrupted and now you need to fix it in order to reach Planetforces.
<image>
Space can be represented as the XY plane. You are starting at point (0, 0), and Planetforces is located in point (p_x, p_y).
The piloting system of your spaceship follows its list of orders which can be represented as a string s. The system reads s from left to right. Suppose you are at point (x, y) and current order is s_i:
* if s_i = U, you move to (x, y + 1);
* if s_i = D, you move to (x, y - 1);
* if s_i = R, you move to (x + 1, y);
* if s_i = L, you move to (x - 1, y).
Since string s could be corrupted, there is a possibility that you won't reach Planetforces in the end. Fortunately, you can delete some orders from s but you can't change their positions.
Can you delete several orders (possibly, zero) from s in such a way, that you'll reach Planetforces after the system processes all orders?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
Each test case consists of two lines. The first line in each test case contains two integers p_x and p_y (-10^5 β€ p_x, p_y β€ 10^5; (p_x, p_y) β (0, 0)) β the coordinates of Planetforces (p_x, p_y).
The second line contains the string s (1 β€ |s| β€ 10^5: |s| is the length of string s) β the list of orders.
It is guaranteed that the sum of |s| over all test cases does not exceed 10^5.
Output
For each test case, print "YES" if you can delete several orders (possibly, zero) from s in such a way, that you'll reach Planetforces. Otherwise, print "NO". You can print each letter in any case (upper or lower).
Example
Input
6
10 5
RRRRRRRRRRUUUUU
1 1
UDDDRLLL
-3 -5
LDLDLDDDR
1 2
LLLLUU
3 -2
RDULRLLDR
-1 6
RUDURUUUUR
Output
YES
YES
YES
NO
YES
NO
Note
In the first case, you don't need to modify s, since the given s will bring you to Planetforces.
In the second case, you can delete orders s_2, s_3, s_4, s_6, s_7 and s_8, so s becomes equal to "UR".
In the third test case, you have to delete order s_9, otherwise, you won't finish in the position of Planetforces.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
long long int t;
cin>>t;
while(t--){
int x,y;
cin>>x>>y;
string s;
cin>>s;
int r=0;
int l=0;
int d=0;
int u=0;
for(int i=0;i<s.size();i++){
if(s[i]=='R')r++;
else if(s[i]=='L')l++;
else if(s[i]=='U')u++;
else if(s[i]=='D')d++;
}
// cout<<r<<l<<u<<d<<endl;
if(x>=0 && y>=0){
// cout<<"Debug"<<endl;
if(x<=r && y<=u){
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
}
else if(x>=0 && y<=0){
if(x<=r && abs(y)<=d){
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
}
else if(x<=0 && y>=0){
if(abs(x)<=l && y<=u){
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
}
else if(x<=0 && y<=0){
if(abs(x)<=l && abs(y)<=d){
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
}
}
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
After a successful field test, Heidi is considering deploying a trap along some Corridor, possibly not the first one. She wants to avoid meeting the Daleks inside the Time Vortex, so for abundance of caution she considers placing the traps only along those Corridors that are not going to be used according to the current Daleks' plan β which is to use a minimum spanning tree of Corridors. Heidi knows that all energy requirements for different Corridors are now different, and that the Daleks have a single unique plan which they are intending to use.
Your task is to calculate the number E_{max}(c), which is defined in the same way as in the easy version β i.e., the largest e β€ 10^9 such that if we changed the energy of corridor c to e, the Daleks might use it β but now for every corridor that Heidi considers.
Input
The first line: number n of destinations, number m of Time Corridors (2 β€ n β€ 10^5, n - 1 β€ m β€ 10^6). The next m lines: destinations a, b and energy e (1 β€ a, b β€ n, a β b, 0 β€ e β€ 10^9).
No pair \\{a, b\} will repeat. The graph is guaranteed to be connected. All energy requirements e are distinct.
Output
Output m-(n-1) lines, each containing one integer: E_{max}(c_i) for the i-th Corridor c_i from the input that is not part of the current Daleks' plan (minimum spanning tree).
Example
Input
3 3
1 2 8
2 3 3
3 1 4
Output
4
Note
If m = n-1, then you need not output anything.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
function<void(void)> ____ = []() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
};
const int MAXN = 1e6 + 7;
vector<pair<pair<int, int>, pair<int, int>>> e;
int n, m, root[MAXN], used[MAXN];
pair<pair<int, int>, pair<int, int>> firste;
vector<pair<int, int>> G[MAXN];
int par[MAXN][20], depth[MAXN], cost[MAXN][20];
int findroot(int x) {
if (x != root[x]) root[x] = findroot(root[x]);
return root[x];
}
void dfs(int u, int f) {
depth[u] = depth[f] + 1;
par[u][0] = f;
for (int i = 1; par[u][i - 1]; i++) {
par[u][i] = par[par[u][i - 1]][i - 1];
cost[u][i] = max(cost[u][i - 1], cost[par[u][i - 1]][i - 1]);
}
for (auto E : G[u]) {
int v = E.first;
int c = E.second;
if (v == f) continue;
cost[v][0] = c;
dfs(v, u);
}
}
int ikun(int u, int v) {
int maxx = 0;
if (depth[u] < depth[v]) swap(u, v);
for (int i = 0; depth[u] - depth[v]; i++)
if ((depth[u] - depth[v]) & (1 << i)) {
maxx = max(maxx, cost[u][i]);
u = par[u][i];
}
if (u == v) return maxx;
for (int i = 19; i >= 0; i--)
if (par[u][i] != par[v][i]) {
maxx = max(maxx, max(cost[u][i], cost[v][i]));
u = par[u][i];
v = par[v][i];
}
return max(maxx, max(cost[u][0], cost[v][0]));
}
int main() {
scanf("%d %d", &n, &m);
e.resize(m);
for (int i = 0; i < m; i++)
scanf("%d %d %d", &e[i].first.first, &e[i].first.second,
&e[i].second.first);
for (int i = 0; i < m; i++) e[i].second.second = i;
sort(e.begin(), e.end(),
[](const pair<pair<int, int>, pair<int, int>> &A,
const pair<pair<int, int>, pair<int, int>> &B) {
return A.second.first < B.second.first;
});
for (int i = 1; i <= n; i++) root[i] = i;
for (int i = 0; i < m; i++) {
int u = e[i].first.first;
int v = e[i].first.second;
if (findroot(u) == findroot(v)) continue;
root[findroot(u)] = findroot(v);
used[e[i].second.second] = 1;
}
for (int i = 0; i < m; i++) {
if (!used[e[i].second.second]) continue;
auto p = e[i];
G[p.first.first].emplace_back(make_pair(p.first.second, p.second.first));
G[p.first.second].emplace_back(make_pair(p.first.first, p.second.first));
}
dfs(1, 0);
sort(e.begin(), e.end(),
[](const pair<pair<int, int>, pair<int, int>> &A,
const pair<pair<int, int>, pair<int, int>> &B) {
return A.second.second < B.second.second;
});
for (int i = 0; i < m; i++)
if (!used[i]) printf("%d\n", ikun(e[i].first.first, e[i].first.second));
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
One day Igor K. stopped programming and took up math. One late autumn evening he was sitting at a table reading a book and thinking about something.
The following statement caught his attention: "Among any six people there are either three pairwise acquainted people or three pairwise unacquainted people"
Igor just couldn't get why the required minimum is 6 people. "Well, that's the same for five people, too!" β he kept on repeating in his mind. β "Let's take, say, Max, Ilya, Vova β here, they all know each other! And now let's add Dima and Oleg to Vova β none of them is acquainted with each other! Now, that math is just rubbish!"
Igor K. took 5 friends of his and wrote down who of them is friends with whom. Now he wants to check whether it is true for the five people that among them there are either three pairwise acquainted or three pairwise not acquainted people.
Input
The first line contains an integer m (0 β€ m β€ 10), which is the number of relations of acquaintances among the five friends of Igor's.
Each of the following m lines contains two integers ai and bi (1 β€ ai, bi β€ 5;ai β bi), where (ai, bi) is a pair of acquainted people. It is guaranteed that each pair of the acquaintances is described exactly once. The acquaintance relation is symmetrical, i.e. if x is acquainted with y, then y is also acquainted with x.
Output
Print "FAIL", if among those five people there are no either three pairwise acquainted or three pairwise unacquainted people. Otherwise print "WIN".
Examples
Input
4
1 3
2 3
1 4
5 3
Output
WIN
Input
5
1 2
2 3
3 4
4 5
5 1
Output
FAIL
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long double pi = 3.141592653589793238;
set<long long>::iterator it;
multiset<long long>::iterator itr;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
;
long long t;
t = 1;
while (t--) {
long long m;
cin >> m;
set<pair<long long, long long>> s1;
for (long long i = 0; i < m; i++) {
long long x, y;
cin >> x >> y;
s1.insert(make_pair(x, y));
s1.insert(make_pair(y, x));
}
long long fl = 0;
for (long long p1 = 1; p1 <= 5; p1++) {
for (long long p2 = p1 + 1; p2 <= 5; p2++) {
for (long long p3 = p2 + 1; p3 <= 5; p3++) {
if (s1.find(make_pair(p1, p2)) != s1.end() &&
s1.find(make_pair(p2, p3)) != s1.end() &&
s1.find(make_pair(p3, p1)) != s1.end()) {
fl = 1;
} else if (s1.find(make_pair(p1, p2)) == s1.end() &&
s1.find(make_pair(p2, p3)) == s1.end() &&
s1.find(make_pair(p3, p1)) == s1.end()) {
fl = 1;
}
}
}
}
if (fl == 1)
cout << "WIN" << endl;
else
cout << "FAIL" << endl;
}
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Write a program which manipulates a sequence A = {a0, a1, . . . , anβ1} with the following operations:
* update(s, t, x): change as, as+1, ..., at to x.
* find(i): output the value of ai.
Note that the initial values of ai (i = 0, 1, . . . , nβ1) are 231-1.
Constraints
* 1 β€ n β€ 100000
* 1 β€ q β€ 100000
* 0 β€ s β€ t < n
* 0 β€ i < n
* 0 β€ x < 231β1
Input
n q
query1
query2
:
queryq
In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:
0 s t x
or
1 i
The first digit represents the type of the query. '0' denotes update(s, t, x) and '1' denotes find(i).
Output
For each find operation, print the value.
Examples
Input
3 5
0 0 1 1
0 1 2 3
0 2 2 2
1 0
1 1
Output
1
3
Input
1 3
1 0
0 0 0 5
1 0
Output
2147483647
5
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int N, Q;
int const INF = INT_MAX;
struct LazySegmentTree {
private:
int n;
vector<int> node, lazy;
vector<bool> lazyFlag;
public:
LazySegmentTree(vector<int> v) {
int sz = (int)v.size();
n = 1; while(n < sz) n *= 2;
node.resize(2*n-1);
lazy.resize(2*n-1, INF);
lazyFlag.resize(2*n-1, false);
for(int i=0; i<sz; i++) node[i+n-1] = v[i];
for(int i=n-2; i>=0; i--) node[i] = min(node[i*2+1], node[i*2+2]);
}
void lazy_evaluate(int k, int l, int r) {
if(lazyFlag[k]) {
node[k] = lazy[k];
if(r - l > 1) {
lazy[2*k+1] = lazy[k];
lazy[2*k+2] = lazy[k];
lazyFlag[2*k+1] = true;
lazyFlag[2*k+2] = true;
}
lazyFlag[k] = false;
}
}
void update(int a, int b, int x, int k=0, int l=0, int r=-1) {
if(r < 0) r = n;
lazy_evaluate(k, l, r);
if(r <= a || b <= l) return;
if(a <= l && r <= b) {
lazy[k] = x;
lazyFlag[k] = true;
lazy_evaluate(k, l, r);
}
else {
update(a, b, x, 2*k+1, l, (l+r)/2);
update(a, b, x, 2*k+2, (l+r)/2, r);
node[k] = min(node[k*2+1], node[k*2+2]);
}
}
int find(int a, int b, int k=0, int l=0, int r=-1) {
if(r < 0) r = n;
lazy_evaluate(k, l, r);
if(r <= a || b <= l) return INF;
if(a <= l && r <= b) return node[k];
int vl = find(a, b, 2*k+1, l, (l+r)/2);
int vr = find(a, b, 2*k+2, (l+r)/2, r);
return min(vl, vr);
}
};
int main() {
cin >> N >> Q;
LazySegmentTree seg( vector<int>(N, INF) );
for(int i=0; i<Q; i++) {
int query; cin >> query;
if(query == 0) {
int s, t, x; cin >> s >> t >> x;
seg.update(s, t+1, x);
}
else {
int i; cin >> i;
cout << seg.find(i, i+1) << endl;
}
}
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
The screen that displays digital numbers that you often see on calculators is called a "7-segment display" because the digital numbers consist of seven parts (segments).
The new product to be launched by Wakamatsu will incorporate a 7-segment display into the product, and as an employee, you will create a program to display the given number on the 7-segment display.
This 7-segment display will not change until the next switch instruction is sent. By sending a signal consisting of 7 bits, the display information of each corresponding segment can be switched. Bits have a value of 1 or 0, where 1 stands for "switch" and 0 stands for "as is".
The correspondence between each bit and segment is shown in the figure below. The signal sends 7 bits in the order of "gfedcba". For example, in order to display "0" from the hidden state, "0111111" must be sent to the display as a signal. To change from "0" to "5", send "1010010". If you want to change "5" to "1" in succession, send "1101011".
<image>
Create a program that takes n (1 β€ n β€ 100) numbers that you want to display and outputs the signal sequence required to correctly display those numbers di (0 β€ di β€ 9) on the 7-segment display. please. It is assumed that the initial state of the 7-segment display is all hidden.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of -1. Each dataset is given in the following format:
n
d1
d2
::
dn
The number of datasets does not exceed 120.
Output
For each input dataset, output the sequence of signals needed to properly output the numbers to the display.
Example
Input
3
0
5
1
1
0
-1
Output
0111111
1010010
1101011
0111111
### Response
```cpp
#include <iostream>
#define rep(i, n) for(int i = 0; i < n; i ++)
using namespace std;
static const bool PATTERN[11][7] =
{
0, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 1, 1, 0,
1, 0, 1, 1, 0, 1, 1,
1, 0, 0, 1, 1, 1, 1,
1, 1, 0, 0, 1, 1, 0,
1, 1, 0, 1, 1, 0, 1,
1, 1, 1, 1, 1, 0, 1,
0, 1, 0, 0, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1,
1, 1, 0, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0
};
static const int DEFAULT = 10;
int main(void){
for(int n; cin >> n, n != -1;){
int preNum = DEFAULT;
while(n --){
int num; cin >> num;
rep(i, 7) cout << (PATTERN[preNum][i] ^ PATTERN[num][i]);
cout << endl;
preNum = num;
}
}
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.
Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?
Input
First line of input contains an integer n (2 β€ n β€ 105), the number of players.
The second line contains n integer numbers a1, a2, ..., an (1 β€ ai β€ 109) β the bids of players.
Output
Print "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise.
Examples
Input
4
75 150 75 50
Output
Yes
Input
3
100 150 250
Output
No
Note
In the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.
It can be shown that in the second sample test there is no way to make all bids equal.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b) {
if (a < b) return gcd(b, a);
if (b == 0) return a;
return gcd(b, a % b);
}
int factor(int a, int b) {
while (a % b == 0) {
a = a / b;
}
return a;
}
int num[100001];
int main() {
int n;
cin >> n;
cin >> num[0];
long long lcm = num[0];
for (int i = 1; i < n; i++) {
cin >> num[i];
lcm = gcd(lcm, num[i]);
}
for (int i = 0; i < n; i++) {
int tmp = num[i] / lcm;
int res = factor(tmp, 2);
if (res == 1 || factor(res, 3) == 1) continue;
cout << "NO";
return 0;
}
cout << "YES";
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
It's Christmas time! PolandBall and his friends will be giving themselves gifts. There are n Balls overall. Each Ball has someone for whom he should bring a present according to some permutation p, pi β i for all i.
Unfortunately, Balls are quite clumsy. We know earlier that exactly k of them will forget to bring their gift. A Ball number i will get his present if the following two constraints will hold:
1. Ball number i will bring the present he should give.
2. Ball x such that px = i will bring his present.
What is minimum and maximum possible number of kids who will not get their present if exactly k Balls will forget theirs?
Input
The first line of input contains two integers n and k (2 β€ n β€ 106, 0 β€ k β€ n), representing the number of Balls and the number of Balls who will forget to bring their presents.
The second line contains the permutation p of integers from 1 to n, where pi is the index of Ball who should get a gift from the i-th Ball. For all i, pi β i holds.
Output
You should output two values β minimum and maximum possible number of Balls who will not get their presents, in that order.
Examples
Input
5 2
3 4 1 5 2
Output
2 4
Input
10 1
2 3 4 5 6 7 8 9 10 1
Output
2 2
Note
In the first sample, if the third and the first balls will forget to bring their presents, they will be th only balls not getting a present. Thus the minimum answer is 2. However, if the first ans the second balls will forget to bring their presents, then only the fifth ball will get a present. So, the maximum answer is 4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
int n, k, p[N];
int cnt[N];
int main() {
scanf("%d%d", &n, &k);
for (int i = 1; i <= n; i++) scanf("%d", p + i);
bitset<N> vis;
vector<int> v;
for (int i = 1; i <= n; i++) {
if (vis[i]) continue;
int cur = i, cnt = 0;
while (!vis[cur]) {
cnt++;
vis[cur] = 1;
cur = p[cur];
}
v.push_back(cnt);
}
sort(v.begin(), v.end());
int tmp = k;
int ans = 0;
for (int i = 0; i < v.size(); i++) {
cnt[v[i]]++;
int x = min(tmp, v[i] / 2);
ans += x * 2;
v[i] -= x * 2;
tmp -= x;
}
for (int i = 0; i < v.size(); i++) {
int x = min(tmp, v[i]);
ans += x;
tmp -= x;
}
vis.reset();
vis[0] = 1;
int ans2 = k + 1;
for (int i = 1; i <= k; i++) {
if (i > 50) {
for (int j = 0; j < cnt[i]; j++) {
vis = (vis | (vis << i));
}
} else {
if (!cnt[i]) continue;
vector<deque<int>> dq(i);
vector<int> sum(i);
int cur = 0;
for (int j = 0; j <= k; j++) {
dq[cur].push_back(vis[j]);
sum[cur] += vis[j];
if (sum[cur]) vis[j] = 1;
if (dq[cur].size() > cnt[i]) {
sum[cur] -= dq[j % i].front();
dq[cur].pop_front();
}
++cur;
if (cur == i) cur = 0;
}
}
}
if (vis[k]) ans2 = k;
cout << ans2 << ' ' << ans << '\n';
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
AtCoDeer the deer recently bought three paint cans. The color of the one he bought two days ago is a, the color of the one he bought yesterday is b, and the color of the one he bought today is c. Here, the color of each paint can is represented by an integer between 1 and 100, inclusive.
Since he is forgetful, he might have bought more than one paint can in the same color. Count the number of different kinds of colors of these paint cans and tell him.
Constraints
* 1β¦a,b,cβ¦100
Input
The input is given from Standard Input in the following format:
a b c
Output
Print the number of different kinds of colors of the paint cans.
Examples
Input
3 1 4
Output
3
Input
3 3 33
Output
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
set<int> s; int a;
for(int i = 0; i < 3; i++) {
cin >> a;
s.insert(a);
}
cout << s.size() << endl;
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.)
You have completed many programming projects. In fact, there are exactly n types of programming projects, and you have completed a_i projects of type i. Your rΓ©sumΓ© has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired.
You want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired:
$$$ f(b_1,β¦,b_n)=β_{i=1}^n b_i(a_i-b_i^2). $$$
Here, b_i denotes the number of projects of type i you include in your rΓ©sumΓ©. Of course, you cannot include more projects than you have completed, so you require 0β€ b_i β€ a_i for all i.
Your rΓ©sumΓ© only has enough room for k projects, and you will absolutely not be hired if your rΓ©sumΓ© has empty space, so you require β_{i=1}^n b_i=k.
Find values for b_1,β¦, b_n that maximize the value of f(b_1,β¦,b_n) while satisfying the above two constraints.
Input
The first line contains two integers n and k (1β€ nβ€ 10^5, 1β€ kβ€ β_{i=1}^n a_i) β the number of types of programming projects and the rΓ©sumΓ© size, respectively.
The next line contains n integers a_1,β¦,a_n (1β€ a_iβ€ 10^9) β a_i is equal to the number of completed projects of type i.
Output
In a single line, output n integers b_1,β¦, b_n that achieve the maximum value of f(b_1,β¦,b_n), while satisfying the requirements 0β€ b_iβ€ a_i and β_{i=1}^n b_i=k. If there are multiple solutions, output any.
Note that you do not have to output the value f(b_1,β¦,b_n).
Examples
Input
10 32
1 2 3 4 5 5 5 5 5 5
Output
1 2 3 3 3 4 4 4 4 4
Input
5 8
4 4 8 2 1
Output
2 2 2 1 1
Note
For the first test, the optimal answer is f=-269. Note that a larger f value is possible if we ignored the constraint β_{i=1}^n b_i=k.
For the second test, the optimal answer is f=9.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void print(vector<long long int>& arr) {
for (auto p : arr) cout << p << " ";
cout << "\n";
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long int n, k, c = 0, v = 0;
cin >> n >> k;
vector<long long int> A(n), B, C;
for (long long int i = 0; i < n; i++) cin >> A[i];
auto f = [&](long long int a, long long int b) {
return a - 3 * b * b - 3 * b - 1;
};
long long int l = -3e18 - 5e15, r = 3e18 + 5e15;
while (l <= r) {
long long int m = (l + r) / 2;
c = k;
vector<long long int> t(n, 0);
for (long long int i = 0; i < n; i++) {
long long int L = 0, R = A[i];
while (L <= R) {
long long int M = (L + R) / 2;
if (f(A[i], M) >= m) {
t[i] = M;
L = M + 1;
} else
R = M - 1;
}
c -= t[i];
}
if (c >= 0)
r = m - 1, B = t, v = m;
else
l = m + 1;
}
c = k;
for (long long int i = 0; i < n; i++) c -= B[i];
for (long long int i = 0; i < n && c; i++) {
if (B[i] < A[i] && f(A[i], B[i] + 1) >= v - 1) B[i]++, c--;
}
print(B);
}
``` |
### Prompt
Please create a solution in cpp to 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>
int main() {
int i, j, k, n, t;
int m, dept[1008], h, sum;
scanf("%d%d%d", &n, &m, &h);
sum = 0;
for (i = 0; i < m; i++) {
scanf("%d", &dept[i]);
sum += dept[i];
}
double prob = 1.000000000;
if (sum < n)
printf("-1.0\n");
else if (dept[h - 1] == 1)
printf("0.0\n");
else {
dept[h - 1]--;
n--;
sum--;
for (i = 0; i < dept[h - 1]; i++) {
prob *= (sum - n - i);
prob /= (sum - i);
}
{
prob = 1.0 - prob;
printf("%0.12lf", prob);
printf("\n");
}
}
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
In Berland prime numbers are fashionable β the respectable citizens dwell only on the floors with numbers that are prime numbers. The numismatists value particularly high the coins with prime nominal values. All the prime days are announced holidays!
Yet even this is not enough to make the Berland people happy. On the main street of the capital stand n houses, numbered from 1 to n. The government decided to paint every house a color so that the sum of the numbers of the houses painted every color is a prime number.
However it turned out that not all the citizens approve of this decision β many of them protest because they don't want many colored houses on the capital's main street. That's why it is decided to use the minimal possible number of colors. The houses don't have to be painted consecutively, but every one of n houses should be painted some color. The one-colored houses should not stand consecutively, any way of painting is acceptable.
There are no more than 5 hours left before the start of painting, help the government find the way when the sum of house numbers for every color is a prime number and the number of used colors is minimal.
Input
The single input line contains an integer n (2 β€ n β€ 6000) β the number of houses on the main streets of the capital.
Output
Print the sequence of n numbers, where the i-th number stands for the number of color for house number i. Number the colors consecutively starting from 1. Any painting order is allowed. If there are several solutions to that problem, print any of them. If there's no such way of painting print the single number -1.
Examples
Input
8
Output
1 2 2 1 1 1 1 2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n;
int t;
int color[10005];
bool prime[50000000];
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
color[i] = 0;
}
t = n * (n + 1) / 2;
for (int i = 0; i <= t; i++) {
prime[i] = true;
}
for (int i = 2; i * i <= t; i++) {
if (prime[i] == false) {
continue;
}
for (int j = i * i; j <= t; j += i) {
prime[j] = false;
}
}
if (prime[t] == true) {
for (int i = 1; i <= n; i++) {
color[i] = 1;
}
} else {
int flag = -1;
for (int i = 2; i < t - 1; i++) {
if (prime[i] == true && prime[t - i] == true) {
flag = i;
}
}
if (flag == -1) {
color[3] = 3;
t -= 3;
flag = -1;
for (int i = 2; i < t - 1; i++) {
if (prime[i] && prime[t - i]) {
flag = i;
}
}
}
for (int i = n; i >= 1; i--) {
if (color[i] == 0 && i <= flag) {
color[i] = 1;
flag -= i;
}
}
for (int i = 1; i <= n; i++) {
if (color[i] == 0) {
color[i] = 2;
}
}
}
for (int i = 1; i <= n; i++) {
printf("%d ", color[i]);
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied:
* a12 + a22 + ... + an2 β₯ x
* a1 + a2 + ... + an β€ y
Input
The first line contains three space-separated integers n, x and y (1 β€ n β€ 105, 1 β€ x β€ 1012, 1 β€ y β€ 106).
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is recommended to use cin, cout streams or the %I64d specificator.
Output
Print n positive integers that satisfy the conditions, one integer per line. If such numbers do not exist, print a single number "-1". If there are several solutions, print any of them.
Examples
Input
5 15 15
Output
4
4
1
1
2
Input
2 3 2
Output
-1
Input
1 99 11
Output
11
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 10000 + 5;
long long a[maxn];
int main() {
long long n, x, y;
scanf("%I64d%I64d%I64d", &n, &x, &y);
if (n > y)
printf("-1\n");
else if ((y - n + 1) * (y - n + 1) + n - 1 < x)
printf("-1\n");
else {
for (int i = 1; i <= n - 1; i++) printf("1\n");
printf("%I64d\n", y - n + 1);
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Authors have come up with the string s consisting of n lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.
For all i from 1 to n-1 the following properties hold: s[p_i] β€ s[p_{i + 1}] and s[q_i] β€ s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.
Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.
If there are multiple answers, you can print any of them.
Input
The first line of the input contains two integers n and k (1 β€ n β€ 2 β
10^5, 1 β€ k β€ 26) β the length of the string and the number of distinct characters required.
The second line of the input contains n integers p_1, p_2, ..., p_n (1 β€ p_i β€ n, all p_i are distinct integers from 1 to n) β the permutation p.
The third line of the input contains n integers q_1, q_2, ..., q_n (1 β€ q_i β€ n, all q_i are distinct integers from 1 to n) β the permutation q.
Output
If it is impossible to find the suitable string, print "NO" on the first line.
Otherwise print "YES" on the first line and string s on the second line. It should consist of n lowercase Latin letters, contain at least k distinct characters and suit the given permutations.
If there are multiple answers, you can print any of them.
Example
Input
3 2
1 2 3
1 3 2
Output
YES
abb
### Response
```cpp
#include <bits/stdc++.h>
template <class... Args>
inline __attribute__((always_inline)) void read(Args&... args) {
(std::cin >> ... >> args);
}
template <class... Args>
inline __attribute__((always_inline)) void write(Args&&... args) {
(std::cout << ... << std::forward<Args>(args));
}
template <class... Args>
inline __attribute__((always_inline)) void writeln(Args&&... args) {
write(std::forward<Args>(args)..., '\n');
}
inline __attribute__((always_inline)) void flush_write() {
std::flush(std::cout);
}
class graph_t {
using node_list_t = std::vector<int>;
using holder_t = std::vector<node_list_t>;
holder_t gr;
public:
graph_t(int n) : gr(n) {}
void add_edge(int a, int b) { gr[b].push_back(a); }
protected:
void fill_comp(int v, std::vector<char>& used, std::vector<int>& comp) {
used[v] = true;
comp.push_back(v);
for (int u : gr[v])
if (!used[u]) fill_comp(u, used, comp);
}
public:
std::vector<std::vector<int>> get_blocks(const std::vector<int>& order) {
std::vector<std::vector<int>> blocks;
std::vector<char> used(gr.size(), false);
for (int v : order) {
if (!used[v]) {
blocks.emplace_back();
fill_comp(v, used, blocks.back());
}
}
return blocks;
}
};
int main() {
std::ios_base::sync_with_stdio(false);
std::fixed(std::cout).precision(20);
std::cin.exceptions(std::ios_base::failbit);
std::cin.tie(nullptr);
int n, k;
read(n, k);
std::vector<int> p1(n), p2(n);
for (int& x : p1) read(x), --x;
for (int& x : p2) read(x), --x;
graph_t g(n);
for (int i = 1; i < n; ++i)
g.add_edge(p1[i - 1], p1[i]), g.add_edge(p2[i - 1], p2[i]);
auto blocks = g.get_blocks(p1);
if ((int)blocks.size() < k) {
writeln("NO");
} else {
writeln("YES");
std::string res(n, '-');
int m = blocks.size();
for (int i = 0; i < m; ++i)
for (int x : blocks[i]) res[x] = 'a' + std::min(i, k - 1);
writeln(res);
}
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Sereja has an n Γ m rectangular table a, each cell of the table contains a zero or a number one. Sereja wants his table to meet the following requirement: each connected component of the same values forms a rectangle with sides parallel to the sides of the table. Rectangles should be filled with cells, that is, if a component form a rectangle of size h Γ w, then the component must contain exactly hw cells.
A connected component of the same values is a set of cells of the table that meet the following conditions:
* every two cells of the set have the same value;
* the cells of the set form a connected region on the table (two cells are connected if they are adjacent in some row or some column of the table);
* it is impossible to add any cell to the set unless we violate the two previous conditions.
Can Sereja change the values of at most k cells of the table so that the table met the described requirement? What minimum number of table cells should he change in this case?
Input
The first line contains integers n, m and k (1 β€ n, m β€ 100; 1 β€ k β€ 10). Next n lines describe the table a: the i-th of them contains m integers ai1, ai2, ..., aim (0 β€ ai, j β€ 1) β the values in the cells of the i-th row.
Output
Print -1, if it is impossible to meet the requirement. Otherwise, print the minimum number of cells which should be changed.
Examples
Input
5 5 2
1 1 1 1 1
1 1 1 1 1
1 1 0 1 1
1 1 1 1 1
1 1 1 1 1
Output
1
Input
3 4 1
1 0 0 0
0 1 1 1
1 1 1 0
Output
-1
Input
3 4 1
1 0 0 1
0 1 1 0
1 0 0 1
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m, k;
int box[101][101];
int dp[101][2];
int aox[101];
int fox[2000];
void ini() {
fox[0] = 1;
for (int i = 1; i <= 10; i++) fox[i] = fox[i - 1] << 1;
}
int main() {
ini();
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) scanf("%d", &box[i][j]);
if (n > 10) {
bool find = 0;
int mi = 2000000000;
for (int i = 1; i <= n; i++) {
int sum = 0;
for (int j = i - 1; j >= 1; j--) {
int fr = 0, se = 0;
for (int u = 1; u <= m; u++)
if (box[j][u] != box[i][u])
fr++;
else
se++;
sum += min(fr, se);
if (sum > k) break;
}
for (int j = i + 1; j <= n; j++) {
int fr = 0, se = 0;
for (int u = 1; u <= m; u++)
if (box[j][u] != box[i][u])
fr++;
else
se++;
sum += min(fr, se);
if (sum > k) break;
}
if (sum <= k) {
find = 1;
mi = min(sum, mi);
}
}
if (find)
printf("%d\n", mi);
else
printf("-1\n");
} else if (m > 10) {
bool find = 0;
int mi = 2000000000;
for (int i = 1; i <= m; i++) {
int sum = 0;
for (int j = i - 1; j >= 1; j--) {
int fr = 0, se = 0;
for (int u = 1; u <= n; u++)
if (box[u][i] != box[u][j])
fr++;
else
se++;
sum += min(fr, se);
if (sum > k) break;
}
for (int j = i + 1; j <= m; j++) {
int fr = 0, se = 0;
for (int u = 1; u <= n; u++)
if (box[u][j] != box[u][i])
fr++;
else
se++;
sum += min(fr, se);
if (sum > k) break;
}
if (sum <= k) {
find = 1;
mi = min(sum, mi);
}
}
if (find)
printf("%d\n", mi);
else
printf("-1\n");
} else {
bool find = 0;
int mi = 2000000000;
for (int i = 0; i < 1 << m; i++) {
int sum = 0;
for (int j = 1; j <= m; j++) {
if (i & fox[j - 1]) {
if (box[1][j] == 0) sum++;
} else {
if (box[1][j] == 1) sum++;
}
}
if (sum > k) continue;
for (int j = 2; j <= n; j++) {
int fr = 0;
int se = 0;
for (int u = 1; u <= m; u++) {
if (i & fox[u - 1]) {
if (box[j][u] == 1)
fr++;
else
se++;
} else {
if (box[j][u] == 0)
fr++;
else
se++;
}
}
sum += min(se, fr);
if (sum > k) break;
}
if (sum <= k) {
find = 1;
mi = min(mi, sum);
}
}
if (find)
printf("%d\n", mi);
else
printf("-1\n");
}
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
There are n programmers that you want to split into several non-empty teams. The skill of the i-th programmer is a_i. You want to assemble the maximum number of teams from them. There is a restriction for each team: the number of programmers in the team multiplied by the minimum skill among all programmers in the team must be at least x.
Each programmer should belong to at most one team. Some programmers may be left without a team.
Calculate the maximum number of teams that you can assemble.
Input
The first line contains the integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains two integers n and x (1 β€ n β€ 10^5; 1 β€ x β€ 10^9) β the number of programmers and the restriction of team skill respectively.
The second line of each test case contains n integers a_1, a_2, ... , a_n (1 β€ a_i β€ 10^9), where a_i is the skill of the i-th programmer.
The sum of n over all inputs does not exceed 10^5.
Output
For each test case print one integer β the maximum number of teams that you can assemble.
Example
Input
3
5 10
7 11 2 9 5
4 8
2 4 2 3
4 11
1 3 3 7
Output
2
1
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
int n, x;
while (t--) {
cin >> n >> x;
int a[n + 1];
for (int i = 1; i <= n; i++) cin >> a[i];
sort(a + 1, a + n + 1);
int s = 0, j, shu = 1;
for (j = n; j > 0; j--) {
if (a[j] * shu >= x) {
s++;
shu = 1;
} else
shu++;
}
cout << s << endl;
}
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Your companyβs next product will be a new game, which is a three-dimensional variant of the classic game βTic-Tac-Toeβ. Two players place balls in a three-dimensional space (board), and try to make a sequence of a certain length.
People believe that it is fun to play the game, but they still cannot fix the values of some parameters of the game. For example, what size of the board makes the game most exciting? Parameters currently under discussion are the board size (we call it n in the following) and the length of the sequence (m). In order to determine these parameter values, you are requested to write a computer simulator of the game.
You can see several snapshots of the game in Figures 1-3. These figures correspond to the three datasets given in the Sample Input.
<image>
Figure 1: A game with n = m = 3
Here are the precise rules of the game.
1. Two players, Black and White, play alternately. Black plays first.
2. There are n Γ n vertical pegs. Each peg can accommodate up to n balls. A peg can be specified by its x- and y-coordinates (1 β€ x, y β€ n). A ball on a peg can be specified by its z-coordinate (1 β€ z β€ n). At the beginning of a game, there are no balls on any of the pegs.
<image>
Figure 2: A game with n = m = 3 (White made a 3-sequence before Black)
3. On his turn, a player chooses one of n Γ n pegs, and puts a ball of his color onto the peg. The ball follows the law of gravity. That is, the ball stays just above the top-most ball on the same peg or on the floor (if there are no balls on the peg). Speaking differently, a player can choose x- and y-coordinates of the ball, but he cannot choose its z-coordinate.
4. The objective of the game is to make an m-sequence. If a player makes an m-sequence or longer of his color, he wins. An m-sequence is a row of m consecutive balls of the same color. For example, black balls in positions (5, 1, 2), (5, 2, 2) and (5, 3, 2) form a 3-sequence. A sequence can be horizontal, vertical, or diagonal. Precisely speaking, there are 13 possible directions to make a sequence, categorized as follows.
<image>
Figure 3: A game with n = 4, m = 3 (Black made two 4-sequences)
(a) One-dimensional axes. For example, (3, 1, 2), (4, 1, 2) and (5, 1, 2) is a 3-sequence. There are three directions in this category.
(b) Two-dimensional diagonals. For example, (2, 3, 1), (3, 3, 2) and (4, 3, 3) is a 3-sequence. There are six directions in this category.
(c) Three-dimensional diagonals. For example, (5, 1, 3), (4, 2, 4) and (3, 3, 5) is a 3- sequence. There are four directions in this category.
Note that we do not distinguish between opposite directions.
As the evaluation process of the game, people have been playing the game several times changing the parameter values. You are given the records of these games. It is your job to write a computer program which determines the winner of each recorded game.
Since it is difficult for a human to find three-dimensional sequences, players often do not notice the end of the game, and continue to play uselessly. In these cases, moves after the end of the game, i.e. after the winner is determined, should be ignored. For example, after a player won making an m-sequence, players may make additional m-sequences. In this case, all m-sequences but the first should be ignored, and the winner of the game is unchanged.
A game does not necessarily end with the victory of one of the players. If there are no pegs left to put a ball on, the game ends with a draw. Moreover, people may quit a game before making any m-sequence. In such cases also, the game ends with a draw.
Input
The input consists of multiple datasets each corresponding to the record of a game. A dataset starts with a line containing three positive integers n, m, and p separated by a space. The relations 3 β€ m β€ n β€ 7 and 1 β€ p β€ n3 hold between them. n and m are the parameter values of the game as described above. p is the number of moves in the game.
The rest of the dataset is p lines each containing two positive integers x and y. Each of these lines describes a move, i.e. the player on turn puts his ball on the peg specified. You can assume that 1 β€ x β€ n and 1 β€ y β€ n. You can also assume that at most n balls are put on a peg throughout a game.
The end of the input is indicated by a line with three zeros separated by a space.
Output
For each dataset, a line describing the winner and the number of moves until the game ends should be output. The winner is either βBlackβ or βWhiteβ. A single space should be inserted between the winner and the number of moves. No other extra characters are allowed in the output.
In case of a draw, the output line should be βDrawβ.
Example
Input
3 3 3
1 1
1 1
1 1
3 3 7
2 2
1 3
1 1
2 3
2 1
3 3
3 1
4 3 15
1 1
2 2
1 1
3 3
3 3
1 1
3 3
3 3
4 4
1 1
4 4
4 4
4 4
4 1
2 2
0 0 0
Output
Draw
White 6
Black 15
### Response
```cpp
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
int dx[] = { 1,0,0,1,1,0,1,1,1,0,-1,1,1 };
int dy[] = { 0,1,0,1,0,1,1,-1,0,1,1,-1,1 };
int dz[] = { 0,0,1,0,1,1,1,0,-1,-1,1,1,-1 };
int board[7][7][7], cnt[7][7];
int main() {
int n, m, p;
while (cin >> n >> m >> p, n) {
vector<int> ix(p + 1), iy(p + 1);
for (int i = 1; i <= p; ++i) cin >> ix[i] >> iy[i];
memset(board, -1, sizeof(board));
memset(cnt, 0, sizeof(cnt));
int flag = -1;
int i;
for (i = 1; i <= p; ++i) {
int color = i & 1;
int x = ix[i], y = iy[i];
--x, --y;
int z = cnt[x][y]++;
board[x][y][z] = color;
for (int j = 0; j < 13; ++j) {
int tmp = 1;
int nx = x + dx[j], ny = y + dy[j], nz = z + dz[j];
while (0 <= nx && nx < n && 0 <= ny && ny < n && 0 <= nz && nz < n) {
if (board[nx][ny][nz] == color) tmp++;
else break;
nx += dx[j], ny += dy[j], nz += dz[j];
}
nx = x - dx[j], ny = y - dy[j], nz = z - dz[j];
while (0 <= nx && nx < n && 0 <= ny && ny < n && 0 <= nz && nz < n) {
if (board[nx][ny][nz] == color) tmp++;
else break;
nx -= dx[j], ny -= dy[j], nz -= dz[j];
}
if (tmp >= m) {
flag = color;
goto output;
}
}
}
output:
if (flag == 1) cout << "Black " << i;
else if (flag == 0) cout << "White " << i;
else cout << "Draw";
cout << endl;
}
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Vadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of n light bulbs in a single row. Each bulb has a number from 1 to n (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.
<image>
Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 2). For example, the complexity of 1 4 2 3 5 is 2 and the complexity of 1 3 5 7 6 4 2 is 1.
No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of light bulbs on the garland.
The second line contains n integers p_1,\ p_2,\ β¦,\ p_n (0 β€ p_i β€ n) β the number on the i-th bulb, or 0 if it was removed.
Output
Output a single number β the minimum complexity of the garland.
Examples
Input
5
0 5 0 2 3
Output
2
Input
7
1 0 0 5 0 0 2
Output
1
Note
In the first example, one should place light bulbs as 1 5 4 2 3. In that case, the complexity would be equal to 2, because only (5, 4) and (2, 3) are the pairs of adjacent bulbs that have different parity.
In the second case, one of the correct answers is 1 7 3 5 6 4 2.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void __print(int x) { cerr << x; }
void __print(long x) { cerr << x; }
void __print(long long x) { cerr << x; }
void __print(unsigned x) { cerr << x; }
void __print(unsigned long x) { cerr << x; }
void __print(unsigned long long x) { cerr << x; }
void __print(float x) { cerr << x; }
void __print(double x) { cerr << x; }
void __print(long double x) { cerr << x; }
void __print(char x) { cerr << '\'' << x << '\''; }
void __print(const char *x) { cerr << '\"' << x << '\"'; }
void __print(const string &x) { cerr << '\"' << x << '\"'; }
void __print(bool x) { cerr << (x ? "true" : "false"); }
template <typename T, typename V>
void __print(const pair<T, V> &x) {
cerr << '{';
__print(x.first);
cerr << ',';
__print(x.second);
cerr << '}';
}
template <typename T>
void __print(const T &x) {
int f = 0;
cerr << '{';
for (auto &i : x) cerr << (f++ ? "," : ""), __print(i);
cerr << "}";
}
void _print() { cerr << "]\n"; }
template <typename T, typename... V>
void _print(T t, V... v) {
__print(t);
if (sizeof...(v)) cerr << ", ";
_print(v...);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long int t = 1;
while (t--) {
long long int n = 0, m = 0, k = 0, i = 0, j = 0, p = 0, q = 0, x = 0, y = 0,
z = 0, ans = 0, cnt = 0, l = 0, r = 0, mid = 0, lo = 0,
hi = 0;
string s;
bool flag = false;
cin >> n;
long long int a[n + 1];
for (i = 1; i <= n; i++) cin >> a[i];
long long int dp[n + 1][n + 1][2];
long long int even = n / 2;
long long int odd = (n % 2 == 0) ? n / 2 : (n / 2) + 1;
for (i = 0; i <= n; i++)
for (j = 0; j <= n; j++)
for (k = 0; k < 2; k++) dp[i][j][k] = 1000000007;
dp[0][0][0] = 0;
dp[0][0][1] = 0;
for (i = 1; i <= n; i++)
if (a[i] == 0)
for (j = 0; j <= even; j++)
if (j > i || (i - j) > odd)
continue;
else
dp[i][j][0] = min(dp[i][j][0], dp[i - 1][j - 1][0]),
dp[i][j][0] = min(dp[i][j][0], dp[i - 1][j - 1][1] + 1),
dp[i][j][1] = min(dp[i][j][1], dp[i - 1][j][1]),
dp[i][j][1] = min(dp[i][j][1], dp[i - 1][j][0] + 1);
else
for (j = 0; j <= even; j++) {
if (j > i || (i - j) > odd) continue;
if (a[i] % 2 == 0)
dp[i][j][0] = min(dp[i][j][0], dp[i - 1][j - 1][0]),
dp[i][j][0] = min(dp[i][j][0], dp[i - 1][j - 1][1] + 1);
else
dp[i][j][1] = min(dp[i][j][1], dp[i - 1][j][1]),
dp[i][j][1] = min(dp[i][j][1], dp[i - 1][j][0] + 1);
}
ans = 1000000007;
for (j = 0; j <= even; j++)
ans = min(ans, dp[n][j][0]), ans = min(ans, dp[n][j][1]);
cout << ans << endl;
;
}
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
You are given an array a of length 2^n. You should process q queries on it. Each query has one of the following 4 types:
1. Replace(x, k) β change a_x to k;
2. Reverse(k) β reverse each subarray [(i-1) β
2^k+1, i β
2^k] for all i (i β₯ 1);
3. Swap(k) β swap subarrays [(2i-2) β
2^k+1, (2i-1) β
2^k] and [(2i-1) β
2^k+1, 2i β
2^k] for all i (i β₯ 1);
4. Sum(l, r) β print the sum of the elements of subarray [l, r].
Write a program that can quickly process given queries.
Input
The first line contains two integers n, q (0 β€ n β€ 18; 1 β€ q β€ 10^5) β the length of array a and the number of queries.
The second line contains 2^n integers a_1, a_2, β¦, a_{2^n} (0 β€ a_i β€ 10^9).
Next q lines contains queries β one per line. Each query has one of 4 types:
* "1 x k" (1 β€ x β€ 2^n; 0 β€ k β€ 10^9) β Replace(x, k);
* "2 k" (0 β€ k β€ n) β Reverse(k);
* "3 k" (0 β€ k < n) β Swap(k);
* "4 l r" (1 β€ l β€ r β€ 2^n) β Sum(l, r).
It is guaranteed that there is at least one Sum query.
Output
Print the answer for each Sum query.
Examples
Input
2 3
7 4 9 9
1 2 8
3 1
4 2 4
Output
24
Input
3 8
7 0 8 8 7 1 5 2
4 3 7
2 1
3 2
4 1 6
2 3
1 5 16
4 8 8
3 0
Output
29
22
1
Note
In the first sample, initially, the array a is equal to \{7,4,9,9\}.
After processing the first query. the array a becomes \{7,8,9,9\}.
After processing the second query, the array a_i becomes \{9,9,7,8\}
Therefore, the answer to the third query is 9+7+8=24.
In the second sample, initially, the array a is equal to \{7,0,8,8,7,1,5,2\}. What happens next is:
1. Sum(3, 7) β 8 + 8 + 7 + 1 + 5 = 29;
2. Reverse(1) β \{0,7,8,8,1,7,2,5\};
3. Swap(2) β \{1,7,2,5,0,7,8,8\};
4. Sum(1, 6) β 1 + 7 + 2 + 5 + 0 + 7 = 22;
5. Reverse(3) β \{8,8,7,0,5,2,7,1\};
6. Replace(5, 16) β \{8,8,7,0,16,2,7,1\};
7. Sum(8, 8) β 1;
8. Swap(0) β \{8,8,0,7,2,16,1,7\}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, q, position;
long long seg[1 << 20];
long long query(int s, int e, int l, int r, int node, int lev) {
if (position & (1 << lev)) {
l = s + e - l;
r = s + e - r;
swap(l, r);
}
if (e < l || r < s) return 0LL;
if (s == l && e == r) return seg[node];
int m = (s + e) / 2;
if (r <= m) return query(s, m, l, r, node * 2, lev - 1);
if (l > m) return query(m + 1, e, l, r, node * 2 + 1, lev - 1);
return query(s, m, l, m, node * 2, lev - 1) +
query(m + 1, e, m + 1, r, node * 2 + 1, lev - 1);
}
int main() {
scanf("%d %d", &n, &q);
int sze = 1 << n;
for (int i = sze; i < 2 * sze; i++) scanf("%lld", &seg[i]);
for (int i = sze - 1; i > 0; i--) seg[i] = seg[2 * i] + seg[2 * i + 1];
while (q--) {
int t;
scanf("%d", &t);
if (t == 1) {
int x;
long long k;
scanf("%d %lld", &x, &k);
x--;
int l = 0, r = sze - 1;
for (int i = n; i > 0; i--) {
if (position & (1 << i)) x = l + r - x;
int m = (l + r) / 2;
if (x <= m)
r = m;
else
l = m + 1;
}
x += sze;
long long diff = k - seg[x];
while (x) {
seg[x] += diff;
x /= 2;
}
} else if (t == 2) {
int k;
scanf("%d", &k);
position ^= (1 << k);
} else if (t == 3) {
int k;
scanf("%d", &k);
position ^= (3 << k);
} else {
int l, r;
scanf("%d %d", &l, &r);
printf("%lld\n", query(0, sze - 1, l - 1, r - 1, 1, n));
}
}
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.
You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must:
* split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 β€ j β€ 2n - qi) should contain the elements a[(j - 1)Β·2qi + 1], a[(j - 1)Β·2qi + 2], ..., a[(j - 1)Β·2qi + 2qi];
* reverse each of the subarrays;
* join them into a single array in the same order (this array becomes new array a);
* output the number of inversions in the new a.
Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries.
Input
The first line of input contains a single integer n (0 β€ n β€ 20).
The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 β€ a[i] β€ 109), the initial array.
The third line of input contains a single integer m (1 β€ m β€ 106).
The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 β€ qi β€ n), the queries.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query.
Examples
Input
2
2 1 4 3
4
1 2 0 2
Output
0
6
6
0
Input
1
1 2
3
0 1 1
Output
0
1
0
Note
If we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.
The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i < j and x[i] > x[j].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline int getPow(int n) {
for (int i = 0;; i++)
if (n == (1 << i)) {
return i;
}
return -1;
}
int status;
long long cnt[2][22] = {0};
int b[1048590];
inline void mergg(int ar[], int low, int mid, int high, int pow) {
for (int i = low; i <= high; ++i) {
b[i] = ar[i];
}
int i = low, j = mid + 1, k = low;
while (i <= mid && j <= high) {
if (b[i] <= b[j]) {
ar[k++] = b[i++];
} else {
ar[k++] = b[j++];
cnt[status][pow] += (long long)mid - i + 1;
}
}
while (i <= mid) {
ar[k++] = b[i++];
}
while (j <= high) {
ar[k++] = b[j++];
}
}
inline void merge_sort(int ar[], int low, int high, int pow) {
if (low < high) {
int mid = low + (high - low) / 2;
merge_sort(ar, low, mid, pow - 1);
merge_sort(ar, mid + 1, high, pow - 1);
mergg(ar, low, mid, high, pow);
}
}
int a[1048590];
int tmp[1048590];
int main() {
int npow;
cin >> npow;
for (int i = 1; i <= (1 << npow); i++) scanf("%d", &a[i]);
memcpy(tmp, a, sizeof a);
status = 0;
merge_sort(a, 1, 1 << npow, npow - 1);
int sz = (1 << npow);
for (int i = 1; i <= sz; i++) a[i] = tmp[sz - i + 1];
status = 1;
merge_sort(a, 1, 1 << npow, npow - 1);
int m;
cin >> m;
int flag[22] = {0};
while (m--) {
int q;
scanf("%d", &q);
for (int i = 0; i < q; i++) {
flag[i] ^= 1;
}
long long ans = 0;
for (int i = 0; i <= npow; i++) {
ans += cnt[flag[i]][i];
}
printf("%I64d\n", ans);
}
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
The Cereal Guy's friend Serial Guy likes to watch soap operas. An episode is about to start, and he hasn't washed his plate yet. But he decided to at least put in under the tap to be filled with water. The plate can be represented by a parallelepiped k Γ n Γ m, that is, it has k layers (the first layer is the upper one), each of which is a rectangle n Γ m with empty squares ('.') and obstacles ('#'). The water can only be present in the empty squares. The tap is positioned above the square (x, y) of the first layer, it is guaranteed that this square is empty. Every minute a cubical unit of water falls into the plate. Find out in how many minutes the Serial Guy should unglue himself from the soap opera and turn the water off for it not to overfill the plate. That is, you should find the moment of time when the plate is absolutely full and is going to be overfilled in the next moment.
Note: the water fills all the area within reach (see sample 4). Water flows in each of the 6 directions, through faces of 1 Γ 1 Γ 1 cubes.
Input
The first line contains three numbers k, n, m (1 β€ k, n, m β€ 10) which are the sizes of the plate. Then follow k rectangles consisting of n lines each containing m characters '.' or '#', which represents the "layers" of the plate in the order from the top to the bottom. The rectangles are separated by empty lines (see the samples). The last line contains x and y (1 β€ x β€ n, 1 β€ y β€ m) which are the tap's coordinates. x is the number of the line and y is the number of the column. Lines of each layer are numbered from left to right by the integers from 1 to n, columns of each layer are numbered from top to bottom by the integers from 1 to m.
Output
The answer should contain a single number, showing in how many minutes the plate will be filled.
Examples
Input
1 1 1
.
1 1
Output
1
Input
2 1 1
.
#
1 1
Output
1
Input
2 2 2
.#
##
..
..
1 1
Output
5
Input
3 2 2
#.
##
#.
.#
..
..
1 2
Output
7
Input
3 3 3
.#.
###
##.
.##
###
##.
...
...
...
1 1
Output
13
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[1000];
int sx, sy;
int k, n, m;
int cnt;
char s[11][11][11];
int vis[11][11][11];
int dir1[4][2] = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};
int dir2[2] = {1, -1};
struct node {
int x, y, z;
};
void bfs() {
cnt = 1;
queue<node> q;
int i, j;
node no, ne;
no.x = sx - 1;
no.y = sy - 1;
no.z = 0;
vis[0][no.x][no.y] = 1;
q.push(no);
while (!q.empty()) {
no = q.front();
q.pop();
for (i = 0; i < 4; i++) {
ne.x = no.x + dir1[i][0];
ne.y = no.y + dir1[i][1];
ne.z = no.z;
if (ne.z < 0 || ne.x < 0 || ne.y < 0 || ne.x >= n || ne.y >= m ||
ne.z >= k || vis[ne.z][ne.x][ne.y] || s[ne.z][ne.x][ne.y] == '#')
continue;
vis[ne.z][ne.x][ne.y] = 1;
cnt++;
q.push(ne);
}
for (j = 0; j < 2; j++) {
ne.x = no.x;
ne.y = no.y;
ne.z = no.z + dir2[j];
if (ne.z >= 0 && ne.x >= 0 && ne.y >= 0 && ne.x < n && ne.y < m &&
ne.z < k && !vis[ne.z][ne.x][ne.y] && s[ne.z][ne.x][ne.y] == '.') {
vis[ne.z][ne.x][ne.y] = 1;
cnt++;
q.push(ne);
}
}
}
}
int main() {
int i, j, t;
scanf("%d%d%d", &k, &n, &m);
getchar();
for (t = 0; t < k; t++) {
bool flag = false;
getchar();
for (i = 0; i < n; i++) {
int cnt = 0;
for (j = 0; j < m; j++) {
vis[t][i][j] = 0;
scanf("%c", &s[t][i][j]);
}
getchar();
}
}
scanf("%d%d", &sx, &sy);
bfs();
cout << cnt << endl;
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph.
A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes.
<image>
Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges.
Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra.
Input
The first line contains four integers n, m, h, t (1 β€ n, m β€ 105, 1 β€ h, t β€ 100) β the number of nodes and edges in graph G, and the number of a hydra's heads and tails.
Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 β€ ai, bi β€ n, a β b) β the numbers of the nodes, connected by the i-th edge.
It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n.
Output
If graph G has no hydra, print "NO" (without the quotes).
Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers β the numbers of nodes u and v. In the third line print h numbers β the numbers of the nodes that are the heads. In the fourth line print t numbers β the numbers of the nodes that are the tails. All printed numbers should be distinct.
If there are multiple possible answers, you are allowed to print any of them.
Examples
Input
9 12 2 3
1 2
2 3
1 3
1 4
2 5
4 5
4 6
6 5
6 7
7 5
8 7
9 1
Output
YES
4 1
5 6
9 3 2
Input
7 10 3 3
1 2
2 3
1 3
1 4
2 5
4 5
4 6
6 5
6 7
7 5
Output
NO
Note
The first sample is depicted on the picture below:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 7;
int n, m, h, t, vis[N];
vector<int> H, T, e[N];
bool check(int u, int v) {
if (((int)(e[u]).size()) < h + 1 || ((int)(e[v]).size()) < t + 1)
return false;
for (int i = (0), I = (min(h + t + 1, ((int)(e[u]).size()))); i < I; ++i) {
int x = e[u][i];
vis[x] = u;
}
vector<int> C;
H.clear(), T.clear();
for (int i = (0), I = (min(h + t + 1, ((int)(e[v]).size()))); i < I; ++i) {
int x = e[v][i];
if (x == u) continue;
if (vis[x] == u)
C.push_back(x);
else
T.push_back(x);
vis[x] = v;
}
for (int i = (0), I = (min(h + t + 1, ((int)(e[u]).size()))); i < I; ++i) {
int x = e[u][i];
if (x == v) continue;
if (vis[x] != v) H.push_back(x);
}
for (int i = (0), I = (((int)(C).size())); i < I; ++i)
if (((int)(H).size()) < h) {
H.push_back(C[i]);
} else if (((int)(T).size()) < t) {
T.push_back(C[i]);
} else
break;
return ((int)(H).size()) >= h && ((int)(T).size()) >= t;
}
void solve() {
for (int u = (1), I = (n + 1); u < I; ++u) {
for (int i = (0), I = (((int)(e[u]).size())); i < I; ++i) {
int v = e[u][i];
if (check(u, v)) {
puts("YES");
printf("%d %d\n", u, v);
for (int i = (0), I = (h); i < I; ++i)
printf("%d%c", H[i], " \n"[i == h - 1]);
for (int i = (0), I = (t); i < I; ++i)
printf("%d%c", T[i], " \n"[i == t - 1]);
return;
}
}
}
puts("NO");
}
int main() {
scanf("%d%d%d%d", &n, &m, &h, &t);
for (int i = (0), I = (m); i < I; ++i) {
int u, v;
scanf("%d%d", &u, &v);
e[u].push_back(v), e[v].push_back(u);
}
solve();
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
You are playing a computer card game called Splay the Sire. Currently you are struggling to defeat the final boss of the game.
The boss battle consists of n turns. During each turn, you will get several cards. Each card has two parameters: its cost c_i and damage d_i. You may play some of your cards during each turn in some sequence (you choose the cards and the exact order they are played), as long as the total cost of the cards you play during the turn does not exceed 3. After playing some (possibly zero) cards, you end your turn, and all cards you didn't play are discarded. Note that you can use each card at most once.
Your character has also found an artifact that boosts the damage of some of your actions: every 10-th card you play deals double damage.
What is the maximum possible damage you can deal during n turns?
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the number of turns.
Then n blocks of input follow, the i-th block representing the cards you get during the i-th turn.
Each block begins with a line containing one integer k_i (1 β€ k_i β€ 2 β
10^5) β the number of cards you get during i-th turn. Then k_i lines follow, each containing two integers c_j and d_j (1 β€ c_j β€ 3, 1 β€ d_j β€ 10^9) β the parameters of the corresponding card.
It is guaranteed that β _{i = 1}^{n} k_i β€ 2 β
10^5.
Output
Print one integer β the maximum damage you may deal.
Example
Input
5
3
1 6
1 7
1 5
2
1 4
1 3
3
1 10
3 5
2 3
3
1 15
2 4
1 10
1
1 100
Output
263
Note
In the example test the best course of action is as follows:
During the first turn, play all three cards in any order and deal 18 damage.
During the second turn, play both cards and deal 7 damage.
During the third turn, play the first and the third card and deal 13 damage.
During the fourth turn, play the first and the third card and deal 25 damage.
During the fifth turn, play the only card, which will deal double damage (200).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 7;
const int mod = 1e9 + 7;
long long int powmod(long long int a, long long int b) {
long long int res = 1;
a %= mod;
assert(b >= 0);
for (; b; b >>= 1) {
if (b & 1) res = res * a % mod;
a = a * a % mod;
}
return res;
}
int nxt() {
int x;
scanf("%d", &x);
return x;
}
void max_self(long long int &a, long long int b) { a = max(a, b); }
int main() {
int n = nxt();
vector<long long int> dp(10);
for (int i = 0; i < 10; i++) dp[i] = LLONG_MIN;
dp[0] = 0;
for (int i = 0; i < n; i++) {
vector<long long int> tmp = dp;
int k = nxt();
vector<int> a[3];
long long int best = 0;
for (int _ = 0; _ < k; _++) {
int c = nxt(), d = nxt();
c--;
a[c].push_back(d);
max_self(best, d);
}
for (int j = 0; j < 3; j++)
sort((a[j]).begin(), (a[j]).end(), greater<int>());
for (int j = 0; j < 10; j++) {
max_self(tmp[(j + 1) % 10], dp[j] + best * (j == 9 ? 2 : 1));
}
if (a[0].size() >= 2) {
long long int tt = 1LL * a[0][0] + a[0][1];
long long int t2 = a[0][0];
for (int j = 0; j < 10; j++) {
max_self(tmp[(j + 2) % 10], dp[j] + tt + (j >= 8 ? t2 : 0));
}
}
if (a[0].size() && a[1].size()) {
long long int tt = 1LL * a[0][0] + a[1][0];
long long int t2 = max(a[0][0], a[1][0]);
for (int j = 0; j < 10; j++) {
max_self(tmp[(j + 2) % 10], dp[j] + tt + (j >= 8 ? t2 : 0));
}
}
if (a[0].size() >= 3) {
long long int tt = 1LL * a[0][0] + a[0][1] + a[0][2];
long long int t2 = a[0][0];
for (int j = 0; j < 10; j++) {
max_self(tmp[(j + 3) % 10], dp[j] + tt + (j >= 7 ? t2 : 0));
}
}
dp = tmp;
}
printf("%lld\n", *max_element((dp).begin(), (dp).end()));
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
You're given Q queries of the form (L, R).
For each query you have to find the number of such x that L β€ x β€ R and there exist integer numbers a > 0, p > 1 such that x = ap.
Input
The first line contains the number of queries Q (1 β€ Q β€ 105).
The next Q lines contains two integers L, R each (1 β€ L β€ R β€ 1018).
Output
Output Q lines β the answers to the queries.
Example
Input
6
1 4
9 9
5 7
12 29
137 591
1 1000000
Output
2
1
0
3
17
1111
Note
In query one the suitable numbers are 1 and 4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
set<long long> Set;
vector<long long> Se;
vector<long long>::iterator it;
long long M = 1000000000000000000;
int main() {
ios::sync_with_stdio(false);
int Q;
cin >> Q;
long double L, R, l, r;
float A;
long long S, lp, rp, p, a, g, b;
for (int i = 2; i <= 60; i++) {
g = 1;
p = 2;
while (g == 1) {
a = p;
A = p;
for (int y = 0; y < i; y++) {
a *= p;
A *= p;
if (a <= 0 || a > M || A / 1.01 > a) {
g = 0;
}
}
b = sqrt(a);
if (g == 1 && b * b != a && (b - 1) * (b - 1) != a &&
(b + 1) * (b + 1) != a) {
if (Set.find(a) == Set.end()) {
Set.insert(a);
Se.push_back(a);
}
}
p++;
}
}
sort(Se.begin(), Se.end());
for (int i = 0; i < Q; i++) {
cin >> L >> R;
S = 0;
g = 1;
l = sqrt(L);
r = sqrt(R);
lp = l;
rp = r;
if (lp * lp == L || (lp - 1) * (lp - 1) == L || (lp + 1) * (lp + 1) == L ||
(lp + 2) * (lp + 2) == L || (lp - 2) * (lp - 2) == L) {
S++;
g = 0;
}
S += rp - lp;
it = lower_bound(Se.begin(), Se.end(), L);
a = it - Se.begin();
it = lower_bound(Se.begin(), Se.end(), R);
b = it - Se.begin();
if (g == 1 && Se[b] == R) {
S++;
}
S += b - a;
cout << S << "\n";
}
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
It's the turn of the year, so Bash wants to send presents to his friends. There are n cities in the Himalayan region and they are connected by m bidirectional roads. Bash is living in city s. Bash has exactly one friend in each of the other cities. Since Bash wants to surprise his friends, he decides to send a Pikachu to each of them. Since there may be some cities which are not reachable from Bash's city, he only sends a Pikachu to those friends who live in a city reachable from his own city. He also wants to send it to them as soon as possible.
He finds out the minimum time for each of his Pikachus to reach its destination city. Since he is a perfectionist, he informs all his friends with the time their gift will reach them. A Pikachu travels at a speed of 1 meters per second. His friends were excited to hear this and would be unhappy if their presents got delayed. Unfortunately Team Rocket is on the loose and they came to know of Bash's plan. They want to maximize the number of friends who are unhappy with Bash.
They do this by destroying exactly one of the other n - 1 cities. This implies that the friend residing in that city dies, so he is unhappy as well.
Note that if a city is destroyed, all the roads directly connected to the city are also destroyed and the Pikachu may be forced to take a longer alternate route.
Please also note that only friends that are waiting for a gift count as unhappy, even if they die.
Since Bash is already a legend, can you help Team Rocket this time and find out the maximum number of Bash's friends who can be made unhappy by destroying exactly one city.
Input
The first line contains three space separated integers n, m and s (2 β€ n β€ 2Β·105, <image>, 1 β€ s β€ n) β the number of cities and the number of roads in the Himalayan region and the city Bash lives in.
Each of the next m lines contain three space-separated integers u, v and w (1 β€ u, v β€ n, u β v, 1 β€ w β€ 109) denoting that there exists a road between city u and city v of length w meters.
It is guaranteed that no road connects a city to itself and there are no two roads that connect the same pair of cities.
Output
Print a single integer, the answer to the problem.
Examples
Input
4 4 3
1 2 1
2 3 1
2 4 1
3 1 1
Output
2
Input
7 11 2
1 2 5
1 3 5
2 4 2
2 5 2
3 6 3
3 7 3
4 6 2
3 4 2
6 7 3
4 5 7
4 7 7
Output
4
Note
In the first sample, on destroying the city 2, the length of shortest distance between pairs of cities (3, 2) and (3, 4) will change. Hence the answer is 2.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<ll>;
using pii = pair<ll, ll>;
const ll maxN = 201005;
const ll MAXLOG = 20;
struct BinaryLifting {
ll BL[maxN][MAXLOG];
ll D[maxN];
void init(ll root) { D[root] = 1; }
void insert(ll n, ll par) {
D[n] = D[par] + 1;
BL[n][0] = par;
for (ll j = (1); j < ll(MAXLOG); j++) BL[n][j] = BL[BL[n][j - 1]][j - 1];
}
ll lift(ll node, ll h) {
ll cnt = 0;
while (h) {
if (h & 1) node = BL[node][cnt];
cnt++;
h >>= 1;
}
return node;
}
int lca(int a, int b) {
if (D[a] > D[b]) swap(a, b);
for (ll i = (MAXLOG)-1; i >= ll(0); i--)
if (D[BL[b][i]] >= D[a]) b = BL[b][i];
if (a == b) return a;
for (ll i = (MAXLOG)-1; i >= ll(0); i--)
if (BL[a][i] != BL[b][i]) a = BL[a][i], b = BL[b][i];
return BL[a][0];
}
};
vector<pii> adj[maxN];
ll dist[maxN];
bool visited[maxN];
vector<ll> adj2[maxN];
ll indeg[maxN];
ll imdom[maxN];
vector<ll> adjdom[maxN];
BinaryLifting bl;
void domdfs(ll cur) {
for (auto o : adj2[cur]) {
if (imdom[o] == -1) {
imdom[o] = cur;
} else {
imdom[o] = bl.lca(cur, imdom[o]);
}
indeg[o]--;
if (!indeg[o]) {
adjdom[imdom[o]].push_back(o);
bl.insert(o, imdom[o]);
domdfs(o);
}
}
}
ll coun[maxN];
void countc2(ll cur) {
ll c = 1;
for (auto o : adjdom[cur]) {
countc2(o);
c += coun[o];
}
coun[cur] = c;
}
ll countc(ll cur) {
ll c = 1;
for (auto o : adjdom[cur]) {
c += countc(o);
}
return c;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
ll n, m, s;
cin >> n >> m >> s;
for (ll i = (0); i < ll(m); i++) {
ll a, b, c;
cin >> a >> b >> c;
adj[a].emplace_back(b, c);
adj[b].emplace_back(a, c);
}
memset(dist, 0x3f, sizeof(dist));
dist[s] = 0;
priority_queue<pii, vector<pii>, greater<pii>> pq;
pq.push(make_pair(0, s));
while (!pq.empty()) {
ll cur = pq.top().second;
pq.pop();
if (visited[cur]) continue;
visited[cur] = true;
for (auto &o : adj[cur]) {
if (dist[o.first] > dist[cur] + o.second) {
dist[o.first] = dist[cur] + o.second;
pq.push(make_pair(dist[o.first], o.first));
}
}
}
for (ll i = (1); i < ll(n + 1); i++) {
if (0) cout << i << ": " << dist[i] << endl;
for (auto &o : adj[i]) {
if (dist[i] + o.second == dist[o.first]) {
adj2[i].push_back(o.first);
indeg[o.first] += 1;
}
}
}
memset(imdom, -1, sizeof(imdom));
bl.init(s);
domdfs(s);
ll res = 0;
countc2(s);
for (ll i = (1); i < ll(n + 1); i++) {
if (i != s && dist[i] < (1ll << 50)) res = max(coun[i], res);
}
cout << res << endl;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
A conglomerate consists of n companies. To make managing easier, their owners have decided to merge all companies into one. By law, it is only possible to merge two companies, so the owners plan to select two companies, merge them into one, and continue doing so until there is only one company left.
But anti-monopoly service forbids to merge companies if they suspect unfriendly absorption. The criterion they use is the difference in maximum salaries between two companies. Merging is allowed only if the maximum salaries are equal.
To fulfill the anti-monopoly requirements, the owners can change salaries in their companies before merging. But the labor union insists on two conditions: it is only allowed to increase salaries, moreover all the employees in one company must get the same increase.
Sure enough, the owners want to minimize the total increase of all salaries in all companies. Help them find the minimal possible increase that will allow them to merge companies into one.
Input
The first line contains a single integer n β the number of companies in the conglomerate (1 β€ n β€ 2 β
10^5). Each of the next n lines describes a company.
A company description start with an integer m_i β the number of its employees (1 β€ m_i β€ 2 β
10^5). Then m_i integers follow: the salaries of the employees. All salaries are positive and do not exceed 10^9.
The total number of employees in all companies does not exceed 2 β
10^5.
Output
Output a single integer β the minimal total increase of all employees that allows to merge all companies.
Example
Input
3
2 4 3
2 2 1
3 1 1 1
Output
13
Note
One of the optimal merging strategies is the following. First increase all salaries in the second company by 2, and merge the first and the second companies. Now the conglomerate consists of two companies with salaries [4, 3, 4, 3] and [1, 1, 1]. To merge them, increase the salaries in the second of those by 3. The total increase is 2 + 2 + 3 + 3 + 3 = 13.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10, mod = 1e9 + 7;
const long long inf = 1e18;
pair<int, int> p[maxn];
int mm;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int x, mx = 0;
cin >> x;
for (int j = 0; j < x; j++) {
int y;
cin >> y;
mx = max(mx, y);
mm = max(mm, y);
}
p[i] = {x, mx};
}
long long ans = 0;
for (int i = 0; i < n; i++) {
ans += 1ll * p[i].first * (mm - p[i].second);
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Drazil and Varda are the earthworm couple. They want to find a good place to bring up their children. They found a good ground containing nature hole. The hole contains many rooms, some pairs of rooms are connected by small tunnels such that earthworm can move between them.
Let's consider rooms and small tunnels as the vertices and edges in a graph. This graph is a tree. In the other words, any pair of vertices has an unique path between them.
Each room that is leaf in the graph is connected with a ground by a vertical tunnel. Here, leaf is a vertex that has only one outgoing edge in the graph.
Each room is large enough only to fit one earthworm living in it. Earthworm can't live in a tunnel.
Drazil and Varda have a plan to educate their children. They want all their children to do morning exercises immediately after getting up!
When the morning is coming, all earthworm children get up in the same time, then each of them chooses the farthest path to the ground for gathering with others (these children are lazy, so they all want to do exercises as late as possible).
Drazil and Varda want the difference between the time first earthworm child arrives outside and the time the last earthworm child arrives outside to be not larger than l (otherwise children will spread around the ground and it will be hard to keep them exercising together).
Also, The rooms that are occupied by their children should form a connected set. In the other words, for any two rooms that are occupied with earthworm children, all rooms that lie on the path between them should be occupied with earthworm children too.
How many children Drazil and Varda may have at most in order to satisfy all conditions above? Drazil and Varda want to know the answer for many different choices of l.
(Drazil and Varda don't live in the hole with their children)
Input
The first line contains one integer n denoting how many rooms there are in the hole (2 β€ n β€ 105).
Then there are n - 1 lines following. Each of these lines contains three integers x, y, v (1 β€ x, y β€ n, 1 β€ v β€ 106) denoting there is a small tunnel between room x and room y that takes time v to pass.
Suppose that the time for an earthworm to get out to the ground from any leaf room is the same.
The next line contains an integer q (1 β€ q β€ 50), denoting the number of different value of l you need to process.
The last line contains q numbers, each number denoting a value of l (1 β€ l β€ 1011).
Output
You should print q lines. Each line should contain one integer denoting the answer for a corresponding value of l.
Examples
Input
5
1 2 3
2 3 4
4 5 3
3 4 2
5
1 2 3 4 5
Output
1
3
3
3
5
Input
12
5 9 3
2 1 7
11 7 2
6 5 5
2 5 3
6 7 2
1 4 4
8 5 7
1 3 8
11 12 3
10 8 2
10
13 14 14 13 13 4 6 7 2 1
Output
10
10
10
10
10
3
3
5
2
1
Note
For the first sample the hole looks like the following. Rooms 1 and 5 are leaves, so they contain a vertical tunnel connecting them to the ground. The lengths of farthest path from rooms 1 β 5 to the ground are 12, 9, 7, 9, 12 respectively.
If l = 1, we may only choose any single room.
If l = 2..4, we may choose rooms 2, 3, and 4 as the answer.
If l = 5, we may choose all rooms.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, x, y, son[100005], q;
int fir[100005], nxt[200005], to[200005], cnt;
long long wi[200005], z, dp[100005][2], f[100005];
struct node {
int id;
long long val;
} c[100005];
int size[100005], fa[100005], Fa[100005];
long long read() {
long long x = 0;
char ch = getchar();
while (!isdigit(ch)) ch = getchar();
while (isdigit(ch)) x = (x << 3) + (x << 1) + (ch ^ 48), ch = getchar();
return x;
}
void dfs(int x, int fa) {
for (int i = fir[x]; i; i = nxt[i]) {
if (to[i] == fa) continue;
dfs(to[i], x);
if (dp[x][0] < dp[to[i]][0] + wi[i])
dp[x][1] = dp[x][0], dp[x][0] = dp[to[i]][0] + wi[i], son[x] = to[i];
else if (dp[x][1] < dp[to[i]][0] + wi[i])
dp[x][1] = dp[to[i]][0] + wi[i];
}
}
void Dfs(int x, int fa, long long W) {
f[x] = max(dp[x][0], W);
for (int i = fir[x]; i; i = nxt[i]) {
if (to[i] == fa) continue;
if (to[i] == son[x])
Dfs(to[i], x, max(W, dp[x][1]) + wi[i]);
else
Dfs(to[i], x, max(W, dp[x][0]) + wi[i]);
}
}
int cmp(node u, node v) { return u.val < v.val; }
void DFS(int x, int f) {
Fa[x] = f;
for (int i = fir[x]; i; i = nxt[i]) {
if (to[i] == f) continue;
DFS(to[i], x);
}
}
int find(int x) {
if (x == fa[x]) return x;
return fa[x] = find(fa[x]);
}
int main() {
n = read();
for (int i = 1; i < n; i++) {
x = read(), y = read(), z = read();
to[++cnt] = y, nxt[cnt] = fir[x], fir[x] = cnt, wi[cnt] = z;
to[++cnt] = x, nxt[cnt] = fir[y], fir[y] = cnt, wi[cnt] = z;
}
dfs(1, 0);
Dfs(1, 0, 0);
for (int i = 1; i <= n; i++) c[i] = (node){i, f[i]};
sort(c + 1, c + n + 1, cmp);
DFS(c[1].id, 0);
q = read();
for (int i = 1; i <= q; i++) {
z = read();
for (int i = 1; i <= n; i++) fa[i] = i;
for (int i = 1; i <= n; i++) size[i] = 1;
int r = n, ans = 0;
for (int j = n; j >= 1; j--) {
while (r && c[r].val - c[j].val > z) size[find(c[r].id)]--, r--;
ans = max(ans, size[find(c[j].id)]);
int u = find(c[j].id), v = find(Fa[c[j].id]);
if (u != v) fa[u] = v, size[v] += size[u];
}
printf("%d\n", ans);
}
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
n fishermen have just returned from a fishing vacation. The i-th fisherman has caught a fish of weight a_i.
Fishermen are going to show off the fish they caught to each other. To do so, they firstly choose an order in which they show their fish (each fisherman shows his fish exactly once, so, formally, the order of showing fish is a permutation of integers from 1 to n). Then they show the fish they caught according to the chosen order. When a fisherman shows his fish, he might either become happy, become sad, or stay content.
Suppose a fisherman shows a fish of weight x, and the maximum weight of a previously shown fish is y (y = 0 if that fisherman is the first to show his fish). Then:
* if x β₯ 2y, the fisherman becomes happy;
* if 2x β€ y, the fisherman becomes sad;
* if none of these two conditions is met, the fisherman stays content.
Let's call an order in which the fishermen show their fish emotional if, after all fishermen show their fish according to this order, each fisherman becomes either happy or sad. Calculate the number of emotional orders modulo 998244353.
Input
The first line contains one integer n (2 β€ n β€ 5000).
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9).
Output
Print one integer β the number of emotional orders, taken modulo 998244353.
Examples
Input
4
1 1 4 9
Output
20
Input
4
4 3 2 1
Output
0
Input
3
4 2 1
Output
6
Input
8
42 1337 13 37 420 666 616 97
Output
19200
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int ri() {
int x;
if (scanf(" %d", &x) == EOF) return -1;
return x;
}
long long int rl() {
long long int x;
if (cin >> x) return x;
return -1;
}
string rs() {
string s;
if (cin >> s) return s;
return "";
}
const long long int mod = 998244353;
struct SingleCase {
int n;
vector<int> v, halfIdx;
vector<long long int> memo, Fact, Inv, Sum;
long long int fact(int a) {
if (a == 0) return 1;
long long int& ret = Fact[a];
if (ret != -1) return ret;
return ret = a * fact(a - 1) % mod;
}
long long int inverse(int a) {
long long int& ret = Inv[a];
if (ret != -1) return ret;
Inv[1] = 1;
for (int i = 2; i < Inv.size(); ++i)
Inv[i] = (mod - (mod / i) * Inv[mod % i] % mod) % mod;
return ret;
}
long long int doit(int idx) {
long long int& ret = memo[idx];
if (ret != -1) return ret;
ret = 1;
int r = halfIdx[idx];
ret = (ret + sum(r)) % mod;
return ret;
}
long long int sum(int idx) {
if (idx < 0) return 0;
long long int& ret = Sum[idx];
if (ret != -1) return ret;
return ret =
(sum(idx - 1) + inverse(n - 2 - halfIdx[idx]) * doit(idx)) % mod;
}
void computeHalfIdx() {
halfIdx = vector<int>(n, -1);
int x = -1, y = 0;
while (y < n) {
if (x + 1 < n && 2 * v[x + 1] <= v[y])
x++;
else {
halfIdx[y] = x;
y++;
}
}
}
bool solveCase() {
n = ri();
if (n < 0) return false;
for (int i = 0; i < n; ++i) v.push_back(ri());
sort(v.begin(), v.end());
memo = vector<long long int>(n, -1);
Fact = vector<long long int>(n, -1);
Inv = vector<long long int>(n, -1);
Sum = vector<long long int>(n, -1);
computeHalfIdx();
long long int ret;
if (n >= 2 && 2 * v[n - 2] > v[n - 1])
ret = 0;
else
ret = doit(n - 1) * fact(n - 1) % mod;
cout << ret << endl;
return true;
}
};
int main() {
while (SingleCase().solveCase()) {
};
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Yanagi is a high school student, and she is called "Hime" by her boyfriend who is a ninja fanboy. She likes picture books very much, so she often writes picture books by herself. She always asks you to make her picture book as an assistant. Today, you got asked to help her with making a comic.
She sometimes reads her picture books for children in kindergartens. Since Yanagi wants to let the children read, she wants to insert numbers to frames in order. Of course, such a task should be done by the assistant, you.
You want to do the task easily and fast, so you decide to write a program to output the order of reading frames based on the positions of the frames.
Write a program to print the number of order for each frame.
The comics in this problem satisfy the following rules.
The each comic is drawn on a sheet of rectangle paper. You can assume that the top side of the paper is on the x-axis. And you can assume that the right-hand side of the paper is on the y-axis. The positive direction of the x-axis is leftward. The positive direction of the y-axis is down direction. The paper is large enough to include all frames of the comic. In other words, no area in a frame is out of the paper.
The area of each frame is at least one. All sides of each frame are parallel to the x-axis or the y-axis. The frames can't overlap one another. However the frames may share the line of side.
You must decide the order to read K , where K is a set of frames, with the following steps.
Step 1:You must choose an unread frame at the right-most position in K.
If you find such frames multiple, you must choose the frame at the top position among them.
If you can't find any unread frames, you stop reading K.
The frame you chose is "Starting Frame".
In step 1, you assume that the position of a frame is the top-right point of the frame.
Step 2:You should draw a line from the right-bottom point of "Starting Frame" to leftward horizontally.
If the line touch the right-hand side of other frame, you should stop drawing.
If the line is on the side of other frame, you should not stop drawing.
If the line touch the edge of paper, you should stop drawing.
Step 3:The set of the unread frames which are above the line ( they may be the bottom-side on the line ) drawn at Step 2 is L.
And you should read L.
Step 4: Go back to Step 1.
Constraints
0 < n < 10
(x0i != x1i) and (y0i != y1i)
0 β€ x0i , y0i , x1i , y1i β€ 500
Input
The input consists of multiple datasets. The last dataset is followed by a line containing one zero. You don't have to process this data.
Each datasets is in the following format.
n
x01 y01 x11 y11
x02 y02 x12 y12
....
x0n y0n x1n y1n
All numbers of the datasets are integer. They are separated by a space. The first line of a dataset contains one integer. n is the number of frames of the comic. x0i , y0i , x1i , y1i are two non-neighboring points of i th frame in the line.
Output
Print n lines for each dataset. Print the number of order for ith frame in the ith line. And you should print blank line between the datasets.
Output format:
num1
num2
...
numi
...
numn
Example
Input
4
0 0 100 60
0 60 50 90
50 60 100 90
0 90 100 120
6
0 0 100 40
0 40 50 70
50 40 100 60
50 60 100 80
0 70 50 120
50 80 100 120
0
Output
1
2
3
4
1
2
4
5
3
6
### Response
```cpp
#include<bits/stdc++.h>
#define LL long long
#define REP(i, n) for(int i=0;i<(n);++i)
#define REPA(i, n) for(int i=1;i<(n);++i)
#define lp(i, n) for(int i=0;i<(n);++i)
#define PII pair<int, int>
#define PLL pair<long long, long long>
#define MOD ((int)1e9 + 7)
#define INF ((int)1e9)
#define DEKAI ((int)1e9+7)
#define ALL(x) (x).begin(), (x).end()
#define BIT(x) (1<<(x))
#define foreach(i, n) for(auto &i:(n))
using namespace std;
vector<vector<int>> ans;
#define NULI {{-1}}
void read(vector<vector<int>> l){
if(l.empty()) return;
int ri=1000,yi=1000,rit;
lp(i,l.size()){
if(ri>l[i][0]){
ri=l[i][0];
yi=l[i][1];
rit=i;
}
else if(ri==l[i][0]){
if(yi>l[i][1]){
ri=l[i][0];
yi=l[i][1];
rit=i;
}
}
}
ans.push_back(l[rit]);
int left=l[rit][2];
int under=l[rit][3];
l.erase(l.begin()+rit);
int findtoright=1000;
if(l.empty()) return;
//cout<<" "<<under<<endl;
lp(i,l.size()){
if(under>l[i][1]&&under<l[i][3]){
//cout<<" "<<l[i][0]<<endl;
findtoright=min(l[i][0],findtoright);
}
}
//cout<<l.size()<<endl;
//cout<<findtoright<<endl;
vector<vector<int>> next;
lp(i,l.size()){
if(l[i][2]<=findtoright){
if(l[i][3]<=under){
next.push_back(l[i]);
l.erase(l.begin()+i);
i--;
}
}
}
if(!next.empty())
read(next);
if(!l.empty())
read(l);
}
int main(){
int check=0;
while(1){
int n;
cin>>n;
if(n==0) break;
if(check==1)cout<<endl;
check=1;
vector<vector<int>> l;
lp(i,n){
int a,b,c,d;
cin>>a>>b>>c>>d;
if(b>d) swap(b,d);
if(a>c) swap(a,c);
l.push_back({a,b,c,d});
}
ans.clear();
read(l);
lp(i,n){
lp(j,n){
if(ans[j]==l[i]){
cout<<j+1<<endl;
break;
}
}
}
}
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Suppose you have two strings s and t, and their length is equal. You may perform the following operation any number of times: choose two different characters c1 and c2, and replace every occurence of c1 in both strings with c2. Let's denote the distance between strings s and t as the minimum number of operations required to make these strings equal. For example, if s is abcd and t is ddcb, the distance between them is 2 β we may replace every occurence of a with b, so s becomes bbcd, and then we may replace every occurence of b with d, so both strings become ddcd.
You are given two strings S and T. For every substring of S consisting of |T| characters you have to determine the distance between this substring and T.
Input
The first line contains the string S, and the second β the string T (1 β€ |T| β€ |S| β€ 125000). Both strings consist of lowercase Latin letters from a to f.
Output
Print |S| - |T| + 1 integers. The i-th of these integers must be equal to the distance between the substring of S beginning at i-th index with length |T| and the string T.
Example
Input
abcdefa
ddcb
Output
2 3 3 3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
double PI = acos(-1);
const int N = 1 << 18;
const int M = 125010;
struct base {
double x, y;
base() : x(0), y(0) {}
base(const double &_x, const double &_y) : x(_x), y(_y) {}
};
inline base operator+(const base &a, const base &b) {
return base(a.x + b.x, a.y + b.y);
}
inline base operator-(const base &a, const base &b) {
return base(a.x - b.x, a.y - b.y);
}
inline base operator*(const base &a, const base &b) {
return base(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);
}
inline base conj(const base &a) { return base(a.x, -a.y); }
base w[N + 5];
int rev[N + 5];
inline void prepare(int n) {
int L = __builtin_ctz(n);
for (int i = 0; i < n; ++i) {
rev[i] = rev[i >> 1] >> 1 | ((i & 1) << (L - 1));
w[i] = base(cos(2 * PI * i / n), sin(2 * PI * i / n));
}
}
inline void fft(base *a, int n) {
for (int i = 0; i < n; ++i)
if (i < rev[i]) swap(a[i], a[rev[i]]);
for (int i = 2, h = n >> 1; i <= n; i <<= 1, h >>= 1) {
for (int j = 0; j < n; j += i) {
base *l = a + j, *r = a + j + (i >> 1), *p = w;
for (int k = 0; k < (i >> 1); ++k) {
base tmp = *r * *p;
*r = *l - tmp, *l = *l + tmp;
++l, ++r, p += h;
}
}
}
}
base A[6][N], B[6][N], C[N];
char S[N], T[N];
struct dsu {
int p[6], sz;
dsu() {
for (int i = 0; i < 6; i++) p[i] = i;
sz = 6;
}
int find(int u) { return u == p[u] ? u : p[u] = find(p[u]); }
void Union(int u, int v) {
u = find(u);
v = find(v);
if (u != v) {
sz--, p[u] = v;
}
}
} DS[M];
int main(int argc, char const *argv[]) {
scanf("%s", S);
scanf("%s", T);
int n = strlen(S), m = strlen(T), t = n + m, sz = 1;
while (sz < t) sz <<= 1;
prepare(sz);
for (char &c : S) c -= 'a';
for (char &c : T) c -= 'a';
for (int a = 0; a < 6; a++) {
for (int i = 0; i < n; i++) A[a][i] = base(S[i] == a, 0);
fft(A[a], sz);
}
for (int b = 0; b < 6; b++) {
for (int i = 0; i < m; i++) B[b][i] = base(T[m - i - 1] == b, 0);
fft(B[b], sz);
}
for (int a = 0; a < 6; a++) {
for (int b = 0; b < 6; b++)
if (a != b) {
for (int i = 0; i < sz; i++) C[i] = A[a][i] * B[b][i];
reverse(C + 1, C + sz);
fft(C, sz);
for (int i = m - 1; i < n; i++) {
int f = C[i].x + 0.5;
if (f) DS[i].Union(a, b);
}
}
}
for (int i = m - 1; i < n; i++) {
printf("%d ", 6 - DS[i].sz);
}
puts("");
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per coconut. Sasha has x chizhiks, Masha has y chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.
The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.
Consider the following example. Suppose Sasha has 5 chizhiks, Masha has 4 chizhiks, and the price for one coconut be 3 chizhiks. If the girls don't exchange with chizhiks, they will buy 1 + 1 = 2 coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have 6 chizhiks, Masha will have 3 chizhiks, and the girls will buy 2 + 1 = 3 coconuts.
It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).
Input
The first line contains three integers x, y and z (0 β€ x, y β€ 10^{18}, 1 β€ z β€ 10^{18}) β the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.
Output
Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.
Examples
Input
5 4 3
Output
3 1
Input
6 8 2
Output
7 0
Note
The first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy 3 + 4 = 7 coconuts.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long x, y, z;
cin >> x >> y >> z;
long long ga = x / z;
long long gba = x % z;
long long gb = y / z;
long long gbm = y % z;
long long ex = (gbm + gba) / z;
long long ex1 = (gbm + gba) % z;
long long z1 = 0;
cout << ga + gb + ex << " " << max(z1, min(gbm, gba) - ex1) << "\n";
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph.
Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no more than k. Distance between two vertices of the tree is the minimum possible number of edges of the path between them.
As this number of ways to paint the tree can be large, Ostap wants you to compute it modulo 109 + 7. Two ways to paint the tree are considered different if there exists a vertex that is painted black in one way and is not painted in the other one.
Input
The first line of the input contains two integers n and k (1 β€ n β€ 100, 0 β€ k β€ min(20, n - 1)) β the number of vertices in Ostap's tree and the maximum allowed distance to the nearest black vertex. Don't miss the unusual constraint for k.
Each of the next n - 1 lines contain two integers ui and vi (1 β€ ui, vi β€ n) β indices of vertices, connected by the i-th edge. It's guaranteed that given graph is a tree.
Output
Print one integer β the remainder of division of the number of ways to paint the tree by 1 000 000 007 (109 + 7).
Examples
Input
2 0
1 2
Output
1
Input
2 1
1 2
Output
3
Input
4 1
1 2
2 3
3 4
Output
9
Input
7 2
1 2
2 3
1 4
4 5
1 6
6 7
Output
91
Note
In the first sample, Ostap has to paint both vertices black.
In the second sample, it is enough to paint only one of two vertices, thus the answer is 3: Ostap can paint only vertex 1, only vertex 2, vertices 1 and 2 both.
In the third sample, the valid ways to paint vertices are: {1, 3}, {1, 4}, {2, 3}, {2, 4}, {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
const int SIZE = 1e6 + 5;
const long long INF = 1LL << 60;
const double eps = 1e-4;
const double PI = 3.1415926535897932;
const int SZE = 1e6 + 1;
vector<int> adj[109], radj[109];
long long dp[109][42];
int n, m;
void dfs(int x) {
for (int i : adj[x]) {
dfs(i);
}
if (((int)(adj[x]).size()) == 0) {
dp[x][m + 1] = dp[x][0] = 1;
return;
}
long long dp2[((int)(adj[x]).size())][42][42];
for (int i = 0; i < (((int)(adj[x]).size())); ++i) {
for (int j = 0; j < (2 * m + 1); ++j) {
for (int k = 0; k < (2 * m + 1); ++k) {
dp2[i][j][k] = 0;
}
}
}
for (int i = 0; i < (2 * m + 1); ++i) dp2[0][i][i] = dp[adj[x][0]][i];
for (int i = (1); i < (((int)(adj[x]).size())); ++i) {
for (int j = 0; j < (2 * m + 1); ++j) {
for (int k = (j); k < (2 * m + 1); ++k) {
for (int l = 0; l < (2 * m + 1); ++l) {
int nmn = min(j, l), nmx = max(k, l);
dp2[i][nmn][nmx] =
(dp2[i][nmn][nmx] + dp2[i - 1][j][k] * dp[adj[x][i]][l]) % MOD;
}
}
}
}
for (int j = 0; j < (2 * m + 1); ++j) {
for (int k = (j); k < (2 * m + 1); ++k) {
int nx;
if (j + k + 1 > 2 * m)
nx = k + 1;
else
nx = j + 1;
dp[x][0] = (dp[x][0] + dp2[((int)(adj[x]).size()) - 1][j][k]) % MOD;
if (nx <= 2 * m) {
dp[x][nx] = (dp[x][nx] + dp2[((int)(adj[x]).size()) - 1][j][k]) % MOD;
}
}
}
}
void ft(int x, int p) {
for (int i : radj[x]) {
if (i == p) continue;
adj[x].push_back(i);
ft(i, x);
}
}
int main() {
scanf("%d%d", &(n), &(m));
for (int i = 0; i < (n - 1); ++i) {
int a, b;
scanf("%d%d", &a, &b);
a--;
b--;
radj[a].push_back(b);
radj[b].push_back(a);
}
ft(0, -1);
dfs(0);
long long ans = 0;
for (int i = 0; i < (m + 1); ++i) {
ans = (ans + dp[0][i]) % MOD;
}
printf("%I64d", ans);
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Alice and Bob begin their day with a quick game. They first choose a starting number X0 β₯ 3 and try to reach one million by the process described below.
Alice goes first and then they take alternating turns. In the i-th turn, the player whose turn it is selects a prime number smaller than the current number, and announces the smallest multiple of this prime number that is not smaller than the current number.
Formally, he or she selects a prime p < Xi - 1 and then finds the minimum Xi β₯ Xi - 1 such that p divides Xi. Note that if the selected prime p already divides Xi - 1, then the number does not change.
Eve has witnessed the state of the game after two turns. Given X2, help her determine what is the smallest possible starting number X0. Note that the players don't necessarily play optimally. You should consider all possible game evolutions.
Input
The input contains a single integer X2 (4 β€ X2 β€ 106). It is guaranteed that the integer X2 is composite, that is, is not prime.
Output
Output a single integer β the minimum possible X0.
Examples
Input
14
Output
6
Input
20
Output
15
Input
8192
Output
8191
Note
In the first test, the smallest possible starting number is X0 = 6. One possible course of the game is as follows:
* Alice picks prime 5 and announces X1 = 10
* Bob picks prime 7 and announces X2 = 14.
In the second case, let X0 = 15.
* Alice picks prime 2 and announces X1 = 16
* Bob picks prime 5 and announces X2 = 20.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX = 1e6 + 10;
const int INF = 1e9 + 7;
int prime[MAX];
int main() {
int x2;
scanf("%d", &x2);
for (int i = 2; i <= x2; i++) {
if (!prime[i]) {
for (int j = i * 2; j <= x2; j += i) prime[j] = i;
}
}
int ans = INF;
for (int i = x2 - prime[x2] + 1; i <= x2; i++) {
if (prime[i] == 0) continue;
ans = min(ans, i - prime[i] + 1);
}
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Heidi and Doctor Who hopped out of the TARDIS and found themselves at EPFL in 2018. They were surrounded by stormtroopers and Darth Vader was approaching. Miraculously, they managed to escape to a nearby rebel base but the Doctor was very confused. Heidi reminded him that last year's HC2 theme was Star Wars. Now he understood, and he's ready to face the evils of the Empire!
The rebels have s spaceships, each with a certain attacking power a.
They want to send their spaceships to destroy the empire bases and steal enough gold and supplies in order to keep the rebellion alive.
The empire has b bases, each with a certain defensive power d, and a certain amount of gold g.
A spaceship can attack all the bases which have a defensive power less than or equal to its attacking power.
If a spaceship attacks a base, it steals all the gold in that base.
The rebels are still undecided which spaceship to send out first, so they asked for the Doctor's help. They would like to know, for each spaceship, the maximum amount of gold it can steal.
Input
The first line contains integers s and b (1 β€ s, b β€ 10^5), the number of spaceships and the number of bases, respectively.
The second line contains s integers a (0 β€ a β€ 10^9), the attacking power of each spaceship.
The next b lines contain integers d, g (0 β€ d β€ 10^9, 0 β€ g β€ 10^4), the defensive power and the gold of each base, respectively.
Output
Print s integers, the maximum amount of gold each spaceship can steal, in the same order as the spaceships are given in the input.
Example
Input
5 4
1 3 5 2 4
0 1
4 2
2 8
9 4
Output
1 9 11 9 11
Note
The first spaceship can only attack the first base.
The second spaceship can attack the first and third bases.
The third spaceship can attack the first, second and third bases.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int hashP = 239017;
const int N = 1e5 + 10;
const int MOD = 1e9 + 7;
const int MOD2 = 998244353;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
vector<pair<int, int> > a(n);
for (int i = 0; i < n; i++) cin >> a[i].first, a[i].second = i;
vector<pair<int, int> > b(m);
for (auto& now : b) {
cin >> now.first >> now.second;
}
vector<int> ans(n);
sort(b.begin(), b.end());
sort(a.begin(), a.end());
long long j = 0, sum = 0;
for (int i = 0; i < n; i++) {
for (j = j; j < m; j++) {
if (b[j].first <= a[i].first)
sum += b[j].second;
else {
break;
}
}
ans[a[i].second] += sum;
}
for (auto now : ans) cout << now << " ";
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Holidays are coming up really soon. Rick realized that it's time to think about buying a traditional spruce tree. But Rick doesn't want real trees to get hurt so he decided to find some in an n Γ m matrix consisting of "*" and ".".
<image>
To find every spruce first let's define what a spruce in the matrix is. A set of matrix cells is called a spruce of height k with origin at point (x, y) if:
* All cells in the set contain an "*".
* For each 1 β€ i β€ k all cells with the row number x+i-1 and columns in range [y - i + 1, y + i - 1] must be a part of the set. All other cells cannot belong to the set.
Examples of correct and incorrect spruce trees:
<image>
Now Rick wants to know how many spruces his n Γ m matrix contains. Help Rick solve this problem.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 10).
The first line of each test case contains two integers n and m (1 β€ n, m β€ 500) β matrix size.
Next n lines of each test case contain m characters c_{i, j} β matrix contents. It is guaranteed that c_{i, j} is either a "." or an "*".
It is guaranteed that the sum of n β
m over all test cases does not exceed 500^2 (β n β
m β€ 500^2).
Output
For each test case, print single integer β the total number of spruces in the matrix.
Example
Input
4
2 3
.*.
***
2 3
.*.
**.
4 5
.***.
*****
*****
*.*.*
5 7
..*.*..
.*****.
*******
.*****.
..*.*..
Output
5
3
23
34
Note
In the first test case the first spruce of height 2 has its origin at point (1, 2), the second spruce of height 1 has its origin at point (1, 2), the third spruce of height 1 has its origin at point (2, 1), the fourth spruce of height 1 has its origin at point (2, 2), the fifth spruce of height 1 has its origin at point (2, 3).
In the second test case the first spruce of height 1 has its origin at point (1, 2), the second spruce of height 1 has its origin at point (2, 1), the third spruce of height 1 has its origin at point (2, 2).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifndef ONLINE_JUDGE
// for getting input from input.txt
freopen("input.txt", "r", stdin);
// for writing output to output.txt
freopen("outputw.txt", "w", stdout);
#endif
long long int t;
cin>>t;
while(t--)
{
int m,n;
cin>>n>>m;
char a[n][m];
for(int i = 0;i<n;i++)
{
for(int j = 0;j<m;j++)
{
cin>>a[i][j];
}
}
int left[n][m];
for(int i = 0;i<n;i++)
{
int count = 0;
for(int j = 0;j<m;j++)
{
if(a[i][j] == '*')
{
count++;
}
else
count = 0;
left[i][j] = count;
}
}
int right[n][m];
for(int i = 0;i<n;i++)
{
int count = 0;
for(int j = m-1;j>=0;j--)
{
if(a[i][j] == '*')
{
count++;
}
else
count = 0;
right[i][j] = count;
}
}
long long int ans = 0;
for(int i = 0;i<n;i++)
{
for(int j = 0;j<m;j++)
{
if(a[i][j] == '*')
{
for(int k = i,w = 1;k<n && a[k][j] == '*';k++,w++)
{
if(left[k][j] >= w && right[k][j] >= w)
{
ans++;
}
else
{
break;
}
}
}
}
}
cout<<ans<<"\n";
}
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
It is now 125 years later, but humanity is still on the run from a humanoid-cyborg race determined to destroy it. Or perhaps we are getting some stories mixed up here... In any case, the fleet is now smaller. However, in a recent upgrade, all the navigation systems have been outfitted with higher-dimensional, linear-algebraic jump processors.
Now, in order to make a jump, a ship's captain needs to specify a subspace of the d-dimensional space in which the events are taking place. She does so by providing a generating set of vectors for that subspace.
Princess Heidi has received such a set from the captain of each of m ships. Again, she would like to group up those ships whose hyperspace jump subspaces are equal. To do so, she wants to assign a group number between 1 and m to each of the ships, so that two ships have the same group number if and only if their corresponding subspaces are equal (even though they might be given using different sets of vectors).
Help Heidi!
Input
The first line of the input contains two space-separated integers m and d (2 β€ m β€ 30 000, 1 β€ d β€ 5) β the number of ships and the dimension of the full underlying vector space, respectively. Next, the m subspaces are described, one after another. The i-th subspace, which corresponds to the i-th ship, is described as follows:
The first line contains one integer ki (1 β€ ki β€ d). Then ki lines follow, the j-th of them describing the j-th vector sent by the i-th ship. Each of the j lines consists of d space-separated integers aj, j = 1, ..., d, that describe the vector <image>; it holds that |aj| β€ 250. The i-th subspace is the linear span of these ki vectors.
Output
Output m space-separated integers g1, ..., gm, where <image> denotes the group number assigned to the i-th ship. That is, for any 1 β€ i < j β€ m, the following should hold: gi = gj if and only if the i-th and the j-th subspaces are equal. In addition, the sequence (g1, g2, ..., gm) should be lexicographically minimal among all sequences with that property.
Example
Input
8 2
1
5 0
1
0 1
1
0 1
2
0 6
0 1
2
0 1
1 0
2
-5 -5
4 3
2
1 1
0 1
2
1 0
1 0
Output
1 2 2 2 3 3 3 1
Note
In the sample testcase, the first and the last subspace are equal, subspaces 2 to 4 are equal, and subspaces 5 to 7 are equal.
Recall that two subspaces, one given as the span of vectors <image> and another given as the span of vectors <image>, are equal if each vector vi can be written as a linear combination of vectors w1, ..., wk (that is, there exist coefficients <image> such that vi = Ξ±1w1 + ... + Ξ±kwk) and, similarly, each vector wi can be written as a linear combination of vectors v1, ..., vn.
Recall that a sequence (g1, g2, ..., gm) is lexicographically smaller than a sequence (h1, h2, ..., hm) if there exists an index i, 1 β€ i β€ m, such that gi < hi and gj = hj for all j < i.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int pow_mod(long long x, long long n, int M) {
long long ans = 1;
for (; n; n >>= 1) {
if (n & 1) ans = ans * x % M;
x = x * x % M;
}
return ans;
}
int inv_mod(int x, int p) { return pow_mod(x, p - 2, p); }
vector<vector<int>> f(vector<vector<int>> a, int MOD) {
int N = a.size(), M = a[0].size();
int k = 0;
for (int j = 0; j < M; j++) {
int i0;
for (i0 = k; i0 < N && !a[i0][j]; i0++)
;
if (i0 == N) continue;
swap(a[k], a[i0]);
int x = inv_mod(a[k][j], MOD);
for (int j = 0; j < M; j++) a[k][j] = (long long)a[k][j] * x % MOD;
for (int i = 0; i < N; i++)
if (i != k) {
int x = a[i][j];
for (int j = 0; j < M; j++)
a[i][j] = (a[i][j] - (long long)a[k][j] * x) % MOD;
}
k++;
}
while (N) {
bool ok = true;
for (int j = 0; j < M; j++)
if (a[N - 1][j]) ok = false;
if (ok)
N--, a.pop_back();
else
break;
}
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++) a[i][j] = (a[i][j] + MOD) % MOD;
return a;
}
int main() {
int T, M;
cin >> T >> M;
map<pair<vector<vector<int>>, vector<vector<int>>>, vector<int>> mp;
for (int t = 0; t < T; t++) {
int N;
scanf("%d", &N);
vector<vector<int>> a(N, vector<int>(M));
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++) scanf("%d", &a[i][j]);
vector<vector<int>> b = f(a, 1e9 + 7);
vector<vector<int>> c = f(a, 1e9 + 9);
mp[{b, c}].push_back(t);
}
vector<int> ans(T);
int K = 0;
for (auto z : mp) {
for (int t : z.second) ans[t] = K;
K++;
}
vector<int> mi(K, INT_MAX);
for (int t = 0; t < T; t++) mi[ans[t]] = min(mi[ans[t]], t);
vector<pair<int, int>> v(K);
for (int k = 0; k < K; k++) v[k] = {mi[k], k};
sort(v.begin(), v.end());
for (int k = 0; k < K; k++) mi[v[k].second] = k;
for (int t = 0; t < T; t++) printf("%d ", mi[ans[t]] + 1);
cout << endl;
}
``` |
Subsets and Splits