text
stringlengths 424
69.5k
|
---|
### Prompt
Please formulate a Cpp solution to the following problem:
You are given n rectangles on a plane with coordinates of their bottom left and upper right points. Some (n-1) of the given n rectangles have some common point. A point belongs to a rectangle if this point is strictly inside the rectangle or belongs to its boundary.
Find any point with integer coordinates that belongs to at least (n-1) given rectangles.
Input
The first line contains a single integer n (2 ≤ n ≤ 132 674) — the number of given rectangles.
Each the next n lines contains four integers x_1, y_1, x_2 and y_2 (-10^9 ≤ x_1 < x_2 ≤ 10^9, -10^9 ≤ y_1 < y_2 ≤ 10^9) — the coordinates of the bottom left and upper right corners of a rectangle.
Output
Print two integers x and y — the coordinates of any point that belongs to at least (n-1) given rectangles.
Examples
Input
3
0 0 1 1
1 1 2 2
3 0 4 1
Output
1 1
Input
3
0 0 1 1
0 1 1 2
1 0 2 1
Output
1 1
Input
4
0 0 5 5
0 0 4 4
1 1 4 4
1 1 4 4
Output
1 1
Input
5
0 0 10 8
1 2 6 7
2 3 5 6
3 4 4 5
8 1 9 2
Output
3 4
Note
The picture below shows the rectangles in the first and second samples. The possible answers are highlighted.
<image>
The picture below shows the rectangles in the third and fourth samples.
<image>
### Response
```cpp
#include <bits/stdc++.h>
const double PI = acos(-1.0);
using namespace std;
int setb(int n, int pos) { return n = n | (1 << pos); }
int resb(int n, int pos) { return n = n & ~(1 << pos); }
bool checkb(int n, int pos) { return (bool)(n & (1 << pos)); }
inline long long bigmod(long long b, long long p, long long m) {
long long ret = 1, cur = b % m;
while (p) {
if (p & 1) ret = (ret * cur) % m;
cur = (cur * cur) % m;
p = p >> 1;
}
return ret;
}
int shit[10000005];
int n;
int ara[200005][2], bra[200005][2];
multiset<int> lx, rx, ly, ry;
void rid(int i) {
int xx1 = ara[i][0], yy1 = ara[i][1];
int xx2 = bra[i][0], yy2 = bra[i][1];
lx.erase(lx.find(xx1));
ly.erase(ly.find(yy1));
rx.erase(rx.find(xx2));
ry.erase(ry.find(yy2));
}
void add(int i) {
lx.insert(ara[i][0]);
ly.insert(ara[i][1]);
rx.insert(bra[i][0]);
ry.insert(bra[i][1]);
}
void solve() {
multiset<int>::iterator it;
it = lx.end();
it--;
int xx1 = *it;
it = rx.begin();
int xx2 = *it;
it = ly.end();
it--;
int yy1 = *it;
it = ry.begin();
int yy2 = *it;
if (xx1 <= xx2 && yy1 <= yy2) {
printf("%d %d\n", xx1, yy1);
exit(0);
}
}
void super_solve() {
int i;
for (i = 1; i <= n; i++) {
rid(i);
solve();
add(i);
}
int oh = 10000000;
while (oh--) {
assert(false);
assert(false);
assert(false);
assert(false);
assert(false);
assert(false);
assert(false);
assert(false);
assert(false);
assert(false);
assert(false);
assert(false);
}
}
int main() {
int i;
scanf("%d", &n);
for (i = 1; i <= n; i++) {
scanf("%d %d", &ara[i][0], &ara[i][1]);
scanf("%d %d", &bra[i][0], &bra[i][1]);
add(i);
}
super_solve();
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one.
A square (x; y) is considered bad, if at least one of the two conditions is fulfilled:
* |x + y| ≡ 0 (mod 2a),
* |x - y| ≡ 0 (mod 2b).
Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2).
Input
The only line contains integers a, b, x1, y1, x2 and y2 — the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 ≤ a, b ≤ 109 and |x1|,|y1|,|x2|,|y2| ≤ 109). It is guaranteed that the initial and the final square aren't bad.
Output
Print a single number — the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2).
Examples
Input
2 2 1 0 0 1
Output
1
Input
2 2 10 11 0 1
Output
5
Input
2 4 3 -1 3 7
Output
2
Note
In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 10086;
int a[MAXN];
vector<int> v;
long long dp[MAXN][2];
int divide(int x, int y) {
long long r = x / y - 1;
if ((r + 1) * y <= x) r++;
return (int)r;
}
int main() {
int a, b, x1, y1, x2, y2;
while (scanf("%d%d%d%d%d%d", &a, &b, &x1, &y1, &x2, &y2) != EOF) {
int xx1 = x1 - y1, yy1 = x1 + y1;
int xx2 = x2 - y2, yy2 = x2 + y2;
printf("%d\n", max(abs(divide(xx1, 2 * b) - divide(xx2, 2 * b)),
abs(divide(yy1, 2 * a) - divide(yy2, 2 * a))));
}
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
You are given a set $T$, which is a subset of $S$. The set $S$ consists of $0, 1, ... n-1$. Print all subsets of $T$. Note that we represent $0, 1, ... n-1$ as 00...0001, 00...0010, 00...0100, ..., 10...0000 in binary respectively and the integer representation of a subset is calculated by bitwise OR of existing elements.
Constraints
* $1 \leq n \leq 28$
* $0 \leq k \leq 18$
* $k \leq n$
* $0 \leq b_i < n$
Input
The input is given in the following format.
$n$
$k \; b_0 \; b_1 \; ... \; b_{k-1}$
$k$ is the number of elements in $T$, and $b_i$ represents elements in $T$.
Output
Print the subsets ordered by their decimal integers. Print a subset in the following format.
$d$: $e_0$ $e_1$ ...
Print ':' after the integer value $d$, then print elements $e_i$ in the subset in ascending order. Separate two adjacency elements by a space character.
Example
Input
4
2 0 2
Output
0:
1: 0
4: 2
5: 0 2
### Response
```cpp
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <map>
#include <numeric>
#include <string>
#include <cmath>
#include <iomanip>
#include <queue>
#include <list>
#include <set>
#include <stack>
#include <cctype>
#include <cmath>
#include <bitset>
using namespace std;
/* typedef */
typedef long long ll;
/* constant */
const int INF = 1 << 30;
const int NIL = -1;
const int MAX = 10000;
const int mod = 1000000007;
const double pi = 3.141592653589;
/* global variables */
/* function */
/* main */
int main(){
int n, m, x;
cin >> n >> m;
bitset<28> mask(0);
for (int i = 0; i < m; i++) {
cin >> x;
mask.set(x);
}
// Print bit if binary(i) includes only mask bits
/*
// 1 ============================
for (int i = 0; i < (1 << n); i++) {
bitset<28> bs(i);
if ((bs | mask) == mask) {
printf("%d:", i);
for (int j = 0; j < n; j++) {
if ((bs >> j)[0]) printf(" %d", j);
}
printf("\n");
}
}
*/
// 2 ===========================
int mask_int = mask.to_ulong();
for (int b = 0; b < (1 << n); b++) {
if ((b | mask_int) == mask_int) {
printf("%d:", b);
for (int i = 0; i < n;i++)
if( (b >> i) & 1)
printf(" %d", i);
printf("\n");
}
}
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.
Arpa can perform two types of operations:
* Choose a number and delete it with cost x.
* Choose a number and increase it by 1 with cost y.
Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.
Help Arpa to find the minimum possible cost to make the list good.
Input
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y.
Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
Output
Print a single integer: the minimum possible cost to make the list good.
Examples
Input
4 23 17
1 17 17 16
Output
40
Input
10 6 2
100 49 71 73 66 96 8 60 41 63
Output
10
Note
In example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).
A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd [here](https://en.wikipedia.org/wiki/Greatest_common_divisor).
### Response
```cpp
#include <bits/stdc++.h>
const int MAXINT = 2147483640;
const long long MAXLL = 9223372036854775800LL;
const long long MAXN = 2000005;
using namespace std;
long long a[MAXN];
long long sum[MAXN], cnt[MAXN];
long long f[MAXN];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
long long n, i, j, x, y, N = 2e6 + 1, ans = MAXLL;
cin >> n >> x >> y;
long long p = x / y;
for (i = 1; i <= n; ++i) {
cin >> a[i];
f[a[i]]++;
}
for (i = 1; i <= N; ++i) cnt[i] = cnt[i - 1] + f[i];
for (i = 1; i <= N; ++i) sum[i] = sum[i - 1] + i * f[i];
for (i = 2; i <= N; ++i) {
long long res = 0;
for (j = i; j <= N; j += i) {
long long best = max(j - i + 1, j - p);
res += (cnt[best - 1] - cnt[j - i]) * x;
res += ((cnt[j] - cnt[best - 1]) * j - (sum[j] - sum[best - 1])) * y;
}
ans = min(ans, res);
}
cout << ans << "\n";
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
You are given a connected undirected weighted graph consisting of n vertices and m edges.
You need to print the k-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
More formally, if d is the matrix of shortest paths, where d_{i, j} is the length of the shortest path between vertices i and j (1 ≤ i < j ≤ n), then you need to print the k-th element in the sorted array consisting of all d_{i, j}, where 1 ≤ i < j ≤ n.
Input
The first line of the input contains three integers n, m and k (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min\Big((n(n-1))/(2), 2 ⋅ 10^5\Big), 1 ≤ k ≤ min\Big((n(n-1))/(2), 400\Big) — the number of vertices in the graph, the number of edges in the graph and the value of k, correspondingly.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^9, x ≠ y) denoting an edge between vertices x and y of weight w.
It is guaranteed that the given graph is connected (there is a path between any pair of vertices), there are no self-loops (edges connecting the vertex with itself) and multiple edges (for each pair of vertices x and y, there is at most one edge between this pair of vertices in the graph).
Output
Print one integer — the length of the k-th smallest shortest path in the given graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
Examples
Input
6 10 5
2 5 1
5 3 9
6 2 2
1 3 1
5 1 8
6 5 10
1 6 5
6 4 6
3 6 2
3 4 5
Output
3
Input
7 15 18
2 6 3
5 7 4
6 5 4
3 6 9
6 7 7
1 6 4
7 1 6
7 2 1
4 3 2
3 2 8
5 3 6
2 5 5
3 7 9
4 1 8
2 1 1
Output
9
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using namespace std;
template <class T>
ostream& operator<<(ostream& os, vector<T> V) {
os << "[ ";
for (auto v : V) os << v << " ";
return os << "]";
}
template <class L, class R>
ostream& operator<<(ostream& os, pair<L, R> P) {
return os << "(" << P.first << "," << P.second << ")";
}
const int N = 2e5 + 5;
int u[N], v[N], w[N];
map<int, long long> adj[N];
map<pair<int, int>, bool> mp;
priority_queue<pair<long long, pair<int, int>>,
vector<pair<long long, pair<int, int>>>,
greater<pair<long long, pair<int, int>>>>
pq;
inline pair<int, int> go(int a, int b) {
return pair<int, int>(min(a, b), max(a, b));
}
inline pair<int, int> gg(int i) { return go(u[i], v[i]); }
void rel(long long we, int a, int b) {
for (auto z : adj[a]) {
int c = z.first;
if (adj[b].find(c) == adj[b].end() || adj[b][c] > we + z.second) {
adj[b][c] = we + z.second, adj[c][b] = we + z.second,
pq.push({we + z.second, go(b, c)});
}
}
}
void relax(long long we, pair<int, int> p) {
rel(we, p.first, p.second);
rel(we, p.second, p.first);
adj[p.first][p.second] = we;
adj[p.second][p.first] = we;
}
void solve() {
int n, m, k;
cin >> n >> m >> k;
for (int i = 0; i < m; i++) {
cin >> u[i] >> v[i] >> w[i];
pq.push({w[i], gg(i)});
}
int done = 0;
long long ans = -1;
while (done < k) {
auto z = pq.top();
pq.pop();
if (mp[z.second] || z.second.first == z.second.second) continue;
mp[z.second] = 1;
done++;
if (done == k) ans = z.first;
relax(z.first, z.second);
}
cout << ans << '\n';
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t = 1;
while (t--) {
solve();
}
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
DLS and JLS are bored with a Math lesson. In order to entertain themselves, DLS took a sheet of paper and drew n distinct lines, given by equations y = x + p_i for some distinct p_1, p_2, …, p_n.
Then JLS drew on the same paper sheet m distinct lines given by equations y = -x + q_i for some distinct q_1, q_2, …, q_m.
DLS and JLS are interested in counting how many line pairs have integer intersection points, i.e. points with both coordinates that are integers. Unfortunately, the lesson will end up soon, so DLS and JLS are asking for your help.
Input
The first line contains one integer t (1 ≤ t ≤ 1000), the number of test cases in the input. Then follow the test case descriptions.
The first line of a test case contains an integer n (1 ≤ n ≤ 10^5), the number of lines drawn by DLS.
The second line of a test case contains n distinct integers p_i (0 ≤ p_i ≤ 10^9) describing the lines drawn by DLS. The integer p_i describes a line given by the equation y = x + p_i.
The third line of a test case contains an integer m (1 ≤ m ≤ 10^5), the number of lines drawn by JLS.
The fourth line of a test case contains m distinct integers q_i (0 ≤ q_i ≤ 10^9) describing the lines drawn by JLS. The integer q_i describes a line given by the equation y = -x + q_i.
The sum of the values of n over all test cases in the input does not exceed 10^5. Similarly, the sum of the values of m over all test cases in the input does not exceed 10^5.
In hacks it is allowed to use only one test case in the input, so t=1 should be satisfied.
Output
For each test case in the input print a single integer — the number of line pairs with integer intersection points.
Example
Input
3
3
1 3 2
2
0 3
1
1
1
1
1
2
1
1
Output
3
1
0
Note
The picture shows the lines from the first test case of the example. Black circles denote intersection points with integer coordinates.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
long long n, m;
long long t;
cin >> t;
while (t--) {
cin >> n;
long long a[n + 5];
for (long long i = 0; i < n; i++) cin >> a[i];
cin >> m;
long long b[m + 5], ans = 0, cnt = 0, cntt = 0;
for (long long i = 0; i < m; i++) cin >> b[i];
for (long long i = 0; i < n; i++) {
if (a[i] & 1) cnt++;
}
for (long long i = 0; i < m; i++)
if (b[i] & 1) cntt++;
ans = (n * m) - (cnt * (m - cntt) + (cntt * (n - cnt)));
cout << ans << endl;
}
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, n coins of arbitrary values a1, a2, ..., an. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally.
As you woke up, you found Mom's coins and read her note. "But why split the money equally?" — you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is strictly larger than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the minimum number of coins, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what minimum number of coins you need to take to divide them in the described manner.
Input
The first line contains integer n (1 ≤ n ≤ 100) — the number of coins. The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 100) — the coins' values. All numbers are separated with spaces.
Output
In the single line print the single number — the minimum needed number of coins.
Examples
Input
2
3 3
Output
2
Input
3
2 1 2
Output
2
Note
In the first sample you will have to take 2 coins (you and your twin have sums equal to 6, 0 correspondingly). If you take 1 coin, you get sums 3, 3. If you take 0 coins, you get sums 0, 6. Those variants do not satisfy you as your sum should be strictly more that your twins' sum.
In the second sample one coin isn't enough for us, too. You can pick coins with values 1, 2 or 2, 2. In any case, the minimum number of coins equals 2.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, sum, res, ress;
int main() {
int a[150];
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
sum += a[i];
}
sort(a, a + n);
for (int i = n - 1; i >= 0; i--) {
res += a[i];
ress++;
{
if (res > sum / 2) break;
}
}
cout << ress << endl;
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of p·ai + q·aj + r·ak for given p, q, r and array a1, a2, ... an such that 1 ≤ i ≤ j ≤ k ≤ n. Help Snape find the value of x. Do note that the value of x may be negative.
Input
First line of input contains 4 integers n, p, q, r ( - 109 ≤ p, q, r ≤ 109, 1 ≤ n ≤ 105).
Next line of input contains n space separated integers a1, a2, ... an ( - 109 ≤ ai ≤ 109).
Output
Output a single integer the maximum value of p·ai + q·aj + r·ak that can be obtained provided 1 ≤ i ≤ j ≤ k ≤ n.
Examples
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
Note
In the first sample case, we can take i = j = k = 5, thus making the answer as 1·5 + 2·5 + 3·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
string vow = "aeiou";
const int dxhorse[] = {-2, -2, -1, -1, 1, 1, 2, 2};
const int dyhorse[] = {1, -1, 2, -2, 2, -2, 1, -1};
const int dx[] = {-1, 0, 0, 1};
const int dy[] = {0, -1, 1, 0};
const long double pie = 3.14159265358979;
const long long mod = 1e9 + 7;
void solve(int test_case) {
int n;
cin >> n;
vector<long long> p(4);
for (int i = 1; i < 4; i++) cin >> p[i];
vector<long long> v(n + 1);
for (int i = 1; i < n + 1; i++) cin >> v[i];
vector<vector<long long> > dp(4, vector<long long>(n + 1));
for (int i = 0; i < 4; i++) dp[i][0] = LLONG_MIN;
for (int j = 1; j < n + 1; j++) {
for (int i = 1; i < 4; i++)
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j] + p[i] * v[j]);
}
cout << dp[3][n];
cout << "\n";
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t = 1;
for (int i = 0; i < t; i++) solve(i);
return 0;
}
``` |
### Prompt
In cpp, your task is to solve 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 arr[100100];
int val[100100];
int main() {
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}
val[n - 1] = arr[n - 1];
for (int i = 0; i < n; ++i) {
val[i] = arr[i] + arr[i + 1];
}
for (int i = 0; i < n; ++i) cout << val[i] << " ";
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Find places where a string P is found within a text T. Print all indices of T where P found. The indices of T start with 0.
Constraints
* 1 ≤ length of T ≤ 1000
* 1 ≤ length of P ≤ 1000
* The input consists of alphabetical characters and digits
Input
In the first line, a text T is given. In the second line, a string P is given.
Examples
Input
aabaaa
aa
Output
0
3
4
Input
xyzz
yz
Output
1
Input
abc
xyz
Output
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("Ofast")
#define rep(i,n) for(int i=0;i<n;i++)
const long long MOD = 1000000007;
int main(){
string s,t; cin >> s >> t;
if(s.size() >= t.size()){
rep(i,s.size()-t.size()+1){
bool frag = true;
rep(j,t.size()){
if(s.at(i+j) != t.at(j) ) frag = false;
}
if(frag) cout << i << "\n";
}
}
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Of course our child likes walking in a zoo. The zoo has n areas, that are numbered from 1 to n. The i-th area contains ai animals in it. Also there are m roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads.
Our child is very smart. Imagine the child want to go from area p to area q. Firstly he considers all the simple routes from p to q. For each route the child writes down the number, that is equal to the minimum number of animals among the route areas. Let's denote the largest of the written numbers as f(p, q). Finally, the child chooses one of the routes for which he writes down the value f(p, q).
After the child has visited the zoo, he thinks about the question: what is the average value of f(p, q) for all pairs p, q (p ≠ q)? Can you answer his question?
Input
The first line contains two integers n and m (2 ≤ n ≤ 105; 0 ≤ m ≤ 105). The second line contains n integers: a1, a2, ..., an (0 ≤ ai ≤ 105). Then follow m lines, each line contains two integers xi and yi (1 ≤ xi, yi ≤ n; xi ≠ yi), denoting the road between areas xi and yi.
All roads are bidirectional, each pair of areas is connected by at most one road.
Output
Output a real number — the value of <image>.
The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4.
Examples
Input
4 3
10 20 30 40
1 3
2 3
4 3
Output
16.666667
Input
3 3
10 20 30
1 2
2 3
3 1
Output
13.333333
Input
7 8
40 20 10 30 20 50 40
1 2
2 3
3 4
4 5
5 6
6 7
1 4
5 7
Output
18.571429
Note
Consider the first sample. There are 12 possible situations:
* p = 1, q = 3, f(p, q) = 10.
* p = 2, q = 3, f(p, q) = 20.
* p = 4, q = 3, f(p, q) = 30.
* p = 1, q = 2, f(p, q) = 10.
* p = 2, q = 4, f(p, q) = 20.
* p = 4, q = 1, f(p, q) = 10.
Another 6 cases are symmetrical to the above. The average is <image>.
Consider the second sample. There are 6 possible situations:
* p = 1, q = 2, f(p, q) = 10.
* p = 2, q = 3, f(p, q) = 20.
* p = 1, q = 3, f(p, q) = 10.
Another 3 cases are symmetrical to the above. The average is <image>.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct OO {
OO& operator<(int a) {
printf("%d", a);
return *this;
}
OO& operator<(long long a) {
printf("%lld", a);
return *this;
}
OO& operator<(double a) {
printf("%.15f", a);
return *this;
}
OO& operator<(char a) {
putchar(a);
return *this;
}
OO& operator<(const char* a) {
fputs(a, stdout);
return *this;
}
} O;
struct II {
II& operator>(int& a) {
scanf("%d", &a);
return *this;
}
II& operator>(long long& a) {
scanf("%lld", &a);
return *this;
}
II& operator>(double& a) {
scanf("%lf", &a);
return *this;
}
II& operator>(char& a) {
a = getchar();
return *this;
}
} I;
struct EE {
EE& operator<(int a) { return *this; }
EE& operator<(long long a) { return *this; }
EE& operator<(double a) { return *this; }
EE& operator<(char a) { return *this; }
EE& operator<(const char* a) { return *this; }
} E;
long double wynik = 0;
int extra[100009];
class UnionFind {
public:
UnionFind(size_t univSize) : parents(univSize), ranks(univSize, 0) {
for (size_t i = 0; i < univSize; ++i) parents[i] = i;
}
size_t find(size_t x) {
size_t root = x;
while (parents[root] != root) root = parents[root];
while (x != root) {
size_t& curr = parents[x];
x = parents[x];
curr = root;
}
return root;
}
bool makeUnion(size_t a, size_t b) {
a = find(a);
b = find(b);
if (a == b) return false;
if (ranks[a] < ranks[b]) {
parents[a] = b, ++ranks[b];
extra[b] += extra[a];
E < "extra[" < (int)b < "] is now " < extra[b] < '\n';
} else {
parents[b] = a, ++ranks[a];
extra[a] += extra[b];
E < "extra[" < (int)a < "] is now " < extra[a] < '\n';
}
return true;
}
private:
std::vector<size_t> parents;
std::vector<size_t> ranks;
};
UnionFind uf(100009);
int n, m;
int tab[100009];
struct edge {
bool operator<(const edge& o) const { return v < o.v; }
int fr, to, v;
} es[100009];
int main() {
I > n > m;
for (int i = (int)(0); i < (int)(n); ++i) {
I > tab[i];
}
for (int i = (int)(0); i < (int)(n); ++i) extra[i] = 1;
for (int i = (int)(0); i < (int)(m); ++i) {
int a, b;
I > a > b;
--a;
--b;
es[i].fr = a;
es[i].to = b;
es[i].v = min(tab[a], tab[b]);
}
sort(es, es + m);
for (int e = (int)(m)-1; e >= (int)(0); --e) {
int a = es[e].fr;
int b = es[e].to;
a = uf.find(a);
b = uf.find(b);
long double mod =
(long double)extra[a] * (long double)extra[b] * (long double)es[e].v;
E < "a=" < a < " b=" < b < '\n';
E < "v " < es[e].v < " " < extra[a] < " " < extra[b] < '\n';
bool r = uf.makeUnion(a, b);
if (!r) continue;
wynik += mod;
}
double w = (long double)wynik / ((long double)n * (n - 1));
O < w * 2 < '\n';
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Problem
N circles are given on the two-dimensional plane, each of which has no intersection. In addition, each circle is assigned a number from 1 to N.
You can place any number of half-lines such that the endpoints are on the circumference of the first circle. Find out how many half lines must be installed in order for each circle to have an intersection with one or more half lines.
Constraints
* 2 ≤ N ≤ 16
* -100 ≤ xi ≤ 100 (1 ≤ i ≤ N)
* -100 ≤ yi ≤ 100 (1 ≤ i ≤ N)
* 1 ≤ ri ≤ 100 (1 ≤ i ≤ N)
Input
The input is given in the following format.
N
x1 y1 r1
x2 y2 r2
...
xN yN rN
The first line is given one integer N. Of the N lines from the second line, the i-th line is given three integers xi, yi, and ri representing the x-coordinate, y-coordinate, and radius of the i-th circle, separated by blanks.
Output
Output at least how many half lines must be installed so that each circle has an intersection with one or more half lines.
Examples
Input
3
0 0 2
3 3 1
6 1 1
Output
1
Input
4
1 2 3
12 2 2
7 6 2
1 9 3
Output
2
Input
5
0 0 5
0 10 1
10 0 1
-10 0 1
0 -10 1
Output
4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second
#define dbg(x) cout<<#x" = "<<((x))<<endl
template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;}
template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;}
/* 基本要素 */
typedef complex<double> Point;
typedef pair<Point, Point> Line;
typedef vector<Point> VP;
const double EPS = 1e-6; // 許容誤差^2
const double INF = 1e9;
#define X real()
#define Y imag()
// #define LE(n,m) ((n) < (m) + EPS)
#define LE(n,m) ((n) - (m) < EPS)
// #define GE(n,m) ((n) + EPS > (m))
#define GE(n,m) (EPS > (m) - (n))
#define EQ(n,m) (abs((n)-(m)) < EPS)
// 内積 dot(a,b) = |a||b|cosθ
double dot(Point a, Point b) {
return a.X*b.X + a.Y*b.Y;
}
// 外積 cross(a,b) = |a||b|sinθ
double cross(Point a, Point b) {
return a.X*b.Y - a.Y*b.X;
}
// 点の進行方向
int ccw(Point a, Point b, Point c) {
b -= a; c -= a;
if (cross(b,c) > EPS) return +1; // counter clockwise
if (cross(b,c) < -EPS) return -1; // clockwise
if (dot(b,c) < -EPS) return +2; // c--a--b on line
if (norm(b) < norm(c)) return -2; // a--b--c on line or a==b
return 0; // a--c--b on line or a==c or b==c
}
// 点pの直線aへの射影点を返す
Point proj(Point a1, Point a2, Point p) {
return a1 + dot(a2-a1, p-a1)/norm(a2-a1) * (a2-a1);
}
VP crosspointLC(Point a1, Point a2, Point c, double r) {
VP ps;
Point ft = proj(a1, a2, c);
if(!GE(r*r,norm(ft-c))) return ps;
Point dir = sqrt(max(r*r - norm(ft-c), 0.0)) / abs(a2-a1) * (a2-a1);
ps.push_back(ft + dir);
if (!EQ(r*r, norm(ft-c))) ps.push_back(ft - dir);
return ps;
}
// 2円の共通接線。返される各直線に含まれる頂点は円との接点となる
vector<Line> tangentLines(Point a, double ar, Point b, double br) {
vector<Line> ls;
double d = abs(b-a);
rep (i,2) {
double sin = (ar - (1-i*2)*br) / d;
if (!LE(sin*sin, 1)) break;
double cos = sqrt(max(1 - sin*sin, 0.0));
rep (j,2) {
Point n = (b-a) * Point(sin, (1-j*2)*cos) / d;
ls.push_back(Line(a + ar*n, b + (1-i*2)*br*n));
if (cos < EPS) break; // 重複する接線を無視(重複していいならこの行不要)
}
}
return ls;
}
const int N = 16;
int dp[1<<N];
int m[N][N][4];
int main(){
int n;
cin >>n;
vector<Point> c(n);
vector<int> r(n);
rep(i,n){
int x,y;
cin >>x >>y >>r[i];
c[i] = Point(x,y);
}
reverse(all(c));
reverse(all(r));
swap(c[0],c[n-1]);
swap(r[0],r[n-1]);
rep(i,n)rep(j,i){
vector<Line> seg = tangentLines(c[i],r[i],c[j],r[j]);
int S = seg.size();
assert(S==4);
rep(k,S){
Line l = seg[k];
VP tmp = crosspointLC(l.fi,l.se,c[0],r[0]);
if(tmp.size()==0) continue;
Point p = tmp[0];
if(ccw(p,l.fi,l.se)==2) continue;
int val = (1<<i)|(1<<j)|1;
for(int x=1; x<n; ++x)if(x!=i && x!=j){
VP ump = crosspointLC(p,l.fi,c[x],r[x]);
if(ump.size()==0) continue;
Point cc = ump[0];
if(ccw(p,l.fi,cc)!=2) val |= (1<<x);
}
m[i][j][k] = m[j][i][k] = val;
}
}
fill(dp,dp+(1<<N),10101);
dp[1] = 0;
rep(mask,1<<n){
rep(i,n)rep(j,n)rep(k,4){
int nmask = (mask|m[i][j][k]);
dp[nmask] = min(dp[nmask], dp[mask]+1);
}
}
cout << dp[(1<<n)-1] << endl;
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of s characters. The first participant types one character in v1 milliseconds and has ping t1 milliseconds. The second participant types one character in v2 milliseconds and has ping t2 milliseconds.
If connection ping (delay) is t milliseconds, the competition passes for a participant as follows:
1. Exactly after t milliseconds after the start of the competition the participant receives the text to be entered.
2. Right after that he starts to type it.
3. Exactly t milliseconds after he ends typing all the text, the site receives information about it.
The winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw.
Given the length of the text and the information about participants, determine the result of the game.
Input
The first line contains five integers s, v1, v2, t1, t2 (1 ≤ s, v1, v2, t1, t2 ≤ 1000) — the number of characters in the text, the time of typing one character for the first participant, the time of typing one character for the the second participant, the ping of the first participant and the ping of the second participant.
Output
If the first participant wins, print "First". If the second participant wins, print "Second". In case of a draw print "Friendship".
Examples
Input
5 1 2 1 2
Output
First
Input
3 3 1 1 1
Output
Second
Input
4 5 3 1 5
Output
Friendship
Note
In the first example, information on the success of the first participant comes in 7 milliseconds, of the second participant — in 14 milliseconds. So, the first wins.
In the second example, information on the success of the first participant comes in 11 milliseconds, of the second participant — in 5 milliseconds. So, the second wins.
In the third example, information on the success of the first participant comes in 22 milliseconds, of the second participant — in 22 milliseconds. So, it is be a draw.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int v1, v2, t1, t2, n;
cin >> n >> v1 >> v2 >> t1 >> t2;
int first = n * v1 + 2 * t1;
int second = n * v2 + 2 * t2;
if (first < second)
cout << "First" << endl;
else if (second < first)
cout << "Second" << endl;
else
cout << "Friendship" << endl;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
There are N cards. The two sides of each of these cards are distinguishable. The i-th of these cards has an integer A_i printed on the front side, and another integer B_i printed on the back side. We will call the deck of these cards X. There are also N+1 cards of another kind. The i-th of these cards has an integer C_i printed on the front side, and nothing is printed on the back side. We will call this another deck of cards Y.
You will play Q rounds of a game. Each of these rounds is played independently. In the i-th round, you are given a new card. The two sides of this card are distinguishable. It has an integer D_i printed on the front side, and another integer E_i printed on the back side. A new deck of cards Z is created by adding this card to X. Then, you are asked to form N+1 pairs of cards, each consisting of one card from Z and one card from Y. Each card must belong to exactly one of the pairs. Additionally, for each card from Z, you need to specify which side to use. For each pair, the following condition must be met:
* (The integer printed on the used side of the card from Z) \leq (The integer printed on the card from Y)
If it is not possible to satisfy this condition regardless of how the pairs are formed and which sides are used, the score for the round will be -1. Otherwise, the score for the round will be the count of the cards from Z whose front side is used.
Find the maximum possible score for each round.
Constraints
* All input values are integers.
* 1 \leq N \leq 10^5
* 1 \leq Q \leq 10^5
* 1 \leq A_i ,B_i ,C_i ,D_i ,E_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 B_1
A_2 B_2
:
A_N B_N
C_1 C_2 .. C_{N+1}
Q
D_1 E_1
D_2 E_2
:
D_Q E_Q
Output
For each round, print the maximum possible score in its own line.
Examples
Input
3
4 1
5 3
3 1
1 2 3 4
3
5 4
4 3
2 3
Output
0
1
2
Input
5
7 1
9 7
13 13
11 8
12 9
16 7 8 6 9 11
7
6 11
7 10
9 3
12 9
18 16
8 9
10 15
Output
4
3
3
1
-1
3
2
Input
9
89 67
37 14
6 1
42 25
61 22
23 1
63 60
93 62
14 2
67 96 26 17 1 62 56 92 13 38
11
93 97
17 93
61 57
88 62
98 29
49 1
5 1
1 77
34 1
63 27
22 66
Output
7
9
8
7
7
9
9
10
9
7
9
### Response
```cpp
#include<iostream>
#include<vector>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<ctime>
#include<queue>
#include<set>
using namespace std;
typedef long long LL;
const int N=2e5;
int gi() {
int w=0;bool q=1;char c=getchar();
while ((c<'0'||c>'9') && c!='-') c=getchar();
if (c=='-') q=0,c=getchar();
while (c>='0'&&c <= '9') w=w*10+c-'0',c=getchar();
return q? w:-w;
}
int a[N],b[N],c[N];
int suf[N],d[N],f[N];
pair<int,int>p[N];
int head[N],nxt[N];
bool side[N];
#define x first
#define y second
int main()
{
int n=gi(),m,i,j,s,l,r,all=0,cur=0;
priority_queue< pair<int,int> >q;
for (i=1;i<=n;i++) a[i]=gi(),b[i]=gi();
for (i=1;i<=n+1;i++) c[i]=gi();
sort(c+1,c+1+n+1);
for (i=1;i<=n;i++) {
a[i]=lower_bound(c+1,c+1+n+1,a[i])-c;
b[i]=lower_bound(c+1,c+1+n+1,b[i])-c;
d[a[i]-1]--;
if (b[i]<a[i])
nxt[i]=head[a[i]-1],head[a[i]-1]=i;
side[i]=true;
}
for (s=-1,i=n+1;i;i--,s++) {//一开始多了一个,每一轮可以抵消一个
s+=d[i];
for (j=head[i];j;j=nxt[j]) q.push(make_pair(-b[j],j));
while (s<-1) //如果<-1则必须把某一个变小
if (q.empty()||-q.top().x>i) { for (m=gi();m--;) puts("-1"); return 0; }
else side[q.top().y]=false,s++,d[i]++,d[-q.top().x-1]--,all++,q.pop();
}
m=gi();
for (i=n+1;i>=0;i--) d[i]=0;
for (i=1;i<=n;i++) d[side[i]?a[i]:b[i]]++;
for (i=2;i<=n+1;i++) d[i]+=d[i-1];
while (!q.empty()) q.pop();
for (i=n+1;i;i--) head[i]=0;
for (i=1;i<=n;i++) if (side[i]) nxt[i]=head[b[i]],head[b[i]]=i;
for (i=1;i<=n+1;i++) {
for (j=head[i];j;j=nxt[j]) q.push(make_pair(a[j]-1,j));
f[i]=f[i-1];
if (d[i]-i==-1&&cur<i) {
if (q.empty()||q.top().x<i) f[i]=1<<30;
else cur=q.top().x,f[i]++,q.pop();
}
}
while (m--) {
l=lower_bound(c+1,c+1+n+1,gi())-c;
r=lower_bound(c+1,c+1+n+1,gi())-c;
l=f[l-1]+all;
r=f[r-1]+all;
l=min(l,r+1);
if (l>n+1) puts("-1");
else printf("%d\n",n+1-l);
}
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position.
Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that.
Input
The first line of the input contains three integers n, k and x (1 ≤ n, k ≤ 200 000, 1 ≤ x ≤ 109) — the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively.
The second line contains n integers a1, a2, ..., an (<image>) — the elements of the array found by Maxim.
Output
Print n integers b1, b2, ..., bn in the only line — the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 ≤ i ≤ n, but the product of all array elements should be minimum possible.
If there are multiple answers, print any of them.
Examples
Input
5 3 1
5 4 3 5 2
Output
5 4 3 5 -1
Input
5 3 1
5 4 3 5 5
Output
5 4 0 5 5
Input
5 3 1
5 4 4 5 5
Output
5 1 4 5 5
Input
3 2 7
5 4 2
Output
5 11 -5
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int nMax = 200010;
const long long inf = 1e18;
int n;
long long k, x;
vector<long long> a(nMax);
int minusCnt() {
int cnt = 0;
for (int i = 1; i <= n; i++)
if (a[i] < 0) cnt++;
return cnt;
}
bool chkminus() {
if (minusCnt() % 2) return true;
for (int i = 1; i <= n; i++) {
if (abs(a[i]) < k * x) return true;
}
return false;
}
int findAbsmin() {
int i, j = 1;
long long mn = inf;
for (i = 1; i <= n; i++) {
if (mn > abs(a[i])) {
mn = abs(a[i]);
j = i;
}
}
return j;
}
void positive() {
int i, j = findAbsmin();
if (a[j] < 0)
a[j] += k * x;
else
a[j] -= k * x;
for (i = 1; i <= n; i++) cout << a[i] << " ";
puts("");
}
int main() {
int i, j;
cin >> n >> k >> x;
for (i = 1; i <= n; i++) cin >> a[i];
if (!chkminus()) {
positive();
return 0;
}
if (minusCnt() % 2 == 0) {
i = findAbsmin();
if (a[i] < 0)
while (a[i] < 0) a[i] += x, k--;
else
while (a[i] >= 0) a[i] -= x, k--;
}
priority_queue<pair<long long, int> > pq;
for (i = 1; i <= n; i++) pq.push(pair<long long, int>(-abs(a[i]), i));
while (k--) {
i = pq.top().second;
pq.pop();
if (a[i] < 0)
a[i] -= x;
else
a[i] += x;
pq.push(pair<long long, int>(-abs(a[i]), i));
}
for (i = 1; i <= n; i++) cout << a[i] << " ";
puts("");
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Martha — as a professional problemsetter — proposed a problem for a world-class contest. This is the problem statement:
Tomorrow is Nadia's birthday, and Bardia (her brother) is assigned to make the balloons ready!
There are n balloons (initially empty) that are tied to a straight line on certain positions x1, x2, ..., xn. Bardia inflates the balloons from left to right. As a result, i-th balloon gets bigger and bigger until its radius reaches the pressure endurance pi or it touches another previously-inflated balloon.
<image>
While Bardia was busy with the balloons, he wondered "What will be the sum of radius of balloons after all of the balloons are inflated?". Being a nerdy type of guy, he is now thinking about the problem instead of preparing his sister's birthday. Calculate the answer to Bardia's problem so that Nadia's birthday won't be balloon-less.
Artha — Martha's student — claimed his solution got accepted. Martha (being his teacher for a long time!) knew he couldn't have solved the problem for real and thus thinks there is something wrong with the testcases. Artha isn't anyhow logical, which means there is no way for Martha to explain the wrong point in his algorithm. So, the only way is to find a testcase to prove him wrong!
Artha's pseudo-code is shown below:
<image>
You should output a small testcase for the problem such that Artha's algorithm is incorrect. The algorithm's output is considered correct if it differs from the correct value by no more than 1.
Input
Please pay attention! No input will be given to your program for this problem. So you do not have to read from the input anything.
Output
You should output the generated small testcase (which Artha's solution doesn't get it right). It should be in the following format:
* First line must contain the only number n (1 ≤ n ≤ 500).
* The i-th of the next n lines should contain the description of the i-th balloon — two space-separated integers xi, pi (1 ≤ pi ≤ 106, 0 ≤ x1 < x2 < ... < xn ≤ 106).
Examples
Note
The testcase depicted in the figure above (just showing how output should be formatted):
4
0 9
6 3
12 7
17 1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
printf("302\n");
printf("0 1000000\n");
for (int i = 0; i < 300; ++i) printf("%d %d\n", i * 1000 + 50000, 330 - i);
printf("%d %d\n", 301 * 1000 + 650000, 1000000);
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved.
This is an interactive problem.
You are given a tree consisting of n nodes numbered with integers from 1 to n. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query:
* Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes.
Recall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them.
More formally, let's define two hidden nodes as s and f. In one query you can provide the set of nodes \\{a_1, a_2, …, a_c\} of the tree. As a result, you will get two numbers a_i and dist(a_i, s) + dist(a_i, f). The node a_i is any node from the provided set, for which the number dist(a_i, s) + dist(a_i, f) is minimal.
You can ask no more than 14 queries.
Input
The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. Please note, how the interaction process is organized.
The first line of each test case consists of a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree.
The next n - 1 lines consist of two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree.
Interaction
To ask a query print a single line:
* In the beginning print "? c " (without quotes) where c (1 ≤ c ≤ n) denotes the number of nodes being queried, followed by c distinct integers in the range [1, n] — the indices of nodes from the list.
For each query, you will receive two integers x, d — the node (among the queried nodes) with the minimum sum of distances to the hidden nodes and the sum of distances from that node to the hidden nodes. If the subset of nodes queried is invalid or you exceeded the number of queries then you will get x = d = -1. In this case, you should terminate the program immediately.
When you have guessed the hidden nodes, print a single line "! " (without quotes), followed by two integers in the range [1, n] — the hidden nodes. You can output the hidden nodes in any order.
After this, you should read a string. If you guess the nodes correctly, you will receive the string "Correct". In this case, you should continue solving the remaining test cases or terminate the program, if all test cases were solved. Otherwise, you will receive the string "Incorrect". In this case, you should terminate the program immediately.
Guessing the hidden nodes does not count towards the number of queries asked.
The interactor is not adaptive. The hidden nodes do not change with queries.
Do not forget to read the string "Correct" / "Incorrect" after guessing the hidden nodes.
You need to solve each test case before receiving the input for the next test case.
The limit of 14 queries applies to each test case and not to the entire input.
After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
To hack the solution, use the following test format:
The first line should contain a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of the test cases follows.
The first line of each test case should contain a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree. The second line should contain two distinct integers in the range [1, n] — the hidden nodes. The next n - 1 lines should contain two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree.
Example
Input
1
3
1 2
1 3
1 1
2 3
3 1
3 1
Correct
Output
? 1 1
? 1 2
? 1 3
? 2 2 3
! 1 3
Note
The tree from the first test is shown below, and the hidden nodes are 1 and 3.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long int t;
cin >> t;
while (t--) {
long long int n, x;
cin >> n >> x;
vector<vector<int>> v(x);
int sz;
int a;
for (int i = 0; i < x; i++) {
cin >> sz;
for (int j = 0; j < sz; j++) {
cin >> a;
v[i].push_back(a);
}
}
int maxx;
cout << '?' << " " << n << " ";
for (int i = 0; i < n; i++) {
cout << i + 1 << " ";
}
cout << endl;
cin >> maxx;
int lo = 0, hi = x - 1, mid;
int curr;
while (lo < hi) {
mid = (lo + hi) / 2;
sz = 0;
for (int i = lo; i <= mid; i++) {
sz += v[i].size();
}
cout << "? " << sz << " ";
for (int i = lo; i <= mid; i++) {
for (auto it : v[i]) {
cout << it << " ";
}
}
cout << endl;
cin >> curr;
if (curr == maxx) {
hi = mid;
} else {
lo = mid + 1;
}
}
sz = n - v[lo].size();
unordered_set<int> us;
for (auto it : v[lo]) {
us.insert(it);
}
cout << "? " << sz << " ";
for (int i = 0; i < n; i++) {
if (us.find(i + 1) != us.end()) {
continue;
}
cout << i + 1 << " ";
}
cout << endl;
int temp;
cin >> temp;
cout << "! ";
for (int i = 0; i < x; i++) {
if (i == lo) {
cout << temp << " ";
} else {
cout << maxx << " ";
}
}
cout << endl;
string ans;
cin >> ans;
if (ans == "Incorrect") {
return 0;
}
}
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
This problem is same as the next one, but has smaller constraints.
Aki is playing a new video game. In the video game, he will control Neko, the giant cat, to fly between planets in the Catniverse.
There are n planets in the Catniverse, numbered from 1 to n. At the beginning of the game, Aki chooses the planet where Neko is initially located. Then Aki performs k - 1 moves, where in each move Neko is moved from the current planet x to some other planet y such that:
* Planet y is not visited yet.
* 1 ≤ y ≤ x + m (where m is a fixed constant given in the input)
This way, Neko will visit exactly k different planets. Two ways of visiting planets are called different if there is some index i such that the i-th planet visited in the first way is different from the i-th planet visited in the second way.
What is the total number of ways to visit k planets this way? Since the answer can be quite large, print it modulo 10^9 + 7.
Input
The only line contains three integers n, k and m (1 ≤ n ≤ 10^5, 1 ≤ k ≤ min(n, 12), 1 ≤ m ≤ 4) — the number of planets in the Catniverse, the number of planets Neko needs to visit and the said constant m.
Output
Print exactly one integer — the number of different ways Neko can visit exactly k planets. Since the answer can be quite large, print it modulo 10^9 + 7.
Examples
Input
3 3 1
Output
4
Input
4 2 1
Output
9
Input
5 5 4
Output
120
Input
100 1 2
Output
100
Note
In the first example, there are 4 ways Neko can visit all the planets:
* 1 → 2 → 3
* 2 → 3 → 1
* 3 → 1 → 2
* 3 → 2 → 1
In the second example, there are 9 ways Neko can visit exactly 2 planets:
* 1 → 2
* 2 → 1
* 2 → 3
* 3 → 1
* 3 → 2
* 3 → 4
* 4 → 1
* 4 → 2
* 4 → 3
In the third example, with m = 4, Neko can visit all the planets in any order, so there are 5! = 120 ways Neko can visit all the planets.
In the fourth example, Neko only visit exactly 1 planet (which is also the planet he initially located), and there are 100 ways to choose the starting planet for Neko.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#pragma warning(disable : 4996)
const int N = 1e5 + 5, K = 13, M = 4, MOD = 1e9 + 7;
int dp[K][N][1 << M], b[1 << M];
void f(int& a, int b) {
a += b;
if (a >= MOD) a -= MOD;
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, k, m;
cin >> n >> k >> m;
for (int i = 0; i < (1 << m); i++) {
int x = i;
while (x > 0) {
b[i] += x & 1;
x >>= 1;
}
}
dp[0][0][0] = 1;
int ans = 0;
for (int i = 0; i <= k; i++) {
for (int j = 0; j < n; j++) {
for (int h = 0; h < (1 << m); h++) {
if (dp[i][j][h]) {
int nh = (h << 1) & ((1 << m) - 1);
f(dp[i][j + 1][nh], dp[i][j][h]);
if (i < k) {
nh |= 1;
f(dp[i + 1][j + 1][nh], dp[i][j][h] * (long long)(b[h] + 1) % MOD);
}
}
}
}
}
for (int i = 0; i < (1 << m); i++) f(ans, dp[k][n][i]);
cout << ans;
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Given a string s, find the number of ways to split s to substrings such that if there are k substrings (p1, p2, p3, ..., pk) in partition, then pi = pk - i + 1 for all i (1 ≤ i ≤ k) and k is even.
Since the number of ways can be large, print it modulo 109 + 7.
Input
The only line of input contains a string s (2 ≤ |s| ≤ 106) of even length consisting of lowercase Latin letters.
Output
Print one integer, the number of ways of partitioning the string modulo 109 + 7.
Examples
Input
abcdcdab
Output
1
Input
abbababababbab
Output
3
Note
In the first case, the only way to partition the string is ab|cd|cd|ab.
In the second case, the string can be partitioned as ab|b|ab|ab|ab|ab|b|ab or ab|b|abab|abab|b|ab or abbab|ab|ab|abbab.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int maxn = 1e6 + 5;
char s[maxn], ss[maxn];
int n;
long long f[maxn], ans[maxn];
int len[maxn], fail[maxn], ch[maxn][26], last = 1, tot = 1, fa[maxn], cha[maxn];
int getfail(int x, int i) {
while (i - len[x] - 1 < 0 || s[i - len[x] - 1] != s[i]) x = fail[x];
return x;
}
int main() {
scanf("%s", ss + 1);
n = strlen(ss + 1);
for (int i = 1; i <= n; i += 2) s[i] = ss[(i + 1) >> 1];
reverse(ss + 1, ss + n + 1);
for (int i = 2; i <= n; i += 2) s[i] = ss[(i + 1) >> 1];
if (n & 1) {
printf("0\n");
return 0;
}
len[1] = -1;
fail[0] = fail[1] = 1;
ans[0] = 1;
fa[0] = 1;
for (int i = 1; i <= n; i++) {
int cur = last;
cur = getfail(cur, i);
if (!ch[cur][s[i] - 'a']) {
fail[++tot] = ch[getfail(fail[cur], i)][s[i] - 'a'];
len[tot] = len[cur] + 2;
ch[cur][s[i] - 'a'] = tot;
cha[tot] = len[tot] - len[fail[tot]];
fa[tot] = (cha[tot] == cha[fail[tot]]) ? fa[fail[tot]] : fail[tot];
}
last = ch[cur][s[i] - 'a'];
for (int j = last; j; j = fa[j]) {
f[j] = ans[i - len[fa[j]] - cha[j]];
if (fa[j] != fail[j]) f[j] = (f[j] + f[fail[j]]) % mod;
if (i % 2 == 0) ans[i] = (ans[i] + f[j]) % mod;
}
}
printf("%lld", ans[n]);
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
An exam for n students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (i and i + 1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sure.
Your task is to choose the maximum number of students and make such an arrangement of students in the room that no two students with adjacent numbers sit side by side.
Input
A single line contains integer n (1 ≤ n ≤ 5000) — the number of students at an exam.
Output
In the first line print integer k — the maximum number of students who can be seated so that no two students with adjacent numbers sit next to each other.
In the second line print k distinct integers a1, a2, ..., ak (1 ≤ ai ≤ n), where ai is the number of the student on the i-th position. The students on adjacent positions mustn't have adjacent numbers. Formally, the following should be true: |ai - ai + 1| ≠ 1 for all i from 1 to k - 1.
If there are several possible answers, output any of them.
Examples
Input
6
Output
6
1 5 3 6 2 4
Input
3
Output
2
1 3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
if (n <= 3) {
if (n == 2)
cout << n / 2 << endl;
else
cout << n / 2 + 1 << endl;
for (int i = 1; i <= n; i += 2) {
cout << i << " ";
}
} else {
cout << n << endl;
for (int i = 2; i <= n; i += 2) {
cout << i << " ";
}
for (int i = 1; i <= n; i += 2) {
cout << i << " ";
}
}
cout << endl;
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
There are n emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The i-th emote increases the opponent's happiness by a_i units (we all know that emotes in this game are used to make opponents happy).
You have time to use some emotes only m times. You are allowed to use any emotion once, more than once, or not use it at all. The only restriction is that you cannot use the same emote more than k times in a row (otherwise the opponent will think that you're trolling him).
Note that two emotes i and j (i ≠ j) such that a_i = a_j are considered different.
You have to make your opponent as happy as possible. Find the maximum possible opponent's happiness.
Input
The first line of the input contains three integers n, m and k (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ m ≤ 2 ⋅ 10^9) — the number of emotes, the number of times you can use emotes and the maximum number of times you may use the same emote 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 value of the happiness of the i-th emote.
Output
Print one integer — the maximum opponent's happiness if you use emotes in a way satisfying the problem statement.
Examples
Input
6 9 2
1 3 3 7 4 2
Output
54
Input
3 1000000000 1
1000000000 987654321 1000000000
Output
1000000000000000000
Note
In the first example you may use emotes in the following sequence: 4, 4, 5, 4, 4, 5, 4, 4, 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
unsigned long long n, m, k, count = 0, c = 0;
cin >> n >> m >> k;
int a[n + 1];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
sort(a, a + n);
int j = 0;
c = m / (k + 1);
count += (m - c) * a[n - 1] + c * a[n - 2];
cout << count << endl;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Let's denote d(n) as the number of divisors of a positive integer n. You are given three integers a, b and c. Your task is to calculate the following sum:
<image>
Find the sum modulo 1073741824 (230).
Input
The first line contains three space-separated integers a, b and c (1 ≤ a, b, c ≤ 2000).
Output
Print a single integer — the required sum modulo 1073741824 (230).
Examples
Input
2 2 2
Output
20
Input
4 4 4
Output
328
Input
10 10 10
Output
11536
Note
For the first example.
* d(1·1·1) = d(1) = 1;
* d(1·1·2) = d(2) = 2;
* d(1·2·1) = d(2) = 2;
* d(1·2·2) = d(4) = 3;
* d(2·1·1) = d(2) = 2;
* d(2·1·2) = d(4) = 3;
* d(2·2·1) = d(4) = 3;
* d(2·2·2) = d(8) = 4.
So the result is 1 + 2 + 2 + 3 + 2 + 3 + 3 + 4 = 20.
### Response
```cpp
#include <bits/stdc++.h>
inline int read() {
char ch = getchar();
int ret = 0, f = 1;
while (ch > '9' || ch < '0') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') ret = ret * 10 + ch - '0', ch = getchar();
return ret * f;
}
const int mx = 2005;
int p[mx], bk[mx], pt, m[mx], m2[mx], g[mx][mx];
inline int gcd(int x, int y) {
if (g[x][y]) return g[x][y];
return y ? gcd(y, x % y) : x;
}
inline void sieve(int up) {
m[1] = 1;
for (int i = 2; i <= up; i++) {
if (!bk[i]) p[++pt] = i, m[i] = -1;
for (int j = 1; j <= pt; j++) {
if (i * p[j] > up) break;
bk[i * p[j]] = 1, m[i * p[j]] = -m[i];
if (i % p[j] == 0) {
m[i * p[j]] = 0;
break;
}
}
}
for (int i = 1; i <= up; i++)
for (int j = i; j <= up; j++) g[i][j] = g[j][i] = (gcd(i, j) == 1);
}
inline unsigned F(int k, int n, unsigned re = 0) {
for (int pp = 1; pp <= n; pp++)
if (g[pp][k] == 1) re += n / pp;
return re;
}
inline int min(int a, int b) { return a < b ? a : b; }
inline void swap(int &a, int &b) {
int t = a;
a = b, b = t;
}
inline void cal(int a, int b, int c, unsigned ans = 0) {
if (b < c) swap(b, c);
for (int i = 1; i <= a; i++) {
for (int j = 1; j <= b && j <= c; j++) {
m2[j] = m2[j - 1];
if (g[i][j]) m2[j] += m[j];
}
for (int d = 1, ls; d <= b && d <= c; d = ls + 1) {
ls = min(b / (b / d), c / (c / d));
if (m2[ls] != m2[d - 1])
ans += (a / i) * (unsigned)(m2[ls] - m2[d - 1]) * F(i, b / d) *
F(i, c / d);
}
}
printf("%d\n", ans % (1 << 30));
}
int main() {
sieve(2000);
cal(read(), read(), read());
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
You are given a rooted tree with n vertices. The vertices are numbered from 1 to n, the root is the vertex number 1.
Each vertex has a color, let's denote the color of vertex v by cv. Initially cv = 0.
You have to color the tree into the given colors using the smallest possible number of steps. On each step you can choose a vertex v and a color x, and then color all vectices in the subtree of v (including v itself) in color x. In other words, for every vertex u, such that the path from root to u passes through v, set cu = x.
It is guaranteed that you have to color each vertex in a color different from 0.
You can learn what a rooted tree is using the link: https://en.wikipedia.org/wiki/Tree_(graph_theory).
Input
The first line contains a single integer n (2 ≤ n ≤ 104) — the number of vertices in the tree.
The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi < i), where pi means that there is an edge between vertices i and pi.
The third line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ n), where ci is the color you should color the i-th vertex into.
It is guaranteed that the given graph is a tree.
Output
Print a single integer — the minimum number of steps you have to perform to color the tree into given colors.
Examples
Input
6
1 2 2 1 5
2 1 1 1 1 1
Output
3
Input
7
1 1 2 3 1 4
3 3 1 1 1 2 3
Output
5
Note
The tree from the first sample is shown on the picture (numbers are vetices' indices):
<image>
On first step we color all vertices in the subtree of vertex 1 into color 2 (numbers are colors):
<image>
On seond step we color all vertices in the subtree of vertex 5 into color 1:
<image>
On third step we color all vertices in the subtree of vertex 2 into color 1:
<image>
The tree from the second sample is shown on the picture (numbers are vetices' indices):
<image>
On first step we color all vertices in the subtree of vertex 1 into color 3 (numbers are colors):
<image>
On second step we color all vertices in the subtree of vertex 3 into color 1:
<image>
On third step we color all vertices in the subtree of vertex 6 into color 2:
<image>
On fourth step we color all vertices in the subtree of vertex 4 into color 1:
<image>
On fith step we color all vertices in the subtree of vertex 7 into color 3:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e4 + 10;
int co[maxn];
list<int> adj[maxn];
int ans = 0;
void df(int v, int col, int p = -1) {
if (co[v] != col) {
ans++;
col = co[v];
}
for (int ver : adj[v]) {
if (ver == p) continue;
df(ver, col, v);
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
for (int i = 2; i <= n; ++i) {
int p;
cin >> p;
adj[i].push_back(p);
adj[p].push_back(i);
}
for (int i = 1; i <= n; ++i) cin >> co[i];
df(1, -1);
cout << ans << '\n';
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Peter likes to travel by train. He likes it so much that on the train he falls asleep.
Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.
The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.
At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.
Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.
Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.
Input
The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.
The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.
Output
Output one of the four words without inverted commas:
* «forward» — if Peter could see such sequences only on the way from A to B;
* «backward» — if Peter could see such sequences on the way from B to A;
* «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;
* «fantasy» — if Peter could not see such sequences.
Examples
Input
atob
a
b
Output
forward
Input
aaacaaa
aca
aa
Output
both
Note
It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 9;
char d[maxn];
string a;
string b;
string c;
int main() {
cin >> a >> b >> c;
int A, B, C;
int flag = 0;
int flag1 = 0;
int flag2 = 0;
int i, j;
int len;
size_t repos1;
size_t repos2;
repos1 = a.find(b);
repos2 = a.find(c, repos1 + b.length());
if (repos1 != string::npos && repos2 != string::npos) flag1 = 1;
len = a.length() - 1;
j = len;
i = 0;
for (; i < j; i++, j--) {
char t;
t = a[i];
a[i] = a[j];
a[j] = t;
}
size_t popos1;
size_t popos2;
popos1 = a.find(b);
popos2 = a.find(c, popos1 + b.length());
if (popos2 != string::npos && popos1 != string::npos) flag2 = 1;
if (flag1 == 1) {
if (flag2 == 1)
cout << "both\n";
else
cout << "forward\n";
} else {
if (flag2 == 1)
cout << "backward\n";
else
cout << "fantasy\n";
}
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Fox Ciel is playing a card game with her friend Fox Jiro. There are n piles of cards on the table. And there is a positive integer on each card.
The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom of any non-empty pile. Each player wants to maximize the total sum of the cards he took. The game ends when all piles become empty.
Suppose Ciel and Jiro play optimally, what is the score of the game?
Input
The first line contain an integer n (1 ≤ n ≤ 100). Each of the next n lines contains a description of the pile: the first integer in the line is si (1 ≤ si ≤ 100) — the number of cards in the i-th pile; then follow si positive integers c1, c2, ..., ck, ..., csi (1 ≤ ck ≤ 1000) — the sequence of the numbers on the cards listed from top of the current pile to bottom of the pile.
Output
Print two integers: the sum of Ciel's cards and the sum of Jiro's cards if they play optimally.
Examples
Input
2
1 100
2 1 10
Output
101 10
Input
1
9 2 8 6 5 9 4 7 1 3
Output
30 15
Input
3
3 1 3 2
3 5 4 6
2 8 7
Output
18 18
Input
3
3 1000 1000 1000
6 1000 1000 1000 1000 1000 1000
5 1000 1000 1000 1000 1000
Output
7000 7000
Note
In the first example, Ciel will take the cards with number 100 and 1, Jiro will take the card with number 10.
In the second example, Ciel will take cards with numbers 2, 8, 6, 5, 9 and Jiro will take cards with numbers 4, 7, 1, 3.
### 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> rem;
int sum1 = 0, sum2 = 0;
for (int i = 0; i < n; i++) {
int k;
cin >> k;
vector<int> a(k);
for (int &x : a) {
cin >> x;
}
if (k % 2) {
rem.push_back(a[k / 2]);
a.erase(a.begin() + k / 2);
k--;
}
for (int j = 0; j < k; j++) {
if (j < k / 2) {
sum1 += a[j];
} else {
sum2 += a[j];
}
}
}
sort(rem.begin(), rem.end());
for (int pl = 0; !rem.empty(); pl ^= 1) {
if (pl) {
sum2 += rem.back();
} else {
sum1 += rem.back();
}
rem.pop_back();
}
cout << sum1 << " " << sum2;
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
There is a square grid of size n × n. Some cells are colored in black, all others are colored in white. In one operation you can select some rectangle and color all its cells in white. It costs max(h, w) to color a rectangle of size h × w. You are to make all cells white for minimum total cost.
Input
The first line contains a single integer n (1 ≤ n ≤ 50) — the size of the square grid.
Each of the next n lines contains a string of length n, consisting of characters '.' and '#'. The j-th character of the i-th line is '#' if the cell with coordinates (i, j) is black, otherwise it is white.
Output
Print a single integer — the minimum total cost to paint all cells in white.
Examples
Input
3
###
#.#
###
Output
3
Input
3
...
...
...
Output
0
Input
4
#...
....
....
#...
Output
2
Input
5
#...#
.#.#.
.....
.#...
#....
Output
5
Note
The examples and some of optimal solutions are shown on the pictures below.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 51;
int n, dp[N][N][N][N];
char M[N][N];
int dfs(int a, int b, int c, int d) {
if (a == c && b == d) return (M[a][b] == '#');
if (dp[a][b][c][d] != -1) return dp[a][b][c][d];
dp[a][b][c][d] = max(c - a, d - b) + 1;
for (int i = a; i < c; i++)
dp[a][b][c][d] = min(dp[a][b][c][d], dfs(a, b, i, d) + dfs(i + 1, b, c, d));
for (int i = b; i < d; i++)
dp[a][b][c][d] = min(dp[a][b][c][d], dfs(a, b, c, i) + dfs(a, i + 1, c, d));
return dp[a][b][c][d];
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) cin >> M[i][j];
memset(dp, -1, sizeof(dp));
cout << dfs(1, 1, n, n) << endl;
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Polycarp decided to relax on his weekend and visited to the performance of famous ropewalkers: Agafon, Boniface and Konrad.
The rope is straight and infinite in both directions. At the beginning of the performance, Agafon, Boniface and Konrad are located in positions a, b and c respectively. At the end of the performance, the distance between each pair of ropewalkers was at least d.
Ropewalkers can walk on the rope. In one second, only one ropewalker can change his position. Every ropewalker can change his position exactly by 1 (i. e. shift by 1 to the left or right direction on the rope). Agafon, Boniface and Konrad can not move at the same time (Only one of them can move at each moment). Ropewalkers can be at the same positions at the same time and can "walk past each other".
You should find the minimum duration (in seconds) of the performance. In other words, find the minimum number of seconds needed so that the distance between each pair of ropewalkers can be greater or equal to d.
Ropewalkers can walk to negative coordinates, due to the rope is infinite to both sides.
Input
The only line of the input contains four integers a, b, c, d (1 ≤ a, b, c, d ≤ 10^9). It is possible that any two (or all three) ropewalkers are in the same position at the beginning of the performance.
Output
Output one integer — the minimum duration (in seconds) of the performance.
Examples
Input
5 2 6 3
Output
2
Input
3 1 5 6
Output
8
Input
8 3 3 2
Output
2
Input
2 3 10 4
Output
3
Note
In the first example: in the first two seconds Konrad moves for 2 positions to the right (to the position 8), while Agafon and Boniface stay at their positions. Thus, the distance between Agafon and Boniface will be |5 - 2| = 3, the distance between Boniface and Konrad will be |2 - 8| = 6 and the distance between Agafon and Konrad will be |5 - 8| = 3. Therefore, all three pairwise distances will be at least d=3, so the performance could be finished within 2 seconds.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void pairsort(long long a[], long long b[], long long n) {
pair<long long, long long> pairt[n];
for (long long i = 0; i < n; i++) {
pairt[i].first = a[i];
pairt[i].second = b[i];
}
sort(pairt, pairt + n);
for (long long i = 0; i < n; i++) {
a[i] = pairt[i].first;
b[i] = pairt[i].second;
}
}
bool isPrime(long long n) {
for (long long i = 2; i <= sqrt(n); i++) {
if (n % i == 0) return 0;
}
return 1;
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long a[3], d;
cin >> a[0] >> a[1] >> a[2] >> d;
sort(a, a + 3);
long long ans = 0;
if (abs(a[0] - a[1]) < d) ans += d - abs(a[0] - a[1]);
if (abs(a[2] - a[1]) < d) ans += d - abs(a[1] - a[2]);
cout << ans;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
You are given two arrays of integers a_1,…,a_n and b_1,…,b_m.
Your task is to find a non-empty array c_1,…,c_k that is a subsequence of a_1,…,a_n, and also a subsequence of b_1,…,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, find any. If there are no such arrays, you should report about it.
A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero) elements. For example, [3,1] is a subsequence of [3,2,1] and [4,3,1], but not a subsequence of [1,3,3,7] and [3,10,4].
Input
The first line contains a single integer t (1≤ t≤ 1000) — the number of test cases. Next 3t lines contain descriptions of test cases.
The first line of each test case contains two integers n and m (1≤ n,m≤ 1000) — the lengths of the two arrays.
The second line of each test case contains n integers a_1,…,a_n (1≤ a_i≤ 1000) — the elements of the first array.
The third line of each test case contains m integers b_1,…,b_m (1≤ b_i≤ 1000) — the elements of the second array.
It is guaranteed that the sum of n and the sum of m across all test cases does not exceed 1000 (∑_{i=1}^t n_i, ∑_{i=1}^t m_i≤ 1000).
Output
For each test case, output "YES" if a solution exists, or "NO" otherwise.
If the answer is "YES", on the next line output an integer k (1≤ k≤ 1000) — the length of the array, followed by k integers c_1,…,c_k (1≤ c_i≤ 1000) — the elements of the array.
If there are multiple solutions with the smallest possible k, output any.
Example
Input
5
4 5
10 8 6 4
1 2 3 4 5
1 1
3
3
1 1
3
2
5 3
1000 2 2 2 3
3 1 5
5 5
1 2 3 4 5
1 2 3 4 5
Output
YES
1 4
YES
1 3
NO
YES
1 3
YES
1 2
Note
In the first test case, [4] is a subsequence of [10, 8, 6, 4] and [1, 2, 3, 4, 5]. This array has length 1, it is the smallest possible length of a subsequence of both a and b.
In the third test case, no non-empty subsequences of both [3] and [2] exist, so the answer is "NO".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long t, x, y, n, m, r[1001], s[1001];
cin >> t;
while (t--) {
cin >> x >> y;
n = x;
m = y;
while (x) cin >> r[--x];
while (y) cin >> s[--y];
sort(r, r + n);
sort(s, s + m);
for (x = 0, y = 0; x < n && y < m;) {
if (r[x] == s[y]) break;
if (r[x] > s[y])
y++;
else
x++;
}
if (x < n && y < m)
cout << "YES\n1 " << r[x] << endl;
else
cout << "NO\n";
}
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Bytelandian Tree Factory produces trees for all kinds of industrial applications. You have been tasked with optimizing the production of a certain type of tree for an especially large and important order.
The tree in question is a rooted tree with n vertices labelled with distinct integers from 0 to n - 1. The vertex labelled 0 is the root of the tree, and for any non-root vertex v the label of its parent p(v) is less than the label of v.
All trees at the factory are made from bamboo blanks. A bamboo is a rooted tree such that each vertex has exactly one child, except for a single leaf vertex with no children. The vertices of a bamboo blank can be labelled arbitrarily before its processing is started.
To process a bamboo into another tree a single type of operation can be made: choose an arbitrary non-root vertex v such that its parent p(v) is not a root either. The operation consists of changing the parent of v to its parent's parent p(p(v)). Note that parents of all other vertices remain unchanged, in particular, the subtree of v does not change.
Efficiency is crucial, hence you have to minimize the number of operations to make the desired tree from a bamboo blank. Construct any optimal sequence of operations to produce the desired tree.
Note that the labelling of the resulting tree has to coincide with the labelling of the desired tree. Formally, the labels of the roots have to be equal, and for non-root vertices with the same label the labels of their parents should be the same.
It is guaranteed that for any test present in this problem an answer exists, and further, an optimal sequence contains at most 10^6 operations. Note that any hack that does not meet these conditions will be invalid.
Input
The first line contains a single integer n — the number of vertices in the tree (2 ≤ n ≤ 10^5).
The second line contains n - 1 integers p(1), …, p(n - 1) — indices of parent vertices of 1, …, n - 1 respectively (0 ≤ p(i) < i).
Output
In the first line, print n distinct integers id_1, …, id_n — the initial labelling of the bamboo blank starting from the root vertex (0 ≤ id_i < n).
In the second line, print a single integer k — the number of operations in your sequence (0 ≤ k ≤ 10^6).
In the third line print k integers v_1, …, v_k describing operations in order. The i-th operation consists of changing p(v_i) to p(p(v_i)). Each operation should be valid, i.e. neither v_i nor p(v_i) can be the root of the tree at the moment.
Examples
Input
5
0 0 1 1
Output
0 2 1 4 3
2
1 3
Input
4
0 1 2
Output
0 1 2 3
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2.001E5;
vector<int> adj[MAXN];
int ans[MAXN];
int up[MAXN];
int treeSize[MAXN];
int dep[MAXN];
int pa[MAXN];
int maxUpSon[MAXN];
int n, cc, minC;
void getAns(int u) {
ans[++cc] = u;
for (int v : adj[u])
if (v != maxUpSon[u]) getAns(v);
if (maxUpSon[u]) getAns(maxUpSon[u]);
}
int main(void) {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n;
for (int i = 2, a; i <= n; ++i)
cin >> a, ++a, pa[i] = a, adj[a].push_back(i), dep[i] = dep[a] + 1;
for (int i = n; i > 1; --i)
if (up[pa[i]] < up[i] + 1) maxUpSon[pa[i]] = i, up[pa[i]] = up[i] + 1;
getAns(1);
for (int i = 1; i <= n; ++i)
cout << ans[i] - 1 << " \n"[i == n],
(i > 1) & (minC += dep[ans[i - 1]] - dep[pa[ans[i]]]);
cout << minC << '\n';
for (int i = 2; i <= n; ++i)
for (int j = 1; j <= dep[ans[i - 1]] - dep[pa[ans[i]]]; ++j)
cout << ans[i] - 1 << " ";
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
This is the easy version of the problem. The only difference is that in this version q=1. You can make hacks only if all versions of the problem are solved.
Zookeeper has been teaching his q sheep how to write and how to add. The i-th sheep has to write exactly k non-negative integers with the sum n_i.
Strangely, sheep have superstitions about digits and believe that the digits 3, 6, and 9 are lucky. To them, the fortune of a number depends on the decimal representation of the number; the fortune of a number is equal to the sum of fortunes of its digits, and the fortune of a digit depends on its value and position and can be described by the following table. For example, the number 319 has fortune F_{2} + 3F_{0}.
<image>
Each sheep wants to maximize the sum of fortune among all its k written integers. Can you help them?
Input
The first line contains a single integer k (1 ≤ k ≤ 999999): the number of numbers each sheep has to write.
The next line contains six integers F_0, F_1, F_2, F_3, F_4, F_5 (1 ≤ F_i ≤ 10^9): the fortune assigned to each digit.
The next line contains a single integer q (q = 1): the number of sheep.
Each of the next q lines contains a single integer n_i (1 ≤ n_i ≤ 999999): the sum of numbers that i-th sheep has to write. In this version, there is only one line.
Output
Print q lines, where the i-th line contains the maximum sum of fortune of all numbers of the i-th sheep. In this version, you should print only one line.
Examples
Input
3
1 2 3 4 5 6
1
57
Output
11
Input
3
1 2 3 4 5 6
1
63
Output
8
Note
In the first test case, 57 = 9 + 9 + 39. The three 9's contribute 1 ⋅ 3 and 3 at the tens position contributes 2 ⋅ 1. Hence the sum of fortune is 11.
In the second test case, 63 = 35 + 19 + 9. The sum of fortune is 8.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
constexpr int inf32 = 0x3f3f3f3f;
constexpr long long inf64 = 0x3f3f3f3f3f3f3f3f;
constexpr int W = 6;
constexpr int N = 1000000;
int main() {
int k;
cin >> k;
vector<long long> a(W);
for (int w = 0; w < (W); ++w) cin >> a[w];
vector<long long> f(N);
for (int i = 0; i < (N); ++i) {
int first = i;
for (int w = 0; w < (W); ++w) {
if ((first % 10) % 3 == 0) f[i] += a[w] * ((first % 10) / 3);
first /= 10;
}
}
vector<int> pro;
int first = 1, m = (k - 1) * 3;
while (first < m) {
pro.push_back(first);
m -= first, first *= 2;
}
if (m) pro.push_back(m);
int now = 3;
for (int w = 0; w < (W); ++w) {
for (const int &p : pro) {
if (1ll * p * now >= N) continue;
for (int i = (N - p * now) - 1; i >= 0; --i)
f[i + p * now] = max(f[i + p * now], f[i] + a[w] * p);
}
now *= 10;
}
int q;
cin >> q;
while (q--) {
int n;
cin >> n;
cout << f[n] << '\n';
}
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Write a program which reads two integers a and b, and calculates the following values:
* a ÷ b: d (in integer)
* remainder of a ÷ b: r (in integer)
* a ÷ b: f (in real number)
Constraints
* 1 ≤ a, b ≤ 109
Input
Two integers a and b are given in a line.
Output
Print d, r and f separated by a space in a line. For f, the output should not contain an absolute error greater than 10-5.
Example
Input
3 2
Output
1 1 1.50000
### Response
```cpp
#include <iostream>
using namespace std;
int main(){
int a,b;
cin >> a >>b;
printf("%d %d %f",a/b,a%b,(double)a/b);
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Today, Yasser and Adel are at the shop buying cupcakes. There are n cupcake types, arranged from 1 to n on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type i is an integer a_i. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.
Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.
On the other hand, Adel will choose some segment [l, r] (1 ≤ l ≤ r ≤ n) that does not include all of cupcakes (he can't choose [l, r] = [1, n]) and buy exactly one cupcake of each of types l, l + 1, ..., r.
After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.
For example, let the tastinesses of the cupcakes be [7, 4, -1]. Yasser will buy all of them, the total tastiness will be 7 + 4 - 1 = 10. Adel can choose segments [7], [4], [-1], [7, 4] or [4, -1], their total tastinesses are 7, 4, -1, 11 and 3, respectively. Adel can choose segment with tastiness 11, and as 10 is not strictly greater than 11, Yasser won't be happy :(
Find out if Yasser will be happy after visiting the shop.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). The description of the test cases follows.
The first line of each test case contains n (2 ≤ n ≤ 10^5).
The second line of each test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9), where a_i represents the tastiness of the i-th type of cupcake.
It is guaranteed that the sum of n over all test cases doesn't exceed 10^5.
Output
For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".
Example
Input
3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
Output
YES
NO
NO
Note
In the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.
In the second example, Adel will choose the segment [1, 2] with total tastiness 11, which is not less than the total tastiness of all cupcakes, which is 10.
In the third example, Adel can choose the segment [3, 3] with total tastiness of 5. Note that Yasser's cupcakes' total tastiness is also 5, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize(2)
using namespace std;
inline int read() {
int a = 0, b = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-') b = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
a = (a << 3) + (a << 1) + c - '0';
c = getchar();
}
return a * b;
}
const int INF = 0x3f3f3f3f;
const int N = 1e5 + 7;
int a[N];
long long sum[N];
int main() {
int T = read();
while (T--) {
memset(sum, 0, sizeof(sum));
int n = read();
for (register int i = (1); i <= (n); i++)
a[i] = read(), sum[i] = sum[i - 1] + a[i];
int flag = 0;
for (register int i = (1); i <= (n - 1); i++) {
if (sum[i] <= 0) flag = 1;
if (sum[n] - sum[i] <= 0) flag = 1;
}
if (flag)
printf("NO\n");
else
printf("YES\n");
}
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
You are given an image, that can be represented with a 2-d n by m grid of pixels. Each pixel of the image is either on or off, denoted by the characters "0" or "1", respectively. You would like to compress this image. You want to choose an integer k > 1 and split the image into k by k blocks. If n and m are not divisible by k, the image is padded with only zeros on the right and bottom so that they are divisible by k. Each pixel in each individual block must have the same value. The given image may not be compressible in its current state. Find the minimum number of pixels you need to toggle (after padding) in order for the image to be compressible for some k. More specifically, the steps are to first choose k, then the image is padded with zeros, then, we can toggle the pixels so it is compressible for this k. The image must be compressible in that state.
Input
The first line of input will contain two integers n, m (2 ≤ n, m ≤ 2 500), the dimensions of the image.
The next n lines of input will contain a binary string with exactly m characters, representing the image.
Output
Print a single integer, the minimum number of pixels needed to toggle to make the image compressible.
Example
Input
3 5
00100
10110
11001
Output
5
Note
We first choose k = 2.
The image is padded as follows:
001000
101100
110010
000000
We can toggle the image to look as follows:
001100
001100
000000
000000
We can see that this image is compressible for k = 2.
### Response
```cpp
#include <bits/stdc++.h>
int n, m;
char arr[2547][2547];
bool prime[50];
int check(int k) {
int ans = 0;
int loss = k * k;
int tmp;
for (int i = 0; i < n / k + 1; ++i) {
for (int j = 0; j < m / k + 1; ++j) {
tmp = 0;
for (int s = 0; s < k; ++s) {
for (int t = 0; t < k; ++t) {
tmp += arr[s + i * k][t + j * k];
}
}
if (tmp <= loss / 2) {
ans += tmp;
} else {
ans += loss - tmp;
}
}
}
return ans;
}
int main() {
scanf("%d%d", &n, &m);
int i, j, k;
for (i = 0; i < n; ++i) {
scanf("\n");
for (int j = 0; j < m; ++j) {
scanf("%c", &arr[i][j]);
arr[i][j] -= '0';
}
}
for (i = 2; i < 50; ++i) {
if (prime[i] == false) {
for (j = i * 2; j < 50; j += i) {
prime[j] = true;
}
}
}
int min = n * m;
int ans;
if (m > n) {
ans = m;
} else {
ans = n;
}
int tmp;
for (k = 2; k < 50; ++k) {
if (prime[k] == false) {
tmp = check(k);
if (min >= tmp) {
min = tmp;
ans = k;
}
}
}
printf("%d", min);
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
You take part in the testing of new weapon. For the testing a polygon was created. The polygon is a rectangular field n × m in size, divided into unit squares 1 × 1 in size. The polygon contains k objects, each of which is a rectangle with sides, parallel to the polygon sides and entirely occupying several unit squares. The objects don't intersect and don't touch each other.
The principle according to which the weapon works is highly secret. You only know that one can use it to strike any rectangular area whose area is not equal to zero with sides, parallel to the sides of the polygon. The area must completely cover some of the unit squares into which the polygon is divided and it must not touch the other squares. Of course the area mustn't cross the polygon border. Your task is as follows: you should hit no less than one and no more than three rectangular objects. Each object must either lay completely inside the area (in that case it is considered to be hit), or lay completely outside the area.
Find the number of ways of hitting.
Input
The first line has three integers n, m и k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 90) — the sizes of the polygon and the number of objects on it respectively. Next n lines contain m symbols each and describe the polygon. The symbol "*" stands for a square occupied an object, whereas the symbol "." stands for an empty space. The symbols "*" form exactly k rectangular connected areas that meet the requirements of the task.
Output
Output a single number — the number of different ways to hit a target.
Examples
Input
3 3 3
*.*
...
*..
Output
21
Input
4 5 4
.*.**
...**
**...
...**
Output
38
Input
2 2 1
.*
..
Output
4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef struct _Object {
int x1, y1, x2, y2;
} Object;
typedef struct _Line {
int x;
int belong;
int kind;
} Line;
typedef struct _Segment {
int left, right, nCoveredObject;
} Segment;
const int hang[4] = {-1, 0, 1, 0};
int cot[4] = {0, 1, 0, -1};
Object *List;
Object *savedList;
Line *ListLine, *savedListLine;
Segment *ListSegment, *savedListSegment;
int m, n, k, nListSegment;
long long res;
char **table;
void getInput() {
scanf("%d%d%d\n", &m, &n, &k);
table = new char *[m + 1];
for (int i = 0; i <= m - 1; i++) {
table[i] = new char[n + 1];
gets(table[i]);
}
}
void DFS(int i, int j) {
table[i][j] = '.';
List->x1 = min(List->x1, i);
List->x2 = max(List->x2, i);
List->y1 = min(List->y1, j);
List->y2 = max(List->y2, j);
for (int t = 0; t <= 3; t++) {
int x = i + hang[t];
int y = j + cot[t];
if (0 <= x && x < m && 0 <= y && y < n)
if (table[x][y] == '*') DFS(x, y);
}
}
void buildList() {
List = (Object *)malloc(sizeof(Object) * 100);
ListLine = (Line *)malloc(sizeof(Line) * 100 * 2);
savedList = List;
savedListLine = ListLine;
int count = 0;
for (int i = 0; i <= m - 1; i++)
for (int j = 0; j <= n - 1; j++)
if (table[i][j] == '*') {
List->x1 = 10000000;
List->x2 = -10000000;
List->y1 = 10000000;
List->y2 = -10000000;
DFS(i, j);
ListLine->belong = count;
ListLine->kind = 0;
ListLine->x = List->y1;
++ListLine;
ListLine->belong = count;
ListLine->kind = 1;
ListLine->x = List->y2;
++count;
++ListLine;
++List;
}
ListLine = savedListLine;
List = savedList;
}
int cmp(Line a, Line b) {
return (a.x < b.x || (a.x == b.x && a.kind < b.kind));
}
void sortListLine() { sort(ListLine, ListLine + 2 * k, cmp); }
int cutStrip(Line a, int up, int down) {
return (!(List[a.belong].x2 < up || List[a.belong].x1 > down));
}
int belongToStrip(Line a, int up, int down) {
return ((List[a.belong].x1 >= up) && (List[a.belong].x2 <= down));
}
long long pre(int j) {
if (j == 0)
return ((long long)(ListSegment[j].left + 1));
else
return ((long long)(ListSegment[j].left - ListSegment[j - 1].right));
}
long long next(int i) {
if (i == nListSegment - 1)
return ((long long)(n - 1 - ListSegment[i].right + 1));
else
return ((long long)(ListSegment[i + 1].left - ListSegment[i].right));
}
void Solve(int up, int down) {
int nTempObject;
for (int i = 0; i <= nListSegment - 1; i++) {
nTempObject = 0;
for (int j = i; j >= max(0, i - 2); j--) {
nTempObject += ListSegment[j].nCoveredObject;
if (nTempObject > 3) break;
res += pre(j) * next(i);
}
};
}
void solve(int up, int down) {
int nCurrentObject = 0;
nListSegment = 0;
ListSegment[nListSegment].nCoveredObject = 0;
for (int i = 0; i <= 2 * k - 1; i++)
if (cutStrip(ListLine[i], up, down)) {
if (ListLine[i].kind == 0) {
if (nCurrentObject == 0) {
ListSegment[nListSegment].left = ListLine[i].x;
}
++nCurrentObject;
if (belongToStrip(ListLine[i], up, down))
ListSegment[nListSegment].nCoveredObject++;
else
ListSegment[nListSegment].nCoveredObject += 10000000;
} else {
--nCurrentObject;
if (nCurrentObject == 0) {
ListSegment[nListSegment].right = ListLine[i].x;
nListSegment++;
ListSegment[nListSegment].nCoveredObject = 0;
}
}
}
Solve(up, down);
}
int main() {
getInput();
buildList();
sortListLine();
res = 0;
ListSegment = (Segment *)malloc(sizeof(Segment) * 100);
savedListSegment = ListSegment;
for (int i = 0; i <= m - 1; i++)
for (int j = i; j <= m - 1; j++) {
solve(i, j);
}
printf("%I64d", res);
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Merge sort is a well-known sorting algorithm. The main function that sorts the elements of array a with indices from [l, r) can be implemented as follows:
1. If the segment [l, r) is already sorted in non-descending order (that is, for any i such that l ≤ i < r - 1 a[i] ≤ a[i + 1]), then end the function call;
2. Let <image>;
3. Call mergesort(a, l, mid);
4. Call mergesort(a, mid, r);
5. Merge segments [l, mid) and [mid, r), making the segment [l, r) sorted in non-descending order. The merge algorithm doesn't call any other functions.
The array in this problem is 0-indexed, so to sort the whole array, you need to call mergesort(a, 0, n).
The number of calls of function mergesort is very important, so Ivan has decided to calculate it while sorting the array. For example, if a = {1, 2, 3, 4}, then there will be 1 call of mergesort — mergesort(0, 4), which will check that the array is sorted and then end. If a = {2, 1, 3}, then the number of calls is 3: first of all, you call mergesort(0, 3), which then sets mid = 1 and calls mergesort(0, 1) and mergesort(1, 3), which do not perform any recursive calls because segments (0, 1) and (1, 3) are sorted.
Ivan has implemented the program that counts the number of mergesort calls, but now he needs to test it. To do this, he needs to find an array a such that a is a permutation of size n (that is, the number of elements in a is n, and every integer number from [1, n] can be found in this array), and the number of mergesort calls when sorting the array is exactly k.
Help Ivan to find an array he wants!
Input
The first line contains two numbers n and k (1 ≤ n ≤ 100000, 1 ≤ k ≤ 200000) — the size of a desired permutation and the number of mergesort calls required to sort it.
Output
If a permutation of size n such that there will be exactly k calls of mergesort while sorting it doesn't exist, output - 1. Otherwise output n integer numbers a[0], a[1], ..., a[n - 1] — the elements of a permutation that would meet the required conditions. If there are multiple answers, print any of them.
Examples
Input
3 3
Output
2 1 3
Input
4 1
Output
1 2 3 4
Input
5 6
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
constexpr int sz = 100005;
int n, k;
void solve(const int& l, const int& r, vector<int>& v, int& k) {
if (k == 0) return;
if (r > l + 1) {
swap(v[(l + r) / 2 - 1], v[(l + r) / 2]);
k -= 2;
solve(l, (l + r) / 2, v, k);
solve((l + r) / 2, r, v, k);
}
}
int main() {
cin >> n >> k;
vector<int> v(n);
if (!(k & 1)) cout << -1, exit(0);
for (int i = 0; i < n; ++i) {
v[i] = i + 1;
}
k--;
solve(0, n, v, k);
if (k == 0)
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
else
cout << -1;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust.
The pizza is a circle of radius r and center at the origin. Pizza consists of the main part — circle of radius r - d with center at the origin, and crust around the main part of the width d. Pieces of sausage are also circles. The radius of the i -th piece of the sausage is ri, and the center is given as a pair (xi, yi).
Gleb asks you to help determine the number of pieces of sausage caught on the crust. A piece of sausage got on the crust, if it completely lies on the crust.
Input
First string contains two integer numbers r and d (0 ≤ d < r ≤ 500) — the radius of pizza and the width of crust.
Next line contains one integer number n — the number of pieces of sausage (1 ≤ n ≤ 105).
Each of next n lines contains three integer numbers xi, yi and ri ( - 500 ≤ xi, yi ≤ 500, 0 ≤ ri ≤ 500), where xi and yi are coordinates of the center of i-th peace of sausage, ri — radius of i-th peace of sausage.
Output
Output the number of pieces of sausage that lay on the crust.
Examples
Input
8 4
7
7 8 1
-7 3 2
0 2 1
0 -2 2
-3 -3 1
0 6 2
5 3 1
Output
2
Input
10 8
4
0 0 9
0 0 10
1 0 1
1 0 2
Output
0
Note
Below is a picture explaining the first example. Circles of green color denote pieces of sausage lying on the crust.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
std::vector<long long> v;
long long x = 0, y = 0;
int main() {
float r, d;
long long ans = 0;
cin >> r >> d;
long long n;
cin >> n;
while (n--) {
float x, y, k;
cin >> x >> y >> k;
if (k * 2 <= d) {
float l = sqrt((x * x) + (y * y));
if (l <= r && l >= (r - d)) {
if (l + k <= r && l - k >= r - d) {
ans++;
}
}
}
}
cout << ans << "\n";
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Count the pairs of length-N sequences consisting of integers between 1 and M (inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy all of the following conditions:
* A_i \neq B_i, for every i such that 1\leq i\leq N.
* A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N.
Since the count can be enormous, print it modulo (10^9+7).
Constraints
* 1\leq N \leq M \leq 5\times10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
Output
Print the count modulo (10^9+7).
Examples
Input
2 2
Output
2
Input
2 3
Output
18
Input
141421 356237
Output
881613484
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int mod = 1000000007;
typedef long long ll;
ll F[500005];
ll I[500005];
ll exp(ll a, ll x){
if (x == 0) return 1ll;
ll p = exp(a,x/2);
p = (p*p)%mod;
if (x&1) p = (p*a)%mod;
return p;
}
ll P(int n, int k){
return (F[n]*I[n-k])%mod;
}
ll C(int n, int k){
return (((F[n]*I[k])%mod)*I[n-k])%mod;
}
ll ans = 0;
int n,m;
int main(){
scanf("%d%d",&n,&m);
F[0] = I[0] = 1;
for (int i = 1; i <= 500000; i++){
F[i] = (F[i-1]*i)%mod;
I[i] = exp(F[i],mod-2);
}
for (int i = 0; i <= n; i++){
ll EX = (P(n,i)*C(m,i))%mod;
ll TR = P(m-i,n-i);
TR = (TR*TR)%mod;
//printf("%lld %lld\n",EX,TR);
if (i & 1) ans -= (EX*TR)%mod;
else ans += (EX*TR)%mod;
ans %= mod;
}
ans = (ans+mod)%mod;
printf("%lld",ans);
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
There are N people, conveniently numbered 1 through N. We want to divide them into some number of groups, under the following two conditions:
* Every group contains between A and B people, inclusive.
* Let F_i be the number of the groups containing exactly i people. Then, for all i, either F_i=0 or C≤F_i≤D holds.
Find the number of these ways to divide the people into groups. Here, two ways to divide them into groups is considered different if and only if there exists two people such that they belong to the same group in exactly one of the two ways. Since the number of these ways can be extremely large, print the count modulo 10^9+7.
Constraints
* 1≤N≤10^3
* 1≤A≤B≤N
* 1≤C≤D≤N
Input
The input is given from Standard Input in the following format:
N A B C D
Output
Print the number of ways to divide the people into groups under the conditions, modulo 10^9+7.
Examples
Input
3 1 3 1 2
Output
4
Input
7 2 3 1 3
Output
105
Input
1000 1 1000 1 1000
Output
465231251
Input
10 3 4 2 5
Output
0
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
const int N(1111);
int dp[N], fac[N], inv[N], invFac[N][N];
int modulo(1e9 + 7);
int main() {
fac[0] = 1;
invFac[0][1] = 1;
for(int i(1); i <= 1000; i++) {
fac[i] = (long long)i * fac[i - 1] % modulo;
inv[i] = i == 1 ? 1 : inv[i - modulo % i] * (long long)((modulo + i - 1) / i) % modulo;
invFac[i][1] = (long long)invFac[i - 1][1] * inv[i] % modulo;
//cout << i << endl;
for(int j(2); j <= 1000; j++) {
invFac[i][j] = (long long)invFac[i][j - 1] * invFac[i][1] % modulo;
}
}
// cout << fac[2] << ' ' << invFac[2][1] << endl;
int n, a, b, c, d;
scanf("%d%d%d%d%d", &n, &a, &b, &c, &d);
dp[n] = 1;
for(int i(a); i <= b; i++) {
for(int j(0); j <= n; j++) {
for(int k(max(1, c)); k <= min(d, j / i); k++) {
dp[j - k * i] = (dp[j - k * i] + (long long)dp[j] * fac[j] % modulo * invFac[i][k] % modulo * invFac[j - k * i][1] % modulo * invFac[k][1]) % modulo;
}
}
//cout << dp[0] << ' ' << dp[3] << endl;
}
cout << dp[0] << endl;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Training is indispensable for achieving good results at ICPC. Rabbit wants to win at ICPC, so he decided to practice today as well.
Today's training is to develop physical strength and judgment by running on a straight road. The rabbit is now standing at the starting line and looking out over a long, long road.
There are some carrots along the way, and rabbits can accelerate by eating carrots. Rabbits run at U meters per second when not accelerating, but by eating carrots, the speed is V meters per second from the last carrot eaten to T seconds later. Rabbits can also carry up to K carrots without eating them. Even if you have a carrot, the running speed does not change.
Assuming that it does not take long to bring and eat carrots, I would like to find the shortest time required to reach the goal.
Input
N K T U V L
D1
...
DN
N is the number of carrots, L is the distance from the start to the goal (meters), and Di (1 ≤ i ≤ N) is the distance from the start where the i-th carrot is located (meters).
1 ≤ N ≤ 200, 1 ≤ K ≤ N, 1 ≤ T ≤ 10,000, 1 ≤ U <V ≤ 10,000, 2 ≤ L ≤ 10,000, 0 <D1 <D2 <... <DN <L. All input values are integers.
Output
Output the shortest required time (seconds) on one line. Absolute errors of 10-6 or less are allowed.
Examples
Input
1 1 1 2 3 100
50
Output
49.500000000
Input
3 1 1 2 3 100
49
50
51
Output
48.666666667
### Response
```cpp
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main(){
int n,k,t,u,v,l,tmp;
bool car[10002];
cin >> n >> k >> t >> u >> v >> l;
memset(car,false,sizeof(car));
for(int i=0;i<n;i++){
cin >> tmp;
car[tmp] = true;
}
int stock = 0,fast = 0, slow = 0, rem = 0;
for(int i=0;i<l;i++){
if(rem == 0 && stock > 0){
rem = v*t;
stock--;
}
if(car[i]){
if(rem == 0){
rem = v*t;
}else{
if(stock == k){
rem = v*t;
}else{
stock++;
}
}
}
if(rem > 0){
fast++;
rem--;
}else{
slow++;
}
}
printf("%.10f\n", (double)fast/v + (double)slow/u);
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
We all know the problem about the number of ways one can tile a 2 × n field by 1 × 2 dominoes. You probably remember that it goes down to Fibonacci numbers. We will talk about some other problem below, there you also are going to deal with tiling a rectangular field with dominoes.
You are given a 4 × n rectangular field, that is the field that contains four lines and n columns. You have to find for it any tiling by 1 × 2 dominoes such that each of the n - 1 potential vertical cuts along the grid lines intersects at least one domino, splitting it in two. No two dominoes in the sought tiling should overlap, each square of the field should be covered by exactly one domino. It is allowed to rotate the dominoes, that is, you can use 2 × 1 as well as 1 × 2 dominoes.
Write a program that finds an arbitrary sought tiling.
Input
The input contains one positive integer n (1 ≤ n ≤ 100) — the number of the field's columns.
Output
If there's no solution, print "-1" (without the quotes). Otherwise, print four lines containing n characters each — that's the description of tiling, where each vertical cut intersects at least one domino. You should print the tiling, having painted the field in no more than 26 colors. Each domino should be painted a color. Different dominoes can be painted the same color, but dominoes of the same color should not be side-neighbouring. To indicate colors you should use lowercase Latin letters. Print any of the acceptable ways of tiling.
Examples
Input
4
Output
yyzz
bccd
bxxd
yyaa
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n;
int main() {
scanf("%d", &n);
if (n % 2 == 0) {
for (int i = 1; i <= n; ++i) {
if (i % 4 == 1 || i % 4 == 2)
printf("a");
else
printf("b");
}
puts("");
printf("e");
for (int i = 1; i <= n - 2; ++i) {
if (i % 4 == 1 || i % 4 == 2)
printf("c");
else
printf("d");
}
printf("f");
puts("");
printf("e");
for (int i = 1; i <= n - 2; ++i) {
if (i % 4 == 1 || i % 4 == 2)
printf("d");
else
printf("c");
}
printf("f");
puts("");
for (int i = 1; i <= n; ++i) {
if (i % 4 == 1 || i % 4 == 2)
printf("a");
else
printf("b");
}
} else {
for (int i = 1; i <= n - 1; ++i) {
if (i % 4 == 1 || i % 4 == 2)
printf("a");
else
printf("b");
}
printf("e");
puts("");
for (int i = 1; i <= n - 1; ++i) {
if (i % 4 == 1 || i % 4 == 2)
printf("b");
else
printf("a");
}
printf("e");
puts("");
printf("f");
for (int i = 1; i <= n - 1; ++i) {
if (i % 4 == 1 || i % 4 == 2)
printf("c");
else
printf("d");
}
puts("");
printf("f");
for (int i = 1; i <= n - 1; ++i) {
if (i % 4 == 1 || i % 4 == 2)
printf("d");
else
printf("c");
}
}
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
You are given n rectangles. The corners of rectangles have integer coordinates and their edges are parallel to the Ox and Oy axes. The rectangles may touch each other, but they do not overlap (that is, there are no points that belong to the interior of more than one rectangle).
Your task is to determine if the rectangles form a square. In other words, determine if the set of points inside or on the border of at least one rectangle is precisely equal to the set of points inside or on the border of some square.
Input
The first line contains a single integer n (1 ≤ n ≤ 5). Next n lines contain four integers each, describing a single rectangle: x1, y1, x2, y2 (0 ≤ x1 < x2 ≤ 31400, 0 ≤ y1 < y2 ≤ 31400) — x1 and x2 are x-coordinates of the left and right edges of the rectangle, and y1 and y2 are y-coordinates of the bottom and top edges of the rectangle.
No two rectangles overlap (that is, there are no points that belong to the interior of more than one rectangle).
Output
In a single line print "YES", if the given rectangles form a square, or "NO" otherwise.
Examples
Input
5
0 0 2 3
0 3 3 5
2 0 5 2
3 2 5 5
2 2 3 3
Output
YES
Input
4
0 0 2 3
0 3 3 5
2 0 5 2
3 2 5 5
Output
NO
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename T, typename U>
inline void makemin(T &res, const U &x) {
if (x < res) {
res = x;
}
}
template <typename T, typename U>
inline void makemax(T &res, const U &x) {
if (x > res) {
res = x;
}
}
struct Point {
int x, y;
};
struct Rect {
int x1, y1, x2, y2;
};
bool inside(const Rect &r, const Point &p) {
return p.x >= r.x1 && p.x <= r.x2 && p.y >= r.y1 && p.y <= r.y2;
}
bool solve() {
int n;
cin >> n;
vector<Rect> rect(n);
vector<Point> qpts;
for (int i = 0; i < n; ++i) {
Rect &r = rect[i];
cin >> r.x1 >> r.y1 >> r.x2 >> r.y2;
r.x1 *= 2;
r.y1 *= 2;
r.x2 *= 2;
r.y2 *= 2;
for (int dx = -1; dx <= 1; ++dx) {
for (int dy = -1; dy <= 1; ++dy) {
qpts.push_back((Point){r.x1 + dx, r.y1 + dy});
qpts.push_back((Point){r.x2 + dx, r.y2 + dy});
}
}
}
Rect bbox = rect[0];
for (int i = 1; i < n; ++i) {
const Rect &r = rect[i];
makemin(bbox.x1, r.x1);
makemax(bbox.x2, r.x2);
makemin(bbox.y1, r.y1);
makemax(bbox.y2, r.y2);
}
if (bbox.x2 - bbox.x1 != bbox.y2 - bbox.y1) {
return false;
}
for (int i = 0; i < (int)qpts.size(); ++i) {
const Point &q = qpts[i];
if (inside(bbox, q)) {
bool ok = false;
for (int j = 0; j < n; ++j) {
ok |= inside(rect[j], q);
}
if (!ok) {
return false;
}
}
}
return true;
}
int main() {
cin.sync_with_stdio(0);
cout << (solve() ? "YES" : "NO") << '\n';
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1.
Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp × i. If the answer is positive, find one way to rearrange the characters.
Input
The only line contains the initial string s, consisting of small Latin letters (1 ≤ |s| ≤ 1000).
Output
If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO".
Examples
Input
abc
Output
YES
abc
Input
abcd
Output
NO
Input
xxxyxxx
Output
YES
xxxxxxy
Note
In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba".
In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4).
In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
const long long int N = 1005;
bool prime[N + 1];
long long int kk;
void sieve() {
memset(prime, true, sizeof(prime));
for (long long int p = 2; p * p <= N; p++) {
if (prime[p] == true) {
for (long long int i = p * p; i <= N; i += p) prime[i] = false;
}
}
}
void solve() {
string s;
cin >> s;
map<char, long long int> mp;
for (auto i : s) mp[i]++;
vector<char> ans(s.length(), '/');
for (long long int i = 2; i * 2 <= s.length(); i++) {
prime[i] = false;
}
for (long long int i = 1; i <= s.length(); i++) {
if (prime[i] == false) kk++;
}
long long int k = -1;
char ch;
for (auto i : mp) {
if (i.second > k) {
k = i.second;
ch = i.first;
}
}
if (k < kk) {
cout << "NO" << '\n';
return;
}
for (long long int i = 1; i <= s.length(); i++) {
if (!prime[i] && mp[ch] > 0) {
ans[i - 1] = ch;
mp[ch]--;
}
}
cout << "YES" << '\n';
k = 0;
for (auto i : mp) {
while (i.second > 0 && k < s.length()) {
if (ans[k] == '/') {
ans[k] = i.first;
i.second--;
}
k++;
}
}
for (auto i : ans) cout << i;
cout << '\n';
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long int t = 1;
sieve();
while (t--) {
solve();
}
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
As you very well know, the whole Universe traditionally uses three-dimensional Cartesian system of coordinates. In this system each point corresponds to three real coordinates (x, y, z). In this coordinate system, the distance between the center of the Universe and the point is calculated by the following formula: <image>. Mushroom scientists that work for the Great Mushroom King think that the Universe isn't exactly right and the distance from the center of the Universe to a point equals xa·yb·zc.
To test the metric of mushroom scientists, the usual scientists offered them a task: find such x, y, z (0 ≤ x, y, z; x + y + z ≤ S), that the distance between the center of the Universe and the point (x, y, z) is maximum possible in the metric of mushroom scientists. The mushroom scientists aren't good at maths, so they commissioned you to do the task.
Note that in this problem, it is considered that 00 = 1.
Input
The first line contains a single integer S (1 ≤ S ≤ 103) — the maximum sum of coordinates of the sought point.
The second line contains three space-separated integers a, b, c (0 ≤ a, b, c ≤ 103) — the numbers that describe the metric of mushroom scientists.
Output
Print three real numbers — the coordinates of the point that reaches maximum value in the metrics of mushroom scientists. If there are multiple answers, print any of them that meets the limitations.
A natural logarithm of distance from the center of the Universe to the given point in the metric of mushroom scientists shouldn't differ from the natural logarithm of the maximum distance by more than 10 - 6. We think that ln(0) = - ∞.
Examples
Input
3
1 1 1
Output
1.0 1.0 1.0
Input
3
2 0 0
Output
3.0 0.0 0.0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline void solve() {
long double a, b, c, s;
cin >> s >> a >> b >> c;
long double x, y, z;
if (b == 0 && c == 0 && a == 0) {
x = s;
} else {
x = (a * s * 1.0) / (1.0 * (a + b + c));
}
if (c == 0 && a == 0 && b == 0) {
y = 0;
} else {
y = (b * s * 1.0) / (1.0 * (a + b + c));
}
if (b == 0 && c == 0 && a == 0) {
z = 0;
} else {
z = (c * s * 1.0) / (1.0 * (c + b + a));
}
std::cout << std::fixed;
std::cout << std::setprecision(10) << x << ' ' << y << ' ' << z << '\n';
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int tests = 1;
while (tests--) {
solve();
}
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Given an integer N not less than 3, find the sum of the interior angles of a regular polygon with N sides.
Print the answer in degrees, but do not print units.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print an integer representing the sum of the interior angles of a regular polygon with N sides.
Examples
Input
3
Output
180
Input
100
Output
17640
### Response
```cpp
#include <iostream>
using namespace std;
int main() {
int N;
cin >> N;
cout << 180 * (N - 2);
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long a[1005][1005];
long long visited[1005][1005];
long long n, m;
long long dirx[] = {1, 0, -1, 0};
long long diry[] = {0, -1, 0, 1};
long long issafe(long long i, long long j) {
if (i >= 0 && i < n && j >= 0 && j < m && a[i][j] && !visited[i][j]) return 1;
return 0;
}
void dfs(long long i, long long j) {
visited[i][j] = 1;
for (long long k = 0; k < 4; k++) {
long long i1 = i + dirx[k], j1 = j + diry[k];
if (issafe(i1, j1)) dfs(i1, j1);
}
return;
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long TESTS = 1;
while (TESTS--) {
cin >> n >> m;
for (long long i = 0; i < n; i++) {
for (long long j = 0; j < m; j++) {
char c;
cin >> c;
if (c == '#')
a[i][j] = 1;
else
a[i][j] = 0;
}
}
long long flag = 0;
long long row[n], col[m];
memset(row, 0, sizeof(row));
memset(col, 0, sizeof(col));
for (long long i = 0; i < n; i++) {
long long bb = 0;
long long j = 0;
while (j < m) {
long long j1 = j;
while (j1 < m && a[i][j1]) j1++;
if (j != j1) bb++;
j = j1 + 1;
}
if (bb >= 2) {
flag = 1;
}
if (bb == 0) row[i] = 1;
}
for (long long j = 0; j < m; j++) {
long long bb = 0;
long long i = 0;
while (i < n) {
long long i1 = i;
while (i1 < n && a[i1][j]) i1++;
if (i != i1) bb++;
i = i1 + 1;
}
if (bb >= 2) {
flag = 1;
}
if (bb == 0) col[j] = 1;
}
long long f1 = 0, f2 = 0;
for (long long i = 0; i < n; i++)
if (row[i]) f1 = 1;
for (long long j = 0; j < m; j++)
if (col[j]) f2 = 1;
if ((f1 && !f2) || (!f1 && f2)) flag = 1;
if (flag) {
cout << -1;
return 0;
}
memset(visited, 0, sizeof(visited));
long long val = 0;
for (long long i = 0; i < n; i++) {
for (long long j = 0; j < m; j++) {
if (issafe(i, j)) {
dfs(i, j);
val++;
}
}
}
cout << val;
}
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Hideo Kojima has just quit his job at Konami. Now he is going to find a new place to work. Despite being such a well-known person, he still needs a CV to apply for a job.
During all his career Hideo has produced n games. Some of them were successful, some were not. Hideo wants to remove several of them (possibly zero) from his CV to make a better impression on employers. As a result there should be no unsuccessful game which comes right after successful one in his CV.
More formally, you are given an array s1, s2, ..., sn of zeros and ones. Zero corresponds to an unsuccessful game, one — to a successful one. Games are given in order they were produced, and Hideo can't swap these values. He should remove some elements from this array in such a way that no zero comes right after one.
Besides that, Hideo still wants to mention as much games in his CV as possible. Help this genius of a man determine the maximum number of games he can leave in his CV.
Input
The first line contains one integer number n (1 ≤ n ≤ 100).
The second line contains n space-separated integer numbers s1, s2, ..., sn (0 ≤ si ≤ 1). 0 corresponds to an unsuccessful game, 1 — to a successful one.
Output
Print one integer — the maximum number of games Hideo can leave in his CV so that no unsuccessful game comes after a successful one.
Examples
Input
4
1 1 0 1
Output
3
Input
6
0 1 0 0 1 0
Output
4
Input
1
0
Output
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int a[N], one[N], zero[N];
int main() {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
one[i] = one[i - 1];
zero[i] = zero[i - 1];
if (a[i])
one[i]++;
else
zero[i]++;
}
int ans = n - one[n];
for (int i = 1; i <= n; i++) {
int Bef = one[i - 1];
int Las = zero[n] - zero[i - 1];
ans = max(ans, n - Bef - Las);
}
cout << ans;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
We all know that GukiZ often plays with arrays.
Now he is thinking about this problem: how many arrays a, of length n, with non-negative elements strictly less then 2l meet the following condition: <image>? Here operation <image> means bitwise AND (in Pascal it is equivalent to and, in C/C++/Java/Python it is equivalent to &), operation <image> means bitwise OR (in Pascal it is equivalent to <image>, in C/C++/Java/Python it is equivalent to |).
Because the answer can be quite large, calculate it modulo m. This time GukiZ hasn't come up with solution, and needs you to help him!
Input
First and the only line of input contains four integers n, k, l, m (2 ≤ n ≤ 1018, 0 ≤ k ≤ 1018, 0 ≤ l ≤ 64, 1 ≤ m ≤ 109 + 7).
Output
In the single line print the number of arrays satisfying the condition above modulo m.
Examples
Input
2 1 2 10
Output
3
Input
2 1 1 3
Output
1
Input
3 3 2 10
Output
9
Note
In the first sample, satisfying arrays are {1, 1}, {3, 1}, {1, 3}.
In the second sample, only satisfying array is {1, 1}.
In the third sample, satisfying arrays are {0, 3, 3}, {1, 3, 2}, {1, 3, 3}, {2, 3, 1}, {2, 3, 3}, {3, 3, 0}, {3, 3, 1}, {3, 3, 2}, {3, 3, 3}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
unsigned long long n, K, L, Mo;
struct Mat {
int nl, ml;
unsigned long long num[10][10];
Mat() {
nl = 0;
ml = 0;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
num[i][j] = 0;
}
}
}
void print() {
cout << "matrix " << endl;
for (int i = 1; i <= nl; ++i) {
for (int j = 1; j <= ml; ++j) {
cout << num[i][j] << ' ';
}
cout << endl;
}
}
} A, B;
Mat operator*(const Mat &a, const Mat &b) {
Mat c;
c.nl = a.nl;
c.ml = b.ml;
memset(c.num, 0, sizeof(c.num));
for (int i = 1; i <= a.nl; ++i) {
for (int j = 1; j <= b.nl; ++j) {
for (int k = 1; k <= b.ml; ++k) {
c.num[i][k] =
((c.num[i][k] + a.num[i][j] * b.num[j][k]) % Mo + Mo) % Mo;
}
}
}
return c;
}
Mat Pow(Mat a, unsigned long long b) {
Mat c;
c.nl = 2;
c.ml = 2;
for (int i = 1; i <= 2; ++i) c.num[i][i] = 1LL;
while (b) {
if (b & 1) c = c * a;
a = a * a;
b >>= 1;
}
return c;
}
unsigned long long Pow2(unsigned long long a, unsigned long long b) {
unsigned long long res = 1LL;
while (b) {
if (b & 1) res = res * a, res %= Mo;
a = a * a;
a %= Mo;
b >>= 1;
}
return res;
}
int main() {
cin >> n >> K >> L >> Mo;
if (L < 64 && K >= (1ULL << L)) {
printf("0");
return 0;
}
A.nl = 1;
A.ml = 2;
A.num[1][1] = A.num[1][2] = 1;
B.nl = B.ml = 2;
B.num[1][2] = B.num[2][1] = B.num[2][2] = 1;
B.num[1][1] = 0;
unsigned long long a = (A * Pow(B, n)).num[1][2];
unsigned long long b =
((long long)((long long)Pow2(2LL, n) - (long long)a) % (long long)Mo +
(long long)Mo) %
(long long)Mo;
a = (a % Mo + Mo) % Mo;
b = (b % Mo + Mo) % Mo;
unsigned long long ans = 1LL;
for (unsigned long long i = 0; i < L; ++i) {
if (K & (1LL << i)) {
ans = ans * b;
} else {
ans = ans * a;
}
ans = (ans % Mo + Mo) % Mo;
}
ans = (ans % Mo + Mo) % Mo;
cout << ans;
fclose(stdin);
fclose(stdout);
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
As it has been found out recently, all the Berland's current economical state can be described using a simple table n × m in size. n — the number of days in each Berland month, m — the number of months. Thus, a table cell corresponds to a day and a month of the Berland's year. Each cell will contain either 1, or -1, which means the state's gains in a particular month, on a particular day. 1 corresponds to profits, -1 corresponds to losses. It turned out important for successful development to analyze the data on the state of the economy of the previous year, however when the treasurers referred to the archives to retrieve the data, it turned out that the table had been substantially damaged. In some table cells the number values had faded and were impossible to be deciphered. It is known that the number of cells in which the data had been preserved is strictly less than max(n, m). However, there is additional information — the product of the numbers in each line and column equaled -1. Your task is to find out how many different tables may conform to the preserved data. As the answer to the task can be quite large, you have to find it modulo p.
Input
The first line contains integers n and m (1 ≤ n, m ≤ 1000). The second line contains the integer k (0 ≤ k < max(n, m)) — the number of cells in which the data had been preserved. The next k lines contain the data on the state of the table in the preserved cells. Each line is of the form "a b c", where a (1 ≤ a ≤ n) — the number of the table row, b (1 ≤ b ≤ m) — the number of the column, c — the value containing in the cell (1 or -1). They are numbered starting from 1. It is guaranteed that no two lines with same a and b values exist. The last line contains an integer p (2 ≤ p ≤ 109 + 7).
Output
Print the number of different tables that could conform to the preserved data modulo p.
Examples
Input
2 2
0
100
Output
2
Input
2 2
1
1 1 -1
100
Output
1
### Response
```cpp
#include <bits/stdc++.h>
const int MaxN = 1010;
int mod_v, pw[MaxN], cnt[MaxN], val[MaxN];
int main() {
int n, m, t, flag = 0;
std::scanf("%d %d %d", &n, &m, &t);
if (n < m) std::swap(n, m), flag = 1;
for (int i = 0; i != t; ++i) {
int x, y, v;
std::scanf("%d %d %d", &x, &y, &v);
if (flag) std::swap(x, y);
++cnt[x];
if (!val[x])
val[x] = v;
else
val[x] *= v;
}
std::scanf("%d", &mod_v);
for (int i = 1; i <= n; ++i) {
if (!cnt[i]) {
std::swap(cnt[i], cnt[n]);
std::swap(val[i], val[n]);
break;
}
}
pw[0] = 1;
for (int i = 1; i <= m; ++i) pw[i] = (pw[i - 1] << 1) % mod_v;
int ans = 1;
for (int i = 1; i != n; ++i) {
if (cnt[i] == m && val[i] == 1)
ans = 0;
else if (m != cnt[i])
ans = (long long)ans * pw[m - cnt[i] - 1] % mod_v;
}
if ((n ^ m) & 1)
std::puts("0");
else
std::printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
We have N camels numbered 1,2,\ldots,N. Snuke has decided to make them line up in a row.
The happiness of Camel i will be L_i if it is among the K_i frontmost camels, and R_i otherwise.
Snuke wants to maximize the total happiness of the camels. Find the maximum possible total happiness of the camel.
Solve this problem for each of the T test cases given.
Constraints
* All values in input are integers.
* 1 \leq T \leq 10^5
* 1 \leq N \leq 2 \times 10^{5}
* 1 \leq K_i \leq N
* 1 \leq L_i, R_i \leq 10^9
* The sum of values of N in each input file is at most 2 \times 10^5.
Input
Input is given from Standard Input in the following format:
T
\mathrm{case}_1
\vdots
\mathrm{case}_T
Each case is given in the following format:
N
K_1 L_1 R_1
\vdots
K_N L_N R_N
Output
Print T lines. The i-th line should contain the answer to the i-th test case.
Example
Input
3
2
1 5 10
2 15 5
3
2 93 78
1 71 59
3 57 96
19
19 23 16
5 90 13
12 85 70
19 67 78
12 16 60
18 48 28
5 4 24
12 97 97
4 57 87
19 91 74
18 100 76
7 86 46
9 100 57
3 76 73
6 84 93
1 6 84
11 75 94
19 15 3
12 11 34
Output
25
221
1354
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define modulo 1000000007
#define mod(mod_x) ((((long long)mod_x+modulo))%modulo)
#define Inf 1000000000
int main(){
int T;
cin>>T;
for(int _=0;_<T;_++){
int N;
cin>>N;
vector<long long> K(N),L(N),R(N);
for(int i=0;i<N;i++)cin>>K[i]>>L[i]>>R[i];
vector<pair<long long,long long>> l,r;
long long ans = 0LL;
for(int i=0;i<N;i++){
if(L[i]>R[i]){
ans += R[i];
l.emplace_back(K[i]-1,L[i]-R[i]);
}
else{
ans += L[i];
r.emplace_back(N-K[i]-1,R[i]-L[i]);
}
}
sort(l.begin(),l.end());
sort(r.begin(),r.end());
priority_queue<long long,vector<long long>,greater<long long>> Q;
for(int i=0;i<l.size();i++){
if(Q.size()<=l[i].first){
ans += l[i].second;
Q.push(l[i].second);
}
else{
if(Q.size()==0)continue;
if(Q.top()<l[i].second){
ans -= Q.top();
Q.pop();
ans += l[i].second;
Q.push(l[i].second);
}
}
}
while(Q.size()!=0)Q.pop();
for(int i=0;i<r.size();i++){
if((int)Q.size()<=r[i].first){
ans += r[i].second;
Q.push(r[i].second);
}
else{
if(Q.size()==0)continue;
if(Q.top()<r[i].second){
ans -= Q.top();
Q.pop();
ans += r[i].second;
Q.push(r[i].second);
}
}
}
cout<<ans<<endl;
}
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Let T be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree T:
1. Set pointer to the root of a tree.
2. Return success if the value in the current vertex is equal to the number you are looking for
3. Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for
4. Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for
5. Return fail if you try to go to the vertex that doesn't exist
Here is the pseudo-code of the described algorithm:
bool find(TreeNode t, int x) {
if (t == null)
return false;
if (t.value == x)
return true;
if (x < t.value)
return find(t.left, x);
else
return find(t.right, x);
}
find(root, x);
The described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree.
Since the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree.
If the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately.
Input
First line contains integer number n (1 ≤ n ≤ 105) — number of vertices in the tree.
Each of the next n lines contains 3 numbers v, l, r (0 ≤ v ≤ 109) — value on current vertex, index of the left child of the vertex and index of the right child of the vertex, respectively. If some child doesn't exist then number - 1 is set instead. Note that different vertices of the tree may contain the same values.
Output
Print number of times when search algorithm will fail.
Examples
Input
3
15 -1 -1
10 1 3
5 -1 -1
Output
2
Input
8
6 2 3
3 4 5
12 6 7
1 -1 8
4 -1 -1
5 -1 -1
14 -1 -1
2 -1 -1
Output
1
Note
In the example the root of the tree in vertex 2. Search of numbers 5 and 15 will return fail because on the first step algorithm will choose the subtree which doesn't contain numbers you are looking for.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const long long maxn = 3e6;
const long long mod = 1e9 + 7;
const long double PI = acos((long double)-1);
long long pw(long long a, long long b, long long md = mod) {
long long res = 1;
while (b) {
if (b & 1) {
res = (a * res) % md;
}
a = (a * a) % md;
b >>= 1;
}
return (res);
}
int n;
int l[maxn], r[maxn];
int val[maxn];
int root[maxn];
int ans;
map<int, int> mp;
void dfs(int v, int mn = 0, int mx = 1e9) {
bool bad = (val[v] > mx or val[v] < mn);
if (!bad) ans -= mp[val[v]], mp[val[v]] = 0;
if (l[v] > 0) {
dfs(l[v], mn, min(mx, val[v]));
}
if (r[v] > 0) {
dfs(r[v], max(mn, val[v]), mx);
}
}
int32_t main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> val[i] >> l[i] >> r[i];
if (l[i] > 0) root[l[i]] = 1;
if (r[i] > 0) root[r[i]] = 1;
mp[val[i]]++;
}
ans = n;
int r = min_element(root + 1, root + n + 1) - root;
dfs(r);
return (cout << ans, 0);
;
return (0);
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
You are given a weighed undirected connected graph, consisting of n vertices and m edges.
You should answer q queries, the i-th query is to find the shortest distance between vertices u_i and v_i.
Input
The first line contains two integers n and m~(1 ≤ n, m ≤ 10^5, m - n ≤ 20) — the number of vertices and edges in the graph.
Next m lines contain the edges: the i-th edge is a triple of integers v_i, u_i, d_i~(1 ≤ u_i, v_i ≤ n, 1 ≤ d_i ≤ 10^9, u_i ≠ v_i). This triple means that there is an edge between vertices u_i and v_i of weight d_i. It is guaranteed that graph contains no self-loops and multiple edges.
The next line contains a single integer q~(1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers u_i and v_i~(1 ≤ u_i, v_i ≤ n) — descriptions of the queries.
Pay attention to the restriction m - n ~ ≤ ~ 20.
Output
Print q lines.
The i-th line should contain the answer to the i-th query — the shortest distance between vertices u_i and v_i.
Examples
Input
3 3
1 2 3
2 3 1
3 1 5
3
1 2
1 3
2 3
Output
3
4
1
Input
8 13
1 2 4
2 3 6
3 4 1
4 5 12
5 6 3
6 7 8
7 8 7
1 4 1
1 8 3
2 6 9
2 7 1
4 6 3
6 8 2
8
1 5
1 7
2 3
2 8
3 7
3 4
6 8
7 8
Output
7
5
6
7
7
1
2
7
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long inf = 1e18 + 5;
const int N = 1e5 + 35;
const int DEG = 21;
long long dis[55][N];
struct Edge {
int u;
int v;
int next;
long long w;
} edge1[N * 2], edge[N * 2];
int tot1;
int head1[N];
int tot;
int head[N];
int f[N];
int fa[N][25];
int deg[N];
long long dep[N];
int n, m;
int se[50];
int scnt;
int vis[N];
vector<Edge> ve[N];
void adde1(int u, int v, long long w) {
edge1[++tot1].u = u;
edge1[tot1].v = v;
edge1[tot1].w = w;
edge1[tot1].next = head1[u];
head1[u] = tot1;
}
void add(int u, int v, long long w) {
edge[++tot].v = v;
edge[tot].w = w;
edge[tot].next = head[u];
head[u] = tot;
}
void init() {
tot = tot1 = 0;
memset(head, -1, sizeof(head));
memset(head1, -1, sizeof(head1));
}
void bfs(int rt) {
queue<int> que;
deg[rt] = 0;
dep[rt] = 0;
fa[rt][0] = rt;
que.push(rt);
while (!que.empty()) {
int tmp = que.front();
que.pop();
for (int i = 1; i < DEG; i++) {
fa[tmp][i] = fa[fa[tmp][i - 1]][i - 1];
}
for (int i = head[tmp]; i != -1; i = edge[i].next) {
int v = edge[i].v;
if (v == fa[tmp][0]) continue;
deg[v] = deg[tmp] + 1;
dep[v] = dep[tmp] + edge[i].w;
fa[v][0] = tmp;
que.push(v);
}
}
}
int LCA(int u, int v) {
if (deg[u] > deg[v]) swap(u, v);
int hu = deg[u];
int hv = deg[v];
int tu = u, tv = v;
for (int det = hv - hu, i = 0; det; det >>= 1, i++) {
if (det & 1) tv = fa[tv][i];
}
if (tu == tv) return tu;
for (int i = DEG - 1; i >= 0; i--) {
if (fa[tu][i] == fa[tv][i]) continue;
tu = fa[tu][i];
tv = fa[tv][i];
}
return fa[tu][0];
}
bool cmp(Edge a, Edge b) { return a.w < b.w; }
void dij(int id, int s) {
for (int i = 0; i <= n + 2; i++) {
vis[i] = 0;
dis[id][i] = inf;
}
dis[id][s] = 0;
priority_queue<pair<long long, int>, vector<pair<long long, int> >,
greater<pair<long long, int> > >
q;
q.push(pair<long long, int>(0, s));
while (!q.empty()) {
pair<long long, int> tmp = q.top();
q.pop();
int u = tmp.second;
if (tmp.first > dis[id][u]) continue;
vis[u] = 1;
for (int i = 0; i < ve[u].size(); i++) {
int v = ve[u][i].v;
long long w = ve[u][i].w;
if (vis[v]) continue;
if (dis[id][v] > dis[id][u] + w) {
dis[id][v] = dis[id][u] + w;
q.push(pair<long long, int>(dis[id][v], v));
}
}
}
}
int getf(int x) { return f[x] == x ? x : (f[x] = getf(f[x])); }
int merge(int x, int y) {
int t1 = getf(x);
int t2 = getf(y);
if (t1 != t2) {
f[t2] = t1;
return 1;
}
return 0;
}
int main() {
scanf("%d %d", &n, &m);
int u, v;
long long w;
init();
for (int i = 1; i <= m; i++) {
scanf("%d %d %lld", &u, &v, &w);
adde1(u, v, w);
ve[u].push_back((Edge){u, v, 0, w});
ve[v].push_back((Edge){v, u, 0, w});
}
sort(edge1 + 1, edge1 + tot1 + 1, cmp);
for (int i = 0; i <= n + 2; i++) {
f[i] = i;
}
for (int i = 1; i <= tot1; i++) {
u = edge1[i].u;
v = edge1[i].v;
if (merge(u, v)) {
add(u, v, edge1[i].w);
add(v, u, edge1[i].w);
} else {
se[++scnt] = u;
se[++scnt] = v;
}
}
bfs(1);
sort(se + 1, se + scnt + 1);
scnt = unique(se + 1, se + scnt + 1) - (se + 1);
for (int i = 1; i <= scnt; i++) {
dij(i, se[i]);
}
int q;
scanf("%d", &q);
while (q--) {
scanf("%d %d", &u, &v);
long long ans = inf;
int lca = LCA(u, v);
ans = dep[u] + dep[v] - 2 * dep[lca];
for (int i = 1; i <= scnt; i++) {
ans = min(ans, dis[i][u] + dis[i][v]);
}
printf("%lld\n", ans);
}
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
You went shopping to buy cakes and donuts with X yen (the currency of Japan).
First, you bought one cake for A yen at a cake shop. Then, you bought as many donuts as possible for B yen each, at a donut shop.
How much do you have left after shopping?
Constraints
* 1 \leq A, B \leq 1 000
* A + B \leq X \leq 10 000
* X, A and B are integers.
Input
Input is given from Standard Input in the following format:
X
A
B
Output
Print the amount you have left after shopping.
Examples
Input
1234
150
100
Output
84
Input
1000
108
108
Output
28
Input
579
123
456
Output
0
Input
7477
549
593
Output
405
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
typedef int ll;
ll a,b,c;
int main()
{
cin>>a>>b>>c;
cout<<(a-b)%c;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree.
A k-tree is an infinite rooted tree where:
* each vertex has exactly k children;
* each edge has some weight;
* if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k.
The picture below shows a part of a 3-tree.
<image>
As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?".
Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7).
Input
A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k).
Output
Print a single integer — the answer to the problem modulo 1000000007 (109 + 7).
Examples
Input
3 3 2
Output
3
Input
3 3 3
Output
1
Input
4 3 2
Output
6
Input
4 5 2
Output
7
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long dp[101][2];
int main() {
memset(dp, 0, sizeof(dp));
int n, k, d;
cin >> n >> k >> d;
dp[0][0] = 1LL;
dp[0][1] = 0LL;
for (int i = 1; i <= n; i++) {
dp[i][0] = dp[i][1] = 0LL;
for (int j = 1; j <= k; j++) {
if (i < j) break;
if (j < d) {
dp[i][0] = (dp[i][0] + dp[i - j][0]) % (long long)1000000007;
dp[i][1] = (dp[i][1] + dp[i - j][1]) % (long long)1000000007;
} else {
dp[i][1] = (dp[i][1] + dp[i - j][0]) % (long long)1000000007;
dp[i][1] = (dp[i][1] + dp[i - j][1]) % (long long)1000000007;
}
}
}
cout << dp[n][1];
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
In Japan, people make offerings called hina arare, colorful crackers, on March 3.
We have a bag that contains N hina arare. (From here, we call them arare.)
It is known that the bag either contains arare in three colors: pink, white and green, or contains arare in four colors: pink, white, green and yellow.
We have taken out the arare in the bag one by one, and the color of the i-th arare was S_i, where colors are represented as follows - pink: `P`, white: `W`, green: `G`, yellow: `Y`.
If the number of colors of the arare in the bag was three, print `Three`; if the number of colors was four, print `Four`.
Constraints
* 1 \leq N \leq 100
* S_i is `P`, `W`, `G` or `Y`.
* There always exist i, j and k such that S_i=`P`, S_j=`W` and S_k=`G`.
Input
Input is given from Standard Input in the following format:
N
S_1 S_2 ... S_N
Output
If the number of colors of the arare in the bag was three, print `Three`; if the number of colors was four, print `Four`.
Examples
Input
6
G W Y P Y W
Output
Four
Input
9
G W W G P W P G G
Output
Three
Input
8
P Y W G Y W Y Y
Output
Four
### Response
```cpp
#include<iostream>
using namespace std;
int main(){
int n;
cin >> n;
char s;
for(int i=0; i<n; i++){
cin >> s;
if(s == 'Y') {
cout << "Four";
return 0;
}
}
cout << "Three";
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Create a program of the square picking method, which is one of the classical random number generation methods. The square harvesting method was proposed by von Neumann in the mid-1940s.
In the square picking method, when the number of digits of the generated random number is n, the square of the initial value s is calculated, and the value is regarded as a 2n digit number (the number of squared digits as shown in the example below). If is not enough, make up for 0.) Let the n numbers in the center be the first random number. Then square this random number and take the n numbers in the center in the same way to get the next random number. For example, if 123 is the initial value
1232 = 00015129 → 0151
1512 = 00022801 → 0228
2282 = 00051984 → 0519
5192 = 00269361 → 2693
26932 = 07252249 → 2522
It will be like. Use this method to create a program that takes the initial value s (a positive integer less than 10000) as an input and generates and outputs 10 random numbers when n = 4.
Input
Given multiple datasets. The first line gives the number of datasets d (d ≤ 10). For each dataset, one row is given the initial value s (integer, 1 ≤ s <10000).
Output
For each dataset
Case x: (x is a dataset number starting with 1)
The first generated random number (integer)
The second generated random number (integer)
:
:
10th generated random number (integer)
Please output.
Example
Input
2
123
567
Output
Case 1:
151
228
519
2693
2522
3604
9888
7725
6756
6435
Case 2:
3214
3297
8702
7248
5335
4622
3628
1623
6341
2082
### Response
```cpp
#include<iostream>
#include<algorithm>
#include<vector>
#include<stack>
#include<queue>
#include<cstdio>
#include<climits>
#include<cmath>
#include<cstring>
#include<string>
#define f first
#define s second
#define mp make_pair
#define REP(i,n) for(int i=0; i<(int)(n); i++)
#define FOR(i,c) for(__typeof((c).begin()) i=(c).begin(); i!=(c).end(); i++)
#define ALL(c) (c).begin(), (c).end()
using namespace std;
typedef unsigned int uint;
typedef long long ll;
int main(){
int n; cin>>n;
REP(c,n){
int s; cin>>s;
printf("Case %d:\n",c+1);
REP(i,10){
char buff[16];
sprintf(buff,"%08d",s*s);
buff[6] = '\0';
sscanf(buff+2,"%d",&s);
printf("%d\n",s);
}
}
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
A telephone number is a sequence of exactly 11 digits such that its first digit is 8.
Vasya and Petya are playing a game. Initially they have a string s of length n (n is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string s becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.
You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
Input
The first line contains one integer n (13 ≤ n < 10^5, n is odd) — the length of string s.
The second line contains the string s (|s| = n) consisting only of decimal digits.
Output
If Vasya has a strategy that guarantees him victory, print YES.
Otherwise print NO.
Examples
Input
13
8380011223344
Output
YES
Input
15
807345619350641
Output
NO
Note
In the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.
In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int N, K;
string S;
int main() {
int i, j, k, a;
cin >> N >> S;
k = K = (N - 11) / 2;
a = 0;
for (i = 0; i < N; i++) {
if (S[i] != '8') {
K--;
if (K < 0) break;
} else {
a++;
}
}
if (K > 0) a -= K;
if (a > k)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Given are two sequences A and B, both of length N. A and B are each sorted in the ascending order. Check if it is possible to reorder the terms of B so that for each i (1 \leq i \leq N) A_i \neq B_i holds, and if it is possible, output any of the reorderings that achieve it.
Constraints
* 1\leq N \leq 2 \times 10^5
* 1\leq A_i,B_i \leq N
* A and B are each sorted in the ascending order.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N
Output
If there exist no reorderings that satisfy the condition, print `No`.
If there exists a reordering that satisfies the condition, print `Yes` on the first line. After that, print a reordering of B on the second line, separating terms with a whitespace.
If there are multiple reorderings that satisfy the condition, you can print any of them.
Examples
Input
6
1 1 1 2 2 3
1 1 1 2 2 3
Output
Yes
2 2 3 1 1 1
Input
3
1 1 2
1 1 3
Output
No
Input
4
1 1 2 3
1 2 3 3
Output
Yes
3 3 1 2
### Response
```cpp
#define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
//template
#define rep(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define ALL(v) (v).begin(),(v).end()
typedef long long int ll;
const int inf = 0x3fffffff; const ll INF = 0x1fffffffffffffff; const double eps=1e-12;
template<typename T>inline bool chmax(T& a,T b){if(a<b){a=b;return 1;}return 0;}
template<typename T>inline bool chmin(T& a,T b){if(a>b){a=b;return 1;}return 0;}
//end
int main(){
int n; cin>>n;
vector<int> a(n),b(n);
rep(i,0,n)cin>>a[i];
rep(i,0,n)cin>>b[i];
int d=0;
rep(i,0,n){
int idx=upper_bound(ALL(b),a[i])-b.begin();
chmax(d,idx-i);
}
rotate(b.begin(),b.begin()+d,b.end());
rep(i,0,n)if(a[i]==b[i]){
puts("No"); return 0;
}
puts("Yes");
rep(i,0,n)cout<<b[i]<<(i==n-1?'\n':' ');
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
char s[N];
int p[N], k;
void kmp() {
int n = strlen(s + 1);
for (int i = 2; i <= n; i++) {
while (k && s[k + 1] != s[i]) k = p[k];
if (s[k + 1] == s[i]) k++;
p[i] = k;
}
}
int main() {
ios_base::sync_with_stdio(false);
scanf("%s", s + 1);
int n = strlen(s + 1);
kmp();
int x = 0, ans = p[n];
for (int i = 2; i < n; i++) x = max(x, p[i]);
while (ans) {
if (ans <= x)
break;
else
ans = p[ans];
}
if (!ans)
puts("Just a legend");
else
for (int i = 1; i <= ans; i++) printf("%c", s[i]);
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
This is an interactive problem.
Vasya and Petya are going to play the following game: Petya has some positive integer number a. After that Vasya should guess this number using the following questions. He can say a pair of non-negative integer numbers (x, y). Petya will answer him:
* "x", if (x mod a) ≥ (y mod a).
* "y", if (x mod a) < (y mod a).
We define (x mod a) as a remainder of division x by a.
Vasya should guess the number a using no more, than 60 questions.
It's guaranteed that Petya has a number, that satisfies the inequality 1 ≤ a ≤ 10^9.
Help Vasya playing this game and write a program, that will guess the number a.
Interaction
Your program should play several games.
Before the start of any game your program should read the string:
* "start" (without quotes) — the start of the new game.
* "mistake" (without quotes) — in the previous game, you found the wrong answer. Your program should terminate after reading this string and it will get verdict "Wrong answer".
* "end" (without quotes) — all games finished. Your program should terminate after reading this string.
After reading the string "start" (without quotes) the new game starts.
At the beginning, your program should ask several questions about pairs of non-negative integer numbers (x, y). You can only ask the numbers, that satisfy the inequalities 0 ≤ x, y ≤ 2 ⋅ 10^9. To ask a question print "? x y" (without quotes). As the answer, you should read one symbol:
* "x" (without quotes), if (x mod a) ≥ (y mod a).
* "y" (without quotes), if (x mod a) < (y mod a).
* "e" (without quotes) — you asked more than 60 questions. Your program should terminate after reading this string and it will get verdict "Wrong answer".
After your program asked several questions your program should print the answer in form "! a" (without quotes). You should print the number a satisfying the inequalities 1 ≤ a ≤ 10^9. It's guaranteed that Petya's number a satisfied this condition. After that, the current game will finish.
We recall that your program can't ask more than 60 questions during one game.
If your program doesn't terminate after reading "mistake" (without quotes), "end" (without quotes) or "e" (without quotes), it can get any verdict, because it will continue reading from closed input. Also, if your program prints answer or question in the incorrect format it can get any verdict, too. Be careful.
Don't forget to flush the output after printing questions and answers.
To flush the output, you can use:
* fflush(stdout) in C++.
* System.out.flush() in Java.
* stdout.flush() in Python.
* flush(output) in Pascal.
* See the documentation for other languages.
It's guaranteed that you should play at least 1 and no more than 100 games.
Hacks:
In hacks, you can use only one game. To hack a solution with Petya's number a (1 ≤ a ≤ 10^9) in the first line you should write a single number 1 and in the second line you should write a single number a.
Example
Input
start
x
x
start
x
x
y
start
x
x
y
y
end
Output
? 0 0
? 10 1
! 1
? 0 0
? 3 4
? 2 5
! 2
? 2 4
? 2 5
? 3 10
? 9 1
! 3
Note
In the first test, you should play 3 games with Petya's numbers 1, 2 and 3.
In the first game, Petya will answer "x" (without quotes) to any question, because (x mod 1) = 0 for any integer x.
In the second game, if you will ask pair (0, 0), the answer will be "x" (without quotes), because (0 mod 2) ≥ (0 mod 2). But if you will ask pair (2, 5), the answer will be "y" (without quotes), because (2 mod 2) < (5 mod 2), because (2 mod 2) = 0 and (5 mod 2) = 1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int inf = 2000000000;
void ans(int first) {
cout << "! " << first << "\n";
fflush(stdout);
}
bool les(int first, int second) {
if (second > 1e9) {
return false;
}
cout << "? " << first << " " << second << "\n";
fflush(stdout);
string s;
cin >> s;
return (s == "y");
}
int main() {
string s;
while (cin >> s) {
fflush(stdout);
if (s == "start") {
int first = 1;
bool res = les(0, 1);
if (res) {
while (res) {
res = les(first, first << 1);
first <<= 1;
}
first >>= 1;
int p = first >> 1;
while (p) {
if (les(first, first + p)) {
first += p;
}
p >>= 1;
}
first += 1;
ans(first);
} else {
ans(1);
}
} else if (s == "end") {
break;
}
}
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
BubbleSquare social network is celebrating 13^{th} anniversary and it is rewarding its members with special edition BubbleSquare tokens. Every member receives one personal token. Also, two additional tokens are awarded to each member for every friend they have on the network. Yet, there is a twist – everyone should end up with different number of tokens from all their friends. Each member may return one received token. Also, each two friends may agree to each return one or two tokens they have obtained on behalf of their friendship.
Input
First line of input contains two integer numbers n and k (2 ≤ n ≤ 12500, 1 ≤ k ≤ 1000000) - number of members in network and number of friendships.
Next k lines contain two integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) - meaning members a_i and b_i are friends.
Output
First line of output should specify the number of members who are keeping their personal token.
The second line should contain space separated list of members who are keeping their personal token.
Each of the following k lines should contain three space separated numbers, representing friend pairs and number of tokens each of them gets on behalf of their friendship.
Examples
Input
2 1
1 2
Output
1
1
1 2 0
Input
3 3
1 2
1 3
2 3
Output
0
1 2 0
2 3 1
1 3 2
Note
In the first test case, only the first member will keep its personal token and no tokens will be awarded for friendship between the first and the second member.
In the second test case, none of the members will keep their personal token. The first member will receive two tokens (for friendship with the third member), the second member will receive one token (for friendship with the third member) and the third member will receive three tokens (for friendships with the first and the second member).
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize(2)
using namespace std;
inline char gc(void) {
static char buf[100000], *p1 = buf, *p2 = buf;
return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2)
? EOF
: *p1++;
}
template <class T>
inline void read(T &x) {
T f = 1;
x = 0;
static char c = gc();
for (; !isdigit(c); c = gc())
if (c == '-') f = -f;
for (; isdigit(c); c = gc()) x = (x << 1) + (x << 3) + (c & 15);
x *= f;
}
inline void readstr(char *s) {
do *s = gc();
while ((*s == ' ') || (*s == '\n') || (*s == '\r'));
do *(++s) = gc();
while ((~*s) && (*s != ' ') && (*s != '\n') && (*s != '\r'));
*s = 0;
return;
}
inline void readch(char &x) {
while (isspace(x = gc()))
;
}
char pf[100000], *o1 = pf, *o2 = pf + 100000;
template <class T>
inline void writeln(T x, char c = '\n') {
if (x < 0)
(o1 == o2 ? fwrite(pf, 1, 100000, stdout), *(o1 = pf)++ = 45 : *o1++ = 45),
x = -x;
static char s[15], *b;
b = s;
if (!x) *b++ = 48;
for (; x; *b++ = x % 10 + 48, x /= 10)
;
for (; b-- != s; (o1 == o2 ? fwrite(pf, 1, 100000, stdout),
*(o1 = pf)++ = *b : *o1++ = *b))
;
(o1 == o2 ? fwrite(pf, 1, 100000, stdout), *(o1 = pf)++ = c : *o1++ = c);
}
template <class T>
inline void chkmax(T &x, const T y) {
x > y ? x = x : x = y;
}
template <class T>
inline void chkmin(T &x, const T y) {
x < y ? x = x : x = y;
}
const int N = 1e6 + 100;
int x[N], y[N], w[N], s[N], v[N];
bool in[N * 2];
vector<pair<int, int> > e[N];
vector<int> res;
int n, m;
int main() {
ios ::sync_with_stdio(false);
cin.tie();
cin >> n >> m;
for (register int i = (1); i <= (m); i++) {
cin >> x[i] >> y[i];
w[i] = 1;
s[x[i]]++;
s[y[i]]++;
e[max(x[i], y[i])].push_back(make_pair(min(x[i], y[i]), i));
}
for (register int i = (1); i <= (n); i++) {
for (auto it : e[i]) {
if (!v[it.first]) {
v[it.first] = 1;
w[it.second] = 0;
s[i]--;
}
in[s[it.first]] = 1;
}
for (auto it : e[i]) {
if (!in[s[i]]) break;
s[i]++;
v[it.first] = 0;
w[it.second]++;
}
for (auto it : e[i]) in[s[it.first]] = 0;
}
for (register int i = (1); i <= (n); i++)
if (v[i]) res.push_back(i);
cout << int(res.size()) << '\n';
for (auto it : res) cout << it << ' ';
cout << '\n';
for (register int i = (1); i <= (m); i++)
cout << x[i] << ' ' << y[i] << ' ' << w[i] << '\n';
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Polycarpus has n markers and m marker caps. Each marker is described by two numbers: xi is the color and yi is the diameter. Correspondingly, each cap is described by two numbers: aj is the color and bj is the diameter. Cap (aj, bj) can close marker (xi, yi) only if their diameters match, that is, bj = yi. Besides, a marker is considered to be beautifully closed, if the cap color and the marker color match, that is, aj = xi.
Find the way to close the maximum number of markers. If there are several such ways, then choose the one that has the maximum number of beautifully closed markers.
Input
The first input line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the number of markers and the number of caps, correspondingly.
Next n lines describe the markers. The i-th line contains two space-separated integers xi, yi (1 ≤ xi, yi ≤ 1000) — the i-th marker's color and diameter, correspondingly.
Next m lines describe the caps. The j-th line contains two space-separated integers aj, bj (1 ≤ aj, bj ≤ 1000) — the color and diameter of the j-th cap, correspondingly.
Output
Print two space-separated integers u, v, where u is the number of closed markers and v is the number of beautifully closed markers in the sought optimal way. Remember that you have to find the way to close the maximum number of markers, and if there are several such ways, you should choose the one where the number of beautifully closed markers is maximum.
Examples
Input
3 4
1 2
3 4
2 4
5 4
2 4
1 1
1 2
Output
3 2
Input
2 2
1 2
2 1
3 4
5 1
Output
1 0
Note
In the first test sample the first marker should be closed by the fourth cap, the second marker should be closed by the first cap and the third marker should be closed by the second cap. Thus, three markers will be closed, and two of them will be beautifully closed — the first and the third markers.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[1001][1001], b[1001][1001];
int main() {
int i, j;
int n, m;
while (cin >> n >> m) {
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
for (i = 0; i < n; ++i) {
int p, q;
cin >> p >> q;
++a[p][q];
}
for (i = 0; i < m; ++i) {
int p, q;
cin >> p >> q;
++b[p][q];
}
int s1 = 0, s2 = 0;
for (i = 1; i <= 1000; ++i) {
int s3 = 0, s4 = 0;
for (j = 1; j <= 1000; ++j) {
int p = min(a[j][i], b[j][i]);
a[j][i] -= p;
b[j][i] -= p;
s1 += p;
s2 += p;
s3 += a[j][i];
s4 += b[j][i];
}
s1 += min(s3, s4);
}
cout << s1 << ' ' << s2 << endl;
}
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
Ringo got interested in modern art. He decided to draw a big picture on the board with N+2 rows and M+2 columns of squares constructed in the venue of CODE FESTIVAL 2017, using some people.
The square at the (i+1)-th row and (j+1)-th column in the board is represented by the pair of integers (i,j). That is, the top-left square is (0,0), and the bottom-right square is (N+1,M+1). Initially, the squares (x,y) satisfying 1 \leq x \leq N and 1 \leq y \leq M are painted white, and the other (outermost) squares are painted black.
Ringo arranged people at some of the outermost squares, facing inward. More specifically, the arrangement of people is represented by four strings A, B, C and D, as follows:
* For each row except the top and bottom, if the i-th character (1 \leq i \leq N) in A is `1`, place a person facing right at the square (i,0); otherwise, do nothing.
* For each row except the top and bottom, if the i-th character (1 \leq i \leq N) in B is `1`, place a person facing left at the square (i,M+1); otherwise, do nothing.
* For each column except the leftmost and rightmost, if the i-th character (1 \leq i \leq M) in C is `1`, place a person facing down at the square (0,i); otherwise, do nothing.
* For each column except the leftmost and rightmost, if the i-th character (1 \leq i \leq M) in D is `1`, place a person facing up at the square (N+1,i); otherwise, do nothing.
Each person has a sufficient amount of non-white paint. No two people have paint of the same color.
<image>
An example of an arrangement of people (For convenience, black squares are displayed in gray)
Ringo repeats the following sequence of operations until all people are dismissed from the venue.
* Select a person who is still in the venue.
* The selected person repeats the following action while the square in front of him/her is white: move one square forward, and paint the square he/she enters with his/her paint. When the square in front of him/her is not white, he/she stops doing the action.
* The person is now dismissed from the venue.
<image>
An example of a way the board is painted
How many different states of the board can Ringo obtain at the end of the process? Find the count modulo 998244353.
Two states of the board are considered different when there is a square painted in different colors.
Constraints
* 1 \leq N,M \leq 10^5
* |A|=|B|=N
* |C|=|D|=M
* A, B, C and D consist of `0` and `1`.
Input
Input is given from Standard Input in the following format:
N M
A
B
C
D
Output
Print the number of the different states of the board Ringo can obtain at the end of the process, modulo 998244353.
Examples
Input
2 2
10
01
10
01
Output
6
Input
2 2
11
11
11
11
Output
32
Input
3 4
111
111
1111
1111
Output
1276
Input
17 21
11001010101011101
11001010011010111
111010101110101111100
011010110110101000111
Output
548356548
Input
3 4
000
101
1111
0010
Output
21
Input
9 13
111100001
010101011
0000000000000
1010111111101
Output
177856
Input
23 30
01010010101010010001110
11010100100100101010101
000101001001010010101010101101
101001000100101001010010101000
Output
734524988
### Response
```cpp
#include<cstdio>
#include<algorithm>
#define N_ 301000
using namespace std;
int n, m;
char X1[N_], X2[N_], Y1[N_], Y2[N_];
long long U[N_], D[N_], L[N_], R[N_], F[N_], InvF[N_], UU[N_], LL[N_], res;
long long Mod = 998244353;
long long Pow(long long a, int b){
long long r = 1;
while(b){
if(b&1)r=r*a%Mod;
a=a*a%Mod;b>>=1;
}
return r;
}
long long Comb(int a, int b){
if(a<b)return 0;
return F[a] * InvF[b]%Mod*InvF[a-b]%Mod;
}
long long Calc(int a, int b, int c){
return (Comb(a+b+c,c) - Comb(a+b+c-1, c) + Mod) % Mod;
}
int main(){
int i;
scanf("%d%d",&n,&m);
scanf("%s",X1+1);
scanf("%s",X2+1);
scanf("%s",Y1+1);
scanf("%s",Y2+1);
F[0]=1;
int sum = 0;
for(i=1;i<=n;i++){
sum += X1[i]-'0';
sum += X2[i]-'0';
}
for(i=1;i<=m;i++){
sum += Y1[i]-'0';
sum += Y2[i]-'0';
}
if(!sum){
printf("1\n");
return 0;
}
for(i=1;i<=300000;i++)F[i]=F[i-1]*i%Mod;
InvF[300000] = Pow(F[300000], Mod-2);
for(i=300000;i>=1;i--)InvF[i-1] = InvF[i] * i % Mod;
int s1 = 0, s2 = 0, cc = 0;
for(i=1;i<=m;i++)if(Y1[i] == '1')cc++;
U[0] = 1;
for(i=1;i<=n;i++){
if(X1[i] == '1')s1++;
if(X2[i] == '1')s2++;
U[i] = Calc(s1,s2,cc);
}
s1 = s2 = cc = 0;
for(i=1;i<=m;i++)if(Y2[i] == '1')cc++;
D[n+1] = 1;
for(i=n;i>=1;i--){
if(X1[i] == '1')s1++;
if(X2[i] == '1')s2++;
D[i] = Calc(s1,s2,cc);
}
s1 = s2 = cc = 0;
for(i=1;i<=n;i++)if(X1[i] == '1')cc++;
L[0] = 1;
for(i=1;i<=m;i++){
if(Y1[i] == '1')s1++;
if(Y2[i] == '1')s2++;
L[i] = Calc(s1,s2,cc);
}
s1 = s2 = cc = 0;
R[m+1] = 1;
for(i=1;i<=n;i++)if(X2[i] == '1')cc++;
for(i=m;i>=1;i--){
if(Y1[i] == '1')s1++;
if(Y2[i] == '1')s2++;
R[i] = Calc(s1,s2,cc);
}
UU[0] = 1;
for(i=1;i<=n;i++){
int t = X1[i]-'0' + X2[i]-'0';
UU[i] = UU[i-1];
if(t==2) UU[i] += UU[i-1];
if(t) UU[i] += U[i];
UU[i]%=Mod;
}
LL[0] = 1;
for(i=1;i<=m;i++){
int t = Y1[i]-'0' + Y2[i]-'0';
LL[i] = LL[i-1];
if(t==2) LL[i] += LL[i-1];
if(t) LL[i] += L[i];
LL[i]%=Mod;
}
for(i=1;i<=n;i++){
int c = X1[i] - '0' + X2[i] - '0';
res = (res + UU[i-1]*D[i+1]*c) % Mod;
}
// printf("%lld\n",res);
for(i=1;i<=m;i++){
int c = Y1[i] - '0' + Y2[i] - '0';
res = (res + LL[i-1]*R[i+1]*c) % Mod;
}
for(i=1;i<=4;i++){
// printf("%lld %lld %lld %lld %lld %lld\n",U[i],D[i],L[i],R[i],UU[i],LL[i]);
}
printf("%lld\n",res);
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
You are given an n × m table, consisting of characters «A», «G», «C», «T». Let's call a table nice, if every 2 × 2 square contains all four distinct characters. Your task is to find a nice table (also consisting of «A», «G», «C», «T»), that differs from the given table in the minimum number of characters.
Input
First line contains two positive integers n and m — number of rows and columns in the table you are given (2 ≤ n, m, n × m ≤ 300 000). Then, n lines describing the table follow. Each line contains exactly m characters «A», «G», «C», «T».
Output
Output n lines, m characters each. This table must be nice and differ from the input table in the minimum number of characters.
Examples
Input
2 2
AG
CT
Output
AG
CT
Input
3 5
AGCAG
AGCAG
AGCAG
Output
TGCAT
CATGC
TGCAT
Note
In the first sample, the table is already nice. In the second sample, you can change 9 elements to make the table nice.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const char mat[] = "AGCT";
int n, m;
int go(vector<string> &lis, int n, int m, char ch1, char ch2,
vector<string> &ret) {
vector<char> mm[2];
mm[0] = {ch1, ch2};
for (int(i) = (0); (i) <= ((4) - 1); (i)++)
if (mat[i] != mm[0][0] && mat[i] != mm[0][1]) mm[1].emplace_back(mat[i]);
int res = 0;
for (int(i) = (0); (i) <= ((n)-1); (i)++) {
int now[2] = {};
for (int(j) = (0); (j) <= ((m)-1); (j)++)
if (lis[i][j] != mm[i & 1][j & 1]) now[0]++;
for (int(j) = (0); (j) <= ((m)-1); (j)++)
if (lis[i][j] != mm[i & 1][j & 1 ^ 1]) now[1]++;
if (now[0] < now[1]) {
for (int(j) = (0); (j) <= ((m)-1); (j)++) ret[i][j] = mm[i & 1][j & 1];
res += now[0];
} else {
for (int(j) = (0); (j) <= ((m)-1); (j)++)
ret[i][j] = mm[i & 1][j & 1 ^ 1];
res += now[1];
}
}
return res;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> n >> m;
vector<string> lis(n);
for (int(i) = (0); (i) <= ((n)-1); (i)++) cin >> lis[i];
int res = n * m;
vector<string> ans;
bool rev = false;
for (int(i) = (0); (i) <= ((4) - 1); (i)++)
for (int(j) = (i + 1); (j) <= (3); (j)++) {
vector<string> tmp(n, string(m, '\0'));
int cur = go(lis, n, m, mat[i], mat[j], tmp);
if (cur < res) {
ans = tmp;
res = cur;
}
}
vector<string> lis2(m);
for (int(i) = (0); (i) <= ((m)-1); (i)++)
for (int(j) = (0); (j) <= ((n)-1); (j)++) lis2[i] += lis[j][i];
for (int(i) = (0); (i) <= ((4) - 1); (i)++)
for (int(j) = (i + 1); (j) <= (3); (j)++) {
vector<string> tmp(m, string(n, '\0'));
int cur = go(lis2, m, n, mat[i], mat[j], tmp);
if (cur < res) {
ans = tmp;
rev = true;
res = cur;
}
}
if (rev) {
for (int(i) = (0); (i) <= ((n)-1); (i)++) {
for (int(j) = (0); (j) <= ((m)-1); (j)++) cout << ans[j][i];
cout << '\n';
}
} else {
for (int(i) = (0); (i) <= ((n)-1); (i)++) cout << ans[i] << '\n';
}
}
``` |
### Prompt
Your task is to create a CPP solution to 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;
struct node {
int l, r;
} s[500001];
bool cmp(node a, node b) {
if (a.r == b.r)
return a.l < b.l;
else
return a.r < b.r;
}
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d%d", &s[i].l, &s[i].r);
}
sort(s, s + n, cmp);
int cnt = 0, p = 0;
for (int i = 0; i < n; i++) {
if (s[i].l > p) {
cnt++;
p = s[i].r;
}
}
printf("%d\n", cnt);
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Recently Luba bought a monitor. Monitor is a rectangular matrix of size n × m. But then she started to notice that some pixels cease to work properly. Luba thinks that the monitor will become broken the first moment when it contains a square k × k consisting entirely of broken pixels. She knows that q pixels are already broken, and for each of them she knows the moment when it stopped working. Help Luba to determine when the monitor became broken (or tell that it's still not broken even after all q pixels stopped working).
Input
The first line contains four integer numbers n, m, k, q (1 ≤ n, m ≤ 500, 1 ≤ k ≤ min(n, m), 0 ≤ q ≤ n·m) — the length and width of the monitor, the size of a rectangle such that the monitor is broken if there is a broken rectangle with this size, and the number of broken pixels.
Each of next q lines contain three integer numbers xi, yi, ti (1 ≤ xi ≤ n, 1 ≤ yi ≤ m, 0 ≤ t ≤ 109) — coordinates of i-th broken pixel (its row and column in matrix) and the moment it stopped working. Each pixel is listed at most once.
We consider that pixel is already broken at moment ti.
Output
Print one number — the minimum moment the monitor became broken, or "-1" if it's still not broken after these q pixels stopped working.
Examples
Input
2 3 2 5
2 1 8
2 2 8
1 2 1
1 3 4
2 3 2
Output
8
Input
3 3 2 5
1 2 2
2 2 1
2 3 5
3 2 10
2 1 100
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct order {
int row;
int column;
long time;
};
int main() {
int n, m, k, qq;
long(*A)[600] = new long[600][600];
int(*B)[600] = new int[600][600];
order *all_order = new order[300000];
cin >> n >> m >> k >> qq;
int i, j;
for (i = 0; i < 600; i++) {
for (j = 0; j < 600; j++) {
A[i][j] = -1;
}
}
long max_num = 0;
for (i = 0; i < qq; i++) {
cin >> all_order[i].row >> all_order[i].column >> all_order[i].time;
A[all_order[i].row][all_order[i].column] = all_order[i].time;
if (all_order[i].time > max_num) {
max_num = all_order[i].time;
}
}
long left = 0;
long right = max_num;
long try_num;
for (i = 0; i < 600; i++) {
for (j = 0; j < 600; j++) {
B[i][j] = 0;
}
}
while (left <= right) {
long mid = (left + right) / 2;
int flag = 0;
long temp_num;
try_num = mid;
for (i = 1; i <= n; i++) {
for (j = 1; j <= m; j++) {
B[i][j] = B[i - 1][j] + B[i][j - 1] - B[i - 1][j - 1] +
(A[i][j] <= try_num) * (A[i][j] != -1);
}
}
for (i = 1; i <= n - k + 1; i++) {
for (j = 1; j <= m - k + 1; j++) {
temp_num = B[i + k - 1][j + k - 1] - B[i - 1][j + k - 1] -
B[i + k - 1][j - 1] + B[i - 1][j - 1];
if (temp_num == k * k) {
flag = 1;
break;
}
}
if (flag == 1) {
break;
}
}
if (flag) {
right = mid - 1;
} else {
left = mid + 1;
}
}
if (left > max_num) {
cout << -1;
return 0;
}
int flag = 0;
long temp_num;
try_num = left;
for (i = 1; i <= n; i++) {
for (j = 1; j <= m; j++) {
B[i][j] = B[i - 1][j] + B[i][j - 1] - B[i - 1][j - 1] +
(A[i][j] <= try_num) * (A[i][j] != -1);
}
}
for (i = 1; i <= n - k + 1; i++) {
for (j = 1; j <= m - k + 1; j++) {
temp_num = B[i + k - 1][j + k - 1] - B[i - 1][j + k - 1] -
B[i + k - 1][j - 1] + B[i - 1][j - 1];
if (temp_num == k * k) {
flag = 1;
break;
}
}
if (flag == 1) {
break;
}
}
if (flag) {
cout << left;
return 0;
}
cout << -1;
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
The Berland road network consists of n cities and of m bidirectional roads. The cities are numbered from 1 to n, where the main capital city has number n, and the culture capital — number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time.
All residents of Berland are very lazy people, and so when they want to get from city v to city u, they always choose one of the shortest paths (no matter which one).
The Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous.
Now the government wonders where to put the police station so that the average number of safe roads for all the shortest paths from the cultural capital to the main capital would take the maximum value.
Input
The first input line contains two integers n and m (2 ≤ n ≤ 100, <image>) — the number of cities and the number of roads in Berland, correspondingly. Next m lines contain pairs of integers vi, ui (1 ≤ vi, ui ≤ n, vi ≠ ui) — the numbers of cities that are connected by the i-th road. The numbers on a line are separated by a space.
It is guaranteed that each pair of cities is connected with no more than one road and that it is possible to get from any city to any other one along Berland roads.
Output
Print the maximum possible value of the average number of safe roads among all shortest paths from the culture capital to the main one. The answer will be considered valid if its absolute or relative inaccuracy does not exceed 10 - 6.
Examples
Input
4 4
1 2
2 4
1 3
3 4
Output
1.000000000000
Input
11 14
1 2
1 3
2 4
3 4
4 5
4 6
5 11
6 11
1 8
8 9
9 7
11 7
1 10
10 4
Output
1.714285714286
Note
In the first sample you can put a police station in one of the capitals, then each path will have exactly one safe road. If we place the station not in the capital, then the average number of safe roads will also make <image>.
In the second sample we can obtain the maximum sought value if we put the station in city 4, then 6 paths will have 2 safe roads each, and one path will have 0 safe roads, so the answer will equal <image>.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxN = 100 + 1;
int n, m;
vector<int> a[maxN], mark[maxN];
int d1[maxN], dN[maxN], f[maxN];
void bfs(int v, int d[]) {
memset(f, 0, sizeof f);
memset(d, -1, sizeof d);
vector<int> q;
f[v] = 1;
d[v] = 0;
q.push_back(v);
for (int i = 0; i < q.size(); i++) {
int x = q[i];
for (int j = 0; j < a[x].size(); j++)
if (!f[a[x][j]]) {
f[a[x][j]] = 1;
d[a[x][j]] = d[x] + 1;
q.push_back(a[x][j]);
}
}
}
double t[maxN][maxN], pc[maxN];
void dfs(int v) {
cerr << "dfs " << v << endl;
f[v] = 1;
for (int i = 0; i < a[v].size(); i++) {
if (!mark[v][i]) continue;
int x = a[v][i];
if (!f[x]) dfs(x);
cerr << v << ' ' << x << ' ' << pc[x] << endl;
pc[v] += pc[x];
for (int j = 0; j < n; j++) t[v][j] += t[x][j];
t[v][v] += pc[x];
}
if (v == n - 1) pc[v] = 1, t[v][v] = 1;
}
int main() {
ios::sync_with_stdio(false);
cin >> n >> m;
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
x--;
y--;
a[x].push_back(y);
a[y].push_back(x);
}
bfs(0, d1);
bfs(n - 1, dN);
for (int i = 0; i < n; i++)
for (int j = 0; j < a[i].size(); j++) {
mark[i].push_back(0);
int x = a[i][j];
if (d1[i] + dN[i] == dN[0] && d1[x] + dN[x] == dN[0] &&
d1[x] == d1[i] + 1)
cerr << i << ' ' << x << endl, mark[i][j] = true;
}
memset(f, 0, sizeof f);
dfs(0);
for (int i = 0; i < n; i++) cerr << pc[i] << ' ';
cerr << endl;
double best = 1;
for (int i = 1; i < n - 1; i++) {
best = max(best, t[0][i] * 2 / pc[0]);
}
cout << fixed << setprecision(20) << best << endl;
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Imagine that you are in a building that has exactly n floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to n. Now you're on the floor number a. You are very bored, so you want to take the lift. Floor number b has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make k consecutive trips in the lift.
Let us suppose that at the moment you are on the floor number x (initially, you were on floor a). For another trip between floors you choose some floor with number y (y ≠ x) and the lift travels to this floor. As you cannot visit floor b with the secret lab, you decided that the distance from the current floor x to the chosen y must be strictly less than the distance from the current floor x to floor b with the secret lab. Formally, it means that the following inequation must fulfill: |x - y| < |x - b|. After the lift successfully transports you to floor y, you write down number y in your notepad.
Your task is to find the number of distinct number sequences that you could have written in the notebook as the result of k trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by 1000000007 (109 + 7).
Input
The first line of the input contains four space-separated integers n, a, b, k (2 ≤ n ≤ 5000, 1 ≤ k ≤ 5000, 1 ≤ a, b ≤ n, a ≠ b).
Output
Print a single integer — the remainder after dividing the sought number of sequences by 1000000007 (109 + 7).
Examples
Input
5 2 4 1
Output
2
Input
5 2 4 2
Output
2
Input
5 3 4 1
Output
0
Note
Two sequences p1, p2, ..., pk and q1, q2, ..., qk are distinct, if there is such integer j (1 ≤ j ≤ k), that pj ≠ qj.
Notes to the samples:
1. In the first sample after the first trip you are either on floor 1, or on floor 3, because |1 - 2| < |2 - 4| and |3 - 2| < |2 - 4|.
2. In the second sample there are two possible sequences: (1, 2); (1, 3). You cannot choose floor 3 for the first trip because in this case no floor can be the floor for the second trip.
3. In the third sample there are no sought sequences, because you cannot choose the floor for the first trip.
### Response
```cpp
#include <bits/stdc++.h>
using namespace ::std;
const long long maxn = 5100;
const long long mod = 1e9 + 7;
const long long inf = 1e9 + 500;
long long dp[2][maxn];
long long par[2][maxn];
long long finds(bool b, long long l, long long r) {
if (l <= 1) {
return par[b][r];
}
return (par[b][r] - par[b][l - 1] + mod) % mod;
}
int main() {
long long n, a, b, k;
cin >> n >> a >> b >> k;
if (a < b) {
n = b;
} else {
a = n - (a - 1);
n = n - (b - 1);
}
for (long long i = 1; i < n; i++) {
par[0][i] = i;
dp[0][i] = 1;
}
for (long long i = 1; i <= k; i++) {
for (long long j = 1; j < n; j++) {
long long f = n - j;
dp[i & 1][j] =
(finds((i & 1) ^ 1, j - f + 1, n - 1) - dp[i & 1 ^ 1][j] + mod) % mod;
}
par[i & 1][1] = dp[i & 1][1];
for (long long j = 2; j < n; j++) {
par[i & 1][j] = (par[i & 1][j - 1] + dp[i & 1][j]) % mod;
}
}
cout << dp[k & 1][a];
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
You have been given n distinct integers a1, a2, ..., an. You can remove at most k of them. Find the minimum modular m (m > 0), so that for every pair of the remaining integers (ai, aj), the following unequality holds: <image>.
Input
The first line contains two integers n and k (1 ≤ n ≤ 5000, 0 ≤ k ≤ 4), which we have mentioned above.
The second line contains n distinct integers a1, a2, ..., an (0 ≤ ai ≤ 106).
Output
Print a single positive integer — the minimum m.
Examples
Input
7 0
0 2 3 6 7 12 18
Output
13
Input
7 1
0 2 3 6 7 12 18
Output
7
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 5000 + 10, maxc = 1000000 + 10;
struct node {
node *nex;
pair<short, short> p;
node(const pair<short, short> &_p) {
nex = NULL;
p = _p;
}
};
int a[maxn];
int fa[maxn];
int getfa(int x) { return fa[x] == x ? x : fa[x] = getfa(fa[x]); }
node *v[maxc];
int n, k;
vector<int> tmp;
bool check(int m) {
tmp.clear();
int cnt = 0, ok = 1;
for (int i = m; ok && i < maxc; i += m)
for (node *j = v[i]; j; j = j->nex) {
int x = getfa(j->p.first), y = getfa(j->p.second);
if (x == y) continue;
if (cnt++ == k) {
ok = 0;
break;
}
fa[x] = y;
tmp.push_back(x);
}
for (auto i : tmp) fa[i] = i;
return ok;
}
int main() {
scanf("%d%d", &n, &k);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
sort(a + 1, a + n + 1);
for (int i = 1; i <= n; i++)
for (int j = i + 1; j <= n; j++) {
node *u = v[a[j] - a[i]];
node *r = new node(make_pair(i, j));
r->nex = u;
v[a[j] - a[i]] = r;
}
for (int i = 1; i <= n; i++) fa[i] = i;
for (int i = 1; i < maxc; i++)
if (check(i)) {
printf("%d\n", i);
return 0;
}
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Numbers k-bonacci (k is integer, k > 1) are a generalization of Fibonacci numbers and are determined as follows:
* F(k, n) = 0, for integer n, 1 ≤ n < k;
* F(k, k) = 1;
* F(k, n) = F(k, n - 1) + F(k, n - 2) + ... + F(k, n - k), for integer n, n > k.
Note that we determine the k-bonacci numbers, F(k, n), only for integer values of n and k.
You've got a number s, represent it as a sum of several (at least two) distinct k-bonacci numbers.
Input
The first line contains two integers s and k (1 ≤ s, k ≤ 109; k > 1).
Output
In the first line print an integer m (m ≥ 2) that shows how many numbers are in the found representation. In the second line print m distinct integers a1, a2, ..., am. Each printed integer should be a k-bonacci number. The sum of printed integers must equal s.
It is guaranteed that the answer exists. If there are several possible answers, print any of them.
Examples
Input
5 2
Output
3
0 2 3
Input
21 5
Output
3
4 1 16
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long f[100050];
long long n, k;
long long ans[5000];
int tot;
int main() {
scanf("%I64d%I64d", &n, &k);
long long temp = 1;
f[0] = 1;
int i;
for (i = 1;; ++i) {
f[i] = temp;
temp += f[i];
if (i - k >= 0) {
temp -= f[i - k];
}
if (f[i] >= n) break;
}
tot = 0;
for (; i >= 0; --i) {
if (f[i] > n) continue;
n -= f[i];
ans[tot++] = f[i];
if (n == 0) break;
}
if (tot == 1) {
ans[tot++] = 0;
}
printf("%d\n", tot);
for (int i = 0; i < tot; ++i) {
if (i) printf(" ");
printf("%I64d", ans[i]);
}
puts("");
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
In the advanced algorithm class, n2 students sit in n rows and n columns. One day, a professor who teaches this subject comes into the class, asks the shortest student in each row to lift up his left hand, and the tallest student in each column to lift up his right hand. What is the height of the student whose both hands are up ? The student will become a target for professor’s questions.
Given the size of the class, and the height of the students in the class, you have to print the height of the student who has both his hands up in the class.
Input
The input will consist of several cases. the first line of each case will be n(0 < n < 100), the number of rows and columns in the class. It will then be followed by a n-by-n matrix, each row of the matrix appearing on a single line. Note that the elements of the matrix may not be necessarily distinct. The input will be terminated by the case n = 0.
Output
For each input case, you have to print the height of the student in the class whose both hands are up. If there is no such student, then print 0 for that case.
Example
Input
3
1 2 3
4 5 6
7 8 9
3
1 2 3
7 8 9
4 5 6
0
Output
7
7
### Response
```cpp
#include<iostream>
#include<algorithm>
using namespace std;
int n;
int t[100][100];
int u[100],v[100];
void solve(){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(u[i]!=v[j])continue;
cout<<t[i][j]<<endl;
return;
}
}
cout<<0<<endl;
}
int main(){
while(cin>>n&&n){
for(int i=0;i<n;i++){
u[i]=1e8;v[i]=-1;
for(int j=0;j<n;j++){
cin>>t[i][j];
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
u[i]=min(u[i],t[i][j]);
v[j]=max(v[j],t[i][j]);
}
}
solve();
}
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.
The trajectory of a camel's spit is an arc, i.e. if the camel in position x spits d meters right, he can hit only the camel in position x + d, if such a camel exists.
Input
The first line contains integer n (1 ≤ n ≤ 100) — the amount of camels in the zoo. Each of the following n lines contains two integers xi and di ( - 104 ≤ xi ≤ 104, 1 ≤ |di| ≤ 2·104) — records in Bob's notepad. xi is a position of the i-th camel, and di is a distance at which the i-th camel spitted. Positive values of di correspond to the spits right, negative values correspond to the spits left. No two camels may stand in the same position.
Output
If there are two camels, which spitted at each other, output YES. Otherwise, output NO.
Examples
Input
2
0 1
1 -1
Output
YES
Input
3
0 1
1 1
2 -2
Output
NO
Input
5
2 -10
3 10
0 5
5 -5
10 1
Output
YES
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, a[101], b[101], c[101];
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i] >> b[i];
c[i] = a[i] + b[i];
}
bool check = false;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if ((c[i] == a[j]) && c[j] == a[i]) {
check = true;
break;
}
}
}
if (check == true)
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≤ i < n there is an edge between the vertices of i and i+1.
Denote the function f(l, r), which takes two integers l and r (l ≤ r):
* We leave in the tree only vertices whose values range from l to r.
* The value of the function will be the number of connected components in the new graph.
Your task is to calculate the following sum: $$$∑_{l=1}^{n} ∑_{r=l}^{n} f(l, r) $$$
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the values of the vertices.
Output
Print one number — the answer to the problem.
Examples
Input
3
2 1 3
Output
7
Input
4
2 1 1 3
Output
11
Input
10
1 5 2 5 5 3 10 6 5 1
Output
104
Note
In the first example, the function values will be as follows:
* f(1, 1)=1 (there is only a vertex with the number 2, which forms one component)
* f(1, 2)=1 (there are vertices 1 and 2 that form one component)
* f(1, 3)=1 (all vertices remain, one component is obtained)
* f(2, 2)=1 (only vertex number 1)
* f(2, 3)=2 (there are vertices 1 and 3 that form two components)
* f(3, 3)=1 (only vertex 3)
Totally out 7.
In the second example, the function values will be as follows:
* f(1, 1)=1
* f(1, 2)=1
* f(1, 3)=1
* f(1, 4)=1
* f(2, 2)=1
* f(2, 3)=2
* f(2, 4)=2
* f(3, 3)=1
* f(3, 4)=1
* f(4, 4)=0 (there is no vertex left, so the number of components is 0)
Totally out 11.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int N;
long long lst, n;
int main() {
cin >> N;
long long tot = 0;
for (int i = 1; i <= N; i++) {
cin >> n;
if (lst < n) {
tot += (n - lst) * (N - n + 1);
} else if (lst > n) {
tot += (lst - n) * (n);
}
lst = n;
}
cout << tot << endl;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
There are three positive integers A, B and C written on a blackboard. E869120 performs the following operation K times:
* Choose one integer written on the blackboard and let the chosen integer be n. Replace the chosen integer with 2n.
What is the largest possible sum of the integers written on the blackboard after K operations?
Constraints
* A, B and C are integers between 1 and 50 (inclusive).
* K is an integer between 1 and 10 (inclusive).
Input
Input is given from Standard Input in the following format:
A B C
K
Output
Print the largest possible sum of the integers written on the blackboard after K operations by E869220.
Examples
Input
5 3 11
1
Output
30
Input
3 3 4
2
Output
22
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int a,b,c,k;
cin>>a>>b>>c>>k;
int rest=a+b+c-max({a,b,c});
cout<<rest+max({a,b,c})*powf(2,k)<<endl;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
As we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with n vertices and m edges. There's a character written on each edge, a lowercase English letter.
<image>
Max and Lucas are playing the game. Max goes first, then Lucas, then Max again and so on. Each player has a marble, initially located at some vertex. Each player in his/her turn should move his/her marble along some edge (a player can move the marble from vertex v to vertex u if there's an outgoing edge from v to u). If the player moves his/her marble from vertex v to vertex u, the "character" of that round is the character written on the edge from v to u. There's one additional rule; the ASCII code of character of round i should be greater than or equal to the ASCII code of character of round i - 1 (for i > 1). The rounds are numbered for both players together, i. e. Max goes in odd numbers, Lucas goes in even numbers. The player that can't make a move loses the game. The marbles may be at the same vertex at the same time.
Since the game could take a while and Lucas and Max have to focus on finding Dart, they don't have time to play. So they asked you, if they both play optimally, who wins the game?
You have to determine the winner of the game for all initial positions of the marbles.
Input
The first line of input contains two integers n and m (2 ≤ n ≤ 100, <image>).
The next m lines contain the edges. Each line contains two integers v, u and a lowercase English letter c, meaning there's an edge from v to u written c on it (1 ≤ v, u ≤ n, v ≠ u). There's at most one edge between any pair of vertices. It is guaranteed that the graph is acyclic.
Output
Print n lines, a string of length n in each one. The j-th character in i-th line should be 'A' if Max will win the game in case her marble is initially at vertex i and Lucas's marble is initially at vertex j, and 'B' otherwise.
Examples
Input
4 4
1 2 b
1 3 a
2 4 c
3 4 b
Output
BAAA
ABAA
BBBA
BBBB
Input
5 8
5 3 h
1 2 c
3 1 c
3 2 r
5 1 r
4 3 z
5 4 r
5 2 h
Output
BABBB
BBBBB
AABBB
AAABA
AAAAB
Note
Here's the graph in the first sample test case:
<image>
Here's the graph in the second sample test case:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 105;
struct node {
int to, v;
};
vector<node> edge[N];
int dp[N][N][30];
bool check(int x, int y, int la) {
if (~dp[x][y][la]) return dp[x][y][la];
for (int i = 0; i < edge[x].size(); i++) {
int to = edge[x][i].to, z = edge[x][i].v;
if (z < la) continue;
if (!check(y, to, z)) return dp[x][y][la] = 1;
}
return dp[x][y][la] = 0;
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1, u, v; i <= m; i++) {
char s[2];
scanf("%d%d%s", &u, &v, s);
int tmp = s[0] - 'a' + 1;
edge[u].push_back(node<% v, tmp %>);
}
memset(dp, -1, sizeof(dp));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++)
if (check(i, j, 0))
cout << 'A';
else
cout << 'B';
cout << endl;
}
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has n balls and m baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from 1 to m, correspondingly. The balls are numbered with numbers from 1 to n.
Valeric decided to sort the balls in the order of increasing of their numbers by the following scheme. He will put each new ball in the basket with the least number of balls. And if he's got several variants, he chooses the basket which stands closer to the middle. That means that he chooses the basket for which <image> is minimum, where i is the number of the basket. If in this case Valeric still has multiple variants, he chooses the basket with the minimum number.
For every ball print the number of the basket where it will go according to Valeric's scheme.
Note that the balls are sorted into baskets in the order of increasing numbers, that is, the first ball goes first, then goes the second ball and so on.
Input
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of balls and baskets, correspondingly.
Output
Print n numbers, one per line. The i-th line must contain the number of the basket for the i-th ball.
Examples
Input
4 3
Output
2
1
3
2
Input
3 1
Output
1
1
1
### Response
```cpp
#include <bits/stdc++.h>
int main() {
int n, m, i;
scanf("%d%d", &n, &m);
if (m & 1) {
for (i = 0; i < n; i++) {
int j = i % m;
if (j & 1)
printf("%d\n", m / 2 - j / 2);
else
printf("%d\n", m / 2 + j / 2 + 1);
}
} else {
for (i = 0; i < n; i++) {
int j = i % m;
if (j & 1)
printf("%d\n", m / 2 + j / 2 + 1);
else
printf("%d\n", m / 2 - j / 2);
}
}
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Let a_1, …, a_n be an array of n positive integers. In one operation, you can choose an index i such that a_i = i, and remove a_i from the array (after the removal, the remaining parts are concatenated).
The weight of a is defined as the maximum number of elements you can remove.
You must answer q independent queries (x, y): after replacing the x first elements of a and the y last elements of a by n+1 (making them impossible to remove), what would be the weight of a?
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 3 ⋅ 10^5) — the length of the array and the number of queries.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — elements of the array.
The i-th of the next q lines contains two integers x and y (x, y ≥ 0 and x+y < n).
Output
Print q lines, i-th line should contain a single integer — the answer to the i-th query.
Examples
Input
13 5
2 2 3 9 5 4 6 5 7 8 3 11 13
3 1
0 0
2 4
5 0
0 12
Output
5
11
6
1
0
Input
5 2
1 4 1 2 4
0 0
1 0
Output
2
0
Note
Explanation of the first query:
After making first x = 3 and last y = 1 elements impossible to remove, a becomes [×, ×, ×, 9, 5, 4, 6, 5, 7, 8, 3, 11, ×] (we represent 14 as × for clarity).
Here is a strategy that removes 5 elements (the element removed is colored in red):
* [×, ×, ×, 9, \color{red}{5}, 4, 6, 5, 7, 8, 3, 11, ×]
* [×, ×, ×, 9, 4, 6, 5, 7, 8, 3, \color{red}{11}, ×]
* [×, ×, ×, 9, 4, \color{red}{6}, 5, 7, 8, 3, ×]
* [×, ×, ×, 9, 4, 5, 7, \color{red}{8}, 3, ×]
* [×, ×, ×, 9, 4, 5, \color{red}{7}, 3, ×]
* [×, ×, ×, 9, 4, 5, 3, ×] (final state)
It is impossible to remove more than 5 elements, hence the weight is 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename A, typename B>
string to_string(pair<A, B> p);
template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p);
template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p);
string to_string(const string& s) { return '"' + s + '"'; }
string to_string(const char& s) {
string res = "'";
res += s;
res += "'";
return res;
}
string to_string(bool b) { return (b ? "true" : "false"); }
string to_string(vector<bool> v) {
string res = "{";
for (int i = 0; i < static_cast<int>(v.size()); i++) {
if (i) res += ", ";
res += to_string(v[i]);
}
res += "}";
return res;
}
template <size_t N>
string to_string(bitset<N> v) {
string res = "";
for (size_t i = 0; i < N; i++) {
res += static_cast<char>('0' + v[i]);
}
return res;
}
template <typename A>
string to_string(A v) {
bool first = true;
string res = "{";
for (const auto& x : v) {
if (!first) {
res += ", ";
}
first = false;
res += to_string(x);
}
res += "}";
return res;
}
template <typename A, typename B>
string to_string(pair<A, B> p) {
return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}
template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p) {
return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " +
to_string(get<2>(p)) + ")";
}
template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p) {
return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " +
to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")";
}
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
cerr << " " << to_string(H);
debug_out(T...);
}
vector<long long> t, d, t2, d2;
vector<long long> upd;
void push2(long long v, long long l, long long r) {
t2[v] += d2[v];
if (l + 1 != r) {
d2[v * 2 + 1] += d2[v];
d2[v * 2 + 2] += d2[v];
}
d2[v] = 0;
}
void update2(long long v, long long l, long long r, long long i, long long x) {
push2(v, l, r);
if (l + 1 == r) {
t2[v] = x;
return;
}
long long m = (l + r) / 2;
if (i < m)
update2(v * 2 + 1, l, m, i, x);
else
update2(v * 2 + 2, m, r, i, x);
t2[v] = min(t2[v * 2 + 1], t2[v * 2 + 2]);
}
void update4(long long v, long long l, long long r) {
push2(v, l, r);
if (t2[v] > 0) return;
if (l + 1 == r) {
upd.push_back(l);
return;
}
long long m = (l + r) / 2;
update4(v * 2 + 1, l, m);
update4(v * 2 + 2, m, r);
}
void update3(long long v, long long l, long long r, long long l1,
long long r1) {
push2(v, l, r);
if (l >= r1 || l1 >= r) return;
if (l1 <= l && r <= r1) {
d2[v] -= 1;
push2(v, l, r);
if (t2[v] > 1) return;
update4(v, l, r);
return;
}
long long m = (l + r) / 2;
update3(v * 2 + 1, l, m, l1, r1);
update3(v * 2 + 2, m, r, l1, r1);
t2[v] = min(t2[v * 2 + 1], t2[v * 2 + 2]);
}
void push(long long v, long long l, long long r) {
if (l + 1 != r) {
d[v * 2 + 1] += d[v];
d[v * 2 + 2] += d[v];
}
t[v] += d[v];
d[v] = 0;
}
long long get(long long v, long long l, long long r, long long l1,
long long r1) {
push(v, l, r);
if (l1 >= r || l >= r1) return 0;
if (l1 <= l && r <= r1) return t[v];
long long m = (l + r) / 2;
return get(v * 2 + 1, l, m, l1, r1) + get(v * 2 + 2, m, r, l1, r1);
}
void update(long long v, long long l, long long r, long long l1, long long r1,
long long x) {
push(v, l, r);
if (l1 >= r || l >= r1) return;
if (l1 <= l && r <= r1) {
d[v] += x;
push(v, l, r);
return;
}
long long m = (l + r) / 2;
update(v * 2 + 1, l, m, l1, r1, x);
update(v * 2 + 2, m, r, l1, r1, x);
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long n, q;
cin >> n >> q;
vector<long long> a(n);
for (long long i = 0; i < n; i++) cin >> a[i];
for (long long i = 0; i < n; i++) {
a[i]--;
a[i] = i - a[i];
}
vector<pair<long long, long long> > query[n + 1];
for (long long i = 0; i < q; i++) {
long long x, y;
cin >> x >> y;
query[x].push_back({y, i});
}
t.resize(4 * n, 0);
d.resize(4 * n, 0);
t2.resize(4 * n, 1e18);
d2.resize(4 * n, 0);
vector<long long> ans(q);
for (long long j = n - 1; j >= 0; j--) {
if (a[j] == 0) {
upd.push_back(j);
} else {
if (a[j] < 0) a[j] = 1e18;
update2(0, 0, n, j, a[j]);
}
while (upd.size() > 0) {
long long x = upd.back();
upd.pop_back();
update(0, 0, n, x, n, 1);
update2(0, 0, n, x, 1e18);
update3(0, 0, n, x + 1, n);
}
for (auto el : query[j]) {
ans[el.second] = get(0, 0, n, n - el.first - 1, n - el.first);
}
}
for (long long i = 0; i < q; i++) cout << ans[i] << '\n';
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
M-kun is a competitor in AtCoder, whose highest rating is X.
In this site, a competitor is given a kyu (class) according to his/her highest rating. For ratings from 400 through 1999, the following kyus are given:
* From 400 through 599: 8-kyu
* From 600 through 799: 7-kyu
* From 800 through 999: 6-kyu
* From 1000 through 1199: 5-kyu
* From 1200 through 1399: 4-kyu
* From 1400 through 1599: 3-kyu
* From 1600 through 1799: 2-kyu
* From 1800 through 1999: 1-kyu
What kyu does M-kun have?
Constraints
* 400 \leq X \leq 1999
* X is an integer.
Input
Input is given from Standard Input in the following format:
X
Output
Print the kyu M-kun has, as an integer. For example, if he has 8-kyu, print `8`.
Examples
Input
725
Output
7
Input
1600
Output
2
### Response
```cpp
#include <iostream>
using namespace std;
int main(){
int x;
cin >> x;
cout << 10 - x / 200 << endl;
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Takahashi has an empty string S and a variable x whose initial value is 0.
Also, we have a string T consisting of `0` and `1`.
Now, Takahashi will do the operation with the following two steps |T| times.
* Insert a `0` or a `1` at any position of S of his choice.
* Then, increment x by the sum of the digits in the odd positions (first, third, fifth, ...) of S. For example, if S is `01101`, the digits in the odd positions are `0`, `1`, `1` from left to right, so x is incremented by 2.
Print the maximum possible final value of x in a sequence of operations such that S equals T in the end.
Constraints
* 1 \leq |T| \leq 2 \times 10^5
* T consists of `0` and `1`.
Input
Input is given from Standard Input in the following format:
T
Output
Print the maximum possible final value of x in a sequence of operations such that S equals T in the end.
Examples
Input
1101
Output
5
Input
0111101101
Output
26
### Response
```cpp
#define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
// #define int long long
// #define double long double
#define rep(i,n) for (int i=0; i<(int)(n); ++i)
#define rep1(i,n) for (int i=1; i<(int)(n); ++i)
#define repeq(i,n) for (int i=0; i<=(int)(n); ++i)
#define rep1eq(i,n) for (int i=1; i<=(int)(n); ++i)
#define rrep(i,n) for (int i=(int)(n)-1; i>=0; --i)
#define rrep1(i,n) for (int i=(int)(n)-1; i>0; --i)
#define rrepeq(i,n) for (int i=(int)(n); i>=0; --i)
#define rrep1eq(i,n) for (int i=(int)(n); i>0; --i)
#define REP(i,a,b) for (int i=(int)(a); i<=(int)(b); ++i)
#define RREP(i,a,b) for (int i=(int)(a); i>=(int)(b); --i)
#define ALL(a) (a).begin(), (a).end()
#define RALL(a) (a).rbegin(), (a).rend()
using ll = long long;
using vi = vector<int>;
using vl = vector<ll>;
using vb = vector<bool>;
template<typename T> using Graph = vector<vector<T>>;
template<typename T> using Spacial = vector<vector<vector<T>>>;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
template<typename T> using greater_priority_queue = priority_queue<T, vector<T>, greater<T>>;
const int MOD = 1e9+7;
const int MOD2 = 998244353;
// const double EPS = 1e-9;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
string interval[2] = {" ", "\n"}; // {" ", "\n"}
template<typename T> struct is_plural : false_type{};
template<typename T1, typename T2> struct is_plural<pair<T1, T2>> : true_type{};
template<typename T> struct is_plural<vector<T>> : true_type{};
template<typename T> struct is_plural<complex<T>> : true_type{};
template<typename T1, typename T2> istream &operator>>(istream &is, pair<T1, T2> &p) { return is >> p.first >> p.second; }
template<typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &p) { return os << p.first << " " << p.second; }
template<typename T> istream &operator>>(istream &is, vector<T> &vec) { for (auto itr = vec.begin(); itr != vec.end(); ++itr) is >> *itr; return is; }
template<typename T> ostream &operator<<(ostream &os, const vector<T> &vec) { if (vec.empty()) return os; bool pl = is_plural<T>(); os << vec.front(); for (auto itr = ++vec.begin(); itr != vec.end(); ++itr) os << interval[pl] << *itr; return os; }
bool CoutYN(bool a, string y = "Yes", string n = "No") { cout << (a ? y : n) << "\n"; return a; }
template<typename T1, typename T2> inline bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); }
template<typename T1, typename T2> inline bool chmin(T1 &a, T2 b) { return a > b && (a = b, true); }
long long modpow(int a, long long n, int mod = MOD) { long long ret = 1; do { if (n & 1) ret = ret * a % mod; a = 1LL * a * a % mod; } while (n >>= 1); return ret; }
template<typename T> T GCD(T a, T b) { return b ? GCD(b, a%b) : a; }
template<typename T> T LCM(T a, T b) { return a / GCD(a, b) * b; }
template<typename T1, typename T2> bool CompareBySecond(pair<T1, T2> a, pair<T1, T2> b) { return a.second != b.second ? a.second < b.second : a.first < b.first; }
template<typename T1, typename T2> bool CompareByInverse(pair<T1, T2> a, pair<T1, T2> b) { return a.first != b.first ? a.first < b.first : a.second > b.second; }
/* -------- <templates end> -------- */
void solve() {
string t; cin >> t;
int n = t.size();
vi pos;
ll sum = 0;
rep(i,n) {
if (t[i] == '1') sum++;
else pos.emplace_back(sum);
}
ll x = ((sum + 1) / 2) * ((sum + 2) / 2);
int sz = pos.size();
int cnt = 0;
vi res;
rep(i,sz) {
if ((pos[i] & 1) ^ (cnt & 1)) {
sum++;
cnt++;
x += (sum + 1) / 2;
} else {
res.emplace_back(i);
}
}
int odd = 0, even = 0;
reverse(ALL(res));
rep(i,res.size()) {
sum++;
if (i & 1) {
odd = sz - res[i] - even;
x += (sum + 1) / 2 - odd;
} else {
even = sz - res[i] - odd;
x += (sum + 1) / 2 - even;
}
}
cout << x << endl;
}
/* -------- <programs end> -------- */
signed main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
cout << fixed << setprecision(10);
solve();
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
<image>
Input
The input contains a single integer a (1 ≤ a ≤ 18257).
Output
Print a single integer output (1 ≤ output ≤ 2·109).
Examples
Input
2
Output
13
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long a, Output, i, k, j;
while (cin >> a) {
i = 0;
j = 0;
Output = 1;
for (k = 1; k <= a; k++) {
i++;
Output += j;
j = 12 * i;
}
cout << Output << endl;
}
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
You are given a rooted tree. Let's denote d(x) as depth of node x: depth of the root is 1, depth of any other node x is d(y) + 1, where y is a parent of x.
The tree has the following property: every node x with d(x) = i has exactly ai children. Maximum possible depth of a node is n, and an = 0.
We define fk as the number of unordered pairs of vertices in the tree such that the number of edges on the simple path between them is equal to k.
Calculate fk modulo 109 + 7 for every 1 ≤ k ≤ 2n - 2.
Input
The first line of input contains an integer n (2 ≤ n ≤ 5 000) — the maximum depth of a node.
The second line of input contains n - 1 integers a1, a2, ..., an - 1 (2 ≤ ai ≤ 109), where ai is the number of children of every node x such that d(x) = i. Since an = 0, it is not given in the input.
Output
Print 2n - 2 numbers. The k-th of these numbers must be equal to fk modulo 109 + 7.
Examples
Input
4
2 2 2
Output
14 19 20 20 16 16
Input
3
2 3
Output
8 13 6 9
Note
This the tree from the first sample:
<image>
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC target("avx2")
#pragma GCC optimization("unroll-loops")
using namespace std;
using ll = long long;
template <class T>
using V = vector<T>;
template <class T, class U>
using P = pair<T, U>;
using vll = V<ll>;
using vii = V<int>;
using vvll = V<vll>;
using vvii = V<V<int> >;
using PII = P<int, int>;
using PLL = P<ll, ll>;
template <class T>
inline bool chmax(T& a, T b) {
if (a < b) {
a = b;
return true;
}
return false;
}
template <class T>
inline bool chmin(T& a, T b) {
if (a > b) {
a = b;
return true;
}
return false;
}
template <class A, class B>
ostream& operator<<(ostream& out, const P<A, B>& p) {
return out << '(' << p.first << ", " << p.second << ')';
}
template <class A>
ostream& operator<<(ostream& out, const V<A>& v) {
out << '[';
for (int i = 0; i < int(v.size()); i++) {
if (i) out << ", ";
out << v[i];
}
return out << ']';
}
const long long MOD = 1000000007;
const long long HIGHINF = (long long)1e18;
const int INF = (int)1e9;
const int N = 5000;
vvii down(N, vii(N, 0)), up(2, vii(2 * N, 0));
vii ans(2 * N, 0);
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n;
cin >> n;
vii a(n);
for (ll i = 0; i < n - 1; i++) cin >> a[i];
vii cha(n, 1);
for (ll i = 1; i < n; i++) cha[i] = ll(cha[i - 1]) * a[i - 1] % MOD;
down[n - 1][0] = 1;
for (ll i = n - 2; i > -1; i--) {
down[i][0] = 1;
for (ll j = 1; j < n; j++) {
down[i][j] += ll(a[i]) * down[i + 1][j - 1] % MOD;
if (down[i][j] >= MOD) down[i][j] -= MOD;
ans[j] += ll(cha[i]) * down[i][j] % MOD;
if (ans[j] >= MOD) ans[j] -= MOD;
}
}
up[0][0] = 1;
for (ll i = 1; i < n; i++) {
up[1] = vii(2 * N, 0);
up[1][0] = 1;
for (ll j = 1; j < 2 * n; j++) {
up[1][j] += up[0][j - 1];
if (up[1][j] >= MOD) up[1][j] -= MOD;
if (j >= 2 and j - 2 < n) {
up[1][j] += ll(a[i - 1] - 1) * down[i][j - 2] % MOD;
if (up[1][j] >= MOD) up[1][j] -= MOD;
}
ans[j] += ll(cha[i]) * up[1][j] % MOD;
if (ans[j] >= MOD) ans[j] -= MOD;
}
swap(up[0], up[1]);
}
const int div2 = (MOD + 1) / 2;
for (ll i = 1; i < 2 * n - 1; i++)
cout << ll(ans[i]) * div2 % MOD << (i == 2 * n - 2 ? '\n' : ' ');
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".
Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.
After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process.
<image>
Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!
Input
The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to
* "L", if the i-th domino has been pushed to the left;
* "R", if the i-th domino has been pushed to the right;
* ".", if the i-th domino has not been pushed.
It is guaranteed that if si = sj = "L" and i < j, then there exists such k that i < k < j and sk = "R"; if si = sj = "R" and i < j, then there exists such k that i < k < j and sk = "L".
Output
Output a single integer, the number of the dominoes that remain vertical at the end of the process.
Examples
Input
14
.L.R...LR..L..
Output
4
Input
5
R....
Output
0
Input
1
.
Output
1
Note
The first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.
In the second example case, all pieces fall down since the first piece topples all the other pieces.
In the last example case, a single piece has not been pushed in either direction.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
string str;
cin >> str;
if (n == 1 && str[0] == '.') {
cout << "1";
return 0;
}
int co = 0, i;
for (i = 0; i < n; i++)
if (str[i] == 'R' || str[i] == 'L') break;
if (i == n) {
cout << n;
return 0;
}
if (str[i] == 'R') {
co += i;
}
int j = i, k;
for (k = i + 1; k < n; k++) {
if (str[k] == 'L' && str[j] == 'R') {
if ((k - j - 1) % 2 != 0) co++;
j = k;
}
if (str[k] == 'R' && str[j] == 'L') {
co += k - j - 1;
j = k;
}
if (str[k] == 'L' && str[j] == 'L') {
j = k;
}
if (str[k] == 'R' && str[j] == 'R') {
j = k;
}
}
if (j < n && str[j] == 'L') co += n - j - 1;
cout << co;
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store.
Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group.
Jzzhu wonders how to get the maximum possible number of groups. Can you help him?
Input
A single integer n (1 ≤ n ≤ 105), the number of the apples.
Output
The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group.
If there are several optimal answers you can print any of them.
Examples
Input
6
Output
2
6 3
2 4
Input
9
Output
3
9 3
2 4
6 8
Input
2
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
bool prim[maxn];
bool vis[maxn];
int last[maxn];
vector<int> ve[2];
vector<int> tmp;
int main() {
int n;
scanf("%d", &n);
int cot = 0;
for (int i = 2; i <= n / 2; i++) {
if (!prim[i]) {
for (int j = 2 * i; j <= n; j += i) prim[j] = 1;
}
}
for (int i = n / 2; i >= 2; i--) {
if (!prim[i]) {
tmp.clear();
for (int j = 1; j * i <= n; j++) {
if (vis[j * i]) continue;
if (j != 2) {
tmp.push_back(j * i);
vis[j * i] = 1;
}
}
if ((tmp.size()) & 1) {
tmp.push_back(2 * i);
vis[2 * i] = 1;
}
for (int j = 0; j < tmp.size(); j += 2) {
ve[0].push_back(tmp[j]);
ve[1].push_back(tmp[j + 1]);
}
}
}
printf("%d\n", ve[0].size());
for (int i = 0; i < ve[0].size(); i++) printf("%d %d\n", ve[0][i], ve[1][i]);
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Fibonacci strings are defined as follows:
* f1 = «a»
* f2 = «b»
* fn = fn - 1 fn - 2, n > 2
Thus, the first five Fibonacci strings are: "a", "b", "ba", "bab", "babba".
You are given a Fibonacci string and m strings si. For each string si, find the number of times it occurs in the given Fibonacci string as a substring.
Input
The first line contains two space-separated integers k and m — the number of a Fibonacci string and the number of queries, correspondingly.
Next m lines contain strings si that correspond to the queries. It is guaranteed that strings si aren't empty and consist only of characters "a" and "b".
The input limitations for getting 30 points are:
* 1 ≤ k ≤ 3000
* 1 ≤ m ≤ 3000
* The total length of strings si doesn't exceed 3000
The input limitations for getting 100 points are:
* 1 ≤ k ≤ 1018
* 1 ≤ m ≤ 104
* The total length of strings si doesn't exceed 105
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.
Output
For each string si print the number of times it occurs in the given Fibonacci string as a substring. Since the numbers can be large enough, print them modulo 1000000007 (109 + 7). Print the answers for the strings in the order in which they are given in the input.
Examples
Input
6 5
a
b
ab
ba
aba
Output
3
5
3
3
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct kieu {
long long mang[5][5];
};
string need, s[10], p, xau;
int n, f[3001], base = 1000000007, full;
kieu matrix;
long long dp[10];
int tinh() {
int q, i, ans;
q = 0;
ans = 0;
for (i = 0; i <= int(need.length()) - 1; i++) {
while ((q != 0) && (need[i] != p[q])) q = f[q];
if (need[i] == p[q]) q++;
if (q == int(p.length())) {
ans++;
q = f[q];
}
}
return ans;
}
void init() {
int i, q;
memset(f, 0, sizeof(f));
q = 0;
f[1] = 0;
for (i = 2; i <= int(p.length()); i++) {
while ((q != 0) && (p[i - 1] != p[q])) q = f[q];
if (p[i - 1] == p[q]) q++;
f[i] = q;
}
}
kieu nhan(kieu u, kieu v) {
int i, j, t;
kieu c;
memset(c.mang, 0, sizeof(c.mang));
for (i = 1; i <= 4; i++)
for (j = 1; j <= 4; j++)
for (t = 1; t <= 4; t++)
c.mang[i][j] = (c.mang[i][j] + u.mang[i][t] * v.mang[t][j]) % base;
return c;
}
kieu power(int x) {
if (x == 1)
return matrix;
else {
kieu p;
p = power(x / 2);
p = nhan(p, p);
if (x & 1) p = nhan(p, matrix);
return p;
}
}
void solve() {
kieu q;
int j, t;
long long ans;
n = full;
if (n <= 2) {
need = s[n];
cout << tinh();
return;
}
n -= 2;
while (s[1].length() < p.length()) {
xau = s[2] + s[1];
s[1] = s[2];
s[2] = xau;
n--;
if (n == 0) break;
}
if (n == 0) {
need = s[2];
cout << tinh();
return;
}
s[3] = s[2] + s[1];
s[4] = s[3] + s[2];
need = s[1];
dp[1] = tinh();
need = s[2];
dp[2] = tinh();
need = s[3];
dp[3] = tinh();
need = s[4];
dp[4] = tinh();
if (n + 2 <= 4) {
cout << dp[n + 2];
return;
}
q = power(n - 2);
ans = 0;
for (j = 4; j <= 4; j++)
for (t = 1; t <= 4; t++) ans = (ans + dp[t] * q.mang[t][j]) % base;
cout << ans;
}
void khoitaomatran() {
memset(matrix.mang, 0, sizeof(matrix.mang));
matrix.mang[4][4] = 1;
matrix.mang[3][4] = 2;
matrix.mang[2][4] = base - 1;
matrix.mang[1][4] = base - 1;
matrix.mang[4][3] = 1;
matrix.mang[3][2] = 1;
matrix.mang[2][1] = 1;
}
int main() {
int test, ntest;
scanf("%d%d\n", &n, &test);
full = n;
for (ntest = 1; ntest <= test; ntest++) {
s[1] = "a";
s[2] = "b";
getline(cin, p);
khoitaomatran();
init();
solve();
cout << endl;
}
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
You are given an integer a that consists of n digits. You are also given a sequence of digits s of length m. The digit in position j (1 ≤ j ≤ m) of sequence s means that you can choose an arbitrary position i (1 ≤ i ≤ n) in a and replace the digit in the chosen position i with sj. Each element in the sequence s can participate in no more than one replacing operation.
Your task is to perform such sequence of replacements, that the given number a gets maximum value. You are allowed to use not all elements from s.
Input
The first line contains positive integer a. Its length n is positive and doesn't exceed 105. The second line contains sequence of digits s. Its length m is positive and doesn't exceed 105. The digits in the sequence s are written consecutively without any separators.
The given number a doesn't contain leading zeroes.
Output
Print the maximum value that can be obtained from a after a series of replacements. You are allowed to use not all elements from s. The printed number shouldn't contain any leading zeroes.
Examples
Input
1024
010
Output
1124
Input
987
1234567
Output
987
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
stack<char> sortStack(stack<char> &input) {
stack<char> tmpStack;
while (!input.empty()) {
int tmp = input.top();
input.pop();
while (!tmpStack.empty() && tmpStack.top() > tmp) {
input.push(tmpStack.top());
tmpStack.pop();
}
tmpStack.push(tmp);
}
return tmpStack;
}
int main() {
string n, s;
cin >> n >> s;
int i, j = 0;
sort(s.rbegin(), s.rend());
for (i = 0; n[i]; i++) {
if (s[j] && s[j] > n[i]) {
n[i] = s[j++];
}
}
cout << n;
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
You're a mikemon breeder currently in the middle of your journey to become a mikemon master. Your current obstacle is go through the infamous Biridian Forest.
The forest
The Biridian Forest is a two-dimensional grid consisting of r rows and c columns. Each cell in Biridian Forest may contain a tree, or may be vacant. A vacant cell may be occupied by zero or more mikemon breeders (there may also be breeders other than you in the forest). Mikemon breeders (including you) cannot enter cells with trees. One of the cells is designated as the exit cell.
The initial grid, including your initial position, the exit cell, and the initial positions of all other breeders, will be given to you. Here's an example of such grid (from the first example):
<image>
Moves
Breeders (including you) may move in the forest. In a single move, breeders may perform one of the following actions:
* Do nothing.
* Move from the current cell to one of the four adjacent cells (two cells are adjacent if they share a side). Note that breeders cannot enter cells with trees.
* If you are located on the exit cell, you may leave the forest. Only you can perform this move — all other mikemon breeders will never leave the forest by using this type of movement.
After each time you make a single move, each of the other breeders simultaneously make a single move (the choice of which move to make may be different for each of the breeders).
Mikemon battle
If you and t (t > 0) mikemon breeders are located on the same cell, exactly t mikemon battles will ensue that time (since you will be battling each of those t breeders once). After the battle, all of those t breeders will leave the forest to heal their respective mikemons.
Note that the moment you leave the forest, no more mikemon battles can ensue, even if another mikemon breeder move to the exit cell immediately after that. Also note that a battle only happens between you and another breeders — there will be no battle between two other breeders (there may be multiple breeders coexisting in a single cell).
Your goal
You would like to leave the forest. In order to do so, you have to make a sequence of moves, ending with a move of the final type. Before you make any move, however, you post this sequence on your personal virtual idol Blog. Then, you will follow this sequence of moves faithfully.
Goal of other breeders
Because you post the sequence in your Blog, the other breeders will all know your exact sequence of moves even before you make your first move. All of them will move in such way that will guarantee a mikemon battle with you, if possible. The breeders that couldn't battle you will do nothing.
Your task
Print the minimum number of mikemon battles that you must participate in, assuming that you pick the sequence of moves that minimize this number. Note that you are not required to minimize the number of moves you make.
Input
The first line consists of two integers: r and c (1 ≤ r, c ≤ 1000), denoting the number of rows and the number of columns in Biridian Forest. The next r rows will each depict a row of the map, where each character represents the content of a single cell:
* 'T': A cell occupied by a tree.
* 'S': An empty cell, and your starting position. There will be exactly one occurence of this in the map.
* 'E': An empty cell, and where the exit is located. There will be exactly one occurence of this in the map.
* A digit (0-9): A cell represented by a digit X means that the cell is empty and is occupied by X breeders (in particular, if X is zero, it means that the cell is not occupied by any breeder).
It is guaranteed that it will be possible for you to go from your starting position to the exit cell through a sequence of moves.
Output
A single line denoted the minimum possible number of mikemon battles that you have to participate in if you pick a strategy that minimize this number.
Examples
Input
5 7
000E0T3
T0TT0T0
010T0T0
2T0T0T0
0T0S000
Output
3
Input
1 4
SE23
Output
2
Note
The following picture illustrates the first example. The blue line denotes a possible sequence of moves that you should post in your blog:
<image>
The three breeders on the left side of the map will be able to battle you — the lone breeder can simply stay in his place until you come while the other two breeders can move to where the lone breeder is and stay there until you come. The three breeders on the right does not have a way to battle you, so they will stay in their place.
For the second example, you should post this sequence in your Blog:
<image>
Here's what happens. First, you move one cell to the right.
<image>
Then, the two breeders directly to the right of the exit will simultaneously move to the left. The other three breeder cannot battle you so they will do nothing.
<image>
You end up in the same cell with 2 breeders, so 2 mikemon battles are conducted. After those battles, all of your opponents leave the forest.
<image>
Finally, you make another move by leaving the forest.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<string> d(n);
for (int i = 0; i < n; ++i) cin >> d[i];
bool v[1000][1000] = {0};
vector<vector<int> > p;
p.resize(n);
for (int i = 0; i < n; ++i) p[i].resize(m);
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j) p[i][j] = 100000000;
;
;
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j) v[i][j] = false;
;
int sx, sy, ex, ey;
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
if (d[i][j] == 'E')
ex = i, ey = j;
else if (d[i][j] == 'S')
sx = i, sy = j;
p[ex][ey] = 0;
queue<pair<int, int> > q;
q.push(make_pair(ex, ey));
while (!q.empty()) {
pair<int, int> c = q.front();
q.pop();
int x = c.first, y = c.second;
int cr = p[x][y] + 1;
if (x + 1 < n && d[x + 1][y] != 'T' && !v[x + 1][y]) {
p[x + 1][y] = cr;
v[x + 1][y] = true;
q.push(make_pair(x + 1, y));
}
if (x - 1 >= 0 && d[x - 1][y] != 'T' && !v[x - 1][y]) {
p[x - 1][y] = cr;
v[x - 1][y] = true;
q.push(make_pair(x - 1, y));
}
if (y + 1 < m && d[x][y + 1] != 'T' && !v[x][y + 1]) {
p[x][y + 1] = cr;
v[x][y + 1] = true;
q.push(make_pair(x, y + 1));
}
if (y - 1 >= 0 && d[x][y - 1] != 'T' && !v[x][y - 1]) {
p[x][y - 1] = cr;
v[x][y - 1] = true;
q.push(make_pair(x, y - 1));
}
}
int ret = 0;
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
if (p[i][j] <= p[sx][sy] && d[i][j] != 'T' && d[i][j] != 'S' &&
d[i][j] != 'E') {
ret += d[i][j] - '0';
}
cout << ret << endl;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
The Oak has n nesting places, numbered with integers from 1 to n. Nesting place i is home to b_i bees and w_i wasps.
Some nesting places are connected by branches. We call two nesting places adjacent if there exists a branch between them. A simple path from nesting place x to y is given by a sequence s_0, …, s_p of distinct nesting places, where p is a non-negative integer, s_0 = x, s_p = y, and s_{i-1} and s_{i} are adjacent for each i = 1, …, p. The branches of The Oak are set up in such a way that for any two pairs of nesting places x and y, there exists a unique simple path from x to y. Because of this, biologists and computer scientists agree that The Oak is in fact, a tree.
A village is a nonempty set V of nesting places such that for any two x and y in V, there exists a simple path from x to y whose intermediate nesting places all lie in V.
A set of villages \cal P is called a partition if each of the n nesting places is contained in exactly one of the villages in \cal P. In other words, no two villages in \cal P share any common nesting place, and altogether, they contain all n nesting places.
The Oak holds its annual Miss Punyverse beauty pageant. The two contestants this year are Ugly Wasp and Pretty Bee. The winner of the beauty pageant is determined by voting, which we will now explain. Suppose P is a partition of the nesting places into m villages V_1, …, V_m. There is a local election in each village. Each of the insects in this village vote for their favorite contestant. If there are strictly more votes for Ugly Wasp than Pretty Bee, then Ugly Wasp is said to win in that village. Otherwise, Pretty Bee wins. Whoever wins in the most number of villages wins.
As it always goes with these pageants, bees always vote for the bee (which is Pretty Bee this year) and wasps always vote for the wasp (which is Ugly Wasp this year). Unlike their general elections, no one abstains from voting for Miss Punyverse as everyone takes it very seriously.
Mayor Waspacito, and his assistant Alexwasp, wants Ugly Wasp to win. He has the power to choose how to partition The Oak into exactly m villages. If he chooses the partition optimally, determine the maximum number of villages in which Ugly Wasp wins.
Input
The first line of input contains a single integer t (1 ≤ t ≤ 100) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains two space-separated integers n and m (1 ≤ m ≤ n ≤ 3000). The second line contains n space-separated integers b_1, b_2, …, b_n (0 ≤ b_i ≤ 10^9). The third line contains n space-separated integers w_1, w_2, …, w_n (0 ≤ w_i ≤ 10^9). The next n - 1 lines describe the pairs of adjacent nesting places. In particular, the i-th of them contains two space-separated integers x_i and y_i (1 ≤ x_i, y_i ≤ n, x_i ≠ y_i) denoting the numbers of two adjacent nesting places. It is guaranteed that these pairs form a tree.
It is guaranteed that the sum of n in a single file is at most 10^5.
Output
For each test case, output a single line containing a single integer denoting the maximum number of villages in which Ugly Wasp wins, among all partitions of The Oak into m villages.
Example
Input
2
4 3
10 160 70 50
70 111 111 0
1 2
2 3
3 4
2 1
143 420
214 349
2 1
Output
2
0
Note
In the first test case, we need to partition the n = 4 nesting places into m = 3 villages. We can make Ugly Wasp win in 2 villages via the following partition: \{\{1, 2\}, \{3\}, \{4\}\}. In this partition,
* Ugly Wasp wins in village \{1, 2\}, garnering 181 votes as opposed to Pretty Bee's 170;
* Ugly Wasp also wins in village \{3\}, garnering 111 votes as opposed to Pretty Bee's 70;
* Ugly Wasp loses in the village \{4\}, garnering 0 votes as opposed to Pretty Bee's 50.
Thus, Ugly Wasp wins in 2 villages, and it can be shown that this is the maximum possible number.
In the second test case, we need to partition the n = 2 nesting places into m = 1 village. There is only one way to do this: \{\{1, 2\}\}. In this partition's sole village, Ugly Wasp gets 563 votes, and Pretty Bee also gets 563 votes. Ugly Wasp needs strictly more votes in order to win. Therefore, Ugly Wasp doesn't win in any village.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long ksm(long long a, long long b) {
if (!b) return 1;
long long ns = ksm(a, b >> 1);
ns = ns * ns % 998244353;
if (b & 1) ns = ns * a % 998244353;
return ns;
}
int w[3010], b[3010], sz[3010];
vector<int> eg[3010];
pair<int, long long> dp[3010][3010];
pair<int, long long> add(pair<int, long long> a, pair<int, long long> b) {
return make_pair(a.first + b.first, a.second + b.second);
}
const long long inf = 1e18;
void upd(int a) {
dp[a][sz[a]] = make_pair(0, -inf);
for (int i = sz[a] - 1; i >= 0; i--)
dp[a][i + 1] = max(dp[a][i + 1],
make_pair(dp[a][i].first + (dp[a][i].second > 0), 0ll));
}
pair<int, long long> r[3010];
void dfs(int a, int fa) {
dp[a][0] = make_pair(0, w[a]);
sz[a] = 1;
for (auto v : eg[a]) {
if (v == fa) continue;
dfs(v, a);
upd(v);
for (int i = 0; i < sz[v] + sz[a]; i++) r[i] = make_pair(0, -inf);
for (int i = 0; i <= sz[v]; i++)
for (int j = 0; j < sz[a]; j++)
r[i + j] = max(r[i + j], add(dp[v][i], dp[a][j]));
sz[a] += sz[v];
for (int i = 0; i < sz[a]; i++) dp[a][i] = r[i];
}
}
int main() {
int t;
cin >> t;
for (int i = 0; i < t; i++) {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
scanf("%d", &b[i]);
eg[i].clear();
}
for (int i = 1; i <= n; i++) scanf("%d", &w[i]), w[i] -= b[i];
for (int i = 1; i < n; i++) {
int u, v;
scanf("%d%d", &u, &v);
eg[u].push_back(v), eg[v].push_back(u);
}
dfs(1, 0);
int ans = dp[1][m - 1].first + (dp[1][m - 1].second > 0);
cout << ans << endl;
}
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?
If Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.
Input
The first line of the input contains integers n and m (1 ≤ n, m ≤ 100) — the number of buttons and the number of bulbs respectively.
Each of the next n lines contains xi (0 ≤ xi ≤ m) — the number of bulbs that are turned on by the i-th button, and then xi numbers yij (1 ≤ yij ≤ m) — the numbers of these bulbs.
Output
If it's possible to turn on all m bulbs print "YES", otherwise print "NO".
Examples
Input
3 4
2 1 4
3 1 3 1
1 2
Output
YES
Input
3 3
1 1
1 2
1 1
Output
NO
Note
In the first sample you can press each button once and turn on all the bulbs. In the 2 sample it is impossible to turn on the 3-rd lamp.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename T>
T in() {
char ch;
T n = 0;
bool ng = false;
while (1) {
ch = getchar();
if (ch == '-') {
ng = true;
ch = getchar();
break;
}
if (ch >= '0' && ch <= '9') break;
}
while (1) {
n = n * 10 + (ch - '0');
ch = getchar();
if (ch < '0' || ch > '9') break;
}
return (ng ? -n : n);
}
template <typename T>
inline T POW(T B, T P) {
if (P == 0) return 1;
if (P & 1)
return B * POW(B, P - 1);
else
return (POW(B, P / 2) * POW(B, P / 2));
}
template <typename T>
inline T Gcd(T a, T b) {
if (a < 0) return Gcd(-a, b);
if (b < 0) return Gcd(a, -b);
return (b == 0) ? a : Gcd(b, a % b);
}
template <typename T>
inline T Lcm(T a, T b) {
if (a < 0) return Lcm(-a, b);
if (b < 0) return Lcm(a, -b);
return a * (b / Gcd(a, b));
}
long long Bigmod(long long base, long long power, long long MOD) {
long long ret = 1;
while (power) {
if (power & 1) ret = (ret * base) % MOD;
base = (base * base) % MOD;
power >>= 1;
}
return ret;
}
bool isVowel(char ch) {
ch = toupper(ch);
if (ch == 'A' || ch == 'U' || ch == 'I' || ch == 'O' || ch == 'E')
return true;
return false;
}
long long ModInverse(long long number, long long MOD) {
return Bigmod(number, MOD - 2, MOD);
}
bool isConst(char ch) {
if (isalpha(ch) && !isVowel(ch)) return true;
return false;
}
int toInt(string s) {
int sm;
stringstream second(s);
second >> sm;
return sm;
}
int vis[400007];
int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
for (int j = 0; j < x; j++) {
int c;
cin >> c;
vis[c] = 1;
}
}
int f = 0;
for (int i = 1; i < m + 1; i++) {
if (!vis[i]) f++;
}
if (!f)
printf("YES\n");
else
printf("NO\n");
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.
You are given a set of q possible operations. Limak can perform them in any order, any operation may be applied any number of times. The i-th operation is described by a string ai of length two and a string bi of length one. No two of q possible operations have the same string ai.
When Limak has a string s he can perform the i-th operation on s if the first two letters of s match a two-letter string ai. Performing the i-th operation removes first two letters of s and inserts there a string bi. See the notes section for further clarification.
You may note that performing an operation decreases the length of a string s exactly by 1. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don't match any ai.
Limak wants to start with a string of length n and perform n - 1 operations to finally get a one-letter string "a". In how many ways can he choose the starting string to be able to get "a"? Remember that Limak can use only letters he knows.
Input
The first line contains two integers n and q (2 ≤ n ≤ 6, 1 ≤ q ≤ 36) — the length of the initial string and the number of available operations.
The next q lines describe the possible operations. The i-th of them contains two strings ai and bi (|ai| = 2, |bi| = 1). It's guaranteed that ai ≠ aj for i ≠ j and that all ai and bi consist of only first six lowercase English letters.
Output
Print the number of strings of length n that Limak will be able to transform to string "a" by applying only operations given in the input.
Examples
Input
3 5
ab a
cc c
ca a
ee c
ff d
Output
4
Input
2 8
af e
dc d
cc f
bc b
da b
eb a
bb b
ff c
Output
1
Input
6 2
bb a
ba a
Output
0
Note
In the first sample, we count initial strings of length 3 from which Limak can get a required string "a". There are 4 such strings: "abb", "cab", "cca", "eea". The first one Limak can compress using operation 1 two times (changing "ab" to a single "a"). The first operation would change "abb" to "ab" and the second operation would change "ab" to "a".
Other three strings may be compressed as follows:
* "cab" <image> "ab" <image> "a"
* "cca" <image> "ca" <image> "a"
* "eea" <image> "ca" <image> "a"
In the second sample, the only correct initial string is "eb" because it can be immediately compressed to "a".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int inf_int = 2e9;
long long inf_ll = 2e18;
const double pi = 3.1415926535898;
template <typename T, typename T1>
void prin(vector<pair<T, T1> >& a) {
for (int i = 0; i < a.size(); i++) {
cout << a[i].first << " " << a[i].second << "\n";
}
}
template <typename T>
void prin(vector<T>& a) {
for (int i = 0; i < a.size(); i++) {
cout << a[i];
if (i < a.size() - 1)
cout << " ";
else
cout << "\n";
}
}
template <typename T>
void prin(set<T>& a) {
for (auto it = a.begin(); it != a.end(); it++) {
cout << *it << " ";
}
}
template <typename T>
void prin_new_line(vector<T>& a) {
for (int i = 0; i < a.size(); i++) {
cout << a[i] << "\n";
}
}
template <typename T, typename T1>
void prin_new_line(vector<pair<T, T1> >& a) {
for (int i = 0; i < a.size(); i++) {
cout << a[i].first << " " << a[i].second << "\n";
}
}
int sum_vec(vector<int>& a) {
int s = 0;
for (int i = 0; i < a.size(); i++) {
s += a[i];
}
return s;
}
template <typename T>
T max(vector<T>& a) {
T ans = a[0];
for (int i = 1; i < a.size(); i++) {
ans = max(ans, a[i]);
}
return ans;
}
template <typename T>
T min(vector<T>& a) {
T ans = a[0];
for (int i = 1; i < a.size(); i++) {
ans = min(ans, a[i]);
}
return ans;
}
template <typename T>
T min(T a, T b, T c) {
return min(a, min(b, c));
}
template <typename T>
T max(T a, T b, T c) {
return max(a, max(b, c));
}
double s_triangle(double x1, double y1, double x2, double y2, double x3,
double y3) {
return abs(((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) / 2);
}
bool overflow(long long a, long long b) {
if (a * b / b != a) return true;
return false;
}
bool debug = 0;
const int maxn = 1e5 + 7;
vector<string> let[26];
map<string, int> mp;
int n;
long long ans = 0;
void dfs(string a) {
if (mp.find(a) != mp.end()) {
return;
}
if (a.size() == n) {
if (mp[a] != 1) ans++;
mp[a] = 1;
return;
}
mp[a] = 1;
int x = a[0] - 'a';
int res = 0;
for (int i = 0; i < let[x].size(); i++) {
string c = let[x][i];
for (int e = 1; e < a.size(); e++) {
c.push_back(a[e]);
}
dfs(c);
}
}
void solve() {
int q;
cin >> n >> q;
for (int i = 0; i < q; i++) {
string a;
cin >> a;
char t;
cin >> t;
let[t - 'a'].push_back(a);
}
dfs("a");
cout << ans;
}
int main() {
if (!debug) {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
int t = 1;
while (t--) solve();
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
We have a grid with N rows and M columns of squares. Initially, all the squares are white.
There is a button attached to each row and each column. When a button attached to a row is pressed, the colors of all the squares in that row are inverted; that is, white squares become black and vice versa. When a button attached to a column is pressed, the colors of all the squares in that column are inverted.
Takahashi can freely press the buttons any number of times. Determine whether he can have exactly K black squares in the grid.
Constraints
* 1 \leq N,M \leq 1000
* 0 \leq K \leq NM
Input
Input is given from Standard Input in the following format:
N M K
Output
If Takahashi can have exactly K black squares in the grid, print `Yes`; otherwise, print `No`.
Examples
Input
2 2 2
Output
Yes
Input
2 2 1
Output
No
Input
3 5 8
Output
Yes
Input
7 9 20
Output
No
### Response
```cpp
#include <iostream>
using namespace std;
int main(){
int N,K,M;
cin >> N >> M >> K;
for(int i=0;i<=N;i++){
for(int j=0;j<=M;j++){
if(j*N + i*M - i*j*2 == K){
cout << "Yes" << endl;
return 0;
}
}
}
cout << "No" << endl;
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
<image>
At the request of a friend who started learning abacus, you decided to create a program to display the abacus beads. Create a program that takes a certain number as input and outputs a row of abacus beads. However, the number of digits of the abacus to be displayed is 5 digits, and the arrangement of beads from 0 to 9 is as follows using'*' (half-width asterisk),''(half-width blank), and'=' (half-width equal). It shall be expressed as.
<image>
Input
Multiple test cases are given. Up to 5 digits (integer) are given on one line for each test case.
The number of test cases does not exceed 1024.
Output
Output the abacus bead arrangement for each test case. Insert a blank line between the test cases.
Example
Input
2006
1111
Output
****
*
=====
* *
****
* ***
*****
*****
*****
=====
****
*
*****
*****
*****
### Response
```cpp
#include <cstdio>
#include <string>
#include <iostream>
using namespace std;
int main()
{
char s[5];
string list[10];
bool flag = true;
list[0] = "* = ****";
list[1] = "* =* ***";
list[2] = "* =** **";
list[3] = "* =*** *";
list[4] = "* =**** ";
list[5] = " *= ****";
list[6] = " *=* ***";
list[7] = " *=** **";
list[8] = " *=*** *";
list[9] = " *=**** ";
while(scanf("%s", s) != EOF){
if(!flag) puts("");
string str = s;
int len = str.size();
string num;
for(int i = 0; i < 5 - len; i++){
num += "0";
}
num += str;
for(int i = 0; i < 8; i++){
for(int j = 0; j < 5; j++){
cout << list[num[j] - '0'][i];
}
puts("");
}
flag = false;
}
return(0);
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
To get money for a new aeonic blaster, ranger Qwerty decided to engage in trade for a while. He wants to buy some number of items (or probably not to buy anything at all) on one of the planets, and then sell the bought items on another planet. Note that this operation is not repeated, that is, the buying and the selling are made only once. To carry out his plan, Qwerty is going to take a bank loan that covers all expenses and to return the loaned money at the end of the operation (the money is returned without the interest). At the same time, Querty wants to get as much profit as possible.
The system has n planets in total. On each of them Qwerty can buy or sell items of m types (such as food, medicine, weapons, alcohol, and so on). For each planet i and each type of items j Qwerty knows the following:
* aij — the cost of buying an item;
* bij — the cost of selling an item;
* cij — the number of remaining items.
It is not allowed to buy more than cij items of type j on planet i, but it is allowed to sell any number of items of any kind.
Knowing that the hold of Qwerty's ship has room for no more than k items, determine the maximum profit which Qwerty can get.
Input
The first line contains three space-separated integers n, m and k (2 ≤ n ≤ 10, 1 ≤ m, k ≤ 100) — the number of planets, the number of question types and the capacity of Qwerty's ship hold, correspondingly.
Then follow n blocks describing each planet.
The first line of the i-th block has the planet's name as a string with length from 1 to 10 Latin letters. The first letter of the name is uppercase, the rest are lowercase. Then in the i-th block follow m lines, the j-th of them contains three integers aij, bij and cij (1 ≤ bij < aij ≤ 1000, 0 ≤ cij ≤ 100) — the numbers that describe money operations with the j-th item on the i-th planet. The numbers in the lines are separated by spaces.
It is guaranteed that the names of all planets are different.
Output
Print a single number — the maximum profit Qwerty can get.
Examples
Input
3 3 10
Venus
6 5 3
7 6 5
8 6 10
Earth
10 9 0
8 6 4
10 9 3
Mars
4 3 0
8 4 12
7 2 5
Output
16
Note
In the first test case you should fly to planet Venus, take a loan on 74 units of money and buy three items of the first type and 7 items of the third type (3·6 + 7·8 = 74). Then the ranger should fly to planet Earth and sell there all the items he has bought. He gets 3·9 + 7·9 = 90 units of money for the items, he should give 74 of them for the loan. The resulting profit equals 16 units of money. We cannot get more profit in this case.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 10000002, INF = 1000 * 1000 * 1000;
const long double eps = 1e-9;
struct node {
int a, b, c, idx;
node(int aa, int bb, int cc, int i) {
a = aa;
c = cc;
b = bb;
idx = i;
}
node(){};
};
vector<vector<node>> p;
int main() {
int n, m, k;
cin >> n >> m >> k;
p.resize(n);
for (int i = 0; i < n; ++i) {
string s;
cin >> s;
p[i].resize(m);
for (int j = 0; j < m; ++j) {
int a, b, c;
cin >> a >> b >> c;
p[i][j] = node(a, b, c, i);
}
}
int ans = 0;
for (int f = 0; f < n; ++f) {
for (int s = 0; s < n; ++s) {
vector<pair<int, int>> a(m);
int tmp = 0;
for (int i = 0; i < m; ++i) {
a[i] = make_pair(p[s][i].b - p[f][i].a, i);
}
sort(a.begin(), a.end());
reverse(a.begin(), a.end());
int cnt = k;
for (int i = 0; i < m; ++i) {
if (a[i].first < 0) break;
int kol = min(p[f][a[i].second].c, cnt);
tmp += kol * a[i].first;
cnt -= kol;
}
ans = max(ans, tmp);
}
}
cout << ans;
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
While resting on the ship after the "Russian Code Cup" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size n × m, consisting of positive integers such that the sum of the squares of numbers for each row and each column was also a square.
Since checking the correctness of the table manually is difficult, Misha asks you to make each number in the table to not exceed 108.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the size of the table.
Output
Print the table that meets the condition: n lines containing m integers, separated by spaces. If there are multiple possible answers, you are allowed to print anyone. It is guaranteed that there exists at least one correct answer.
Examples
Input
1 1
Output
1
Input
1 2
Output
3 4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using DO = double;
using LL = long long;
using VI = vector<int>;
using pii = pair<int, int>;
const int mod = 1e9 + 7;
int power(int a, int b, int c = mod) {
int ans = 1;
for (; b; b >>= 1, a = (LL)a * a % c) {
if (b & 1) ans = (LL)ans * a % c;
}
return ans;
}
int a[111][111];
int main() {
int n, m;
scanf("%d%d", &n, &m);
if (n == 1) {
if (m == 2) {
puts("3 4");
return 0;
}
if (m == 1) {
puts("1");
return 0;
}
if (m % 2)
a[1][m - 1] = 2;
else
a[1][m - 1] = 1;
for (int i = 1; i < m - 1; i++) a[1][i] = 1;
int s = m - 1;
if (s % 2 == 0) s += 3;
s /= 2;
a[1][m] = s;
for (int i = 1; i <= m; i++) cout << a[1][i] << ' ';
return 0;
}
if (n == 2) {
if (m == 2) {
puts("3 4");
puts("4 3");
return 0;
}
if (m == 1) {
puts("3\n4");
return 0;
}
if (m % 2)
a[1][m - 1] = 2;
else
a[1][m - 1] = 1;
for (int i = 1; i < m - 1; i++) a[1][i] = 1;
int s = m - 1;
if (s % 2 == 0) s += 3;
s /= 2;
a[1][m] = s;
for (int i = 1; i <= m; i++) cout << a[1][i] * 3 << ' ';
cout << endl;
for (int i = 1; i <= m; i++) cout << a[1][i] * 4 << ' ';
return 0;
}
if (m == 2) {
if (n % 2)
a[n - 1][1] = 2;
else
a[n - 1][1] = 1;
for (int i = 1; i < n - 1; i++) a[i][1] = 1;
int s = n - 1;
if (s % 2 == 0) s += 3;
s /= 2;
a[n][1] = s;
for (int i = 1; i <= n; i++)
cout << a[i][1] * 3 << ' ' << a[i][1] * 4 << endl;
return 0;
}
if (n % 2)
a[n - 1][1] = 2;
else
a[n - 1][1] = 1;
for (int i = 1; i < n - 1; i++) a[i][1] = 1;
int s = n - 1;
if (s % 2 == 0) s += 3;
s /= 2;
a[n][1] = s;
if (m == 1) {
for (int i = 1; i <= n; i++) cout << a[i][1] << endl;
return 0;
}
if (m % 2)
a[1][m - 1] = 2;
else
a[1][m - 1] = 1;
for (int i = 1; i < m - 1; i++) a[1][i] = 1;
s = m - 1;
if (s % 2 == 0) s += 3;
s /= 2;
a[1][m] = s;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) printf("%d ", a[i][1] * a[1][j]);
puts("");
}
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
You are working for an administration office of the International Center for Picassonian Cubism (ICPC), which plans to build a new art gallery for young artists. The center is organizing an architectural design competition to find the best design for the new building.
Submitted designs will look like a screenshot of a well known game as shown below.
<image>
This is because the center specifies that the building should be constructed by stacking regular units called pieces, each of which consists of four cubic blocks. In addition, the center requires the competitors to submit designs that satisfy the following restrictions.
* All the pieces are aligned. When two pieces touch each other, the faces of the touching blocks must be placed exactly at the same position.
* All the pieces are stable. Since pieces are merely stacked, their centers of masses must be carefully positioned so as not to collapse.
* The pieces are stacked in a tree-like form in order to symbolize boundless potentiality of young artists. In other words, one and only one piece touches the ground, and each of other pieces touches one and only one piece on its bottom faces.
* The building has a flat shape. This is because the construction site is a narrow area located between a straight moat and an expressway where no more than one block can be placed between the moat and the expressway as illustrated below.
<image>
It will take many days to fully check stability of designs as it requires complicated structural calculation. Therefore, you are asked to quickly check obviously unstable designs by focusing on centers of masses. The rules of your quick check are as follows.
Assume the center of mass of a block is located at the center of the block, and all blocks have the same weight. We denote a location of a block by xy-coordinates of its left-bottom corner. The unit length is the edge length of a block.
Among the blocks of the piece that touch another piece or the ground on their bottom faces, let xL be the leftmost x-coordinate of the leftmost block, and let xR be the rightmost x-coordinate of the rightmost block. Let the x-coordinate of its accumulated center of mass of the piece be M, where the accumulated center of mass of a piece P is the center of the mass of the pieces that are directly and indirectly supported by P, in addition to P itself. Then the piece is stable, if and only if xL < M < xR. Otherwise, it is unstable. A design of a building is unstable if any of its pieces is unstable.
Note that the above rules could judge some designs to be unstable even if it would not collapse in reality. For example, the left one of the following designs shall be judged to be unstable.
<image> | | <image>
---|---|---
Also note that the rules judge boundary cases to be unstable. For example, the top piece in the above right design has its center of mass exactly above the right end of the bottom piece. This shall be judged to be unstable.
Write a program that judges stability of each design based on the above quick check rules.
Input
The input is a sequence of datasets. The end of the input is indicated by a line containing two zeros separated by a space. Each dataset, which represents a front view of a building, is formatted as follows.
> w h
> p0(h-1)p1(h-1)...p(w-1)(h-1)
> ...
> p01p11...p(w-1)1
> p00p10...p(w-1)0
>
The integers w and h separated by a space are the numbers of columns and rows of the layout, respectively. You may assume 1 ≤ w ≤ 10 and 1 ≤ h ≤ 60. The next h lines specify the placement of the pieces. The character pxy indicates the status of a block at (x,y), either ``.`', meaning empty, or one digit character between ``1`' and ``9`', inclusive, meaning a block of a piece. (As mentioned earlier, we denote a location of a block by xy-coordinates of its left-bottom corner.)
When two blocks with the same number touch each other by any of their top, bottom, left or right face, those blocks are of the same piece. (Note that there might be two different pieces that are denoted by the same number.) The bottom of a block at (x,0) touches the ground.
You may assume that the pieces in each dataset are stacked in a tree-like form.
Output
For each dataset, output a line containing a word `STABLE` when the design is stable with respect to the above quick check rules. Otherwise, output `UNSTABLE`. The output should be written with uppercase letters, and should not contain any other extra characters.
Sample Input
4 5
..33
..33
2222
..1.
.111
5 7
....1
.1..1
.1..1
11..1
.2222
..111
...1.
3 6
.3.
233
23.
22.
.11
.11
4 3
2222
..11
..11
4 5
.3..
33..
322.
2211
.11.
3 3
222
2.1
111
3 4
11.
11.
.2.
222
3 4
.11
.11
.2.
222
2 7
11
.1
21
22
23
.3
33
2 3
1.
11
.1
0 0
Output for the Sample Input
STABLE
STABLE
STABLE
UNSTABLE
STABLE
STABLE
UNSTABLE
UNSTABLE
UNSTABLE
UNSTABLE
Example
Input
4 5
..33
..33
2222
..1.
.111
5 7
....1
.1..1
.1..1
11..1
.2222
..111
...1.
3 6
.3.
233
23.
22.
.11
.11
4 3
2222
..11
..11
4 5
.3..
33..
322.
2211
.11.
3 3
222
2.1
111
3 4
11.
11.
.2.
222
3 4
.11
.11
.2.
222
2 7
11
.1
21
22
23
.3
33
2 3
1.
11
.1
0 0
Output
STABLE
STABLE
STABLE
UNSTABLE
STABLE
STABLE
UNSTABLE
UNSTABLE
UNSTABLE
UNSTABLE
### Response
```cpp
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
#include <numeric>
using namespace std;
#define rep(i, n) for(int i=0; i<(n); ++i)
#define all(c) (c).begin(), (c).end()
#define mp(a, b) make_pair(a, b)
const double eps = 1e-8;
const int dx[] = {-1, 0, 1, 0}, dy[] = {0, -1, 0, 1};
template<typename T> inline void chmax(T& t, T f){if(t < f)t = f;}
template<typename T> inline void chmin(T& t, T f){if(t > f)t = f;}
int h, w;
vector<string> bldg;
vector<vector<bool> > vis;
inline bool inrect(int x, int y){
return 0 <= x && x < h && 0 <= y && y < w;
}
pair<double, int> dfs(int sx, int sy){
vis[sx][sy] = true;
vector<double> ys;
vector<pair<int, int> > on;
int ly = w, ry = 0;
queue<pair<int, int> > q;
for(q.emplace(sx, sy); !q.empty();){
int x = q.front().first, y = q.front().second; q.pop();
ys.emplace_back(y + .5);
if(x && !vis[x-1][y] && bldg[x-1][y] != '.' && bldg[x-1][y] != bldg[sx][sy]){
on.emplace_back(x-1, y);
}
if(x == h-1 || (bldg[x+1][y] != '.' && bldg[x+1][y] != bldg[sx][sy])){
chmin(ly, y); chmax(ry, y+1);
}
rep(i, 4){
int nx = x + dx[i], ny = y + dy[i];
if(!inrect(nx, ny) || vis[nx][ny] || bldg[nx][ny] != bldg[sx][sy])continue;
vis[nx][ny] = true;
q.emplace(nx, ny);
}
}
double M = accumulate(all(ys), 0.);
int n = (int)ys.size();
for(auto p: on)if(!vis[p.first][p.second]){
pair<double, int> t = dfs(p.first, p.second);
if(t.second == -1)return mp(M, -1);
M += t.first; n += t.second;
}
return ly < M/n - eps && M/n + eps < ry? mp(M, n): mp(M, -1);
}
const char* solve(){
vis.assign(h, vector<bool>(w, false));
int y = find_if_not(all(bldg[h-1]), [](const char& c){return c == '.';}) - bldg[h-1].begin();
return dfs(h-1, y).second != -1? "STABLE": "UNSTABLE";
}
int main(){
while(cin >> w >> h, w|h){
bldg.assign(h, "");
rep(i, h)cin >> bldg[i];
cout << solve() << '\n';
}
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Alfred wants to buy a toy moose that costs c dollars. The store doesn’t give change, so he must give the store exactly c dollars, no more and no less. He has n coins. To make c dollars from his coins, he follows the following algorithm: let S be the set of coins being used. S is initially empty. Alfred repeatedly adds to S the highest-valued coin he has such that the total value of the coins in S after adding the coin doesn’t exceed c. If there is no such coin, and the value of the coins in S is still less than c, he gives up and goes home. Note that Alfred never removes a coin from S after adding it.
As a programmer, you might be aware that Alfred’s algorithm can fail even when there is a set of coins with value exactly c. For example, if Alfred has one coin worth $3, one coin worth $4, and two coins worth $5, and the moose costs $12, then Alfred will add both of the $5 coins to S and then give up, since adding any other coin would cause the value of the coins in S to exceed $12. Of course, Alfred could instead combine one $3 coin, one $4 coin, and one $5 coin to reach the total.
Bob tried to convince Alfred that his algorithm was flawed, but Alfred didn’t believe him. Now Bob wants to give Alfred some coins (in addition to those that Alfred already has) such that Alfred’s algorithm fails. Bob can give Alfred any number of coins of any denomination (subject to the constraint that each coin must be worth a positive integer number of dollars). There can be multiple coins of a single denomination. He would like to minimize the total value of the coins he gives Alfred. Please find this minimum value. If there is no solution, print "Greed is good". You can assume that the answer, if it exists, is positive. In other words, Alfred's algorithm will work if Bob doesn't give him any coins.
Input
The first line contains c (1 ≤ c ≤ 200 000) — the price Alfred wants to pay. The second line contains n (1 ≤ n ≤ 200 000) — the number of coins Alfred initially has. Then n lines follow, each containing a single integer x (1 ≤ x ≤ c) representing the value of one of Alfred's coins.
Output
If there is a solution, print the minimum possible total value of the coins in a solution. Otherwise, print "Greed is good" (without quotes).
Examples
Input
12
3
5
3
4
Output
5
Input
50
8
1
2
4
8
16
37
37
37
Output
Greed is good
Note
In the first sample, Bob should give Alfred a single coin worth $5. This creates the situation described in the problem statement.
In the second sample, there is no set of coins that will cause Alfred's algorithm to fail.
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("no-stack-protector")
#pragma GCC target("sse,sse2,ssse3,sse3,sse4,popcnt,avx,mmx,abm,tune=native")
using namespace std;
namespace output {
void __(short x) { cout << x; }
void __(unsigned x) { cout << x; }
void __(int x) { cout << x; }
void __(long long x) { cout << x; }
void __(unsigned long long x) { cout << x; }
void __(double x) { cout << x; }
void __(long double x) { cout << x; }
void __(char x) { cout << x; }
void __(const char* x) { cout << x; }
void __(const string& x) { cout << x; }
void __(bool x) { cout << (x ? "true" : "false"); }
template <class S, class T>
void __(const pair<S, T>& x) {
__(1 ? "(" : ""), __(x.first), __(1 ? ", " : " "), __(x.second),
__(1 ? ")" : "");
}
template <class T>
void __(const vector<T>& x) {
__(1 ? "{" : "");
bool _ = 0;
for (const auto& v : x) __(_ ? 1 ? ", " : " " : ""), __(v), _ = 1;
__(1 ? "}" : "");
}
template <class T>
void __(const set<T>& x) {
__(1 ? "{" : "");
bool _ = 0;
for (const auto& v : x) __(_ ? 1 ? ", " : " " : ""), __(v), _ = 1;
__(1 ? "}" : "");
}
template <class T>
void __(const multiset<T>& x) {
__(1 ? "{" : "");
bool _ = 0;
for (const auto& v : x) __(_ ? 1 ? ", " : " " : ""), __(v), _ = 1;
__(1 ? "}" : "");
}
template <class S, class T>
void __(const map<S, T>& x) {
__(1 ? "{" : "");
bool _ = 0;
for (const auto& v : x) __(_ ? 1 ? ", " : " " : ""), __(v), _ = 1;
__(1 ? "}" : "");
}
void pr() { cout << "\n"; }
template <class S, class... T>
void pr(const S& a, const T&... b) {
__(a);
if (sizeof...(b)) __(' ');
pr(b...);
}
} // namespace output
using namespace output;
const int MN = 2e5 + 5;
int N, C, T, i, j, arr[MN], cnt[MN], nxt[MN], ans;
map<int, int> pos;
bool solve(int n, int lim) {
if (!n) return 1;
auto it = pos.upper_bound(min(n, lim));
if (it == pos.begin()) return 0;
it--;
int c = it->first;
int r = min(cnt[c], n / c);
return solve(n - r * c, c - 1);
}
int main() {
scanf("%d%d", &C, &N);
for (i = 1; i <= N; i++) {
scanf("%d", &arr[i]);
cnt[arr[i]]++;
pos[arr[i]]++;
}
for (i = 1; i <= C; i++) {
pos[i]++;
cnt[i]++;
if (!solve(C, C)) {
printf("%d\n", i);
return 0;
}
pos[i]--;
cnt[i]--;
if (!pos[i]) pos.erase(i);
}
printf("Greed is good\n");
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
There are several rectangular sheets placed on a flat surface. Create a program to find the area and perimeter of the part covered by these sheets.
However, when the plane is regarded as the coordinate plane, the arrangement of the sheets shall satisfy the following conditions (1) and (2).
(1) The x and y coordinates of the four vertices of the rectangle on each sheet are all integers from 0 to 10000, and each side of the rectangle is parallel to the x-axis or y-axis.
(2) The number of sheets is at most 10,000 or less.
The number n of rectangles and the integer r indicating the type of problem are separated by a space in the first line of the input data. In each line after the second line, the coordinates of the lower left vertex of each sheet (x1, y1) and The coordinates of the upper right vertex coordinates (x2, y2) are written in the order of x1, y1, x2, y2, separated by a blank.
The output outputs the area on the first line when r = 1, the area on the first line when r = 2, and the perimeter on the second line. In either case, insert a line break at the end.
In 40% of the test data, the coordinates of the vertices of the rectangle are 0 or more and 100 or less, and 1/2 of them is the problem of finding only the area. Furthermore, 1/2 of the whole is the problem of finding only the area.
Input Example 1 | Input Example 2 | Input Example 3 | Input Example 4
--- | --- | --- | ---
|
5 1 | 5 2 | 2 2 | 3 2
0 0 3 2 | 0 0 3 2 | 0 0 8 9 | 2 2 8 8
1 1 2 5 | 1 1 2 5 | 0 0 9 8 | 3 0 4 9
0 4 6 5 | 0 4 6 5 | | 5 0 7 9
3 3 5 6 | 3 3 5 6 | |
5 0 7 6 | 5 0 7 6 | |
Output example 1 | Output example 2 | Output example 3 | Output example 4
29 | 29 | 80 | 45
38 | 36 | 36
input
The input consists of multiple datasets. Input ends when both n and r are 0. The number of datasets does not exceed 10.
output
For each dataset, the area is output on the first line when r = 1, the area is output on the first line when r = 2, and the perimeter is output on the second line.
Example
Input
5 1
0 0 3 2
1 1 2 5
0 4 6 5
3 3 5 6
5 0 7 6
5 2
0 0 3 2
1 1 2 5
0 4 6 5
3 3 5 6
5 0 7 6
2 2
0 0 8 9
0 0 9 8
3 2
2 2 8 8
3 0 4 9
5 0 7 9
0 0
Output
29
29
38
80
36
45
36
### Response
```cpp
#include<iostream>
#include<vector>
#include<algorithm>
#include<cstdio>
#define F first
#define S second
using namespace std;
typedef pair<int,int> P;
bool cmp_x( const pair<P,P> &p , const pair<P,P> &q ){
return p.F < q.F;
}
bool cmp_y( const pair<P,P> &p , const pair<P,P> &q ){
return p.S < q.S;
}
int main(void){
int n,r,x1,x2,y1,y2;
while(cin >> n >> r){
if(n==0 && r==0)break;
vector<pair<P,P> > in;
for(int i=0;i<n;i++){
scanf("%d %d %d %d",&x1,&y1,&x2,&y2);
in.push_back(make_pair(make_pair(x1,x2), make_pair(y1,y2)));
}
sort(in.begin(),in.end(),cmp_x);
int S=0,L=0;
vector<P>v;
for(int i=0;i+1<10001;i++){
v.clear();
for(int j=0;j<n;j++){
if(in[j].S.S>=i+1 && i>=in[j].S.F){
v.push_back(make_pair(in[j].F.F,in[j].F.S));
}
}
if(v.size()!=0){
//sort(v.begin(),v.end());
int b=v[0].F,e=v[0].S;
for(int j=1;j<v.size();j++){
int B=v[j].F,E=v[j].S;
if(e>=B)e=max(e,E);
else S+=e-b, b=B, e=E, L+=2;
}
S+=e-b, L+=2;
}
}
cout << S << endl;
if(r==2){
sort(in.begin(),in.end(),cmp_y);
for(int i=0;i+1<10001;i++){
v.clear();
for(int j=0;j<n;j++){
if(in[j].F.S>=i+1 && i>=in[j].F.F)
v.push_back(make_pair(in[j].S.F,in[j].S.S));
}
if(v.size()!=0){
//sort(v.begin(),v.end());
int b=v[0].F,e=v[0].S;
for(int j=1;j<v.size();j++){
int B=v[j].F,E=v[j].S;
if(e>=B)e=max(e,E);
else b=B, e=E, L+=2;
}
L+=2;
}
}
cout << L << endl;
}
}
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
You are given a text consisting of n lines. Each line contains some space-separated words, consisting of lowercase English letters.
We define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowels: 'a', 'e', 'i', 'o', 'u' and 'y'.
Each word of the text that contains at least one vowel can be divided into syllables. Each character should be a part of exactly one syllable. For example, the word "mamma" can be divided into syllables as "ma" and "mma", "mam" and "ma", and "mamm" and "a". Words that consist of only consonants should be ignored.
The verse patterns for the given text is a sequence of n integers p1, p2, ..., pn. Text matches the given verse pattern if for each i from 1 to n one can divide words of the i-th line in syllables in such a way that the total number of syllables is equal to pi.
You are given the text and the verse pattern. Check, if the given text matches the given verse pattern.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of lines in the text.
The second line contains integers p1, ..., pn (0 ≤ pi ≤ 100) — the verse pattern.
Next n lines contain the text itself. Text consists of lowercase English letters and spaces. It's guaranteed that all lines are non-empty, each line starts and ends with a letter and words are separated by exactly one space. The length of each line doesn't exceed 100 characters.
Output
If the given text matches the given verse pattern, then print "YES" (without quotes) in the only line of the output. Otherwise, print "NO" (without quotes).
Examples
Input
3
2 2 3
intel
code
ch allenge
Output
YES
Input
4
1 2 3 1
a
bcdefghi
jklmnopqrstu
vwxyz
Output
NO
Input
4
13 11 15 15
to be or not to be that is the question
whether tis nobler in the mind to suffer
the slings and arrows of outrageous fortune
or to take arms against a sea of troubles
Output
YES
Note
In the first sample, one can split words into syllables in the following way:
in-tel
co-de
ch al-len-ge
Since the word "ch" in the third line doesn't contain vowels, we can ignore it. As the result we get 2 syllabels in first two lines and 3 syllables in the third one.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int p[100];
char in[1111];
int main() {
int n;
bool ans = true;
fgets(in, 1111, stdin);
sscanf(in, "%d", &n);
for (int i = 0; i < n; i++) scanf("%d", p + i);
fgets(in, 11, stdin);
for (int z = 0; z < n; z++) {
fgets(in, 1111, stdin);
if (!ans) continue;
int v = 0;
for (int i = 0; in[i]; i++) {
if (in[i] == 'a' || in[i] == 'e' || in[i] == 'i' || in[i] == 'o' ||
in[i] == 'u' || in[i] == 'y')
v++;
}
if (v != p[z]) ans = false;
}
puts(ans ? "YES" : "NO");
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Vasily the bear has got a sequence of positive integers a1, a2, ..., an. Vasily the Bear wants to write out several numbers on a piece of paper so that the beauty of the numbers he wrote out was maximum.
The beauty of the written out numbers b1, b2, ..., bk is such maximum non-negative integer v, that number b1 and b2 and ... and bk is divisible by number 2v without a remainder. If such number v doesn't exist (that is, for any non-negative integer v, number b1 and b2 and ... and bk is divisible by 2v without a remainder), the beauty of the written out numbers equals -1.
Tell the bear which numbers he should write out so that the beauty of the written out numbers is maximum. If there are multiple ways to write out the numbers, you need to choose the one where the bear writes out as many numbers as possible.
Here expression x and y means applying the bitwise AND operation to numbers x and y. In programming languages C++ and Java this operation is represented by "&", in Pascal — by "and".
Input
The first line contains integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ a1 < a2 < ... < an ≤ 109).
Output
In the first line print a single integer k (k > 0), showing how many numbers to write out. In the second line print k integers b1, b2, ..., bk — the numbers to write out. You are allowed to print numbers b1, b2, ..., bk in any order, but all of them must be distinct. If there are multiple ways to write out the numbers, choose the one with the maximum number of numbers to write out. If there still are multiple ways, you are allowed to print any of them.
Examples
Input
5
1 2 3 4 5
Output
2
4 5
Input
3
1 2 4
Output
1
4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<int> ans;
int main() {
int n, exp = 0;
cin >> n;
int v[n], m = 0;
for (int i = 0; i < n; i++) {
cin >> v[i];
m = max(m, v[i]);
}
int cont = 0, a;
bool ok, deu;
while (m >= (1 << cont)) {
deu = true;
for (int j = 0; j < cont; j++) {
ok = false;
for (int i = 0; i < n; i++) {
if ((v[i] >> cont) % 2 == 1 && (v[i] >> j) % 2 == 0) {
ok = true;
}
}
if (!ok) deu = false;
}
if (deu) exp = cont;
cont++;
}
for (int i = 0; i < n; i++)
if ((v[i] >> exp) % 2 == 1) ans.push_back(v[i]);
cout << ans.size() << endl;
for (int i = 0; i < ans.size(); i++) cout << ans[i] << " ";
cout << endl;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
You might have remembered Theatre square from the [problem 1A](https://codeforces.com/problemset/problem/1/A). Now it's finally getting repaved.
The square still has a rectangular shape of n × m meters. However, the picture is about to get more complicated now. Let a_{i,j} be the j-th square in the i-th row of the pavement.
You are given the picture of the squares:
* if a_{i,j} = "*", then the j-th square in the i-th row should be black;
* if a_{i,j} = ".", then the j-th square in the i-th row should be white.
The black squares are paved already. You have to pave the white squares. There are two options for pavement tiles:
* 1 × 1 tiles — each tile costs x burles and covers exactly 1 square;
* 1 × 2 tiles — each tile costs y burles and covers exactly 2 adjacent squares of the same row. Note that you are not allowed to rotate these tiles or cut them into 1 × 1 tiles.
You should cover all the white squares, no two tiles should overlap and no black squares should be covered by tiles.
What is the smallest total price of the tiles needed to cover all the white squares?
Input
The first line contains a single integer t (1 ≤ t ≤ 500) — the number of testcases. Then the description of t testcases follow.
The first line of each testcase contains four integers n, m, x and y (1 ≤ n ≤ 100; 1 ≤ m ≤ 1000; 1 ≤ x, y ≤ 1000) — the size of the Theatre square, the price of the 1 × 1 tile and the price of the 1 × 2 tile.
Each of the next n lines contains m characters. The j-th character in the i-th line is a_{i,j}. If a_{i,j} = "*", then the j-th square in the i-th row should be black, and if a_{i,j} = ".", then the j-th square in the i-th row should be white.
It's guaranteed that the sum of n × m over all testcases doesn't exceed 10^5.
Output
For each testcase print a single integer — the smallest total price of the tiles needed to cover all the white squares in burles.
Example
Input
4
1 1 10 1
.
1 2 10 1
..
2 1 10 1
.
.
3 3 3 7
..*
*..
.*.
Output
10
1
20
18
Note
In the first testcase you are required to use a single 1 × 1 tile, even though 1 × 2 tile is cheaper. So the total price is 10 burles.
In the second testcase you can either use two 1 × 1 tiles and spend 20 burles or use a single 1 × 2 tile and spend 1 burle. The second option is cheaper, thus the answer is 1.
The third testcase shows that you can't rotate 1 × 2 tiles. You still have to use two 1 × 1 tiles for the total price of 20.
In the fourth testcase the cheapest way is to use 1 × 1 tiles everywhere. The total cost is 6 ⋅ 3 = 18.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n, m, x, y;
cin >> n >> m >> x >> y;
int ans = 0;
char ch;
if (x <= y / 2) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cin >> ch;
if (ch == '.') {
ans += x;
}
}
}
cout << ans << endl;
return;
}
bool flag = false;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cin >> ch;
if (ch == '.') {
if (flag) {
ans += y;
flag = false;
} else {
flag = true;
}
} else {
if (flag) {
ans += x;
}
flag = false;
}
}
if (flag) {
ans += x;
flag = false;
}
}
cout << ans << endl;
}
int main() {
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
You are given N points in the xy-plane. You have a circle of radius one and move it on the xy-plane, so as to enclose as many of the points as possible. Find how many points can be simultaneously enclosed at the maximum. A point is considered enclosed by a circle when it is inside or on the circle.
<image>
Fig 1. Circle and Points
Input
The input consists of a series of data sets, followed by a single line only containing a single character '0', which indicates the end of the input. Each data set begins with a line containing an integer N, which indicates the number of points in the data set. It is followed by N lines describing the coordinates of the points. Each of the N lines has two decimal fractions X and Y, describing the x- and y-coordinates of a point, respectively. They are given with five digits after the decimal point.
You may assume 1 <= N <= 300, 0.0 <= X <= 10.0, and 0.0 <= Y <= 10.0. No two points are closer than 0.0001. No two points in a data set are approximately at a distance of 2.0. More precisely, for any two points in a data set, the distance d between the two never satisfies 1.9999 <= d <= 2.0001. Finally, no three points in a data set are simultaneously very close to a single circle of radius one. More precisely, let P1, P2, and P3 be any three points in a data set, and d1, d2, and d3 the distances from an arbitrarily selected point in the xy-plane to each of them respectively. Then it never simultaneously holds that 0.9999 <= di <= 1.0001 (i = 1, 2, 3).
Output
For each data set, print a single line containing the maximum number of points in the data set that can be simultaneously enclosed by a circle of radius one. No other characters including leading and trailing spaces should be printed.
Example
Input
3
6.47634 7.69628
5.16828 4.79915
6.69533 6.20378
6
7.15296 4.08328
6.50827 2.69466
5.91219 3.86661
5.29853 4.16097
6.10838 3.46039
6.34060 2.41599
8
7.90650 4.01746
4.10998 4.18354
4.67289 4.01887
6.33885 4.28388
4.98106 3.82728
5.12379 5.16473
7.84664 4.67693
4.02776 3.87990
20
6.65128 5.47490
6.42743 6.26189
6.35864 4.61611
6.59020 4.54228
4.43967 5.70059
4.38226 5.70536
5.50755 6.18163
7.41971 6.13668
6.71936 3.04496
5.61832 4.23857
5.99424 4.29328
5.60961 4.32998
6.82242 5.79683
5.44693 3.82724
6.70906 3.65736
7.89087 5.68000
6.23300 4.59530
5.92401 4.92329
6.24168 3.81389
6.22671 3.62210
0
Output
2
5
5
11
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<n;++i)
struct Point{double x,y;};
double dist(Point a,Point b) {return sqrt(pow(a.x-b.x,2)+pow(a.y-b.y,2));}
int main(void){
int N;
while(cin>>N,N){
vector<Point> p(N);
int maxcnt=1;
rep(i,N)cin>>p[i].x>>p[i].y;
rep(i,N){
for(int j=i+1;j<N;j++){
double d = dist(p[i],p[j]);
if(d>2.0)continue;
int sign[]={-1,1};
rep(s,2){
Point C;
C.x = p[i].x + cos(atan2(p[j].y-p[i].y,p[j].x-p[i].x) + sign[s]*acos(d/2.0));
C.y = p[i].y + sin(atan2(p[j].y-p[i].y,p[j].x-p[i].x) + sign[s]*acos(d/2.0));
int cnt=0;
rep(k,N) cnt += (pow(C.x-p[k].x,2) + pow(C.y-p[k].y,2) <= 1.0001);
if(maxcnt<cnt)maxcnt=cnt;
}
}
}
cout<<maxcnt<<endl;
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
You have a string s consisting of n characters. Each character is either 0 or 1.
You can perform operations on the string. Each operation consists of two steps:
1. select an integer i from 1 to the length of the string s, then delete the character s_i (the string length gets reduced by 1, the indices of characters to the right of the deleted one also get reduced by 1);
2. if the string s is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix).
Note that both steps are mandatory in each operation, and their order cannot be changed.
For example, if you have a string s = 111010, the first operation can be one of the following:
1. select i = 1: we'll get 111010 → 11010 → 010;
2. select i = 2: we'll get 111010 → 11010 → 010;
3. select i = 3: we'll get 111010 → 11010 → 010;
4. select i = 4: we'll get 111010 → 11110 → 0;
5. select i = 5: we'll get 111010 → 11100 → 00;
6. select i = 6: we'll get 111010 → 11101 → 01.
You finish performing operations when the string s becomes empty. What is the maximum number of operations you can perform?
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the string s.
The second line contains string s of n characters. Each character is either 0 or 1.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print a single integer — the maximum number of operations you can perform.
Example
Input
5
6
111010
1
0
1
1
2
11
6
101010
Output
3
1
1
1
3
Note
In the first test case, you can, for example, select i = 2 and get string 010 after the first operation. After that, you can select i = 3 and get string 1. Finally, you can only select i = 1 and get empty string.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
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(long double t) { cerr << t; }
void _print(double t) { cerr << t; }
void _print(unsigned long long t) { cerr << t; }
template <class T, class V>
void _print(T a[], V sz);
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 << "}" << endl;
}
template <class T, class V>
void _print(T a[], V sz) {
for (V i = 0; i < sz; i++) {
_print(a[i]);
cerr << " ";
}
cerr << endl;
}
template <class T>
void _print(vector<T> v) {
cerr << "[ ";
for (T i : v) {
_print(i);
cerr << " ";
}
cerr << "]" << endl;
}
template <class T>
void _print(set<T> v) {
cerr << "[ ";
for (T i : v) {
_print(i);
cerr << " ";
}
cerr << "]" << endl;
}
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 << "]" << endl;
}
void _printall(long long t) { cout << t; }
void _printall(int t) { cout << t; }
void _printall(string t) { cout << t; }
void _printall(char t) { cout << t; }
void _printall(long double t) { cout << t; }
void _printall(double t) { cout << t; }
void _printall(unsigned long long t) { cout << t; }
template <class T, class V>
void _printall(T a[], V sz);
template <class T, class V>
void _printall(pair<T, V> p);
template <class T>
void _printall(vector<T> v);
template <class T>
void _printall(set<T> v);
template <class T, class V>
void _printall(map<T, V> v);
template <class T>
void _printall(multiset<T> v);
template <class T, class V>
void _printall(T a[], V sz) {
for (V i = 0; i < sz; i++) {
_printall(a[i]);
cout << " ";
}
cout << endl;
}
template <class T, class V>
void _printall(pair<T, V> p) {
_printall(p.ff);
cout << ",";
_printall(p.ss);
}
template <class T>
void _printall(vector<T> v) {
for (T i : v) {
_printall(i);
cout << " ";
}
cout << endl;
}
template <class T>
void _printall(set<T> v) {
for (T i : v) {
_printall(i);
cout << " ";
}
cout << endl;
}
template <class T>
void _printall(multiset<T> v) {
for (T i : v) {
_printall(i);
cout << " ";
}
cout << endl;
}
template <class T, class V>
void _printall(map<T, V> v) {
for (auto i : v) {
_printall(i);
cout << " ";
}
cout << endl;
}
long long MAXN = 200001;
long long spf[200001];
void sieve() {
spf[1] = 1;
for (int i = 2; i < MAXN; i++) {
spf[i] = i;
}
for (long long i = 4; i < MAXN; i += 2) {
spf[i] = 2;
}
for (long long i = 3; i * i < MAXN; i++) {
if (spf[i] == i) {
for (long long j = i * i; j < MAXN; j += i) {
if (spf[j] == j) spf[j] = i;
}
}
}
}
vector<long long> getFactorization(long long x) {
vector<long long> ret;
while (x != 1) {
ret.push_back(spf[x]);
x = x / spf[x];
}
return ret;
}
void solve() {
long long n;
cin >> n;
string s;
cin >> s;
vector<int> pre;
int cnt = 0;
for (int i = 0; i < n; i++) {
pre.push_back(1);
}
for (int i = n - 2; i >= 0; i--) {
if (s[i] == s[i + 1]) {
pre[i] = pre[i + 1] + 1;
}
}
reverse(pre.begin(), pre.end());
vector<int> fin;
for (int i = 0; i < pre.size() - 1; i++) {
if (pre[i] == 1 && pre[i + 1] == 1) {
fin.push_back(pre[i]);
} else if (pre[i] >= 1 && pre[i + 1] == 1) {
fin.push_back(pre[i]);
}
}
if (pre[n - 1] >= 1) {
fin.push_back(pre[n - 1]);
}
int ind1 = fin.size() - 1;
int ind2 = fin.size() - 1;
while (pre.size() != 0 && ind1 >= 0 && ind2 >= 0) {
if (fin[ind1] > 1) {
cnt++;
fin.pop_back();
if (ind2 == ind1) {
ind2--;
}
ind1--;
} else {
while (fin[ind2] == 1) {
ind2--;
}
if (ind2 < 0) {
break;
} else {
cnt++;
fin[ind2]--;
fin.pop_back();
ind1--;
}
}
}
if (pre.size() != 0) {
cnt += (fin.size() + 1) / 2;
}
cout << cnt << endl;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
long long t = 1;
cin >> t;
while (t--) {
solve();
}
cerr << "time taken : " << (float)clock() / CLOCKS_PER_SEC << " secs" << endl;
return 0;
}
``` |
Subsets and Splits