text
stringlengths 424
69.5k
|
---|
### Prompt
Construct a CPP code solution to the problem outlined:
This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline.
You are given string s consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk (1 β€ p1 < p2 < ... < pk β€ |s|) a subsequence of string s = s1s2... s|s|, where |s| is the length of string s. For example, strings "abcb", "b" and "abacaba" are subsequences of string "abacaba".
String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y| if either |x| > |y| and x1 = y1, x2 = y2, ..., x|y| = y|y|, or there exists such number r (r < |x|, r < |y|) that x1 = y1, x2 = y2, ..., xr = yr and xr + 1 > yr + 1. Characters in the strings are compared according to their ASCII codes. For example, string "ranger" is lexicographically larger than string "racecar" and string "poster" is lexicographically larger than string "post".
String s = s1s2... s|s| is a palindrome if it matches string rev(s) = s|s|s|s| - 1... s1. In other words, a string is a palindrome if it reads the same way from left to right and from right to left. For example, palindromic strings are "racecar", "refer" and "z".
Input
The only input line contains a non-empty string s consisting of lowercase English letters only. Its length does not exceed 10.
Output
Print the lexicographically largest palindromic subsequence of string s.
Examples
Input
radar
Output
rr
Input
bowwowwow
Output
wwwww
Input
codeforces
Output
s
Input
mississipp
Output
ssss
Note
Among all distinct subsequences of string "radar" the following ones are palindromes: "a", "d", "r", "aa", "rr", "ada", "rar", "rdr", "raar" and "radar". The lexicographically largest of them is "rr".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
map<char, int> m;
for (int i = 0; i < s.length(); i++) {
m[s[i]]++;
}
sort(s.begin(), s.end());
cout << string(m[s[s.length() - 1]], s[s.length() - 1]);
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
"You must lift the dam. With a lever. I will give it to you.
You must block the canal. With a rock. I will not give the rock to you."
Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.
Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.
You are given a positive integer n, and an array a of positive integers. The task is to calculate the number of such pairs (i,j) that i<j and a_i \& a_j β₯ a_i β a_j, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND), and β denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Danik has solved this task. But can you solve it?
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 β€ t β€ 10) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains one positive integer n (1 β€ n β€ 10^5) β length of the array.
The second line contains n positive integers a_i (1 β€ a_i β€ 10^9) β elements of the array.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For every test case print one non-negative integer β the answer to the problem.
Example
Input
5
5
1 4 3 7 10
3
1 1 1
4
6 2 5 3
2
2 4
1
1
Output
1
3
2
0
0
Note
In the first test case there is only one pair: (4,7): for it 4 \& 7 = 4, and 4 β 7 = 3.
In the second test case all pairs are good.
In the third test case there are two pairs: (6,5) and (2,3).
In the fourth test case there are no good pairs.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int T, n, a[100003], b[32], bb, tot;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> T;
for (int t = (1); t <= (T); t++) {
cin >> n;
tot = 0;
for (int i = (1); i <= (n); i++) cin >> a[i];
for (int j = (0); j <= (32 - 1); j++) b[j] = 0;
for (int i = (1); i <= (n); i++) {
for (int j = (0); j <= (32 - 1); j++) {
if (a[i] > 0)
a[i] >>= 1;
else {
bb = j - 1;
break;
}
}
for (int j = (0); j <= (32 - 1); j++) {
if (j == bb) {
tot += b[j];
++b[j];
}
}
}
cout << tot << "\n";
}
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(s, t, x): add x to as, as+1, ..., at.
* get(i): output the value of ai.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 β€ n β€ 100000
* 1 β€ q β€ 100000
* 1 β€ s β€ t β€ n
* 1 β€ i β€ n
* 0 β€ x β€ 1000
Input
n q
query1
query2
:
queryq
In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:
0 s t x
or
1 t
The first digit represents the type of the query. '0' denotes add(s, t, x) and '1' denotes get(i).
Output
For each get operation, print the value.
Examples
Input
3 5
0 1 2 1
0 2 3 2
0 3 3 3
1 2
1 3
Output
3
5
Input
4 3
1 2
0 1 4 1
1 2
Output
0
1
### Response
```cpp
#include "bits/stdc++.h"
using namespace std;
#ifdef _DEBUG
#include "dump.hpp"
#else
#define dump(...)
#endif
#define int long long
#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define rrep(i,a,b) for(int i=(b)-1;i>=(a);i--)
#define all(c) begin(c),end(c)
const int INF = sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f;
const int MOD = (int)(1e9) + 7;
const double PI = acos(-1);
const double EPS = 1e-9;
template<class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; }
template<class T> bool chmin(T &a, const T &b) { if (a > b) { a = b; return true; } return false; }
struct RangeAddQuery {
int n;
vector<int>d;
RangeAddQuery(int m) {
for (n = 1; n < m; n <<= 1);
d.assign(2 * n, 0);
}
void add(int a, int b, int x = -1, int k = 1, int l = 0, int r = -1) {
if (r == -1)r = n;
if (r <= a || b <= l)return;
if (a <= l&&r <= b) {
if (x >= 0)d[k] += (r - l)*x;
return;
}
else {
if (d[k] != 0) {
d[2 * k] += d[k] / 2;
d[2 * k + 1] += d[k] / 2;
d[k] = 0;
}
add(a, b, x, 2 * k, l, (l + r) / 2);
add(a, b, x, 2 * k + 1, (l + r) / 2, r);
}
}
int get(int i) {
add(i, i + 1);
return d[n + i];
}
};
signed main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n, q; cin >> n >> q;
RangeAddQuery raq(n);
rep(z, 0, q) {
int com; cin >> com;
if (com) {
int i; cin >> i;
cout << raq.get(i-1) << endl;
}
else {
int s, t, x; cin >> s >> t >> x;
raq.add(s - 1, t, x);
}
}
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
We have a weighted directed graph with N vertices numbered 0 to N-1.
The graph initially has N-1 edges. The i-th edge (0 \leq i \leq N-2) is directed from Vertex i to Vertex i+1 and has a weight of 0.
Snuke will now add a new edge (i β j) for every pair i, j (0 \leq i,j \leq N-1,\ i \neq j). The weight of the edge will be -1 if i < j, and 1 otherwise.
Ringo is a boy. A negative cycle (a cycle whose total weight is negative) in a graph makes him sad. He will delete some of the edges added by Snuke so that the graph will no longer contain a negative cycle. The cost of deleting the edge (i β j) is A_{i,j}. He cannot delete edges that have been present from the beginning.
Find the minimum total cost required to achieve Ringo's objective.
Constraints
* 3 \leq N \leq 500
* 1 \leq A_{i,j} \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_{0,1} A_{0,2} A_{0,3} \cdots A_{0,N-1}
A_{1,0} A_{1,2} A_{1,3} \cdots A_{1,N-1}
A_{2,0} A_{2,1} A_{2,3} \cdots A_{2,N-1}
\vdots
A_{N-1,0} A_{N-1,1} A_{N-1,2} \cdots A_{N-1,N-2}
Output
Print the minimum total cost required to achieve Ringo's objective.
Examples
Input
3
2 1
1 4
3 3
Output
2
Input
4
1 1 1
1 1 1
1 1 1
1 1 1
Output
2
Input
10
190587 2038070 142162180 88207341 215145790 38 2 5 20
32047998 21426 4177178 52 734621629 2596 102224223 5 1864
41 481241221 1518272 51 772 146 8805349 3243297 449
918151 126080576 5186563 46354 6646 491776 5750138 2897 161
3656 7551068 2919714 43035419 495 3408 26 3317 2698
455357 3 12 1857 5459 7870 4123856 2402 258
3 25700 16191 102120 971821039 52375 40449 20548149 16186673
2 16 130300357 18 6574485 29175 179 1693 2681
99 833 131 2 414045824 57357 56 302669472 95
8408 7 1266941 60620177 129747 41382505 38966 187 5151064
Output
2280211
### Response
```cpp
#include <bits/stdc++.h>
#define pb emplace_back
#define ll long long
#define fi first
#define se second
#define mp make_pair
#define sz(x) int(x.size())
#define int int64_t
using namespace std;
typedef pair<int, int> pii;
const int N = 5e2 + 5;
const int inf = (ll)1e18;
int f[N][N], n, c[N][N], cost[N][N];
int get(int x, int y, int u, int v) {
if(x > u || y > v) return 0;
return c[u][v] + c[x - 1][y - 1] - c[u][y - 1] - c[x - 1][v];
}
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
#define Task "test"
if(fopen(Task".inp", "r")) {
freopen(Task".inp", "r", stdin);
freopen(Task".out", "w", stdout);
}
cin >> n;
for(int i = 1; i <= n + 1; ++i) {
for(int j = 1; j <= n + 1; ++j) {
if(i != j && i <= n && j <= n) cin >> c[i][j];
c[i][j] += c[i - 1][j] + c[i][j - 1] - c[i - 1][j - 1];
}
}
/// cost(i, j) = sum c[a][b] | i < a < b <= j
for(int i = 0; i <= n + 1; ++i) {
for(int j = i + 1; j <= n + 1; ++j)
cost[i][j] = cost[i][j - 1] + get(i + 1, j, j - 1, j);
}
fill_n(&f[0][0], N * N, inf);
for(int i = 1; i <= n + 1; ++i) f[0][i] = cost[0][i];
auto minimize = [&](int& x, int y) {if(x > y) x = y;};
for(int i = 0; i <= n; ++i) {
for(int j = i + 1; j <= n + 1; ++j) {
if(f[i][j] == inf) continue;
for(int k = j + 1; k <= n + 1; ++k) {
minimize(f[j][k], f[i][j] + cost[j][k] + get(k + 1, i + 1, n + 1, j));
}
}
}
int res = inf;
for(int i = 0; i <= n; ++i) res = min(res, f[i][n + 1]);
cout << res;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Everything is great about Ilya's city, except the roads. The thing is, the only ZooVille road is represented as n holes in a row. We will consider the holes numbered from 1 to n, from left to right.
Ilya is really keep on helping his city. So, he wants to fix at least k holes (perharps he can fix more) on a single ZooVille road.
The city has m building companies, the i-th company needs ci money units to fix a road segment containing holes with numbers of at least li and at most ri. The companies in ZooVille are very greedy, so, if they fix a segment containing some already fixed holes, they do not decrease the price for fixing the segment.
Determine the minimum money Ilya will need to fix at least k holes.
Input
The first line contains three integers n, m, k (1 β€ n β€ 300, 1 β€ m β€ 105, 1 β€ k β€ n). The next m lines contain the companies' description. The i-th line contains three integers li, ri, ci (1 β€ li β€ ri β€ n, 1 β€ ci β€ 109).
Output
Print a single integer β the minimum money Ilya needs to fix at least k holes.
If it is impossible to fix at least k holes, print -1.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
10 4 6
7 9 11
6 9 13
7 7 7
3 5 6
Output
17
Input
10 7 1
3 4 15
8 9 8
5 6 8
9 10 6
1 4 2
1 4 10
8 10 13
Output
2
Input
10 1 9
5 10 14
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long INF = 200000000000000LL;
long long dp[305][305], pri[305][305];
long long n, m, k;
long long cnt(long long pos, long long taken) {
if (taken <= 0) return 0;
if (pos == 0) return INF;
long long &res = dp[pos][taken];
if (res != -1) return res;
res = cnt(pos - 1, taken);
for (long long i = 1; i <= pos; i++)
res = min(res, pri[i][pos] + cnt(i - 1, taken - pos + i - 1));
return res;
}
int main() {
long long i, j, p, q, x, y;
for (i = 0; i < 305; i++) {
for (j = 0; j < 305; j++) pri[i][j] = INF;
}
cin >> n >> m >> k;
while (m--) {
long long l, r, c;
scanf("%I64d %I64d %I64d", &l, &r, &c);
for (i = l; i <= r; i++) pri[l][i] = min(pri[l][i], c);
}
for (i = 1; i <= n; i++) {
for (j = n; j; j--)
pri[i][j] = min(pri[i][j], min(pri[i - 1][j], pri[i][j + 1]));
}
memset(dp, -1, sizeof(dp));
p = cnt(n, k);
if (p >= INF) p = -1;
cout << p << endl;
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).
Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Input
The first line contains integer n (1 β€ n β€ 2Β·109) β the number of the game's rounds.
The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 β€ m, k β€ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
Output
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
Examples
Input
7
RPS
RSPP
Output
3 2
Input
5
RRRRRRRR
R
Output
0 0
Note
In the first sample the game went like this:
* R - R. Draw.
* P - S. Nikephoros loses.
* S - P. Polycarpus loses.
* R - P. Nikephoros loses.
* P - R. Polycarpus loses.
* S - S. Draw.
* R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, c, p[3][1], p1, p2;
p[0][0] = p[1][0] = p[2][0] = 0;
string a, b;
scanf("%d", &n);
cin >> a >> b;
c = a.size() * b.size();
p1 = n / c;
p2 = n % c;
char j1, j2;
for (int i = 0; i < c; i++) {
j1 = a[i % a.size()];
j2 = b[i % b.size()];
if (j1 == 'R') {
if (j2 == 'R')
p[0][0]++;
else if (j2 == 'P')
p[1][0]++;
else
p[2][0]++;
} else {
if (j1 == 'P') {
if (j2 == 'R')
p[2][0]++;
else if (j2 == 'P')
p[0][0]++;
else
p[1][0]++;
} else {
if (j2 == 'R')
p[1][0]++;
else if (j2 == 'P')
p[2][0]++;
else
p[0][0]++;
}
}
}
p[1][0] *= p1;
p[2][0] *= p1;
for (int i = 0; i < p2; i++) {
j1 = a[i % a.size()];
j2 = b[i % b.size()];
if (j1 == 'R') {
if (j2 == 'R')
p[0][0]++;
else if (j2 == 'P')
p[1][0]++;
else
p[2][0]++;
} else {
if (j1 == 'P') {
if (j2 == 'R')
p[2][0]++;
else if (j2 == 'P')
p[0][0]++;
else
p[1][0]++;
} else {
if (j2 == 'R')
p[1][0]++;
else if (j2 == 'P')
p[2][0]++;
else
p[0][0]++;
}
}
}
printf("%d %d\n", p[1][0], p[2][0]);
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task.
Recently, out of blue Captain Flint has been interested in math and even defined a new class of integers. Let's define a positive integer x as nearly prime if it can be represented as p β
q, where 1 < p < q and p and q are prime numbers. For example, integers 6 and 10 are nearly primes (since 2 β
3 = 6 and 2 β
5 = 10), but integers 1, 3, 4, 16, 17 or 44 are not.
Captain Flint guessed an integer n and asked you: can you represent it as the sum of 4 different positive integers where at least 3 of them should be nearly prime.
Uncle Bogdan easily solved the task and joined the crew. Can you do the same?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
Next t lines contain test cases β one per line. The first and only line of each test case contains the single integer n (1 β€ n β€ 2 β
10^5) β the number Flint guessed.
Output
For each test case print:
* YES and 4 different positive integers such that at least 3 of them are nearly prime and their sum is equal to n (if there are multiple answers print any of them);
* NO if there is no way to represent n as the sum of 4 different positive integers where at least 3 of them are nearly prime.
You can print each character of YES or NO in any case.
Example
Input
7
7
23
31
36
44
100
258
Output
NO
NO
YES
14 10 6 1
YES
5 6 10 15
YES
6 7 10 21
YES
2 10 33 55
YES
10 21 221 6
Note
In the first and second test cases, it can be proven that there are no four different positive integers such that at least three of them are nearly prime.
In the third test case, n=31=2 β
7 + 2 β
5 + 2 β
3 + 1: integers 14, 10, 6 are nearly prime.
In the fourth test case, n=36=5 + 2 β
3 + 2 β
5 + 3 β
5: integers 6, 10, 15 are nearly prime.
In the fifth test case, n=44=2 β
3 + 7 + 2 β
5 + 3 β
7: integers 6, 10, 21 are nearly prime.
In the sixth test case, n=100=2 + 2 β
5 + 3 β
11 + 5 β
11: integers 10, 33, 55 are nearly prime.
In the seventh test case, n=258=2 β
5 + 3 β
7 + 13 β
17 + 2 β
3: integers 10, 21, 221, 6 are nearly prime.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int cases;
cin >> cases;
while (cases > 0) {
cases -= 1;
int a;
cin >> a;
if (a < 31) {
cout << "NO" << '\n';
} else {
cout << "YES" << '\n';
if (a - 30 == 6) {
cout << 5 << ' ' << 6 << ' ' << 10 << ' ' << 15 << '\n';
} else if (a - 30 == 10) {
cout << 10 << ' ' << 14 << ' ' << 15 << ' ' << 1 << '\n';
} else if (a - 30 == 14) {
cout << 10 << ' ' << 14 << ' ' << 15 << ' ' << 5 << '\n';
} else {
cout << 6 << ' ' << 10 << ' ' << 14 << ' ' << a - 30 << '\n';
}
}
}
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
There is a string s of length 3 or greater. No two neighboring characters in s are equal.
Takahashi and Aoki will play a game against each other. The two players alternately performs the following operation, Takahashi going first:
* Remove one of the characters in s, excluding both ends. However, a character cannot be removed if removal of the character would result in two neighboring equal characters in s.
The player who becomes unable to perform the operation, loses the game. Determine which player will win when the two play optimally.
Constraints
* 3 β€ |s| β€ 10^5
* s consists of lowercase English letters.
* No two neighboring characters in s are equal.
Input
The input is given from Standard Input in the following format:
s
Output
If Takahashi will win, print `First`. If Aoki will win, print `Second`.
Examples
Input
aba
Output
Second
Input
abc
Output
First
Input
abcab
Output
First
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int ans;
string st;
int main()
{
getline(cin,st);
if(st[0]==st[st.size()-1]) ans++;
if(st.size()%2==1) ans++;
if(ans==1) cout<<"First\n";
else cout<<"Second\n";
exit(0);
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Π‘ity N. has a huge problem with roads, food and IT-infrastructure. In total the city has n junctions, some pairs of them are connected by bidirectional roads. The road network consists of n - 1 roads, you can get from any junction to any other one by these roads. Yes, you're right β the road network forms an undirected tree.
Recently, the Mayor came up with a way that eliminates the problems with the food and the IT-infrastructure at the same time! He decided to put at the city junctions restaurants of two well-known cafe networks for IT professionals: "iMac D0naldz" and "Burger Bing". Since the network owners are not friends, it is strictly prohibited to place two restaurants of different networks on neighboring junctions. There are other requirements. Here's the full list:
* each junction must have at most one restaurant;
* each restaurant belongs either to "iMac D0naldz", or to "Burger Bing";
* each network should build at least one restaurant;
* there is no pair of junctions that are connected by a road and contains restaurants of different networks.
The Mayor is going to take a large tax from each restaurant, so he is interested in making the total number of the restaurants as large as possible.
Help the Mayor to analyze the situation. Find all such pairs of (a, b) that a restaurants can belong to "iMac D0naldz", b restaurants can belong to "Burger Bing", and the sum of a + b is as large as possible.
Input
The first input line contains integer n (3 β€ n β€ 5000) β the number of junctions in the city. Next n - 1 lines list all roads one per line. Each road is given as a pair of integers xi, yi (1 β€ xi, yi β€ n) β the indexes of connected junctions. Consider the junctions indexed from 1 to n.
It is guaranteed that the given road network is represented by an undirected tree with n vertexes.
Output
Print on the first line integer z β the number of sought pairs. Then print all sought pairs (a, b) in the order of increasing of the first component a.
Examples
Input
5
1 2
2 3
3 4
4 5
Output
3
1 3
2 2
3 1
Input
10
1 2
2 3
3 4
5 6
6 7
7 4
8 9
9 10
10 4
Output
6
1 8
2 7
3 6
6 3
7 2
8 1
Note
The figure below shows the answers to the first test case. The junctions with "iMac D0naldz" restaurants are marked red and "Burger Bing" restaurants are marked blue.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<int> v[5001], A;
int x, y, n, m, i, j, k;
bool f[50001], F[50001], Fr[50001];
int go(int x) {
f[x] = 1;
int K = 1;
for (int I = 0; I < v[x].size(); I++)
if (!f[v[x][I]]) K += go(v[x][I]);
return K;
}
int main() {
cin >> n;
for (i = 1; i < n; i++) {
scanf("%d%d", &x, &y);
v[x].push_back(y);
v[y].push_back(x);
}
for (i = 1; i <= n; i++) {
for (j = 0; j <= n; j++) {
f[j] = 0;
F[j] = 0;
}
f[i] = 1;
A.clear();
for (j = 0; j < v[i].size(); j++) A.push_back(go(v[i][j]));
F[0] = 1;
for (j = 0; j < A.size(); j++)
for (k = n; k >= 0; k--)
if (F[k]) F[k + A[j]] = 1;
for (j = 1; j <= n; j++) Fr[j] = (Fr[j] || F[j]);
}
k = 0;
for (i = 1; i < n - 1; i++)
if (Fr[i]) k++;
cout << k << endl;
for (i = 1; i < n - 1; i++)
if (Fr[i]) printf("%d %d\n", i, n - i - 1);
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice!
Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to play a simple game. All n people who came to the barbecue sat in a circle (thus each person received a unique index bi from 0 to n - 1). The person number 0 started the game (this time it was Vasya). All turns in the game were numbered by integers starting from 1. If the j-th turn was made by the person with index bi, then this person acted like that:
1. he pointed at the person with index (bi + 1) mod n either with an elbow or with a nod (x mod y is the remainder after dividing x by y);
2. if j β₯ 4 and the players who had turns number j - 1, j - 2, j - 3, made during their turns the same moves as player bi on the current turn, then he had drunk a glass of juice;
3. the turn went to person number (bi + 1) mod n.
The person who was pointed on the last turn did not make any actions.
The problem was, Vasya's drunk too much juice and can't remember the goal of the game. However, Vasya's got the recorded sequence of all the participants' actions (including himself). Now Vasya wants to find out the maximum amount of juice he could drink if he played optimally well (the other players' actions do not change). Help him.
You can assume that in any scenario, there is enough juice for everybody.
Input
The first line contains a single integer n (4 β€ n β€ 2000) β the number of participants in the game. The second line describes the actual game: the i-th character of this line equals 'a', if the participant who moved i-th pointed at the next person with his elbow, and 'b', if the participant pointed with a nod. The game continued for at least 1 and at most 2000 turns.
Output
Print a single integer β the number of glasses of juice Vasya could have drunk if he had played optimally well.
Examples
Input
4
abbba
Output
1
Input
4
abbab
Output
0
Note
In both samples Vasya has got two turns β 1 and 5. In the first sample, Vasya could have drunk a glass of juice during the fifth turn if he had pointed at the next person with a nod. In this case, the sequence of moves would look like "abbbb". In the second sample Vasya wouldn't drink a single glass of juice as the moves performed during turns 3 and 4 are different.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int Maxn = 2010;
int n, ans;
char s[Maxn];
int main() {
scanf("%d", &n);
scanf("%s", (s + 1));
int m = strlen(s + 1);
int temp = 0;
for (int j = 1; j <= m; j += n) {
if (j >= 4) {
temp += (s[j - 1] == s[j - 2] && s[j - 2] == s[j - 3]);
}
}
cout << temp << endl;
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
There are b boys and g girls participating in Olympiad of Metropolises. There will be a board games tournament in the evening and n participants have accepted the invitation. The organizers do not know how many boys and girls are among them.
Organizers are preparing red badges for girls and blue ones for boys.
Vasya prepared n+1 decks of badges. The i-th (where i is from 0 to n, inclusive) deck contains i blue badges and n-i red ones. The total number of badges in any deck is exactly n.
Determine the minimum number of decks among these n+1 that Vasya should take, so that there will be a suitable deck no matter how many girls and boys there will be among the participants of the tournament.
Input
The first line contains an integer b (1 β€ b β€ 300), the number of boys.
The second line contains an integer g (1 β€ g β€ 300), the number of girls.
The third line contains an integer n (1 β€ n β€ b + g), the number of the board games tournament participants.
Output
Output the only integer, the minimum number of badge decks that Vasya could take.
Examples
Input
5
6
3
Output
4
Input
5
3
5
Output
4
Note
In the first example, each of 4 decks should be taken: (0 blue, 3 red), (1 blue, 2 red), (2 blue, 1 red), (3 blue, 0 red).
In the second example, 4 decks should be taken: (2 blue, 3 red), (3 blue, 2 red), (4 blue, 1 red), (5 blue, 0 red). Piles (0 blue, 5 red) and (1 blue, 4 red) can not be used.
### Response
```cpp
#include <bits/stdc++.h>
int main() {
long b, g, n;
scanf("%ld %ld %ld", &b, &g, &n);
long mnb(0), mxb(b);
if (g < n) {
mnb = n - g;
}
if (n < b) {
mxb = n;
}
printf("%ld\n", mxb - mnb + 1);
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills.
The boy is now looking at the ratings of consecutive participants written in a binary system. He thinks that the more such ratings differ, the more unfair is that such people are next to each other. He defines the difference between two numbers as the number of bit positions, where one number has zero, and another has one (we suppose that numbers are padded with leading zeros to the same length). For example, the difference of 5 = 101_2 and 14 = 1110_2 equals to 3, since 0101 and 1110 differ in 3 positions. Johnny defines the unfairness of the contest as the sum of such differences counted for neighboring participants.
Johnny has just sent you the rating sequence and wants you to find the unfairness of the competition. You have noticed that you've got a sequence of consecutive integers from 0 to n. That's strange, but the boy stubbornly says that everything is right. So help him and find the desired unfairness for received numbers.
Input
The input consists of multiple test cases. The first line contains one integer t (1 β€ t β€ 10 000) β the number of test cases. The following t lines contain a description of test cases.
The first and only line in each test case contains a single integer n (1 β€ n β€ 10^{18}).
Output
Output t lines. For each test case, you should output a single line with one integer β the unfairness of the contest if the rating sequence equals to 0, 1, ..., n - 1, n.
Example
Input
5
5
7
11
1
2000000000000
Output
8
11
19
1
3999999999987
Note
For n = 5 we calculate unfairness of the following sequence (numbers from 0 to 5 written in binary with extra leading zeroes, so they all have the same length):
* 000
* 001
* 010
* 011
* 100
* 101
The differences are equal to 1, 2, 1, 3, 1 respectively, so unfairness is equal to 1 + 2 + 1 + 3 + 1 = 8.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int diff_bits(int n) {
if (n == 0) return 1;
long long int a, res;
a = 1;
for (int i = 0; i < n; i++) {
res = 2 * a + 1;
a = res;
}
return res;
}
int main() {
int t;
cin >> t;
while (t--) {
long long int n;
cin >> n;
long long int ans = 0;
int counter = 0;
while (n > 0) {
if ((n & 1) == 1) {
ans += diff_bits(counter);
}
counter++;
n = n >> 1;
}
cout << ans << endl;
}
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
There are n points on the plane, the i-th of which is at (x_i, y_i). Tokitsukaze wants to draw a strange rectangular area and pick all the points in the area.
The strange area is enclosed by three lines, x = l, y = a and x = r, as its left side, its bottom side and its right side respectively, where l, r and a can be any real numbers satisfying that l < r. The upper side of the area is boundless, which you can regard as a line parallel to the x-axis at infinity. The following figure shows a strange rectangular area.
<image>
A point (x_i, y_i) is in the strange rectangular area if and only if l < x_i < r and y_i > a. For example, in the above figure, p_1 is in the area while p_2 is not.
Tokitsukaze wants to know how many different non-empty sets she can obtain by picking all the points in a strange rectangular area, where we think two sets are different if there exists at least one point in one set of them but not in the other.
Input
The first line contains a single integer n (1 β€ n β€ 2 Γ 10^5) β the number of points on the plane.
The i-th of the next n lines contains two integers x_i, y_i (1 β€ x_i, y_i β€ 10^9) β the coordinates of the i-th point.
All points are distinct.
Output
Print a single integer β the number of different non-empty sets of points she can obtain.
Examples
Input
3
1 1
1 2
1 3
Output
3
Input
3
1 1
2 1
3 1
Output
6
Input
4
2 1
2 2
3 1
3 2
Output
6
Note
For the first example, there is exactly one set having k points for k = 1, 2, 3, so the total number is 3.
For the second example, the numbers of sets having k points for k = 1, 2, 3 are 3, 2, 1 respectively, and their sum is 6.
For the third example, as the following figure shows, there are
* 2 sets having one point;
* 3 sets having two points;
* 1 set having four points.
Therefore, the number of different non-empty sets in this example is 2 + 3 + 0 + 1 = 6.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline long long read() {
char c = getchar();
long long x = 0, f = 1;
while (c > '9' || c < '0') {
if (c == '-') f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = getchar();
}
return x * f;
}
int n, m, k, p[200005], x[200005], y[200005];
long long ans;
set<int> h[200005];
struct node {
int x, y, id;
} e[200005];
int t[200005 << 2];
inline bool cmp1(node a, node b) { return a.x < b.x; }
inline bool cmp2(node a, node b) { return a.y < b.y; }
inline void pushup(int x) { t[x] = t[x << 1] + t[x << 1 | 1]; }
inline void ins(int x, int l, int r, int k) {
if (l == r) {
t[x] = 1;
return;
}
int mid = (l + r) >> 1;
if (mid >= k)
ins(x << 1, l, mid, k);
else
ins(x << 1 | 1, mid + 1, r, k);
pushup(x);
}
inline int qry(int x, int l, int r, int ql, int qr) {
if (ql <= l && r <= qr) {
return t[x];
}
int mid = (l + r) >> 1, res = 0;
if (ql <= mid) res += qry(x << 1, l, mid, ql, qr);
if (qr > mid) res += qry(x << 1 | 1, mid + 1, r, ql, qr);
return res;
}
signed main() {
n = read();
for (int i = 1; i <= n; i++) e[i].x = read(), e[i].y = read(), e[i].id = i;
sort(e + 1, e + 1 + n, cmp1);
for (int i = 1; i <= n; i++) {
m++;
p[e[i].id] = m;
while (i < n && e[i].x == e[i + 1].x) i++, p[e[i].id] = m;
}
for (int i = 1; i <= n; i++) x[i] = p[i];
sort(e + 1, e + 1 + n, cmp2);
for (int i = 1; i <= n; i++) {
k++;
p[e[i].id] = k;
while (i < n && e[i].y == e[i + 1].y) i++, p[e[i].id] = k;
}
for (int i = 1; i <= n; i++) y[i] = p[i];
for (int i = 1; i <= n; i++) h[y[i]].insert(x[i]);
for (int i = k; i >= 1; i--) {
set<int>::iterator it = h[i].begin();
for (; it != h[i].end(); it++) {
int x = *it;
int y;
ins(1, 1, m, x);
set<int>::iterator it1 = it;
it1++;
if (it1 == h[i].end())
y = m;
else
y = (*it1) - 1;
int tmp1 = qry(1, 1, m, 1, x);
int tmp2 = qry(1, 1, m, x, y);
ans += 1ll * tmp1 * tmp2;
}
}
cout << ans << endl;
}
``` |
### 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;
char a[1005][1005];
long long n, m, vis[1005][1005];
long long r[1005], c[1005], ar[1005], ac[1005];
const long long dx[4] = {0, 1, 0, -1};
const long long dy[4] = {1, 0, -1, 0};
bool isvalid(long long x, long long y) {
return x >= 1 and y >= 1 and x <= n and y <= m and a[x][y] == '#';
}
void dfs(long long x, long long y) {
a[x][y] = '.';
for (long long j = 0; j < 4; j++) {
long long cx = x + dx[j];
long long cy = y + dy[j];
if (isvalid(cx, cy)) dfs(cx, cy);
}
}
void solve() {
cin >> n >> m;
memset(vis, 0, sizeof vis);
for (long long i = 1; i < n + 1; i++)
for (long long j = 1; j < m + 1; j++) cin >> a[i][j];
for (long long i = 1; i < n + 1; i++)
for (long long j = 1; j < m + 1; j++)
if (a[i][j] == '#') r[i] = c[j] = 1;
for (long long i = 1; i < n + 1; i++)
for (long long j = 1; j < m + 1; j++) {
if (!r[i] and !c[j]) ar[i] = ac[j] = 1;
}
for (long long i = 1; i < n + 1; i++)
if (!r[i] and !ar[i]) {
cout << -1 << '\n';
return;
}
for (long long j = 1; j < m + 1; j++)
if (!c[j] and !ac[j]) {
cout << -1 << '\n';
return;
}
for (long long i = 1; i < n + 1; i++) {
long long st = m + 1, en = 0;
for (long long j = 1; j < m + 1; j++)
if (a[i][j] == '#') {
st = min(st, j);
en = max(en, j);
}
for (long long j = st; j < en + 1; j++)
if (a[i][j] == '.') {
cout << -1 << '\n';
return;
}
}
for (long long j = 1; j < m + 1; j++) {
long long st = n + 1, en = 0;
for (long long i = 1; i < n + 1; i++)
if (a[i][j] == '#') {
st = min(st, i);
en = max(en, i);
}
for (long long i = st; i < en + 1; i++)
if (a[i][j] == '.') {
cout << -1 << '\n';
return;
}
}
long long ans = 0;
for (long long i = 1; i < n + 1; i++)
for (long long j = 1; j < m + 1; j++)
if (isvalid(i, j)) {
dfs(i, j);
ans++;
}
cout << ans << '\n';
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long TESTS = 1;
while (TESTS--) {
solve();
}
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.
The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 β€ i β€ n - 1.
To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li β€ x β€ ri, li + 1 β€ y β€ ri + 1 and y - x = a.
The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.
Input
The first line contains integers n (2 β€ n β€ 2Β·105) and m (1 β€ m β€ 2Β·105) β the number of islands and bridges.
Next n lines each contain two integers li and ri (1 β€ li β€ ri β€ 1018) β the coordinates of the island endpoints.
The last line contains m integer numbers a1, a2, ..., am (1 β€ ai β€ 1018) β the lengths of the bridges that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.
Examples
Input
4 4
1 4
7 8
9 10
12 14
4 5 3 8
Output
Yes
2 3 1
Input
2 2
11 14
17 18
2 9
Output
No
Input
2 1
1 1
1000000000000000000 1000000000000000000
999999999999999999
Output
Yes
1
Note
In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.
In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m, k, x, y, len;
long long g, tree[200005 << 2], addsum[200005 << 2];
struct node {
long long l, r;
int id;
} q[200005];
struct node2 {
long long x;
int id;
} f[200005];
bool cmp(node a, node b) { return a.l < b.l; }
bool cmp2(node2 a, node2 b) { return a.x < b.x; }
long long l[200005], r[200005], a[200005], tmp[200005];
int ans[200005];
inline long long build_tree(int l, int r, int cnt) {
if (l >= r) {
tree[cnt] = q[l].r, len = max(len, cnt);
return q[l].r;
}
int mid = (l + r) >> 1, f = cnt << 1;
tree[cnt] = min(build_tree(l, mid, f), build_tree(mid + 1, r, f + 1));
return tree[cnt];
}
inline void update(int l, int r, int cnt, int x) {
int mid = (l + r) >> 1, f = cnt << 1;
if (l == r) {
tree[cnt] = 2e18;
return;
}
(x <= mid) ? update(l, mid, f, x) : update(mid + 1, r, f + 1, x);
tree[cnt] = min(tree[f], tree[f + 1]);
return;
}
inline int Find(int nowl, int nowr, int l, int r, int cnt) {
int mid = (nowl + nowr) >> 1, f = cnt << 1;
if (l <= nowl && nowr <= r) {
if (nowl == nowr) return nowl;
return (tree[f] < tree[f + 1]) ? Find(nowl, mid, l, r, f)
: Find(mid + 1, nowr, l, r, f + 1);
}
if (nowr < l || r < nowl) return n + 1;
int t1 = Find(nowl, mid, l, r, f), t2 = Find(mid + 1, nowr, l, r, f + 1);
return (q[t1].r < q[t2].r) ? t1 : t2;
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
scanf("%lld%lld", &l[i], &r[i]);
}
n--;
for (int i = 1; i <= n; i++)
q[i].l = l[i + 1] - r[i], q[i].r = r[i + 1] - l[i], q[i].id = i;
sort(q + 1, q + n + 1, cmp);
for (int i = 1; i <= n; i++) tmp[i] = q[i].l;
build_tree(1, n, 1);
q[n + 1].r = 2e18;
for (int i = 1; i <= m; i++) scanf("%lld", &f[i].x), f[i].id = i;
sort(f + 1, f + m + 1, cmp2);
for (int i = 1; i <= m; i++) a[i] = f[i].x;
int num = 0;
for (int i = 1; i <= m; i++) {
long long r = upper_bound(tmp + 1, tmp + n + 1, a[i]) - tmp - 1;
if (r == 0) continue;
int gg = Find(1, n, 1, r, 1);
if (q[gg].r < a[i]) return 0 * printf("No\n");
if (q[gg].r == 2e18) continue;
ans[q[gg].id] = f[i].id;
q[gg].r = 2e18;
update(1, n, 1, gg);
if (++num == n) break;
}
if (num != n) return 0 * printf("No\n");
printf("Yes\n");
for (int i = 1; i <= n; i++) printf("%d ", ans[i]);
printf("\n");
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly ai calories on touching the i-th strip.
You've got a string s, describing the process of the game and numbers a1, a2, a3, a4. Calculate how many calories Jury needs to destroy all the squares?
Input
The first line contains four space-separated integers a1, a2, a3, a4 (0 β€ a1, a2, a3, a4 β€ 104).
The second line contains string s (1 β€ |s| β€ 105), where the Ρ-th character of the string equals "1", if on the i-th second of the game the square appears on the first strip, "2", if it appears on the second strip, "3", if it appears on the third strip, "4", if it appears on the fourth strip.
Output
Print a single integer β the total number of calories that Jury wastes.
Examples
Input
1 2 3 4
123214
Output
13
Input
1 5 3 2
11221
Output
13
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a[5], ans = 0;
string s;
cin >> a[1] >> a[2] >> a[3] >> a[4];
cin >> s;
for (int i = 0; i < s.length(); i++) {
ans += a[s[i] - '0'];
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
This is an interactive problem.
Khanh has n points on the Cartesian plane, denoted by a_1, a_2, β¦, a_n. All points' coordinates are integers between -10^9 and 10^9, inclusive. No three points are collinear. He says that these points are vertices of a convex polygon; in other words, there exists a permutation p_1, p_2, β¦, p_n of integers from 1 to n such that the polygon a_{p_1} a_{p_2} β¦ a_{p_n} is convex and vertices are listed in counter-clockwise order.
Khanh gives you the number n, but hides the coordinates of his points. Your task is to guess the above permutation by asking multiple queries. In each query, you give Khanh 4 integers t, i, j, k; where either t = 1 or t = 2; and i, j, k are three distinct indices from 1 to n, inclusive. In response, Khanh tells you:
* if t = 1, the area of the triangle a_ia_ja_k multiplied by 2.
* if t = 2, the sign of the cross product of two vectors \overrightarrow{a_ia_j} and \overrightarrow{a_ia_k}.
Recall that the cross product of vector \overrightarrow{a} = (x_a, y_a) and vector \overrightarrow{b} = (x_b, y_b) is the integer x_a β
y_b - x_b β
y_a. The sign of a number is 1 it it is positive, and -1 otherwise. It can be proven that the cross product obtained in the above queries can not be 0.
You can ask at most 3 β
n queries.
Please note that Khanh fixes the coordinates of his points and does not change it while answering your queries. You do not need to guess the coordinates. In your permutation a_{p_1}a_{p_2}β¦ a_{p_n}, p_1 should be equal to 1 and the indices of vertices should be listed in counter-clockwise order.
Interaction
You start the interaction by reading n (3 β€ n β€ 1 000) β the number of vertices.
To ask a query, write 4 integers t, i, j, k (1 β€ t β€ 2, 1 β€ i, j, k β€ n) in a separate line. i, j and k should be distinct.
Then read a single integer to get the answer to this query, as explained above. It can be proven that the answer of a query is always an integer.
When you find the permutation, write a number 0. Then write n integers p_1, p_2, β¦, p_n in the same line.
After printing a query do not forget to output end of 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 documentation for other languages.
Hack format
To hack, use the following format:
The first line contains an integer n (3 β€ n β€ 1 000) β the number of vertices.
The i-th of the next n lines contains two integers x_i and y_i (-10^9 β€ x_i, y_i β€ 10^9) β the coordinate of the point a_i.
Example
Input
6
15
-1
1
Output
1 1 4 6
2 1 5 6
2 2 1 4
0 1 3 4 2 6 5
Note
The image below shows the hidden polygon in the example:
<image>
The interaction in the example goes as below:
* Contestant reads n = 6.
* Contestant asks a query with t = 1, i = 1, j = 4, k = 6.
* Jury answers 15. The area of the triangle A_1A_4A_6 is 7.5. Note that the answer is two times the area of the triangle.
* Contestant asks a query with t = 2, i = 1, j = 5, k = 6.
* Jury answers -1. The cross product of \overrightarrow{A_1A_5} = (2, 2) and \overrightarrow{A_1A_6} = (4, 1) is -2. The sign of -2 is -1.
* Contestant asks a query with t = 2, i = 2, j = 1, k = 4.
* Jury answers 1. The cross product of \overrightarrow{A_2A_1} = (-5, 2) and \overrightarrow{A_2A_4} = (-2, -1) is 1. The sign of 1 is 1.
* Contestant says that the permutation is (1, 3, 4, 2, 6, 5).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long MaxN = 2e5 + 100;
const long long LogN = 20;
const long long Inf = 2e15;
double eps = 1e-3;
long long md = 998244353;
long long dx[4] = {1, 0, 0, -1};
long long dy[4] = {0, 1, -1, 0};
long long gcdex(long long a, long long mod = md) {
long long g = mod, r = a, x = 0, y = 1;
while (r != 0) {
long long q = g / r;
g %= r;
swap(g, r);
x -= q * y;
swap(x, y);
}
return x < 0 ? x + mod : x;
}
long long N;
vector<long long> lt;
vector<long long> rg;
long long getS(long long a, long long b, long long c) {
cout << 1 << ' ' << a << ' ' << b << ' ' << c << endl;
long long t;
cin >> t;
return t;
}
long long getN(long long a, long long b, long long c) {
cout << 2 << ' ' << a << ' ' << b << ' ' << c << endl;
long long t;
cin >> t;
return t;
}
void calc() {
for (int i = 3; i <= N; i++) {
long long k = getN(1, 2, i);
if (k == 1)
lt.push_back(i);
else
rg.push_back(i);
}
}
vector<long long> Ans;
long long d[MaxN];
void Sort(vector<long long>& Mt) {
if ((Ans).size() == 0)
Ans.push_back(1);
else
Ans.push_back(2);
if ((Mt).size() == 0) {
return;
}
long long t = Mt[0];
for (long long a : Mt) {
d[a] = getS(1, 2, a);
if (d[a] > d[t]) t = a;
}
vector<long long> At;
vector<long long> Bt;
for (long long a : Mt) {
if (a == t) continue;
if (getN(1, t, a) == 1)
At.push_back(a);
else
Bt.push_back(a);
}
sort(At.begin(), At.end(),
[=](long long a, long long b) { return d[a] > d[b]; });
sort(Bt.begin(), Bt.end(),
[=](long long a, long long b) { return d[a] < d[b]; });
for (long long a : Bt) Ans.push_back(a);
Ans.push_back(t);
for (long long a : At) Ans.push_back(a);
}
int main() {
cin >> N;
calc();
Sort(rg);
Sort(lt);
cout << 0 << ' ';
for (long long a : Ans) cout << a << ' ';
cout << endl;
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
For a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that β_{i=1}^{n}{β_{j=i}^{n}{(a_j)/(j)}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for example, 5/2=2.5.
Input
The first line contains a single integer t β the number of test cases (1 β€ t β€ 100). The test cases follow, each in two lines.
The first line of a test case contains two integers n and m (1 β€ n β€ 100, 0 β€ m β€ 10^6). The second line contains integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^6) β the elements of the array.
Output
For each test case print "YES", if it is possible to reorder the elements of the array in such a way that the given formula gives the given value, and "NO" otherwise.
Example
Input
2
3 8
2 5 1
4 4
0 1 2 3
Output
YES
NO
Note
In the first test case one of the reorders could be [1, 2, 5]. The sum is equal to (1/1 + 2/2 + 5/3) + (2/2 + 5/3) + (5/3) = 8. The brackets denote the inner sum β_{j=i}^{n}{(a_j)/(j)}, while the summation of brackets corresponds to the sum over i.
### Response
```cpp
#include <bits/stdc++.h>
int main() {
int t, n;
double sum, a, m;
scanf("%d", &t);
while (t--) {
sum = 0;
scanf("%d%lf", &n, &m);
for (int i = 0; i < n; i++) {
scanf("%lf", &a);
sum += a;
}
if (sum == m) {
printf("YES\n");
} else {
printf("NO\n");
}
}
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.
Let's index all the leaf nodes from the left to the right from 1 to 2h. The exit is located at some node n where 1 β€ n β€ 2h, the player doesn't know where the exit is so he has to guess his way out!
Amr follows simple algorithm to choose the path. Let's consider infinite command string "LRLRLRLRL..." (consisting of alternating characters 'L' and 'R'). Amr sequentially executes the characters of the string using following rules:
* Character 'L' means "go to the left child of the current node";
* Character 'R' means "go to the right child of the current node";
* If the destination node is already visited, Amr skips current command, otherwise he moves to the destination node;
* If Amr skipped two consecutive commands, he goes back to the parent of the current node before executing next command;
* If he reached a leaf node that is not the exit, he returns to the parent of the current node;
* If he reaches an exit, the game is finished.
Now Amr wonders, if he follows this algorithm, how many nodes he is going to visit before reaching the exit?
Input
Input consists of two integers h, n (1 β€ h β€ 50, 1 β€ n β€ 2h).
Output
Output a single integer representing the number of nodes (excluding the exit node) Amr is going to visit before reaching the exit by following this algorithm.
Examples
Input
1 2
Output
2
Input
2 3
Output
5
Input
3 6
Output
10
Input
10 1024
Output
2046
Note
A perfect binary tree of height h is a binary tree consisting of h + 1 levels. Level 0 consists of a single node called root, level h consists of 2h nodes called leaves. Each node that is not a leaf has exactly two children, left and right one.
Following picture illustrates the sample test number 3. Nodes are labeled according to the order of visit.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long p(long long a, long long b) {
long long temp = 1;
while (b > 0) {
temp *= a;
b--;
}
return temp;
}
long long divide(long long node) {
long long count = 0;
while (node != 0) {
node /= 2;
count++;
}
return count - 1;
}
int main() {
long long left, right, status, node, n, h, i, height, num, count;
scanf("%I64d%I64d", &h, &n);
n += p(2, h) - 1;
node = 1;
status = 0;
count = 0;
while (node != n) {
height = h - divide(node);
left = node * p(2, height);
right = left + p(2, height) - 1;
if (n < left || n > right) {
count += (p(2, height + 1) - 1);
if (node % 2 == 1) {
node /= 2;
status = 0;
} else {
node /= 2;
status = 1;
}
count--;
} else {
count++;
if (status == 0)
node *= 2;
else
node = 2 * node + 1;
if (status == 0)
status = 1;
else
status = 0;
}
}
printf("%I64d\n", count);
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Mike and Ann are sitting in the classroom. The lesson is boring, so they decided to play an interesting game. Fortunately, all they need to play this game is a string s and a number k (0 β€ k < |s|).
At the beginning of the game, players are given a substring of s with left border l and right border r, both equal to k (i.e. initially l=r=k). Then players start to make moves one by one, according to the following rules:
* A player chooses l^{\prime} and r^{\prime} so that l^{\prime} β€ l, r^{\prime} β₯ r and s[l^{\prime}, r^{\prime}] is lexicographically less than s[l, r]. Then the player changes l and r in this way: l := l^{\prime}, r := r^{\prime}.
* Ann moves first.
* The player, that can't make a move loses.
Recall that a substring s[l, r] (l β€ r) of a string s is a continuous segment of letters from s that starts at position l and ends at position r. For example, "ehn" is a substring (s[3, 5]) of "aaaehnsvz" and "ahz" is not.
Mike and Ann were playing so enthusiastically that they did not notice the teacher approached them. Surprisingly, the teacher didn't scold them, instead of that he said, that he can figure out the winner of the game before it starts, even if he knows only s and k.
Unfortunately, Mike and Ann are not so keen in the game theory, so they ask you to write a program, that takes s and determines the winner for all possible k.
Input
The first line of the input contains a single string s (1 β€ |s| β€ 5 β
10^5) consisting of lowercase English letters.
Output
Print |s| lines.
In the line i write the name of the winner (print Mike or Ann) in the game with string s and k = i, if both play optimally
Examples
Input
abba
Output
Mike
Ann
Ann
Mike
Input
cba
Output
Mike
Mike
Mike
### Response
```cpp
#include <bits/stdc++.h>
const double PI = 3.141592653589793238460;
using namespace std;
int ar[26];
int getMeAns(char c) {
for (char ch = 'a'; ch < c; ch++)
if (ar[ch - 'a'] > 0) return 1;
return 0;
}
int main() {
string ans[] = {"Mike", "Ann"};
string st;
cin >> st;
for (int i = 0; i < st.size(); i++)
cout << ans[getMeAns(st[i])] << '\n', ar[st[i] - 'a']++;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Bob is a pirate looking for the greatest treasure the world has ever seen. The treasure is located at the point T, which coordinates to be found out.
Bob travelled around the world and collected clues of the treasure location at n obelisks. These clues were in an ancient language, and he has only decrypted them at home. Since he does not know which clue belongs to which obelisk, finding the treasure might pose a challenge. Can you help him?
As everyone knows, the world is a two-dimensional plane. The i-th obelisk is at integer coordinates (x_i, y_i). The j-th clue consists of 2 integers (a_j, b_j) and belongs to the obelisk p_j, where p is some (unknown) permutation on n elements. It means that the treasure is located at T=(x_{p_j} + a_j, y_{p_j} + b_j). This point T is the same for all clues.
In other words, each clue belongs to exactly one of the obelisks, and each obelisk has exactly one clue that belongs to it. A clue represents the vector from the obelisk to the treasure. The clues must be distributed among the obelisks in such a way that they all point to the same position of the treasure.
Your task is to find the coordinates of the treasure. If there are multiple solutions, you may print any of them.
Note that you don't need to find the permutation. Permutations are used only in order to explain the problem.
Input
The first line contains an integer n (1 β€ n β€ 1000) β the number of obelisks, that is also equal to the number of clues.
Each of the next n lines contains two integers x_i, y_i (-10^6 β€ x_i, y_i β€ 10^6) β the coordinates of the i-th obelisk. All coordinates are distinct, that is x_i β x_j or y_i β y_j will be satisfied for every (i, j) such that i β j.
Each of the next n lines contains two integers a_i, b_i (-2 β
10^6 β€ a_i, b_i β€ 2 β
10^6) β the direction of the i-th clue. All coordinates are distinct, that is a_i β a_j or b_i β b_j will be satisfied for every (i, j) such that i β j.
It is guaranteed that there exists a permutation p, such that for all i,j it holds \left(x_{p_i} + a_i, y_{p_i} + b_i\right) = \left(x_{p_j} + a_j, y_{p_j} + b_j\right).
Output
Output a single line containing two integers T_x, T_y β the coordinates of the treasure.
If there are multiple answers, you may print any of them.
Examples
Input
2
2 5
-6 4
7 -2
-1 -3
Output
1 2
Input
4
2 2
8 2
-7 0
-2 6
1 -14
16 -12
11 -18
7 -14
Output
9 -12
Note
As n = 2, we can consider all permutations on two elements.
If p = [1, 2], then the obelisk (2, 5) holds the clue (7, -2), which means that the treasure is hidden at (9, 3). The second obelisk (-6, 4) would give the clue (-1,-3) and the treasure at (-7, 1). However, both obelisks must give the same location, hence this is clearly not the correct permutation.
If the hidden permutation is [2, 1], then the first clue belongs to the second obelisk and the second clue belongs to the first obelisk. Hence (-6, 4) + (7, -2) = (2,5) + (-1,-3) = (1, 2), so T = (1,2) is the location of the treasure.
<image>
In the second sample, the hidden permutation is [2, 3, 4, 1].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct tt {
int x, y;
};
tt a[1010], b[1010];
int p[1010], vis[1010];
bool cmp(tt a, tt b) {
if (a.x == b.x) return a.y < b.y;
return a.x < b.x;
}
int main() {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d%d", &a[i].x, &a[i].y);
}
for (int i = 1; i <= n; i++) {
scanf("%d%d", &b[i].x, &b[i].y);
}
sort(a + 1, a + 1 + n, cmp);
sort(b + 1, b + 1 + n, cmp);
printf("%d %d", a[1].x + b[n].x, a[1].y + b[n].y);
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
long long k;
cin >> k;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
if (k > n - 1) {
k = n - 1;
}
int ans = 0;
for (int i = 0; i < n; i++) {
int v = arr[i];
bool isAns = true;
for (int j = 1; j < k; j++) {
int idx = (i + j) % n;
if (v < arr[idx]) {
isAns = false;
}
}
if (i == 0) {
int idx = (i + k) % n;
if (v < arr[idx]) {
isAns = false;
}
} else {
int idx = (i - 1) % n;
if (v < arr[idx]) {
isAns = false;
}
}
if (isAns) {
ans = v;
break;
}
}
cout << ans;
}
int main() {
solve();
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Today you are going to lead a group of elven archers to defend the castle that is attacked by an army of angry orcs. Three sides of the castle are protected by impassable mountains and the remaining side is occupied by a long wall that is split into n sections. At this moment there are exactly ai archers located at the i-th section of this wall. You know that archer who stands at section i can shoot orcs that attack section located at distance not exceeding r, that is all such sections j that |i - j| β€ r. In particular, r = 0 means that archers are only capable of shooting at orcs who attack section i.
Denote as defense level of section i the total number of archers who can shoot at the orcs attacking this section. Reliability of the defense plan is the minimum value of defense level of individual wall section.
There is a little time left till the attack so you can't redistribute archers that are already located at the wall. However, there is a reserve of k archers that you can distribute among wall sections in arbitrary way. You would like to achieve maximum possible reliability of the defence plan.
Input
The first line of the input contains three integers n, r and k (1 β€ n β€ 500 000, 0 β€ r β€ n, 0 β€ k β€ 1018) β the number of sections of the wall, the maximum distance to other section archers can still shoot and the number of archers yet to be distributed along the wall. The second line contains n integers a1, a2, ..., an (0 β€ ai β€ 109) β the current number of archers at each section.
Output
Print one integer β the maximum possible value of defense plan reliability, i.e. the maximum possible value of minimum defense level if we distribute k additional archers optimally.
Examples
Input
5 0 6
5 4 3 4 9
Output
5
Input
4 2 0
1 2 3 4
Output
6
Input
5 1 1
2 1 2 1 2
Output
3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n, r, k, sum[1000001], a[1000001], f[1000001], sumx[1000001],
su[1000001];
bool check(long long x) {
for (int i = 1; i <= n; i++)
if (su[i] < x)
f[i] = x - su[i];
else
f[i] = 0;
long long cnt = 0;
for (int i = 1; i <= n; i++) {
long long now;
if (i - r * 2 - 1 < 0)
now = max(f[i] - sumx[i - 1], 0ll);
else
now = max(0ll, f[i] - (sumx[i - 1] - sumx[i - r * 2 - 1]));
cnt += now;
if (cnt > k) return 0;
sumx[i] = sumx[i - 1] + now;
}
if (cnt > k) return 0;
return 1;
}
int main() {
scanf("%lld%lld%lld", &n, &r, &k);
for (int i = 1; i <= n; i++) scanf("%lld", &a[i]);
for (int i = 1; i <= n + r; i++) sum[i] = sum[i - 1] + a[i];
for (int i = 1; i <= n; i++)
if (i - r - 1 < 0)
su[i] = sum[i + r];
else
su[i] = sum[i + r] - sum[i - r - 1];
long long l = 0, r = 4e18;
while (l < r) {
long long mid = (l + r + 1) / 2;
if (check(mid))
l = mid;
else
r = mid - 1;
}
printf("%lld\n", l);
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
The protection of a popular program developed by one of IT City companies is organized the following way. After installation it outputs a random five digit number which should be sent in SMS to a particular phone number. In response an SMS activation code arrives.
A young hacker Vasya disassembled the program and found the algorithm that transforms the shown number into the activation code. Note: it is clear that Vasya is a law-abiding hacker, and made it for a noble purpose β to show the developer the imperfection of their protection.
The found algorithm looks the following way. At first the digits of the number are shuffled in the following order <first digit><third digit><fifth digit><fourth digit><second digit>. For example the shuffle of 12345 should lead to 13542. On the second stage the number is raised to the fifth power. The result of the shuffle and exponentiation of the number 12345 is 455 422 043 125 550 171 232. The answer is the 5 last digits of this result. For the number 12345 the answer should be 71232.
Vasya is going to write a keygen program implementing this algorithm. Can you do the same?
Input
The only line of the input contains a positive integer five digit number for which the activation code should be found.
Output
Output exactly 5 digits without spaces between them β the found activation code of the program.
Examples
Input
12345
Output
71232
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
long long k, s1 = 1, s2, ans = 0;
string second, s3;
int32_t main() {
cin >> second;
k = (second[1] - '0') + 10 * (second[3] - '0') + (second[4] - '0') * 100 +
(second[2] - '0') * 1000 + (second[0] - '0') * 10000;
for (long long i = 0; i < 5; i++) s1 = (s1 * k) % 100000;
s2 = s1;
if (s1 == 0) {
ans++;
}
while (s2 != 0) {
ans++;
s2 = s2 / 10;
}
if (ans < 5) {
for (long long i = 0; i < 5 - ans; i++) cout << 0;
cout << s1;
} else {
ans = 0;
while (s1) {
s3.push_back(s1 % 10 + '0');
s1 = s1 / 10;
ans++;
if (ans == 5) {
break;
}
}
reverse(s3.begin(), s3.end());
cout << s3;
}
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Vasya is developing his own programming language VPL (Vasya Programming Language). Right now he is busy making the system of exceptions. He thinks that the system of exceptions must function like that.
The exceptions are processed by try-catch-blocks. There are two operators that work with the blocks:
1. The try operator. It opens a new try-catch-block.
2. The catch(<exception_type>, <message>) operator. It closes the try-catch-block that was started last and haven't yet been closed. This block can be activated only via exception of type <exception_type>. When we activate this block, the screen displays the <message>. If at the given moment there is no open try-catch-block, then we can't use the catch operator.
The exceptions can occur in the program in only one case: when we use the throw operator. The throw(<exception_type>) operator creates the exception of the given type.
Let's suggest that as a result of using some throw operator the program created an exception of type a. In this case a try-catch-block is activated, such that this block's try operator was described in the program earlier than the used throw operator. Also, this block's catch operator was given an exception type a as a parameter and this block's catch operator is described later that the used throw operator. If there are several such try-catch-blocks, then the system activates the block whose catch operator occurs earlier than others. If no try-catch-block was activated, then the screen displays message "Unhandled Exception".
To test the system, Vasya wrote a program that contains only try, catch and throw operators, one line contains no more than one operator, the whole program contains exactly one throw operator.
Your task is: given a program in VPL, determine, what message will be displayed on the screen.
Input
The first line contains a single integer: n (1 β€ n β€ 105) the number of lines in the program. Next n lines contain the program in language VPL. Each line contains no more than one operator. It means that input file can contain empty lines and lines, consisting only of spaces.
The program contains only operators try, catch and throw. It is guaranteed that the program is correct. It means that each started try-catch-block was closed, the catch operators aren't used unless there is an open try-catch-block. The program has exactly one throw operator. The program may have spaces at the beginning of a line, at the end of a line, before and after a bracket, a comma or a quote mark.
The exception type is a nonempty string, that consists only of upper and lower case english letters. The length of the string does not exceed 20 symbols. Message is a nonempty string, that consists only of upper and lower case english letters, digits and spaces. Message is surrounded with quote marks. Quote marks shouldn't be printed. The length of the string does not exceed 20 symbols.
Length of any line in the input file does not exceed 50 symbols.
Output
Print the message the screen will show after the given program is executed.
Examples
Input
8
try
try
throw ( AE )
catch ( BE, "BE in line 3")
try
catch(AE, "AE in line 5")
catch(AE,"AE somewhere")
Output
AE somewhere
Input
8
try
try
throw ( AE )
catch ( AE, "AE in line 3")
try
catch(BE, "BE in line 5")
catch(AE,"AE somewhere")
Output
AE in line 3
Input
8
try
try
throw ( CE )
catch ( BE, "BE in line 3")
try
catch(AE, "AE in line 5")
catch(AE,"AE somewhere")
Output
Unhandled Exception
Note
In the first sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(BE,"BE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so the second block will be activated, because operator catch(AE,"AE somewhere") has exception type AE as parameter and operator catch(BE,"BE in line 3") has exception type BE.
In the second sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(AE,"AE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so both blocks can be activated, but only the first one will be activated, because operator catch(AE,"AE in line 3") is described earlier than catch(AE,"AE somewhere")
In the third sample there is no blocks that can be activated by an exception of type CE.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n;
int main() {
cin >> n >> ws;
stack<int> st;
int head = -1;
string temp;
for (int i = 0; i < n; i++) {
string s;
getline(cin, s);
for (int j = 0; j < s.size(); j++)
if (s[j] == '(' || s[j] == ')' || s[j] == ',') s[j] = ' ';
string command;
istringstream scin(s);
scin >> command;
if (command == "try") st.push(i);
if (command == "throw") {
scin >> temp;
head = i;
}
if (command == "catch") {
string temp1;
scin >> temp1;
if (st.top() < head && temp == temp1) {
s.erase(0, s.find('"') + 1);
s.erase(s.find('"'), s.size());
cout << s;
return 0;
}
st.pop();
}
}
cout << "Unhandled Exception";
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Programming teacher Dmitry Olegovich is going to propose the following task for one of his tests for students:
You are given a tree T with n vertices, specified by its adjacency matrix a[1... n, 1... n]. What is the output of the following pseudocode?
used[1 ... n] = {0, ..., 0};
procedure dfs(v):
print v;
used[v] = 1;
for i = 1, 2, ..., n:
if (a[v][i] == 1 and used[i] == 0):
dfs(i);
dfs(1);
In order to simplify the test results checking procedure, Dmitry Olegovich decided to create a tree T such that the result is his favorite sequence b. On the other hand, Dmitry Olegovich doesn't want to provide students with same trees as input, otherwise they might cheat. That's why Dmitry Olegovich is trying to find out the number of different trees T such that the result of running the above pseudocode with T as input is exactly the sequence b. Can you help him?
Two trees with n vertices are called different if their adjacency matrices a1 and a2 are different, i. e. there exists a pair (i, j), such that 1 β€ i, j β€ n and a1[i][j] β a2[i][j].
Input
The first line contains the positive integer n (1 β€ n β€ 500) β the length of sequence b.
The second line contains n positive integers b1, b2, ..., bn (1 β€ bi β€ n). It is guaranteed that b is a permutation, or in other words, each of the numbers 1, 2, ..., n appears exactly once in the sequence b. Also it is guaranteed that b1 = 1.
Output
Output the number of trees satisfying the conditions above modulo 109 + 7.
Examples
Input
3
1 2 3
Output
2
Input
3
1 3 2
Output
1
### Response
```cpp
#include <bits/stdc++.h>
template <typename T>
T sqr(T x) {
return x * x;
}
template <typename T>
bool exmax(T &a, T b) {
return (b > a) ? (a = b) || 1 : 0;
}
template <typename T>
bool exmin(T &a, T b) {
return (b < a) ? (a = b) || 1 : 0;
}
using namespace std;
int g[510];
long long f[510][510];
long long dfs(int l, int r) {
if (f[l][r] != -1) return f[l][r];
if (l == r) return f[l][r] = 1LL;
long long &ret = f[l][r];
ret = 0;
for (int i = l + 1; i <= r; i++)
if (i == r || g[i + 1] > g[l + 1])
ret = (ret + dfs(l + 1, i) * dfs(i, r)) % 1000000007;
return ret;
}
int main() {
int n;
cin >> n;
for (__typeof(n) i = 0; i < (n); i++) cin >> g[i];
memset(f, 0xff, sizeof(f));
cout << dfs(0, n - 1) << endl;
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Chris the Rabbit found the traces of an ancient Martian civilization. The brave astronomer managed to see through a small telescope an architecture masterpiece β "A Road to the Sun". The building stands on cubical stones of the same size. The foundation divides the entire "road" into cells, into which the cubical stones are fit tightly. Thus, to any cell of the foundation a coordinate can be assigned. To become the leader of the tribe, a Martian should build a Road to the Sun, that is to build from those cubical stones on a given foundation a stairway. The stairway should be described by the number of stones in the initial coordinate and the coordinates of the stairway's beginning and end. Each following cell in the coordinate's increasing order should contain one cubical stone more than the previous one. At that if the cell has already got stones, they do not count in this building process, the stairways were simply built on them. In other words, let us assume that a stairway is built with the initial coordinate of l, the final coordinate of r and the number of stones in the initial coordinate x. That means that x stones will be added in the cell l, x + 1 stones will be added in the cell l + 1, ..., x + r - l stones will be added in the cell r.
Chris managed to find an ancient manuscript, containing the descriptions of all the stairways. Now he wants to compare the data to be sure that he has really found "A Road to the Sun". For that he chose some road cells and counted the total number of cubical stones that has been accumulated throughout the Martian history and then asked you to count using the manuscript to what the sum should ideally total.
Input
The first line contains three space-separated integers: n, m, k (1 β€ n, m β€ 105, 1 β€ k β€ min(n, 100)) which is the number of cells, the number of "Roads to the Sun" and the number of cells in the query correspondingly. Each of the following m roads contain three space-separated integers: ai, bi, ci (1 β€ ai β€ bi β€ n, 1 β€ ci β€ 1000) which are the stairway's description, its beginning, end and the initial cell's height. Then follow a line, containing k different space-separated integers bi. All these numbers ranging from 1 to n are cells, the number of stones in which interests Chris.
Output
You have to print a single number on a single line which is the sum of stones in all the cells Chris is interested in.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
Examples
Input
5 2 1
1 5 1
2 4 1
3
Output
5
Input
3 2 1
1 3 1
1 3 1
2
Output
4
Input
3 2 1
1 3 1
1 3 1
3
Output
6
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int Maxm = 100000;
int n, m, k, a[Maxm], b[Maxm], c[Maxm];
int main() {
long long res = 0;
scanf("%d %d %d", &n, &m, &k);
for (int i = 0; i < m; i++) scanf("%d %d %d", &a[i], &b[i], &c[i]);
for (int i = 0; i < k; i++) {
int num;
scanf("%d", &num);
for (int j = 0; j < m; j++)
if (a[j] <= num && num <= b[j]) res += num - a[j] + c[j];
}
printf("%I64d\n", res);
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls from his box in his move. Players alternate turns and the first player starts the game. The one who can't make a move loses. Your task is to determine who wins if both players play optimally.
Input
The first line contains four integers n1, n2, k1, k2. All numbers in the input are from 1 to 50.
This problem doesn't have subproblems. You will get 3 points for the correct submission.
Output
Output "First" if the first player wins and "Second" otherwise.
Examples
Input
2 2 1 2
Output
Second
Input
2 1 1 1
Output
First
Note
Consider the first sample test. Each player has a box with 2 balls. The first player draws a single ball from his box in one move and the second player can either take 1 or 2 balls from his box in one move. No matter how the first player acts, the second player can always win if he plays wisely.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a, b, c, d;
cin >> a >> b >> c >> d;
if (a == b)
cout << "Second" << endl;
else if (a > b)
cout << "First" << endl;
else
cout << "Second" << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Today Peter has got an additional homework for tomorrow. The teacher has given three integers to him: n, m and k, and asked him to mark one or more squares on a square grid of size n Γ m.
The marked squares must form a connected figure, and there must be exactly k triples of marked squares that form an L-shaped tromino β all three squares are inside a 2 Γ 2 square.
The set of squares forms a connected figure if it is possible to get from any square to any other one if you are allowed to move from a square to any adjacent by a common side square.
Peter cannot fulfill the task, so he asks you for help. Help him to create such figure.
Input
Input data contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
Each of the following t test cases is described by a line that contains three integers: n, m and k (3 β€ n, m, n Γ m β€ 105, 0 β€ k β€ 109).
The sum of values of n Γ m for all tests in one input data doesn't exceed 105.
Output
For each test case print the answer.
If it is possible to create such figure, print n lines, m characters each, use asterisk '*' to denote the marked square, and dot '.' to denote the unmarked one.
If there is no solution, print -1.
Print empty line between test cases.
Example
Input
3
3 3 4
3 3 5
3 3 3
Output
.*.
***
.*.
**.
**.
*..
.*.
***
*..
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }
const int MAXN = 100000;
int h, w, n, want;
bool haveret;
char ret[MAXN + 1], nret[MAXN + 1];
void bf() {
for (int msk = (1); msk < (1 << n); ++msk) {
int cur = 0;
for (int x = (0); x < (h - 1); ++x)
for (int y = (0); y < (w - 1); ++y) {
int cnt = 0;
for (int dx = (0); dx < (2); ++dx)
for (int dy = (0); dy < (2); ++dy)
if ((msk >> ((x + dx) * w + (y + dy))) & 1) ++cnt;
if (cnt == 3) ++cur;
if (cnt == 4) cur += 4;
}
if (cur == want) {
haveret = true;
for (int j = (0); j < (n); ++j) ret[j] = (msk >> j) & 1 ? '*' : '.';
return;
}
}
}
void greedy() {
if (h == 2 && want == (w - 2) * 4) {
haveret = true;
for (int x = (0); x < (h); ++x)
for (int y = (0); y < (w); ++y)
ret[x * w + y] = 0 <= y && y < w - 1 ? '*' : '.';
return;
}
if (h == 2 && want == (w - 3) * 4) {
haveret = true;
for (int x = (0); x < (h); ++x)
for (int y = (0); y < (w); ++y)
ret[x * w + y] = 1 <= y && y < w - 1 ? '*' : '.';
return;
}
if (h == 3 && want == (w - 2) * 8) {
haveret = true;
for (int x = (0); x < (h); ++x)
for (int y = (0); y < (w); ++y)
ret[x * w + y] = 0 <= y && y < w - 1 ? '*' : '.';
return;
}
int left = want;
for (int x = (0); x < (h); ++x)
for (int y = (0); y < (w); ++y) ret[x * w + y] = x == 0 ? '*' : '.';
int x, y;
for (x = 1; x < h; ++x) {
for (y = 0; y < w; ++y) {
if (left <= 3 || x == h - 1 && w - y == 4) break;
ret[x * w + y] = '*';
left -= y == 0 ? 1 : y == w - 1 ? 3 : 4;
}
if (left <= 3 || x == h - 1 && w - y == 4) break;
}
if (x == h - 1 && w - y == 4) {
for (int msk = (0); msk < (1 << 4); ++msk) {
int cur = 0;
for (int yy = (0); yy < (4); ++yy) {
int cnt = 0;
for (int dy = (0); dy < (2); ++dy)
if (yy + dy == 0 || (msk >> (yy + dy - 1) & 1)) ++cnt;
if (cnt == 1) ++cur;
if (cnt == 2) cur += 4;
}
if (cur - 1 == left) {
haveret = true;
for (int j = (0); j < (4); ++j)
ret[x * w + y + j] = (msk >> j) & 1 ? '*' : '.';
return;
}
}
}
if (left <= 3) {
int dy = w - y;
int y1 = dy == 2 || dy >= 4 ? w - 1 : 0;
int y2 = dy == 3 ? w - 2 : dy >= 4 ? w - 3 : dy == 2 ? 1 : 2;
if (left & 1) ret[(x + (y1 < y ? 1 : 0)) * w + y1] = '*';
if (left & 2) ret[(x + (y2 < y ? 1 : 0)) * w + y2] = '*';
haveret = true;
}
}
void run() {
scanf("%d%d%d", &h, &w, &want);
n = h * w;
haveret = false;
if (h <= 4 && w <= 4) {
bf();
} else {
bool swp = w < h;
if (swp) swap(w, h);
greedy();
if (swp) {
swap(w, h);
for (int x = (0); x < (h); ++x)
for (int y = (0); y < (w); ++y) nret[x * w + y] = ret[y * h + x];
for (int i = (0); i < (n); ++i) ret[i] = nret[i];
}
}
if (!haveret)
printf("-1\n");
else
for (int x = (0); x < (h); ++x) {
for (int y = (0); y < (w); ++y) printf("%c", ret[x * w + y]);
puts("");
}
}
int main() {
int n;
scanf("%d", &n);
for (int i = (1); i <= (n); ++i) {
if (i != 1) puts("");
run();
}
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Little Elephant loves Furik and Rubik, who he met in a small city Kremenchug.
The Little Elephant has two strings of equal length a and b, consisting only of uppercase English letters. The Little Elephant selects a pair of substrings of equal length β the first one from string a, the second one from string b. The choice is equiprobable among all possible pairs. Let's denote the substring of a as x, and the substring of b β as y. The Little Elephant gives string x to Furik and string y β to Rubik.
Let's assume that f(x, y) is the number of such positions of i (1 β€ i β€ |x|), that xi = yi (where |x| is the length of lines x and y, and xi, yi are the i-th characters of strings x and y, correspondingly). Help Furik and Rubik find the expected value of f(x, y).
Input
The first line contains a single integer n (1 β€ n β€ 2Β·105) β the length of strings a and b. The second line contains string a, the third line contains string b. The strings consist of uppercase English letters only. The length of both strings equals n.
Output
On a single line print a real number β the answer to the problem. The answer will be considered correct if its relative or absolute error does not exceed 10 - 6.
Examples
Input
2
AB
BA
Output
0.400000000
Input
3
AAB
CAA
Output
0.642857143
Note
Let's assume that we are given string a = a1a2... a|a|, then let's denote the string's length as |a|, and its i-th character β as ai.
A substring a[l... r] (1 β€ l β€ r β€ |a|) of string a is string alal + 1... ar.
String a is a substring of string b, if there exists such pair of integers l and r (1 β€ l β€ r β€ |b|), that b[l... r] = a.
Let's consider the first test sample. The first sample has 5 possible substring pairs: ("A", "B"), ("A", "A"), ("B", "B"), ("B", "A"), ("AB", "BA"). For the second and third pair value f(x, y) equals 1, for the rest it equals 0. The probability of choosing each pair equals <image>, that's why the answer is <image> Β· 0 + <image> Β· 1 + <image> Β· 1 + <image> Β· 0 + <image> Β· 0 = <image> = 0.4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
double a[30], b[30], res = 0;
string s1, s2;
double n;
cin >> n;
cin >> s1 >> s2;
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
for (int i = 0; s1[i]; i++) {
int A = s1[i] - 'A';
int B = s2[i] - 'A';
a[A] += i + 1;
res += (n - i) * (a[B] + b[A]);
b[B] += i + 1;
}
res /= (n * (n + 1) * (n * 2 + 1) / 6.0);
printf("%.9lf\n", res);
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
After returning from the army Makes received a gift β an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that aiΒ·ajΒ·ak is minimum possible, are there in the array? Help him with it!
Input
The first line of input contains a positive integer number n (3 β€ n β€ 105) β the number of elements in array a. The second line contains n positive integer numbers ai (1 β€ ai β€ 109) β the elements of a given array.
Output
Print one number β the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and aiΒ·ajΒ·ak is minimum possible.
Examples
Input
4
1 1 1 1
Output
4
Input
5
1 3 2 3 4
Output
2
Input
6
1 3 3 1 3 2
Output
1
Note
In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.
In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.
In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int mod = 998244353;
const int mex = 250002;
long long int power(long long int a, long long int b) {
long long int ans = 1, f = a;
while (b) {
if (b & 1) ans = (ans * f) % mod;
b = b >> 1;
f = (f * f) % mod;
}
return ans % mod;
}
int sl(int a[2][3]) {
vector<long long int> v;
for (int i = 0; i < 3; i++) {
for (int j = i + 1; j < 3; j++) {
long long int y = (a[0][j] - a[0][i]) * (a[0][j] - a[0][i]) +
(a[1][j] - a[1][i]) * (a[1][j] - a[1][i]);
v.push_back(y);
}
}
sort(v.begin(), v.end());
if (v[0] == 0 || v[1] == 0 || v[2] == 0) return 0;
if (v[2] == (v[0] + v[1]))
return 1;
else
return 0;
}
int main() {
int n;
cin >> n;
long long int a[n];
for (int i = 0; i < n; i++) cin >> a[i];
sort(a, a + n);
long long int ans = 0;
map<int, int> mp;
for (int i = 0; i < n; i++) {
mp[a[i]]++;
if (mp.size() == 4) break;
}
auto it = mp.begin();
if (it->second >= 3) {
long long int u = it->second;
u = (u * (u - 1) * (u - 2)) / 6;
ans = u;
} else if (it->second >= 2) {
it++;
long long int u = it->second;
ans = u;
} else {
it++;
if (it->second == 1) {
it++;
ans = it->second;
} else {
long long int u = it->second;
u = (u * (u - 1)) / 2;
ans = u;
}
}
cout << ans;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
The cows have just learned what a primitive root is! Given a prime p, a primitive root <image> is an integer x (1 β€ x < p) such that none of integers x - 1, x2 - 1, ..., xp - 2 - 1 are divisible by p, but xp - 1 - 1 is.
Unfortunately, computing primitive roots can be time consuming, so the cows need your help. Given a prime p, help the cows find the number of primitive roots <image>.
Input
The input contains a single line containing an integer p (2 β€ p < 2000). It is guaranteed that p is a prime.
Output
Output on a single line the number of primitive roots <image>.
Examples
Input
3
Output
1
Input
5
Output
2
Note
The only primitive root <image> is 2.
The primitive roots <image> are 2 and 3.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47};
int phi(int n) {
int num = 1, root = (int)sqrt(n), *prime = primes, Phi = n, N = n;
for (; *prime <= root && n != 1; prime++)
if (!(n % *prime)) {
Phi = Phi / (*prime) * (*prime - 1);
for (; !(n % *prime); n /= *prime, num *= *prime)
;
}
if (num != N) {
num = N / num;
Phi = Phi / num * (num - 1);
}
return Phi;
}
int main() {
int p;
while (scanf("%d", &p) != EOF) printf("%d\n", phi(phi(p)));
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".
To play Mau-Mau, you need a pack of 52 cards. Each card has a suit (Diamonds β D, Clubs β C, Spades β S, or Hearts β H), and a rank (2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, or A).
At the start of the game, there is one card on the table and you have five cards in your hand. You can play a card from your hand if and only if it has the same rank or the same suit as the card on the table.
In order to check if you'd be a good playing partner, Gennady has prepared a task for you. Given the card on the table and five cards in your hand, check if you can play at least one card.
Input
The first line of the input contains one string which describes the card on the table. The second line contains five strings which describe the cards in your hand.
Each string is two characters long. The first character denotes the rank and belongs to the set \{{\tt 2}, {\tt 3}, {\tt 4}, {\tt 5}, {\tt 6}, {\tt 7}, {\tt 8}, {\tt 9}, {\tt T}, {\tt J}, {\tt Q}, {\tt K}, {\tt A}\}. The second character denotes the suit and belongs to the set \{{\tt D}, {\tt C}, {\tt S}, {\tt H}\}.
All the cards in the input are different.
Output
If it is possible to play a card from your hand, print one word "YES". Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Examples
Input
AS
2H 4C TH JH AD
Output
YES
Input
2H
3D 4C AC KD AS
Output
NO
Input
4D
AS AC AD AH 5H
Output
YES
Note
In the first example, there is an Ace of Spades (AS) on the table. You can play an Ace of Diamonds (AD) because both of them are Aces.
In the second example, you cannot play any card.
In the third example, you can play an Ace of Diamonds (AD) because it has the same suit as a Four of Diamonds (4D), which lies on the table.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string str, str1;
cin >> str;
long long int i;
for (i = 1; i <= 5; ++i) {
cin >> str1;
if (str1[0] == str[0] || str1[1] == str[1]) {
puts("YES");
return 0;
}
}
puts("NO");
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Professor Random, known for his research on randomized algorithms, is now conducting an experiment on biased dice. His experiment consists of dropping a number of dice onto a plane, one after another from a fixed position above the plane. The dice fall onto the plane or dice already there, without rotating, and may roll and fall according to their property. Then he observes and records the status of the stack formed on the plane, specifically, how many times each number appears on the faces visible from above. All the dice have the same size and their face numbering is identical, which we show in Figure C-1.
<image>
Figure C-1: Numbering of a die
The dice have very special properties, as in the following.
(1) Ordinary dice can roll in four directions, but the dice used in this experiment never roll in the directions of faces 1, 2 and 3; they can only roll in the directions of faces 4, 5 and 6. In the situation shown in Figure C-2, our die can only roll to one of two directions.
<image>
Figure C-2: An ordinary die and a biased die
(2) The die can only roll when it will fall down after rolling, as shown in Figure C-3. When multiple possibilities exist, the die rolls towards the face with the largest number among those directions it can roll to.
<image>
Figure C-3: A die can roll only when it can fall
(3) When a die rolls, it rolls exactly 90 degrees, and then falls straight down until its bottom face touches another die or the plane, as in the case [B] or [C] of Figure C-4.
(4) After rolling and falling, the die repeatedly does so according to the rules (1) to (3) above.
<image>
Figure C-4: Example stacking of biased dice
For example, when we drop four dice all in the same orientation, 6 at the top and 4 at the front, then a stack will be formed as shown in Figure C-4.
<image>
Figure C-5: Example records
After forming the stack, we count the numbers of faces with 1 through 6 visible from above and record them. For example, in the left case of Figure C-5, the record will be "0 2 1 0 0 0", and in the right case, "0 1 1 0 0 1".
Input
The input consists of several datasets each in the following format.
> n
> t1 f1
> t2 f2
> ...
> tn fn
>
Here, n (1 β€ n β€ 100) is an integer and is the number of the dice to be dropped. ti and fi (1 β€ ti, fi β€ 6) are two integers separated by a space and represent the numbers on the top and the front faces of the i-th die, when it is released, respectively.
The end of the input is indicated by a line containing a single zero.
Output
For each dataset, output six integers separated by a space. The integers represent the numbers of faces with 1 through 6 correspondingly, visible from above. There may not be any other characters in the output.
Sample Input
4
6 4
6 4
6 4
6 4
2
5 3
5 3
8
4 2
4 2
4 2
4 2
4 2
4 2
4 2
4 2
6
4 6
1 5
2 3
5 3
2 4
4 2
0
Output for the Sample Input
0 1 1 0 0 1
1 0 0 0 1 0
1 2 2 1 0 0
2 3 0 0 0 0
Example
Input
4
6 4
6 4
6 4
6 4
2
5 3
5 3
8
4 2
4 2
4 2
4 2
4 2
4 2
4 2
4 2
6
4 6
1 5
2 3
5 3
2 4
4 2
0
Output
0 1 1 0 0 1
1 0 0 0 1 0
1 2 2 1 0 0
2 3 0 0 0 0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define REP(i,n) for(int i=0; i<n; i++)
using ll = long long;
int dx[] = {1,-1,0,0,0,0};
int dy[] = {0,0,1,-1,0,0};
int dz[] = {0,0,0,0,1,-1};
struct Dice {
int v[6];
Dice(){};
Dice(const Dice &d){
REP(i,6)v[i]=d.v[i];
}
Dice(int top, int front){
v[4] = top;
v[0] = front;
v[5] = 7-top;
v[1] = 7-front;
int mn = min({top,front,7-top,7-front});
int mn2 = 7;
REP(i,6)if(i!=2 && i!=3 && v[i]!=mn){
mn2 = min(mn2,v[i]);
}
int cnt = 0;
while(v[4]!=mn)rotate(0),cnt++;
if(v[4]==1 && v[0]==2){
v[2]=3;
}else if(v[4]==1 && v[0]==5){
v[2]=4;
}else if(v[4]==1 && v[0]==3){
v[2]=5;
}else if(v[4]==1 && v[0]==4){
v[2]=2;
}else if(v[4]==2 && v[0]==3){
v[2]=1;
}else{
v[2]=6;
}
v[3]=7-v[2];
while(cnt--)rotate(1);
}
void rotate(int d){
vector<int> ids;
if(d==1){
ids = vector<int>({4,0,5,1});
}else if(d==0){
ids = vector<int>({4,1,5,0});
}else if(d==3){
ids = vector<int>({4,2,5,3});
}else{
ids = vector<int>({4,3,5,2});
}
REP(i,3)swap(v[ids[i]],v[ids[i+1]]);
// abcd -> bacd -> bcad -> bcda
}
};
int field[252][252][125];
int main(){
while(true){
int n;
cin>>n;
if(n==0)break;
REP(i,252)REP(j,252)REP(k,125)field[i][j][k] = -1;
REP(i,252)REP(j,252)field[i][j][0] = 0;
int cnt[7] = {};
while(n--){
int t,f;
cin>>t>>f;
Dice di(t,f);
int x = 125, y = 125, z = 124;
while(field[x][y][z-1]==-1)z--;
while(true){
int nd = -1, nv = -1;
REP(d,4){
if(di.v[d]<4)continue;
int nx = x+dx[d];
int ny = y+dy[d];
if(field[nx][ny][z-1]==-1 && di.v[d]>nv){
nd = d;
nv = di.v[d];
}
}
if(nd==-1)break;
x += dx[nd];
y += dy[nd];
di.rotate(nd);
while(field[x][y][z-1]==-1)z--;
}
// printf("%d %d %d, t=%d, f=%d\n",x,y,z,di.v[4],di.v[0]);
cnt[field[x][y][z-1]]--;
cnt[field[x][y][z] = di.v[4]]++;
}
REP(i,6)printf("%d%c",cnt[i+1]," \n"[i==5]);
}
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
The winter in Berland lasts n days. For each day we know the forecast for the average air temperature that day.
Vasya has a new set of winter tires which allows him to drive safely no more than k days at any average air temperature. After k days of using it (regardless of the temperature of these days) the set of winter tires wears down and cannot be used more. It is not necessary that these k days form a continuous segment of days.
Before the first winter day Vasya still uses summer tires. It is possible to drive safely on summer tires any number of days when the average air temperature is non-negative. It is impossible to drive on summer tires at days when the average air temperature is negative.
Vasya can change summer tires to winter tires and vice versa at the beginning of any day.
Find the minimum number of times Vasya needs to change summer tires to winter tires and vice versa to drive safely during the winter. At the end of the winter the car can be with any set of tires.
Input
The first line contains two positive integers n and k (1 β€ n β€ 2Β·105, 0 β€ k β€ n) β the number of winter days and the number of days winter tires can be used. It is allowed to drive on winter tires at any temperature, but no more than k days in total.
The second line contains a sequence of n integers t1, t2, ..., tn ( - 20 β€ ti β€ 20) β the average air temperature in the i-th winter day.
Output
Print the minimum number of times Vasya has to change summer tires to winter tires and vice versa to drive safely during all winter. If it is impossible, print -1.
Examples
Input
4 3
-5 20 -3 0
Output
2
Input
4 2
-5 20 -3 0
Output
4
Input
10 6
2 -5 1 3 0 0 -4 -3 1 0
Output
3
Note
In the first example before the first winter day Vasya should change summer tires to winter tires, use it for three days, and then change winter tires to summer tires because he can drive safely with the winter tires for just three days. Thus, the total number of tires' changes equals two.
In the second example before the first winter day Vasya should change summer tires to winter tires, and then after the first winter day change winter tires to summer tires. After the second day it is necessary to change summer tires to winter tires again, and after the third day it is necessary to change winter tires to summer tires. Thus, the total number of tires' changes equals four.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[200001];
vector<int> v;
vector<pair<int, int> > v1;
int main() {
int n, k, cnt = 0;
scanf("%d%d", &n, &k);
int naive = 0;
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
if (a[i] < 0) {
cnt++;
if (i > 0 && a[i - 1] >= 0) {
naive++;
} else if (i == 0) {
naive++;
}
v.push_back(i);
} else {
if (i > 0 && a[i - 1] < 0) {
naive++;
}
}
}
if (k < cnt) {
printf("-1");
return 0;
}
if (v.size() == 0) {
printf("0");
return 0;
}
k = k - cnt;
for (int i = 0; i < v.size() - 1; i++) {
int x = v[i];
int y = v[i + 1];
if (y == x + 1) continue;
v1.push_back(make_pair((y - x - 1), 0));
}
sort(v1.begin(), v1.end());
int i;
for (i = 0; i < v1.size(); i++) {
if (k <= 0) break;
if (v1[i].first <= k) {
k -= v1[i].first;
naive -= 2;
if (v1[i].second == 1000000000) {
naive++;
}
} else
break;
}
if ((n - 1) > (v[v.size() - 1])) {
if ((n - 1 - v[v.size() - 1]) <= k) naive--;
}
printf("%d", naive);
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Little Paul wants to learn how to play piano. He already has a melody he wants to start with. For simplicity he represented this melody as a sequence a_1, a_2, β¦, a_n of key numbers: the more a number is, the closer it is to the right end of the piano keyboard.
Paul is very clever and knows that the essential thing is to properly assign fingers to notes he's going to play. If he chooses an inconvenient fingering, he will then waste a lot of time trying to learn how to play the melody by these fingers and he will probably not succeed.
Let's denote the fingers of hand by numbers from 1 to 5. We call a fingering any sequence b_1, β¦, b_n of fingers numbers. A fingering is convenient if for all 1β€ i β€ n - 1 the following holds:
* if a_i < a_{i+1} then b_i < b_{i+1}, because otherwise Paul needs to take his hand off the keyboard to play the (i+1)-st note;
* if a_i > a_{i+1} then b_i > b_{i+1}, because of the same;
* if a_i = a_{i+1} then b_iβ b_{i+1}, because using the same finger twice in a row is dumb. Please note that there is β , not = between b_i and b_{i+1}.
Please provide any convenient fingering or find out that there is none.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) denoting the number of notes.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 2β
10^5) denoting the positions of notes on the keyboard.
Output
If there is no convenient fingering, print -1. Otherwise, print n numbers b_1, b_2, β¦, b_n, each from 1 to 5, denoting a convenient fingering, separated by spaces.
Examples
Input
5
1 1 4 2 2
Output
1 4 5 4 5
Input
7
1 5 7 8 10 3 1
Output
1 2 3 4 5 4 3
Input
19
3 3 7 9 8 8 8 8 7 7 7 7 5 3 3 3 3 8 8
Output
1 3 4 5 4 5 4 5 4 5 4 5 4 3 5 4 3 5 4
Note
The third sample test is kinda "Non stop" song by Reflex.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n, p;
cin >> n;
long long a[n], b[n];
for (long long i = 0; i < n; i++) cin >> a[i];
if (a[0] > a[1]) b[0] = 5;
if (a[0] < a[1]) b[0] = 1;
if (a[0] == a[1]) b[0] = 3;
for (long long i = 0; i < n - 1; i++) {
if ((a[i + 1] > a[i]) && (b[i] == 5)) {
cout << -1 << endl;
return 0;
} else if ((a[i + 1] < a[i]) && (b[i] == 1)) {
cout << -1 << endl;
return 0;
} else if (a[i + 1] > a[i]) {
p = b[i] + 1;
if ((i + 2) < n) {
if (a[i + 2] < a[i + 1]) p = 5;
}
} else if (a[i + 1] < a[i]) {
p = b[i] - 1;
if ((i + 2) < n) {
if (a[i + 2] > a[i + 1]) p = 1;
}
} else if (a[i + 1] == a[i]) {
p = (b[i] == 3) ? 2 : 3;
if ((i + 2) < n) {
if (a[i + 2] > a[i + 1])
p = (b[i] == 1) ? 2 : 1;
else if (a[i + 2] < a[i + 1])
p = (b[i] == 5) ? 4 : 5;
}
}
b[i + 1] = p;
}
for (long long i = 0; i < n; i++) cout << b[i] << " ";
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
We have N bricks arranged in a row from left to right.
The i-th brick from the left (1 \leq i \leq N) has an integer a_i written on it.
Among them, you can break at most N-1 bricks of your choice.
Let us say there are K bricks remaining. Snuke will be satisfied if, for each integer i (1 \leq i \leq K), the i-th of those brick from the left has the integer i written on it.
Find the minimum number of bricks you need to break to satisfy Snuke's desire. If his desire is unsatisfiable, print `-1` instead.
Constraints
* All values in input are integers.
* 1 \leq N \leq 200000
* 1 \leq a_i \leq N
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum number of bricks that need to be broken to satisfy Snuke's desire, or print `-1` if his desire is unsatisfiable.
Examples
Input
3
2 1 2
Output
1
Input
3
2 2 2
Output
-1
Input
10
3 1 4 1 5 9 2 6 5 3
Output
7
Input
1
1
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin>>N;
int Z=0,A=1;
for(int i=0;i<N;i++){
int a;
cin>>a;
if(a==A){
A++;
}
else{
Z++;
}
}
if(Z==N){
Z=-1;
}
cout<<Z<<endl;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Earlier, when there was no Internet, each bank had a lot of offices all around Bankopolis, and it caused a lot of problems. Namely, each day the bank had to collect cash from all the offices.
Once Oleg the bank client heard a dialogue of two cash collectors. Each day they traveled through all the departments and offices of the bank following the same route every day. The collectors started from the central department and moved between some departments or between some department and some office using special roads. Finally, they returned to the central department. The total number of departments and offices was n, the total number of roads was n - 1. In other words, the special roads system was a rooted tree in which the root was the central department, the leaves were offices, the internal vertices were departments. The collectors always followed the same route in which the number of roads was minimum possible, that is 2n - 2.
One of the collectors said that the number of offices they visited between their visits to offices a and then b (in the given order) is equal to the number of offices they visited between their visits to offices b and then a (in this order). The other collector said that the number of offices they visited between their visits to offices c and then d (in this order) is equal to the number of offices they visited between their visits to offices d and then c (in this order). The interesting part in this talk was that the shortest path (using special roads only) between any pair of offices among a, b, c and d passed through the central department.
Given the special roads map and the indexes of offices a, b, c and d, determine if the situation described by the collectors was possible, or not.
Input
The first line contains single integer n (5 β€ n β€ 5000) β the total number of offices and departments. The departments and offices are numbered from 1 to n, the central office has index 1.
The second line contains four integers a, b, c and d (2 β€ a, b, c, d β€ n) β the indexes of the departments mentioned in collector's dialogue. It is guaranteed that these indexes are offices (i.e. leaves of the tree), not departments. It is guaranteed that the shortest path between any pair of these offices passes through the central department.
On the third line n - 1 integers follow: p2, p3, ..., pn (1 β€ pi < i), where pi denotes that there is a special road between the i-th office or department and the pi-th department.
Please note the joint enumeration of departments and offices.
It is guaranteed that the given graph is a tree. The offices are the leaves, the departments are the internal vertices.
Output
If the situation described by the cash collectors was possible, print "YES". Otherwise, print "NO".
Examples
Input
5
2 3 4 5
1 1 1 1
Output
YES
Input
10
3 8 9 10
1 2 2 2 2 2 1 1 1
Output
NO
Input
13
13 12 9 7
1 1 1 1 5 5 2 2 2 3 3 4
Output
YES
Note
In the first example the following collector's route was possible: <image>. We can note that between their visits to offices a and b the collectors visited the same number of offices as between visits to offices b and a; the same holds for c and d (the collectors' route is infinite as they follow it each day).
In the second example there is no route such that between their visits to offices c and d the collectors visited the same number of offices as between visits to offices d and c. Thus, there situation is impossible.
In the third example one of the following routes is: <image>.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }
const int MAXN = 5000;
typedef struct Knap {
int opt[MAXN], nopt;
bool dp[MAXN + 1];
void clear() { nopt = 0; }
void add(int x) { opt[nopt++] = x; }
bool can(int want) {
for (int j = (0); j <= (want); ++j) dp[j] = false;
dp[0] = true;
for (int i = (0); i < (nopt); ++i)
for (int j = want; j >= opt[i]; --j)
if (dp[j - opt[i]]) dp[j] = true;
return dp[want];
}
} Knap;
Knap knap;
int n;
int A, B, C, D;
int par[MAXN];
int chead[MAXN], cnxt[MAXN];
int sz[MAXN];
int mask[MAXN];
void dfs(int at) {
sz[at] = chead[at] == -1 ? 1 : 0;
mask[at] = 0;
if (at == A) mask[at] |= 1;
if (at == B) mask[at] |= 2;
if (at == C) mask[at] |= 4;
if (at == D) mask[at] |= 8;
for (int to = chead[at]; to != -1; to = cnxt[to]) {
dfs(to);
sz[at] += sz[to];
mask[at] |= mask[to];
}
}
void run() {
scanf("%d", &n);
scanf("%d%d%d%d", &A, &B, &C, &D);
--A, --B, --C, --D;
par[0] = -1;
for (int i = (1); i < (n); ++i) {
scanf("%d", &par[i]);
--par[i];
}
for (int i = (0); i < (n); ++i) chead[i] = -1;
for (int i = (1); i < (n); ++i) cnxt[i] = chead[par[i]], chead[par[i]] = i;
dfs(0);
int nleaf = 0;
for (int i = (0); i < (n); ++i)
if (chead[i] == -1) ++nleaf;
if (nleaf % 2 == 1) {
printf("NO\n");
return;
}
for (int x = (0); x < (2); ++x) {
knap.clear();
int want = nleaf / 2 - 1;
for (int i = (1); i < (n); ++i)
if (par[i] == 0 && mask[i] == 0) knap.add(sz[i]);
for (int i = (1); i < (n); ++i)
if (mask[i] == 0 && (mask[par[i]] == (1 << (0 + 2 * x)) ||
mask[par[i]] == (1 << (1 + 2 * x))))
knap.add(sz[i]);
for (int i = (1); i < (n); ++i)
if (par[i] == 0 && mask[i] == (1 << (2 - x))) want -= sz[i];
if (!knap.can(want)) {
printf("NO\n");
return;
}
}
printf("YES\n");
}
int main() {
run();
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and ai < aj. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation a of size n and m queries to it. Each query is represented by two indices l and r denoting that you have to reverse the segment [l, r] of the permutation. For example, if a = [1, 2, 3, 4] and a query l = 2, r = 4 is applied, then the resulting permutation is [1, 4, 3, 2].
After each query you have to determine whether the number of inversions is odd or even.
Input
The first line contains one integer n (1 β€ n β€ 1500) β the size of the permutation.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β the elements of the permutation. These integers are pairwise distinct.
The third line contains one integer m (1 β€ m β€ 2Β·105) β the number of queries to process.
Then m lines follow, i-th line containing two integers li, ri (1 β€ li β€ ri β€ n) denoting that i-th query is to reverse a segment [li, ri] of the permutation. All queries are performed one after another.
Output
Print m lines. i-th of them must be equal to odd if the number of inversions in the permutation after i-th query is odd, and even otherwise.
Examples
Input
3
1 2 3
2
1 2
2 3
Output
odd
even
Input
4
1 2 4 3
4
1 1
1 4
1 4
2 3
Output
odd
odd
odd
even
Note
The first example:
1. after the first query a = [2, 1, 3], inversion: (2, 1);
2. after the second query a = [2, 3, 1], inversions: (3, 1), (3, 2).
The second example:
1. a = [1, 2, 4, 3], inversion: (4, 3);
2. a = [3, 4, 2, 1], inversions: (3, 1), (4, 1), (3, 2), (4, 2), (4, 3);
3. a = [1, 2, 4, 3], inversion: (4, 3);
4. a = [1, 4, 2, 3], inversions: (3, 2), (4, 2).
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")
#pragma GCC optimize("unroll-loops")
using namespace std;
using ll = long long;
using pii = pair<int, int>;
template <class T = int>
struct Fenwick {
vector<T> t;
T tn;
Fenwick(int _n) {
assert(_n > 0);
tn = _n;
t = vector<T>(tn + 1, 0);
}
void update(int x, T val) {
x++;
while (x <= tn) {
t[x] += val;
x += (x & -x);
}
}
T query(int x) {
assert(x < tn);
x++;
int res = 0;
while (x > 0) {
res += t[x];
x -= (x & -x);
}
return res;
}
T query(int l, int r) {
assert(l <= r);
if (l == 0) return query(r);
return query(r) - query(l - 1);
}
int find_last_prefix(T sum) {
if (sum < 0) return -1;
int pref = 0;
for (int k = 31 - __builtin_clz(tn); k >= 0; k--) {
if (pref + (1 << k) <= tn && t[pref + (1 << k)] <= sum) {
pref += 1 << k;
sum -= t[pref];
}
}
return pref;
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, m;
cin >> n;
vector<int> p(n);
for (auto& x : p) cin >> x;
int isodd = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (p[i] > p[j]) isodd ^= 1;
cin >> m;
while (m--) {
int l, r;
cin >> l >> r;
int swaps = (r - l + 1);
swaps = swaps * (swaps - 1) / 2;
isodd ^= (swaps & 1);
if (isodd)
cout << "odd\n";
else
cout << "even\n";
}
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
In the Isle of Guernsey there are n different types of coins. For each i (1 β€ i β€ n), coin of type i is worth ai cents. It is possible that ai = aj for some i and j (i β j).
Bessie has some set of these coins totaling t cents. She tells Jessie q pairs of integers. For each i (1 β€ i β€ q), the pair bi, ci tells Jessie that Bessie has a strictly greater number of coins of type bi than coins of type ci. It is known that all bi are distinct and all ci are distinct.
Help Jessie find the number of possible combinations of coins Bessie could have. Two combinations are considered different if there is some i (1 β€ i β€ n), such that the number of coins Bessie has of type i is different in the two combinations. Since the answer can be very large, output it modulo 1000000007 (109 + 7).
If there are no possible combinations of coins totaling t cents that satisfy Bessie's conditions, output 0.
Input
The first line contains three space-separated integers, n, q and t (1 β€ n β€ 300; 0 β€ q β€ n; 1 β€ t β€ 105). The second line contains n space separated integers, a1, a2, ..., an (1 β€ ai β€ 105). The next q lines each contain two distinct space-separated integers, bi and ci (1 β€ bi, ci β€ n; bi β ci).
It's guaranteed that all bi are distinct and all ci are distinct.
Output
A single integer, the number of valid coin combinations that Bessie could have, modulo 1000000007 (109 + 7).
Examples
Input
4 2 17
3 1 2 5
4 2
3 4
Output
3
Input
3 2 6
3 1 1
1 2
2 3
Output
0
Input
3 2 10
1 2 3
1 2
2 1
Output
0
Note
For the first sample, the following 3 combinations give a total of 17 cents and satisfy the given conditions: {0 of type 1, 1 of type 2, 3 of type 3, 2 of type 4}, {0, 0, 6, 1}, {2, 0, 3, 1}.
No other combinations exist. Note that even though 4 occurs in both bi and ci, the problem conditions are still satisfied because all bi are distinct and all ci are distinct.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long MAXN = 3e2 + 10;
const long long MAXT = 1e5 + 10;
const long long Mod = 1e9 + 7;
long long dp[MAXN][MAXT];
long long a[MAXN];
long long b[MAXN];
long long f[MAXN];
bool e[MAXN];
bool check[MAXN];
long long t = 1;
void dfs(long long v) {
if (v == 0) {
return;
}
check[v] = true;
b[t++] = v;
dfs(f[v]);
}
int main() {
ios_base ::sync_with_stdio(false);
cin.tie(0);
long long n, q, t, sum = 0;
cin >> n >> q >> t;
for (long long i = 1; i <= n; i++) {
cin >> a[i];
}
for (long long i = 0; i < q; i++) {
long long v, u;
cin >> v >> u;
f[v] = u;
e[u] = true;
}
for (long long i = 1; i <= n; i++) {
if (!e[i]) {
dfs(i);
}
}
for (long long i = 1; i <= n; i++) {
if (!check[i]) {
cout << 0;
return 0;
}
}
dp[0][0] = 1;
for (long long i = 1; i <= n; i++) {
if (!e[b[i]]) {
sum = 0;
}
sum += a[b[i]];
for (long long j = 0; j < MAXT; j++) {
dp[i][j] = (j >= sum - a[b[i]] ? dp[i - 1][j - sum + a[b[i]]] : 0) +
(j >= sum ? dp[i][j - sum] : 0);
dp[i][j] %= Mod;
}
}
cout << dp[n][t];
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Artem is building a new robot. He has a matrix a consisting of n rows and m columns. The cell located on the i-th row from the top and the j-th column from the left has a value a_{i,j} written in it.
If two adjacent cells contain the same value, the robot will break. A matrix is called good if no two adjacent cells contain the same value, where two cells are called adjacent if they share a side.
Artem wants to increment the values in some cells by one to make a good.
More formally, find a good matrix b that satisfies the following condition β
* For all valid (i,j), either b_{i,j} = a_{i,j} or b_{i,j} = a_{i,j}+1.
For the constraints of this problem, it can be shown that such a matrix b always exists. If there are several such tables, you can output any of them. Please note that you do not have to minimize the number of increments.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 10). Description of the test cases follows.
The first line of each test case contains two integers n, m (1 β€ n β€ 100, 1 β€ m β€ 100) β the number of rows and columns, respectively.
The following n lines each contain m integers. The j-th integer in the i-th line is a_{i,j} (1 β€ a_{i,j} β€ 10^9).
Output
For each case, output n lines each containing m integers. The j-th integer in the i-th line is b_{i,j}.
Example
Input
3
3 2
1 2
4 5
7 8
2 2
1 1
3 3
2 2
1 3
2 2
Output
1 2
5 6
7 8
2 1
4 3
2 4
3 2
Note
In all the cases, you can verify that no two adjacent cells have the same value and that b is the same as a with some values incremented by one.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m;
int a[105][105];
inline int getint() {
int num = 0, bj = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == EOF) return EOF;
bj = (c == '-' || bj == -1) ? -1 : 1, c = getchar();
}
while (c >= '0' && c <= '9') num = num * 10 + c - '0', c = getchar();
return num * bj;
}
void init() {
n = getint();
m = getint();
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) a[i][j] = getint();
}
}
void solve() {
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
a[i][j] += (a[i][j] % 2 == (i + j) % 2 ? 0 : 1);
cout << a[i][j] << " ";
}
cout << "\n";
}
}
int main() {
int T;
cin >> T;
while (T--) {
init();
solve();
}
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Tic-tac-toe is a game in which you win when you put β and Γ alternately in the 3 Γ 3 squares and line up β or Γ in one of the vertical, horizontal, and diagonal lines (Fig.). 1 to Fig. 3)
<image> | <image> | <image>
--- | --- | ---
Figure 1: β wins | Figure 2: Γ wins | Figure 3: Draw
In tic-tac-toe, β and Γ alternately fill the squares, and the game ends when either one is lined up. Therefore, as shown in Fig. 4, it is impossible for both β and Γ to be aligned. No improbable aspect is entered.
<image>
---
Figure 4: Impossible phase
Please create a program that reads the board of tic-tac-toe and outputs the result of victory or defeat.
Input
The input consists of multiple datasets. For each data set, one character string representing the board is given on one line. The character strings on the board are represented by o, x, and s in half-width lowercase letters for β, Γ, and blanks, respectively, and are arranged in the order of the squares in the figure below.
<image>
The number of datasets does not exceed 50.
Output
For each data set, output o in half-width lowercase letters if β wins, x in lowercase half-width letters if Γ wins, and d in lowercase half-width letters if it is a draw.
Example
Input
ooosxssxs
xoosxsosx
ooxxxooxo
Output
o
x
d
### Response
```cpp
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
using namespace std;
char a[4][4];
bool f(char c){
for(int y = 0; y < 3; y++){
int cnt = 0;
for(int x = 0; x < 3; x++){
if( a[y][x] == c ) cnt++;
}
if( cnt == 3 ) return true;
}
for(int x = 0; x < 3; x++){
int cnt = 0;
for(int y = 0; y < 3; y++){
if( a[y][x] == c ) cnt++;
}
if( cnt == 3 ) return true;
}
if( a[0][0] == c && a[1][1] == c && a[2][2] == c ) return true;
if( a[0][2] == c && a[1][1] == c && a[2][0] == c ) return true;
return false;
}
int main(){
while( cin >> a[0][0] ){
for(int i = 1; i < 9; i++){
int x = i % 3, y = i / 3;
cin >> a[y][x];
}
if( f('x') ){
cout << "x" << endl;
}else if( f('o') ){
cout << "o" << endl;
}else{
cout << "d" << endl;
}
cin.ignore();
}
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it [here](http://tiny.cc/636xmz).
The picture showing the correct sudoku solution:
<image>
Blocks are bordered with bold black color.
Your task is to change at most 9 elements of this field (i.e. choose some 1 β€ i, j β€ 9 and change the number at the position (i, j) to any other number in range [1; 9]) to make it anti-sudoku. The anti-sudoku is the 9 Γ 9 field, in which:
* Any number in this field is in range [1; 9];
* each row contains at least two equal elements;
* each column contains at least two equal elements;
* each 3 Γ 3 block (you can read what is the block in the link above) contains at least two equal elements.
It is guaranteed that the answer exists.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case consists of 9 lines, each line consists of 9 characters from 1 to 9 without any whitespaces β the correct solution of the sudoku puzzle.
Output
For each test case, print the answer β the initial field with at most 9 changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
Example
Input
1
154873296
386592714
729641835
863725149
975314628
412968357
631457982
598236471
247189563
Output
154873396
336592714
729645835
863725145
979314628
412958357
631457992
998236471
247789563
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long int t, ti = 0;
cin >> t;
while ((ti++) != t) {
long long int ar[10][10];
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
scanf("%1lld", &ar[i][j]);
}
}
ar[2][2] = ar[2][1];
ar[1][7] = ar[1][6];
ar[3][6] = ar[3][9];
ar[5][3] = ar[5][1];
ar[4][9] = ar[4][6];
ar[6][5] = ar[6][8];
ar[8][1] = ar[8][2];
ar[9][4] = ar[9][3];
ar[7][8] = ar[7][7];
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) printf("%lld", ar[i][j]);
printf("\n");
}
}
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Vasya is a born Berland film director, he is currently working on a new blockbuster, "The Unexpected". Vasya knows from his own experience how important it is to choose the main characters' names and surnames wisely. He made up a list of n names and n surnames that he wants to use. Vasya haven't decided yet how to call characters, so he is free to match any name to any surname. Now he has to make the list of all the main characters in the following format: "Name1 Surname1, Name2 Surname2, ..., Namen Surnamen", i.e. all the name-surname pairs should be separated by exactly one comma and exactly one space, and the name should be separated from the surname by exactly one space. First of all Vasya wants to maximize the number of the pairs, in which the name and the surname start from one letter. If there are several such variants, Vasya wants to get the lexicographically minimal one. Help him.
An answer will be verified a line in the format as is shown above, including the needed commas and spaces. It's the lexicographical minimality of such a line that needs to be ensured. The output line shouldn't end with a space or with a comma.
Input
The first input line contains number n (1 β€ n β€ 100) β the number of names and surnames. Then follow n lines β the list of names. Then follow n lines β the list of surnames. No two from those 2n strings match. Every name and surname is a non-empty string consisting of no more than 10 Latin letters. It is guaranteed that the first letter is uppercase and the rest are lowercase.
Output
The output data consist of a single line β the needed list. Note that one should follow closely the output data format!
Examples
Input
4
Ann
Anna
Sabrina
John
Petrov
Ivanova
Stoltz
Abacaba
Output
Ann Abacaba, Anna Ivanova, John Petrov, Sabrina Stoltz
Input
4
Aa
Ab
Ac
Ba
Ad
Ae
Bb
Bc
Output
Aa Ad, Ab Ae, Ac Bb, Ba Bc
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 110;
int n, a[26], b[26];
string A[maxn], B[maxn];
namespace Ninit {
void init() {
int i, c;
scanf("%d", &n);
for (i = 0; i < n; ++i) cin >> A[i], ++a[A[i][0] - 'A'], A[i] += ' ';
sort(A, A + n);
for (i = 0; i < n; ++i) cin >> B[i], ++b[B[i][0] - 'A'], B[i] += ',';
sort(B, B + n);
for (i = 0; i < 26; ++i) c = min(a[i], b[i]), a[i] -= c, b[i] -= c;
}
} // namespace Ninit
namespace Nsolve {
bool use[maxn];
void solve() {
int i, j;
for (i = 0; i < n; ++i) {
for (j = 0;; ++j) {
for (; j < n; ++j)
if (!use[j]) break;
if (A[i][0] == B[j][0]) break;
if (a[A[i][0] - 'A'] && b[B[j][0] - 'A']) {
--a[A[i][0] - 'A'], --b[B[j][0] - 'A'];
break;
}
}
use[j] = true;
if (i) cout << ' ';
cout << A[i];
if (i < n - 1)
cout << B[j];
else
cout << B[j].substr(0, B[j].size() - 1);
}
cout << endl;
}
} // namespace Nsolve
int main() {
Ninit::init();
Nsolve::solve();
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
You have a large rectangular board which is divided into n Γ m cells (the board has n rows and m columns). Each cell is either white or black.
You paint each white cell either red or blue. Obviously, the number of different ways to paint them is 2^w, where w is the number of white cells.
After painting the white cells of the board, you want to place the maximum number of dominoes on it, according to the following rules:
* each domino covers two adjacent cells;
* each cell is covered by at most one domino;
* if a domino is placed horizontally (it covers two adjacent cells in one of the rows), it should cover only red cells;
* if a domino is placed vertically (it covers two adjacent cells in one of the columns), it should cover only blue cells.
Let the value of the board be the maximum number of dominoes you can place. Calculate the sum of values of the board over all 2^w possible ways to paint it. Since it can be huge, print it modulo 998 244 353.
Input
The first line contains two integers n and m (1 β€ n, m β€ 3 β
10^5; nm β€ 3 β
10^5) β the number of rows and columns, respectively.
Then n lines follow, each line contains a string of m characters. The j-th character in the i-th string is * if the j-th cell in the i-th row is black; otherwise, that character is o.
Output
Print one integer β the sum of values of the board over all 2^w possible ways to paint it, taken modulo 998 244 353.
Examples
Input
3 4
**oo
oo*o
**oo
Output
144
Input
3 4
**oo
oo**
**oo
Output
48
Input
2 2
oo
o*
Output
4
Input
1 4
oooo
Output
9
### Response
```cpp
#include <cstdlib>
#include <iostream>
#include <cstdio>
#include <math.h>
#include <cstring>
#include <time.h>
#include <complex>
#include <algorithm>
#include <queue>
#include <stack>
#include <unordered_map>
#include <set>
#include <bitset>
#pragma warning(disable:4996)
#define PII std::pair<long long, long long>
#define PTT std::pair<tree *, tree *>
template<typename T> T min(T x, T y)
{
return x < y ? x : y;
}
template<typename T> T max(T x, T y)
{
return x > y ? x : y;
};
const long long INF = 2000000005;//00000;// autojs.org
const long long mod = 998244353;//1000000007;//
const int MAXN = 300005;
int N, M, tot, cntr[MAXN], cntc[MAXN];
std::vector<bool> v[MAXN];
long long f[MAXN][2];
long long qpow(long long x, long long y)
{
if (!y)
return 1;
long long t = qpow(x, y / 2);
t = t * t % mod;
return y & 1 ? t * x % mod : t;
}
void DP(bool *a, int n)
{
static int cnt[MAXN];
for (int i = 1; i <= n; i++)
cnt[i] = cnt[i - 1] + !a[i];
for (int i = 2; i <= n; i++)
{
f[i][0] = (f[i - 1][0] + f[i - 1][1]) % mod;
f[i][1] = 0;
if (!a[i])
{
f[i][1] += f[i - 1][0];
if (!a[i - 1])
f[i][1] += qpow(2, cnt[i - 2]) + f[i - 2][0] + f[i - 2][1];
f[i][1] %= mod;
}
}
}
void init()
{
static char s[MAXN];
scanf("%d %d", &N, &M);
for (int i = 1; i <= N; i++)
{
scanf("%s", s + 1);
for (int j = 1; j <= M; j++)
{
v[i].push_back(s[j] == '*');
tot += !(s[j] == '*');
cntr[i] += !(s[j] == '*');
cntc[j] += !(s[j] == '*');
}
}
}
void solve()
{
bool tmp[MAXN];
long long ans = 0;
for (int i = 1; i <= N; i++)
{
for (int j = 0; j < M; j++)
tmp[j + 1] = v[i][j];
DP(tmp, M);
ans = (ans + (f[M][0] + f[M][1]) % mod * qpow(2, tot - cntr[i]) % mod) % mod;
}
for (int j = 1; j <= M; j++)
{
for (int i = 1; i <= N; i++)
tmp[i] = v[i][j - 1];
DP(tmp, N);
ans = (ans + (f[N][0] + f[N][1]) % mod * qpow(2, tot - cntc[j]) % mod) % mod;
}
printf("%lld\n", ans);
}
int main()
{
init();
solve();
return 0;
}
/*
5 5
ooooo
ooooo
ooooo
ooooo
ooooo
*/
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
In this problem you have to build tournament graph, consisting of n vertices, such, that for any oriented pair of vertices (v, u) (v β u) there exists a path from vertex v to vertex u consisting of no more then two edges.
A directed graph without self-loops is a tournament, if there is exactly one edge between any two distinct vertices (in one out of two possible directions).
Input
The first line contains an integer n (3 β€ n β€ 1000), the number of the graph's vertices.
Output
Print -1 if there is no graph, satisfying the described conditions.
Otherwise, print n lines with n integers in each. The numbers should be separated with spaces. That is adjacency matrix a of the found tournament. Consider the graph vertices to be numbered with integers from 1 to n. Then av, u = 0, if there is no edge from v to u, and av, u = 1 if there is one.
As the output graph has to be a tournament, following equalities must be satisfied:
* av, u + au, v = 1 for each v, u (1 β€ v, u β€ n; v β u);
* av, v = 0 for each v (1 β€ v β€ n).
Examples
Input
3
Output
0 1 0
0 0 1
1 0 0
Input
4
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
const int N = 1010;
int n, i, j, a[N][N];
void c(int n) {
for (i = 1; i <= n; i++)
for (j = 1; j <= n / 2; j++) a[i][(i + j - 1) % n + 1] = 1;
}
int main() {
scanf("%d", &n);
if (n == 4) {
printf("-1\n");
return 0;
}
if (n & 1)
c(n);
else {
c(n - 1);
for (i = 1; i <= n - 1; i++)
if (i & 1)
a[n][i] = 1;
else
a[i][n] = 1;
}
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
if (j > 1) printf(" ");
printf("%d", a[i][j]);
}
printf("\n");
}
scanf("\n");
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Note that girls in Arpaβs land are really attractive.
Arpa loves overnight parties. In the middle of one of these parties Mehrdad suddenly appeared. He saw n pairs of friends sitting around a table. i-th pair consisted of a boy, sitting on the ai-th chair, and his girlfriend, sitting on the bi-th chair. The chairs were numbered 1 through 2n in clockwise direction. There was exactly one person sitting on each chair.
<image>
There were two types of food: Kooft and Zahre-mar. Now Mehrdad wonders, was there any way to serve food for the guests such that:
* Each person had exactly one type of food,
* No boy had the same type of food as his girlfriend,
* Among any three guests sitting on consecutive chairs, there was two of them who had different type of food. Note that chairs 2n and 1 are considered consecutive.
Find the answer for the Mehrdad question. If it was possible, find some arrangement of food types that satisfies the conditions.
Input
The first line contains an integer n (1 β€ n β€ 105) β the number of pairs of guests.
The i-th of the next n lines contains a pair of integers ai and bi (1 β€ ai, bi β€ 2n) β the number of chair on which the boy in the i-th pair was sitting and the number of chair on which his girlfriend was sitting. It's guaranteed that there was exactly one person sitting on each chair.
Output
If there is no solution, print -1.
Otherwise print n lines, the i-th of them should contain two integers which represent the type of food for the i-th pair. The first integer in the line is the type of food the boy had, and the second integer is the type of food the girl had. If someone had Kooft, print 1, otherwise print 2.
If there are multiple solutions, print any of them.
Example
Input
3
1 4
2 5
3 6
Output
1 2
2 1
1 2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MaxN = 100050;
int head[MaxN * 2], cnt;
struct edge {
int next, to;
} e[MaxN * 6];
int n, a[MaxN], b[MaxN], col[MaxN * 2];
void link(int u, int v) {
++cnt;
e[cnt].next = head[u];
e[cnt].to = v;
head[u] = cnt;
++cnt;
e[cnt].next = head[v];
e[cnt].to = u;
head[v] = cnt;
}
void dfs(int x, int c) {
col[x] = c;
for (int i = head[x]; i; i = e[i].next)
if (col[e[i].to] == -1) dfs(e[i].to, c ^ 1);
}
int main() {
scanf("%d", &n);
memset(col, 0xff, sizeof(col));
for (int i = 1; i <= n; ++i) scanf("%d%d", &a[i], &b[i]);
for (int i = 1; i <= n; ++i) {
link(a[i], b[i]);
if (i != n)
link(2 * i, 2 * i + 1);
else
link(2 * i, 1);
}
for (int i = 1; i <= 2 * n; ++i)
if (col[i] == -1) dfs(i, 1);
for (int i = 1; i <= n; ++i) printf("%d %d\n", col[a[i]] + 1, col[b[i]] + 1);
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.
For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.
You are given an integer n no less than 12, express it as a sum of two composite numbers.
Input
The only line contains an integer n (12 β€ n β€ 106).
Output
Output two composite integers x and y (1 < x, y < n) such that x + y = n. If there are multiple solutions, you can output any of them.
Examples
Input
12
Output
4 8
Input
15
Output
6 9
Input
23
Output
8 15
Input
1000000
Output
500000 500000
Note
In the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.
In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long int n;
cin >> n;
vector<int> v(n + 1);
for (int i = 2; i <= n; i++) {
if (v[i] == 0)
for (int j = 2; j * i < n; j++) v[i * j] = 1;
}
vector<int> v1;
v1.push_back(1);
for (int i = 2; i <= n; i++)
if (v[i] != 0) v1.push_back(i);
for (int i = 1; i < v1.size(); i++)
if (binary_search(v1.begin(), v1.end(), (n - v1[i]))) {
cout << v1[i] << " " << n - v1[i];
break;
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Takahashi bought a piece of apple pie at ABC Confiserie. According to his memory, he paid N yen (the currency of Japan) for it.
The consumption tax rate for foods in this shop is 8 percent. That is, to buy an apple pie priced at X yen before tax, you have to pay X \times 1.08 yen (rounded down to the nearest integer).
Takahashi forgot the price of his apple pie before tax, X, and wants to know it again. Write a program that takes N as input and finds X. We assume X is an integer.
If there are multiple possible values for X, find any one of them. Also, Takahashi's memory of N, the amount he paid, may be incorrect. If no value could be X, report that fact.
Constraints
* 1 \leq N \leq 50000
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If there are values that could be X, the price of the apple pie before tax, print any one of them.
If there are multiple such values, printing any one of them will be accepted.
If no value could be X, print `:(`.
Examples
Input
432
Output
400
Input
1079
Output
:(
Input
1001
Output
927
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
long N;cin>>N;
for(long i=1;i<=50000;i++){
if(i*108/100==N){
cout<<i<<endl;
return 0;
}
}
cout<<":("<<endl;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
In the game of Mastermind, there are two players β Alice and Bob. Alice has a secret code, which Bob tries to guess. Here, a code is defined as a sequence of n colors. There are exactly n+1 colors in the entire universe, numbered from 1 to n+1 inclusive.
When Bob guesses a code, Alice tells him some information about how good of a guess it is, in the form of two integers x and y.
The first integer x is the number of indices where Bob's guess correctly matches Alice's code. The second integer y is the size of the intersection of the two codes as multisets. That is, if Bob were to change the order of the colors in his guess, y is the maximum number of indices he could get correct.
For example, suppose n=5, Alice's code is [3,1,6,1,2], and Bob's guess is [3,1,1,2,5]. At indices 1 and 2 colors are equal, while in the other indices they are not equal. So x=2. And the two codes have the four colors 1,1,2,3 in common, so y=4.
<image> Solid lines denote a matched color for the same index. Dashed lines denote a matched color at a different index. x is the number of solid lines, and y is the total number of lines.
You are given Bob's guess and two values x and y. Can you find one possibility of Alice's code so that the values of x and y are correct?
Input
The first line contains a single integer t (1β€ tβ€ 1000) β the number of test cases. Next 2t lines contain descriptions of test cases.
The first line of each test case contains three integers n,x,y (1β€ nβ€ 10^5, 0β€ xβ€ yβ€ n) β the length of the codes, and two values Alice responds with.
The second line of each test case contains n integers b_1,β¦,b_n (1β€ b_iβ€ n+1) β Bob's guess, where b_i is the i-th color of the guess.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, on the first line, output "YES" if there is a solution, or "NO" if there is no possible secret code consistent with the described situation. You can print each character in any case (upper or lower).
If the answer is "YES", on the next line output n integers a_1,β¦,a_n (1β€ a_iβ€ n+1) β Alice's secret code, where a_i is the i-th color of the code.
If there are multiple solutions, output any.
Example
Input
7
5 2 4
3 1 1 2 5
5 3 4
1 1 2 1 2
4 0 4
5 5 3 3
4 1 4
2 3 2 3
6 1 2
3 2 1 1 1 1
6 2 4
3 3 2 1 1 1
6 2 6
1 1 3 2 1 1
Output
YES
3 1 6 1 2
YES
3 1 1 1 2
YES
3 3 5 5
NO
YES
4 4 4 4 3 1
YES
3 1 3 1 7 7
YES
2 3 1 1 1 1
Note
The first test case is described in the statement.
In the second test case, x=3 because the colors are equal at indices 2,4,5. And y=4 because they share the colors 1,1,1,2.
In the third test case, x=0 because there is no index where the colors are the same. But y=4 because they share the colors 3,3,5,5.
In the fourth test case, it can be proved that no solution exists.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
for (int q = 1; q <= t; q++) {
int n, x, y;
cin >> n >> x >> y;
vector<int> b(n), cnt(n + 2, 0);
for (int i = 0; i < n; i++) {
cin >> b[i];
cnt[b[i]]++;
}
int c = (y - x) / 2, C = (y - x);
vector<pair<int, int>> p;
int non = 0;
for (int i = 1; i <= n + 1; i++) {
if (cnt[i]) {
p.push_back({cnt[i], i});
} else
non = i;
}
sort(p.begin(), p.end());
if ((y - x) & 1) {
int contr = 0;
for (int i = 0; i < p.size(); i++) {
contr += min(c, p[i].first);
}
if (contr < C) {
c++;
C = 2 * c;
}
}
vector<int> ch, a(n, 0);
map<int, vector<int>> mp;
bool ok = true;
for (int i = 0; i < p.size(); i++) {
for (int j = 1; j <= min(c, p[i].first) && ch.size() < C; j++) {
ch.push_back(p[i].second);
}
}
if (ch.size() != C || n - C < x)
ok = false;
else {
sort(ch.begin(), ch.end());
for (int i = 0; i < ch.size(); i++) {
mp[ch[i]].push_back(ch[(i + c) % (C)]);
}
int k = y - x;
for (int i = 0; i < n; i++) {
if (!mp[b[i]].empty()) {
if (k) {
a[i] = mp[b[i]].back();
mp[b[i]].pop_back();
k--;
} else {
a[i] = non;
mp[b[i]].pop_back();
}
} else {
if (x) {
a[i] = b[i];
x--;
} else
a[i] = non;
}
}
}
if (ok) {
cout << "YES"
<< "\n";
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << "\n";
} else {
cout << "NO"
<< "\n";
}
}
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
You have a rectangular chocolate bar consisting of n Γ m single squares. You want to eat exactly k squares, so you may need to break the chocolate bar.
In one move you can break any single rectangular piece of chocolate in two rectangular pieces. You can break only by lines between squares: horizontally or vertically. The cost of breaking is equal to square of the break length.
For example, if you have a chocolate bar consisting of 2 Γ 3 unit squares then you can break it horizontally and get two 1 Γ 3 pieces (the cost of such breaking is 32 = 9), or you can break it vertically in two ways and get two pieces: 2 Γ 1 and 2 Γ 2 (the cost of such breaking is 22 = 4).
For several given values n, m and k find the minimum total cost of breaking. You can eat exactly k squares of chocolate if after all operations of breaking there is a set of rectangular pieces of chocolate with the total size equal to k squares. The remaining nΒ·m - k squares are not necessarily form a single rectangular piece.
Input
The first line of the input contains a single integer t (1 β€ t β€ 40910) β the number of values n, m and k to process.
Each of the next t lines contains three integers n, m and k (1 β€ n, m β€ 30, 1 β€ k β€ min(nΒ·m, 50)) β the dimensions of the chocolate bar and the number of squares you want to eat respectively.
Output
For each n, m and k print the minimum total cost needed to break the chocolate bar, in order to make it possible to eat exactly k squares.
Examples
Input
4
2 2 1
2 2 3
2 2 2
2 2 4
Output
5
5
4
0
Note
In the first query of the sample one needs to perform two breaks:
* to split 2 Γ 2 bar into two pieces of 2 Γ 1 (cost is 22 = 4),
* to split the resulting 2 Γ 1 into two 1 Γ 1 pieces (cost is 12 = 1).
In the second query of the sample one wants to eat 3 unit squares. One can use exactly the same strategy as in the first query of the sample.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int dp[35][35][55];
int t, n, m, k;
int main() {
scanf("%d", &t);
dp[1][1][1] = 0;
dp[1][1][0] = 0;
for (int i = 1; i <= 31; i++) {
for (int j = 1; j <= 31; j++) {
if (i == 1 && j == 1) continue;
int op = min(i * j, 52);
for (int k = 1; k < op; k++) {
dp[i][j][k] = 100000000;
for (int s = 1; s <= (i / 2) + 1 && i - s >= 0; s++) {
for (int q = 0; q <= s * j && q <= k; q++) {
if ((k - q) > (i - s) * j) continue;
dp[i][j][k] =
min(dp[i][j][k], dp[i - s][j][k - q] + dp[s][j][q] + j * j);
}
}
for (int s = 1; s <= (j / 2) + 1 && j - s >= 0; s++) {
for (int q = 0; q <= i * s && q <= k; q++) {
if (k - q > i * (j - s)) continue;
dp[i][j][k] =
min(dp[i][j][k], dp[i][j - s][k - q] + dp[i][s][q] + i * i);
}
}
}
}
}
while (t--) {
scanf("%d", &n), scanf("%d", &m), scanf("%d", &k);
printf("%d\n", dp[n][m][k]);
}
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Polycarp lives on the coordinate axis Ox and travels from the point x=a to x=b. It moves uniformly rectilinearly at a speed of one unit of distance per minute.
On the axis Ox at the point x=c the base station of the mobile operator is placed. It is known that the radius of its coverage is r. Thus, if Polycarp is at a distance less than or equal to r from the point x=c, then he is in the network coverage area, otherwise β no. The base station can be located both on the route of Polycarp and outside it.
Print the time in minutes during which Polycarp will not be in the coverage area of the network, with a rectilinear uniform movement from x=a to x=b. His speed β one unit of distance per minute.
Input
The first line contains a positive integer t (1 β€ t β€ 1000) β the number of test cases. In the following lines are written t test cases.
The description of each test case is one line, which contains four integers a, b, c and r (-10^8 β€ a,b,c β€ 10^8, 0 β€ r β€ 10^8) β the coordinates of the starting and ending points of the path, the base station, and its coverage radius, respectively.
Any of the numbers a, b and c can be equal (either any pair or all three numbers). The base station can be located both on the route of Polycarp and outside it.
Output
Print t numbers β answers to given test cases in the order they are written in the test. Each answer is an integer β the number of minutes during which Polycarp will be unavailable during his movement.
Example
Input
9
1 10 7 1
3 3 3 0
8 2 10 4
8 2 10 100
-10 20 -17 2
-3 2 2 0
-3 1 2 0
2 3 2 3
-1 3 -2 2
Output
7
0
4
0
30
5
4
0
3
Note
The following picture illustrates the first test case.
<image> Polycarp goes from 1 to 10. The yellow area shows the coverage area of the station with a radius of coverage of 1, which is located at the point of 7. The green area shows a part of the path when Polycarp is out of coverage area.
### Response
```cpp
#include <bits/stdc++.h>
const int N = 500005;
const int mod = 1e9 + 7;
using namespace std;
void solve() {
int n, m, k, x = 0, y = 0, c = 0, q, ans = 0, a, b, r;
cin >> a >> b >> c >> r;
if (a > b) swap(a, b);
if (a <= c and c <= b) {
x = c - r;
ans = max(0, x - a);
x = r + c;
ans += max(0, b - x);
cout << ans << "\n";
return;
}
if (c <= a and c <= b) {
c = c + r;
c = max(c, a);
cout << max(0, b - c) << "\n";
} else {
c = c - r;
c = min(c, b);
cout << max(0, c - a) << "\n";
}
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int T = 1;
cin >> T;
while (T--) {
solve();
}
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Once upon a time there was only one router in the well-known company Bmail. Years went by and over time new routers were purchased. Every time they bought a new router, they connected it to one of the routers bought before it. You are given the values p_i β the index of the router to which the i-th router was connected after being purchased (p_i < i).
There are n routers in Boogle in total now. Print the sequence of routers on the path from the first to the n-th router.
Input
The first line contains integer number n (2 β€ n β€ 200000) β the number of the routers. The following line contains n-1 integers p_2, p_3, ..., p_n (1 β€ p_i < i), where p_i is equal to index of the router to which the i-th was connected after purchase.
Output
Print the path from the 1-st to the n-th router. It starts with 1 and ends with n. All the elements in the path should be distinct.
Examples
Input
8
1 1 2 2 3 2 5
Output
1 2 5 8
Input
6
1 2 3 4 5
Output
1 2 3 4 5 6
Input
7
1 1 2 3 4 3
Output
1 3 7
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int a[n + 1];
int i, j, l;
for (i = 2; i <= n; i++) cin >> a[i];
stack<int> s;
a[1] = 0;
j = n;
while (j > 0) {
s.push(j);
j = a[j];
}
while (!s.empty()) {
j = s.top();
s.pop();
cout << j << " ";
}
cout << endl;
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Autumn came late to the kingdom of Far Far Away. The harvest was exuberant and it is now time to get ready for the winter. As most people celebrate the Harvest festival, Simon the Caretaker tries to solve a very non-trivial task of how to find place for the agricultural equipment in the warehouse.
He's got problems with some particularly large piece of equipment, which is, of course, turboplows. The problem is that when a turboplow is stored, it takes up not some simply rectangular space. It takes up a T-shaped space like on one of the four pictures below (here character "#" stands for the space occupied by the turboplow and character "." stands for the free space):
### ..# .#. #..
.#. ### .#. ###
.#. ..# ### #..
Simon faced a quite natural challenge: placing in the given n Γ m cells warehouse the maximum number of turboplows. As one stores the turboplows, he can rotate them in any manner (so that they take up the space like on one of the four pictures above). However, two turboplows cannot "overlap", that is, they cannot share the same cell in the warehouse.
Simon feels that he alone cannot find the optimal way of positioning the plugs in the warehouse that would maximize their quantity. Can you help him?
Input
The only line contains two space-separated integers n and m β the sizes of the warehouse (1 β€ n, m β€ 9).
Output
In the first line print the maximum number of turboplows that can be positioned in the warehouse. In each of the next n lines print m characters. Use "." (dot) to mark empty space and use successive capital Latin letters ("A" for the first turboplow, "B" for the second one and so on until you reach the number of turboplows in your scheme) to mark place for the corresponding turboplows considering that they are positioned in the optimal manner in the warehouse. The order in which you number places for the turboplows does not matter. If there are several optimal solutions for a warehouse of the given size, print any of them.
Examples
Input
3 3
Output
1
AAA
.A.
.A.
Input
5 6
Output
4
A..C..
AAAC..
ABCCCD
.B.DDD
BBB..D
Input
2 2
Output
0
..
..
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int MSK;
int dp[1 << 19][9][9];
int adj[4][2];
int n, m;
int f(int bt, int r, int c) {
if (r >= n - 2) return 0;
int &res = dp[bt][r][c];
if (res != -1) return res;
if (m - c < 3) {
res = f((bt << (m - c)) & MSK, r + 1, 0);
} else {
res = f((bt << 1) & MSK, r, c + 1);
int bt2 = (bt >> 1);
int b = (bt & 1) << 2;
for (int i = 0; i < 4; i++) {
if (bt2 & adj[i][0]) continue;
if (b & adj[i][1]) continue;
int k = (((bt2 | adj[i][0]) << 3) | (adj[i][1] | b)) & MSK;
k = f(k, r, c + 2) + 1;
if (k > res) {
res = k;
}
}
}
return res;
}
string s[11];
char alp = 'A';
string T[4][3] = {{"###", ".#.", ".#."},
{"..#", "###", "..#"},
{".#.", ".#.", "###"},
{"#..", "###", "#.."}};
void print(int bt, int r, int c) {
if (r >= n - 2) return;
if (m - c < 3) {
print((bt << (m - c)) & MSK, r + 1, 0);
} else {
int bt2 = (bt >> 1);
int b = (bt & 1) << 2;
int x = 0;
for (x = 0; x < 4; x++) {
if (bt2 & adj[x][0]) continue;
if (b & adj[x][1]) continue;
int k = (((bt2 | adj[x][0]) << 3) | (adj[x][1] | b)) & MSK;
if (dp[bt][r][c] == f(k, r, c + 2) + 1) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
if (T[x][i][j] == '#') s[r + i][c + j] = alp;
}
alp++;
print(k, r, c + 2);
break;
}
}
if (x == 4) print((bt << 1) & MSK, r, c + 1);
}
}
int main() {
cin >> n >> m;
MSK = (1 << (2 * m + 1)) - 1;
int a[4][3] = {{7, 2, 2}, {1, 7, 1}, {2, 2, 7}, {4, 7, 4}};
for (int i = 0; i < 4; i++) {
adj[i][0] = (a[i][0] << (2 * m - 3)) | (a[i][1] << (m - 3));
adj[i][1] = a[i][2];
}
for (int i = 0; i < m; i++) s[0] += '.';
for (int i = 1; i < n; i++) s[i] = s[0];
memset(dp, -1, sizeof dp);
int ans = f(0, 0, 0);
cout << ans << endl;
print(0, 0, 0);
for (int i = 0; i < n; i++) cout << s[i] << endl;
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
problem
Given $ N $ different natural numbers $ a_i $. I decided to make a pair by choosing a different natural number from the given natural numbers. Output one pair that can be created with a value difference that is a multiple of $ N -1 $.
It should be noted that such a pair always exists.
Example
Input
5
1 2 4 7 10
Output
2 10
### Response
```cpp
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <set>
#include <map>
#include <cmath>
using namespace std;
typedef long long i64;
typedef long double ld;
typedef pair<i64,i64> P;
#define rep(i,s,e) for(int (i) = (s);(i) <= (e);(i)++)
int n;
vector<int> a(1010);
int main(){
cin >> n;
for(int i = 0;i < n;i++){
cin >> a[i];
}
rep(i,0,n - 1) rep(j,0,n - 1){
if(i == j) continue;
if(abs(a[i] - a[j]) % (n - 1) == 0){
cout << a[i] << " " << a[j] << endl;
return 0;
}
}
}
``` |
### Prompt
Generate a cpp solution to the following problem:
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.
Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
Input
The first line contains the only integer n (3 β€ n β€ 105) β the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| β€ 109) β coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order.
The next line contains a single integer m (3 β€ m β€ 2Β·104) β the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| β€ 109) β the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order.
The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
Output
Print on the only line the answer to the problem β if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
Examples
Input
6
-2 1
0 3
3 3
4 1
3 -2
2 -2
4
0 1
2 2
3 1
1 0
Output
YES
Input
5
1 2
4 2
3 -3
-2 -2
-2 1
4
0 1
1 2
4 1
2 -1
Output
NO
Input
5
-1 2
2 3
4 1
3 -2
0 -3
5
1 0
1 1
3 1
5 -1
2 -1
Output
NO
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int sz = 2e5 + 5;
pair<long long, long long> pv[sz];
long long cross(pair<long long, long long> a, pair<long long, long long> b,
pair<long long, long long> c) {
return (b.second - a.second) * (c.first - a.first) -
(b.first - a.first) * (c.second - a.second);
}
int orient(pair<long long, long long> a, pair<long long, long long> b,
pair<long long, long long> c) {
long long val = cross(a, b, c);
if (!val) return 0;
return val > 0 ? 1 : 2;
}
bool up(pair<long long, long long> p) {
return p.second > 0 || (!p.second && p.first >= 0);
}
bool pip(pair<long long, long long> p, int n) {
if (n < 3) return 0;
int l = 1, r = n - 2;
while (l < r) {
int md = (l + r + 1) >> 1;
if (orient(pv[0], pv[md], p) == 1)
r = md - 1;
else
l = md;
}
if (!cross(pv[0], pv[1], p)) return 0;
if (!cross(pv[0], pv[n - 1], p)) return 0;
if (!cross(pv[l], pv[l + 1], p)) return 0;
if (orient(pv[0], pv[l], p) == 1) return 0;
if (orient(pv[l], pv[l + 1], p) == 1) return 0;
if (orient(pv[l + 1], pv[0], p) == 1) return 0;
return 1;
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) scanf("%lld %lld", &pv[i].first, &pv[i].second);
reverse(pv, pv + n);
int q;
cin >> q;
bool ans = 1;
while (q--) {
pair<long long, long long> p;
scanf("%lld %lld", &p.first, &p.second);
bool in = pip(p, n);
ans &= in;
}
if (ans)
puts("YES");
else
puts("NO");
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals.
Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow crystals, green β one yellow and one blue, and for a blue ball, three blue crystals are enough.
Right now there are A yellow and B blue crystals in Grisha's disposal. Find out how many additional crystals he should acquire in order to produce the required number of balls.
Input
The first line features two integers A and B (0 β€ A, B β€ 109), denoting the number of yellow and blue crystals respectively at Grisha's disposal.
The next line contains three integers x, y and z (0 β€ x, y, z β€ 109) β the respective amounts of yellow, green and blue balls to be obtained.
Output
Print a single integer β the minimum number of crystals that Grisha should acquire in addition.
Examples
Input
4 3
2 1 1
Output
2
Input
3 9
1 1 3
Output
1
Input
12345678 87654321
43043751 1000000000 53798715
Output
2147483648
Note
In the first sample case, Grisha needs five yellow and four blue crystals to create two yellow balls, one green ball, and one blue ball. To do that, Grisha needs to obtain two additional crystals: one yellow and one blue.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int toNumber(string s) {
int Number;
if (!(istringstream(s) >> Number)) Number = 0;
return Number;
}
string toString(int number) {
ostringstream ostr;
ostr << number;
return ostr.str();
}
long long ele(long long a, long long b) {
if (b == 0) return 1;
if (b % 2 == 0) {
return ele((a * a), b / 2);
} else {
return a * ele((a * a), b / 2);
}
}
long long mcd(long long a, long long b) {
if (a == 0) return b;
return mcd(b % a, a);
}
double d_abs(long a, long b) {
if (a > b) {
return a - b;
}
return b - a;
}
int ent(char c) { return c - '0'; }
void solve() {
long long a, b, x, y, z;
cin >> a >> b >> x >> y >> z;
long long needye = 2 * x + y;
long long needblue = 3 * z + y;
long long cero = 0;
cout << max(cero, needye - a) + max(cero, needblue - b) << endl;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int T;
T = 1;
while (T--) {
solve();
}
}
``` |
### Prompt
Generate 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;
const int MAXN = 100001;
int sm[MAXN], sc[MAXN];
int main(int argc, char const* argv[]) {
int n, m;
scanf("%d%d", &n, &m);
map<int, map<int, int> > markers, caps;
int a, b;
for (int i = 0; i < n; ++i) {
scanf("%d%d", &a, &b);
++sm[b];
++markers[b][a];
}
for (int i = 0; i < m; ++i) {
scanf("%d%d", &a, &b);
++sc[b];
++caps[b][a];
}
int rc = 0, rb = 0;
for (map<int, map<int, int> >::iterator it = markers.begin();
it != markers.end(); ++it) {
int size = it->first;
if (sc[size] == 0) continue;
rc += min(sm[size], sc[size]);
map<int, int>&mm = it->second, mc = caps[size];
for (map<int, int>::iterator itt = mm.begin(); itt != mm.end(); ++itt) {
rb += min(itt->second, mc[itt->first]);
}
}
printf("%d %d\n", rc, rb);
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
You are playing the following game. There are n points on a plane. They are the vertices of a regular n-polygon. Points are labeled with integer numbers from 1 to n. Each pair of distinct points is connected by a diagonal, which is colored in one of 26 colors. Points are denoted by lowercase English letters. There are three stones positioned on three distinct vertices. All stones are the same. With one move you can move the stone to another free vertex along some diagonal. The color of this diagonal must be the same as the color of the diagonal, connecting another two stones.
Your goal is to move stones in such way that the only vertices occupied by stones are 1, 2 and 3. You must achieve such position using minimal number of moves. Write a program which plays this game in an optimal way.
Input
In the first line there is one integer n (3 β€ n β€ 70) β the number of points. In the second line there are three space-separated integer from 1 to n β numbers of vertices, where stones are initially located.
Each of the following n lines contains n symbols β the matrix denoting the colors of the diagonals. Colors are denoted by lowercase English letters. The symbol j of line i denotes the color of diagonal between points i and j. Matrix is symmetric, so j-th symbol of i-th line is equal to i-th symbol of j-th line. Main diagonal is filled with '*' symbols because there is no diagonal, connecting point to itself.
Output
If there is no way to put stones on vertices 1, 2 and 3, print -1 on a single line. Otherwise, on the first line print minimal required number of moves and in the next lines print the description of each move, one move per line. To describe a move print two integers. The point from which to remove the stone, and the point to which move the stone. If there are several optimal solutions, print any of them.
Examples
Input
4
2 3 4
*aba
a*ab
ba*b
abb*
Output
1
4 1
Input
4
2 3 4
*abc
a*ab
ba*b
cbb*
Output
-1
Note
In the first example we can move stone from point 4 to point 1 because this points are connected by the diagonal of color 'a' and the diagonal connection point 2 and 3, where the other stones are located, are connected by the diagonal of the same color. After that stones will be on the points 1, 2 and 3.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using fst = tuple<int, int, int>;
const int N = 75;
int n, h[N][N][N], a[3], tmp[3];
fst par[N][N][N];
string s[N];
bool vis[N][N][N];
vector<pair<int, int>> ans;
queue<fst> q;
int main() {
ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
cin >> n;
for (int i = 0; i < 3; i++) cin >> a[i], --a[i];
sort(a, a + 3);
for (int i = 0; i < n; i++) cin >> s[i];
vis[a[0]][a[1]][a[2]] = true, par[a[0]][a[1]][a[2]] = {-1, -1, -1};
q.push({a[0], a[1], a[2]});
while (!q.empty()) {
tie(tmp[0], tmp[1], tmp[2]) = q.front();
q.pop();
for (int i = 0; i < n; i++) {
bool flag = false;
for (int j = 0; j < 3; j++)
if (tmp[j] == i) flag = true;
if (flag) continue;
for (int j = 0; j < 3; j++)
for (int k = j + 1; k < 3; k++) {
a[0] = tmp[j], a[1] = tmp[k];
a[2] = tmp[1 ^ 2 ^ j ^ k];
if (s[a[0]][a[1]] ^ s[a[2]][i]) continue;
a[2] = i;
sort(a, a + 3);
if (!vis[a[0]][a[1]][a[2]]) {
h[a[0]][a[1]][a[2]] = h[tmp[0]][tmp[1]][tmp[2]] + 1;
vis[a[0]][a[1]][a[2]] = true,
par[a[0]][a[1]][a[2]] = {tmp[0], tmp[1], tmp[2]};
q.push({a[0], a[1], a[2]});
}
}
}
}
if (!vis[0][1][2]) return cout << "-1\n", 0;
cout << h[0][1][2] << '\n';
fst sv = {0, 1, 2}, sv2;
set<int> exist;
int res;
while (get<0>(sv) ^ -1 || !get<0>(sv)) {
sv2 = par[get<0>(sv)][get<1>(sv)][get<2>(sv)];
tie(a[0], a[1], a[2]) = sv;
if (get<0>(sv2) == -1) {
sv = sv2;
continue;
}
exist.insert(get<0>(sv2)), exist.insert(get<1>(sv2)),
exist.insert(get<2>(sv2));
for (int i = 0; i < 3; i++)
exist.count(a[i]) ? exist.erase(a[i]) : res = a[i];
ans.push_back({*exist.begin() + 1, res + 1});
exist.clear(), sv = sv2;
}
reverse(ans.begin(), ans.end());
for (auto [x, y] : ans) cout << x << ' ' << y << '\n';
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
There is a staircase with N steps. Takahashi is now standing at the foot of the stairs, that is, on the 0-th step. He can climb up one or two steps at a time.
However, the treads of the a_1-th, a_2-th, a_3-th, \ldots, a_M-th steps are broken, so it is dangerous to set foot on those steps.
How many are there to climb up to the top step, that is, the N-th step, without setting foot on the broken steps? Find the count modulo 1\ 000\ 000\ 007.
Constraints
* 1 \leq N \leq 10^5
* 0 \leq M \leq N-1
* 1 \leq a_1 < a_2 < ... < a_M \leq N-1
Input
Input is given from Standard Input in the following format:
N M
a_1
a_2
.
.
.
a_M
Output
Print the number of ways to climb up the stairs under the condition, modulo 1\ 000\ 000\ 007.
Examples
Input
6 1
3
Output
4
Input
10 2
4
5
Output
0
Input
100 5
1
23
45
67
89
Output
608200469
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int mod=1000000007;
int main(){
int n,m;
cin >> n >> m;
vector<int> a(m);
vector<int> d(n+1,-1);
d[0]=1;
d[1]=1;
for(int i=0;i<m;i++){
cin >> a[i];
d[a[i]]=0;
}
for(int i=2;i<=n;i++){
if(d[i]!=0){
d[i]=(d[i-1]+d[i-2])%mod;
}
}
cout << d[n] << endl;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Dima loves making pictures on a piece of squared paper. And yet more than that Dima loves the pictures that depict one of his favorite figures.
A piece of squared paper of size n Γ m is represented by a table, consisting of n rows and m columns. All squares are white on blank squared paper. Dima defines a picture as an image on a blank piece of paper, obtained by painting some squares black.
The picture portrays one of Dima's favorite figures, if the following conditions hold:
* The picture contains at least one painted cell;
* All painted cells form a connected set, that is, you can get from any painted cell to any other one (you can move from one cell to a side-adjacent one);
* The minimum number of moves needed to go from the painted cell at coordinates (x1, y1) to the painted cell at coordinates (x2, y2), moving only through the colored cells, equals |x1 - x2| + |y1 - y2|.
Now Dima is wondering: how many paintings are on an n Γ m piece of paper, that depict one of his favorite figures? Count this number modulo 1000000007 (109 + 7).
Input
The first line contains two integers n and m β the sizes of the piece of paper (1 β€ n, m β€ 150).
Output
In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7).
Examples
Input
2 2
Output
13
Input
3 4
Output
571
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 160, P = 1e9 + 7;
int n, m, dp[N][N][N][4];
void add(int &a, int b) {
a += b;
if (a >= P) a -= P;
if (a < 0) a += P;
}
void add(int i, int x1, int y1, int x2, int y2, int op, int r) {
++x2, ++y2;
add(dp[i][x1][y1][op], r);
add(dp[i][x1][y2][op], -r);
add(dp[i][x2][y1][op], -r);
add(dp[i][x2][y2][op], r);
}
int main() {
scanf("%d%d", &n, &m);
add(1, 1, 1, m, m, 0, 1);
int ans = 0;
for (int i = 1; i <= n + 1; ++i)
for (int l = 1; l <= m; ++l)
for (int r = 1; r <= m; ++r)
for (int z = 0; z <= 3; ++z) {
int &ret = dp[i - 1][l][r][z];
add(ret, dp[i - 1][l - 1][r][z]);
add(ret, dp[i - 1][l][r - 1][z]);
add(ret, -dp[i - 1][l - 1][r - 1][z]);
if (!ret || l > r) continue;
ans = (ans + (long long)(n + 2 - i) * ret) % P;
if (i == n + 1) continue;
if (z == 0) {
add(i, 1, r, l, m, 0, ret);
if (l + 1 <= r) add(i, l + 1, r, r, m, 1, ret);
if (l <= r - 1) add(i, 1, l, l, r - 1, 2, ret);
if (l + 1 <= r - 1) add(i, l + 1, l + 1, r, r - 1, 3, ret);
} else if (z == 1) {
add(i, l, r, r, m, 1, ret);
if (l <= r - 1) add(i, l, l, r, r - 1, 3, ret);
} else if (z == 2) {
add(i, 1, l, l, r, 2, ret);
if (l + 1 <= r) add(i, l + 1, l + 1, r, r, 3, ret);
} else if (z == 3) {
add(i, l, l, r, r, 3, ret);
}
}
printf("%d\n", ans);
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences.
Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in which the respective symbols of s and t are the same. Function h(s, t) can be used to define the function of Vasya distance Ο(s, t):
<image> where <image> is obtained from string s, by applying left circular shift i times. For example, Ο("AGC", "CGT") = h("AGC", "CGT") + h("AGC", "GTC") + h("AGC", "TCG") + h("GCA", "CGT") + h("GCA", "GTC") + h("GCA", "TCG") + h("CAG", "CGT") + h("CAG", "GTC") + h("CAG", "TCG") = 1 + 1 + 0 + 0 + 1 + 1 + 1 + 0 + 1 = 6
Vasya found a string s of length n on the Internet. Now he wants to count how many strings t there are such that the Vasya distance from the string s attains maximum possible value. Formally speaking, t must satisfy the equation: <image>.
Vasya could not try all possible strings to find an answer, so he needs your help. As the answer may be very large, count the number of such strings modulo 109 + 7.
Input
The first line of the input contains a single integer n (1 β€ n β€ 105).
The second line of the input contains a single string of length n, consisting of characters "ACGT".
Output
Print a single number β the answer modulo 109 + 7.
Examples
Input
1
C
Output
1
Input
2
AG
Output
4
Input
3
TTT
Output
1
Note
Please note that if for two distinct strings t1 and t2 values Ο(s, t1) ΠΈ Ο(s, t2) are maximum among all possible t, then both strings must be taken into account in the answer even if one of them can be obtained by a circular shift of another one.
In the first sample, there is Ο("C", "C") = 1, for the remaining strings t of length 1 the value of Ο(s, t) is 0.
In the second sample, Ο("AG", "AG") = Ο("AG", "GA") = Ο("AG", "AA") = Ο("AG", "GG") = 4.
In the third sample, Ο("TTT", "TTT") = 27
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n;
string str;
cin >> n >> str;
int freq[0x100];
memset(freq, 0, sizeof(freq));
for (int i = 0; i < n; i++) freq[(int)str[i]]++;
int maxFreq = max(max(freq['A'], freq['C']), max(freq['G'], freq['T']));
int k = (freq['A'] == maxFreq) + (freq['C'] == maxFreq) +
(freq['G'] == maxFreq) + (freq['T'] == maxFreq);
long long ans = 1;
for (int i = 0; i < n; i++) ans = (ans * k) % 1000000007;
cout << ans << endl;
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls from his box in his move. Players alternate turns and the first player starts the game. The one who can't make a move loses. Your task is to determine who wins if both players play optimally.
Input
The first line contains four integers n1, n2, k1, k2. All numbers in the input are from 1 to 50.
This problem doesn't have subproblems. You will get 3 points for the correct submission.
Output
Output "First" if the first player wins and "Second" otherwise.
Examples
Input
2 2 1 2
Output
Second
Input
2 1 1 1
Output
First
Note
Consider the first sample test. Each player has a box with 2 balls. The first player draws a single ball from his box in one move and the second player can either take 1 or 2 balls from his box in one move. No matter how the first player acts, the second player can always win if he plays wisely.
### Response
```cpp
#include <bits/stdc++.h>
double EPS = 1e-9;
long long INFF = 1000000000000000005LL;
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
;
int n1, n2, k1, k2;
cin >> n1 >> n2 >> k1 >> k2;
if (n2 >= n1) {
cout << "Second" << '\n';
} else {
cout << "First" << '\n';
}
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
The Little Elephant enjoys recursive functions.
This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows:
* If x = 1, exit the function.
* Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a).
The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order.
Input
A single line contains integer n (1 β€ n β€ 1000) β the size of permutation.
Output
In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces.
It is guaranteed that the answer exists.
Examples
Input
1
Output
1
Input
2
Output
2 1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
cout << n;
for (int i = 1; i < n; i++) cout << " " << i;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes.
Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the i-th safe from the left is called safe i. There are n banknotes left in all the safes in total. The i-th banknote is in safe xi. Oleg is now at safe a. There are two security guards, one of which guards the safe b such that b < a, i.e. the first guard is to the left of Oleg. The other guard guards the safe c so that c > a, i.e. he is to the right of Oleg.
The two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather.
Input
The first line of input contains three space-separated integers, a, b and c (1 β€ b < a < c β€ 109), denoting the positions of Oleg, the first security guard and the second security guard, respectively.
The next line of input contains a single integer n (1 β€ n β€ 105), denoting the number of banknotes.
The next line of input contains n space-separated integers x1, x2, ..., xn (1 β€ xi β€ 109), denoting that the i-th banknote is located in the xi-th safe. Note that xi are not guaranteed to be distinct.
Output
Output a single integer: the maximum number of banknotes Oleg can take.
Examples
Input
5 3 7
8
4 7 5 5 3 6 2 8
Output
4
Input
6 5 7
5
1 5 7 92 3
Output
0
Note
In the first example Oleg can take the banknotes in positions 4, 5, 6 (note that there are 2 banknotes at position 5). Oleg can't take the banknotes in safes 7 and 8 because he can't run into the second security guard. Similarly, Oleg cannot take the banknotes at positions 3 and 2 because he can't run into the first security guard. Thus, he can take a maximum of 4 banknotes.
For the second sample, Oleg can't take any banknotes without bumping into any of the security guards.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int b, a, c, n, x, ans;
int main() {
scanf("%d%d%d%d", &a, &b, &c, &n);
while (n--) {
scanf("%d", &x);
if (x > b && x < c) ans++;
}
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 β€ n β€ 10^5, 1 β€ s β€ 10^9) β the number of vertices in the tree and the sum of edge weights.
Each of the following nβ1 lines contains two space-separated integer numbers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} β€ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, s;
vector<int> a[100000 + 5];
int X[100000 + 5], Y[100000 + 5];
int main() {
scanf("%d", &n), scanf("%d", &s);
for (int i = 1; i < n; i++) {
scanf("%d", &X[i]), scanf("%d", &Y[i]);
a[X[i]].push_back(Y[i]);
a[Y[i]].push_back(X[i]);
}
int cnt = 0;
for (int i = 1; i <= n; i++) {
if (a[i].size() == 1) cnt++;
}
double ans = (double)s * 2 / cnt;
printf("%.18lf\n", ans);
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
You are given an array a consisting of n integers. In one move, you can jump from the position i to the position i - a_i (if 1 β€ i - a_i) or to the position i + a_i (if i + a_i β€ n).
For each position i from 1 to n you want to know the minimum the number of moves required to reach any position j such that a_j has the opposite parity from a_i (i.e. if a_i is odd then a_j has to be even and vice versa).
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
Output
Print n integers d_1, d_2, ..., d_n, where d_i is the minimum the number of moves required to reach any position j such that a_j has the opposite parity from a_i (i.e. if a_i is odd then a_j has to be even and vice versa) or -1 if it is impossible to reach such a position.
Example
Input
10
4 5 7 6 7 5 4 4 6 4
Output
1 1 1 2 -1 1 1 3 1 1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, a[200005], dp[200005], vis[200005];
std::vector<int> v[200005];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
dp[i] = n;
vis[i] = 0;
if (i - a[i] >= 0) v[i - a[i]].push_back(i);
if (i + a[i] < n) v[i + a[i]].push_back(i);
}
vector<int> v1, v2;
v1.clear();
v2.clear();
for (int i = 0; i < n; i++) {
if (i - a[i] >= 0 && a[i] % 2 != a[i - a[i]] % 2) {
dp[i] = 1;
v1.push_back(i);
} else if (i + a[i] < n && a[i] % 2 != a[i + a[i]] % 2) {
dp[i] = 1;
v1.push_back(i);
}
}
int cnt = 2;
while (!v1.empty()) {
for (int j : v1) {
for (int k : v[j]) {
if (dp[k] > cnt) {
dp[k] = cnt;
v2.push_back(k);
}
}
}
v1 = v2;
v2.clear();
cnt++;
}
for (int i = 0; i < n; i++) {
if (dp[i] >= n)
cout << "-1 ";
else
cout << dp[i] << " ";
}
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first line contains two integers n and k (1 β€ n β€ 200 000, 0 β€ k β€ n) β the number of digits in the decimal representation of S and the maximum allowed number of changed digits.
The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes.
Output
Output the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits.
Examples
Input
5 3
51528
Output
10028
Input
3 2
102
Output
100
Input
1 1
1
Output
0
Note
A number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void ayushmehta651() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
long long magic() {
long long n, k;
cin >> n >> k;
string s;
cin >> s;
if (n == 1) {
if (k)
cout << 0 << '\n';
else
cout << s << '\n';
return 0;
}
if (s[0] != '1' and k) {
s[0] = '1';
k -= 1;
}
for (long long i = 1; i < s.length() and k; ++i) {
if (s[i] != '0') {
s[i] = '0';
k -= 1;
}
}
cout << s << '\n';
return 0;
}
int32_t main() {
ayushmehta651();
magic();
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A Γ floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 β€ A β€ 10^{6}
* 1 β€ B β€ 10^{12}
* 1 β€ N β€ 10^{12}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B N
Output
Print the maximum possible value of floor(Ax/B) - A Γ floor(x/B) for a non-negative integer x not greater than N, as an integer.
Examples
Input
5 7 4
Output
2
Input
11 10 9
Output
9
### Response
```cpp
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
long a, b, n;
cin >> a >> b >> n;
cout << a*min(n, b-1)/b;
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
There are N balls in a two-dimensional plane. The i-th ball is at coordinates (x_i, y_i).
We will collect all of these balls, by choosing two integers p and q such that p \neq 0 or q \neq 0 and then repeating the following operation:
* Choose a ball remaining in the plane and collect it. Let (a, b) be the coordinates of this ball. If we collected a ball at coordinates (a - p, b - q) in the previous operation, the cost of this operation is 0. Otherwise, including when this is the first time to do this operation, the cost of this operation is 1.
Find the minimum total cost required to collect all the balls when we optimally choose p and q.
Constraints
* 1 \leq N \leq 50
* |x_i|, |y_i| \leq 10^9
* If i \neq j, x_i \neq x_j or y_i \neq y_j.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
:
x_N y_N
Output
Print the minimum total cost required to collect all the balls.
Examples
Input
2
1 1
2 2
Output
1
Input
3
1 4
4 6
7 8
Output
1
Input
4
1 1
1 2
2 1
2 2
Output
2
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
const int INF = 1<<30;
int main(){
int n;cin>>n;
map<pair<int, int>, int> mp;
vector<pair<int, int>> vec(n);
for(int i=0;i<n;i++){
int x, y;cin>>x>>y;
vec[i]=make_pair(x, y);
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i==j)continue;
mp[make_pair(vec[j].first-vec[i].first, vec[j].second-vec[i].second)]++;
}
}
int m=0;
for(auto itr=mp.begin();itr!=mp.end();itr++){
m=max(m, itr->second);
}
cout<<n-m<<endl;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
On Bertown's main street n trees are growing, the tree number i has the height of ai meters (1 β€ i β€ n). By the arrival of the President of Berland these trees were decided to be changed so that their heights formed a beautiful sequence. This means that the heights of trees on ends (the 1st one and the n-th one) should be equal to each other, the heights of the 2-nd and the (n - 1)-th tree must also be equal to each other, at that the height of the 2-nd tree should be larger than the height of the first tree by 1, and so on. In other words, the heights of the trees, standing at equal distance from the edge (of one end of the sequence) must be equal to each other, and with the increasing of the distance from the edge by 1 the tree height must also increase by 1. For example, the sequences "2 3 4 5 5 4 3 2" and "1 2 3 2 1" are beautiful, and '1 3 3 1" and "1 2 3 1" are not.
Changing the height of a tree is a very expensive operation, using advanced technologies invented by Berland scientists. In one operation you can choose any tree and change its height to any number, either increase or decrease. Note that even after the change the height should remain a positive integer, i. e, it can't be less than or equal to zero. Identify the smallest number of changes of the trees' height needed for the sequence of their heights to become beautiful.
Input
The first line contains integer n (1 β€ n β€ 105) which is the number of trees. The second line contains integers ai (1 β€ ai β€ 105) which are the heights of the trees.
Output
Print a single number which is the minimal number of trees whose heights will have to be changed for the sequence to become beautiful.
Examples
Input
3
2 2 2
Output
1
Input
4
1 2 2 1
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[100005], n, x, y, ans;
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> x;
if (i <= n / 2)
y = i;
else
y = n - i + 1;
if (x - y >= 0) {
a[x - y]++;
if (a[x - y] > ans) ans = a[x - y];
}
}
cout << n - ans << endl;
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
This is the easy version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved.
You are given an array [a_1, a_2, ..., a_n].
Your goal is to find the length of the longest subarray of this array such that the most frequent value in it is not unique. In other words, you are looking for a subarray such that if the most frequent value occurs f times in this subarray, then at least 2 different values should occur exactly f times.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
The first line contains a single integer n (1 β€ n β€ 200 000) β the length of the array.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ min(n, 100)) β elements of the array.
Output
You should output exactly one integer β the length of the longest subarray of the array whose most frequent value is not unique. If there is no such subarray, output 0.
Examples
Input
7
1 1 2 2 3 3 3
Output
6
Input
10
1 1 1 5 4 1 3 1 2 2
Output
7
Input
1
1
Output
0
Note
In the first sample, the subarray [1, 1, 2, 2, 3, 3] is good, but [1, 1, 2, 2, 3, 3, 3] isn't: in the latter there are 3 occurrences of number 3, and no other element appears 3 times.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int solve(int a, int b, vector<int> &v) {
int balance = 0, n = v.size();
vector<int> fst(1 + n + n, -2);
int ans = 0;
fst[n] = -1;
for (int i = 0; i < n; i++) {
if (v[i] == a) balance++;
if (v[i] == b) balance--;
if (fst[n + balance] >= -1)
ans = max(ans, i - fst[n + balance]);
else
fst[n + balance] = i;
}
return ans;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
vector<int> v(n), freq(101);
for (int i = 0; i < n; i++) cin >> v[i], freq[v[i]]++;
int mx = 0;
for (int i = 1; i <= 100; i++)
if (freq[mx] < freq[i]) mx = i;
int ans = 0;
for (int i = 1; i <= 100; i++)
if (i != mx) ans = max(ans, solve(mx, i, v));
cout << ans << "\n";
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Sugoroku
problem
JOI is playing sugoroku alone. There are N squares in a straight line in this sugoroku, and each has a movement instruction written on it. The starting point is the 1st square and the goal is the Nth square. JOI repeats the following until he reaches the goal.
Roll the dice and proceed from the current square by the number of rolls, and follow the instructions of that square. Do not follow the instructions of the square to which you moved according to the instructions.
The goal is not only when you stop at the Nth square, but also when the destination exceeds the Nth square.
Create a program that outputs how many times you roll the dice to reach the goal when you are given a sugoroku board and M dice rolls.
input
The input consists of multiple datasets. Each dataset is given in the following format.
Each dataset consists of 1 + N + M rows.
Two integers N, M (2 β€ N β€ 1000, 1 β€ M β€ 1000) are written on the first line of the input, separated by blanks. N represents the number of sugoroku squares, and M represents the number of dice given.
In the following N lines, integers between -999 and 999 are written one by one. The integer on the 1 + i line (1 β€ i β€ N) represents the indication of the sugoroku i-th cell. Let X be the written integer. When X = 0, it indicates "do nothing", when X> 0, it indicates "advance X mass", and when X <0, it indicates "| X | mass return". However, | X | represents the absolute value of X.
In the following M line, integers from 1 to 6 are written one by one, and the number on the 1 + N + j line (1 β€ j β€ M) represents the dice roll that appears on the jth time.
However, the number of lines 2 and 1 + N is always 0. There is no cell with instructions to move to the cell before the first cell. In addition, the number of times the dice are rolled is M or less in any scoring input data.
When both N and M are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
For each data set, an integer indicating how many times the dice are rolled to reach the goal is output on one line.
Input / output example
Input example
10 5
0
0
Five
6
-3
8
1
8
-Four
0
1
3
Five
1
Five
10 10
0
-1
-1
Four
Four
-Five
0
1
-6
0
1
Five
2
Four
6
Five
Five
Four
1
6
0 0
Output example
Five
6
The following figure shows the first input example.
<image>
The following figure shows the second input example.
<image>
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
Example
Input
10 5
0
0
5
6
-3
8
1
8
-4
0
1
3
5
1
5
10 10
0
-1
-1
4
4
-5
0
1
-6
0
1
5
2
4
6
5
5
4
1
6
0 0
Output
5
6
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int N, M;
void solve() {
vector<int> v(N), d(M);
for (auto& i : v) cin >> i;
for (auto& i : d) cin >> i;
int start = 0;
int ans = 0;
for (int i = 0; i < M; i++) {
if (start >= N) break;
ans++;
start = d[i] + start + v[d[i] + start];
}
cout << ans << endl;
}
int main() {
while (cin >> N >> M, N || M) solve();
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
One Big Software Company has n employees numbered from 1 to n. The director is assigned number 1. Every employee of the company except the director has exactly one immediate superior. The director, of course, doesn't have a superior.
We will call person a a subordinates of another person b, if either b is an immediate supervisor of a, or the immediate supervisor of a is a subordinate to person b. In particular, subordinates of the head are all other employees of the company.
To solve achieve an Important Goal we need to form a workgroup. Every person has some efficiency, expressed by a positive integer ai, where i is the person's number. The efficiency of the workgroup is defined as the total efficiency of all the people included in it.
The employees of the big software company are obsessed with modern ways of work process organization. Today pair programming is at the peak of popularity, so the workgroup should be formed with the following condition. Each person entering the workgroup should be able to sort all of his subordinates who are also in the workgroup into pairs. In other words, for each of the members of the workgroup the number of his subordinates within the workgroup should be even.
Your task is to determine the maximum possible efficiency of the workgroup formed at observing the given condition. Any person including the director of company can enter the workgroup.
Input
The first line contains integer n (1 β€ n β€ 2Β·105) β the number of workers of the Big Software Company.
Then n lines follow, describing the company employees. The i-th line contains two integers pi, ai (1 β€ ai β€ 105) β the number of the person who is the i-th employee's immediate superior and i-th employee's efficiency. For the director p1 = - 1, for all other people the condition 1 β€ pi < i is fulfilled.
Output
Print a single integer β the maximum possible efficiency of the workgroup.
Examples
Input
7
-1 3
1 2
1 1
1 4
4 5
4 3
5 2
Output
17
Note
In the sample test the most effective way is to make a workgroup from employees number 1, 2, 4, 5, 6.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<int> adj[200010];
int val[200010];
long long ans[200010][3];
inline void dfs(int u) {
long long temp[2] = {0, 0};
for (int i = 0; i < adj[u].size(); i++) {
int v = adj[u][i];
dfs(v);
if (i) {
long long t0, t1;
t0 = max(temp[0] + ans[v][0], temp[1] + max(ans[v][2], ans[v][1]));
t1 = max(temp[1] + ans[v][0], temp[0] + max(ans[v][2], ans[v][1]));
temp[0] = t0;
temp[1] = t1;
} else {
temp[0] = ans[v][0];
temp[1] = max(ans[v][1], ans[v][2]);
}
}
ans[u][0] = temp[0];
ans[u][1] = temp[1];
ans[u][2] = temp[0] + val[u];
}
int main() {
int n, p, root;
cin >> n;
for (int i = 1; i <= n; i++) {
scanf("%d%d", &p, val + i);
if (p == -1) {
root = i;
continue;
}
adj[p].push_back(i);
}
dfs(root);
long long res = 0;
for (int i = 0; i < 3; i++) res = max(res, ans[root][i]);
cout << res << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Barney is standing in a bar and starring at a pretty girl. He wants to shoot her with his heart arrow but he needs to know the distance between him and the girl to make his shot accurate.
<image>
Barney asked the bar tender Carl about this distance value, but Carl was so busy talking to the customers so he wrote the distance value (it's a real number) on a napkin. The problem is that he wrote it in scientific notation. The scientific notation of some real number x is the notation of form AeB, where A is a real number and B is an integer and x = A Γ 10B is true. In our case A is between 0 and 9 and B is non-negative.
Barney doesn't know anything about scientific notation (as well as anything scientific at all). So he asked you to tell him the distance value in usual decimal representation with minimal number of digits after the decimal point (and no decimal point if it is an integer). See the output format for better understanding.
Input
The first and only line of input contains a single string of form a.deb where a, d and b are integers and e is usual character 'e' (0 β€ a β€ 9, 0 β€ d < 10100, 0 β€ b β€ 100) β the scientific notation of the desired distance value.
a and b contain no leading zeros and d contains no trailing zeros (but may be equal to 0). Also, b can not be non-zero if a is zero.
Output
Print the only real number x (the desired distance value) in the only line in its decimal notation.
Thus if x is an integer, print it's integer value without decimal part and decimal point and without leading zeroes.
Otherwise print x in a form of p.q such that p is an integer that have no leading zeroes (but may be equal to zero), and q is an integer that have no trailing zeroes (and may not be equal to zero).
Examples
Input
8.549e2
Output
854.9
Input
8.549e3
Output
8549
Input
0.33e0
Output
0.33
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int N(int n) {
int ans = 0;
for (; n > 0; n /= 10) {
ans += n % 10;
}
return ans;
}
int main() {
string s, ans = "";
cin >> s;
int n = s.size(), b, q;
if (s[n - 2] == 'e') q = 1, b = s[n - 1] - '0';
if (s[n - 3] == 'e') q = 2, b = s[n - 1] - '0' + (s[n - 2] - '0') * 10;
if (s[n - 4] == 'e')
q = 3, b = s[n - 1] - '0' + (s[n - 2] - '0') * 10 + (s[n - 3] - '0') * 100;
cout << s[0];
s = s.substr(2, n - 3 - q);
int i = 0;
if (!(s == "0"))
for (i = 0; i < s.size(); i++) {
if (i == b) cout << '.';
cout << s[i];
}
for (; i < b; i++) cout << "0";
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Polycarp plans to conduct a load testing of its new project Fakebook. He already agreed with his friends that at certain points in time they will send requests to Fakebook. The load testing will last n minutes and in the i-th minute friends will send ai requests.
Polycarp plans to test Fakebook under a special kind of load. In case the information about Fakebook gets into the mass media, Polycarp hopes for a monotone increase of the load, followed by a monotone decrease of the interest to the service. Polycarp wants to test this form of load.
Your task is to determine how many requests Polycarp must add so that before some moment the load on the server strictly increases and after that moment strictly decreases. Both the increasing part and the decreasing part can be empty (i. e. absent). The decrease should immediately follow the increase. In particular, the load with two equal neigbouring values is unacceptable.
For example, if the load is described with one of the arrays [1, 2, 8, 4, 3], [1, 3, 5] or [10], then such load satisfies Polycarp (in each of the cases there is an increasing part, immediately followed with a decreasing part). If the load is described with one of the arrays [1, 2, 2, 1], [2, 1, 2] or [10, 10], then such load does not satisfy Polycarp.
Help Polycarp to make the minimum number of additional requests, so that the resulting load satisfies Polycarp. He can make any number of additional requests at any minute from 1 to n.
Input
The first line contains a single integer n (1 β€ n β€ 100 000) β the duration of the load testing.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109), where ai is the number of requests from friends in the i-th minute of the load testing.
Output
Print the minimum number of additional requests from Polycarp that would make the load strictly increasing in the beginning and then strictly decreasing afterwards.
Examples
Input
5
1 4 3 2 5
Output
6
Input
5
1 2 2 2 1
Output
1
Input
7
10 20 40 50 70 90 30
Output
0
Note
In the first example Polycarp must make two additional requests in the third minute and four additional requests in the fourth minute. So the resulting load will look like: [1, 4, 5, 6, 5]. In total, Polycarp will make 6 additional requests.
In the second example it is enough to make one additional request in the third minute, so the answer is 1.
In the third example the load already satisfies all conditions described in the statement, so the answer is 0.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int kMaxN = 100000;
long long a[kMaxN];
long long pre[kMaxN], suf[kMaxN];
long long opt_prefix[kMaxN], opt_suffix[kMaxN];
int main() {
cin.tie(0);
ios_base::sync_with_stdio(false);
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
pre[0] = a[0];
for (int i = 1; i < n; ++i) {
opt_prefix[i] = opt_prefix[i - 1];
if (a[i] <= pre[i - 1]) {
opt_prefix[i] += pre[i - 1] - a[i] + 1;
pre[i] = 1 + pre[i - 1];
} else {
pre[i] = a[i];
}
}
suf[n - 1] = a[n - 1];
for (int i = n - 2; i >= 0; --i) {
opt_suffix[i] = opt_suffix[i + 1];
if (a[i] <= suf[i + 1]) {
opt_suffix[i] += suf[i + 1] - a[i] + 1;
suf[i] = 1 + suf[i + 1];
} else {
suf[i] = a[i];
}
}
long long answer = min(opt_prefix[n - 1], opt_suffix[0]);
for (int i = 1; i < n - 1; ++i) {
long long opt = opt_prefix[i - 1] + opt_suffix[i + 1];
long long el = max(pre[i - 1], suf[i + 1]) + 1;
if (a[i] < el) {
opt += el - a[i];
}
if (opt < answer) {
answer = opt;
}
}
cout << answer << endl;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Rock... Paper!
After Karen have found the deterministic winning (losing?) strategy for rock-paper-scissors, her brother, Koyomi, comes up with a new game as a substitute. The game works as follows.
A positive integer n is decided first. Both Koyomi and Karen independently choose n distinct positive integers, denoted by x1, x2, ..., xn and y1, y2, ..., yn respectively. They reveal their sequences, and repeat until all of 2n integers become distinct, which is the only final state to be kept and considered.
Then they count the number of ordered pairs (i, j) (1 β€ i, j β€ n) such that the value xi xor yj equals to one of the 2n integers. Here xor means the [bitwise exclusive or](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) operation on two integers, and is denoted by operators ^ and/or xor in most programming languages.
Karen claims a win if the number of such pairs is even, and Koyomi does otherwise. And you're here to help determine the winner of their latest game.
Input
The first line of input contains a positive integer n (1 β€ n β€ 2 000) β the length of both sequences.
The second line contains n space-separated integers x1, x2, ..., xn (1 β€ xi β€ 2Β·106) β the integers finally chosen by Koyomi.
The third line contains n space-separated integers y1, y2, ..., yn (1 β€ yi β€ 2Β·106) β the integers finally chosen by Karen.
Input guarantees that the given 2n integers are pairwise distinct, that is, no pair (i, j) (1 β€ i, j β€ n) exists such that one of the following holds: xi = yj; i β j and xi = xj; i β j and yi = yj.
Output
Output one line β the name of the winner, that is, "Koyomi" or "Karen" (without quotes). Please be aware of the capitalization.
Examples
Input
3
1 2 3
4 5 6
Output
Karen
Input
5
2 4 6 8 10
9 7 5 3 1
Output
Karen
Note
In the first example, there are 6 pairs satisfying the constraint: (1, 1), (1, 2), (2, 1), (2, 3), (3, 2) and (3, 3). Thus, Karen wins since 6 is an even number.
In the second example, there are 16 such pairs, and Karen wins again.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() { cout << "Karen"; }
``` |
### Prompt
Create a solution in cpp for the following problem:
Just to remind, girls in Arpa's land are really nice.
Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 β€ i < k, and a1 = x and ak = y.
<image>
Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it.
Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w.
Input
The first line contains integers n, m and w (1 β€ n β€ 1000, <image>, 1 β€ w β€ 1000) β the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited.
The second line contains n integers w1, w2, ..., wn (1 β€ wi β€ 1000) β the weights of the Hoses.
The third line contains n integers b1, b2, ..., bn (1 β€ bi β€ 106) β the beauties of the Hoses.
The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 β€ xi, yi β€ n, xi β yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct.
Output
Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w.
Examples
Input
3 1 5
3 2 5
2 4 2
1 2
Output
6
Input
4 2 11
2 4 6 6
6 4 2 1
1 2
2 3
Output
7
Note
In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6.
In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const double eps = 1e-7;
const long long mod = 1000000007;
vector<long long> w, b, u;
vector<vector<long long> > g;
vector<vector<long long> > comps;
void dfs(int v, int ind) {
comps[ind].push_back(v);
for (int i = 0; i < g[v].size(); i++) {
if (u[g[v][i]] == 0) {
u[g[v][i]] = 1;
dfs(g[v][i], ind);
}
}
return;
}
void solve() {
int n, m, q;
cin >> n >> m >> q;
w.resize(n), b.resize(n), u.resize(n, 0);
g.resize(n);
for (int i = 0; i < n; i++) {
cin >> w[i];
}
for (int i = 0; i < n; i++) {
cin >> b[i];
}
for (int i = 0; i < m; i++) {
int f, t;
cin >> f >> t;
t--;
f--;
g[f].push_back(t);
g[t].push_back(f);
}
for (int i = 0; i < n; i++) {
if (u[i] == 0) {
comps.push_back(vector<long long>());
u[i] = 1;
dfs(i, comps.size() - 1);
}
}
vector<vector<long long> > dp(comps.size() + 1, vector<long long>(q + 1, 0));
for (int i = 0; i < comps.size(); i++) {
for (int j = 0; j < q + 1; j++) {
dp[i + 1][j] = max(dp[i + 1][j], dp[i][j]);
long long allb = 0, allw = 0;
for (int z = 0; z < comps[i].size(); z++) {
allb += b[comps[i][z]];
allw += w[comps[i][z]];
if (j + w[comps[i][z]] <= q) {
dp[i + 1][j + w[comps[i][z]]] =
max(dp[i + 1][j + w[comps[i][z]]], dp[i][j] + b[comps[i][z]]);
}
}
if (j + allw <= q) {
dp[i + 1][j + allw] = max(dp[i + 1][j + allw], dp[i][j] + allb);
}
}
}
long long ans = 0;
for (int i = 0; i <= q; i++) ans = max(ans, dp[comps.size()][i]);
cout << ans << endl;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solve();
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Find the sum of the weights of edges of the Minimum-Cost Arborescence with the root r for a given weighted directed graph G = (V, E).
Constraints
* 1 β€ |V| β€ 100
* 0 β€ |E| β€ 1,000
* 0 β€ wi β€ 10,000
* G has arborescence(s) with the root r
Input
|V| |E| r
s0 t0 w0
s1 t1 w1
:
s|E|-1 t|E|-1 w|E|-1
, where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the root of the Minimum-Cost Arborescence.
si and ti represent source and target verticess of i-th directed edge. wi represents the weight of the i-th directed edge.
Output
Print the sum of the weights the Minimum-Cost Arborescence.
Examples
Input
4 6 0
0 1 3
0 2 2
2 0 1
2 3 1
3 0 1
3 1 5
Output
6
Input
6 10 0
0 2 7
0 1 1
0 3 5
1 4 9
2 1 6
1 3 2
3 4 3
4 2 2
2 5 8
3 5 3
Output
11
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int inf = 1e9+10;
struct Edge {
int from,to,weight;
Edge(int f,int t,int w)
{
from=f;to=t;weight=w;
}
bool operator < (const Edge &x) const
{
return weight < x.weight;
}
};
int edmonds(vector<Edge> &G, int V, int R)
{
vector<Edge> minInEdge(V,Edge(-1, -1, inf));
for (int i=0;i<G.size();i++)
{
const Edge &e = G[i];
minInEdge[e.to] = min(minInEdge[e.to], e);
}
minInEdge[R] = Edge(-1, R, 0);
vector<int> group(V, 0);
vector<bool> visited(V, false), isCycleGroup(V, false);
int cnt = 0;
for (int i = 0; i < V; i++)
{
if (visited[i])
continue;
int node = i;
vector<int> path;
while (node != -1 && !visited[node])
{
visited[node] = true;
path.push_back(node);
node = minInEdge[node].from;
}
bool isCycle = false;
for (int i=0;i<path.size();i++)
{
int v = path[i];
group[v] = cnt;
if (v == node)
isCycleGroup[cnt] = isCycle = true;
if (!isCycle)
cnt++;
}
if (isCycle)
cnt++;
}
if (cnt == V)
{
int answer = 0;
for(int i=0;i<minInEdge.size();i++)
{
Edge &e = minInEdge[i];
answer += e.weight;
}
return answer;
}
int answer = 0;
for (int i=0;i<minInEdge.size();i++)
{
Edge &e = minInEdge[i];
if (isCycleGroup[group[e.to]])
answer += e.weight;
}
vector<Edge> n_G;
for (int i=0;i<G.size();i++)
{
const Edge &e = G[i];
int u = group[e.from], v = group[e.to], w = e.weight;
if (u == v)
continue;
else
n_G.push_back(Edge(u, v, w - (isCycleGroup[v] ? minInEdge[e.to].weight : 0)));
}
return answer + edmonds(n_G, cnt, group[R]);
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int v,e,r;
cin>>v>>e>>r;
vector<Edge> G;
for(int i=0;i<e;i++)
{
int s,t,w;
cin>>s>>t>>w;
G.push_back(Edge(s,t,w));
}
cout<<edmonds(G,v,r)<<endl;
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2 Γ 10^5) β the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 β€ a_i β€ 10^9) β the elements of a.
Output
Output a single integer β the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
set<signed long long> s;
signed long long ans = 0;
vector<signed long long> sum(n + 1);
for (int i = 0; i < n; i++) sum[i + 1] = sum[i] + a[i];
for (int i = 0, j = 0; i <= n; ++i) {
while (s.count(sum[i])) {
s.erase(sum[j]);
++j;
}
s.insert(sum[i]);
ans += i - j;
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
The prehistoric caves of El Toll are located in MoiΓ (Barcelona). You have heard that there is a treasure hidden in one of n possible spots in the caves. You assume that each of the spots has probability 1 / n to contain a treasure.
You cannot get into the caves yourself, so you have constructed a robot that can search the caves for treasure. Each day you can instruct the robot to visit exactly k distinct spots in the caves. If none of these spots contain treasure, then the robot will obviously return with empty hands. However, the caves are dark, and the robot may miss the treasure even when visiting the right spot. Formally, if one of the visited spots does contain a treasure, the robot will obtain it with probability 1 / 2, otherwise it will return empty. Each time the robot searches the spot with the treasure, his success probability is independent of all previous tries (that is, the probability to miss the treasure after searching the right spot x times is 1 / 2x).
What is the expected number of days it will take to obtain the treasure if you choose optimal scheduling for the robot? Output the answer as a rational number modulo 109 + 7. Formally, let the answer be an irreducible fraction P / Q, then you have to output <image>. It is guaranteed that Q is not divisible by 109 + 7.
Input
The first line contains the number of test cases T (1 β€ T β€ 1000).
Each of the next T lines contains two integers n and k (1 β€ k β€ n β€ 5Β·108).
Output
For each test case output the answer in a separate line.
Example
Input
3
1 1
2 1
3 2
Output
2
500000007
777777786
Note
In the first case the robot will repeatedly search in the only spot. The expected number of days in this case is 2. Note that in spite of the fact that we know the treasure spot from the start, the robot still has to search there until he succesfully recovers the treasure.
In the second case the answer can be shown to be equal to 7 / 2 if we search the two spots alternatively. In the third case the answer is 25 / 9.
### Response
```cpp
#include <bits/stdc++.h>
long long n, k, p, mo, gc, t, c, answ;
int ttt;
long long gcd(long long x, long long y) {
if (y == 0)
return (x);
else
return (gcd(y, x % y));
}
long long mi(long long aa, long long bb) {
long long s = 1;
while (bb != 0) {
if ((bb % 2) == 1) s = (s * aa) % mo;
aa = (aa * aa) % mo;
bb = bb / 2;
}
return (s);
}
void ask(long long ni, long long ki, long long x, long long y, long long xi,
long long yi, long long sz, long long siz) {
if (ki == 1) {
long long li, ri, ai;
li = mi(x, ni - 1);
if ((x + mo) % mo == 1)
ri = (ni - 1) * y % mo;
else
ri = (li - 1) * mi(x - 1, mo - 2) % mo * y % mo;
ai = (xi * ri + yi) % mo * mi((1 - li * xi) % mo, mo - 2) % mo;
if ((x + mo) % mo == 1) {
answ = (answ + ni * ai % mo * siz) % mo;
answ = (answ + ((ni - 1) * ni / 2) % mo * y % mo * siz) % mo;
} else {
answ = (answ + (li * x - 1) % mo * mi(x - 1, mo - 2) % mo *
(ai + (y * mi(x - 1, mo - 2)) % mo) % mo * siz) %
mo;
answ = (answ - ni * mi(x - 1, mo - 2) % mo * y % mo * siz) % mo;
}
answ = (answ - ai * (siz - sz)) % mo;
} else {
long long li, ri, mm = ni / ki, m = ni % ki, yy, sz1, sz2, aa, bb;
li = mi(x, mm - 1);
if ((x + mo) % mo == 1) {
answ = (answ + ((mm + 1) * mm / 2) % mo * m % mo * y % mo * siz) % mo;
answ =
(answ + (mm * (mm - 1) / 2) % mo * (ki - m) % mo * y % mo * siz) % mo;
} else {
answ = (answ + (li * x - 1) % mo * mi(x - 1, 2 * mo - 4) % mo * (ki - m) %
mo * y % mo * siz) %
mo;
answ = (answ + ((li * x % mo) * x - 1) % mo * mi(x - 1, 2 * mo - 4) % mo *
m % mo * y % mo * siz) %
mo;
answ = (answ - ni * mi(x - 1, mo - 2) % mo * y % mo * siz) % mo;
}
if (x == 1) {
sz1 = sz + mm * siz;
sz2 = sz + (mm - 1) * siz;
} else {
sz1 = (sz + ((li * x % mo) * x - 1) % mo * siz % mo * mi(x - 1, mo - 2) -
siz) %
mo;
sz2 = (sz + (li * x - 1) % mo * siz % mo * mi(x - 1, mo - 2) - siz) % mo;
}
if ((x + mo) % mo == 1) {
ri = mm * y % mo;
yy = (mm - 1) * y % mo;
} else {
ri = (li * x - 1) % mo * mi(x - 1, mo - 2) % mo * y % mo;
;
yy = (li - 1) * mi(x - 1, mo - 2) % mo * y % mo;
}
aa = (li * xi % mo * x) % mo;
bb = (li * xi) % mo;
aa = mi(aa, mo - 2);
bb = mi(bb, mo - 2);
ask(ki, m, bb, (0 - yy * xi - yi) % mo * bb % mo, aa,
(0 - ri * xi - yi) % mo * aa % mo, sz1, sz2);
}
}
int main() {
scanf("%d", &ttt);
mo = 1000000007;
p = (mo + 1) / 2;
for (int iii = 1; iii <= ttt; iii++) {
scanf("%I64d%I64d", &n, &k);
gc = gcd(n, k);
n = n / gc;
k = k / gc;
answ = 0;
if (p != 1)
ask(n, k, 1, 1, 1 - p, 1, 1, 1);
else {
t = n / k;
answ = (t * (t + 1) / 2) % mo;
answ = answ * k % mo;
c = n % k;
answ = (answ + c * (t + 1)) % mo;
}
answ = answ % mo;
answ = (answ * mi(n, mo - 2)) % mo;
answ = (answ + mo) % mo;
printf("%I64d\n", answ);
}
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
There are n children, who study at the school β41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.
Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other.
You are given the number n, the initial arrangement of children and the number k. You have to find a way for the children to act if they want to finish the process in exactly k seconds. More formally, for each of the k moves, you need to output the numbers of the children who turn left during this move.
For instance, for the configuration shown below and k = 2 children can do the following steps:
<image> At the beginning, two pairs make move: (1, 2) and (3, 4). After that, we receive the following configuration: <image> At the second move pair (2, 3) makes the move. The final configuration is reached. Good job. <image>
It is guaranteed that if the solution exists, it takes not more than n^2 "headturns".
Input
The first line of input contains two integers n and k (2 β€ n β€ 3000, 1 β€ k β€ 3000000) β the number of children and required number of moves.
The next line contains a string of length n and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right.
Output
If there is no solution, print a single line with number -1.
Otherwise, output k lines. Each line has to start with a number n_i (1β€ n_i β€ n/2) β the number of pairs of children, who turn at this move. After that print n_i distinct integers β the numbers of the children who will turn left during this move.
After performing all "headturns", there can't be a pair of two neighboring children looking at each other.
If there are many solutions, print any of them.
Examples
Input
2 1
RL
Output
1 1
Input
2 1
LR
Output
-1
Input
4 2
RLRL
Output
2 1 3
1 2
Note
The first sample contains a pair of children who look at each other. After one move, they can finish the process.
In the second sample, children can't make any move. As a result, they can't end in k>0 moves.
The third configuration is described in the statement.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout << fixed;
cout.precision(10);
int n, k;
string s;
cin >> n >> k >> s;
vector<int> a(n);
for (int i = 0; i < n; i++) {
a[i] = (s[i] == 'R');
}
vector<int> cur;
for (int i = 0; i < n - 1; i++) {
if (a[i] and !a[i + 1]) {
cur.push_back(i);
}
}
int total_moves = 0;
vector<vector<int>> moves;
while (!cur.empty()) {
moves.push_back(cur);
total_moves += cur.size();
cur.clear();
for (int x : moves.back()) {
swap(a[x], a[x + 1]);
if (x < n - 2 and !a[x + 2]) {
cur.push_back(x + 1);
}
if (x > 0 and a[x - 1]) {
cur.push_back(x - 1);
}
}
}
if (k < (int)moves.size() or k > total_moves) {
cout << -1;
exit(0);
}
int x = k - moves.size();
vector<vector<int>> ans;
bool is = true;
for (auto in : moves) {
for (int i : in) {
if (x == 0) is = false;
cur.push_back(i);
if (is) {
ans.push_back(cur);
cur.clear();
x--;
}
}
x++;
if (cur.size()) ans.push_back(cur);
cur.clear();
}
for (auto i : ans) {
cout << (int)i.size() << " ";
for (auto j : i) {
cout << j + 1 << " ";
}
cout << "\n";
}
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
We have N locked treasure boxes, numbered 1 to N.
A shop sells M keys. The i-th key is sold for a_i yen (the currency of Japan), and it can unlock b_i of the boxes: Box c_{i1}, c_{i2}, ..., c_{i{b_i}}. Each key purchased can be used any number of times.
Find the minimum cost required to unlock all the treasure boxes. If it is impossible to unlock all of them, print -1.
Constraints
* All values in input are integers.
* 1 \leq N \leq 12
* 1 \leq M \leq 10^3
* 1 \leq a_i \leq 10^5
* 1 \leq b_i \leq N
* 1 \leq c_{i1} < c_{i2} < ... < c_{i{b_i}} \leq N
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
c_{11} c_{12} ... c_{1{b_1}}
:
a_M b_M
c_{M1} c_{M2} ... c_{M{b_M}}
Output
Print the minimum cost required to unlock all the treasure boxes. If it is impossible to unlock all of them, print -1.
Examples
Input
2 3
10 1
1
15 1
2
30 2
1 2
Output
25
Input
12 1
100000 1
2
Output
-1
Input
4 6
67786 3
1 3 4
3497 1
2
44908 3
2 3 4
2156 3
2 3 4
26230 1
2
86918 1
3
Output
69942
### Response
```cpp
#define INF 1000000000
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
int n, m;
cin >> n >> m;
vector<int> p(1 << n, INF);
p.at(0) = 0;
for (int i = 0; i < m; i++) {
int a, b, open = 0;
cin >> a >> b;
for (int j = 0; j < b; j++) {
int c;
cin >> c;
open += 1 << (c - 1);
}
for (int j = 0; j < 1 << n; j++) {
p.at(j) = min(p.at(j), p.at(j & (~open)) + a);
}
}
if (p.at((1 << n) - 1) == INF) {
cout << -1 << endl;
} else {
cout << p.at((1 << n) - 1) << endl;
}
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Polycarpus has been working in the analytic department of the "F.R.A.U.D." company for as much as n days. Right now his task is to make a series of reports about the company's performance for the last n days. We know that the main information in a day report is value ai, the company's profit on the i-th day. If ai is negative, then the company suffered losses on the i-th day.
Polycarpus should sort the daily reports into folders. Each folder should include data on the company's performance for several consecutive days. Of course, the information on each of the n days should be exactly in one folder. Thus, Polycarpus puts information on the first few days in the first folder. The information on the several following days goes to the second folder, and so on.
It is known that the boss reads one daily report folder per day. If one folder has three or more reports for the days in which the company suffered losses (ai < 0), he loses his temper and his wrath is terrible.
Therefore, Polycarpus wants to prepare the folders so that none of them contains information on three or more days with the loss, and the number of folders is minimal.
Write a program that, given sequence ai, will print the minimum number of folders.
Input
The first line contains integer n (1 β€ n β€ 100), n is the number of days. The second line contains a sequence of integers a1, a2, ..., an (|ai| β€ 100), where ai means the company profit on the i-th day. It is possible that the company has no days with the negative ai.
Output
Print an integer k β the required minimum number of folders. In the second line print a sequence of integers b1, b2, ..., bk, where bj is the number of day reports in the j-th folder.
If there are multiple ways to sort the reports into k days, print any of them.
Examples
Input
11
1 2 3 -4 -5 -6 5 -5 -6 -7 6
Output
3
5 3 3
Input
5
0 -1 100 -1 0
Output
1
5
Note
Here goes a way to sort the reports from the first sample into three folders:
1 2 3 -4 -5 | -6 5 -5 | -6 -7 6
In the second sample you can put all five reports in one folder.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<int> a;
int main() {
int n, m, x = 0, y = 0;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> m;
++x;
if (m < 0) ++y;
if (y == 3) {
a.push_back(x - 1);
x = 1;
y = 1;
}
}
cout << a.size() + 1 << endl;
for (int i = 0; i < a.size(); ++i) cout << a[i] << ' ';
cout << x;
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 Γ 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:
<image>
In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.
Input
The first two lines of the input consist of a 2 Γ 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 Γ 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.
Output
Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).
Examples
Input
AB
XC
XB
AC
Output
YES
Input
AB
XC
AC
BX
Output
NO
Note
The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.
In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all...
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int inf = 2e9 + 9091203;
const long long MOD = 1e9 + 696969;
const long long INF = 1e18;
const int BASE = 10000;
int n, m, b, c, k;
int goal[5];
int main() {
char a;
int tab[5], DL = 0;
for (int i = 1; i <= 2; ++i)
for (int j = 1; j <= 2; ++j) scanf(" %c", &a) ?: 0, tab[++DL] = a;
DL = 0;
for (int i = 1; i <= 2; ++i)
for (int j = 1; j <= 2; ++j) scanf(" %c", &a) ?: 0, goal[++DL] = a;
for (int steps = 0; steps < 10000000; ++steps) {
int r = rand() % 4;
if (r == 0 && (goal[1] == 'X' || goal[2] == 'X')) swap(goal[1], goal[2]);
if (r == 1 && (goal[2] == 'X' || goal[4] == 'X')) swap(goal[2], goal[4]);
if (r == 2 && (goal[4] == 'X' || goal[3] == 'X')) swap(goal[4], goal[3]);
if (r == 3 && (goal[3] == 'X' || goal[1] == 'X')) swap(goal[3], goal[1]);
bool b1 = 1;
for (int i = 1; i <= 4; ++i)
if (tab[i] != goal[i]) b1 = 0;
if (b1) {
cout << "YES";
exit(0);
};
}
{
cout << "NO";
exit(0);
};
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
One day Polycarp decided to rewatch his absolute favourite episode of well-known TV series "Tufurama". He was pretty surprised when he got results only for season 7 episode 3 with his search query of "Watch Tufurama season 3 episode 7 online full hd free". This got Polycarp confused β what if he decides to rewatch the entire series someday and won't be able to find the right episodes to watch? Polycarp now wants to count the number of times he will be forced to search for an episode using some different method.
TV series have n seasons (numbered 1 through n), the i-th season has ai episodes (numbered 1 through ai). Polycarp thinks that if for some pair of integers x and y (x < y) exist both season x episode y and season y episode x then one of these search queries will include the wrong results. Help Polycarp to calculate the number of such pairs!
Input
The first line contains one integer n (1 β€ n β€ 2Β·105) β the number of seasons.
The second line contains n integers separated by space a1, a2, ..., an (1 β€ ai β€ 109) β number of episodes in each season.
Output
Print one integer β the number of pairs x and y (x < y) such that there exist both season x episode y and season y episode x.
Examples
Input
5
1 2 3 4 5
Output
0
Input
3
8 12 7
Output
3
Input
3
3 2 1
Output
2
Note
Possible pairs in the second example:
1. x = 1, y = 2 (season 1 episode 2 <image> season 2 episode 1);
2. x = 2, y = 3 (season 2 episode 3 <image> season 3 episode 2);
3. x = 1, y = 3 (season 1 episode 3 <image> season 3 episode 1).
In the third example:
1. x = 1, y = 2 (season 1 episode 2 <image> season 2 episode 1);
2. x = 1, y = 3 (season 1 episode 3 <image> season 3 episode 1).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
int a[maxn], T[maxn];
int n;
void add(int x, int p) {
for (; x <= n; x += x & -x) T[x] += p;
}
long long sum(int x) {
long long res = 0;
for (; x; x -= x & -x) res += T[x];
return res;
}
priority_queue<pair<int, int>, vector<pair<int, int> >,
greater<pair<int, int> > >
pq;
int main() {
long long ans = 0;
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", a + i);
for (int i = 1; i <= n; i++) {
while (!pq.empty() && pq.top().first < i) {
add(pq.top().second, -1);
pq.pop();
}
ans += sum(min(i, a[i]));
if (a[i] <= i) continue;
add(i, 1);
pq.push(make_pair(a[i], i));
}
printf("%lld\n", ans);
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Given is a string S. Let T be the concatenation of K copies of S. We can repeatedly perform the following operation: choose a character in T and replace it with a different character. Find the minimum number of operations required to satisfy the following condition: any two adjacent characters in T are different.
Constraints
* 1 \leq |S| \leq 100
* S consists of lowercase English letters.
* 1 \leq K \leq 10^9
* K is an integer.
Input
Input is given from Standard Input in the following format:
S
K
Output
Print the minimum number of operations required.
Examples
Input
issii
2
Output
4
Input
qq
81
Output
81
Input
cooooooooonteeeeeeeeeest
999993333
Output
8999939997
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin>>s;
int k=0;
long long n;
cin>>n;
long long count=0,a=0,b=0;
while(s[0]==s[k++] && k<=s.length() && s[0]==s[s.length()-1])a++;
k=s.length()-1;
while(s[s.length()-1]==s[k--] && k>=0 &&s[0]==s[s.length()-1])b++;
if(a==s.length())
{
cout<<n*a/2<<endl;
return 0;
}
for(int i=a;i<s.length()-b;i++)
{
if(s[i]==s[i-1])
{
count++;
i++;
}
}
//cout<<a<<' '<<b<<' '<<count<<endl;
long long sum=(a/2)+(b/2)+(n-1)*((a+b)/2)+n*(count);
cout<<sum<<endl;
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible.
Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type β if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c.
Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task!
Input
The first line of the input contains three space-separated numbers, n, m and k (1 β€ m β€ n β€ 18, 0 β€ k β€ n * (n - 1)) β the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules.
The second line contains n space-separated numbers ai, (0 β€ ai β€ 109) β the satisfaction he gets from the i-th dish.
Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 β€ xi, yi β€ n, 0 β€ ci β€ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 β€ i < j β€ k), that xi = xj and yi = yj.
Output
In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant.
Examples
Input
2 2 1
1 1
2 1 1
Output
3
Input
4 3 2
1 2 3 4
2 1 5
3 4 2
Output
12
Note
In the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.
In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int const oo = 1e9, bound = 1e6, mod = oo + 7;
long long const OO = 1e18;
int n, m, k, aa[20];
int cc[20][20];
long long dp[18][1 << 18];
long long rec(int idx, int msk) {
long long &ret = dp[idx][msk];
if (ret != -1) return ret;
int cop = msk, e = 0;
while (cop) {
if (cop & 1) e++;
cop >>= 1;
}
if (e == m) return ret = 0;
for (int(i) = 0; (i) < (n); (i)++) {
if (!((msk >> i) & 1))
ret = max(ret,
rec(i, (1 << i) | msk) + aa[i] + (msk != 0 ? cc[idx][i] : 0));
}
return ret;
}
int main() {
memset(dp, -1, sizeof dp);
scanf("%d", &n), scanf("%d", &m), scanf("%d", &k);
for (int(i) = 0; (i) < (n); (i)++) scanf("%d", &aa[i]);
for (int(i) = 0; (i) < (k); (i)++) {
int a, b, c;
scanf("%d", &a), scanf("%d", &b), scanf("%d", &c);
a--, b--;
cc[a][b] = c;
}
long long mx = rec(0, 0);
printf("%lld\n", mx);
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!
In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage.
One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.
But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).
The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.
Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
Input
The first line contains an integer n (1 β€ n β€ 105).
The next line contains n integers a1, a2, ..., an (0 β€ ai β€ 1012) β Mr. Bitkoch's sausage.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single integer β the maximum pleasure BitHaval and BitAryo can get from the dinner.
Examples
Input
2
1 2
Output
3
Input
3
1 2 3
Output
3
Input
2
1000 1000
Output
1000
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long one = 1;
struct Tree {
int ct;
struct Tree *left, *right;
Tree(int x) : ct(x), left(NULL), right(NULL) {}
};
void InsertNode(Tree *TreeNode, int level, long long x, int change) {
if (level < 0) return;
if ((x & (one << level)) == 0) {
if (TreeNode->left == NULL) TreeNode->left = new Tree(0);
TreeNode->left->ct += change;
InsertNode(TreeNode->left, level - 1, x, change);
} else {
if (TreeNode->right == NULL) TreeNode->right = new Tree(0);
TreeNode->right->ct += change;
InsertNode(TreeNode->right, level - 1, x, change);
}
}
long long query(Tree *TreeNode, int level, long long x) {
if (TreeNode == NULL) return 0;
if (level < 0) return 0;
if ((one << level) & x) {
if (TreeNode->left != NULL) {
if (TreeNode->left->ct)
return (one << level) + query(TreeNode->left, level - 1, x);
else
return query(TreeNode->right, level - 1, x);
} else
return query(TreeNode->right, level - 1, x);
} else {
if (TreeNode->right != NULL) {
if (TreeNode->right->ct)
return (one << level) + query(TreeNode->right, level - 1, x);
else
return query(TreeNode->left, level - 1, x);
} else
return query(TreeNode->left, level - 1, x);
}
}
int main() {
Tree *TreeNode = new Tree(0);
int n;
scanf("%d", &n);
long long arr[n];
for (int i(0); i < n; i++) scanf("%lld", &arr[i]);
long long arr_suf[n + 1];
arr_suf[n] = 0;
InsertNode(TreeNode, 40, 0, 1);
long long temp(0);
for (int i(n - 1); i >= 0; i--) {
temp = temp ^ arr[i];
arr_suf[i] = temp;
InsertNode(TreeNode, 40, temp, 1);
}
temp = 0;
long long res = query(TreeNode, 40, 0);
for (int i(0); i <= n - 1; i++) {
InsertNode(TreeNode, 40, arr_suf[i], -1);
temp = temp ^ arr[i];
long long value = query(TreeNode, 40, temp);
res = max(res, value);
}
printf("%lld\n", res);
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Problem F and F2 are the same problem, but with different constraints and time limits.
We have a board divided into N horizontal rows and N vertical columns of square cells. The cell at the i-th row from the top and the j-th column from the left is called Cell (i,j). Each cell is either empty or occupied by an obstacle. Also, each empty cell has a digit written on it. If A_{i,j}= `1`, `2`, ..., or `9`, Cell (i,j) is empty and the digit A_{i,j} is written on it. If A_{i,j}= `#`, Cell (i,j) is occupied by an obstacle.
Cell Y is reachable from cell X when the following conditions are all met:
* Cells X and Y are different.
* Cells X and Y are both empty.
* One can reach from Cell X to Cell Y by repeatedly moving right or down to an adjacent empty cell.
Consider all pairs of cells (X,Y) such that cell Y is reachable from cell X. Find the sum of the products of the digits written on cell X and cell Y for all of those pairs.
Constraints
* 1 \leq N \leq 500
* A_{i,j} is one of the following characters: `1`, `2`, ... `9` and `#`.
Input
Input is given from Standard Input in the following format:
N
A_{1,1}A_{1,2}...A_{1,N}
A_{2,1}A_{2,2}...A_{2,N}
:
A_{N,1}A_{N,2}...A_{N,N}
Output
Print the sum of the products of the digits written on cell X and cell Y for all pairs (X,Y) such that cell Y is reachable from cell X.
Examples
Input
2
11
11
Output
5
Input
4
1111
11#1
1#11
1111
Output
47
Input
10
76##63##3#
8445669721
75#9542133
3#285##445
749632##89
2458##9515
5952578#77
1#3#44196#
4355#99#1#
298#63587
Output
36065
Input
10
4177143673
7#########
5#1716155#
6#4#####5#
2#3#597#6#
6#9#8#3#5#
5#2#899#9#
1#6#####6#
6#5359657#
5#########
Output
6525
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
string to_string(string s) {
return '"' + s + '"';
}
string to_string(const char *s) {
return to_string((string)s);
}
string to_string(bool b) {
return (b ? "true" : "false");
}
template<typename A, typename B> string to_string(pair<A, B> p) {
return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}
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;
}
void debug_out() {
cerr << endl;
}
template<typename Head, typename... Tail> void debug_out(Head H, Tail... T) {
cerr << " " << to_string(H);
debug_out(T...);
}
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
const int inf = 0x3f3f3f3f;
void cmax(int &x, int y) {
if (x < y) {
x = y;
}
}
void cmin(int &x, int y) {
if (x > y) {
x = y;
}
}
int main() {
#ifdef wxh010910
freopen("input.txt", "r", stdin);
#endif
int n;
cin >> n;
vector<string> board(n);
for (int i = 0; i < n; ++i) {
cin >> board[i];
}
long long answer = 0;
function<void(vector<string>)> solve = [&](vector<string> board) {
int n = board.size(), m = board[0].size();
if (n < m) {
vector<string> rotated(m, string(n, ' '));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
rotated[j][i] = board[i][j];
}
}
swap(n, m);
board = rotated;
}
if (m == 1) {
int sum = 0;
for (int i = 0; i < n; ++i) {
if (board[i][0] == '#') {
sum = 0;
} else {
answer += (board[i][0] - '0') * sum;
sum += board[i][0] - '0';
}
}
return;
}
vector<string> u = vector<string> (board.begin(), board.begin() + (n >> 1));
vector<string> d = vector<string> (board.begin() + (n >> 1), board.end());
solve(u);
solve(d);
u.push_back(d[0]);
int nu = n >> 1, nd = n + 1 >> 1;
vector<vector<int>> left(nd, vector<int> (m, inf));
vector<vector<int>> right(nd, vector<int> (m, -inf));
vector<int> top(m);
vector<int> bottom(m);
for (int i = 0; i < m; ++i) {
if (d[0][i] != '#') {
left[0][i] = right[0][i] = i;
}
}
for (int i = 0; i < nd; ++i) {
for (int j = 0; j < m; ++j) {
if (d[i][j] != '#') {
if (i) {
cmin(left[i][j], left[i - 1][j]);
cmax(right[i][j], right[i - 1][j]);
}
if (j) {
cmin(left[i][j], left[i][j - 1]);
cmax(right[i][j], right[i][j - 1]);
}
}
}
}
{
vector<vector<int>> temp(nd, vector<int> (m, -inf));
for (int i = nd - 1; ~i; --i) {
for (int j = m - 1; ~j; --j) {
if (d[i][j] != '#') {
temp[i][j] = i;
if (i + 1 < nd) {
cmax(temp[i][j], temp[i + 1][j]);
}
if (j + 1 < m) {
cmax(temp[i][j], temp[i][j + 1]);
}
}
}
}
for (int i = 0; i < m; ++i) {
bottom[i] = temp[0][i];
}
}
{
vector<vector<int>> temp(nu + 1, vector<int> (m, inf));
for (int i = 0; i <= nu; ++i) {
for (int j = 0; j < m; ++j) {
if (u[i][j] != '#') {
temp[i][j] = i;
if (i) {
cmin(temp[i][j], temp[i - 1][j]);
}
if (j) {
cmin(temp[i][j], temp[i][j - 1]);
}
}
}
}
for (int i = 0; i < m; ++i) {
top[i] = temp[nu][i];
}
}
vector<vector<int>> mp(m, vector<int> (m, inf));
for (int i = 0; i < nd; ++i) {
for (int j = 0; j < m; ++j) {
if (left[i][j] <= right[i][j]) {
cmin(mp[left[i][j]][right[i][j]], i);
}
}
}
for (int l = 0; l < m; ++l) {
for (int r = m - 1; ~r; --r) {
if (l) {
cmin(mp[l][r], mp[l - 1][r]);
}
if (r + 1 < m) {
cmin(mp[l][r], mp[l][r + 1]);
}
}
}
auto meeting_point = [&](int a, int b) {
int p = mp[a][b];
return p <= min(bottom[a], bottom[b]) ? p : inf;
};
vector<int> sum1(nd);
vector<vector<int>> sum2(nd, vector<int> (m));
vector<vector<int>> sum3(nd, vector<int> (m));
vector<vector<int>> sum4(m, vector<int> (m));
for (int i = 0; i < nd; ++i) {
if (i) {
sum1[i] = sum1[i - 1];
for (int j = 0; j < m; ++j) {
sum2[i][j] = sum2[i - 1][j];
sum3[i][j] = sum3[i - 1][j];
}
}
for (int j = 0; j < m; ++j) {
if (left[i][j] <= right[i][j]) {
sum1[i] += d[i][j] - '0';
if (left[i][j]) {
sum2[i][left[i][j] - 1] += d[i][j] - '0';
}
if (right[i][j] + 1 < m) {
sum3[i][right[i][j] + 1] += d[i][j] - '0';
}
if (left[i][j] && right[i][j] + 1 < m) {
sum4[left[i][j] - 1][right[i][j] + 1] += d[i][j] - '0';
}
}
}
}
for (int i = 0; i < nd; ++i) {
for (int j = m - 1; j; --j) {
sum2[i][j - 1] += sum2[i][j];
}
for (int j = 1; j < m; ++j) {
sum3[i][j] += sum3[i][j - 1];
}
}
for (int l = m - 1; ~l; --l) {
for (int r = l; r < m; ++r) {
if (l + 1 < m) {
sum4[l][r] += sum4[l + 1][r];
}
if (r) {
sum4[l][r] += sum4[l][r - 1];
}
if (l + 1 < m && r) {
sum4[l][r] -= sum4[l + 1][r - 1];
}
}
}
auto both_reachable = [&](int a, int b, int l) {
if (meeting_point(a, b) > l) {
return 0;
} else {
return sum1[l] - sum2[l][a] - sum3[l][b] + sum4[a][b];
}
};
vector<int> reachable(m);
for (int i = 0; i < m; ++i) {
reachable[i] = both_reachable(i, i, bottom[i]);
}
vector<vector<int>> event(nu);
vector<bool> ban(m);
for (int i = 0; i < m; ++i) {
if (top[i] >= nu) {
ban[i] = true;
} else {
event[top[i]].push_back(i);
}
}
vector<int> l(m), r(m);
for (int i = m - 1; ~i; --i) {
if (d[0][i] == '#') {
l[i] = inf;
r[i] = -inf;
} else {
l[i] = i;
r[i] = max(i, i + 1 < m ? r[i + 1] : -inf);
}
}
for (int row = nu - 1; ~row; --row) {
for (int i = m - 1; ~i; --i) {
if (u[row][i] == '#') {
l[i] = inf;
r[i] = -inf;
} else if (i + 1 < m) {
cmin(l[i], l[i + 1]);
cmax(r[i], r[i + 1]);
}
}
vector<int> has(m);
vector<int> st(m);
int sum = 0, stl = 0, str = 0, myl = 0, myr = -1;
auto insert = [&](int x) {
if (!ban[x]) {
if (stl < str) {
sum -= has[st[str - 1]];
has[st[str - 1]] -= both_reachable(st[str - 1], x, min(bottom[st[str - 1]], bottom[x]));
sum += has[st[str - 1]];
if (bottom[st[str - 1]] <= bottom[x]) {
--str;
while (stl < str) {
sum -= has[st[str - 1]];
has[st[str - 1]] -= both_reachable(st[str - 1], x, min(bottom[st[str - 1]], bottom[x])) - both_reachable(st[str - 1], x, min(bottom[st[str]], bottom[x]));
sum += has[st[str - 1]];
if (bottom[st[str - 1]] <= bottom[x]) {
--str;
} else {
break;
}
}
}
}
st[str++] = x;
has[x] = reachable[x];
sum += has[x];
}
};
auto erase = [&](int x) {
if (!ban[x]) {
sum -= has[x];
if (stl < str && st[stl] == x) {
++stl;
}
}
};
for (int i = 0; i < m; ++i) {
if (l[i] <= r[i]) {
while (myr < r[i]) {
insert(++myr);
}
while (myl < l[i]) {
erase(myl++);
}
answer += (u[row][i] - '0') * sum;
}
}
for (auto p : event[row]) {
ban[p] = true;
}
}
};
solve(board);
cout << answer << endl;
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u β v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuroβs body and sting him.
Kuro wants to know how many pair of city (u, v) he can take as his route. Since heβs not really bright, he asked you to help him with this problem.
Input
The first line contains three integers n, x and y (1 β€ n β€ 3 β
10^5, 1 β€ x, y β€ n, x β y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
n - 1 lines follow, each line contains two integers a and b (1 β€ a, b β€ n, a β b), describes a road connecting two towns a and b.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output
A single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.
Examples
Input
3 1 3
1 2
2 3
Output
5
Input
3 1 3
1 2
1 3
Output
4
Note
On the first example, Kuro can choose these pairs:
* (1, 2): his route would be 1 β 2,
* (2, 3): his route would be 2 β 3,
* (3, 2): his route would be 3 β 2,
* (2, 1): his route would be 2 β 1,
* (3, 1): his route would be 3 β 2 β 1.
Kuro can't choose pair (1, 3) since his walking route would be 1 β 2 β 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
* (1, 2): his route would be 1 β 2,
* (2, 1): his route would be 2 β 1,
* (3, 2): his route would be 3 β 1 β 2,
* (3, 1): his route would be 3 β 1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 500005;
using namespace std;
vector<long long> e[MAXN];
vector<long long> re[MAXN];
long long use[MAXN];
long long num;
long long dfs(long long x, long long aim) {
use[x] = 1;
num++;
long long k = 0;
if (x == aim) k = 1;
long long t1 = 0;
for (long long i = 0; i < e[x].size(); i++) {
long long t = e[x][i];
if (!use[t]) t1 = dfs(t, aim);
if (t1 == 1) k = 1;
}
return k;
}
int main() {
long long n, i, j, k, t1, t2, t3, x, y, m1, m2, s, t;
cin >> n >> s >> t;
for (i = 0; i < n - 1; i++) {
cin >> t1 >> t2;
e[t1].push_back(t2);
e[t2].push_back(t1);
}
num = 0;
memset(use, 0, sizeof(use));
use[s] = 1;
m1 = 1;
for (i = 0; i < e[s].size(); i++) {
t1 = e[s][i];
num = 0;
if (!dfs(t1, t)) m1 += num;
}
memset(use, 0, sizeof(use));
use[t] = 1;
num = 0;
m2 = 1;
for (i = 0; i < e[t].size(); i++) {
t1 = e[t][i];
num = 0;
if (!dfs(t1, s)) m2 += num;
}
cout << (n * (n - 1)) - m1 * m2;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
You are given a tree with n vertices and you are allowed to perform no more than 2n transformations on it. Transformation is defined by three vertices x, y, y' and consists of deleting edge (x, y) and adding edge (x, y'). Transformation x, y, y' could be performed if all the following conditions are satisfied:
1. There is an edge (x, y) in the current tree.
2. After the transformation the graph remains a tree.
3. After the deletion of edge (x, y) the tree would consist of two connected components. Let's denote the set of nodes in the component containing vertex x by Vx, and the set of nodes in the component containing vertex y by Vy. Then condition |Vx| > |Vy| should be satisfied, i.e. the size of the component with x should be strictly larger than the size of the component with y.
You should minimize the sum of squared distances between all pairs of vertices in a tree, which you could get after no more than 2n transformations and output any sequence of transformations leading initial tree to such state.
Note that you don't need to minimize the number of operations. It is necessary to minimize only the sum of the squared distances.
Input
The first line of input contains integer n (1 β€ n β€ 2Β·105) β number of vertices in tree.
The next n - 1 lines of input contains integers a and b (1 β€ a, b β€ n, a β b) β the descriptions of edges. It is guaranteed that the given edges form a tree.
Output
In the first line output integer k (0 β€ k β€ 2n) β the number of transformations from your example, minimizing sum of squared distances between all pairs of vertices.
In each of the next k lines output three integers x, y, y' β indices of vertices from the corresponding transformation.
Transformations with y = y' are allowed (even though they don't change tree) if transformation conditions are satisfied.
If there are several possible answers, print any of them.
Examples
Input
3
3 2
1 3
Output
0
Input
7
1 2
2 3
3 4
4 5
5 6
6 7
Output
2
4 3 2
4 5 6
Note
This is a picture for the second sample. Added edges are dark, deleted edges are dotted.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct tri {
int x, y, z;
};
const int MAXN = 200005;
vector<int> sas[MAXN], tmp;
int rozm[MAXN], n, last;
int byl[MAXN];
queue<tri> q;
void dfs(int co, int nie) {
rozm[co] = 1;
bool ta = 1;
for (auto x : sas[co])
if (x != nie) {
dfs(x, co);
rozm[co] += rozm[x];
if (rozm[x] * 2 > n) ta = 0;
}
if ((n - rozm[co]) * 2 > n) ta = 0;
if (ta) byl[co] = 1;
}
void wal(int co) {
byl[co] = 2;
tri t;
for (int x : sas[co])
if (!byl[x]) {
t.x = last;
t.y = co;
t.z = x;
q.push(t);
wal(x);
}
tmp.push_back(co);
last = co;
}
int main() {
int m, k, a, b, c, d, e, f;
tri t;
scanf("%d", &n);
for (a = 1; a < n; a++) {
scanf("%d%d", &b, &c);
sas[b].push_back(c);
sas[c].push_back(b);
}
dfs(1, 1);
for (a = 1; a <= n; a++)
if (byl[a] == 1)
for (int x : sas[a])
if (!byl[x]) {
last = a;
tmp.push_back(a);
wal(x);
for (b = tmp.size() - 4; b >= 0; b--) {
t.x = tmp[b];
t.y = tmp[b + 1];
t.z = tmp[tmp.size() - 2];
q.push(t);
}
tmp.clear();
}
printf("%d\n", q.size());
while (!q.empty()) {
t = q.front();
q.pop();
printf("%d %d %d\n", t.x, t.y, t.z);
}
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Wojtek has just won a maths competition in Byteland! The prize is admirable β a great book called 'Card Tricks for Everyone.' 'Great!' he thought, 'I can finally use this old, dusted deck of cards that's always been lying unused on my desk!'
The first chapter of the book is 'How to Shuffle k Cards in Any Order You Want.' It's basically a list of n intricate methods of shuffling the deck of k cards in a deterministic way. Specifically, the i-th recipe can be described as a permutation (P_{i,1}, P_{i,2}, ..., P_{i,k}) of integers from 1 to k. If we enumerate the cards in the deck from 1 to k from top to bottom, then P_{i,j} indicates the number of the j-th card from the top of the deck after the shuffle.
The day is short and Wojtek wants to learn only some of the tricks today. He will pick two integers l, r (1 β€ l β€ r β€ n), and he will memorize each trick from the l-th to the r-th, inclusive. He will then take a sorted deck of k cards and repeatedly apply random memorized tricks until he gets bored. He still likes maths, so he started wondering: how many different decks can he have after he stops shuffling it?
Wojtek still didn't choose the integers l and r, but he is still curious. Therefore, he defined f(l, r) as the number of different decks he can get if he memorizes all the tricks between the l-th and the r-th, inclusive. What is the value of
$$$β_{l=1}^n β_{r=l}^n f(l, r)?$$$
Input
The first line contains two integers n, k (1 β€ n β€ 200 000, 1 β€ k β€ 5) β the number of tricks and the number of cards in Wojtek's deck.
Each of the following n lines describes a single trick and is described by k distinct integers P_{i,1}, P_{i,2}, ..., P_{i, k} (1 β€ P_{i, j} β€ k).
Output
Output the value of the sum described in the statement.
Examples
Input
3 3
2 1 3
3 1 2
1 3 2
Output
25
Input
2 4
4 1 3 2
4 3 1 2
Output
31
Note
Consider the first sample:
* The first trick swaps two top cards.
* The second trick takes a card from the bottom and puts it on the top of the deck.
* The third trick swaps two bottom cards.
The first or the third trick allow Wojtek to generate only two distinct decks (either the two cards are swapped or not). Therefore, f(1, 1) = f(3, 3) = 2.
The second trick allows him to shuffle the deck in a cyclic order. Therefore, f(2,2)=3.
It turns that two first tricks or two last tricks are enough to shuffle the deck in any way desired by Wojtek. Therefore, f(1,2) = f(2,3) = f(1,3) = 3! = 6.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int P = 1e9 + 7;
int n, k, f[120][120], g[120][6], h[6][6][6][6][6];
vector<pair<pair<bitset<120>, int>, vector<int>>> V[2];
bitset<120> zr, b;
vector<int> t;
void dfs(int id) {
for (auto x : t)
if (!b[f[id][x]]) {
b[f[id][x]] = 1;
dfs(f[id][x]);
}
}
bitset<120> sol(vector<int> v, int g) {
v.push_back(g);
t = v;
b = zr;
dfs(0);
return b;
}
int main() {
scanf("%d%d", &n, &k);
zr[0] = 1;
long long ans = 0;
int p[6] = {0, 1, 2, 3, 4, 5};
for (int i = 0; i < 120; i++) {
for (int j = 1; j <= 5; j++) g[i][j] = p[j];
h[p[1]][p[2]][p[3]][p[4]][p[5]] = i;
next_permutation(p + 1, p + 6);
}
for (int i = 0; i < 120; i++)
for (int j = 0; j < 120; j++)
f[i][j] = h[g[j][g[i][1]]][g[j][g[i][2]]][g[j][g[i][3]]][g[j][g[i][4]]]
[g[j][g[i][5]]];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= k; j++) scanf("%d", &p[j]);
for (int j = k + 1; j <= 5; j++) p[j] = j;
int id = h[p[1]][p[2]][p[3]][p[4]][p[5]], nw = i & 1, pr = nw ^ 1;
vector<int> ff;
V[pr].push_back({{zr, 1}, ff});
V[nw].clear();
for (auto t : V[pr]) {
bitset<120> x = sol(t.second, id);
if (x != t.first.first) t.first.first = x, t.second.push_back(id);
if (!V[nw].empty() && V[nw].back().first.first == x)
V[nw].back().first.second += t.first.second;
else
V[nw].push_back(t);
}
for (auto t : V[nw]) ans += t.first.first.count() * t.first.second;
}
printf("%lld\n", ans);
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Dr. Jimbo, an applied mathematician, needs to calculate matrices all day for solving his own problems. In his laboratory, he uses an excellent application program for manipulating matrix expressions, however, he cannot use it outside his laboratory because the software consumes much of resources. He wants to manipulate matrices outside, so he needs a small program similar to the excellent application for his handheld computer.
Your job is to provide him a program that computes expressions of matrices.
Expressions of matrices are described in a simple language. Its syntax is shown in Table J.1. Note that even a space and a newline have meaningful roles in the syntax.
<image>
The start symbol of this syntax is program that is defined as a sequence of assignments in Table J.1. Each assignment has a variable on the left hand side of an equal symbol ("=") and an expression of matrices on the right hand side followed by a period and a newline (NL). It denotes an assignment of the value of the expression to the variable. The variable (var in Table J.1) is indicated by an uppercase Roman letter. The value of the expression (expr) is a matrix or a scalar, whose elements are integers. Here, a scalar integer and a 1 Γ 1 matrix whose only element is the same integer can be used interchangeably.
An expression is one or more terms connected by "+" or "-" symbols. A term is one or more factors connected by "*" symbol. These operators ("+", "-", "*") are left associative.
A factor is either a primary expression (primary) or a "-" symbol followed by a factor. This unary operator "-" is right associative.
The meaning of operators are the same as those in the ordinary arithmetic on matrices: Denoting matrices by A and B, A + B, A - B, A * B, and -A are defined as the matrix sum, difference, product, and negation. The sizes of A and B should be the same for addition and subtraction. The number of columns of A and the number of rows of B should be the same for multiplication.
Note that all the operators +, -, * and unary - represent computations of addition, subtraction, multiplication and negation modulo M = 215 = 32768, respectively. Thus all the values are nonnegative integers between 0 and 32767, inclusive. For example, the result of an expression 2 - 3 should be 32767, instead of -1.
inum is a non-negative decimal integer less than M.
var represents the matrix that is assigned to the variable var in the most recent preceding assignment statement of the same variable.
matrix represents a mathematical matrix similar to a 2-dimensional array whose elements are integers. It is denoted by a row-seq with a pair of enclosing square brackets. row-seq represents a sequence of rows, adjacent two of which are separated by a semicolon. row represents a sequence of expressions, adjacent two of which are separated by a space character.
For example, [1 2 3;4 5 6] represents a matrix <image>. The first row has three integers separated by two space characters, i.e. "1 2 3". The second row has three integers, i.e. "4 5 6". Here, the row-seq consists of the two rows separated by a semicolon. The matrix is denoted by the row-seq with a pair of square brackets.
Note that elements of a row may be matrices again. Thus the nested representation of a matrix may appear. The number of rows of the value of each expression of a row should be the same, and the number of columns of the value of each row of a row-seq should be the same.
For example, a matrix represented by
[[1 2 3;4 5 6] [7 8;9 10] [11;12];13 14 15 16 17 18]
is <image> The sizes of matrices should be consistent, as mentioned above, in order to form a well-formed matrix as the result. For example, [[1 2;3 4] [5;6;7];6 7 8] is not consistent since the first row "[1 2;3 4] [5;6;7]" has two matrices (2 Γ 2 and 3 Γ 1) whose numbers of rows are different. [1 2;3 4 5] is not consistent since the number of columns of two rows are different.
The multiplication of 1 Γ 1 matrix and m Γ n matrix is well-defined for arbitrary m > 0 and n > 0, since a 1 Γ 1 matrices can be regarded as a scalar integer. For example, 2*[1 2;3 4] and [1 2;3 4]*3 represent the products of a scalar and a matrix <image> and <image>. [2]*[1 2;3 4] and [1 2;3 4]*[3] are also well-defined similarly.
An indexed-primary is a primary expression followed by two expressions as indices. The first index is 1 Γ k integer matrix denoted by (i1 i2 ... ik), and the second index is 1 Γ l integer matrix denoted by (j1 j2 ... jl). The two indices specify the submatrix extracted from the matrix which is the value of the preceding primary expression. The size of the submatrix is k Γ l and whose (a, b)-element is the (ia, jb)-element of the value of the preceding primary expression. The way of indexing is one-origin, i.e., the first element is indexed by 1.
For example, the value of ([1 2;3 4]+[3 0;0 2])([1],[2]) is equal to 2, since the value of its primary expression is a matrix [4 2;3 6], and the first index [1] and the second [2] indicate the (1, 2)-element of the matrix. The same integer may appear twice or more in an index matrix, e.g., the first index matrix of an expression [1 2;3 4]([2 1 1],[2 1]) is [2 1 1], which has two 1's. Its value is <image>.
A transposed-primary is a primary expression followed by a single quote symbol ("'"), which indicates the transpose operation. The transposed matrix of an m Γ n matrix A = (aij) (i = 1, ..., m and j = 1, ... , n) is the n Γ m matrix B = (bij) (i = 1, ... , n and j = 1, ... , m), where bij = aji. For example, the value of [1 2;3 4]' is <image>.
Input
The input consists of multiple datasets, followed by a line containing a zero. Each dataset has the following format.
n
program
n is a positive integer, which is followed by a program that is a sequence of single or multiple lines each of which is an assignment statement whose syntax is defined in Table J.1. n indicates the number of the assignment statements in the program. All the values of vars are undefined at the beginning of a program.
You can assume the following:
* 1 β€ n β€ 10,
* the number of characters in a line does not exceed 80 (excluding a newline),
* there are no syntax errors and semantic errors (e.g., reference of undefined var),
* the number of rows of matrices appearing in the computations does not exceed 100, and
* the number of columns of matrices appearing in the computations does not exceed 100.
Output
For each dataset, the value of the expression of each assignment statement of the program should be printed in the same order. All the values should be printed as non-negative integers less than M.
When the value is an m Γ n matrix A = (aij) (i = 1, ... ,m and j = 1, ... , n), m lines should be printed. In the k-th line (1 β€ k β€ m), integers of the k-th row, i.e., ak1, ... , akn, should be printed separated by a space.
After the last value of a dataset is printed, a line containing five minus symbols '-----' should be printed for human readability.
The output should not contain any other extra characters.
Example
Input
1
A=[1 2 3;4 5 6].
1
A=[[1 2 3;4 5 6] [7 8;9 10] [11;12];13 14 15 16 17 18].
3
B=[3 -2 1;-9 8 7].
C=([1 2 3;4 5 6]+B)(2,3).
D=([1 2 3;4 5 6]+B)([1 2],[2 3]).
5
A=2*[1 2;-3 4]'.
B=A([2 1 2],[2 1]).
A=[1 2;3 4]*3.
A=[2]*[1 2;3 4].
A=[1 2;3 4]*[3].
2
A=[11 12 13;0 22 23;0 0 33].
A=[A A';--A''' A].
2
A=[1 -1 1;1 1 -1;-1 1 1]*3.
A=[A -A+-A;-A'([3 2 1],[3 2 1]) -A'].
1
A=1([1 1 1],[1 1 1 1]).
3
A=[1 2 -3;4 -5 6;-7 8 9].
B=A([3 1 2],[2 1 3]).
C=A*B-B*A+-A*-B-B*-A.
3
A=[1 2 3 4 5].
B=A'*A.
C=B([1 5],[5 1]).
3
A=[-11 12 13;21 -22 23;31 32 -33].
B=[1 0 0;0 1 0;0 0 1].
C=[(A-B) (A+B)*B (A+B)*(B-A)([1 1 1],[3 2 1]) [1 2 3;2 1 1;-1 2 1]*(A-B)].
3
A=[11 12 13;0 22 23;0 0 33].
B=[1 2].
C=------A((((B))),B)(B,B)''''''.
2
A=1+[2]+[[3]]+[[[4]]]+2*[[[[5]]]]*3.
B=[(-[([(-A)]+-A)])].
8
A=[1 2;3 4].
B=[A A+[1 1;0 1]*4;A+[1 1;0 1]'*8 A+[1 1;0 1]''*12].
C=B([1],[1]).
C=B([1],[1 2 3 4]).
C=B([1 2 3 4],[1]).
C=B([2 3],[2 3]).
A=[1 2;1 2].
D=(A*-A+-A)'(A'(1,[1 2]),A'(2,[1 2])).
0
Output
1 2 3
4 5 6
-----
1 2 3 7 8 11
4 5 6 9 10 12
13 14 15 16 17 18
-----
3 32766 1
32759 8 7
13
0 4
13 13
-----
2 32762
4 8
8 4
32762 2
8 4
3 6
9 12
2 4
6 8
3 6
9 12
-----
11 12 13
0 22 23
0 0 33
11 12 13 11 0 0
0 22 23 12 22 0
0 0 33 13 23 33
11 0 0 11 12 13
12 22 0 0 22 23
13 23 33 0 0 33
-----
3 32765 3
3 3 32765
32765 3 3
3 32765 3 32762 6 32762
3 3 32765 32762 32762 6
32765 3 3 6 32762 32762
32765 3 32765 32765 32765 3
32765 32765 3 3 32765 32765
3 32765 32765 32765 3 32765
-----
1 1 1 1
1 1 1 1
1 1 1 1
-----
1 2 32765
4 32763 6
32761 8 9
8 32761 9
2 1 32765
32763 4 6
54 32734 32738
32752 32750 174
32598 186 32702
-----
1 2 3 4 5
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
5 1
25 5
-----
32757 12 13
21 32746 23
31 32 32735
1 0 0
0 1 0
0 0 1
32756 12 13 32758 12 13 32573 32588 180 123 62 32725
21 32745 23 21 32747 23 32469 32492 276 28 33 15
31 32 32734 31 32 32736 32365 32396 372 85 32742 32767
-----
11 12 13
0 22 23
0 0 33
1 2
11 12
0 22
-----
40
80
-----
1 2
3 4
1 2 5 6
3 4 3 8
9 2 13 14
11 12 3 16
1
1 2 5 6
1
3
9
11
4 3
2 13
1 2
1 2
32764 32764
32764 32764
-----
### Response
```cpp
#include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 99999999999999999
//#define MOD 1000000007
#define EPS 0.000000001
using namespace std;
#define MOD 32768
typedef vector<int> V;
typedef vector<V> MATRIX;
int N;
int global_index;
char buf[105];
MATRIX TABLE[26];
MATRIX expr();
MATRIX operator+(const MATRIX &A,const MATRIX &B){
int num_row = A.size();
int num_col = A[0].size();
MATRIX RET(num_row,V(num_col));
for(int row = 0; row < num_row; row++){
for(int col = 0; col < num_col; col++){
RET[row][col] = A[row][col]+B[row][col];
RET[row][col] %= MOD;
}
}
return RET;
}
MATRIX operator-(const MATRIX &A,const MATRIX &B){
int num_row = A.size();
int num_col = A[0].size();
MATRIX RET(num_row,V(num_col));
for(int row = 0; row < num_row; row++){
for(int col = 0; col < num_col; col++){
RET[row][col] = A[row][col]-B[row][col];
RET[row][col] = (RET[row][col]+MOD)%MOD;
}
}
return RET;
}
MATRIX operator*(const MATRIX &A, const MATRIX &B){
int num_rowA = A.size();
int num_colA = A[0].size();
int num_rowB = B.size();
int num_colB = B[0].size();
if(num_rowA == 1 && num_colA == 1){ //AγγΉγ«γ©γΌ
MATRIX RET(num_rowB,V(num_colB));
for(int row = 0; row < num_rowB; row++){
for(int col = 0; col < num_colB; col++){
RET[row][col] = B[row][col]*A[0][0];
RET[row][col] %= MOD;
}
}
return RET;
}else if(num_rowB == 1 && num_colB == 1){ //BγγΉγ«γ©γΌ
MATRIX RET(num_rowA,V(num_colA));
for(int row = 0; row < num_rowA; row++){
for(int col = 0; col < num_colA; col++){
RET[row][col] = A[row][col]*B[0][0];
RET[row][col] %= MOD;
}
}
return RET;
}else{
MATRIX RET(num_rowA,V(num_colB));
for(int row = 0; row < num_rowA; row++){
for(int col = 0; col < num_colB; col++){
RET[row][col] = 0;
for(int a = 0; a < num_colA; a++){
RET[row][col] += A[row][a]*B[a][col];
RET[row][col] %= MOD;
}
}
}
return RET;
}
}
MATRIX operator-(const MATRIX &A){
int num_rowA = A.size();
int num_colA = A[0].size();
MATRIX RET(num_rowA,V(num_colA));
for(int row = 0; row < num_rowA; row++){
for(int col = 0; col < num_colA; col++){
RET[row][col] = (-A[row][col]+MOD)%MOD;
}
}
return RET;
}
MATRIX transpose(MATRIX A){
int num_row = A[0].size();
int num_col = A.size();
MATRIX RET(num_row,V(num_col));
for(int row = 0; row < A.size(); row++){
for(int col = 0; col < A[0].size(); col++){
RET[col][row] = A[row][col];
}
}
return RET;
}
MATRIX get_row(){
MATRIX A = expr();
while(buf[global_index] == ' '){
global_index++;
MATRIX B = expr();
for(int a = 0; a < A.size(); a++){
A[a].insert(A[a].end(),B[a].begin(),B[a].end());
}
}
return A;
}
MATRIX row_seq(){
MATRIX A = get_row();
while(buf[global_index] == ';'){
global_index++;
MATRIX B = get_row();
A.insert(A.end(),B.begin(),B.end());
}
return A;
}
MATRIX matrix(){
global_index++;
MATRIX A = row_seq();
global_index++;
return A;
}
MATRIX get_var(){
MATRIX RET = TABLE[buf[global_index]-'A'];
global_index++;
return RET;
}
MATRIX inum(){
int tmp = 0;
while(buf[global_index] >= '0' && buf[global_index] <= '9'){
tmp = 10*tmp+(buf[global_index]-'0');
tmp %= MOD;
global_index++;
}
MATRIX RET(1,V(1));
RET[0][0] = tmp;
return RET;
}
MATRIX primary(){
MATRIX A;
if(buf[global_index] >= '0' && buf[global_index] <= '9'){
A = inum();
}else if(buf[global_index] >= 'A' && buf[global_index] <= 'Z'){
A = get_var();
}else if(buf[global_index] == '['){
A = matrix();
}else if(buf[global_index] == '('){
global_index++;
A = expr();
global_index++;
}
bool FLG;
while(true){
FLG = false;
if(buf[global_index] == '('){
FLG = true;
global_index++;
MATRIX B = expr();
global_index++;
MATRIX C = expr();
global_index++;
int num_row = B[0].size();
int num_col = C[0].size();
MATRIX TMP(num_row,V(num_col));
for(int row = 0; row < num_row; row++){
for(int col = 0; col < num_col; col++){
TMP[row][col] = A[B[0][row]-1][C[0][col]-1];
}
}
A = TMP;
}else if(buf[global_index] == '\''){
FLG = true;
global_index++;
A = transpose(A);
}
if(!FLG)break;
}
return A;
}
MATRIX factor(){
if(buf[global_index] == '-'){
global_index++;
return -factor();
}else{
return primary();
}
}
MATRIX term(){
MATRIX A = factor();
while(buf[global_index] == '*'){
global_index++;
A = A*factor();
}
return A;
}
MATRIX expr(){
MATRIX A = term();
char op;
while(buf[global_index] == '+' || buf[global_index] == '-'){
op = buf[global_index++];
if(op == '+'){
A = A+term();
}else{
A = A-term();
}
}
return A;
}
void assignment(){
int type = buf[0]-'A';
global_index = 2;
TABLE[type] = expr();
global_index++;
}
void func(){
getchar();
for(int loop = 0; loop < N; loop++){
fgets(buf,100,stdin);
assignment();
MATRIX A = TABLE[buf[0]-'A'];
int num_row = A.size();
int num_col = A[0].size();
for(int row = 0; row < num_row; row++){
printf("%d",A[row][0]);
for(int col = 1; col < num_col; col++){
printf(" %d",A[row][col]);
}
printf("\n");
}
}
printf("-----\n");
}
int main(){
while(true){
scanf("%d",&N);
if(N == 0)break;
func();
}
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
All modern mobile applications are divided into free and paid. Even a single application developers often release two versions: a paid version without ads and a free version with ads.
<image>
Suppose that a paid version of the app costs p (p is an integer) rubles, and the free version of the application contains c ad banners. Each user can be described by two integers: ai β the number of rubles this user is willing to pay for the paid version of the application, and bi β the number of banners he is willing to tolerate in the free version.
The behavior of each member shall be considered strictly deterministic:
* if for user i, value bi is at least c, then he uses the free version,
* otherwise, if value ai is at least p, then he buys the paid version without advertising,
* otherwise the user simply does not use the application.
Each user of the free version brings the profit of c Γ w rubles. Each user of the paid version brings the profit of p rubles.
Your task is to help the application developers to select the optimal parameters p and c. Namely, knowing all the characteristics of users, for each value of c from 0 to (max bi) + 1 you need to determine the maximum profit from the application and the corresponding parameter p.
Input
The first line contains two integers n and w (1 β€ n β€ 105; 1 β€ w β€ 105) β the number of users and the profit from a single banner. Each of the next n lines contains two integers ai and bi (0 β€ ai, bi β€ 105) β the characteristics of the i-th user.
Output
Print (max bi) + 2 lines, in the i-th line print two integers: pay β the maximum gained profit at c = i - 1, p (0 β€ p β€ 109) β the corresponding optimal app cost. If there are multiple optimal solutions, print any of them.
Examples
Input
2 1
2 0
0 2
Output
0 3
3 2
4 2
2 2
Input
3 1
3 1
2 2
1 3
Output
0 4
3 4
7 3
7 2
4 2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int inf = 0x7fffffff;
const double eps = 1e-10;
const double pi = acos(-1.0);
const int N = 1e5 + 10;
void read(int &x) {
int f = 1;
x = 0;
char ch;
ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = x * 10 + ch - '0';
ch = getchar();
}
x *= f;
}
int n, w, Maxb, Maxa, bel[N], nn, tim[350], q[350][350], qh[350], qt[350];
long long d[N];
struct node {
int a, b;
} l[N];
double cmp(node a, node b) { return a.b != b.b ? a.b < b.b : a.a > b.a; }
double slope(int i, int j) { return (d[i] - d[j]) * 1.0 / (j - i); }
void add(int x) {
if (!x) return;
for (int i = 1; i < bel[x]; ++i) {
tim[i]++;
while (qh[i] < qt[i] && slope(q[i][qh[i]], q[i][qh[i] + 1]) <= tim[i])
++qh[i];
}
int l = (bel[x] - 1) * nn + 1, r = min(bel[x] * nn, Maxa), id = bel[x];
for (int i = l; i <= r; ++i) d[i] += (long long)tim[id] * i;
for (int i = l; i <= x; ++i) d[i] += i;
tim[id] = 0;
qh[id] = 1;
qt[id] = 0;
for (int i = l; i <= r; ++i) {
while (qh[id] < qt[id] &&
slope(q[id][qt[id]], i) < slope(q[id][qt[id] - 1], q[id][qt[id]]))
--qt[id];
q[id][++qt[id]] = i;
}
while (qh[id] < qt[id] && slope(q[id][qh[id]], q[id][qh[id] + 1]) <= 0)
++qh[id];
}
int main() {
read(n);
read(w);
for (int i = 1; i <= n; i++)
read(l[i].a), Maxa = max(Maxa, l[i].a), read(l[i].b),
Maxb = max(Maxb, l[i].b);
sort(l + 1, l + n + 1, cmp);
int now = 1;
nn = sqrt(Maxa);
for (int i = 1; i <= Maxa; i++) bel[i] = (i - 1) / nn + 1;
int tot = bel[Maxa];
for (int i = 1; i <= tot; i++) qh[i] = 1, q[i][++qt[i]] = min(i * nn, Maxa);
for (int c = 0; c <= Maxb + 1; c++) {
while (now <= n && l[now].b < c) add(l[now].a), ++now;
long long ans = 0;
int ans1 = 0;
for (int i = 1; i <= tot; ++i) {
int x = q[i][qh[i]];
if (d[x] + (long long)x * tim[i] > ans)
ans = d[x] + (long long)x * tim[i], ans1 = x;
}
printf("%lld %d\n", ans + (long long)w * c * (n - now + 1), ans1);
}
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Some company is going to hold a fair in Byteland. There are n towns in Byteland and m two-way roads between towns. Of course, you can reach any town from any other town using roads.
There are k types of goods produced in Byteland and every town produces only one type. To hold a fair you have to bring at least s different types of goods. It costs d(u,v) coins to bring goods from town u to town v where d(u,v) is the length of the shortest path from u to v. Length of a path is the number of roads in this path.
The organizers will cover all travel expenses but they can choose the towns to bring goods from. Now they want to calculate minimum expenses to hold a fair in each of n towns.
Input
There are 4 integers n, m, k, s in the first line of input (1 β€ n β€ 10^{5}, 0 β€ m β€ 10^{5}, 1 β€ s β€ k β€ min(n, 100)) β the number of towns, the number of roads, the number of different types of goods, the number of different types of goods necessary to hold a fair.
In the next line there are n integers a_1, a_2, β¦, a_n (1 β€ a_{i} β€ k), where a_i is the type of goods produced in the i-th town. It is guaranteed that all integers between 1 and k occur at least once among integers a_{i}.
In the next m lines roads are described. Each road is described by two integers u v (1 β€ u, v β€ n, u β v) β the towns connected by this road. It is guaranteed that there is no more than one road between every two towns. It is guaranteed that you can go from any town to any other town via roads.
Output
Print n numbers, the i-th of them is the minimum number of coins you need to spend on travel expenses to hold a fair in town i. Separate numbers with spaces.
Examples
Input
5 5 4 3
1 2 4 3 2
1 2
2 3
3 4
4 1
4 5
Output
2 2 2 2 3
Input
7 6 3 2
1 2 3 3 2 2 1
1 2
2 3
3 4
2 5
5 6
6 7
Output
1 1 1 2 2 1 1
Note
Let's look at the first sample.
To hold a fair in town 1 you can bring goods from towns 1 (0 coins), 2 (1 coin) and 4 (1 coin). Total numbers of coins is 2.
Town 2: Goods from towns 2 (0), 1 (1), 3 (1). Sum equals 2.
Town 3: Goods from towns 3 (0), 2 (1), 4 (1). Sum equals 2.
Town 4: Goods from towns 4 (0), 1 (1), 5 (1). Sum equals 2.
Town 5: Goods from towns 5 (0), 4 (1), 3 (2). Sum equals 3.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m, K, S, tot, x, y, k[100100], h[101][100100], dis[100100][101],
ans[100100], head[100100], vis[100100];
struct Node {
int y, nxt;
} side[200100];
void add(int x, int y) {
tot++;
side[tot].y = y;
side[tot].nxt = head[x];
head[x] = tot;
}
void BFS(int t) {
queue<int> q;
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= h[t][0]; i++)
q.push(h[t][i]), dis[h[t][i]][t] = 0, vis[h[t][i]] = 1;
while (!q.empty()) {
int x = q.front();
q.pop();
vis[x] = 0;
for (int i = head[x]; i; i = side[i].nxt) {
int y = side[i].y;
if (dis[y][t] > dis[x][t] + 1) {
dis[y][t] = dis[x][t] + 1;
if (!vis[y]) q.push(y), vis[y] = 1;
}
}
}
}
int main() {
cin >> n >> m >> K >> S;
for (int i = 1; i <= n; i++) cin >> k[i], h[k[i]][++h[k[i]][0]] = i;
for (int i = 1; i <= m; i++) cin >> x >> y, add(x, y), add(y, x);
memset(dis, 0x3f, sizeof(dis));
for (int i = 1; i <= K; i++) BFS(i);
for (int i = 1; i <= n; i++) {
sort(dis[i] + 1, dis[i] + 1 + K);
for (int j = 1; j <= S; j++) ans[i] += dis[i][j];
}
for (int i = 1; i <= n; i++) cout << ans[i] << " ";
}
``` |
### Prompt
Create a solution in cpp for the following problem:
The 7 puzzle consists of 8 square cards and a frame that fits them snugly. Each card is numbered 0, 1, 2, ..., 7 to distinguish them from each other. You can arrange two cards vertically and four cards horizontally in the frame.
7 When you start the puzzle, first put all the cards in the frame. Only 0 cards in the frame can be swapped with adjacent cards on the top, bottom, left, and right. For example, when the frame state is shown in Figure (a), if you exchange the position with the 7 card adjacent to the right of the 0 card, you will get the state shown in Figure (b). Alternatively, the state shown in Fig. (A) can be changed to the state shown in Fig. (C) by exchanging the position with the adjacent 2 card under the 0 card. In the state shown in Fig. (A), the cards with 0 and the cards adjacent to the top, bottom, left, and right are only the cards 7 and 2, so other positions cannot be swapped.
The purpose of the game is to arrange the cards neatly so that they are in the state shown in Figure (d). Create a program that takes the initial state as input and outputs the minimum number of steps required to align the cards neatly. However, it is possible to move from the state of the entered card to the state shown in Fig. (D).
The input data is given eight numbers per line, separated by blanks. These represent the initial sequence of cards. For example, the number representation in Figure (a) is 0 7 3 4 2 5 1 6 and Figure (c) is 2 7 3 4 0 5 1 6.
<image> | <image>
--- | ---
Figure (a) 0 7 3 4 2 5 1 6 | Figure (b) 7 0 3 4 2 5 1 6
<image> | <image>
--- | ---
Figure (c) 2 7 3 4 0 5 1 6 | Figure (d) 0 1 2 3 4 5 6 7 (final state)
Input
Multiple puzzles are given in the above format. Please process until the end of the input. No more than 1,000 puzzles will be given.
Output
For each puzzle, output the minimum number of steps to move to the final state on one line.
Example
Input
0 1 2 3 4 5 6 7
1 0 2 3 4 5 6 7
7 6 5 4 3 2 1 0
Output
0
1
28
### Response
```cpp
#include <iostream>
#include <set>
#include <queue>
#define SWAP(A,B,C) ((C)=(A),(A)=(B),(B)=(C))
using namespace std;
class State{
public:
int p[2][4];
int cost;
int zx, zy;
bool operator < (const State &s) const {
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 4; j++) {
if(p[i][j] != s.p[i][j]) return p[i][j] < s.p[i][j];
}
}
return false;
}
};
int dx[] = {0,1,0,-1},dy[] = {-1,0,1,0};
int main()
{
State a;
for(int i = 0;i<2;i++)
for(int j = 0;j<4;j++)
a.p[i][j] = i*4+j;
a.cost = 0;a.zx=0;a.zy=0;
set<State> data;data.insert(a);
queue<State> q;q.push(a);
while(!q.empty())
{
State b = q.front();q.pop();
for(int i = 0;i<4;i++)
{
State tb = b;
int nx = tb.zx + dx[i];
int ny = tb.zy + dy[i];
if(nx<0||nx>=4||ny<0||ny>=2)continue;
tb.cost++;
int temp;
SWAP(tb.p[b.zy][b.zx],tb.p[ny][nx],temp);
tb.zy = ny;tb.zx = nx;
if(data.find(tb)!=data.end())continue;
data.insert(tb);
q.push(tb);
}
}
State input;
while(cin >> input.p[0][0]) {
for(int i = 1; i < 8; i++) {
cin >> input.p[i/4][i%4];
}
cout << data.find(input)->cost << endl;
}
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Let's solve the puzzle by programming.
The numbers n x n are arranged in a grid pattern. Some of the numbers are circled and we will call them the starting point. The rules of the puzzle are as follows:
* Draw one line that goes vertically and horizontally from each starting point (cannot be drawn diagonally).
* Extend the line so that the sum of the numbers passed is the same as the starting number.
* The line must not be branched.
* Lines cannot pass through numbers already drawn (lines must not intersect).
* A line cannot pass through more than one origin.
As shown in the figure below, the goal of the puzzle is to use all the starting points and draw lines on all the numbers.
<image>
Your job is to create a puzzle-solving program. However, in this problem, it is only necessary to determine whether the given puzzle can be solved.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
n x n numbers
Indicates a puzzle given a number of n x n, the starting number is given as a negative number.
When n is 0, it indicates the end of input.
It can be assumed that n is 3 or more and 8 or less, numbers other than the starting point are 1 or more and 50 or less, and the starting point is -50 or more and -1 or less. You may also assume the following as the nature of the puzzle being entered:
* Each row and column of a given puzzle has at least one starting point.
* The number of starting points is about 20% to 40% of the total number of numbers (n x n).
Output
For each dataset, print "YES" if the puzzle can be solved, otherwise "NO" on one line.
Example
Input
3
-3 1 1
2 -4 1
2 1 -1
3
-4 1 1
1 1 -6
1 -5 3
4
-8 6 -2 1
2 -7 -2 1
1 -1 1 1
1 1 1 -5
6
2 2 3 -7 3 2
1 -10 1 1 3 2
2 6 5 2 -6 1
3 4 -23 2 2 5
3 3 -6 2 3 7
-7 2 3 2 -5 -13
6
2 2 3 -7 3 2
1 -10 1 1 3 2
2 6 5 2 -6 1
3 4 -23 2 2 5
3 3 -6 2 3 7
-7 2 3 2 -5 -12
0
Output
YES
NO
NO
YES
NO
### Response
```cpp
#include<iostream>
#include<vector>
#include<tuple>
using namespace std;
struct State { int x[8][8]; };
int dx[4] = { -1,0,1,0 }, dy[4] = { 0,1,0,-1 };
int F[8][8], n; vector<tuple<int,int,int>>vec;
int solve(State S, int pos, int rec, int px, int py, int cnts) {
if (pos == vec.size() - 1 && cnts == n*n) { return 1; }
int cnt = 0;
for (int i = 0; i < 4; i++) {
int cx = px + dx[i], cy = py + dy[i];
if (cx < 0 || cy < 0 || cx >= n || cy >= n || S.x[cx][cy] == 1)continue;
if (F[cx][cy] + rec > get<2>(vec[pos]))continue;
State T = S; T.x[cx][cy] = 1;
if (F[cx][cy] + rec == get<2>(vec[pos])) {
cnt += solve(T, pos + 1, 0, get<0>(vec[pos + 1]), get<1>(vec[pos + 1]), cnts + 1);
}
else {
cnt += solve(T, pos, rec + F[cx][cy], cx, cy, cnts + 1);
}
}
return cnt;
}
int main() {
while (true) {
cin >> n; if (n == 0)break; vec.clear();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> F[i][j];
if (F[i][j] < 0)vec.push_back(make_tuple(i, j, -F[i][j]));
}
}
State ST; vec.push_back(make_tuple(-1, -1, -1));
for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { ST.x[i][j] = 0; if (F[i][j] < 0)ST.x[i][j] = 1; } }
int sum = solve(ST, 0, 0, get<0>(vec[0]), get<1>(vec[0]), vec.size() - 1);
if (sum >= 1)cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
You are given two arrays a_1, a_2, ... , a_n and b_1, b_2, ... , b_m. Array b is sorted in ascending order (b_i < b_{i + 1} for each i from 1 to m - 1).
You have to divide the array a into m consecutive subarrays so that, for each i from 1 to m, the minimum on the i-th subarray is equal to b_i. Note that each element belongs to exactly one subarray, and they are formed in such a way: the first several elements of a compose the first subarray, the next several elements of a compose the second subarray, and so on.
For example, if a = [12, 10, 20, 20, 25, 30] and b = [10, 20, 30] then there are two good partitions of array a:
1. [12, 10, 20], [20, 25], [30];
2. [12, 10], [20, 20, 25], [30].
You have to calculate the number of ways to divide the array a. Since the number can be pretty large print it modulo 998244353.
Input
The first line contains two integers n and m (1 β€ n, m β€ 2 β
10^5) β the length of arrays a and b respectively.
The second line contains n integers a_1, a_2, ... , a_n (1 β€ a_i β€ 10^9) β the array a.
The third line contains m integers b_1, b_2, ... , b_m (1 β€ b_i β€ 10^9; b_i < b_{i+1}) β the array b.
Output
In only line print one integer β the number of ways to divide the array a modulo 998244353.
Examples
Input
6 3
12 10 20 20 25 30
10 20 30
Output
2
Input
4 2
1 3 3 7
3 7
Output
0
Input
8 2
1 2 2 2 2 2 2 2
1 2
Output
7
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long mod = 998244353;
int main() {
long long n, m, i, j, cnt, flg, ans, chk, ini, fin;
cin >> n >> m;
long long a[n];
for (i = 0; i < n; i++) {
cin >> a[i];
}
chk = 0;
flg = 0;
long long b[m];
long long fpos[m];
long long ipos[m];
for (i = 0; i < m; i++) {
cin >> b[i];
fpos[i] = -1;
ipos[i] = -1;
}
j = m - 1;
for (i = n - 1; i > -1 && j > -1; i--) {
if (a[i] == b[j]) {
if (ipos[j] == -1) ipos[j] = i;
} else if (a[i] < b[j]) {
if (ipos[j] == -1) {
flg = 1;
break;
}
if (j == 0) {
flg = 1;
break;
}
fpos[j] = i + 1;
i++;
j--;
if (j < 0) break;
}
}
for (i = 0; i < m; i++) {
if (ipos[i] == -1) {
flg = 1;
break;
}
}
fpos[0] = ipos[0];
ans = 1;
j = 0;
i = 0;
for (i = 0; i < m; i++) {
ans = ((ans % mod) * ((ipos[i] - fpos[i] + 1) % mod)) % mod;
}
if (flg) {
cout << 0;
} else {
cout << ans % mod;
}
cout << "\n";
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Given is an integer N.
Takahashi chooses an integer a from the positive integers not greater than N with equal probability.
Find the probability that a is odd.
Constraints
* 1 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the probability that a is odd. Your output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-6}.
Examples
Input
4
Output
0.5000000000
Input
5
Output
0.6000000000
Input
1
Output
1.0000000000
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main()
{
double n;
cin >> n;
cout << (int(n+1)/2/n) << endl;
return 0;
}
``` |
Subsets and Splits