text
stringlengths 424
69.5k
|
---|
### Prompt
Develop a solution in cpp to the problem described below:
Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples.
For example, triples (3, 4, 5), (5, 12, 13) and (6, 8, 10) are Pythagorean triples.
Here Katya wondered if she can specify the length of some side of right triangle and find any Pythagorean triple corresponding to such length? Note that the side which length is specified can be a cathetus as well as hypotenuse.
Katya had no problems with completing this task. Will you do the same?
Input
The only line of the input contains single integer n (1 β€ n β€ 109) β the length of some side of a right triangle.
Output
Print two integers m and k (1 β€ m, k β€ 1018), such that n, m and k form a Pythagorean triple, in the only line.
In case if there is no any Pythagorean triple containing integer n, print - 1 in the only line. If there are many answers, print any of them.
Examples
Input
3
Output
4 5
Input
6
Output
8 10
Input
1
Output
-1
Input
17
Output
144 145
Input
67
Output
2244 2245
Note
<image>
Illustration for the first sample.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long int n;
cin >> n;
long long int N = n;
if (n == 1 || n == 2)
cout << -1 << endl;
else {
if (n % 2 != 0)
cout << (n * n) / 2 << ' ' << ((n * n) / 2) + 1 << endl;
else {
long long int t = 1;
while (n % 2 == 0) {
n /= 2;
t *= 2;
}
if (n != 1)
cout << t * ((n * n) / 2) << ' ' << (((n * n) / 2) + 1) * t << endl;
else {
cout << 3 * (N / 4) << ' ' << 5 * (N / 4) << endl;
}
}
}
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
You've got a undirected tree s, consisting of n nodes. Your task is to build an optimal T-decomposition for it. Let's define a T-decomposition as follows.
Let's denote the set of all nodes s as v. Let's consider an undirected tree t, whose nodes are some non-empty subsets of v, we'll call them xi <image>. The tree t is a T-decomposition of s, if the following conditions holds:
1. the union of all xi equals v;
2. for any edge (a, b) of tree s exists the tree node t, containing both a and b;
3. if the nodes of the tree t xi and xj contain the node a of the tree s, then all nodes of the tree t, lying on the path from xi to xj also contain node a. So this condition is equivalent to the following: all nodes of the tree t, that contain node a of the tree s, form a connected subtree of tree t.
There are obviously many distinct trees t, that are T-decompositions of the tree s. For example, a T-decomposition is a tree that consists of a single node, equal to set v.
Let's define the cardinality of node xi as the number of nodes in tree s, containing in the node. Let's choose the node with the maximum cardinality in t. Let's assume that its cardinality equals w. Then the weight of T-decomposition t is value w. The optimal T-decomposition is the one with the minimum weight.
Your task is to find the optimal T-decomposition of the given tree s that has the minimum number of nodes.
Input
The first line contains a single integer n (2 β€ n β€ 105), that denotes the number of nodes in tree s.
Each of the following n - 1 lines contains two space-separated integers ai, bi (1 β€ ai, bi β€ n; ai β bi), denoting that the nodes of tree s with indices ai and bi are connected by an edge.
Consider the nodes of tree s indexed from 1 to n. It is guaranteed that s is a tree.
Output
In the first line print a single integer m that denotes the number of nodes in the required T-decomposition.
Then print m lines, containing descriptions of the T-decomposition nodes. In the i-th (1 β€ i β€ m) of them print the description of node xi of the T-decomposition. The description of each node xi should start from an integer ki, that represents the number of nodes of the initial tree s, that are contained in the node xi. Then you should print ki distinct space-separated integers β the numbers of nodes from s, contained in xi, in arbitrary order.
Then print m - 1 lines, each consisting two integers pi, qi (1 β€ pi, qi β€ m; pi β qi). The pair of integers pi, qi means there is an edge between nodes xpi and xqi of T-decomposition.
The printed T-decomposition should be the optimal T-decomposition for the given tree s and have the minimum possible number of nodes among all optimal T-decompositions. If there are multiple optimal T-decompositions with the minimum number of nodes, print any of them.
Examples
Input
2
1 2
Output
1
2 1 2
Input
3
1 2
2 3
Output
2
2 1 2
2 2 3
1 2
Input
4
2 1
3 1
4 1
Output
3
2 2 1
2 3 1
2 4 1
1 2
2 3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<int> G[100010];
int T[100010];
vector<pair<int, int> > sol;
vector<pair<int, int> > muchii;
int K;
int n;
bool viz[100010];
void df(int x) {
viz[x] = 1;
T[x] = -1;
for (typeof(G[x].begin()) i = G[x].begin(); i != G[x].end(); i++) {
if (!viz[*i]) {
df(*i);
K++;
if (T[x] == -1) {
T[x] = K;
} else {
muchii.push_back(make_pair(T[x], K));
}
if (T[*i] != -1) muchii.push_back(make_pair(K, T[*i]));
sol.push_back(make_pair(x, *i));
}
}
}
int main() {
scanf("%d", &n);
for (int i = 1; i < n; i++) {
int x, y;
scanf("%d%d", &x, &y);
G[x].push_back(y);
G[y].push_back(x);
}
df(1);
printf("%d\n", sol.size());
for (typeof(sol.begin()) i = sol.begin(); i != sol.end(); i++) {
printf("2 %d %d\n", i->first, i->second);
}
for (typeof(muchii.begin()) i = muchii.begin(); i != muchii.end(); i++) {
printf("%d %d\n", i->first, i->second);
}
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
Input
The first line contains two integers n and m (2 β€ n, m β€ 100) β the number of employees and the number of languages.
Then n lines follow β each employee's language list. At the beginning of the i-th line is integer ki (0 β€ ki β€ m) β the number of languages the i-th employee knows. Next, the i-th line contains ki integers β aij (1 β€ aij β€ m) β the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces.
Output
Print a single integer β the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
Examples
Input
5 5
1 2
2 2 3
2 3 4
2 4 5
1 5
Output
0
Input
8 7
0
3 1 2 3
1 1
2 5 4
2 6 7
1 3
2 7 4
1 1
Output
2
Input
2 2
1 2
0
Output
1
Note
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m, num, a, cnt, c2;
vector<int> vis(110);
vector<set<int> > grp(110);
vector<int> clrs[110];
void dfs(int src) {
vis[src] = 1;
for (auto u : grp[src])
if (!vis[u]) dfs(u);
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> num;
if (!num) c2++;
while (num--) {
cin >> a;
clrs[a].push_back(i);
}
}
if (c2 == n) return cout << n, 0;
for (int i = 1; i <= m; i++)
for (int j = 0; j < clrs[i].size(); j++)
for (int k = j + 1; k < clrs[i].size(); k++)
grp[clrs[i][j]].insert(clrs[i][k]), grp[clrs[i][k]].insert(clrs[i][j]);
for (int i = 1; i <= n; i++)
if (!vis[i]) {
dfs(i);
cnt++;
}
cout << cnt - 1;
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
You are given a sequence a consisting of n integers. Find the maximum possible value of <image> (integer remainder of ai divided by aj), where 1 β€ i, j β€ n and ai β₯ aj.
Input
The first line contains integer n β the length of the sequence (1 β€ n β€ 2Β·105).
The second line contains n space-separated integers ai (1 β€ ai β€ 106).
Output
Print the answer to the problem.
Examples
Input
3
3 4 5
Output
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e6 + 100;
int a[MAXN], n, ans;
int main() {
int maxa = 0;
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
sort(a + 1, a + n + 1);
for (int i = n - 1; i >= 1; i--) {
if (a[i] == a[i - 1]) continue;
if (ans >= a[i] - 1) break;
int tmp = a[i];
while (tmp <= a[n]) {
tmp += a[i];
int k = lower_bound(a + 1, a + n + 1, tmp) - a;
k--;
ans = max(ans, a[k] % a[i]);
}
}
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
You are given an array a. Some element of this array ai is a local minimum iff it is strictly less than both of its neighbours (that is, ai < ai - 1 and ai < ai + 1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, ai > ai - 1 and ai > ai + 1). Since a1 and an have only one neighbour each, they are neither local minima nor local maxima.
An element is called a local extremum iff it is either local maximum or local minimum. Your task is to calculate the number of local extrema in the given array.
Input
The first line contains one integer n (1 β€ n β€ 1000) β the number of elements in array a.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 1000) β the elements of array a.
Output
Print the number of local extrema in the given array.
Examples
Input
3
1 2 3
Output
0
Input
4
1 5 2 5
Output
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, cnt = 0;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) cin >> arr[i];
n--;
for (int i = 1; i < n; i++) {
if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1])
cnt++;
else if (arr[i] < arr[i - 1] && arr[i] < arr[i + 1])
cnt++;
}
cout << cnt;
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills.
Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisible by 64, in the binary numerical system.
Input
In the only line given a non-empty binary string s with length up to 100.
Output
Print Β«yesΒ» (without quotes) if it's possible to remove digits required way and Β«noΒ» otherwise.
Examples
Input
100010001
Output
yes
Input
100
Output
no
Note
In the first test case, you can get string 1 000 000 after removing two ones which is a representation of number 64 in the binary numerical system.
You can read more about binary numeral system representation here: <https://en.wikipedia.org/wiki/Binary_system>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
if (s == "0") {
cout << "no\n";
return 0;
}
if (s.length() < 7) {
cout << "no\n";
return 0;
}
int cnt = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s[i] == '0') cnt++;
if (cnt >= 6 && s[i] == '1') {
cout << "yes\n";
return 0;
}
}
cout << "no\n";
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
As you very well know, this year's funkiest numbers are so called triangular numbers (that is, integers that are representable as <image>, where k is some positive integer), and the coolest numbers are those that are representable as a sum of two triangular numbers.
A well-known hipster Andrew adores everything funky and cool but unfortunately, he isn't good at maths. Given number n, help him define whether this number can be represented by a sum of two triangular numbers (not necessarily different)!
Input
The first input line contains an integer n (1 β€ n β€ 109).
Output
Print "YES" (without the quotes), if n can be represented as a sum of two triangular numbers, otherwise print "NO" (without the quotes).
Examples
Input
256
Output
YES
Input
512
Output
NO
Note
In the first sample number <image>.
In the second sample number 512 can not be represented as a sum of two triangular numbers.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
set<int> st;
set<int>::iterator it;
for (int i = 1; i <= 45000; ++i) {
int ans = i * (i + 1) / 2;
st.insert(ans);
}
while (~scanf("%d", &n)) {
int flag = 0;
for (it = st.begin(); it != st.end(); ++it) {
if (st.find(n - *it) != st.end()) {
flag = 1;
break;
}
}
if (flag)
puts("YES");
else
puts("NO");
}
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of a thimbles per day after the k days are complete.
Initially, no orders are pending. The factory receives updates of the form di, ai, indicating that ai new orders have been placed for the di-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes.
As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day pi. Help the owner answer his questions.
Input
The first line contains five integers n, k, a, b, and q (1 β€ k β€ n β€ 200 000, 1 β€ b < a β€ 10 000, 1 β€ q β€ 200 000) β the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively.
The next q lines contain the descriptions of the queries. Each query is of one of the following two forms:
* 1 di ai (1 β€ di β€ n, 1 β€ ai β€ 10 000), representing an update of ai orders on day di, or
* 2 pi (1 β€ pi β€ n - k + 1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day pi?
It's guaranteed that the input will contain at least one query of the second type.
Output
For each query of the second type, print a line containing a single integer β the maximum number of orders that the factory can fill over all n days.
Examples
Input
5 2 2 1 8
1 1 2
1 5 3
1 2 1
2 2
1 4 2
1 3 2
2 1
2 3
Output
3
6
4
Input
5 4 10 1 6
1 1 5
1 5 5
1 3 2
1 5 2
2 1
2 2
Output
7
1
Note
Consider the first sample.
We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days.
For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled.
For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int n, k, a, b, q;
int tree[2][22 * N];
void upd(int cur, int st, int en, int x, int y, int val, int ty) {
if (en < x || st > y || x > y) return;
if (st >= x && en <= y) {
if (ty == 0) {
tree[ty][cur] = min(tree[ty][cur] + val, b);
} else {
tree[ty][cur] = min(tree[ty][cur] + val, a);
}
return;
}
int mid = (st + en) / 2;
upd(cur + cur, st, mid, x, y, val, ty);
upd(cur + cur + 1, mid + 1, en, x, y, val, ty);
tree[ty][cur] = (tree[ty][cur + cur] + tree[ty][cur + cur + 1]);
}
int get(int cur, int st, int en, int x, int y, int ty) {
if (en < x || st > y || x > y) return 0;
if (st >= x && en <= y) {
return tree[ty][cur];
}
int mid = (st + en) / 2;
int v1 = get(cur + cur, st, mid, x, y, ty);
int v2 = get(cur + cur + 1, mid + 1, en, x, y, ty);
return v1 + v2;
}
int main() {
cin >> n >> k >> a >> b >> q;
for (int i = 0; i < q; i++) {
int ty;
scanf("%d", &ty);
if (ty == 1) {
int d, o;
scanf("%d%d", &d, &o);
upd(1, 1, n, d, d, o, 0);
upd(1, 1, n, d, d, o, 1);
} else {
int d;
scanf("%d", &d);
int ans = get(1, 1, n, 1, d - 1, 0);
ans += get(1, 1, n, d + k, n, 1);
printf("%d\n", ans);
}
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer q. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circles around the hotel. Let us remind you that a number's divisor is called non-trivial if it is different from one and from the divided number itself.
The first person who can't make a move wins as he continues to lie in his warm bed under three blankets while the other one keeps running. Determine which player wins considering that both players play optimally. If the first player wins, print any winning first move.
Input
The first line contains the only integer q (1 β€ q β€ 1013).
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.
Output
In the first line print the number of the winning player (1 or 2). If the first player wins then the second line should contain another integer β his first move (if the first player can't even make the first move, print 0). If there are multiple solutions, print any of them.
Examples
Input
6
Output
2
Input
30
Output
1
6
Input
1
Output
1
0
Note
Number 6 has only two non-trivial divisors: 2 and 3. It is impossible to make a move after the numbers 2 and 3 are written, so both of them are winning, thus, number 6 is the losing number. A player can make a move and write number 6 after number 30; 6, as we know, is a losing number. Thus, this move will bring us the victory.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool isPrime(long long n) {
for (long long i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long n;
cin >> n;
if (isPrime(n)) {
cout << 1 << endl << 0 << endl;
} else {
long long a = -1, b = -1;
long long temp = n;
for (long long i = 2; i <= n; i++) {
if (n % i == 0) {
if (isPrime(i) && isPrime(n / i) && (n == temp)) {
a = i;
b = n / i;
} else {
if (a == -1)
a = i;
else if (b == -1)
b = i;
n /= i;
while ((n % i) == 0) {
if (b == -1) b = i;
n /= i;
}
}
}
if (a != -1 && b != -1) break;
}
if ((a * b) == temp) {
cout << 2 << endl;
} else {
cout << 1 << endl;
cout << a * b << endl;
}
}
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
You are given array a_1, a_2, ..., a_n. Find the subsegment a_l, a_{l+1}, ..., a_r (1 β€ l β€ r β€ n) with maximum arithmetic mean (1)/(r - l + 1)β_{i=l}^{r}{a_i} (in floating-point numbers, i.e. without any rounding).
If there are many such subsegments find the longest one.
Input
The first line contains single integer n (1 β€ n β€ 10^5) β length of the array a.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 10^9) β the array a.
Output
Print the single integer β the length of the longest subsegment with maximum possible arithmetic mean.
Example
Input
5
6 1 6 6 0
Output
2
Note
The subsegment [3, 4] is the longest among all subsegments with maximum arithmetic mean.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n;
cin >> n;
long long max_avg = -1;
long long max_len = -1;
long long curr_len = 0;
std::vector<long long> input;
for (long long i = 0; i < n; i++) {
long long temp;
cin >> temp;
input.push_back(temp);
if (temp > max_avg) {
max_avg = temp;
curr_len = 1;
max_len = 1;
} else if (temp == max_avg && temp == input[i - 1]) {
curr_len++;
if (curr_len > max_len) max_len = curr_len;
} else if (temp == max_avg && temp != input[i - 1]) {
curr_len = 1;
}
}
cout << max_len;
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
We will say that two integer sequences of length N, x_1, x_2, ..., x_N and y_1, y_2, ..., y_N, are similar when |x_i - y_i| \leq 1 holds for all i (1 \leq i \leq N).
In particular, any integer sequence is similar to itself.
You are given an integer N and an integer sequence of length N, A_1, A_2, ..., A_N.
How many integer sequences b_1, b_2, ..., b_N are there such that b_1, b_2, ..., b_N is similar to A and the product of all elements, b_1 b_2 ... b_N, is even?
Constraints
* 1 \leq N \leq 10
* 1 \leq A_i \leq 100
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the number of integer sequences that satisfy the condition.
Examples
Input
2
2 3
Output
7
Input
3
3 3 3
Output
26
Input
1
100
Output
1
Input
10
90 52 56 71 44 8 13 30 57 84
Output
58921
### Response
```cpp
#include <iostream>
#include <cmath>
using namespace std;
int a[15];
int main()
{
int i,n,ans,pro=1;
cin >> n;
for(i=0;i<n;i++){
cin >> a[n];
if(a[n]%2 == 0){
pro = pro*2;
}
}
ans=pow(3,n)-pro;
cout << ans << endl;
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
The "Western calendar" is a concept imported from the West, but in Japan there is a concept called the Japanese calendar, which identifies the "era name" by adding a year as a method of expressing the year on the calendar. For example, this year is 2016 in the Christian era, but 2016 in the Japanese calendar. Both are commonly used expressions of years, but have you ever experienced a situation where you know the year of a year but do not know how many years it is in the Japanese calendar, or vice versa?
Create a program that outputs the year of the Japanese calendar when the year is given in the Christian era, and the year of the Western calendar when the year is given in the Japanese calendar. However, the correspondence between the Western calendar and the Japanese calendar is as follows for the sake of simplicity.
Western calendar | Japanese calendar
--- | ---
From 1868 to 1911 | From the first year of the Meiji era to the 44th year of the Meiji era
1912 to 1925 | Taisho 1st year to Taisho 14th year
From 1926 to 1988 | From the first year of Showa to 1988
1989-2016 | 1989-2016
Input
The input is given in the following format.
E Y
The input consists of one line, where E (0 β€ E β€ 4) is the type of calendar given, Y is the year in that calendar, and when E is 0, the year Y (1868 β€ Y β€ 2016), 1 When is the Meiji Y (1 β€ Y β€ 44) year of the Japanese calendar, when it is 2, the Taisho Y (1 β€ Y β€ 14) year of the Japanese calendar, and when it is 3, the Showa Y (1 β€ Y β€ 63) of the Japanese calendar ) Year, 4 represents the Heisei Y (1 β€ Y β€ 28) year of the Japanese calendar.
Output
If it is the Western calendar, it is converted to the Japanese calendar, and if it is the Japanese calendar, it is converted to the Western calendar. However, the result of converting the Western calendar to the Japanese calendar is output with the letter "M" in the Meiji era, the letter "T" in the Taisho era, the letter "S" in the Showa era, and the letter "H" in the Heisei era.
Examples
Input
0 2015
Output
H27
Input
0 1912
Output
T1
Input
2 1
Output
1912
Input
4 28
Output
2016
### Response
```cpp
using namespace std;
#include<iostream>
int main(){
int E,Y;
cin>>E>>Y;
switch(E){
case 0: if(1868<=Y&&Y<=1911) cout<<"M"<<Y-1867<<endl;
else if(1912<=Y&&Y<=1925) cout<<"T"<<Y-1911<<endl;
else if(1926<=Y&&Y<=1988) cout<<"S"<<Y-1925<<endl;
else cout<<"H"<<Y-1988<<endl;
break;
case 1: cout<<Y+1867<<endl;
break;
case 2: cout<<Y+1911<<endl;
break;
case 3: cout<<Y+1925<<endl;
break;
case 4: cout<<Y+1988<<endl;
break;
}
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Little girl Susie went shopping with her mom and she wondered how to improve service quality.
There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed.
Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.
Input
The first line contains integer n (1 β€ n β€ 105).
The next line contains n integers ti (1 β€ ti β€ 109), separated by spaces.
Output
Print a single number β the maximum number of not disappointed people in the queue.
Examples
Input
5
15 2 1 5 3
Output
4
Note
Value 4 is achieved at such an arrangement, for example: 1, 2, 3, 5, 15. Thus, you can make everything feel not disappointed except for the person with time 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i++) cin >> a[i];
sort(a, a + n);
long int ts = 0;
int ans = 0;
for (int i = 0; i < n; i++) {
if (a[i] < ts) {
ans++;
continue;
}
ts += a[i];
}
cout << n - ans << "\n";
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Important: All possible tests are in the pretest, so you shouldn't hack on this problem. So, if you passed pretests, you will also pass the system test.
You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak monsters, you arrived at a square room consisting of tiles forming an n Γ n grid, surrounded entirely by walls. At the end of the room lies a door locked with evil magical forces. The following inscriptions are written on the door:
The sound of clashing rocks will awaken the door!
Being a very senior adventurer, you immediately realize what this means. In the room next door lies an infinite number of magical rocks. There are four types of rocks:
* '^': this rock moves upwards;
* '<': this rock moves leftwards;
* '>': this rock moves rightwards;
* 'v': this rock moves downwards.
To open the door, you first need to place the rocks on some of the tiles (one tile can be occupied by at most one rock). Then, you select a single rock that you have placed and activate it. The activated rock will then move in its direction until it hits another rock or hits the walls of the room (the rock will not move if something already blocks it in its chosen direction). The rock then deactivates. If it hits the walls, or if there have been already 107 events of rock becoming activated, the movements end. Otherwise, the rock that was hit becomes activated and this procedure is repeated.
If a rock moves at least one cell before hitting either the wall or another rock, the hit produces a sound. The door will open once the number of produced sounds is at least x. It is okay for the rocks to continue moving after producing x sounds.
The following picture illustrates the four possible scenarios of moving rocks.
* Moves at least one cell, then hits another rock. A sound is produced, the hit rock becomes activated. <image>
* Moves at least one cell, then hits the wall (i.e., the side of the room). A sound is produced, the movements end. <image>
* Does not move because a rock is already standing in the path. The blocking rock becomes activated, but no sounds are produced. <image>
* Does not move because the wall is in the way. No sounds are produced and the movements end. <image>
Assume there's an infinite number of rocks of each type in the neighboring room. You know what to do: place the rocks and open the door!
Input
The first line will consists of two integers n and x, denoting the size of the room and the number of sounds required to open the door. There will be exactly three test cases for this problem:
* n = 5, x = 5;
* n = 3, x = 2;
* n = 100, x = 105.
All of these testcases are in pretest.
Output
Output n lines. Each line consists of n characters β the j-th character of the i-th line represents the content of the tile at the i-th row and the j-th column, and should be one of these:
* '^', '<', '>', or 'v': a rock as described in the problem statement.
* '.': an empty tile.
Then, output two integers r and c (1 β€ r, c β€ n) on the next line β this means that the rock you activate first is located at the r-th row from above and c-th column from the left. There must be a rock in this cell.
If there are multiple solutions, you may output any of them.
Examples
Input
5 5
Output
>...v
v.<..
..^..
>....
..^.<
1 1
Input
3 2
Output
>vv
^<.
^.<
1 3
Note
Here's a simulation of the first example, accompanied with the number of sounds produced so far.
<image> 0 sound <image> 1 sound <image> 2 sounds <image> 3 sounds <image> 4 sounds <image> still 4 sounds
In the picture above, the activated rock switches between the '^' rock and the '<' rock. However, no sound is produced since the '^' rock didn't move even a single tile. So, still 4 sound.
<image> 5 sounds
At this point, 5 sound are already produced, so this solution is already correct. However, for the sake of example, we will continue simulating what happens.
<image> 6 sounds <image> 7 sounds <image> still 7 sounds <image> 8 sounds
And the movement stops. In total, it produces 8 sounds. Notice that the last move produced sound.
Here's a simulation of the second example:
<image> 0 sound <image> 1 sound <image> 2 sounds
Now, the activated stone will switch continuously from one to another without producing a sound until it reaches the 107 limit, after which the movement will cease.
<image>
In total, it produced exactly 2 sounds, so the solution is correct.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
if (n == 5) {
cout << ">...v\nv.<..\n..^..\n>....\n..^.<\n1 1";
} else if (n == 3) {
cout << ">vv\n^<.\n^.<\n1 3";
} else {
string a =
"v<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<<<<<<<<<<<<<<<<<<<"
"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<";
string b =
"v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>"
"v>v>v>v>v>v>v>v>v>v>v>v>v>v>v^";
string c =
"v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v."
"v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.";
string d =
"v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^"
"v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^";
string e =
".^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^"
".^.^.^.^.^.^.^.^.^.^.^.^.^.^.^";
string f =
">^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^"
">^>^>^>^>^>^>^>^>^>^>^>^>^>^>^";
string g =
"......................................................................"
"..............................";
cout << a << endl << b << endl;
for (int(i) = 0; (i) < (24); (i)++) cout << c << endl << d << endl;
for (int(i) = 0; (i) < (24); (i)++) cout << d << endl << e << endl;
cout << f << endl << g << endl;
cout << "1 1" << endl;
}
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Takahashi and Aoki are going to together construct a sequence of integers.
First, Takahashi will provide a sequence of integers a, satisfying all of the following conditions:
* The length of a is N.
* Each element in a is an integer between 1 and K, inclusive.
* a is a palindrome, that is, reversing the order of elements in a will result in the same sequence as the original.
Then, Aoki will perform the following operation an arbitrary number of times:
* Move the first element in a to the end of a.
How many sequences a can be obtained after this procedure, modulo 10^9+7?
Constraints
* 1β€Nβ€10^9
* 1β€Kβ€10^9
Input
The input is given from Standard Input in the following format:
N K
Output
Print the number of the sequences a that can be obtained after the procedure, modulo 10^9+7.
Examples
Input
4 2
Output
6
Input
1 10
Output
10
Input
6 3
Output
75
Input
1000000000 1000000000
Output
875699961
### Response
```cpp
#include<bits/stdc++.h>
#define L long long
using namespace std;
const int q=1000000007;
int n,m,x[100010],t,f[100010],p;
inline int power(int a,int b)
{
if(!b)
return 1;
int c=power(a,b>>1);
c=(L)c*c%q;
if(b&1)
c=(L)c*a%q;
return c;
}
int main()
{
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
int i,j;
scanf("%d%d",&n,&m);
for(i=1;i*i<=n;i++)
if(n%i==0)
{
x[++t]=i;
if(n/i!=i)
x[++t]=n/i;
}
sort(x+1,x+t+1);
for(i=1;i<=t;i++)
{
f[i]=power(m,(x[i]+1)/2);
for(j=1;j<i;j++)
if(x[i]%x[j]==0)
f[i]=(f[i]-f[j])%q;
p=(p+(L)f[i]*((x[i]&1)?x[i]:(x[i]/2)))%q;
}
p=(p+q)%q;
printf("%d\n",p);
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Ksenia has ordinary pan scales and several weights of an equal mass. Ksenia has already put some weights on the scales, while other weights are untouched. Ksenia is now wondering whether it is possible to put all the remaining weights on the scales so that the scales were in equilibrium.
The scales is in equilibrium if the total sum of weights on the left pan is equal to the total sum of weights on the right pan.
Input
The first line has a non-empty sequence of characters describing the scales. In this sequence, an uppercase English letter indicates a weight, and the symbol "|" indicates the delimiter (the character occurs in the sequence exactly once). All weights that are recorded in the sequence before the delimiter are initially on the left pan of the scale. All weights that are recorded in the sequence after the delimiter are initially on the right pan of the scale.
The second line contains a non-empty sequence containing uppercase English letters. Each letter indicates a weight which is not used yet.
It is guaranteed that all the English letters in the input data are different. It is guaranteed that the input does not contain any extra characters.
Output
If you cannot put all the weights on the scales so that the scales were in equilibrium, print string "Impossible". Otherwise, print the description of the resulting scales, copy the format of the input.
If there are multiple answers, print any of them.
Examples
Input
AC|T
L
Output
AC|TL
Input
|ABC
XYZ
Output
XYZ|ABC
Input
W|T
F
Output
Impossible
Input
ABC|
D
Output
Impossible
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 10005;
char s[MAXN];
int main() {
while (scanf("%s", s) + 1) {
char t[MAXN];
scanf("%s", t);
int l, r;
int i = 0;
while (s[i] != '|') i++;
l = i;
r = strlen(s) - l - 1;
int len = strlen(t);
int sum = l + r + len;
if ((sum) % 2 == 0 && l <= sum / 2 && r <= sum / 2) {
for (int i = 0; i < l; i++) printf("%c", s[i]);
for (int i = 0; i < sum / 2 - l; i++) printf("%c", t[i]);
for (int i = l; s[i]; i++) printf("%c", s[i]);
for (int i = sum / 2 - l; t[i]; i++) printf("%c", t[i]);
printf("\n");
} else {
printf("Impossible\n");
}
}
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.
Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.
Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.
Please see the test case analysis.
Input
The first line contains number t (1 β€ t β€ 50) β the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
Output
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
Examples
Input
2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......
........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#
Output
YES
NO
Note
Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).
On the second board the semiknights will never meet.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct ASDF {
ASDF& operator,(int& a) {
scanf("%d", &a);
return *this;
}
ASDF& operator,(long int& a) {
scanf("%ld", &a);
return *this;
}
ASDF& operator,(long long int& a) {
scanf("%lld", &a);
return *this;
}
ASDF& operator,(char& c) {
scanf("%c", &c);
return *this;
}
ASDF& operator,(double& d) {
scanf("%lf", &d);
return *this;
}
template <typename T>
ASDF& operator,(T& a) {
cin >> a;
return *this;
}
} asdf;
struct ASDFG {
template <typename T>
ASDFG& operator,(vector<T>& v) {
printf("[");
cout << v[0];
for (int i = 1; i < int(v.size()); i++) {
cout << ", " << v[i];
}
printf("]");
return *this;
}
template <typename T>
ASDFG& operator,(T x) {
cout << x << " ";
return *this;
}
} asdfg;
bool cnt[8][8];
string board[8];
int dist[8][8];
int x[] = {2, 2, -2, -2};
int y[] = {2, -2, 2, -2};
bool isValid(int i, int j) { return -1 < i && i < 8 && -1 < j && j < 8; }
bool search(int i, int j) {
cnt[i][j] = true;
if (board[i][j] == 'K') {
return dist[i][j] % 2 == 0;
} else {
bool res = false;
for (int k = 0; k < 4; k++) {
int xx, yy;
xx = i + x[k];
yy = j + y[k];
if (isValid(xx, yy) && cnt[xx][yy] == false) {
dist[xx][yy] = dist[i][j] + 1;
res = res | search(xx, yy);
}
}
return res;
}
}
int main() {
int kases;
scanf("%d", &kases);
bool result;
while (kases--) {
for (int i = 0; i < 8; i++) {
cin >> board[i];
}
memset(cnt, 0, sizeof(cnt));
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (board[i][j] == 'K') {
dist[i][j] = 0;
board[i][j] = '.';
result = search(i, j);
goto hell;
}
}
}
hell:
if (result) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
The Berland capital is shaken with three bold crimes committed by the Pihsters, a notorious criminal gang.
The Berland capital's map is represented by an n Γ m rectangular table. Each cell of the table on the map represents some districts of the capital.
The capital's main detective Polycarpus took a map and marked there the districts where the first three robberies had been committed as asterisks. Deduction tells Polycarpus that the fourth robbery will be committed in such district, that all four robbed districts will form the vertices of some rectangle, parallel to the sides of the map.
Polycarpus is good at deduction but he's hopeless at math. So he asked you to find the district where the fourth robbery will be committed.
Input
The first line contains two space-separated integers n and m (2 β€ n, m β€ 100) β the number of rows and columns in the table, correspondingly.
Each of the next n lines contains m characters β the description of the capital's map. Each character can either be a "." (dot), or an "*" (asterisk). A character equals "*" if the corresponding district has been robbed. Otherwise, it equals ".".
It is guaranteed that the map has exactly three characters "*" and we can always find the fourth district that meets the problem requirements.
Output
Print two integers β the number of the row and the number of the column of the city district that is the fourth one to be robbed. The rows are numbered starting from one from top to bottom and the columns are numbered starting from one from left to right.
Examples
Input
3 2
.*
..
**
Output
1 1
Input
3 3
*.*
*..
...
Output
2 3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int i, j, k = 0, n, m, x[101] = {0}, y[101] = {0};
cin >> n >> m;
char c;
for (i = 0; i < n; i++)
for (j = 0; j < m; j++) {
cin >> c;
if (c == '*') {
x[j]++;
y[i]++;
}
}
for (i = 0; i < m; i++) {
if (x[i] == 1) k = i;
}
for (i = 0; i < n; i++) {
if (y[i] == 1) j = i;
}
cout << j + 1 << ' ' << k + 1;
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
We have a sequence of length N, a = (a_1, a_2, ..., a_N). Each a_i is a positive integer.
Snuke's objective is to permute the element in a so that the following condition is satisfied:
* For each 1 β€ i β€ N - 1, the product of a_i and a_{i + 1} is a multiple of 4.
Determine whether Snuke can achieve his objective.
Constraints
* 2 β€ N β€ 10^5
* a_i is an integer.
* 1 β€ a_i β€ 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
If Snuke can achieve his objective, print `Yes`; otherwise, print `No`.
Examples
Input
3
1 10 100
Output
Yes
Input
4
1 2 3 4
Output
No
Input
3
1 4 1
Output
Yes
Input
2
1 1
Output
No
Input
6
2 7 1 8 2 8
Output
Yes
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,a,n4=0,n2=0;
cin>>n;
for(int i=0;i<n;i++){
cin>>a;
if(a%4==0)
n4++;
else if(a%2==0)
n2++;
}
if(n/2<=n4+n2/2)
cout<<"Yes";
else
cout<<"No";
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
You are given a sequence a consisting of n integers. You may partition this sequence into two sequences b and c in such a way that every element belongs exactly to one of these sequences.
Let B be the sum of elements belonging to b, and C be the sum of elements belonging to c (if some of these sequences is empty, then its sum is 0). What is the maximum possible value of B - C?
Input
The first line contains one integer n (1 β€ n β€ 100) β the number of elements in a.
The second line contains n integers a1, a2, ..., an ( - 100 β€ ai β€ 100) β the elements of sequence a.
Output
Print the maximum possible value of B - C, where B is the sum of elements of sequence b, and C is the sum of elements of sequence c.
Examples
Input
3
1 -2 0
Output
3
Input
6
16 23 16 15 42 8
Output
120
Note
In the first example we may choose b = {1, 0}, c = { - 2}. Then B = 1, C = - 2, B - C = 3.
In the second example we choose b = {16, 23, 16, 15, 42, 8}, c = {} (an empty sequence). Then B = 120, C = 0, B - C = 120.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n(0);
cin >> n;
vector<int> v(n);
long long sum_b(0), sum_c(0);
for (auto i = 0; i < n; i++) {
cin >> v[i];
if (v[i] >= 0)
sum_b += v[i];
else
sum_c += v[i];
}
cout << sum_b - sum_c << endl;
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
A nearby pie shop is having a special sale. For each pie you pay full price for, you may select one pie of a strictly lesser value to get for free. Given the prices of all the pies you wish to acquire, determine the minimum total amount you must pay for all of the pies.
Input
Input will begin with an integer n (1 β€ n β€ 500000), the number of pies you wish to acquire. Following this is a line with n integers, each indicating the cost of a pie. All costs are positive integers not exceeding 109.
Output
Print the minimum cost to acquire all the pies.
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
6
3 4 5 3 4 5
Output
14
Input
5
5 5 5 5 5
Output
25
Input
4
309999 6000 2080 2080
Output
314159
Note
In the first test case you can pay for a pie with cost 5 and get a pie with cost 4 for free, then pay for a pie with cost 5 and get a pie with cost 3 for free, then pay for a pie with cost 4 and get a pie with cost 3 for free.
In the second test case you have to pay full price for every pie.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 500005;
map<int, int> mp;
priority_queue<int, vector<int>, greater<int> > q;
void update(int price, int Y, int S) {
int X = q.size();
Y = min(Y, S);
int cy = Y, cx = (S - Y) / 2;
vector<int> removed;
while (q.size() > cx) {
int tmp = q.top();
removed.push_back(tmp);
q.pop();
}
reverse(removed.begin(), removed.end());
int x = cx, y = 0;
while (x + y < cx + cy) {
if (y == 0 && x < X && removed[x - cx] > price) {
q.push(removed[x - cx]);
x++;
} else if (y < Y && 2 * x + y < S) {
q.push(price);
y++;
} else {
if (2 * price > removed[x - cx - 1])
q.push(2 * price - removed[x - cx - 1]);
else
q.push(0);
x--;
y += 2;
}
}
}
int main() {
int n, x;
int sum = 0;
long long ans = 0ll;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &x);
mp[-x]++;
ans += x;
}
map<int, int>::iterator it;
for (it = mp.begin(); it != mp.end(); it++) {
update(-(it->first), it->second, sum);
sum += it->second;
}
while (q.size()) {
x = q.top();
q.pop();
ans -= x;
}
printf("%I64d\n", ans);
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
In programming languages like C/C++, a goto statement provides an unconditional jump from the "goto" to a labeled statement. For example, a statement "goto CHECK_NUM;" is executed, control of the program jumps to CHECK_NUM. Using these constructs, you can implement, for example, loops.
Note that use of goto statement is highly discouraged, because it is difficult to trace the control flow of a program which includes goto.
Write a program which does precisely the same thing as the following program (this example is wrtten in C++). Let's try to write the program without goto statements.
void call(int n){
int i = 1;
CHECK_NUM:
int x = i;
if ( x % 3 == 0 ){
cout << " " << i;
goto END_CHECK_NUM;
}
INCLUDE3:
if ( x % 10 == 3 ){
cout << " " << i;
goto END_CHECK_NUM;
}
x /= 10;
if ( x ) goto INCLUDE3;
END_CHECK_NUM:
if ( ++i <= n ) goto CHECK_NUM;
cout << endl;
}
Constraints
* 3 β€ n β€ 10000
Input
An integer n is given in a line.
Output
Print the output result of the above program for given integer n.
Example
Input
30
Output
3 6 9 12 13 15 18 21 23 24 27 30
### Response
```cpp
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for(int i = 1; i <= n; i++){
if( i % 3 == 0 || i % 10 == 3 || i / 10 % 10 == 3 || i / 100 % 10 == 3 || i / 1000 % 10 == 3) cout << " " << i;
}
cout<<endl;
// your code goes here
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
A programming competition site AtCode provides algorithmic problems. Each problem is allocated a score based on its difficulty. Currently, for each integer i between 1 and D (inclusive), there are p_i problems with a score of 100i points. These p_1 + β¦ + p_D problems are all of the problems available on AtCode.
A user of AtCode has a value called total score. The total score of a user is the sum of the following two elements:
* Base score: the sum of the scores of all problems solved by the user.
* Perfect bonuses: when a user solves all problems with a score of 100i points, he/she earns the perfect bonus of c_i points, aside from the base score (1 β€ i β€ D).
Takahashi, who is the new user of AtCode, has not solved any problem. His objective is to have a total score of G or more points. At least how many problems does he need to solve for this objective?
Constraints
* 1 β€ D β€ 10
* 1 β€ p_i β€ 100
* 100 β€ c_i β€ 10^6
* 100 β€ G
* All values in input are integers.
* c_i and G are all multiples of 100.
* It is possible to have a total score of G or more points.
Input
Input is given from Standard Input in the following format:
D G
p_1 c_1
:
p_D c_D
Output
Print the minimum number of problems that needs to be solved in order to have a total score of G or more points. Note that this objective is always achievable (see Constraints).
Examples
Input
2 700
3 500
5 800
Output
3
Input
2 2000
3 500
5 800
Output
7
Input
2 400
3 500
5 800
Output
2
Input
5 25000
20 1000
40 1000
50 1000
30 1000
1 1000
Output
66
### Response
```cpp
#include <iostream>
using namespace std;
int main(){
int D, G, p[10], c[10] ;
cin >> D >> G;
for(int i=0; i<D; ++i){
cin >> p[i] >> c[i];
}
int ans=1e3;
for(int mask=0; mask<(1<<D); ++mask){
int s=0, num=0, rest_max=0;
for(int i=0; i<D; ++i){
if(mask >>i &1){
s+= 100*p[i]*(i+1)+c[i];
num+=p[i];
}
else{
rest_max=i;
}
}
int need=0;
if(s<G){
int s1=100*(rest_max+1);
need=(G-s+s1-1)/s1;
if(need>= p[rest_max]) continue;
num+= need;
}
ans= min(ans,num);
}
cout << ans << endl;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
Input
The single line of the input contains two positive integers a and b (1 β€ a, b β€ 100) β the number of red and blue socks that Vasya's got.
Output
Print two space-separated integers β the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.
Examples
Input
3 1
Output
1 1
Input
2 3
Output
2 0
Input
7 3
Output
3 2
Note
In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int inf = 1000;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
;
int a, b;
cin >> a >> b;
cout << min(a, b) << ' ';
a = max(a, b) - min(a, b);
cout << a / 2;
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Long time ago, there was a great kingdom and it was being ruled by The Great Arya and Pari The Great. These two had some problems about the numbers they like, so they decided to divide the great kingdom between themselves.
The great kingdom consisted of n cities numbered from 1 to n and m bidirectional roads between these cities, numbered from 1 to m. The i-th road had length equal to wi. The Great Arya and Pari The Great were discussing about destructing some prefix (all road with numbers less than some x) and suffix (all roads with numbers greater than some x) of the roads so there will remain only the roads with numbers l, l + 1, ..., r - 1 and r.
After that they will divide the great kingdom into two pieces (with each city belonging to exactly one piece) such that the hardness of the division is minimized. The hardness of a division is the maximum length of a road such that its both endpoints are in the same piece of the kingdom. In case there is no such road, the hardness of the division is considered to be equal to - 1.
Historians found the map of the great kingdom, and they have q guesses about the l and r chosen by those great rulers. Given these data, for each guess li and ri print the minimum possible hardness of the division of the kingdom.
Input
The first line of the input contains three integers n, m and q (1 β€ n, q β€ 1000, <image>) β the number of cities and roads in the great kingdom, and the number of guesses, respectively.
The i-th line of the following m lines contains three integers ui, vi and wi (1 β€ ui, vi β€ n, 0 β€ wi β€ 109), denoting the road number i connects cities ui and vi and its length is equal wi. It's guaranteed that no road connects the city to itself and no pair of cities is connected by more than one road.
Each of the next q lines contains a pair of integers li and ri (1 β€ li β€ ri β€ m) β a guess from the historians about the remaining roads in the kingdom.
Output
For each guess print the minimum possible hardness of the division in described scenario.
Example
Input
5 6 5
5 4 86
5 1 0
1 3 38
2 1 33
2 4 28
2 3 40
3 5
2 6
1 3
2 3
1 6
Output
-1
33
-1
-1
33
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct str {
int a, b, len;
} edge[1010 * 1010], sing[1010 * 1010];
vector<str> Edge[501000 << 2];
int n, m, Q;
int top, ans;
int re[1010], fa[1010];
bool cmp(const str &a, const str &b) { return (a.len > b.len); }
int find(int a) {
if (a == fa[a]) return a;
int f = fa[a];
fa[a] = find(f);
re[a] ^= re[f];
return fa[a];
}
void build(int u, int L, int R) {
int n = 0;
for (int i = L; i <= R; i++) sing[++n] = edge[i];
sort(sing + 1, sing + n + 1, cmp);
for (int i = 1; i <= n; i++) {
int a = sing[i].a, b = sing[i].b;
if (find(a) != find(b)) {
re[fa[a]] = re[a] ^ re[b] ^ 1;
fa[fa[a]] = fa[b];
Edge[u].push_back(sing[i]);
} else if (re[a] == re[b]) {
Edge[u].push_back(sing[i]);
break;
}
}
for (int i = 1; i <= n; i++) {
int a = sing[i].a, b = sing[i].b;
re[a] = 0;
re[b] = 0;
fa[a] = a;
fa[b] = b;
}
if (L < R) {
build((u << 1), L, ((L + R) >> 1));
build((u << 1 | 1), (((L + R) >> 1) + 1), R);
}
return;
}
void proc(int u, int L, int R, int l, int r) {
if (L == l && R == r) {
for (int i = 0; i < (int)Edge[u].size(); i++) sing[++top] = Edge[u][i];
return;
}
if (r < (((L + R) >> 1) + 1))
proc((u << 1), L, ((L + R) >> 1), l, r);
else if (l > ((L + R) >> 1))
proc((u << 1 | 1), (((L + R) >> 1) + 1), R, l, r);
else {
proc((u << 1), L, ((L + R) >> 1), l, ((L + R) >> 1));
proc((u << 1 | 1), (((L + R) >> 1) + 1), R, (((L + R) >> 1) + 1), r);
}
return;
}
int main() {
scanf("%d %d %d", &n, &m, &Q);
for (int i = 1; i <= m; i++) {
scanf("%d %d %d", &edge[i].a, &edge[i].b, &edge[i].len);
}
for (int i = 1; i <= n; i++) fa[i] = i;
build(1, 1, m);
for (; Q; Q--) {
int l, r;
for (int i = 1; i <= n; i++) re[i] = 0, fa[i] = i;
scanf("%d %d", &l, &r);
top = 0;
proc(1, 1, m, l, r);
sort(sing + 1, sing + top + 1, cmp);
ans = -1;
for (int i = 1; i <= top; i++) {
int a = sing[i].a, b = sing[i].b;
if (find(a) != find(b)) {
re[fa[a]] = re[a] ^ re[b] ^ 1;
fa[fa[a]] = fa[b];
} else if (re[a] == re[b]) {
ans = sing[i].len;
break;
}
}
printf("%d\n", ans);
}
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.
For instance, if we are given an array [10, 20, 30, 40], we can permute it so that it becomes [20, 40, 10, 30]. Then on the first and the second positions the integers became larger (20>10, 40>20) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals 2. Read the note for the first example, there is one more demonstrative test case.
Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the length of the array.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9) β the elements of the array.
Output
Print a single integer β the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array.
Examples
Input
7
10 1 1 1 5 5 3
Output
4
Input
5
1 1 1 1 1
Output
0
Note
In the first sample, one of the best permutations is [1, 5, 5, 3, 10, 1, 1]. On the positions from second to fifth the elements became larger, so the answer for this permutation is 4.
In the second sample, there is no way to increase any element with a permutation, so the answer is 0.
### Response
```cpp
#include <bits/stdc++.h>
int cmp(const void *a, const void *b) { return *(int *)a - *(int *)b; }
void run(void) {
int n;
scanf("%d", &n);
int *a = (int *)malloc(sizeof(int) * n);
int i;
for (i = 0; i < n; i++) scanf("%d", a + i);
qsort(a, n, sizeof(int), cmp);
int ans = 0;
int l, r;
l = r = 0;
while (r < n) {
while (r < n && a[l] < a[r]) {
ans++;
l++;
r++;
}
while (r < n && a[l] == a[r]) r++;
}
printf("%d\n", ans);
}
int main(void) {
run();
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
There is a cave.
The cave has N rooms and M passages. The rooms are numbered 1 to N, and the passages are numbered 1 to M. Passage i connects Room A_i and Room B_i bidirectionally. One can travel between any two rooms by traversing passages. Room 1 is a special room with an entrance from the outside.
It is dark in the cave, so we have decided to place a signpost in each room except Room 1. The signpost in each room will point to one of the rooms directly connected to that room with a passage.
Since it is dangerous in the cave, our objective is to satisfy the condition below for each room except Room 1.
* If you start in that room and repeatedly move to the room indicated by the signpost in the room you are in, you will reach Room 1 after traversing the minimum number of passages possible.
Determine whether there is a way to place signposts satisfying our objective, and print one such way if it exists.
Constraints
* All values in input are integers.
* 2 \leq N \leq 10^5
* 1 \leq M \leq 2 \times 10^5
* 1 \leq A_i, B_i \leq N\ (1 \leq i \leq M)
* A_i \neq B_i\ (1 \leq i \leq M)
* One can travel between any two rooms by traversing passages.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1
:
A_M B_M
Output
If there is no way to place signposts satisfying the objective, print `No`.
Otherwise, print N lines. The first line should contain `Yes`, and the i-th line (2 \leq i \leq N) should contain the integer representing the room indicated by the signpost in Room i.
Examples
Input
4 4
1 2
2 3
3 4
4 2
Output
Yes
1
2
2
Input
6 9
3 4
6 1
2 4
5 3
4 6
1 5
6 2
4 5
5 6
Output
Yes
6
5
5
1
1
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int n, m; cin >> n >> m;
vector<vector<int>> graph(n+1);
for(int i = 0; i < m; i++){
int a, b; cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
queue<int> que;
que.push(1);
vector<int> seen(n+1, -1);
seen[1] = 1;
vector<int> parent(n+1);
while(!que.empty()){
int nv = que.front();
que.pop();
for(int v : graph[nv]){
if(seen[v] != -1) continue;
que.push(v);
seen[v] = 1;
parent[v] = nv;
}
}
cout << "Yes" << endl;
for(int i = 2; i <= n; i++) cout << parent[i] << endl;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets.
Dr. Evil has his favorite evil integer x. He asks Mahmoud and Ehab to find a set of n distinct non-negative integers such the bitwise-xor sum of the integers in it is exactly x. Dr. Evil doesn't like big numbers, so any number in the set shouldn't be greater than 106.
Input
The only line contains two integers n and x (1 β€ n β€ 105, 0 β€ x β€ 105) β the number of elements in the set and the desired bitwise-xor, respectively.
Output
If there is no such set, print "NO" (without quotes).
Otherwise, on the first line print "YES" (without quotes) and on the second line print n distinct integers, denoting the elements in the set is any order. If there are multiple solutions you can print any of them.
Examples
Input
5 5
Output
YES
1 2 4 5 7
Input
3 6
Output
YES
1 2 5
Note
You can read more about the bitwise-xor operation here: <https://en.wikipedia.org/wiki/Bitwise_operation#XOR>
For the first sample <image>.
For the second sample <image>.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
const long long magicconst = 2000000000000000000;
long long gcd(long long a, long long b) {
if (b > a) swap(a, b);
while (a > 0 && b > 0) {
a %= b;
swap(a, b);
}
return a + b;
}
long long lcm(long long a, long long b) { return (a / gcd(a, b)) * b; }
int getrandomint(int max) {
return (int)(((long long)rand() * (RAND_MAX + 1) + rand()) % max);
}
int main() {
ios_base::sync_with_stdio(false);
srand(505);
int n, m;
cin >> n >> m;
if (n == 2 && m == 0) {
cout << "NO";
return 0;
}
cout << "YES" << endl;
if (n == 1) {
cout << m;
return 0;
}
bool f = true;
while (f) {
set<int> answer;
int x = 0;
for (int i = 0; i < n - 1; i++) {
bool tr = true;
int temp;
while (tr) {
temp = getrandomint(399998) + 100001;
if (answer.find(temp) == answer.end()) {
tr = false;
}
}
x ^= temp;
answer.insert(temp);
}
int last = m ^ x;
if (answer.find(last) == answer.end()) {
cout << last << " ";
for (int k : answer) {
cout << k << " ";
}
return 0;
}
}
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Berkomnadzor β Federal Service for Supervision of Communications, Information Technology and Mass Media β is a Berland federal executive body that protects ordinary residents of Berland from the threats of modern internet.
Berkomnadzor maintains a list of prohibited IPv4 subnets (blacklist) and a list of allowed IPv4 subnets (whitelist). All Internet Service Providers (ISPs) in Berland must configure the network equipment to block access to all IPv4 addresses matching the blacklist. Also ISPs must provide access (that is, do not block) to all IPv4 addresses matching the whitelist. If an IPv4 address does not match either of those lists, it's up to the ISP to decide whether to block it or not. An IPv4 address matches the blacklist (whitelist) if and only if it matches some subnet from the blacklist (whitelist). An IPv4 address can belong to a whitelist and to a blacklist at the same time, this situation leads to a contradiction (see no solution case in the output description).
An IPv4 address is a 32-bit unsigned integer written in the form a.b.c.d, where each of the values a,b,c,d is called an octet and is an integer from 0 to 255 written in decimal notation. For example, IPv4 address 192.168.0.1 can be converted to a 32-bit number using the following expression 192 β
2^{24} + 168 β
2^{16} + 0 β
2^8 + 1 β
2^0. First octet a encodes the most significant (leftmost) 8 bits, the octets b and c β the following blocks of 8 bits (in this order), and the octet d encodes the least significant (rightmost) 8 bits.
The IPv4 network in Berland is slightly different from the rest of the world. There are no reserved or internal addresses in Berland and use all 2^{32} possible values.
An IPv4 subnet is represented either as a.b.c.d or as a.b.c.d/x (where 0 β€ x β€ 32). A subnet a.b.c.d contains a single address a.b.c.d. A subnet a.b.c.d/x contains all IPv4 addresses with x leftmost (most significant) bits equal to x leftmost bits of the address a.b.c.d. It is required that 32 - x rightmost (least significant) bits of subnet a.b.c.d/x are zeroes.
Naturally it happens that all addresses matching subnet a.b.c.d/x form a continuous range. The range starts with address a.b.c.d (its rightmost 32 - x bits are zeroes). The range ends with address which x leftmost bits equal to x leftmost bits of address a.b.c.d, and its 32 - x rightmost bits are all ones. Subnet contains exactly 2^{32-x} addresses. Subnet a.b.c.d/32 contains exactly one address and can also be represented by just a.b.c.d.
For example subnet 192.168.0.0/24 contains range of 256 addresses. 192.168.0.0 is the first address of the range, and 192.168.0.255 is the last one.
Berkomnadzor's engineers have devised a plan to improve performance of Berland's global network. Instead of maintaining both whitelist and blacklist they want to build only a single optimised blacklist containing minimal number of subnets. The idea is to block all IPv4 addresses matching the optimised blacklist and allow all the rest addresses. Of course, IPv4 addresses from the old blacklist must remain blocked and all IPv4 addresses from the old whitelist must still be allowed. Those IPv4 addresses which matched neither the old blacklist nor the old whitelist may be either blocked or allowed regardless of their accessibility before.
Please write a program which takes blacklist and whitelist as input and produces optimised blacklist. The optimised blacklist must contain the minimal possible number of subnets and satisfy all IPv4 addresses accessibility requirements mentioned above.
IPv4 subnets in the source lists may intersect arbitrarily. Please output a single number -1 if some IPv4 address matches both source whitelist and blacklist.
Input
The first line of the input contains single integer n (1 β€ n β€ 2β
10^5) β total number of IPv4 subnets in the input.
The following n lines contain IPv4 subnets. Each line starts with either '-' or '+' sign, which indicates if the subnet belongs to the blacklist or to the whitelist correspondingly. It is followed, without any spaces, by the IPv4 subnet in a.b.c.d or a.b.c.d/x format (0 β€ x β€ 32). The blacklist always contains at least one subnet.
All of the IPv4 subnets given in the input are valid. Integer numbers do not start with extra leading zeroes. The provided IPv4 subnets can intersect arbitrarily.
Output
Output -1, if there is an IPv4 address that matches both the whitelist and the blacklist. Otherwise output t β the length of the optimised blacklist, followed by t subnets, with each subnet on a new line. Subnets may be printed in arbitrary order. All addresses matching the source blacklist must match the optimised blacklist. All addresses matching the source whitelist must not match the optimised blacklist. You can print a subnet a.b.c.d/32 in any of two ways: as a.b.c.d/32 or as a.b.c.d.
If there is more than one solution, output any.
Examples
Input
1
-149.154.167.99
Output
1
0.0.0.0/0
Input
4
-149.154.167.99
+149.154.167.100/30
+149.154.167.128/25
-149.154.167.120/29
Output
2
149.154.167.99
149.154.167.120/29
Input
5
-127.0.0.4/31
+127.0.0.8
+127.0.0.0/30
-195.82.146.208/29
-127.0.0.6/31
Output
2
195.0.0.0/8
127.0.0.4/30
Input
2
+127.0.0.1/32
-127.0.0.1
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 7000000;
int dp[N], chd[N][2], e[4], T = 1, fa[N];
short val[N];
bool sel[N], sgn[N], cn[N][3];
char s[44];
void dfs(int u) {
cn[u][1] = cn[u][2] = 0;
cn[u][val[u]] = 1;
for (int i = 0; i < 2; i++) {
int v = chd[u][i];
if (!v) continue;
dp[v] = dp[u] + 1;
dfs(v);
for (int j = 1; j <= 2; j++) cn[u][j] |= cn[v][j];
}
}
int main() {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%s", s);
int len = strlen(s);
int x = 0, tp = 1;
int j;
for (j = len - 1; j >= 0; j--) {
if (s[j] == '/') break;
x = (s[j] - '0') * tp + x;
tp *= 10;
}
if (j == -1) x = 32;
long long X = 0;
for (int c = 0, j = 1; c < 4; c++) {
int d = 0;
for (; s[j] != '.' && s[j] != '/' && j < len; j++)
d = d * 10 + s[j] - '0';
j++;
X = X << 8 | d;
}
if (((1LL << (32 - x)) - 1) & X) return puts("-1"), 0;
int root = 1;
for (j = 0; j < x; j++) {
int c = X >> (31 - j) & 1;
if (!chd[root][c]) chd[root][c] = ++T, fa[T] = root, sgn[T] = c;
root = chd[root][c];
}
int t = (s[0] == '-' ? 1 : 2);
if (val[root] + t == 3) return puts("-1"), 0;
val[root] = t;
}
dfs(1);
for (int i = 1; i <= T; i++)
if (val[i]) {
if (cn[i][3 - val[i]]) return puts("-1"), 0;
if (val[i] == 2) continue;
int j = i;
while (j > 1 && !cn[fa[j]][2]) j = fa[j];
sel[j] = 1;
}
int tot = 0;
for (int i = 1; i <= T; i++) tot += sel[i];
cout << tot << endl;
for (int i = 1; i <= T; i++) {
if (!sel[i]) continue;
int j = i, x = 0;
long long tp = (1LL << (32 - dp[i]));
long long X = 0;
while (j != 1) {
X += tp * sgn[j], j = fa[j], tp *= 2, x++;
}
for (int c = 0; c < 4; c++) e[c] = X % 256, X /= 256;
printf("%d.%d.%d.%d", e[3], e[2], e[1], e[0]);
if (x < 32) printf("/%d", x);
puts("");
}
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
One of Arkady's friends works at a huge radio telescope. A few decades ago the telescope has sent a signal s towards a faraway galaxy. Recently they've received a response t which they believe to be a response from aliens! The scientists now want to check if the signal t is similar to s.
The original signal s was a sequence of zeros and ones (everyone knows that binary code is the universe-wide language). The returned signal t, however, does not look as easy as s, but the scientists don't give up! They represented t as a sequence of English letters and say that t is similar to s if you can replace all zeros in s with some string r_0 and all ones in s with some other string r_1 and obtain t. The strings r_0 and r_1 must be different and non-empty.
Please help Arkady's friend and find the number of possible replacements for zeros and ones (the number of pairs of strings r_0 and r_1) that transform s to t.
Input
The first line contains a string s (2 β€ |s| β€ 10^5) consisting of zeros and ones β the original signal.
The second line contains a string t (1 β€ |t| β€ 10^6) consisting of lowercase English letters only β the received signal.
It is guaranteed, that the string s contains at least one '0' and at least one '1'.
Output
Print a single integer β the number of pairs of strings r_0 and r_1 that transform s to t.
In case there are no such pairs, print 0.
Examples
Input
01
aaaaaa
Output
4
Input
001
kokokokotlin
Output
2
Note
In the first example, the possible pairs (r_0, r_1) are as follows:
* "a", "aaaaa"
* "aa", "aaaa"
* "aaaa", "aa"
* "aaaaa", "a"
The pair "aaa", "aaa" is not allowed, since r_0 and r_1 must be different.
In the second example, the following pairs are possible:
* "ko", "kokotlin"
* "koko", "tlin"
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int mod[] = {1000000007, 1000000009};
const int base[] = {79, 271};
string s1, s2;
int pws[2][1000009], pre[2][1000009], lol[2], n, m;
pair<int, int> unini;
pair<int, int> getHash(int l, int r) {
if (l == 0) {
return make_pair(pre[0][r], pre[1][r]);
}
int i, j, t1, t2, t3, t4;
long long int buf1, buf2, buf3, buf4;
for (i = 0; i < 2; i++) {
buf1 = (1ll * pre[i][l - 1] * pws[i][r - l + 1]) % mod[i];
buf1 = (pre[i][r] - buf1) % mod[i];
if (buf1 < 0) {
buf1 += mod[i];
}
lol[i] = buf1;
}
return make_pair(lol[0], lol[1]);
}
int solve(int l1, int l2) {
int i, j, t1, t2, t3, t4;
pair<int, int> p1, p2;
p1 = p2 = unini;
t1 = 0;
for (i = 0; i < n; i++) {
if (s1[i] == '0') {
if (p1 == unini) {
p1 = getHash(t1, t1 + l1 - 1);
} else {
if (p1 != getHash(t1, t1 + l1 - 1)) {
return 0;
}
}
t1 += l1;
} else {
if (p2 == unini) {
p2 = getHash(t1, t1 + l2 - 1);
} else {
if (p2 != getHash(t1, t1 + l2 - 1)) {
return 0;
}
}
t1 += l2;
}
}
if (p1 == p2) {
return 0;
}
return (t1 == m);
}
int main() {
ios::sync_with_stdio(0);
int i, j, t1, t2, t3, t4, cnt0, cnt1, ans = 0;
string temp1, temp2;
cin >> s1 >> s2;
n = s1.length();
m = s2.length();
unini = make_pair(-1, -1);
pws[0][0] = pws[1][0] = 1;
for (i = 0; i < 2; i++) {
for (j = 1; j <= m; j++) {
pws[i][j] = (1ll * pws[i][j - 1] * base[i]) % mod[i];
}
}
pre[0][0] = pre[1][0] = (s2[0] - 'a' + 1);
for (i = 0; i < 2; i++) {
for (j = 1; j < m; j++) {
pre[i][j] = (1ll * pre[i][j - 1] * base[i]) % mod[i];
pre[i][j] += (s2[j] - 'a' + 1);
pre[i][j] %= mod[i];
}
}
if (s1[0] == '1') {
for (i = 0; i < n; i++) {
if (s1[i] == '0') {
s1[i] = '1';
} else {
s1[i] = '0';
}
}
}
cnt0 = cnt1 = 0;
for (i = 0; i < n; i++) {
if (s1[i] == '0') {
cnt0++;
} else {
cnt1++;
}
}
for (i = 1; i <= m; i++) {
t1 = cnt0 * i;
t2 = (m - t1) / cnt1;
t3 = (cnt1 * t2) + t1;
if ((m - t1) % cnt1 || t3 != m || t2 <= 0) {
continue;
}
ans += solve(i, (m - t1) / cnt1);
}
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems.
But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest by its name.
It is known, that problem is from this contest if and only if its name contains one of Alex's friends' name exactly once. His friends' names are "Danil", "Olya", "Slava", "Ann" and "Nikita".
Names are case sensitive.
Input
The only line contains string from lowercase and uppercase letters and "_" symbols of length, not more than 100 β the name of the problem.
Output
Print "YES", if problem is from this contest, and "NO" otherwise.
Examples
Input
Alex_and_broken_contest
Output
NO
Input
NikitaAndString
Output
YES
Input
Danil_and_Olya
Output
NO
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string a[] = {"Danil", "Olya", "Slava", "Ann", "Nikita"};
string str;
cin >> str;
int num = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < str.size(); j++) {
if (str.substr(j, a[i].size()) == a[i]) {
num++;
}
}
}
if (num == 1)
printf("YES");
else
printf("NO");
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
You are given an array a of n integers.
You want to make all elements of a equal to zero by doing the following operation exactly three times:
* Select a segment, for each number in this segment we can add a multiple of len to it, where len is the length of this segment (added integers can be different).
It can be proven that it is always possible to make all elements of a equal to zero.
Input
The first line contains one integer n (1 β€ n β€ 100 000): the number of elements of the array.
The second line contains n elements of an array a separated by spaces: a_1, a_2, ..., a_n (-10^9 β€ a_i β€ 10^9).
Output
The output should contain six lines representing three operations.
For each operation, print two lines:
* The first line contains two integers l, r (1 β€ l β€ r β€ n): the bounds of the selected segment.
* The second line contains r-l+1 integers b_l, b_{l+1}, ..., b_r (-10^{18} β€ b_i β€ 10^{18}): the numbers to add to a_l, a_{l+1}, β¦, a_r, respectively; b_i should be divisible by r - l + 1.
Example
Input
4
1 3 2 4
Output
1 1
-1
3 4
4 2
2 4
-3 -6 -6
### Response
```cpp
#include <bits/stdc++.h>
const unsigned long long int M = 1000000007;
using namespace std;
long long power(long long x, long long y) {
long long res = 1;
while (y > 0) {
if (y & 1) res = x * res;
y = y >> 1;
x = x * x;
}
return res;
}
long long power(long long x, long long y, long long mod) {
long long res = 1;
while (y > 0) {
if (y & 1) res = x * res % mod;
y = y >> 1;
x = x * x % mod;
}
return res;
}
void nik() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
}
signed main() {
nik();
long long test = 1;
while (test--) {
long long n;
cin >> n;
long long a[n];
for (long long i = 0; i < n; i++) cin >> a[i];
if (n == 1) {
cout << "1 1\n";
cout << -a[0] << "\n";
cout << "1 1\n";
cout << 0 << "\n";
cout << "1 1\n";
cout << 0 << "\n";
continue;
}
cout << "1 1\n";
cout << -a[0] << "\n";
cout << "1 " << n << "\n";
a[0] = 0;
for (long long i = 0; i < n; i++) cout << -n * a[i] << " ";
cout << "\n2 " << n << "\n";
for (long long i = 1; i < n; i++) cout << ((n - 1) * a[i]) << " ";
}
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Nearly each project of the F company has a whole team of developers working on it. They often are in different rooms of the office in different cities and even countries. To keep in touch and track the results of the project, the F company conducts shared online meetings in a Spyke chat.
One day the director of the F company got hold of the records of a part of an online meeting of one successful team. The director watched the record and wanted to talk to the team leader. But how can he tell who the leader is? The director logically supposed that the leader is the person who is present at any conversation during a chat meeting. In other words, if at some moment of time at least one person is present on the meeting, then the leader is present on the meeting.
You are the assistant director. Given the 'user logged on'/'user logged off' messages of the meeting in the chronological order, help the director determine who can be the leader. Note that the director has the record of only a continuous part of the meeting (probably, it's not the whole meeting).
Input
The first line contains integers n and m (1 β€ n, m β€ 105) β the number of team participants and the number of messages. Each of the next m lines contains a message in the format:
* '+ id': the record means that the person with number id (1 β€ id β€ n) has logged on to the meeting.
* '- id': the record means that the person with number id (1 β€ id β€ n) has logged off from the meeting.
Assume that all the people of the team are numbered from 1 to n and the messages are given in the chronological order. It is guaranteed that the given sequence is the correct record of a continuous part of the meeting. It is guaranteed that no two log on/log off events occurred simultaneously.
Output
In the first line print integer k (0 β€ k β€ n) β how many people can be leaders. In the next line, print k integers in the increasing order β the numbers of the people who can be leaders.
If the data is such that no member of the team can be a leader, print a single number 0.
Examples
Input
5 4
+ 1
+ 2
- 2
- 1
Output
4
1 3 4 5
Input
3 2
+ 1
- 2
Output
1
3
Input
2 4
+ 1
- 1
+ 2
- 2
Output
0
Input
5 6
+ 1
- 1
- 3
+ 3
+ 4
- 4
Output
3
2 3 5
Input
2 4
+ 1
- 2
+ 2
- 1
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m;
char c[100001];
int a[100001];
int f[100001];
bool mark[100001];
int cnt;
set<int> s;
void cl() {
for (set<int>::iterator i = s.begin(); i != s.end(); i++) mark[*i] = true;
s.clear();
}
int main() {
memset(f, -1, sizeof(f));
scanf("%d %d\n", &n, &m);
for (int i = 1; i <= m; i++) {
scanf("%c %d\n", &c[i], &a[i]);
if (f[a[i]] == -1) {
if (c[i] == '+')
f[a[i]] = 0;
else
f[a[i]] = 1;
}
}
for (int i = 1; i <= n; i++) {
if (f[i] == 1) cnt++;
if (f[i] == 0) s.insert(i);
}
if (cnt > 0) cl();
for (int i = 1; i <= m; i++) {
if (c[i] == '+') {
f[a[i]] = 1;
cnt++;
s.erase(a[i]);
cl();
} else {
f[a[i]] = 0;
cnt--;
if (!mark[a[i]]) s.insert(a[i]);
if (cnt > 0) cl();
}
}
cnt = 0;
for (int i = 1; i <= n; i++)
if (!mark[i]) cnt++;
printf("%d\n", cnt);
for (int i = 1; i <= n; i++)
if (!mark[i]) printf("%d ", i);
printf("\n");
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Jeff has become friends with Furik. Now these two are going to play one quite amusing game.
At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality pi > pi + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality pi < pi + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.
Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.
You can consider that the coin shows the heads (or tails) with the probability of 50 percent.
Input
The first line contains integer n (1 β€ n β€ 3000). The next line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β the permutation p. The numbers are separated by spaces.
Output
In a single line print a single real value β the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
Examples
Input
2
1 2
Output
0.000000
Input
5
3 5 2 4 1
Output
13.000000
Note
In the first test the sequence is already sorted, so the answer is 0.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX = 3010;
int p[MAX];
int main() {
int i, j, n, br = 0;
scanf("%d", &n);
for (i = 0; i < n; i++) scanf("%d", &p[i]);
for (i = 0; i < n; i++)
for (j = 0; j < i; j++)
if (p[j] > p[i]) br++;
if (br % 2)
printf("%d.000000\n", br * 2 - 1);
else
printf("%d.000000\n", br * 2);
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Jeff got 2n real numbers a1, a2, ..., a2n as a birthday present. The boy hates non-integer numbers, so he decided to slightly "adjust" the numbers he's got. Namely, Jeff consecutively executes n operations, each of them goes as follows:
* choose indexes i and j (i β j) that haven't been chosen yet;
* round element ai to the nearest integer that isn't more than ai (assign to ai: β ai β);
* round element aj to the nearest integer that isn't less than aj (assign to aj: β aj β).
Nevertheless, Jeff doesn't want to hurt the feelings of the person who gave him the sequence. That's why the boy wants to perform the operations so as to make the absolute value of the difference between the sum of elements before performing the operations and the sum of elements after performing the operations as small as possible. Help Jeff find the minimum absolute value of the difference.
Input
The first line contains integer n (1 β€ n β€ 2000). The next line contains 2n real numbers a1, a2, ..., a2n (0 β€ ai β€ 10000), given with exactly three digits after the decimal point. The numbers are separated by spaces.
Output
In a single line print a single real number β the required difference with exactly three digits after the decimal point.
Examples
Input
3
0.000 0.500 0.750 1.000 2.000 3.000
Output
0.250
Input
3
4469.000 6526.000 4864.000 9356.383 7490.000 995.896
Output
0.279
Note
In the first test case you need to perform the operations as follows: (i = 1, j = 4), (i = 2, j = 3), (i = 5, j = 6). In this case, the difference will equal |(0 + 0.5 + 0.75 + 1 + 2 + 3) - (0 + 0 + 1 + 1 + 2 + 3)| = 0.25.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <class T>
T abs(T x) {
return x > 0 ? x : -x;
}
const double pi = 2 * asin(1.0);
int n;
int m;
int main() {
scanf("%d", &n);
int n1, n2, n12 = 0, n3, s1 = 0, res = (int)1e9;
for (int i = 0; i < 2 * n; i++) {
int x, y;
scanf("%d.%d", &x, &y);
if (y != 0) {
s1 += y;
n12++;
}
}
n3 = 2 * n - n12;
for (int i = 0; i <= n3 / 2; i++) {
n1 = n - n3 + i;
n2 = n - i;
if (n1 < 0 || n2 < 0 || n1 + n2 + n3 != 2 * n) continue;
res = min(min(abs(n1 * 1000 - s1), abs(n2 * 1000 - s1)), res);
}
float ans = (float)res / 1000;
printf("%0.3lf\n", ans);
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Snuke has a permutation (P_0,P_1,\cdots,P_{N-1}) of (0,1,\cdots,N-1).
Now, he will perform the following operation exactly once:
* Choose K consecutive elements in P and sort them in ascending order.
Find the number of permutations that can be produced as P after the operation.
Constraints
* 2 \leq N \leq 200000
* 2 \leq K \leq N
* 0 \leq P_i \leq N-1
* P_0,P_1,\cdots,P_{N-1} are all different.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
P_0 P_1 \cdots P_{N-1}
Output
Print the number of permutations that can be produced as P after the operation.
Examples
Input
5 3
0 2 1 4 3
Output
2
Input
4 4
0 1 2 3
Output
1
Input
10 4
2 0 1 3 7 5 4 6 8 9
Output
6
### Response
```cpp
#include <iostream>
#include <cstring>
#include <set>
using namespace std;
const int MAXN = 200010;
int a[MAXN];
int main() {
int n, k;
cin>>n>>k;
for (int i=0; i<n; i++)
cin>>a[i];
set<int> s;
for (int i=0; i<k; i++)
s.insert(a[i]);
int ans = 0, flagasc = 0;
int rcount = 0;
for (int i=1; i<k; i++)
if (a[i-1] > a[i])
rcount++;
if (rcount)
ans = 1;
else
flagasc = 1;
for (int i=k; i<n; i++) {
int round = 0;
s.erase(a[i-k]);
if (a[i-k] > a[i-k+1])
rcount--;
if (a[i-k] > *s.begin() && rcount != 0)
round = 1;
if (a[i] < *s.rbegin())
round = 1;
s.insert(a[i]);
if (a[i-1] > a[i])
rcount++;
ans += round;
if (rcount == 0)
flagasc = 1;
}
cout<<ans + flagasc<<endl;
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
You are given a string S consisting of lowercase English letters. Determine whether we can turn S into a palindrome by repeating the operation of swapping two adjacent characters. If it is possible, find the minimum required number of operations.
Constraints
* 1 \leq |S| \leq 2 Γ 10^5
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
If we cannot turn S into a palindrome, print `-1`. Otherwise, print the minimum required number of operations.
Examples
Input
eel
Output
1
Input
ataatmma
Output
4
Input
snuke
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int const N = 202000;
char s[N];
deque<int>nex[26];
bool vis[N];
vector<int>ans;
int seg[N*4] , k;
int get(int node , int start , int end){
if(end < k)return 0;
if(start >= k)return seg[node];
int mid = (start+end)/2;
return get(node*2,start,mid) + get(node*2+1,mid+1,end);
}
int up(int node , int start , int end){
if(start==end)seg[node] = 1;
else{
int mid = (start+end)/2;
if(mid >= k)up(node*2,start,mid);
else up(node*2+1,mid+1,end);
seg[node] = seg[node*2] + seg[node*2+1];
}
}
int main()
{
scanf("%s",s);
int len = strlen(s);
int frq[26];
memset(frq,0,sizeof frq);
for(int i = 0 ; i < len ; i++){
nex[s[i]-'a'].push_back(i);
frq[s[i]-'a']++;
}
bool odd = 0;
for(int i = 0 ; i < 26 ; i++){
if(frq[i]%2==1)if(!odd)odd = 1;else {puts("-1");return 0;}
}
string s1 = "";
int l = 0 , r = len-1;
ans.resize(len);
for(int i = 0 ; i < len ; i++){
if(vis[i])continue;
if(frq[s[i]-'a']<=1)continue;
ans[l] = nex[s[i]-'a'].front()+1;
ans[r] = nex[s[i]-'a'].back()+1;
vis[ans[r]-1] = 1;
nex[s[i]-'a'].pop_back();
nex[s[i]-'a'].pop_front();
l++;
r--;
frq[s[i]-'a']-=2;
}
if(odd)for(int i = 0 ; i < 26 ; i++)
if(frq[i]==1)ans[l] = nex[i].front()+1;
ll res = 0;
for(int i = 0 ; i < len ; i++){
k = ans[i];
res += get(1,1,len);
up(1,1,len);
}
printf("%lld\n", res);
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Your friend has a hidden directed graph with n nodes.
Let f(u, v) be true if there is a directed path from node u to node v, and false otherwise. For each pair of distinct nodes, u, v, you know at least one of the three statements is true:
1. <image>
2. <image>
3. <image>
Here AND, OR and XOR mean AND, OR and exclusive OR operations, respectively.
You are given an n by n matrix saying which one of the three statements holds for each pair of vertices. The entry in the u-th row and v-th column has a single character.
1. If the first statement holds, this is represented by the character 'A'.
2. If the second holds, this is represented by the character 'O'.
3. If the third holds, this is represented by the character 'X'.
4. The diagonal of this matrix will only contain the character '-'.
Note that it is possible that a pair of nodes may satisfy multiple statements, in which case, the character given will represent one of the true statements for that pair. This matrix is also guaranteed to be symmetric.
You would like to know if there is a directed graph that is consistent with this matrix. If it is impossible, print the integer -1. Otherwise, print the minimum number of edges that could be consistent with this information.
Input
The first line will contain an integer n (1 β€ n β€ 47), the number of nodes.
The next n lines will contain n characters each: the matrix of what you know about the graph connectivity in the format described in the statement.
Output
Print the minimum number of edges that is consistent with the given information, or -1 if it is impossible.
Examples
Input
4
-AAA
A-AA
AA-A
AAA-
Output
4
Input
3
-XX
X-X
XX-
Output
2
Note
Sample 1: The hidden graph is a strongly connected graph. We can put all four nodes in a cycle.
Sample 2: One valid graph is 3 β 1 β 2. For each distinct pair, exactly one of f(u, v), f(v, u) holds.
### Response
```cpp
#include <bits/stdc++.h>
const int mod = 1000000007;
const int gmod = 3;
const int inf = 1039074182;
const double eps = 1e-9;
const long long llinf = 2LL * inf * inf;
template <typename T1, typename T2>
inline void chmin(T1 &x, T2 b) {
if (b < x) x = b;
}
template <typename T1, typename T2>
inline void chmax(T1 &x, T2 b) {
if (b > x) x = b;
}
inline void chadd(int &x, int b) {
x += b - mod;
x += (x >> 31 & mod);
}
template <typename T1, typename T2>
inline void chadd(T1 &x, T2 b) {
x += b;
if (x >= mod) x -= mod;
}
template <typename T1, typename T2>
inline void chmul(T1 &x, T2 b) {
x = 1LL * x * b % mod;
}
template <typename T1, typename T2>
inline void chmod(T1 &x, T2 b) {
x %= b, x += b;
if (x >= b) x -= b;
}
template <typename T>
inline T mabs(T x) {
return (x < 0 ? -x : x);
}
using namespace std;
using namespace std;
template <typename T>
ostream &operator<<(ostream &cout, vector<T> vec) {
cout << "{";
for (int i = 0; i < (int)vec.size(); i++) {
cout << vec[i];
if (i != (int)vec.size() - 1) cout << ',';
}
cout << "}";
return cout;
}
template <typename T1, typename T2>
ostream &operator<<(ostream &cout, pair<T1, T2> p) {
cout << "(" << p.first << ',' << p.second << ")";
return cout;
}
template <typename T, typename T2>
ostream &operator<<(ostream &cout, set<T, T2> s) {
vector<T> t;
for (auto x : s) t.push_back(x);
cout << t;
return cout;
}
template <typename T, typename T2>
ostream &operator<<(ostream &cout, multiset<T, T2> s) {
vector<T> t;
for (auto x : s) t.push_back(x);
cout << t;
return cout;
}
template <typename T>
ostream &operator<<(ostream &cout, queue<T> q) {
vector<T> t;
while (q.size()) {
t.push_back(q.front());
q.pop();
}
cout << t;
return cout;
}
template <typename T1, typename T2, typename T3>
ostream &operator<<(ostream &cout, map<T1, T2, T3> m) {
for (auto &x : m) {
cout << "Key: " << x.first << ' ' << "Value: " << x.second << endl;
}
return cout;
}
template <typename T1, typename T2>
void operator+=(pair<T1, T2> &x, const pair<T1, T2> y) {
x.first += y.first;
x.second += y.second;
}
template <typename T1, typename T2>
pair<T1, T2> operator+(const pair<T1, T2> &x, const pair<T1, T2> &y) {
return make_pair(x.first + y.first, x.second + y.second);
}
template <typename T1, typename T2>
pair<T1, T2> operator-(const pair<T1, T2> &x, const pair<T1, T2> &y) {
return make_pair(x.first - y.first, x.second - y.second);
}
template <typename T1, typename T2>
pair<T1, T2> operator-(pair<T1, T2> x) {
return make_pair(-x.first, -x.second);
}
template <typename T>
vector<vector<T>> operator~(vector<vector<T>> vec) {
vector<vector<T>> v;
int n = vec.size(), m = vec[0].size();
v.resize(m);
for (int i = 0; i < m; i++) {
v[i].resize(n);
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
v[i][j] = vec[j][i];
}
}
return v;
}
void print0x(int x) {
std::vector<int> vec;
while (x) {
vec.push_back(x & 1);
x >>= 1;
}
std::reverse(vec.begin(), vec.end());
for (int i = 0; i < (int)vec.size(); i++) {
std::cout << vec[i];
}
std::cout << ' ';
}
template <typename T>
void print0x(T x, int len) {
std::vector<int> vec;
while (x) {
vec.push_back(x & 1);
x >>= 1;
}
reverse(vec.begin(), vec.end());
for (int i = (int)vec.size(); i < len; i++) {
putchar('0');
}
for (size_t i = 0; i < vec.size(); i++) {
std::cout << vec[i];
}
std::cout << ' ';
}
vector<string> vec_splitter(string s) {
s += ',';
vector<string> res;
while (!s.empty()) {
res.push_back(s.substr(0, s.find(',')));
s = s.substr(s.find(',') + 1);
}
return res;
}
void debug_out(vector<string> __attribute__((unused)) args,
__attribute__((unused)) int idx,
__attribute__((unused)) int LINE_NUM) {
cerr << endl;
}
template <typename Head, typename... Tail>
void debug_out(vector<string> args, int idx, int LINE_NUM, Head H, Tail... T) {
if (idx > 0)
cerr << ", ";
else
cerr << "Line(" << LINE_NUM << ") ";
stringstream ss;
ss << H;
cerr << args[idx] << " = " << ss.str();
debug_out(args, idx + 1, LINE_NUM, T...);
}
struct DSUAE {
int *f;
inline void clear(int n) {
for (int i = 0; i < n; i++) {
f[i] = i;
}
}
inline void init(int n) {
f = new int[n + 5];
clear(n);
}
inline int find(int x) { return (f[x] == x ? x : f[x] = find(f[x])); }
inline void merge(int x, int y) {
x = find(x);
y = find(y);
if (x == y) return;
if (x & 1)
f[x] = y;
else
f[y] = x;
}
};
struct DSU {
int *f;
int *depth;
int *sz;
inline void clear(int n) {
for (int i = 0; i < n; i++) {
f[i] = i;
depth[i] = 1;
sz[i] = 1;
}
}
inline void init(int n) {
f = new int[n + 5];
depth = new int[n + 5];
sz = new int[n + 5];
clear(n);
}
inline int find(int x) { return (f[x] == x ? x : f[x] = find(f[x])); }
inline int getSize(int x) { return sz[find(x)]; }
inline int merge(int x, int y) {
x = find(x);
y = find(y);
if (x == y) return false;
if (depth[x] > depth[y]) {
f[y] = x;
sz[x] += sz[y];
} else if (depth[y] > depth[x]) {
f[x] = y;
sz[y] += sz[x];
} else {
sz[y] += sz[x];
f[x] = y;
depth[y]++;
}
return true;
}
inline int same(int x, int y) { return (find(x) == find(y)); }
~DSU() {
delete f;
delete depth;
delete sz;
}
};
struct PersistentDSU : public DSU {
int find(int x) { return (x == f[x] ? x : find(f[x])); }
inline int merge(int x, int y) {
x = find(x);
y = find(y);
if (x == y) return false;
if (depth[x] > depth[y]) {
f[y] = x;
sz[x] += sz[y];
} else if (depth[y] > depth[x]) {
f[x] = y;
sz[y] += sz[x];
} else {
sz[y] += sz[x];
f[x] = y;
depth[y]++;
}
return true;
}
};
using namespace std;
int n;
char c[55][55];
DSUAE dsu;
vector<int> scc[55];
vector<vector<int>> a;
int b[55][55];
int p[55];
int main() {
double t = clock();
scanf("%d", &n);
dsu.init(n);
for (int i = 0; i < n; i++) scanf("%s", c[i]);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (c[i][j] == 'A') dsu.merge(i, j);
}
}
for (int i = 0; i < n; i++) scc[dsu.find(i)].push_back(i);
int now = 0;
for (int i = 0; i < n; i++) {
if (scc[i].empty()) continue;
for (auto x : scc[i]) {
for (auto y : scc[i]) {
if (c[x][y] == 'X') {
cout << "-1" << endl;
exit(0);
};
}
}
if (scc[i].size() > 1)
now += scc[i].size();
else
now += 1;
if (scc[i].size() > 1) a.push_back(scc[i]);
}
n = a.size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) continue;
bool noXor = true;
for (auto x : a[i]) {
for (auto y : a[j]) {
noXor &= (c[x][y] != 'X');
}
}
if (!noXor)
b[i][j] = 1;
else
b[i][j] = 0;
}
}
for (int i = 0; i < n; i++) p[i] = i;
int res = inf;
while ((clock() - t) / CLOCKS_PER_SEC <= 0.001) {
random_shuffle(p, p + n);
vector<vector<int>> v;
for (int i = 0; i < n; i++) {
int x = p[i];
int found = false;
for (auto &vv : v) {
int ok = true;
for (auto &u : vv) {
ok &= (b[u][x] == 0);
}
if (ok) {
found = true;
vv.push_back(x);
break;
}
}
if (!found) {
v.push_back(vector<int>{x});
}
}
chmin(res, v.size());
}
cout << res + now - 1 << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Takahashi has an N \times M grid, with N horizontal rows and M vertical columns. Determine if we can place A 1 \times 2 tiles (1 vertical, 2 horizontal) and B 2 \times 1 tiles (2 vertical, 1 horizontal) satisfying the following conditions, and construct one arrangement of the tiles if it is possible:
* All the tiles must be placed on the grid.
* Tiles must not stick out of the grid, and no two different tiles may intersect.
* Neither the grid nor the tiles may be rotated.
* Every tile completely covers exactly two squares.
Constraints
* 1 \leq N,M \leq 1000
* 0 \leq A,B \leq 500000
* N, M, A and B are integers.
Input
Input is given from Standard Input in the following format:
N M A B
Output
If it is impossible to place all the tiles, print `NO`. Otherwise, print the following:
YES
c_{11}...c_{1M}
:
c_{N1}...c_{NM}
Here, c_{ij} must be one of the following characters: `.`, `<`, `>`, `^` and `v`. Represent an arrangement by using each of these characters as follows:
* When c_{ij} is `.`, it indicates that the square at the i-th row and j-th column is empty;
* When c_{ij} is `<`, it indicates that the square at the i-th row and j-th column is covered by the left half of a 1 \times 2 tile;
* When c_{ij} is `>`, it indicates that the square at the i-th row and j-th column is covered by the right half of a 1 \times 2 tile;
* When c_{ij} is `^`, it indicates that the square at the i-th row and j-th column is covered by the top half of a 2 \times 1 tile;
* When c_{ij} is `v`, it indicates that the square at the i-th row and j-th column is covered by the bottom half of a 2 \times 1 tile.
Examples
Input
3 4 4 2
Output
YES
<><>
^<>^
v<>v
Input
4 5 5 3
Output
YES
<>..^
^.<>v
v<>.^
<><>v
Input
7 9 20 20
Output
NO
### Response
```cpp
#include <algorithm>
#include <bitset>
#include <deque>
#include <iostream>
#include <istream>
#include <iterator>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
#define rep(i, n) for(ll i = 0; i < (n); i++)
#define revrep(i, n) for(ll i = (n)-1; i >= 0; i--)
#define pb push_back
#define f first
#define s second
const ll INFL = 1LL << 60;//10^18 = 2^60
//ll MOD = 998244353;
int N, M;
char mp[1010][1010];
int main(){
int A, B;
cin >> N >> M >> A >> B;
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
mp[i][j] = '.';
}
}
if(N % 2){
for(int j = 0; j < M-1; j += 2){
if(A == 0) break;
A--;
mp[N-1][j] = '<';
mp[N-1][j+1] = '>';
}
}
if(M % 2){
for(int i = 0; i < N-1; i += 2){
if(B == 0) break;
B--;
mp[i][M-1] = '^';
mp[i+1][M-1] = 'v';
}
}
if(N % 2 && M % 2){
if(mp[N-1][M-2] == '>'){
mp[N-1][M-1] = '>';
mp[N-1][M-2] = '<';
mp[N-1][M-3] = '.';
}
}
for(int i = 0; i < N-1; i += 2){
for(int j = 0; j < M-1; j += 2){
if(A >= 2){
A -= 2;
mp[i][j] = '<';
mp[i][j+1] = '>';
mp[i+1][j] = '<';
mp[i+1][j+1] = '>';
}else if(B >= 2){
B -= 2;
mp[i][j] = '^';
mp[i+1][j] = 'v';
mp[i][j+1] = '^';
mp[i+1][j+1] = 'v';
}
}
}
for(int i = N-1; i >= 1; i--){
if(B == 0) break;
for(int j = 0; j < M; j++){
if(B == 0) break;
if(mp[i-1][j] == '.' && mp[i][j] == '.'){
mp[i-1][j] = '^';
mp[i][j] = 'v';
B--;
}
}
}
for(int i = 0; i < N; i++){
if(A == 0) break;
for(int j = 0; j < M-1; j++){
if(A == 0) break;
if(mp[i][j] == '.' && mp[i][j+1] == '.'){
mp[i][j] = '<';
mp[i][j+1] = '>';
A--;
}
}
}
if(A || B){
cout << "NO" << endl;
}else{
cout << "YES" << endl;
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
cout << mp[i][j];
}
cout << endl;
}
}
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door:
The cleaning of all evil will awaken the door!
Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells.
The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once.
You would like to purify all n Γ n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell.
Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way.
Input
The first line will contain a single integer n (1 β€ n β€ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise.
Output
If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell.
Examples
Input
3
.E.
E.E
.E.
Output
1 1
2 2
3 3
Input
3
EEE
E..
E.E
Output
-1
Input
5
EE.EE
E.EE.
E...E
.EE.E
EE.EE
Output
3 3
1 3
2 2
4 4
5 3
Note
The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously.
<image>
In the second example, it is impossible to purify the cell located at row 1 and column 1.
For the third example:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, a[10000][1000], res, flag, x[1000], y[1000], cnt;
char q;
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> q;
if (q == '.')
a[i][j] = 1;
else
a[i][j] = 2;
}
scanf("\n");
}
res = n;
cnt = 1;
for (int i = 1; i <= n; i++) {
flag = 0;
for (int j = 1; j <= n; j++)
if (a[j][i] == 1) {
flag = 1;
x[cnt] = j;
y[cnt] = i;
cnt++;
break;
}
if (flag == 0) {
res = -1;
break;
}
}
if (res == n) {
for (int i = 1; i <= n; i++) cout << x[i] << " " << y[i] << "\n";
return 0;
}
res = n;
cnt = 1;
for (int i = 1; i <= n; i++) {
flag = 0;
for (int j = 1; j <= n; j++)
if (a[i][j] == 1) {
flag = 1;
x[cnt] = i;
y[cnt] = j;
cnt++;
break;
}
if (flag == 0) {
res = -1;
break;
}
}
if (res == n) {
for (int i = 1; i <= n; i++) cout << x[i] << " " << y[i] << "\n";
return 0;
}
cout << res;
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
You've got an n Γ m table (n rows and m columns), each cell of the table contains a "0" or a "1".
Your task is to calculate the number of rectangles with the sides that are parallel to the sides of the table and go along the cell borders, such that the number one occurs exactly k times in the rectangle.
Input
The first line contains three space-separated integers n, m and k (1 β€ n, m β€ 2500, 0 β€ k β€ 6) β the sizes of the table and the required number of numbers one.
Next n lines each contains m characters "0" or "1". The i-th character of the j-th line corresponds to the character that is in the j-th row and the i-th column of the table.
Output
Print a single number β the number of rectangles that contain exactly k numbers one.
Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
3 3 2
101
000
101
Output
8
Input
5 5 1
00000
00000
00100
00000
00000
Output
81
Input
5 5 6
01010
10101
01010
10101
01010
Output
12
Input
3 3 0
001
010
000
Output
15
Input
4 4 0
0000
0101
0000
0000
Output
52
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m, k;
int sum[2505][2505], f[2][10];
char s[2505];
long long ans;
int get(int l1, int r1, int l2, int r2) {
return sum[l2][r2] - sum[l2][r1] - sum[l1][r2] + sum[l1][r1];
}
void solve(int l1, int r1, int l2, int r2, int flg) {
if (l1 == l2 || r1 == r2) return;
if (l1 + 1 == l2 && r1 + 1 == r2) {
ans += (get(l1, r1, l2, r2) == k);
return;
}
if (!flg) {
int mid = (l1 + l2) >> 1, i, j, l;
solve(l1, r1, mid, r2, flg ^ 1);
solve(mid, r1, l2, r2, flg ^ 1);
for (i = r1; i < r2; i++) {
f[0][0] = f[1][0] = mid;
for (l = 1; l <= k + 1; l++) f[0][l] = l1, f[1][l] = l2;
for (j = i + 1; j <= r2; j++) {
for (l = 1; l <= k + 1; l++) {
while (get(f[0][l], i, mid, j) >= l) f[0][l]++;
while (get(mid, i, f[1][l], j) >= l) f[1][l]--;
}
for (l = 0; l <= k; l++)
ans +=
1ll * (f[0][l] - f[0][l + 1]) * (f[1][k - l + 1] - f[1][k - l]);
}
}
} else {
int mid = (r1 + r2) >> 1, i, j, l;
solve(l1, r1, l2, mid, flg ^ 1);
solve(l1, mid, l2, r2, flg ^ 1);
for (i = l1; i < l2; i++) {
f[0][0] = f[1][0] = mid;
for (l = 1; l <= k + 1; l++) f[0][l] = r1, f[1][l] = r2;
for (j = i + 1; j <= l2; j++) {
for (l = 1; l <= k + 1; l++) {
while (get(i, f[0][l], j, mid) >= l) f[0][l]++;
while (get(i, mid, j, f[1][l]) >= l) f[1][l]--;
}
for (l = 0; l <= k; l++)
ans +=
1ll * (f[0][l] - f[0][l + 1]) * (f[1][k - l + 1] - f[1][k - l]);
}
}
}
}
int main() {
int i, j;
scanf("%d%d%d", &n, &m, &k);
for (i = 1; i <= n; i++) {
scanf("%s", s + 1);
for (j = 1; j <= m; j++)
sum[i][j] = sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + s[j] - 48;
}
solve(0, 0, n, m, 0);
printf("%I64d", ans);
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
I guess there's not much point in reminding you that Nvodsk winters aren't exactly hot. That increased the popularity of the public transport dramatically. The route of bus 62 has exactly n stops (stop 1 goes first on its way and stop n goes last). The stops are positioned on a straight line and their coordinates are 0 = x1 < x2 < ... < xn.
Each day exactly m people use bus 62. For each person we know the number of the stop where he gets on the bus and the number of the stop where he gets off the bus. A ticket from stop a to stop b (a < b) costs xb - xa rubles. However, the conductor can choose no more than one segment NOT TO SELL a ticket for. We mean that conductor should choose C and D (Π‘ <= D) and sell a ticket for the segments [A, C] and [D, B], or not sell the ticket at all. The conductor and the passenger divide the saved money between themselves equally. The conductor's "untaxed income" is sometimes interrupted by inspections that take place as the bus drives on some segment of the route located between two consecutive stops. The inspector fines the conductor by c rubles for each passenger who doesn't have the ticket for this route's segment.
You know the coordinated of all stops xi; the numbers of stops where the i-th passenger gets on and off, ai and bi (ai < bi); the fine c; and also pi β the probability of inspection on segment between the i-th and the i + 1-th stop. The conductor asked you to help him make a plan of selling tickets that maximizes the mathematical expectation of his profit.
Input
The first line contains three integers n, m and c (2 β€ n β€ 150 000, 1 β€ m β€ 300 000, 1 β€ c β€ 10 000).
The next line contains n integers xi (0 β€ xi β€ 109, x1 = 0, xi < xi + 1) β the coordinates of the stops on the bus's route.
The third line contains n - 1 integer pi (0 β€ pi β€ 100) β the probability of inspection in percents on the segment between stop i and stop i + 1.
Then follow m lines that describe the bus's passengers. Each line contains exactly two integers ai and bi (1 β€ ai < bi β€ n) β the numbers of stops where the i-th passenger gets on and off.
Output
Print the single real number β the maximum expectation of the conductor's profit. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>.
Examples
Input
3 3 10
0 10 100
100 0
1 2
2 3
1 3
Output
90.000000000
Input
10 8 187
0 10 30 70 150 310 630 1270 2550 51100
13 87 65 0 100 44 67 3 4
1 10
2 9
3 8
1 5
6 10
2 7
4 10
4 5
Output
76859.990000000
Note
A comment to the first sample:
The first and third passengers get tickets from stop 1 to stop 2. The second passenger doesn't get a ticket. There always is inspection on the segment 1-2 but both passengers have the ticket for it. There never is an inspection on the segment 2-3, that's why the second passenger gets away with the cheating. Our total profit is (0 + 90 / 2 + 90 / 2) = 90.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct node {
double l, c, r, t;
int a, b;
} tree[4 * 150000];
double expv[150000];
void build(int x, int a, int b) {
tree[x].a = a;
tree[x].b = b;
if (tree[x].a != tree[x].b) {
build(2 * x, a, (a + b) / 2);
build(2 * x + 1, (a + b) / 2 + 1, b);
tree[x].l = max(tree[2 * x].l, tree[2 * x].t + tree[2 * x + 1].l);
tree[x].t = tree[2 * x].t + tree[2 * x + 1].t;
tree[x].r = max(tree[2 * x + 1].r, tree[2 * x + 1].t + tree[2 * x].r);
tree[x].c = max(tree[2 * x].r + tree[2 * x + 1].l,
max(tree[2 * x].c, tree[2 * x + 1].c));
} else
tree[x].c = max(0.0, tree[x].l = tree[x].t = tree[x].r = expv[tree[x].a]);
}
node query(int x, int a, int b) {
node ans;
ans.l = -1;
if (a > tree[x].b || b < tree[x].a) return ans;
if (a <= tree[x].a && tree[x].b <= b) return tree[x];
node a1 = query(2 * x, a, b), a2 = query(2 * x + 1, a, b);
ans.l = max(a1.l, a1.t + a2.l);
ans.t = a1.t + a2.t;
ans.r = max(a2.r, a2.t + a1.r);
ans.c = max(a1.r + a2.l, max(a1.c, a2.c));
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int n, m, c;
cin >> n >> m >> c;
double x[n];
for (int i = 0; i < n; i++) cin >> x[i];
for (int i = 0; i < n - 1; i++) {
double p;
cin >> p;
expv[i] = (x[i + 1] - x[i]) * 0.5 - c * p * 0.01;
}
build(1, 0, n - 2);
double ans = 0;
while (m--) {
int a, b;
cin >> a >> b;
a--;
b -= 2;
node n = query(1, a, b);
ans += n.c;
}
cout << fixed << setprecision(7) << ans << endl;
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Cowboy Beblop is a funny little boy who likes sitting at his computer. He somehow obtained two elastic hoops in the shape of 2D polygons, which are not necessarily convex. Since there's no gravity on his spaceship, the hoops are standing still in the air. Since the hoops are very elastic, Cowboy Beblop can stretch, rotate, translate or shorten their edges as much as he wants.
For both hoops, you are given the number of their vertices, as well as the position of each vertex, defined by the X , Y and Z coordinates. The vertices are given in the order they're connected: the 1st vertex is connected to the 2nd, which is connected to the 3rd, etc., and the last vertex is connected to the first one. Two hoops are connected if it's impossible to pull them to infinity in different directions by manipulating their edges, without having their edges or vertices intersect at any point β just like when two links of a chain are connected. The polygons' edges do not intersect or overlap.
To make things easier, we say that two polygons are well-connected, if the edges of one polygon cross the area of the other polygon in two different directions (from the upper and lower sides of the plane defined by that polygon) a different number of times.
Cowboy Beblop is fascinated with the hoops he has obtained and he would like to know whether they are well-connected or not. Since heβs busy playing with his dog, Zwei, heβd like you to figure it out for him. He promised you some sweets if you help him!
Input
The first line of input contains an integer n (3 β€ n β€ 100 000), which denotes the number of edges of the first polygon. The next N lines each contain the integers x, y and z ( - 1 000 000 β€ x, y, z β€ 1 000 000) β coordinates of the vertices, in the manner mentioned above. The next line contains an integer m (3 β€ m β€ 100 000) , denoting the number of edges of the second polygon, followed by m lines containing the coordinates of the second polygonβs vertices.
It is guaranteed that both polygons are simple (no self-intersections), and in general that the obtained polygonal lines do not intersect each other. Also, you can assume that no 3 consecutive points of a polygon lie on the same line.
Output
Your output should contain only one line, with the words "YES" or "NO", depending on whether the two given polygons are well-connected.
Example
Input
4
0 0 0
2 0 0
2 2 0
0 2 0
4
1 1 -1
1 1 1
1 3 1
1 3 -1
Output
YES
Note
On the picture below, the two polygons are well-connected, as the edges of the vertical polygon cross the area of the horizontal one exactly once in one direction (for example, from above to below), and zero times in the other (in this case, from below to above). Note that the polygons do not have to be parallel to any of the xy-,xz-,yz- planes in general. <image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
tuple<double, double> simultaneous_equation(double a, double b, double c,
double d, double u, double v) {
return make_tuple((u * d - b * v) / (a * d - b * c),
(a * v - u * c) / (a * d - b * c));
}
tuple<double, double, double> cross_product(double x1, double y1, double z1,
double x2, double y2, double z2) {
return make_tuple(y1 * z2 - y2 * z1, z1 * x2 - z2 * x1, x1 * y2 - x2 * y1);
}
double dot_product(double x1, double y1, double z1, double x2, double y2,
double z2) {
return x1 * x2 + y1 * y2 + z1 * z2;
}
int main(int argc, char const *argv[]) {
int n, m;
scanf("%d", &n);
double x1[n], y1[n], z1[n];
tuple<double, double, double> normal1;
for (int i = 0; i < n; i++) {
scanf("%lf %lf %lf", &x1[i], &y1[i], &z1[i]);
if (i == 2) {
normal1 = cross_product(x1[1] - x1[0], y1[1] - y1[0], z1[1] - z1[0],
x1[2] - x1[1], y1[2] - y1[1], z1[2] - z1[1]);
}
}
scanf("%d", &m);
double x2[m], y2[m], z2[m];
tuple<double, double, double> normal2;
for (int i = 0; i < m; i++) {
scanf("%lf %lf %lf", &x2[i], &y2[i], &z2[i]);
if (i == 2) {
normal2 = cross_product(x2[1] - x2[0], y2[1] - y2[0], z2[1] - z2[0],
x2[2] - x2[1], y2[2] - y2[1], z2[2] - z2[1]);
}
}
tuple<double, double, double> intersection_vector =
cross_product(get<0>(normal1), get<1>(normal1), get<2>(normal1),
get<0>(normal2), get<1>(normal2), get<2>(normal2));
double a1 = get<0>(normal1);
double b1 = get<1>(normal1);
double c1 = get<2>(normal1);
double d1 = -(get<0>(normal1) * x1[0] + get<1>(normal1) * y1[0] +
get<2>(normal1) * z1[0]);
double a2 = get<0>(normal2);
double b2 = get<1>(normal2);
double c2 = get<2>(normal2);
double d2 = -(get<0>(normal2) * x2[0] + get<1>(normal2) * y2[0] +
get<2>(normal2) * z2[0]);
double intersection_x;
double intersection_y;
double intersection_z;
double max = 0;
if (abs(get<0>(intersection_vector)) > max) {
max = abs(get<0>(intersection_vector));
intersection_x = 0;
intersection_y = (c1 * d2 - c2 * d1) / (b1 * c2 - b2 * c1);
intersection_z = (b2 * d1 - b1 * d2) / (b1 * c2 - b2 * c1);
}
if (abs(get<1>(intersection_vector)) > max) {
max = abs(get<1>(intersection_vector));
intersection_x = (c1 * d2 - c2 * d1) / (a1 * c2 - a2 * c1);
intersection_y = 0;
intersection_z = (a2 * d1 - a1 * d2) / (a1 * c2 - a2 * c1);
}
if (abs(get<2>(intersection_vector)) > max) {
max = abs(get<2>(intersection_vector));
intersection_x = (b1 * d2 - b2 * d1) / (a1 * b2 - a2 * b1);
intersection_y = (a2 * d1 - a1 * d2) / (a1 * b2 - a2 * b1);
intersection_z = 0;
}
tuple<double, double, double> intersection_normal_1 =
cross_product(get<0>(normal1), get<1>(normal1), get<2>(normal1),
get<0>(intersection_vector), get<1>(intersection_vector),
get<2>(intersection_vector));
tuple<double, double, double> intersection_normal_2 =
cross_product(get<0>(normal2), get<1>(normal2), get<2>(normal2),
get<0>(intersection_vector), get<1>(intersection_vector),
get<2>(intersection_vector));
int sign1[n];
for (int i = 0; i < n; i++) {
if (dot_product(x1[i] - intersection_x, y1[i] - intersection_y,
z1[i] - intersection_z, get<0>(intersection_normal_1),
get<1>(intersection_normal_1),
get<2>(intersection_normal_1)) > 0) {
sign1[i] = 1;
} else if (dot_product(x1[i] - intersection_x, y1[i] - intersection_y,
z1[i] - intersection_z,
get<0>(intersection_normal_1),
get<1>(intersection_normal_1),
get<2>(intersection_normal_1)) < 0) {
sign1[i] = -1;
} else {
sign1[i] = 0;
}
}
int sign2[m];
for (int i = 0; i < m; i++) {
if (dot_product(x2[i] - intersection_x, y2[i] - intersection_y,
z2[i] - intersection_z, get<0>(intersection_normal_2),
get<1>(intersection_normal_2),
get<2>(intersection_normal_2)) > 0) {
sign2[i] = 1;
} else if (dot_product(x2[i] - intersection_x, y2[i] - intersection_y,
z2[i] - intersection_z,
get<0>(intersection_normal_2),
get<1>(intersection_normal_2),
get<2>(intersection_normal_2)) < 0) {
sign2[i] = -1;
} else {
sign2[i] = 0;
}
}
vector<pair<double, int>> intersection_list_1;
for (int i = 0; i < n; i++) {
int previous_i = i - 1;
int current_i = i;
int next_i = i + 1;
int next_next_i = i + 2;
if (i == 0) {
previous_i = n - 1;
} else if (i == n - 1) {
next_i = 0;
next_next_i = 1;
} else if (i == n - 2) {
next_next_i = 0;
}
if (sign1[current_i] * sign1[next_i] == -1) {
double multiplier;
if (!isnan(get<1>(simultaneous_equation(
x1[current_i] - x1[next_i], -get<0>(intersection_vector),
y1[current_i] - y1[next_i], -get<1>(intersection_vector),
intersection_x - x1[current_i],
intersection_y - y1[current_i])))) {
multiplier = get<1>(simultaneous_equation(
x1[current_i] - x1[next_i], -get<0>(intersection_vector),
y1[current_i] - y1[next_i], -get<1>(intersection_vector),
intersection_x - x1[current_i], intersection_y - y1[current_i]));
} else if (!isnan(get<1>(simultaneous_equation(
y1[current_i] - y1[next_i], -get<1>(intersection_vector),
z1[current_i] - z1[next_i], -get<2>(intersection_vector),
intersection_y - y1[current_i],
intersection_z - z1[current_i])))) {
multiplier = get<1>(simultaneous_equation(
y1[current_i] - y1[next_i], -get<1>(intersection_vector),
z1[current_i] - z1[next_i], -get<2>(intersection_vector),
intersection_y - y1[current_i], intersection_z - z1[current_i]));
} else if (!isnan(get<1>(simultaneous_equation(
z1[current_i] - z1[next_i], -get<2>(intersection_vector),
x1[current_i] - x1[next_i], -get<0>(intersection_vector),
intersection_z - z1[current_i],
intersection_x - x1[current_i])))) {
multiplier = get<1>(simultaneous_equation(
z1[current_i] - z1[next_i], -get<2>(intersection_vector),
x1[current_i] - x1[next_i], -get<0>(intersection_vector),
intersection_z - z1[current_i], intersection_x - x1[current_i]));
}
intersection_list_1.push_back(pair<double, int>(
dot_product(get<0>(intersection_vector) * multiplier + intersection_x,
get<1>(intersection_vector) * multiplier + intersection_y,
get<2>(intersection_vector) * multiplier + intersection_z,
get<0>(intersection_vector), get<1>(intersection_vector),
get<2>(intersection_vector)),
1));
} else if ((sign1[current_i] == 0 &&
sign1[previous_i] * sign1[next_i] == -1) ||
(n >= 4 && sign1[current_i] == 0 && sign1[next_i] == 0 &&
sign1[previous_i] * sign1[next_next_i] == -1)) {
intersection_list_1.push_back(pair<double, int>(
dot_product(x1[current_i], y1[current_i], z1[current_i],
get<0>(intersection_vector), get<1>(intersection_vector),
get<2>(intersection_vector)),
1));
}
}
vector<pair<double, int>> intersection_list_2;
for (int i = 0; i < m; i++) {
int previous_i = i - 1;
int current_i = i;
int next_i = i + 1;
int next_next_i = i + 2;
if (i == 0) {
previous_i = m - 1;
} else if (i == m - 1) {
next_i = 0;
next_next_i = 1;
} else if (i == m - 2) {
next_next_i = 0;
}
if (sign2[current_i] * sign2[next_i] == -1) {
double multiplier;
if (!isnan(get<1>(simultaneous_equation(
x2[current_i] - x2[next_i], -get<0>(intersection_vector),
y2[current_i] - y2[next_i], -get<1>(intersection_vector),
intersection_x - x2[current_i],
intersection_y - y2[current_i])))) {
multiplier = get<1>(simultaneous_equation(
x2[current_i] - x2[next_i], -get<0>(intersection_vector),
y2[current_i] - y2[next_i], -get<1>(intersection_vector),
intersection_x - x2[current_i], intersection_y - y2[current_i]));
} else if (!isnan(get<1>(simultaneous_equation(
y2[current_i] - y2[next_i], -get<1>(intersection_vector),
z2[current_i] - z2[next_i], -get<2>(intersection_vector),
intersection_y - y2[current_i],
intersection_z - z2[current_i])))) {
multiplier = get<1>(simultaneous_equation(
y2[current_i] - y2[next_i], -get<1>(intersection_vector),
z2[current_i] - z2[next_i], -get<2>(intersection_vector),
intersection_y - y2[current_i], intersection_z - z2[current_i]));
} else if (!isnan(get<1>(simultaneous_equation(
z2[current_i] - z2[next_i], -get<2>(intersection_vector),
x2[current_i] - x2[next_i], -get<0>(intersection_vector),
intersection_z - z2[current_i],
intersection_x - x2[current_i])))) {
multiplier = get<1>(simultaneous_equation(
z2[current_i] - z2[next_i], -get<2>(intersection_vector),
x2[current_i] - x2[next_i], -get<0>(intersection_vector),
intersection_z - z2[current_i], intersection_x - x2[current_i]));
}
intersection_list_2.push_back(pair<double, int>(
dot_product(get<0>(intersection_vector) * multiplier + intersection_x,
get<1>(intersection_vector) * multiplier + intersection_y,
get<2>(intersection_vector) * multiplier + intersection_z,
get<0>(intersection_vector), get<1>(intersection_vector),
get<2>(intersection_vector)),
2));
} else if ((sign2[current_i] == 0 &&
sign2[previous_i] * sign2[next_i] == -1) ||
(m >= 4 && sign2[current_i] == 0 && sign2[next_i] == 0 &&
sign2[previous_i] * sign2[next_next_i] == -1)) {
intersection_list_2.push_back(pair<double, int>(
dot_product(x2[current_i], y2[current_i], z2[current_i],
get<0>(intersection_vector), get<1>(intersection_vector),
get<2>(intersection_vector)),
2));
}
}
intersection_list_1.insert(intersection_list_1.end(),
intersection_list_2.begin(),
intersection_list_2.end());
sort(intersection_list_1.begin(), intersection_list_1.end());
vector<int> result_list;
while (!intersection_list_1.empty()) {
if (result_list.empty() ||
(!result_list.empty() &&
intersection_list_1.back().second != result_list.back())) {
result_list.push_back(intersection_list_1.back().second);
} else if (!result_list.empty() &&
intersection_list_1.back().second == result_list.back()) {
result_list.pop_back();
}
intersection_list_1.pop_back();
}
if (result_list.empty()) {
cout << "NO" << endl;
} else {
cout << "YES" << endl;
}
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Nauuo is a girl who loves playing chess.
One day she invented a game by herself which needs n chess pieces to play on a mΓ m chessboard. The rows and columns are numbered from 1 to m. We denote a cell on the intersection of the r-th row and c-th column as (r,c).
The game's goal is to place n chess pieces numbered from 1 to n on the chessboard, the i-th piece lies on (r_i,\,c_i), while the following rule is satisfied: for all pairs of pieces i and j, |r_i-r_j|+|c_i-c_j|β₯|i-j|. Here |x| means the absolute value of x.
However, Nauuo discovered that sometimes she couldn't find a solution because the chessboard was too small.
She wants to find the smallest chessboard on which she can put n pieces according to the rules.
She also wonders how to place the pieces on such a chessboard. Can you help her?
Input
The only line contains a single integer n (1β€ nβ€ 1000) β the number of chess pieces for the game.
Output
The first line contains a single integer β the minimum value of m, where m is the length of sides of the suitable chessboard.
The i-th of the next n lines contains two integers r_i and c_i (1β€ r_i,c_iβ€ m) β the coordinates of the i-th chess piece.
If there are multiple answers, print any.
Examples
Input
2
Output
2
1 1
1 2
Input
4
Output
3
1 1
1 3
3 1
3 3
Note
In the first example, you can't place the two pieces on a 1Γ1 chessboard without breaking the rule. But you can place two pieces on a 2Γ2 chessboard like this:
<image>
In the second example, you can't place four pieces on a 2Γ2 chessboard without breaking the rule. For example, if you place the pieces like this:
<image>
then |r_1-r_3|+|c_1-c_3|=|1-2|+|1-1|=1, |1-3|=2, 1<2; and |r_1-r_4|+|c_1-c_4|=|1-2|+|1-2|=2, |1-4|=3, 2<3. It doesn't satisfy the rule.
However, on a 3Γ3 chessboard, you can place four pieces like this:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
int m = (n + 1) / 2;
if (n % 2 == 0) m++;
cout << m << "\n";
int a[m][m], i, j;
memset(a, 0, sizeof(a));
for (i = 0; i < m; i++) a[0][i] = 1;
int tot = n - m;
i = 1;
while (tot--) {
a[i][m - 1] = 1;
i++;
}
for (i = 0; i < m; i++) {
for (j = 0; j < m; j++) {
if (a[i][j] != 0) {
cout << i + 1 << " " << j + 1 << "\n";
}
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
;
int tc = 0;
if (tc) {
int tcs;
cin >> tcs;
while (tcs--) solve();
} else
solve();
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Making Lunch Boxes
Taro has been hooked on making lunch boxes recently. Taro has obtained a new lunch box recipe book today, and wants to try as many of the recipes listed in the book as possible.
Enough of the ingredients for all the recipes are at hand, but they all are in vacuum packs of two. If only one of them is used leaving the other, the leftover will be rotten easily, but making two of the same recipe is not interesting. Thus he decided to make a set of lunch boxes, each with different recipe, that wouldn't leave any unused ingredients.
Note that the book may include recipes for different lunch boxes made of the same set of ingredients.
How many lunch box recipes can Taro try today at most following his dogma?
Input
The input consists of at most 50 datasets, each in the following format.
n m
b1,1...b1,m
...
bn,1...bn,m
The first line contains n, which is the number of recipes listed in the book, and m, which is the number of ingredients. Both n and m are positive integers and satisfy 1 β€ n β€ 500, 1 β€ m β€ 500 and 1 β€ n Γ m β€ 500. The following n lines contain the information for each recipe with the string of length m consisting of 0 or 1. bi,j implies whether the i-th recipe needs the j-th ingredient. 1 means the ingredient is needed for the recipe and 0 means not. Each line contains at least one 1.
The end of the input is indicated by a line containing two zeros.
Output
For each dataset, output the maximum number of recipes Taro can try.
Sample Input
4 3
110
101
011
110
7 1
1
1
1
1
1
1
1
4 5
10000
01000
00100
00010
6 6
111111
011000
100000
000010
100001
100100
0 0
Output for the Sample Input
3
6
0
6
Example
Input
4 3
110
101
011
110
7 1
1
1
1
1
1
1
1
4 5
10000
01000
00100
00010
6 6
111111
011000
100000
000010
100001
100100
0 0
Output
3
6
0
6
### Response
```cpp
#include <bits/stdc++.h>
#define ll long long
#define INF 1000000005
#define MOD 1000000007
#define EPS 1e-10
#define rep(i,n) for(int i=0;i<(int)(n);++i)
#define rrep(i,n) for(int i=(int)(n)-1;i>=0;--i)
#define srep(i,s,t) for(int i=(int)(s);i<(int)(t);++i)
#define each(a,b) for(auto (a): (b))
#define all(v) (v).begin(),(v).end()
#define len(v) (int)(v).size()
#define zip(v) sort(all(v)),v.erase(unique(all(v)),v.end())
#define cmx(x,y) x=max(x,y)
#define cmn(x,y) x=min(x,y)
#define fi first
#define se second
#define pb push_back
#define show(x) cout<<#x<<" = "<<(x)<<endl
#define spair(p) cout<<#p<<": "<<p.fi<<" "<<p.se<<endl
#define svec(v) cout<<#v<<":";rep(kbrni,v.size())cout<<" "<<v[kbrni];cout<<endl
#define sset(s) cout<<#s<<":";each(kbrni,s)cout<<" "<<kbrni;cout<<endl
#define smap(m) cout<<#m<<":";each(kbrni,m)cout<<" {"<<kbrni.first<<":"<<kbrni.second<<"}";cout<<endl
using namespace std;
typedef pair<int,int> P;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<double> vd;
typedef vector<P> vp;
typedef vector<string> vs;
const int MAX_N = 100005;
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
while(1){
int n,m;
cin >> n >> m;
if(n == 0 && m == 0){
break;
}
vvi vec(n,vi(m));
string s;
rep(i,n){
cin >> s;
rep(j,m){
vec[i][j] = s[j]-'0';
}
}
int ans = 0;
if(n <= 16){
rep(i,(1 << n)){
vi v(m,0);
rep(j,n){
if((i >> j)&1){
rep(k,m){
v[k] ^= vec[j][k];
}
}
}
bool flag = true;
rep(j,m){
if(v[j] != 0){
flag = false;
break;
}
}
if(flag){
cmx(ans,__builtin_popcount(i));
}
}
cout << ans << "\n";
}else{
vl val(n);
rep(i,n){
// svec(vec[i]);
rep(j,m){
val[i] += ((ll)vec[i][j] << j);
}
}
// svec(val);
map<ll,int> mp;
mp[0] = 0;
rep(i,n){
map<ll,int> mp2;
each(it,mp){
mp2[it.fi] = max(mp[it.fi],mp2[it.fi]);
mp2[it.fi^val[i]] = max(it.se+1,mp2[it.fi^val[i]]);
}
mp = mp2;
}
cout << mp[0] << "\n";
}
}
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Petya loves volleyball very much. One day he was running late for a volleyball match. Petya hasn't bought his own car yet, that's why he had to take a taxi. The city has n junctions, some of which are connected by two-way roads. The length of each road is defined by some positive integer number of meters; the roads can have different lengths.
Initially each junction has exactly one taxi standing there. The taxi driver from the i-th junction agrees to drive Petya (perhaps through several intermediate junctions) to some other junction if the travel distance is not more than ti meters. Also, the cost of the ride doesn't depend on the distance and is equal to ci bourles. Taxis can't stop in the middle of a road. Each taxi can be used no more than once. Petya can catch taxi only in the junction, where it stands initially.
At the moment Petya is located on the junction x and the volleyball stadium is on the junction y. Determine the minimum amount of money Petya will need to drive to the stadium.
Input
The first line contains two integers n and m (1 β€ n β€ 1000, 0 β€ m β€ 1000). They are the number of junctions and roads in the city correspondingly. The junctions are numbered from 1 to n, inclusive. The next line contains two integers x and y (1 β€ x, y β€ n). They are the numbers of the initial and final junctions correspondingly. Next m lines contain the roads' description. Each road is described by a group of three integers ui, vi, wi (1 β€ ui, vi β€ n, 1 β€ wi β€ 109) β they are the numbers of the junctions connected by the road and the length of the road, correspondingly. The next n lines contain n pairs of integers ti and ci (1 β€ ti, ci β€ 109), which describe the taxi driver that waits at the i-th junction β the maximum distance he can drive and the drive's cost. The road can't connect the junction with itself, but between a pair of junctions there can be more than one road. All consecutive numbers in each line are separated by exactly one space character.
Output
If taxis can't drive Petya to the destination point, print "-1" (without the quotes). Otherwise, print the drive's minimum cost.
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
4 4
1 3
1 2 3
1 4 1
2 4 1
2 3 5
2 7
7 2
1 2
7 7
Output
9
Note
An optimal way β ride from the junction 1 to 2 (via junction 4), then from 2 to 3. It costs 7+2=9 bourles.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int mxN = 1e3 + 3;
int edges[mxN][mxN], maxPath[mxN], n, m, d, s;
long long APSP[mxN][mxN], dis[mxN], cost[mxN];
struct edge {
int from, to;
long long weight;
edge() {}
edge(int f, int t, long long w) : from(f), to(t), weight(w) {}
bool operator<(const edge &rhs) const { return weight > rhs.weight; }
};
vector<edge> adj[mxN];
bool ok;
void Dijkstra(int node) {
priority_queue<edge> pq;
pq.push(edge(-1, node, 0));
for (int i = 1; i <= n; ++i) dis[i] = 1e18;
while (!pq.empty()) {
edge e = pq.top();
pq.pop();
if (e.weight > dis[e.to]) continue;
if (!ok) APSP[node][e.to] = e.weight;
dis[e.to] = e.weight;
for (edge &x : adj[e.to]) {
if (ok) {
if (maxPath[e.to] >= APSP[e.to][x.to] &&
e.weight + x.weight < dis[x.to])
pq.push(edge(e.to, x.to, e.weight + x.weight));
} else if (e.weight + x.weight < dis[x.to])
pq.push(edge(e.to, x.to, e.weight + x.weight));
}
}
}
int main() {
cin >> n >> m >> s >> d;
memset(edges, 0x3F, sizeof edges);
while (m--) {
int u, v, w;
cin >> u >> v >> w;
edges[u][v] = min(edges[u][v], w);
edges[v][u] = edges[u][v];
}
for (int i = 1; i <= n; ++i) cin >> maxPath[i] >> cost[i];
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j)
if (edges[i][j] <= 1e9) adj[i].push_back(edge(i, j, edges[i][j]));
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j) APSP[i][j] = 1e18;
for (int i = 1; i <= n; ++i) Dijkstra(i);
for (int i = 1; i <= n; ++i) {
adj[i].clear();
for (int j = 1; j <= n; ++j)
if (APSP[i][j] != 1e18) adj[i].push_back(edge(i, j, cost[i]));
}
ok = true;
Dijkstra(s);
cout << (dis[d] == 1e18 ? -1 : dis[d]);
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
We have a set S of N points in a two-dimensional plane. The coordinates of the i-th point are (x_i, y_i). The N points have distinct x-coordinates and distinct y-coordinates.
For a non-empty subset T of S, let f(T) be the number of points contained in the smallest rectangle, whose sides are parallel to the coordinate axes, that contains all the points in T. More formally, we define f(T) as follows:
* f(T) := (the number of integers i (1 \leq i \leq N) such that a \leq x_i \leq b and c \leq y_i \leq d, where a, b, c, and d are the minimum x-coordinate, the maximum x-coordinate, the minimum y-coordinate, and the maximum y-coordinate of the points in T)
Find the sum of f(T) over all non-empty subset T of S. Since it can be enormous, print the sum modulo 998244353.
Constraints
* 1 \leq N \leq 2 \times 10^5
* -10^9 \leq x_i, y_i \leq 10^9
* x_i \neq x_j (i \neq j)
* y_i \neq y_j (i \neq 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 sum of f(T) over all non-empty subset T of S, modulo 998244353.
Examples
Input
3
-1 3
2 1
3 -2
Output
13
Input
4
1 4
2 1
3 3
4 2
Output
34
Input
10
19 -11
-3 -12
5 3
3 -15
8 -14
-9 -20
10 -9
0 2
-7 17
6 -6
Output
7222
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
const int maxn = 2e5 + 5;
int Bit[maxn], A[maxn], n;
pair<int, int> p[maxn];
void Update(int i) {
while(i <= n) {
Bit[i]++;
i += i&(-i);
}
}
int Getsum(int i) {
int res = 0;
while(i) {
res += Bit[i];
i -= i&(-i);
}
return res;
}
int main() {
scanf("%d", &n);
for(int i = 0; i < n; i++)
scanf("%d%d", &p[i].first, &p[i].second);
sort(p, p+n);
for(int i = 0; i < n; i++) {
p[i].first = p[i].second;
p[i].second = i;
}
sort(p, p+n);
A[0] = 1;
for(int i = 1; i <= n; i++) {
A[i] = A[i-1]<<1;
if(A[i] >= MOD) A[i] -= MOD;
}
int ans = 0;
for(int i = 0; i < n; i++) {
int t = Getsum(p[i].second+1);
int a = A[t], b = A[p[i].second-t], c = A[i-t], d = A[n-1-(i+p[i].second-t)];
ans = ((long long)(a+d-1)*(b+c-1)%MOD + ans) % MOD;
Update(p[i].second+1);
}
ans = ((long long)n*A[n] - ans) % MOD;
printf("%d", (ans+MOD)%MOD);
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.
Roger Waters has a square grid of size nΓ n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it.
Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'.
For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4)
The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n).
We can show that there always exists a solution for the given constraints.
Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 50). Description of the test cases follows.
The first line of each test case contains one integers n (3 β€ n β€ 200).
The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'.
The sum of values of n doesn't exceed 200.
Output
For each test case output on the first line an integer c (0 β€ c β€ 2) β the number of inverted cells.
In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n).
Example
Input
3
4
S010
0001
1000
111F
3
S10
101
01F
5
S0101
00000
01111
11111
0001F
Output
1
3 4
2
1 2
2 1
0
Note
For the first test case, after inverting the cell, we get the following grid:
S010
0001
1001
111F
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long a;
cin >> a;
for (long long i = 0; i < a; i++) {
long long b;
cin >> b;
string s[b + 1];
for (long long j = 0; j < b; j++) {
cin >> s[j];
}
vector<pair<long long, long long>> ans;
if (s[0][1] == s[1][0]) {
if (s[b - 1][b - 2] == s[0][1]) {
ans.push_back({b - 1, b - 2});
}
if (s[b - 2][b - 1] == s[0][1]) {
ans.push_back({b - 2, b - 1});
}
} else {
if (s[b - 1][b - 2] == s[b - 2][b - 1]) {
if (s[0][1] == s[b - 1][b - 2]) {
ans.push_back({0, 1});
}
if (s[b - 2][b - 1] == s[1][0]) {
ans.push_back({1, 0});
}
} else {
if (s[0][1] == '1') {
ans.push_back({0, 1});
} else {
ans.push_back({1, 0});
}
if (s[b - 1][b - 2] == '0') {
ans.push_back({b - 1, b - 2});
} else {
ans.push_back({b - 2, b - 1});
}
}
}
cout << ans.size() << "\n";
for (long long j = 0; j < ans.size(); j++) {
cout << ans[j].first + 1 << " " << ans[j].second + 1 << "\n";
}
}
}
``` |
### Prompt
Create a solution in CPP for the following problem:
You are given an array a, consisting of n positive integers.
Let's call a concatenation of numbers x and y the number that is obtained by writing down numbers x and y one right after another without changing the order. For example, a concatenation of numbers 12 and 3456 is a number 123456.
Count the number of ordered pairs of positions (i, j) (i β j) in array a such that the concatenation of a_i and a_j is divisible by k.
Input
The first line contains two integers n and k (1 β€ n β€ 2 β
10^5, 2 β€ k β€ 10^9).
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9).
Output
Print a single integer β the number of ordered pairs of positions (i, j) (i β j) in array a such that the concatenation of a_i and a_j is divisible by k.
Examples
Input
6 11
45 1 10 12 11 7
Output
7
Input
4 2
2 78 4 10
Output
12
Input
5 2
3 7 19 3 3
Output
0
Note
In the first example pairs (1, 2), (1, 3), (2, 3), (3, 1), (3, 4), (4, 2), (4, 3) suffice. They produce numbers 451, 4510, 110, 1045, 1012, 121, 1210, respectively, each of them is divisible by 11.
In the second example all n(n - 1) pairs suffice.
In the third example no pair is sufficient.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <class T>
bool chmax(T& a, const T& b) {
if (a < b) {
a = b;
return 1;
}
return 0;
}
template <class T>
bool chmin(T& a, const T& b) {
if (b < a) {
a = b;
return 1;
}
return 0;
}
const long long int MOD = 1e9 + 7, INF = 1e18;
long long int dx[8] = {0, -1, 1, 0, 1, -1, 1, -1},
dy[8] = {1, 0, 0, -1, -1, -1, 1, 1};
struct edge {
long long int cost;
long long int u, v;
};
long long int digit(long long int v) {
string s = to_string(v);
return ((long long int)(s).size());
}
long long int N, K;
long long int arr[202000];
map<long long int, long long int> cnt[14];
int main() {
cin >> N >> K;
for (long long int i = (0), i_end_ = (N); i < i_end_; i++) {
cin >> arr[i];
cnt[digit(arr[i])][arr[i] % K]++;
}
long long int ans = 0;
for (long long int i = (0), i_end_ = (N); i < i_end_; i++) {
long long int curr = 1;
for (long long int j = (1), j_end_ = (14); j < j_end_; j++) {
curr *= 10;
curr %= K;
long long int dis = K - ((arr[i] * curr) % K);
dis %= K;
if (cnt[j].find(dis) != cnt[j].end()) ans += cnt[j][dis];
}
long long int p = 1;
for (long long int j = (0), j_end_ = (digit(arr[i])); j < j_end_; j++) {
p *= 10;
p %= K;
}
if ((arr[i] * p + arr[i]) % K == 0) ans--;
}
cout << ans << '\n';
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
You are given a simple connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge connects Vertex A_i and Vertex B_i. Takahashi will assign one of the two possible directions to each of the edges in the graph to make a directed graph. Determine if it is possible to make a directed graph with an even number of edges going out from every vertex. If the answer is yes, construct one such graph.
Constraints
* 2 \leq N \leq 10^5
* N-1 \leq M \leq 10^5
* 1 \leq A_i,B_i \leq N (1\leq i\leq M)
* The given graph is simple and connected.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1
:
A_M B_M
Output
If it is impossible to assign directions to satisfy the requirement, print -1. Otherwise, print an assignment of directions that satisfies the requirement, in the following format:
C_1 D_1
:
C_M D_M
Here each pair (C_i, D_i) means that there is an edge directed from Vertex C_i to Vertex D_i. The edges may be printed in any order.
Examples
Input
4 4
1 2
2 3
3 4
4 1
Output
1 2
1 4
3 2
3 4
Input
5 5
1 2
2 3
3 4
2 5
4 5
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using PII = pair<int, int>;
using LL = long long;
vector<int> G[100005];
int deg[100005], depth[100005];
vector<PII> edges;
void dfs(int from, int id) {
depth[id] = depth[from] + 1;
int x = 0;
for (auto x: G[id]) {
if (depth[x] == -1) {
dfs(id, x);
} else {
if (depth[x] > depth[id]) {
edges.emplace_back(id, x);
deg[id]++;
}
}
}
if (deg[id] % 2) {
if (from != 0) {
edges.emplace_back(id, from);
deg[id]++;
}
} else {
if (from != 0) {
edges.emplace_back(from, id);
deg[from]++;
}
}
}
int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i <= n; i++) depth[i] = -1;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
G[a].push_back(b);
G[b].push_back(a);
}
if (m % 2 == 1) {
cout << "-1\n";
return 0;
}
dfs(0, 1);
for (auto p: edges) {
cout << p.first << ' ' << p.second << '\n';
}
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
There are two main kinds of events in the life of top-model: fashion shows and photo shoots. Participating in any of these events affects the rating of appropriate top-model. After each photo shoot model's rating increases by a and after each fashion show decreases by b (designers do too many experiments nowadays). Moreover, sometimes top-models participates in talk shows. After participating in talk show model becomes more popular and increasing of her rating after photo shoots become c and decreasing of her rating after fashion show becomes d.
Izabella wants to participate in a talk show, but she wants to do it in such a way that her rating will never become negative. Help her to find a suitable moment for participating in the talk show.
Let's assume that model's career begins in moment 0. At that moment Izabella's rating was equal to start. If talk show happens in moment t if will affect all events in model's life in interval of time [t..t + len) (including t and not including t + len), where len is duration of influence.
Izabella wants to participate in a talk show, but she wants to do it in such a way that her rating will not become become negative before talk show or during period of influence of talk show. Help her to find a suitable moment for participating in the talk show.
Input
In first line there are 7 positive integers n, a, b, c, d, start, len (1 β€ n β€ 3Β·105, 0 β€ start β€ 109, 1 β€ a, b, c, d, len β€ 109), where n is a number of fashion shows and photo shoots, a, b, c and d are rating changes described above, start is an initial rating of model and len is a duration of influence of talk show.
In next n lines descriptions of events are given. Each of those lines contains two integers ti and qi (1 β€ ti β€ 109, 0 β€ q β€ 1) β moment, in which event happens and type of this event. Type 0 corresponds to the fashion show and type 1 β to photo shoot.
Events are given in order of increasing ti, all ti are different.
Output
Print one non-negative integer t β the moment of time in which talk show should happen to make Izabella's rating non-negative before talk show and during period of influence of talk show. If there are multiple answers print smallest of them. If there are no such moments, print - 1.
Examples
Input
5 1 1 1 4 0 5
1 1
2 1
3 1
4 0
5 0
Output
6
Input
1 1 2 1 2 1 2
1 0
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 300050;
long long n, a, b, c, d, start, len;
int t[MAXN], op[MAXN];
long long w[MAXN];
int main() {
cin >> n >> a >> b >> c >> d >> start >> len;
for (int i = 1; i <= n; i++) {
scanf("%d %d", &t[i], &op[i]);
}
int id = 1;
long long delta = 0, now = start, low = 0x3f3f3f3f;
t[0] = -1;
for (int i = 1; i <= n; i++) {
while (id <= n && t[id] - t[i] < len) {
delta += op[id] ? c : -d;
low = min(low, delta);
id++;
}
if (low + now >= 0) {
cout << t[i - 1] + 1 << endl;
return 0;
}
delta -= op[i] ? c : -d;
low -= op[i] ? c : -d;
now += op[i] ? a : -b;
if (now < 0) {
cout << -1 << endl;
return 0;
}
}
cout << t[n] + 1 << endl;
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3.
m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj.
A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served.
You are to compute the prices each buyer will pay for t-shirts.
Input
The first line contains single integer n (1 β€ n β€ 200 000) β the number of t-shirts.
The following line contains sequence of integers p1, p2, ..., pn (1 β€ pi β€ 1 000 000 000), where pi equals to the price of the i-th t-shirt.
The following line contains sequence of integers a1, a2, ..., an (1 β€ ai β€ 3), where ai equals to the front color of the i-th t-shirt.
The following line contains sequence of integers b1, b2, ..., bn (1 β€ bi β€ 3), where bi equals to the back color of the i-th t-shirt.
The next line contains single integer m (1 β€ m β€ 200 000) β the number of buyers.
The following line contains sequence c1, c2, ..., cm (1 β€ cj β€ 3), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served.
Output
Print to the first line m integers β the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1.
Examples
Input
5
300 200 400 500 911
1 2 1 2 3
2 1 3 2 1
6
2 3 1 2 1 1
Output
200 400 300 500 911 -1
Input
2
1000000000 1
1 1
1 2
2
2 1
Output
1 1000000000
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n;
long long p[n], y;
set<long long> c[4];
set<long long>::iterator it;
c[1].insert(-1);
c[2].insert(-1);
c[3].insert(-1);
int temp;
for (int i = 0; i < n; i++) cin >> p[i];
for (int i = 0; i < n; i++) {
cin >> temp;
c[temp].insert(p[i]);
}
for (int i = 0; i < n; i++) {
cin >> temp;
c[temp].insert(p[i]);
}
cin >> m;
for (int i = 0; i < m; i++) {
cin >> temp;
it = c[temp].begin();
it++;
if (it == c[temp].end()) {
cout << "-1 ";
continue;
} else {
y = *it;
cout << y << " ";
}
c[1].erase(y);
c[2].erase(y);
c[3].erase(y);
}
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Monocarp has got two strings s and t having equal length. Both strings consist of lowercase Latin letters "a" and "b".
Monocarp wants to make these two strings s and t equal to each other. He can do the following operation any number of times: choose an index pos_1 in the string s, choose an index pos_2 in the string t, and swap s_{pos_1} with t_{pos_2}.
You have to determine the minimum number of operations Monocarp has to perform to make s and t equal, and print any optimal sequence of operations β or say that it is impossible to make these strings equal.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^{5}) β the length of s and t.
The second line contains one string s consisting of n characters "a" and "b".
The third line contains one string t consisting of n characters "a" and "b".
Output
If it is impossible to make these strings equal, print -1.
Otherwise, in the first line print k β the minimum number of operations required to make the strings equal. In each of the next k lines print two integers β the index in the string s and the index in the string t that should be used in the corresponding swap operation.
Examples
Input
4
abab
aabb
Output
2
3 3
3 2
Input
1
a
b
Output
-1
Input
8
babbaabb
abababaa
Output
3
2 6
1 3
7 8
Note
In the first example two operations are enough. For example, you can swap the third letter in s with the third letter in t. Then s = "abbb", t = "aaab". Then swap the third letter in s and the second letter in t. Then both s and t are equal to "abab".
In the second example it's impossible to make two strings equal.
### Response
```cpp
#include <bits/stdc++.h>
const int oo = 2139063143;
const int N = 1010000;
const int P = 1000000007;
using namespace std;
template <typename T>
inline void sc(T &x) {
x = 0;
static int p;
p = 1;
static char c;
c = getchar();
while (!isdigit(c)) {
if (c == '-') p = -1;
c = getchar();
}
while (isdigit(c)) {
x = (x << 1) + (x << 3) + (c - 48);
c = getchar();
}
x *= p;
}
template <typename T>
inline void print(T x) {
if (x < 0) putchar('-'), x = -x;
if (x >= 10) print(x / 10);
putchar(x % 10 + '0');
}
template <typename T>
inline void pr(T x) {
print(x), putchar('\n');
}
int a[2][2][N], tt[2][2];
char s[N], t[N];
pair<int, int> ans[N];
int tot = 0;
int main() {
int n;
sc(n);
scanf("%s", s + 1);
scanf("%s", t + 1);
for (int i = 1; i <= n; i++)
if (s[i] != t[i])
a[s[i] - 'a'][t[i] - 'a'][++tt[s[i] - 'a'][t[i] - 'a']] = i;
if ((tt[0][1] + tt[1][0]) & 1) {
pr(-1);
return 0;
}
for (int i = 2; i <= tt[0][1]; i += 2)
ans[++tot] = make_pair(a[0][1][i - 1], a[0][1][i]);
for (int i = 2; i <= tt[1][0]; i += 2)
ans[++tot] = make_pair(a[1][0][i - 1], a[1][0][i]);
if (tt[0][1] & 1 && tt[1][0] & 1) {
ans[++tot] = make_pair(a[0][1][tt[0][1]], a[0][1][tt[0][1]]);
ans[++tot] = make_pair(a[0][1][tt[0][1]], a[1][0][tt[1][0]]);
}
pr(tot);
for (int i = 1; i <= tot; i++) printf("%d %d\n", ans[i].first, ans[i].second);
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.
Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.
Constraints
* 2 \leq N \leq 10^5
* 0 \leq M \leq \min(10^5, N (N-1))
* 1 \leq u_i, v_i \leq N(1 \leq i \leq M)
* u_i \neq v_i (1 \leq i \leq M)
* If i \neq j, (u_i, v_i) \neq (u_j, v_j).
* 1 \leq S, T \leq N
* S \neq T
Input
Input is given from Standard Input in the following format:
N M
u_1 v_1
:
u_M v_M
S T
Output
If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1. If he can, print the minimum number of ken-ken-pa needed to reach vertex T.
Examples
Input
4 4
1 2
2 3
3 4
4 1
1 3
Output
2
Input
3 3
1 2
2 3
3 1
1 2
Output
-1
Input
2 0
1 2
Output
-1
Input
6 8
1 2
2 3
3 4
4 5
5 1
1 4
1 5
4 6
1 6
Output
2
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int n, m, s, t;
vector<int>adjl[100002];
int dist[100002][3];
queue<pair<int,int> >bfs;
int main(){
ios_base::sync_with_stdio(0);cin.tie(0);
memset(dist,-1,sizeof dist);
cin >> n >> m;
for (int i=0;i<m;i++){
int u, v;
cin >> u >> v;
adjl[u].push_back(v);
}
cin >> s >> t;
bfs.push({s,0});
while (!bfs.empty()){
int now=bfs.front().first;
int distnow=bfs.front().second;
bfs.pop();
if (dist[now][distnow%3]!=-1) continue;
dist[now][distnow%3]=distnow;
for (int next : adjl[now]) bfs.push({next,distnow+1});
}
cout << (dist[t][0]==-1 ? -1 : dist[t][0]/3) << "\n";
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
There are n phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct.
There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: 123456789, 100000000 and 100123456, then:
* if he enters 00 two numbers will show up: 100000000 and 100123456,
* if he enters 123 two numbers will show up 123456789 and 100123456,
* if he enters 01 there will be only one number 100123456.
For each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number.
Input
The first line contains single integer n (1 β€ n β€ 70000) β the total number of phone contacts in Polycarp's contacts.
The phone numbers follow, one in each line. Each number is a positive 9-digit integer starting with a digit from 1 to 9. All the numbers are distinct.
Output
Print exactly n lines: the i-th of them should contain the shortest non-empty sequence of digits, such that if Polycarp enters it, the Berdroid OS shows up only the i-th number from the contacts. If there are several such sequences, print any of them.
Examples
Input
3
123456789
100000000
100123456
Output
9
000
01
Input
4
123456789
193456789
134567819
934567891
Output
2
193
81
91
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long int mod = 1e9 + 7;
int main(void) {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
int mayoke = mt19937(0xe869120)() % 20;
vector<string> s(n);
unordered_map<string, set<int> > tbl;
for (int i = (int)(0); i < (int)(n); i++) {
cin >> s[i];
for (int j = (int)(0); j < (int)(9); j++) {
s[i][j] += mayoke;
}
for (int j = (int)(0); j < (int)(9); j++) {
for (int k = (int)(1); k < (int)(10 - j); k++) {
string t = s[i].substr(j, k);
if (tbl[t].size() <= 1) {
tbl[t].insert(i);
}
}
}
}
vector<string> ans(n);
vector<int> len(n, 100);
for (auto &p : tbl) {
if (p.second.size() != 1) {
continue;
}
string u = p.first;
int idx = *p.second.begin();
if (len[idx] > (int)u.length()) {
len[idx] = u.length();
ans[idx] = u;
}
}
for (int i = (int)(0); i < (int)(n); i++) {
for (int j = (int)(0); j < (int)(ans[i].size()); j++) {
ans[i][j] -= mayoke;
}
cout << ans[i] << "\n";
}
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
The black king is standing on a chess field consisting of 109 rows and 109 columns. We will consider the rows of the field numbered with integers from 1 to 109 from top to bottom. The columns are similarly numbered with integers from 1 to 109 from left to right. We will denote a cell of the field that is located in the i-th row and j-th column as (i, j).
You know that some squares of the given chess field are allowed. All allowed cells of the chess field are given as n segments. Each segment is described by three integers ri, ai, bi (ai β€ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed.
Your task is to find the minimum number of moves the king needs to get from square (x0, y0) to square (x1, y1), provided that he only moves along the allowed cells. In other words, the king can be located only on allowed cells on his way.
Let us remind you that a chess king can move to any of the neighboring cells in one move. Two cells of a chess field are considered neighboring if they share at least one point.
Input
The first line contains four space-separated integers x0, y0, x1, y1 (1 β€ x0, y0, x1, y1 β€ 109), denoting the initial and the final positions of the king.
The second line contains a single integer n (1 β€ n β€ 105), denoting the number of segments of allowed cells. Next n lines contain the descriptions of these segments. The i-th line contains three space-separated integers ri, ai, bi (1 β€ ri, ai, bi β€ 109, ai β€ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed. Note that the segments of the allowed cells can intersect and embed arbitrarily.
It is guaranteed that the king's initial and final position are allowed cells. It is guaranteed that the king's initial and the final positions do not coincide. It is guaranteed that the total length of all given segments doesn't exceed 105.
Output
If there is no path between the initial and final position along allowed cells, print -1.
Otherwise print a single integer β the minimum number of moves the king needs to get from the initial position to the final one.
Examples
Input
5 7 6 11
3
5 3 8
6 7 11
5 2 5
Output
4
Input
3 4 3 10
3
3 1 4
4 5 9
3 10 10
Output
6
Input
1 1 2 10
2
1 1 3
2 6 10
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void write(vector<int> &v) {
for (auto i : v) cout << i << " ";
cout << "\n";
}
void read(vector<int> &v) {
for (auto &i : v) cin >> i;
}
const int INF = 1e9;
const int64_t INFF = 1e18;
const int N = 1e6 + 69;
map<pair<int, int>, int> grid;
vector<int> dRow = {0, 1, 0, -1, 1, 1, -1, -1};
vector<int> dCol = {1, 0, -1, 0, 1, -1, -1, 1};
map<pair<int, int>, int> vis;
void solve() {
int x0, x1, y0, y1;
cin >> x0 >> y0 >> x1 >> y1;
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int r, c1, c2;
cin >> r >> c1 >> c2;
for (int j = c1; j <= c2; j++) {
grid[{r, j}] = 1;
}
}
queue<pair<int, int> > q;
q.push({x0, y0});
vis[{x0, y0}] = 1;
bool exist = false;
while (!q.empty()) {
int x = q.front().first;
int y = q.front().second;
q.pop();
for (int i = 0; i < 8; i++) {
int newx = x + dRow[i], newy = y + dCol[i];
if (vis[{newx, newy}] == 0 && grid[{newx, newy}] && 0 <= newx &&
newx < (int)1e9 && 0 <= newy < (int)1e9) {
vis[{newx, newy}] = vis[{x, y}] + 1;
q.push({newx, newy});
if (newx == x1 && newy == y1) {
exist = true;
break;
}
}
}
if (exist) break;
}
if (exist)
cout << vis[{x1, y1}] - 1 << "\n";
else
cout << -1 << "\n";
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t = 1;
for (int i = 1; i <= t; i++) {
solve();
}
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
AtCoDeer the deer is seeing a quick report of election results on TV. Two candidates are standing for the election: Takahashi and Aoki. The report shows the ratio of the current numbers of votes the two candidates have obtained, but not the actual numbers of votes. AtCoDeer has checked the report N times, and when he checked it for the i-th (1β¦iβ¦N) time, the ratio was T_i:A_i. It is known that each candidate had at least one vote when he checked the report for the first time.
Find the minimum possible total number of votes obtained by the two candidates when he checked the report for the N-th time. It can be assumed that the number of votes obtained by each candidate never decreases.
Constraints
* 1β¦Nβ¦1000
* 1β¦T_i,A_iβ¦1000 (1β¦iβ¦N)
* T_i and A_i (1β¦iβ¦N) are coprime.
* It is guaranteed that the correct answer is at most 10^{18}.
Input
The input is given from Standard Input in the following format:
N
T_1 A_1
T_2 A_2
:
T_N A_N
Output
Print the minimum possible total number of votes obtained by Takahashi and Aoki when AtCoDeer checked the report for the N-th time.
Examples
Input
3
2 3
1 1
3 2
Output
10
Input
4
1 1
1 1
1 5
1 100
Output
101
Input
5
3 10
48 17
31 199
231 23
3 2
Output
6930
### Response
```cpp
#include <iostream>
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
ll n; cin>>n;
ll ax,bx; cin>>ax>>bx;
n--;
while(n--)
{
ll a,b; cin>>a>>b;
ll xx=(ax+a-1)/a;
xx=max(xx,(bx+b-1)/b);
ax=xx*a;
bx=xx*b;
}
cout<<ax+bx;
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of a thimbles per day after the k days are complete.
Initially, no orders are pending. The factory receives updates of the form di, ai, indicating that ai new orders have been placed for the di-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes.
As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day pi. Help the owner answer his questions.
Input
The first line contains five integers n, k, a, b, and q (1 β€ k β€ n β€ 200 000, 1 β€ b < a β€ 10 000, 1 β€ q β€ 200 000) β the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively.
The next q lines contain the descriptions of the queries. Each query is of one of the following two forms:
* 1 di ai (1 β€ di β€ n, 1 β€ ai β€ 10 000), representing an update of ai orders on day di, or
* 2 pi (1 β€ pi β€ n - k + 1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day pi?
It's guaranteed that the input will contain at least one query of the second type.
Output
For each query of the second type, print a line containing a single integer β the maximum number of orders that the factory can fill over all n days.
Examples
Input
5 2 2 1 8
1 1 2
1 5 3
1 2 1
2 2
1 4 2
1 3 2
2 1
2 3
Output
3
6
4
Input
5 4 10 1 6
1 1 5
1 5 5
1 3 2
1 5 2
2 1
2 2
Output
7
1
Note
Consider the first sample.
We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days.
For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled.
For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int input[300010];
long long int n, k, a, b, q;
struct Tree_Node {
long long int maxi;
long long int mini;
} tree[4 * 300010 + 5];
void build(long long int node, long long int st, long long int en) {
if (st == en) {
if (input[st] > a)
tree[node].maxi = a;
else
tree[node].maxi = input[st];
if (input[st] > b)
tree[node].mini = b;
else
tree[node].mini = input[st];
} else {
long long int mid = (st + en) / 2;
build(2 * node, st, mid);
build(2 * node + 1, mid + 1, en);
tree[node].mini = tree[2 * node].mini + tree[2 * node + 1].mini;
tree[node].maxi = tree[2 * node].maxi + tree[2 * node + 1].maxi;
}
}
void update(long long int node, long long int st, long long int en,
long long int in, long long int x) {
if (st == en) {
long long int m = tree[node].maxi;
long long int n = tree[node].mini;
m += x;
n += x;
if (m > a)
tree[node].maxi = a;
else
tree[node].maxi = m;
if (n > b)
tree[node].mini = b;
else
tree[node].mini = n;
} else {
long long int mid = (st + en) / 2;
if (st <= in && in <= mid)
update(2 * node, st, mid, in, x);
else
update(2 * node + 1, mid + 1, en, in, x);
tree[node].mini = tree[2 * node].mini + tree[2 * node + 1].mini;
tree[node].maxi = tree[2 * node].maxi + tree[2 * node + 1].maxi;
}
}
long long int query(long long int node, long long int st, long long int en,
long long int l, long long int r, long long int type) {
if (l <= st && en <= r && type == 1)
return tree[node].maxi;
else if (l <= st && en <= r && type == 0)
return tree[node].mini;
else if (r < st || en < l)
return 0;
else {
long long int mid = (st + en) / 2;
return query(2 * node, st, mid, l, r, type) +
query(2 * node + 1, mid + 1, en, l, r, type);
}
}
int main() {
cin >> n >> k >> a >> b >> q;
long long int in, x, type;
while (q--) {
cin >> type;
if (type == 1) {
cin >> in >> x;
update(1, 1, n, in, x);
} else {
cin >> in;
cout << query(1, 1, n, 1, in - 1, 0) + query(1, 1, n, in + k, n, 1)
<< endl;
}
}
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
Let x be an array of integers x = [x_1, x_2, ..., x_n]. Let's define B(x) as a minimal size of a partition of x into subsegments such that all elements in each subsegment are equal. For example, B([3, 3, 6, 1, 6, 6, 6]) = 4 using next partition: [3, 3\ |\ 6\ |\ 1\ |\ 6, 6, 6].
Now you don't have any exact values of x, but you know that x_i can be any integer value from [l_i, r_i] (l_i β€ r_i) uniformly at random. All x_i are independent.
Calculate expected value of (B(x))^2, or E((B(x))^2). It's guaranteed that the expected value can be represented as rational fraction P/Q where (P, Q) = 1, so print the value P β
Q^{-1} mod 10^9 + 7.
Input
The first line contains the single integer n (1 β€ n β€ 2 β
10^5) β the size of the array x.
The second line contains n integers l_1, l_2, ..., l_n (1 β€ l_i β€ 10^9).
The third line contains n integers r_1, r_2, ..., r_n (l_i β€ r_i β€ 10^9).
Output
Print the single integer β E((B(x))^2) as P β
Q^{-1} mod 10^9 + 7.
Examples
Input
3
1 1 1
1 2 3
Output
166666673
Input
3
3 4 5
4 5 6
Output
500000010
Note
Let's describe all possible values of x for the first sample:
* [1, 1, 1]: B(x) = 1, B^2(x) = 1;
* [1, 1, 2]: B(x) = 2, B^2(x) = 4;
* [1, 1, 3]: B(x) = 2, B^2(x) = 4;
* [1, 2, 1]: B(x) = 3, B^2(x) = 9;
* [1, 2, 2]: B(x) = 2, B^2(x) = 4;
* [1, 2, 3]: B(x) = 3, B^2(x) = 9;
So E = 1/6 (1 + 4 + 4 + 9 + 4 + 9) = 31/6 or 31 β
6^{-1} = 166666673.
All possible values of x for the second sample:
* [3, 4, 5]: B(x) = 3, B^2(x) = 9;
* [3, 4, 6]: B(x) = 3, B^2(x) = 9;
* [3, 5, 5]: B(x) = 2, B^2(x) = 4;
* [3, 5, 6]: B(x) = 3, B^2(x) = 9;
* [4, 4, 5]: B(x) = 2, B^2(x) = 4;
* [4, 4, 6]: B(x) = 2, B^2(x) = 4;
* [4, 5, 5]: B(x) = 2, B^2(x) = 4;
* [4, 5, 6]: B(x) = 3, B^2(x) = 9;
So E = 1/8 (9 + 9 + 4 + 9 + 4 + 4 + 4 + 9) = 52/8 or 13 β
2^{-1} = 500000010.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int inf = 2147483647;
const int mod = 1e9 + 7;
const int N = 200001;
int _max(int x, int y) { return x > y ? x : y; }
int _min(int x, int y) { return x < y ? x : y; }
inline int read() {
int x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
x = (x << 3) + (x << 1) + (ch ^ 48), ch = getchar();
return x * f;
}
void put(int x) {
if (x < 0) putchar('-'), x = -x;
if (x >= 10) put(x / 10);
putchar(x % 10 + '0');
}
int L[N], R[N];
int p[N], q[N];
int add(int x, int y) {
x += y;
return x >= mod ? x - mod : x;
}
int dec(int x, int y) {
x -= y;
return x < 0 ? x + mod : x;
}
int pow_mod(int a, int k) {
int ans = 1;
while (k) {
if (k & 1) ans = (long long)ans * a % mod;
a = (long long)a * a % mod, k /= 2;
}
return ans;
}
int gao(int i) {
int s = (long long)_max(0, _min(R[i], _min(R[i - 1], R[i + 1])) -
_max(L[i], _max(L[i - 1], L[i + 1]))) *
pow_mod(R[i] - L[i], mod - 2) % mod *
pow_mod(R[i - 1] - L[i - 1], mod - 2) % mod *
pow_mod(R[i + 1] - L[i + 1], mod - 2) % mod;
return add(dec(mod + 1 - p[i], p[i + 1]), s);
}
int main() {
int n = read();
for (int i = 1; i <= n; i++) L[i] = read();
for (int i = 1; i <= n; i++) R[i] = read() + 1;
for (int i = 2; i <= n; i++) {
p[i] = (long long)_max(0, _min(R[i - 1], R[i]) - _max(L[i - 1], L[i])) *
pow_mod(R[i - 1] - L[i - 1], mod - 2) % mod *
pow_mod(R[i] - L[i], mod - 2) % mod;
q[i] = dec(1, p[i]);
}
q[1] = 1;
int sum = 0, ans = 0;
for (int i = 1; i <= n; i++) sum = add(sum, q[i]);
for (int i = 1; i <= n; i++) {
ans = add(ans, q[i]);
ans = add(ans, (long long)dec(dec(dec(sum, q[i]), q[i - 1]), q[i + 1]) *
q[i] % mod);
}
ans = add(ans, 2LL * q[2] % mod);
for (int i = 2; i < n; i++) ans = add(ans, 2LL * gao(i) % mod);
put(ans), puts("");
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Kevin Sun wants to move his precious collection of n cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into k boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single box. Since Kevin wishes to minimize expenses, he is curious about the smallest size box he can use to pack his entire collection.
Kevin is a meticulous cowbell collector and knows that the size of his i-th (1 β€ i β€ n) cowbell is an integer si. In fact, he keeps his cowbells sorted by size, so si - 1 β€ si for any i > 1. Also an expert packer, Kevin can fit one or two cowbells into a box of size s if and only if the sum of their sizes does not exceed s. Given this information, help Kevin determine the smallest s for which it is possible to put all of his cowbells into k boxes of size s.
Input
The first line of the input contains two space-separated integers n and k (1 β€ n β€ 2Β·k β€ 100 000), denoting the number of cowbells and the number of boxes, respectively.
The next line contains n space-separated integers s1, s2, ..., sn (1 β€ s1 β€ s2 β€ ... β€ sn β€ 1 000 000), the sizes of Kevin's cowbells. It is guaranteed that the sizes si are given in non-decreasing order.
Output
Print a single integer, the smallest s for which it is possible for Kevin to put all of his cowbells into k boxes of size s.
Examples
Input
2 1
2 5
Output
7
Input
4 3
2 3 5 9
Output
9
Input
3 2
3 5 7
Output
8
Note
In the first sample, Kevin must pack his two cowbells into the same box.
In the second sample, Kevin can pack together the following sets of cowbells: {2, 3}, {5} and {9}.
In the third sample, the optimal solution is {3, 5} and {7}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
int N, K, sol;
int v[MAXN];
bool check(int dim) {
int cnt = N - K;
int j = 1;
for (int i = N; i >= N - K + 1 && cnt; i--) {
if (v[i] + v[j] <= dim) {
j++;
cnt--;
}
}
return cnt == 0;
}
void bs() {
int l = v[N], r = v[N] * 2;
while (l <= r) {
int mid = (l + r) / 2;
if (check(mid)) {
sol = mid;
r = mid - 1;
} else
l = mid + 1;
}
cout << sol;
}
int main() {
cin >> N >> K;
K = min(N, K);
for (int i = 1; i <= N; i++) cin >> v[i];
bs();
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Try guessing the statement from this picture:
<image>
You are given a non-negative integer d. You have to find two non-negative real numbers a and b such that a + b = d and a β
b = d.
Input
The first line contains t (1 β€ t β€ 10^3) β the number of test cases.
Each test case contains one integer d (0 β€ d β€ 10^3).
Output
For each test print one line.
If there is an answer for the i-th test, print "Y", and then the numbers a and b.
If there is no answer for the i-th test, print "N".
Your answer will be considered correct if |(a + b) - a β
b| β€ 10^{-6} and |(a + b) - d| β€ 10^{-6}.
Example
Input
7
69
0
1
4
5
999
1000
Output
Y 67.985071301 1.014928699
Y 0.000000000 0.000000000
N
Y 2.000000000 2.000000000
Y 3.618033989 1.381966011
Y 997.998996990 1.001003010
Y 998.998997995 1.001002005
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long inf = 0x3f3f3f3f;
const int N = 1e6 + 10;
const long long mod = 998244353;
map<string, long long> mp;
map<string, int> ml;
int c[N], vis[N], a[N], t, n, m, x, y, ans;
char s[N];
int ex, ey, cnt;
long long p(long long x) {
for (long long i = 2; i <= sqrt(x); i++) {
if (n % i == 0) return 0;
}
return 1;
}
long long f(long long x) {
for (long long i = 2; i <= n; i++) {
if (n % i == 0 && p(i)) return i;
}
}
int main() {
scanf("%d", &n);
while (n--) {
double m;
scanf("%lf", &m);
double l, r;
if (m == 0) {
cout << "Y 0.000000000 0.000000000" << endl;
} else {
l = 0;
r = m;
double mid;
for (int i = 1; i <= 50; i++) {
mid = (l + r) / 2;
double t = mid * mid - m * mid + m;
if (t > 0) {
r = mid - 1;
} else
l = mid + 1;
}
if (mid > 0 && m - mid > 0)
printf("Y %.9f %.9f\n", mid, m - mid);
else
cout << "N" << endl;
}
}
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Suppose that there are some light sources and many spherical balloons. All light sources have sizes small enough to be modeled as point light sources, and they emit light in all directions. The surfaces of the balloons absorb light and do not reflect light. Surprisingly in this world, balloons may overlap.
You want the total illumination intensity at an objective point as high as possible. For this purpose, some of the balloons obstructing lights can be removed. Because of the removal costs, however, there is a certain limit on the number of balloons to be removed. Thus, you would like to remove an appropriate set of balloons so as to maximize the illumination intensity at the objective point.
The following figure illustrates the configuration specified in the first dataset of the sample input given below. The figure shows the xy-plane, which is enough because, in this dataset, the z-coordinates of all the light sources, balloon centers, and the objective point are zero. In the figure, light sources are shown as stars and balloons as circles. The objective point is at the origin, and you may remove up to 4 balloons. In this case, the dashed circles in the figure correspond to the balloons to be removed.
<image>
Figure G.1: First dataset of the sample input.
Input
The input is a sequence of datasets. Each dataset is formatted as follows.
N M R
S1x S1y S1z S1r
...
SNx SNy SNz SNr
T1x T1y T1z T1b
...
TMx TMy TMz TMb
Ex Ey Ez
The first line of a dataset contains three positive integers, N, M and R, separated by a single space. N means the number of balloons that does not exceed 2000. M means the number of light sources that does not exceed 15. R means the number of balloons that may be removed, which does not exceed N.
Each of the N lines following the first line contains four integers separated by a single space. (Six, Siy, Siz) means the center position of the i-th balloon and Sir means its radius.
Each of the following M lines contains four integers separated by a single space. (Tjx, Tjy, Tjz) means the position of the j-th light source and Tjb means its brightness.
The last line of a dataset contains three integers separated by a single space. (Ex, Ey, Ez) means the position of the objective point.
Six, Siy, Siz, Tjx, Tjy, Tjz, Ex, Ey and Ez are greater than -500, and less than 500. Sir is greater than 0, and less than 500. Tjb is greater than 0, and less than 80000.
At the objective point, the intensity of the light from the j-th light source is in inverse proportion to the square of the distance, namely
Tjb / { (Tjx β Ex)2 + (Tjy β Ey)2 + (Tjz β Ez)2 },
if there is no balloon interrupting the light. The total illumination intensity is the sum of the above.
You may assume the following.
1. The distance between the objective point and any light source is not less than 1.
2. For every i and j, even if Sir changes by Ξ΅ (|Ξ΅| < 0.01), whether the i-th balloon hides the j-th light or not does not change.
The end of the input is indicated by a line of three zeros.
Output
For each dataset, output a line containing a decimal fraction which means the highest possible illumination intensity at the objective point after removing R balloons. The output should not contain an error greater than 0.0001.
Example
Input
12 5 4
0 10 0 1
1 5 0 2
1 4 0 2
0 0 0 2
10 0 0 1
3 -1 0 2
5 -1 0 2
10 10 0 15
0 -10 0 1
10 -10 0 1
-10 -10 0 1
10 10 0 1
0 10 0 240
10 0 0 200
10 -2 0 52
-10 0 0 100
1 1 0 2
0 0 0
12 5 4
0 10 0 1
1 5 0 2
1 4 0 2
0 0 0 2
10 0 0 1
3 -1 0 2
5 -1 0 2
10 10 0 15
0 -10 0 1
10 -10 0 1
-10 -10 0 1
10 10 0 1
0 10 0 260
10 0 0 200
10 -2 0 52
-10 0 0 100
1 1 0 2
0 0 0
5 1 3
1 2 0 2
-1 8 -1 8
-2 -3 5 6
-2 1 3 3
-4 2 3 5
1 1 2 7
0 0 0
5 1 2
1 2 0 2
-1 8 -1 8
-2 -3 5 6
-2 1 3 3
-4 2 3 5
1 1 2 7
0 0 0
0 0 0
Output
3.5
3.6
1.1666666666666667
0.0
### Response
```cpp
#include <iostream>
#include <iomanip>
#include <vector>
#include <bitset>
#include <cmath>
using namespace std;
static const double EPS = 1e-8;
inline int sign(double x){ return abs(x) < EPS ? 0 : (x > 0 ? 1 : -1); }
struct Point3D {
double x, y, z;
Point3D() : x(0), y(0), z(0) { }
Point3D(double x, double y, double z) : x(x), y(y), z(z) { }
Point3D operator-() const { return Point3D(-x, -y, -z); }
Point3D operator+(const Point3D &p) const {
return Point3D(x + p.x, y + p.y, z + p.z);
}
Point3D operator-(const Point3D &p) const {
return Point3D(x - p.x, y - p.y, z - p.z);
}
Point3D operator*(const double s) const {
return Point3D(x * s, y * s, z * s);
}
Point3D operator/(const double s) const {
return Point3D(x / s, y / s, z / s);
}
};
struct Line3D {
Point3D a, b;
Line3D() : a(), b() { }
Line3D(const Point3D &a, const Point3D &b) : a(a), b(b) { }
};
struct Sphere {
Point3D c;
double r;
Sphere() : c(), r(0) { }
Sphere(const Point3D &c, double r) : c(c), r(r) { }
};
inline double dot(const Point3D &a, const Point3D &b){
return a.x * b.x + a.y * b.y + a.z * b.z;
}
inline Point3D cross(const Point3D &a, const Point3D &b){
return Point3D(
a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x);
}
inline double norm(const Point3D &p){
return p.x * p.x + p.y * p.y + p.z * p.z;
}
inline double abs(const Point3D &p){
return sqrt(norm(p));
}
inline Point3D unit(const Point3D &p){
return p / abs(p);
}
inline Point3D vec(const Line3D &l){
return l.b - l.a;
}
inline Point3D projection(const Line3D &l, const Point3D &p){
const Point3D v = vec(l);
return l.a + v * (dot(p - l.a, v) / norm(v));
}
inline Point3D refrect(const Line3D &l, const Point3D &p){
const Point3D q = projection(l, p);
return p + (q - p) * 2.0;
}
inline bool intersectLP(const Line3D &l, const Point3D &p){
return !sign(norm(cross(p - l.a, vec(l))));
}
inline bool intersectSP(const Line3D &l, const Point3D &p){
const Point3D a = p - l.a, b = vec(l);
if(norm(a) < EPS || norm(a - b) < EPS){ return true; }
if(norm(cross(a, b)) > EPS){ return false; }
if(a.x * b.x < -EPS){ return false; }
if(a.y * b.y < -EPS){ return false; }
if(a.z * b.z < -EPS){ return false; }
return norm(a) < norm(b);
}
inline double distanceLP(const Line3D &l, const Point3D &p){
const Point3D q = projection(l, p);
return abs(p - q);
}
inline double distanceSP(const Line3D &l, const Point3D &p){
const Point3D u = p - l.a;
const Point3D v = projection(Line3D(Point3D(), vec(l)), u);
if(intersectSP(Line3D(Point3D(), vec(l)), v)){ return abs(u - v); }
return sqrt(min(norm(p - l.a), norm(p - l.b)));
}
vector<Point3D> crosspointCL(const Sphere &s, const Line3D &l){
const Point3D &p = projection(l, s.c);
const double d2 = norm(s.c - p);
if(d2 > s.r * s.r + EPS){ return vector<Point3D>(); }
if(d2 > s.r * s.r - EPS){ return vector<Point3D>(1, p); }
const double sc = sqrt(s.r * s.r - d2);
vector<Point3D> ret;
ret.push_back(p + unit(vec(l)) * sc);
ret.push_back(p - unit(vec(l)) * sc);
return ret;
}
vector<Point3D> crosspointCS(const Sphere &s, const Line3D &l){
const vector<Point3D> ps = crosspointCL(s, l);
vector<Point3D> ret;
for(int i = 0; i < ps.size(); ++i){
if(intersectSP(l, ps[i])){ ret.push_back(ps[i]); }
}
return ret;
}
bool intersectCL(const Sphere &s, const Line3D &l){
return distanceLP(l, s.c) < s.r + EPS;
}
bool intersectCS(const Sphere &s, const Line3D &l){
return !crosspointCS(s, l).empty();
}
int main(){
ios_base::sync_with_stdio(false);
cout << setiosflags(ios::fixed) << setprecision(10);
while(true){
int n, m, r;
cin >> n >> m >> r;
if(n == 0 && m == 0 && r == 0){ break; }
vector<Sphere> balloons(n);
for(int i = 0; i < n; ++i){
double x, y, z, r;
cin >> x >> y >> z >> r;
balloons[i] = Sphere(Point3D(x, y, z), r);
}
vector<Point3D> lights(m);
vector<int> intensities(m);
for(int i = 0; i < m; ++i){
int x, y, z, intensity;
cin >> x >> y >> z >> intensity;
lights[i] = Point3D(x, y, z);
intensities[i] = intensity;
}
Point3D objective;
cin >> objective.x >> objective.y >> objective.z;
vector< bitset<2048> > collisions(m);
for(int i = 0; i < m; ++i){
const Line3D s(objective, lights[i]);
for(int j = 0; j < n; ++j){
collisions[i][j] = intersectCS(balloons[j], s);
}
}
double answer = 0.0;
for(int i = 0; i < (1 << m); ++i){
bitset<2048> collision;
for(int j = 0; j < m; ++j){
if(i & (1 << j)){ collision |= collisions[j]; }
}
if(collision.count() > r){ continue; }
double sum = 0.0;
for(int j = 0; j < m; ++j){
if(i & (1 << j)){
sum += intensities[j] / norm(lights[j] - objective);
}
}
answer = max(answer, sum);
}
cout << answer << endl;
}
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make s airplanes.
A group of k people decided to make n airplanes each. They are going to buy several packs of paper, each of them containing p sheets, and then distribute the sheets between the people. Each person should have enough sheets to make n airplanes. How many packs should they buy?
Input
The only line contains four integers k, n, s, p (1 β€ k, n, s, p β€ 10^4) β the number of people, the number of airplanes each should make, the number of airplanes that can be made using one sheet and the number of sheets in one pack, respectively.
Output
Print a single integer β the minimum number of packs they should buy.
Examples
Input
5 3 2 3
Output
4
Input
5 3 100 1
Output
5
Note
In the first sample they have to buy 4 packs of paper: there will be 12 sheets in total, and giving 2 sheets to each person is enough to suit everyone's needs.
In the second sample they have to buy a pack for each person as they can't share sheets.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long ans, k, n, s, p;
cin >> k >> n >> s >> p;
ans = ceil((k * ceil(((double)n) / s)) / p);
cout << ans;
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Write a program which reads an integer n and draws a Koch curve based on recursive calles of depth n.
The Koch curve is well known as a kind of fractals.
You can draw a Koch curve in the following algorithm:
* Divide a given segment (p1, p2) into three equal segments.
* Replace the middle segment by the two sides of an equilateral triangle (s, u, t) of the same length as the segment.
* Repeat this procedure recursively for new segments (p1, s), (s, u), (u, t), (t, p2).
<image>
You should start (0, 0), (100, 0) as the first segment.
Notes
Constraints
* 0 β€ n β€ 6
Input
An integer n is given.
Output
Print each point (x, y) of the Koch curve. Print a point in a line. You should start the point(0, 0), which is the endpoint of the first segment and end with the point (100, 0), the other endpoint so that you can draw the Koch curve as an unbroken line. Each solution should be given as a decimal with an arbitrary number of fractional digits, and with an absolute error of at most 10-4.
Examples
Input
1
Output
0.00000000 0.00000000
33.33333333 0.00000000
50.00000000 28.86751346
66.66666667 0.00000000
100.00000000 0.00000000
Input
2
Output
0.00000000 0.00000000
11.11111111 0.00000000
16.66666667 9.62250449
22.22222222 0.00000000
33.33333333 0.00000000
38.88888889 9.62250449
33.33333333 19.24500897
44.44444444 19.24500897
50.00000000 28.86751346
55.55555556 19.24500897
66.66666667 19.24500897
61.11111111 9.62250449
66.66666667 0.00000000
77.77777778 0.00000000
83.33333333 9.62250449
88.88888889 0.00000000
100.00000000 0.00000000
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
struct point{
double x,y;
};
void func(point a,point b,int cnt);
int n;
const double rad=M_PI*60.0/180.0;
int main(void){
point a,b;
cin>>n;
a.x=0.0; a.y=0.0;
b.x=100.0; b.y=0.0;
printf("%.8f %.8f\n",a.x,a.y);
func(a,b,0);
printf("%.8f %.8f\n",b.x,b.y);
return 0;
}
void func(point a,point b,int cnt){
point s,t,u;
if(n!=0){
if(cnt<n){
s.x=(2.0*a.x+1.0*b.x)/3.0;
s.y=(2.0*a.y+1.0*b.y)/3.0;
t.x=(1.0*a.x+2.0*b.x)/3.0;
t.y=(1.0*a.y+2.0*b.y)/3.0;
u.x=(t.x-s.x)*cos(rad)-(t.y-s.y)*sin(rad)+s.x;
u.y=(t.x-s.x)*sin(rad)+(t.y-s.y)*cos(rad)+s.y;
func(a,s,cnt+1);
printf("%.8f %.8f\n",s.x,s.y);
func(s,u,cnt+1);
printf("%.8f %.8f\n",u.x,u.y);
func(u,t,cnt+1);
printf("%.8f %.8f\n",t.x,t.y);
func(t,b,cnt+1);
}
}
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Snuke has N integers. Among them, the smallest is A, and the largest is B. We are interested in the sum of those N integers. How many different possible sums there are?
Constraints
* 1 β€ N,A,B β€ 10^9
* A and B are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
Print the number of the different possible sums.
Examples
Input
4 4 6
Output
5
Input
5 4 3
Output
0
Input
1 7 10
Output
0
Input
1 3 3
Output
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2e1+1;
const ll p=1e9+7;
int main()
{
ll n,a,b;
cin>>n>>a>>b;
cout<<max(0LL,(b-a)*(n-2)+1);
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Nauuo is a girl who loves playing cards.
One day she was playing cards but found that the cards were mixed with some empty ones.
There are n cards numbered from 1 to n, and they were mixed with another n empty cards. She piled up the 2n cards and drew n of them. The n cards in Nauuo's hands are given. The remaining n cards in the pile are also given in the order from top to bottom.
In one operation she can choose a card in her hands and play it β put it at the bottom of the pile, then draw the top card from the pile.
Nauuo wants to make the n numbered cards piled up in increasing order (the i-th card in the pile from top to bottom is the card i) as quickly as possible. Can you tell her the minimum number of operations?
Input
The first line contains a single integer n (1β€ nβ€ 2β
10^5) β the number of numbered cards.
The second line contains n integers a_1,a_2,β¦,a_n (0β€ a_iβ€ n) β the initial cards in Nauuo's hands. 0 represents an empty card.
The third line contains n integers b_1,b_2,β¦,b_n (0β€ b_iβ€ n) β the initial cards in the pile, given in order from top to bottom. 0 represents an empty card.
It is guaranteed that each number from 1 to n appears exactly once, either in a_{1..n} or b_{1..n}.
Output
The output contains a single integer β the minimum number of operations to make the n numbered cards piled up in increasing order.
Examples
Input
3
0 2 0
3 0 1
Output
2
Input
3
0 2 0
1 0 3
Output
4
Input
11
0 0 0 5 0 0 0 4 0 0 11
9 2 6 0 8 1 7 0 3 0 10
Output
18
Note
Example 1
We can play the card 2 and draw the card 3 in the first operation. After that, we have [0,3,0] in hands and the cards in the pile are [0,1,2] from top to bottom.
Then, we play the card 3 in the second operation. The cards in the pile are [1,2,3], in which the cards are piled up in increasing order.
Example 2
Play an empty card and draw the card 1, then play 1, 2, 3 in order.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e6 + 5;
int n;
int num[MAXN];
int vis[MAXN];
int main() {
num[0] = 1;
cin >> n;
for (int i = 1; i <= n; i++) {
int tmp;
cin >> tmp;
vis[tmp]++;
}
for (int i = 1; i <= n; i++) cin >> num[i];
int pos;
for (int i = n - 1; i >= 0; i--) {
if (num[i + 1] - num[i] != 1 || num[i] == 0) {
pos = i + 1;
break;
}
}
if (num[pos] == 1) {
int flag = 1;
for (int i = 1; i < pos; i++) {
if (num[i] && num[i] - i <= num[n]) {
flag = 0;
break;
}
}
if (flag == 1) {
cout << pos - 1;
return 0;
}
}
int ans = 0;
for (int i = 1; i <= n; i++)
if (num[i]) ans = max(ans, i - num[i] + 1);
cout << (ans + n);
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Right now she actually isn't. But she will be, if you don't solve this problem.
You are given integers n, k, A and B. There is a number x, which is initially equal to n. You are allowed to perform two types of operations:
1. Subtract 1 from x. This operation costs you A coins.
2. Divide x by k. Can be performed only if x is divisible by k. This operation costs you B coins.
What is the minimum amount of coins you have to pay to make x equal to 1?
Input
The first line contains a single integer n (1 β€ n β€ 2Β·109).
The second line contains a single integer k (1 β€ k β€ 2Β·109).
The third line contains a single integer A (1 β€ A β€ 2Β·109).
The fourth line contains a single integer B (1 β€ B β€ 2Β·109).
Output
Output a single integer β the minimum amount of coins you have to pay to make x equal to 1.
Examples
Input
9
2
3
1
Output
6
Input
5
5
2
20
Output
8
Input
19
3
4
2
Output
12
Note
In the first testcase, the optimal strategy is as follows:
* Subtract 1 from x (9 β 8) paying 3 coins.
* Divide x by 2 (8 β 4) paying 1 coin.
* Divide x by 2 (4 β 2) paying 1 coin.
* Divide x by 2 (2 β 1) paying 1 coin.
The total cost is 6 coins.
In the second test case the optimal strategy is to subtract 1 from x 4 times paying 8 coins in total.
### Response
```cpp
#include <bits/stdc++.h>
int main() {
long long n, k, a, b;
std::cin >> n >> k >> a >> b;
long long sum = 0;
while (n > 1) {
if (k == 1) {
sum += (n - 1) * a;
break;
}
if (n % k != 0) {
if (n / k == 0) {
sum += (n - 1) * a;
break;
} else {
sum += (n % k) * a;
n -= n % k;
}
}
if (n % k == 0) {
long long d = n - n / k;
if (d * a < b) {
sum += d * a;
} else {
sum += b;
}
n = n / k;
}
}
std::cout << sum << std::endl;
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Suppose you are living with two cats: A and B. There are n napping spots where both cats usually sleep.
Your cats like to sleep and also like all these spots, so they change napping spot each hour cyclically:
* Cat A changes its napping place in order: n, n - 1, n - 2, ..., 3, 2, 1, n, n - 1, ... In other words, at the first hour it's on the spot n and then goes in decreasing order cyclically;
* Cat B changes its napping place in order: 1, 2, 3, ..., n - 1, n, 1, 2, ... In other words, at the first hour it's on the spot 1 and then goes in increasing order cyclically.
The cat B is much younger, so they have a strict hierarchy: A and B don't lie together. In other words, if both cats'd like to go in spot x then the A takes this place and B moves to the next place in its order (if x < n then to x + 1, but if x = n then to 1). Cat B follows his order, so it won't return to the skipped spot x after A frees it, but will move to the spot x + 2 and so on.
Calculate, where cat B will be at hour k?
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first and only line of each test case contains two integers n and k (2 β€ n β€ 10^9; 1 β€ k β€ 10^9) β the number of spots and hour k.
Output
For each test case, print one integer β the index of the spot where cat B will sleep at hour k.
Example
Input
7
2 1
2 2
3 1
3 2
3 3
5 5
69 1337
Output
1
2
1
3
2
2
65
Note
In the first and second test cases n = 2, so:
* at the 1-st hour, A is on spot 2 and B is on 1;
* at the 2-nd hour, A moves to spot 1 and B β to 2.
If n = 3 then:
* at the 1-st hour, A is on spot 3 and B is on 1;
* at the 2-nd hour, A moves to spot 2; B'd like to move from 1 to 2, but this spot is occupied, so it moves to 3;
* at the 3-rd hour, A moves to spot 1; B also would like to move from 3 to 1, but this spot is occupied, so it moves to 2.
In the sixth test case:
* A's spots at each hour are [5, 4, 3, 2, 1];
* B's spots at each hour are [1, 2, 4, 5, 2].
### Response
```cpp
#include <bits/stdc++.h>
#define fastIO ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr)
//#pragma G++ optimize("Ofast,no-stack-protector")
//#pragma G++ optimize("-O3,-O2,-O1")
//#pragma G++ target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
//#pragma G++ optimize("unroll-loops")
#define endl "\n"
#define amd and
#define pb push_back
#define f first
#define s second
#define ret return
#define cont continue
#define lcm(x,y) (x*y/__gcd(x,y))
#define all(x) x.begin(),x.end()
#define y1 Popajopa
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef unsigned long long ull;
typedef pair<ll,ll> pll;
typedef long double ld;
typedef char ch;
typedef string str;
typedef bool bl;
typedef void vd;
const ll mod=1e9+7;
/// ///////////////////////////////////////////////////////
ll t,l,o,xj,yj,n,m;
ll oo=1e18,q1,q2;
char c[1001][1001];
ll b[300005],dp[1001][1001],a;
//string s;
pair<ll,ll>q[100001];
int main()
{
ll t;
cin >> t;
while(t--)
{
ll n,k;
cin >> n >> k;
if(n%2==0)
{
if(k%n==0)cout << n << endl;
else cout << k%n << endl;
}
else
{
k--;
if(((k%n + k/((n-1)/2))+1)%n==0)cout << n << endl;
else cout << ((k%n + k/((n-1)/2))+1)%n << endl;
}
}
return 0;
}
/*
4 4
4 2
2 4
1 1 1 1
1 1 1 0
1 1 1 0
1 0 0 0
*/
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Two positive integers a and b have a sum of s and a bitwise XOR of x. How many possible values are there for the ordered pair (a, b)?
Input
The first line of the input contains two integers s and x (2 β€ s β€ 1012, 0 β€ x β€ 1012), the sum and bitwise xor of the pair of positive integers, respectively.
Output
Print a single integer, the number of solutions to the given conditions. If no solutions exist, print 0.
Examples
Input
9 5
Output
4
Input
3 3
Output
2
Input
5 2
Output
0
Note
In the first sample, we have the following solutions: (2, 7), (3, 6), (6, 3), (7, 2).
In the second sample, the only solutions are (1, 2) and (2, 1).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int po(long long int a, long long int b) {
long long int s = 1;
for (int i = 0; i < b; ++i) s *= a;
return s;
}
int main() {
long long int s, x;
cin >> s >> x;
if (s - x < 0 || (s - x) % 2 != 0) {
cout << 0;
return 0;
}
s = (s - x) / 2;
long long int c = 0;
long long int t = 0;
long long int y = 0;
while (s > 0 || x > 0) {
int d = s % 2;
int d2 = x % 2;
s /= 2;
x /= 2;
if (d == 0 && d2 == 1) {
++y;
++c;
}
if (d == 1 && d2 == 1) {
cout << 0;
return 0;
}
++t;
if (d == 0 && d2 == 0) ++y;
}
long long int r = 0;
if (t == y) r = 2;
cout << po(2, c) - r;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i.
You are given m queries. The i-th query is given as an integer q_i. In this query you need to calculate the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 2 β
10^5) β the number of vertices in the tree and the number of queries.
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i β the labels of vertices it connects (1 β€ u_i, v_i β€ n, u_i β v_i) and the weight of the edge (1 β€ w_i β€ 2 β
10^5). It is guaranteed that the given edges form a tree.
The last line of the input contains m integers q_1, q_2, ..., q_m (1 β€ q_i β€ 2 β
10^5), where q_i is the maximum weight of an edge in the i-th query.
Output
Print m integers β the answers to the queries. The i-th value should be equal to the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i.
Queries are numbered from 1 to m in the order of the input.
Examples
Input
7 5
1 2 1
3 2 3
2 4 1
4 5 2
5 7 4
3 6 2
5 2 3 4 1
Output
21 7 15 21 3
Input
1 2
1 2
Output
0 0
Input
3 3
1 2 1
2 3 2
1 3 2
Output
1 3 3
Note
The picture shows the tree from the first example: <image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long maxn = 205;
inline long long read() {
char c = getchar();
long long t = 0, f = 1;
while (!isdigit(c)) {
if (c == '-') f = -1;
c = getchar();
}
while (isdigit(c)) {
t = (t << 3) + (t << 1) + (c ^ 48);
c = getchar();
}
return t * f;
}
long long n, k, a[maxn];
struct edge {
long long v, p;
} e[maxn << 1];
long long h[maxn], cnt;
inline void add(long long a, long long b) {
e[++cnt].p = h[a];
e[cnt].v = b;
h[a] = cnt;
e[++cnt].p = h[b];
e[cnt].v = a;
h[b] = cnt;
}
long long dp[maxn][maxn];
void dfs(long long u, long long fa) {
dp[u][0] = a[u];
for (long long i = h[u]; i; i = e[i].p) {
long long v = e[i].v;
if (v == fa) continue;
dfs(v, u);
}
for (long long dep = 0; dep < n; dep++) {
if (dep == 0) {
for (long long i = h[u]; i; i = e[i].p) {
long long v = e[i].v;
if (v == fa) continue;
dp[u][dep] += dp[v][max(0ll, k - dep - 1)];
}
} else {
for (long long i = h[u]; i; i = e[i].p) {
long long v = e[i].v;
if (v == fa) continue;
long long cur = dp[v][dep - 1];
for (long long i = h[u]; i; i = e[i].p) {
long long v2 = e[i].v;
if (v2 == v || v2 == fa) continue;
cur += dp[v2][max(dep - 1, k - dep - 1)];
}
dp[u][dep] = max(dp[u][dep], cur);
}
}
}
for (long long dep = n - 1; dep > 0; dep--) {
dp[u][dep - 1] = max(dp[u][dep], dp[u][dep - 1]);
}
}
signed main() {
n = read(), k = read();
k++;
for (long long i = 1; i <= n; i++) a[i] = read();
for (long long i = 1; i < n; i++) {
long long a = read(), b = read();
add(a, b);
}
dfs(1, 0);
printf("%lld\n", dp[1][0]);
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
In this problem, we only consider strings consisting of lowercase English letters.
Strings s and t are said to be isomorphic when the following conditions are satisfied:
* |s| = |t| holds.
* For every pair i, j, one of the following holds:
* s_i = s_j and t_i = t_j.
* s_i \neq s_j and t_i \neq t_j.
For example, `abcac` and `zyxzx` are isomorphic, while `abcac` and `ppppp` are not.
A string s is said to be in normal form when the following condition is satisfied:
* For every string t that is isomorphic to s, s \leq t holds. Here \leq denotes lexicographic comparison.
For example, `abcac` is in normal form, but `zyxzx` is not since it is isomorphic to `abcac`, which is lexicographically smaller than `zyxzx`.
You are given an integer N. Print all strings of length N that are in normal form, in lexicographically ascending order.
Constraints
* 1 \leq N \leq 10
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Assume that there are K strings of length N that are in normal form: w_1, \ldots, w_K in lexicographical order. Output should be in the following format:
w_1
:
w_K
Output
Assume that there are K strings of length N that are in normal form: w_1, \ldots, w_K in lexicographical order. Output should be in the following format:
w_1
:
w_K
Examples
Input
1
Output
a
Input
2
Output
aa
ab
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int n;
void dfs(string s, char now) {
if(s.size()==n) {
cout<<s<<endl;
return;
}
for(char i='a';i<now;i++) {
dfs(s+i,now);
}
dfs(s+now,now+1);
}
int main() {
cin>>n;
dfs("",'a');
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
You are given an integer value x and a string s consisting of digits from 1 to 9 inclusive.
A substring of a string is a contiguous subsequence of that string.
Let f(l, r) be the sum of digits of a substring s[l..r].
Let's call substring s[l_1..r_1] x-prime if
* f(l_1, r_1) = x;
* there are no values l_2, r_2 such that
* l_1 β€ l_2 β€ r_2 β€ r_1;
* f(l_2, r_2) β x;
* x is divisible by f(l_2, r_2).
You are allowed to erase some characters from the string. If you erase a character, the two resulting parts of the string are concatenated without changing their order.
What is the minimum number of characters you should erase from the string so that there are no x-prime substrings in it? If there are no x-prime substrings in the given string s, then print 0.
Input
The first line contains a string s (1 β€ |s| β€ 1000). s contains only digits from 1 to 9 inclusive.
The second line contains an integer x (1 β€ x β€ 20).
Output
Print a single integer β the minimum number of characters you should erase from the string so that there are no x-prime substrings in it. If there are no x-prime substrings in the given string s, then print 0.
Examples
Input
116285317
8
Output
2
Input
314159265359
1
Output
2
Input
13
13
Output
0
Input
3434343434
7
Output
5
Note
In the first example there are two 8-prime substrings "8" and "53". You can erase these characters to get rid of both: "116285317". The resulting string "1162317" contains no 8-prime substrings. Removing these characters is also a valid answer: "116285317".
In the second example you just have to erase both ones.
In the third example there are no 13-prime substrings. There are no substrings with the sum of digits equal to 13 at all.
In the fourth example you can have neither "34", nor "43" in a string. Thus, you have to erase either all threes or all fours. There are 5 of each of them, so it doesn't matter which.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e3 + 5;
const int MAXX = 20 + 5;
const int inf = 0x3f3f3f3f;
template <const char minc = '0', const int MAXD = 10>
struct Aho_Corasick {
struct Node {
int link[MAXD], suff;
bool leaf;
Node(void) : suff(-1), leaf(0) { memset(link, -1, sizeof(link)); }
};
vector<Node> p;
Aho_Corasick(void) { p.resize(1); }
Aho_Corasick(const vector<string> &vec) {
p.resize(1);
build(vec);
}
inline void clear(void) { p.resize(1); }
inline int size(void) { return (int)p.size(); }
void insert(const string &s) {
int u = 0;
for (int i = 0; i < (int)s.size(); ++i) {
if (p[u].link[s[i] - minc] == -1)
p[u].link[s[i] - minc] = (int)p.size(), p.push_back(Node());
u = p[u].link[s[i] - minc];
}
p[u].leaf = 1;
}
void build(void) {
queue<int> q;
p[0].suff = 0;
q.push(0);
while (!q.empty()) {
int u = q.front();
q.pop();
for (int i = 0; i < MAXD; ++i) {
int &v = p[u].link[i];
if (~v)
p[v].suff = u ? p[p[u].suff].link[i] : 0, q.push(v);
else
v = u ? p[p[u].suff].link[i] : 0;
}
}
}
void build(const vector<string> &vec) {
for (int i = 0; i < (int)vec.size(); ++i) insert(vec[i]);
build();
}
inline bool is_leaf(int u) { return p[u].leaf; }
inline int link(int u, char c) { return p[u].link[c - minc]; }
};
int x;
char a[MAXX];
inline bool check(int pos) {
for (int i = 1; i < pos; ++i) {
int sum = 0;
for (int j = i; j < pos; ++j) {
sum += a[j] - '0';
if (sum < x && x % sum == 0) return 0;
}
}
return 1;
}
Aho_Corasick<'0', 10> ac_auto;
void dfs(int sum, int pos) {
if (sum > x) return;
if (sum == x) {
if (check(pos)) ac_auto.insert(string(a + 1, a + pos));
return;
}
for (int i = 1; i <= 9 && sum + i <= x; ++i)
a[pos] = i + '0', dfs(sum + i, pos + 1);
}
char s[MAXN];
int main(void) {
scanf("%s%d", s + 1, &x);
int n = strlen(s + 1);
dfs(0, 1);
ac_auto.build();
int tot = ac_auto.size();
vector<int> dp(tot, inf);
dp[0] = 0;
for (int i = 1; i <= n; ++i) {
vector<int> ndp(tot, inf);
for (int j = 0; j < tot; ++j)
if (dp[j] != inf) {
ndp[j] = min(ndp[j], dp[j] + 1);
int k = ac_auto.link(j, s[i]);
if (!ac_auto.is_leaf(k)) ndp[k] = min(ndp[k], dp[j]);
}
dp = ndp;
}
printf("%d", *min_element(dp.begin(), dp.end()));
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Little Chris is participating in a graph cutting contest. He's a pro. The time has come to test his skills to the fullest.
Chris is given a simple undirected connected graph with n vertices (numbered from 1 to n) and m edges. The problem is to cut it into edge-distinct paths of length 2. Formally, Chris has to partition all edges of the graph into pairs in such a way that the edges in a single pair are adjacent and each edge must be contained in exactly one pair.
For example, the figure shows a way Chris can cut a graph. The first sample test contains the description of this graph.
<image>
You are given a chance to compete with Chris. Find a way to cut the given graph or determine that it is impossible!
Input
The first line of input contains two space-separated integers n and m (1 β€ n, m β€ 105), the number of vertices and the number of edges in the graph. The next m lines contain the description of the graph's edges. The i-th line contains two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), the numbers of the vertices connected by the i-th edge. It is guaranteed that the given graph is simple (without self-loops and multi-edges) and connected.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
If it is possible to cut the given graph into edge-distinct paths of length 2, output <image> lines. In the i-th line print three space-separated integers xi, yi and zi, the description of the i-th path. The graph should contain this path, i.e., the graph should contain edges (xi, yi) and (yi, zi). Each edge should appear in exactly one path of length 2. If there are multiple solutions, output any of them.
If it is impossible to cut the given graph, print "No solution" (without quotes).
Examples
Input
8 12
1 2
2 3
3 4
4 1
1 3
2 4
3 5
3 6
5 6
6 7
6 8
7 8
Output
1 2 4
1 3 2
1 4 3
5 3 6
5 6 8
6 7 8
Input
3 3
1 2
2 3
3 1
Output
No solution
Input
3 2
1 2
2 3
Output
1 2 3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
int N, M;
vector<int> adj[maxn];
int cnt = 0, num[maxn];
vector<pair<int, pair<int, int>>> res;
bool dfs(int u, int p = 0) {
num[u] = ++cnt;
int cur = 0;
for (int v : adj[u]) {
if (v == p) continue;
if ((num[v] != 0 && num[v] < num[u]) || (num[v] == 0 && dfs(v, u))) {
if (cur == 0)
cur = v;
else
res.push_back(make_pair(cur, make_pair(u, v))), cur = 0;
}
}
if (cur == 0)
return true;
else {
if (p != 0) res.push_back(make_pair(p, make_pair(u, cur)));
return false;
}
}
signed main(void) {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> N >> M;
for (int i = 1; i <= M; ++i) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
if (M & 1) {
cout << "No solution";
return 0;
}
for (int i = 1; i <= N; ++i) {
if (num[i] == 0) dfs(i);
}
for (auto& x : res)
cout << x.first << ' ' << x.second.first << ' ' << x.second.second << '\n';
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Ikta loves fast programs. Recently, I'm trying to speed up the division program. However, it doesn't get much faster, so I thought it would be better to make it faster only for "common sense and typical" inputs. The problem Ikta is trying to solve is as follows.
For a given non-negative integer n, divide p (n) β 1-digit positive integer 11 ... 1 by p (n) in decimal notation. However, p (n) represents the smallest prime number larger than 22 {... 2} (n 2). Let p (0) = 2.
Your job is to complete the program faster than Ikta.
Input
The input is given in the following format.
n
Given the non-negative integer n of the input in question.
Constraints
Each variable being input satisfies the following constraints.
* 0 β€ n <1000
Output
Print the solution to the problem on one line.
Examples
Input
0
Output
1
Input
1
Output
2
Input
2
Output
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int n; cin >> n;
if(n==0 || n==2) cout << 1;
else if(n==1) cout << 2;
else cout << 0;
cout << endl;
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
You are given a multiset of n integers. You should select exactly k of them in a such way that the difference between any two of them is divisible by m, or tell that it is impossible.
Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in multiset of selected numbers should not exceed the number of its occurrences in the original multiset.
Input
First line contains three integers n, k and m (2 β€ k β€ n β€ 100 000, 1 β€ m β€ 100 000) β number of integers in the multiset, number of integers you should select and the required divisor of any pair of selected integers.
Second line contains n integers a1, a2, ..., an (0 β€ ai β€ 109) β the numbers in the multiset.
Output
If it is not possible to select k numbers in the desired way, output Β«NoΒ» (without the quotes).
Otherwise, in the first line of output print Β«YesΒ» (without the quotes). In the second line print k integers b1, b2, ..., bk β the selected numbers. If there are multiple possible solutions, print any of them.
Examples
Input
3 2 3
1 8 4
Output
Yes
1 4
Input
3 3 3
1 8 4
Output
No
Input
4 3 5
2 7 7 7
Output
Yes
2 7 7
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
long long n, k, m, a[N], Map[N];
vector<long long> ans;
int main() {
ios_base::sync_with_stdio(false), cin.tie(NULL);
cin >> n >> k >> m;
for (int i = 0; i < n; i++) {
cin >> a[i];
Map[a[i] % m]++;
}
for (int i = 0; i < m; i++) {
if (Map[i] >= k) {
cout << "Yes" << endl;
for (int j = 0; j < n && k; j++) {
if (a[j] % m == i) {
cout << a[j] << ' ';
k--;
}
}
return 0;
}
}
cout << "No" << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
In "Takahashi-ya", a ramen restaurant, a bowl of ramen costs 700 yen (the currency of Japan), plus 100 yen for each kind of topping (boiled egg, sliced pork, green onions).
A customer ordered a bowl of ramen and told which toppings to put on his ramen to a clerk. The clerk took a memo of the order as a string S. S is three characters long, and if the first character in S is `o`, it means the ramen should be topped with boiled egg; if that character is `x`, it means the ramen should not be topped with boiled egg. Similarly, the second and third characters in S mean the presence or absence of sliced pork and green onions on top of the ramen.
Write a program that, when S is given, prints the price of the corresponding bowl of ramen.
Constraints
* S is a string of length 3.
* Each character in S is `o` or `x`.
Input
Input is given from Standard Input in the following format:
S
Output
Print the price of the bowl of ramen corresponding to S.
Examples
Input
oxo
Output
900
Input
ooo
Output
1000
Input
xxx
Output
700
### Response
```cpp
#include<cstdio>
int main() {
char s[4];
int val = 700;
scanf("%s", s);
for (int i = 0; i < 3; i++) {
if (s[i] == 'o')val += 100;
}
printf("%d", val);
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Little Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.
You are given three segments on the plane. They form the letter A if the following conditions hold:
* Two segments have common endpoint (lets call these segments first and second), while the third segment connects two points on the different segments.
* The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees.
* The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4).
Input
The first line contains one integer t (1 β€ t β€ 10000) β the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers β coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.
Output
Output one line for each test case. Print Β«YESΒ» (without quotes), if the segments form the letter A and Β«NOΒ» otherwise.
Examples
Input
3
4 4 6 0
4 1 5 2
4 0 4 4
0 0 0 6
0 6 2 -4
1 1 0 1
0 0 0 5
0 5 2 -1
1 2 0 1
Output
YES
NO
YES
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int inf = ~0U >> 1;
const long long LINF = ~(((long long)0x1) << 63) / 2;
template <class T>
bool get_max(T& a, T& b) {
return b > a ? a = b, 1 : 0;
}
template <class T>
bool get_min(T& a, T& b) {
return b < a ? a = b, 1 : 0;
}
int sgn(double d) { return d > 1e-10 ? 1 : (d < -1e-10 ? -1 : 0); }
inline double sqr(double x) { return x * x; }
int dbcmp(double x, double y) { return sgn(x - y); }
struct point {
double x, y;
point(){};
point(double _x, double _y) {
x = _x;
y = _y;
}
void input() { scanf("%lf%lf", &x, &y); }
void output() { printf("%lf %lf", &x, &y); }
double norm() const { return sqrt(sqr(x) + sqr(y)); }
double len() { return sqrt(len2()); }
double len2() { return x * x + y * y; }
double dis(const point& p) {
return sqrt((p.x - x) * (p.x - x) + (p.y - y) * (p.y - y));
}
point trunc(double l) {
if (sgn(len()) == 0) return *this;
double r = l / len();
return point(x * r, y * r);
}
point rotate_left() const { return point(-y, x); }
point rotate_left(double ang) const {
double c = cos(ang), s = sin(ang);
return point(x * c - y * s, y * c + x * s);
}
point rotate_right() const { return point(y, -x); }
point rotate_right(double ang) const {
double c = cos(ang), s = sin(ang);
return point(x * c + y * s, y * c - x * s);
}
point rotate(point p, double angle) {
point v = *this - p;
double c = cos(angle), s = sin(angle);
return point(p.x + v.x * c - v.y * s, p.y + v.x * s + v.y * c);
}
point unify() { return *this / len(); }
point operator+(const point& p) { return point(x + p.x, y + p.y); }
point operator-(const point& p) { return point(x - p.x, y - p.y); }
point operator*(double r) { return point(x * r, y * r); }
point operator/(double r) { return point(x / r, y / r); }
point operator=(const point& p) {
x = p.x;
y = p.y;
return *this;
}
bool operator==(const point& p) {
return sgn(x - p.x) == 0 && sgn(y - p.y) == 0;
}
bool operator!=(const point& p) { return !(*this == p); }
bool operator<(const point& p) {
return sgn(x - p.x) == 0 ? sgn(y - p.y) < 0 : x < p.x;
}
bool operator>(const point& p) {
return sgn(x - p.x) == 0 ? sgn(y - p.y) > 0 : x > p.x;
}
double operator*(point b) { return (x * b.y - y * b.x); }
};
struct line {
point a, b;
line() {}
line(point _a, point _b) {
a = _a;
b = _b;
}
line operator=(const line& l) {
a = l.a;
b = l.b;
return *this;
}
line swap() {
std::swap(a, b);
return *this;
}
};
double dot(point p, point q) { return p.x * q.x + p.y * q.y; }
double xmult(point p1, point p2) { return p1.x * p2.y - p1.y * p2.x; }
double len(point p) { return p.x * p.x + p.y * p.y; }
bool is_online(point p, line l) {
if (xmult(p - l.a, l.b - l.a) == 0) {
if (p.x >= min(l.a.x, l.b.x) && p.x <= max(l.a.x, l.b.x) &&
p.y >= min(l.a.y, l.b.y) && p.y <= max(l.a.y, l.b.y))
return true;
else
return false;
}
return false;
}
line l1, l2, l3;
bool check(line l1, line l2, line l3) {
double re = dot(l1.b - l1.a, l2.b - l2.a);
if (xmult(l1.b - l1.a, l2.b - l2.a) == 0 || re < 0) return false;
if (is_online(l3.a, l1) && is_online(l3.b, l2)) {
double len1 = len(l1.a - l3.a);
double len2 = len(l1.b - l3.a);
double mmin = min(len1, len2);
double mmax = max(len1, len2);
if (16.0 * mmin - mmax >= 0) {
len1 = len(l2.a - l3.b);
len2 = len(l2.b - l3.b);
mmin = min(len1, len2);
mmax = max(len1, len2);
if (16 * mmin - mmax >= 0)
return true;
else
return false;
} else
return false;
} else if (is_online(l3.b, l1) && is_online(l3.a, l2)) {
double len1 = len(l1.a - l3.b);
double len2 = len(l1.b - l3.b);
double mmin = min(len1, len2);
double mmax = max(len1, len2);
if (16.0 * mmin - mmax >= 0) {
len1 = len(l2.a - l3.a);
len2 = len(l2.b - l3.a);
mmin = min(len1, len2);
mmax = max(len1, len2);
if (16 * mmin - mmax >= 0)
return true;
else
return false;
} else
return false;
} else {
return false;
}
}
void solve() {
int ok1 = 0;
if (l1.a == l2.a) {
ok1 = check(l1, l2, l3);
}
if (l1.a == l2.b) {
ok1 = ok1 + check(l1, l2.swap(), l3);
l2.swap();
}
if (l1.b == l2.a) {
ok1 = ok1 + check(l1.swap(), l2, l3);
l1.swap();
}
if (l1.b == l2.b) {
ok1 = ok1 + check(l1.swap(), l2.swap(), l3);
l1.swap();
l2.swap();
}
if (l1.a == l3.a) {
ok1 = ok1 + check(l1, l3, l2);
}
if (l1.a == l3.b) {
ok1 = ok1 + check(l1, l3.swap(), l2);
l3.swap();
}
if (l1.b == l3.a) {
ok1 = ok1 + check(l1.swap(), l3, l2);
l1.swap();
}
if (l1.b == l3.b) {
ok1 = ok1 + check(l1.swap(), l3.swap(), l2);
l1.swap();
l3.swap();
}
if (l2.a == l3.a) {
ok1 = ok1 + check(l2, l3, l1);
}
if (l2.a == l3.b) {
ok1 = ok1 + check(l2, l3.swap(), l1);
l3.swap();
}
if (l2.b == l3.a) {
ok1 = ok1 + check(l2.swap(), l3, l1);
l2.swap();
}
if (l2.b == l3.b) {
ok1 = ok1 + check(l2.swap(), l3.swap(), l1);
l2.swap();
l3.swap();
}
if (ok1 > 0)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
int main() {
int T;
cin >> T;
while (T--) {
cin >> l1.a.x >> l1.a.y >> l1.b.x >> l1.b.y;
cin >> l2.a.x >> l2.a.y >> l2.b.x >> l2.b.y;
cin >> l3.a.x >> l3.a.y >> l3.b.x >> l3.b.y;
solve();
}
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
You are given an undirected graph with n vertices. There are no edge-simple cycles with the even length in it. In other words, there are no cycles of even length that pass each edge at most once. Let's enumerate vertices from 1 to n.
You have to answer q queries. Each query is described by a segment of vertices [l; r], and you have to count the number of its subsegments [x; y] (l β€ x β€ y β€ r), such that if we delete all vertices except the segment of vertices [x; y] (including x and y) and edges between them, the resulting graph is bipartite.
Input
The first line contains two integers n and m (1 β€ n β€ 3Β·105, 1 β€ m β€ 3Β·105) β the number of vertices and the number of edges in the graph.
The next m lines describe edges in the graph. The i-th of these lines contains two integers ai and bi (1 β€ ai, bi β€ n; ai β bi), denoting an edge between vertices ai and bi. It is guaranteed that this graph does not contain edge-simple cycles of even length.
The next line contains a single integer q (1 β€ q β€ 3Β·105) β the number of queries.
The next q lines contain queries. The i-th of these lines contains two integers li and ri (1 β€ li β€ ri β€ n) β the query parameters.
Output
Print q numbers, each in new line: the i-th of them should be the number of subsegments [x; y] (li β€ x β€ y β€ ri), such that the graph that only includes vertices from segment [x; y] and edges between them is bipartite.
Examples
Input
6 6
1 2
2 3
3 1
4 5
5 6
6 4
3
1 3
4 6
1 6
Output
5
5
14
Input
8 9
1 2
2 3
3 1
4 5
5 6
6 7
7 8
8 4
7 2
3
1 8
1 4
3 8
Output
27
8
19
Note
The first example is shown on the picture below:
<image>
For the first query, all subsegments of [1; 3], except this segment itself, are suitable.
For the first query, all subsegments of [4; 6], except this segment itself, are suitable.
For the third query, all subsegments of [1; 6] are suitable, except [1; 3], [1; 4], [1; 5], [1; 6], [2; 6], [3; 6], [4; 6].
The second example is shown on the picture below:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m, a, b, q, mx[300005];
long long acu[300005];
vector<vector<int> > adj;
int maxi, mini, p[300005];
void ciclo(int u, int v) {
if (v == u) return;
maxi = max(u, maxi);
mini = min(u, mini);
ciclo(p[u], v);
}
vector<int> vis;
void dfs(int u) {
vis[u] = 1;
for (int v : adj[u]) {
if (vis[v]) {
if (vis[v] == 1 && v != p[u]) {
maxi = mini = v;
ciclo(u, v);
mx[mini] = min(mx[mini], maxi - 1);
}
} else {
p[v] = u;
dfs(v);
}
}
vis[u] = 2;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
adj = vector<vector<int> >(n + 1);
while (m--) {
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
vis = vector<int>(n + 1);
fill(mx, mx + n + 1, n);
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
p[i] = i;
dfs(i);
}
}
for (int i = n - 1; i; i--) mx[i] = min(mx[i], mx[i + 1]);
acu[0] = 0;
for (int i = 1; i <= n; i++) acu[i] = acu[i - 1] + mx[i] - i + 1;
cin >> q;
while (q--) {
cin >> a >> b;
long long x = lower_bound(mx + 1, mx + n + 1, b) - mx;
if (x < a) {
x = b - a + 1;
cout << x * (x + 1) / 2 << '\n';
} else {
long long d = b - x + 1;
cout << d * (d + 1) / 2 + acu[x - 1] - acu[a - 1] << '\n';
}
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Developing tools for creation of locations maps for turn-based fights in a new game, Petya faced the following problem.
A field map consists of hexagonal cells. Since locations sizes are going to be big, a game designer wants to have a tool for quick filling of a field part with identical enemy units. This action will look like following: a game designer will select a rectangular area on the map, and each cell whose center belongs to the selected rectangle will be filled with the enemy unit.
More formally, if a game designer selected cells having coordinates (x1, y1) and (x2, y2), where x1 β€ x2 and y1 β€ y2, then all cells having center coordinates (x, y) such that x1 β€ x β€ x2 and y1 β€ y β€ y2 will be filled. Orthogonal coordinates system is set up so that one of cell sides is parallel to OX axis, all hexagon centers have integer coordinates and for each integer x there are cells having center with such x coordinate and for each integer y there are cells having center with such y coordinate. It is guaranteed that difference x2 - x1 is divisible by 2.
Working on the problem Petya decided that before painting selected units he wants to output number of units that will be painted on the map.
Help him implement counting of these units before painting.
<image>
Input
The only line of input contains four integers x1, y1, x2, y2 ( - 109 β€ x1 β€ x2 β€ 109, - 109 β€ y1 β€ y2 β€ 109) β the coordinates of the centers of two cells.
Output
Output one integer β the number of cells to be filled.
Examples
Input
1 1 5 5
Output
13
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long int x1, x2, y1, y2;
cin >> x1 >> y1 >> x2 >> y2;
long long int a = ((x2 + 1) - (x1 - 1)) / 2;
long long int b = ((y2 + 1) - (y1 - 1)) / 2;
long long int out = a * b + (a - 1) * (b - 1);
cout << out;
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
You are given two arrays of integers a_1,β¦,a_n and b_1,β¦,b_m.
Your task is to find a non-empty array c_1,β¦,c_k that is a subsequence of a_1,β¦,a_n, and also a subsequence of b_1,β¦,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, find any. If there are no such arrays, you should report about it.
A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero) elements. For example, [3,1] is a subsequence of [3,2,1] and [4,3,1], but not a subsequence of [1,3,3,7] and [3,10,4].
Input
The first line contains a single integer t (1β€ tβ€ 1000) β the number of test cases. Next 3t lines contain descriptions of test cases.
The first line of each test case contains two integers n and m (1β€ n,mβ€ 1000) β the lengths of the two arrays.
The second line of each test case contains n integers a_1,β¦,a_n (1β€ a_iβ€ 1000) β the elements of the first array.
The third line of each test case contains m integers b_1,β¦,b_m (1β€ b_iβ€ 1000) β the elements of the second array.
It is guaranteed that the sum of n and the sum of m across all test cases does not exceed 1000 (β_{i=1}^t n_i, β_{i=1}^t m_iβ€ 1000).
Output
For each test case, output "YES" if a solution exists, or "NO" otherwise.
If the answer is "YES", on the next line output an integer k (1β€ kβ€ 1000) β the length of the array, followed by k integers c_1,β¦,c_k (1β€ c_iβ€ 1000) β the elements of the array.
If there are multiple solutions with the smallest possible k, output any.
Example
Input
5
4 5
10 8 6 4
1 2 3 4 5
1 1
3
3
1 1
3
2
5 3
1000 2 2 2 3
3 1 5
5 5
1 2 3 4 5
1 2 3 4 5
Output
YES
1 4
YES
1 3
NO
YES
1 3
YES
1 2
Note
In the first test case, [4] is a subsequence of [10, 8, 6, 4] and [1, 2, 3, 4, 5]. This array has length 1, it is the smallest possible length of a subsequence of both a and b.
In the third test case, no non-empty subsequences of both [3] and [2] exist, so the answer is "NO".
### Response
```cpp
#include <bits/stdc++.h>
const long long infl = 1e18;
const int infi = 2e9;
const int mod = 1e9 + 7;
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long t;
cin >> t;
while (t--) {
long long n, m;
cin >> n >> m;
long long ans;
long long a[100000];
long long b[100000];
long long count = 0;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = 0; i < m; i++) {
cin >> b[i];
}
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
if (a[i] == b[j]) {
count++;
ans = a[i];
break;
}
}
if (count) {
cout << "YES"
<< "\n";
cout << 1 << " " << ans << "\n";
} else {
cout << "NO"
<< "\n";
}
}
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back.
Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that:
* this list contains all Jinotega's flights in this year (in arbitrary order),
* Jinotega has only flown from his hometown to a snooker contest and back,
* after each competition Jinotega flies back home (though they may attend a competition in one place several times),
* and finally, at the beginning of the year Jinotega was at home.
Please help them to determine Jinotega's location!
Input
In the first line of input there is a single integer n: the number of Jinotega's flights (1 β€ n β€ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport.
It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement.
Output
If Jinotega is now at home, print "home" (without quotes), otherwise print "contest".
Examples
Input
4
SVO
SVO->CDG
LHR->SVO
SVO->LHR
CDG->SVO
Output
home
Input
3
SVO
SVO->HKT
HKT->SVO
SVO->RAP
Output
contest
Note
In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n;
int main() {
cin >> n;
if (n % 2 == 0)
cout << "home";
else
cout << "contest";
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
You are given four integers: H, W, h and w (1 β€ h β€ H, 1 β€ w β€ W). Determine whether there exists a matrix such that all of the following conditions are held, and construct one such matrix if the answer is positive:
* The matrix has H rows and W columns.
* Each element of the matrix is an integer between -10^9 and 10^9 (inclusive).
* The sum of all the elements of the matrix is positive.
* The sum of all the elements within every subrectangle with h rows and w columns in the matrix is negative.
Constraints
* 1 β€ h β€ H β€ 500
* 1 β€ w β€ W β€ 500
Input
Input is given from Standard Input in the following format:
H W h w
Output
If there does not exist a matrix that satisfies all of the conditions, print `No`.
Otherwise, print `Yes` in the first line, and print a matrix in the subsequent lines in the following format:
a_{11} ... a_{1W}
:
a_{H1} ... a_{HW}
Here, a_{ij} represents the (i,\ j) element of the matrix.
Examples
Input
3 3 2 2
Output
Yes
1 1 1
1 -4 1
1 1 1
Input
2 4 1 2
Output
No
Input
3 4 2 3
Output
Yes
2 -5 8 7
3 -5 -4 -5
2 1 -1 7
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
int H, W, h, w;
cin >> H >> W >> h >> w;
if (H % h == 0 && W % w == 0) {
cout << "No\n";
return 0;
}
cout << "Yes\n";
for (int i = 0; i < H; ++i) {
for (int j = 0; j < W; ++j) {
if (i % h == h - 1 && j % w == w - 1) {
cout << -1007 * (h * w - 1) - 1 << " ";
} else {
cout << 1007 << " ";
}
}
cout << "\n";
}
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Stepan has a very big positive integer.
Let's consider all cyclic shifts of Stepan's integer (if we look at his integer like at a string) which are also integers (i.e. they do not have leading zeros). Let's call such shifts as good shifts. For example, for the integer 10203 the good shifts are the integer itself 10203 and integers 20310 and 31020.
Stepan wants to know the minimum remainder of the division by the given number m among all good shifts. Your task is to determine the minimum remainder of the division by m.
Input
The first line contains the integer which Stepan has. The length of Stepan's integer is between 2 and 200 000 digits, inclusive. It is guaranteed that Stepan's integer does not contain leading zeros.
The second line contains the integer m (2 β€ m β€ 108) β the number by which Stepan divides good shifts of his integer.
Output
Print the minimum remainder which Stepan can get if he divides all good shifts of his integer by the given number m.
Examples
Input
521
3
Output
2
Input
1001
5
Output
0
Input
5678901234567890123456789
10000
Output
123
Note
In the first example all good shifts of the integer 521 (good shifts are equal to 521, 215 and 152) has same remainder 2 when dividing by 3.
In the second example there are only two good shifts: the Stepan's integer itself and the shift by one position to the right. The integer itself is 1001 and the remainder after dividing it by 5 equals 1. The shift by one position to the right equals to 1100 and the remainder after dividing it by 5 equals 0, which is the minimum possible remainder.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = .2e6 + 5;
long long pw[N], hs[N];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
string s;
cin >> s;
int n = s.length();
s = '_' + s;
int m;
cin >> m;
pw[0] = 1;
for (int i = 1; i <= n; i++) {
hs[i] = (hs[i - 1] * 10 + (s[i] - '0')) % m;
pw[i] = (pw[i - 1] * 10) % m;
}
long long ans = m;
for (int i = 1; i <= n; i++) {
if (s[i] == '0') continue;
long long val1 = hs[i - 1];
long long val2 = (hs[n] - hs[i - 1] * pw[n - i + 1]) % m;
if (val2 < 0) val2 += m;
long long cnt = (val2 * pw[i - 1] + val1) % m;
ans = min(ans, cnt);
}
cout << ans << "\n";
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Volodya is an odd boy and his taste is strange as well. It seems to him that a positive integer number is beautiful if and only if it is divisible by each of its nonzero digits. We will not argue with this and just count the quantity of beautiful numbers in given ranges.
Input
The first line of the input contains the number of cases t (1 β€ t β€ 10). Each of the next t lines contains two natural numbers li and ri (1 β€ li β€ ri β€ 9 Β·1018).
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).
Output
Output should contain t numbers β answers to the queries, one number per line β quantities of beautiful numbers in given intervals (from li to ri, inclusively).
Examples
Input
1
1 9
Output
9
Input
1
12 15
Output
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long d[25][50][2550];
int a[50];
int hh[2550];
long long gcd(long long a, long long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
long long lcm(long long a, long long b) { return a / gcd(a, b) * b; }
long long dfs(int len, int pl, int px, bool l) {
if (len == -1) return px % pl == 0;
if (!l && d[len][hh[pl]][px] != -1) return d[len][hh[pl]][px];
int n = l ? a[len] : 9;
long long sum = 0;
for (int i = 0; i <= n; i++) {
int nowpx = (px * 10 + i) % 2520;
int nowpl = pl;
if (i) nowpl = lcm(pl, i);
sum += dfs(len - 1, nowpl, nowpx, l && i == n);
}
if (!l) d[len][hh[pl]][px] = sum;
return sum;
}
long long CC(long long x) {
int n = 0;
while (x) {
a[n++] = x % 10;
x /= 10;
}
return dfs(n - 1, 1, 0, 1);
}
int main() {
int u = 0;
for (int i = 1; i <= 2520; i++) {
if (2520 % i == 0) hh[i] = ++u;
}
int T;
while (~scanf("%d", &T)) {
memset(d, -1, sizeof(d));
while (T--) {
long long a, b;
scanf("%I64d%I64d", &a, &b);
printf("%I64d\n", CC(b) - CC(a - 1));
}
}
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied:
* a12 + a22 + ... + an2 β₯ x
* a1 + a2 + ... + an β€ y
Input
The first line contains three space-separated integers n, x and y (1 β€ n β€ 105, 1 β€ x β€ 1012, 1 β€ y β€ 106).
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is recommended to use cin, cout streams or the %I64d specificator.
Output
Print n positive integers that satisfy the conditions, one integer per line. If such numbers do not exist, print a single number "-1". If there are several solutions, print any of them.
Examples
Input
5 15 15
Output
4
4
1
1
2
Input
2 3 2
Output
-1
Input
1 99 11
Output
11
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
long long n, x, y;
cin >> n >> x >> y;
if (y < n || (n - 1) + (y - n + 1) * (y - n + 1) < x) {
cout << -1;
} else {
for (int i = 1; i < n; i++) cout << 1 << endl;
cout << y - n + 1;
}
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Let's call an array a of size n coprime iff gcd(a1, a2, ..., an) = 1, where gcd is the greatest common divisor of the arguments.
You are given two numbers n and k. For each i (1 β€ i β€ k) you have to determine the number of coprime arrays a of size n such that for every j (1 β€ j β€ n) 1 β€ aj β€ i. Since the answers can be very large, you have to calculate them modulo 109 + 7.
Input
The first line contains two integers n and k (1 β€ n, k β€ 2Β·106) β the size of the desired arrays and the maximum upper bound on elements, respectively.
Output
Since printing 2Β·106 numbers may take a lot of time, you have to output the answer in such a way:
Let bi be the number of coprime arrays with elements in range [1, i], taken modulo 109 + 7. You have to print <image>, taken modulo 109 + 7. Here <image> denotes bitwise xor operation (^ in C++ or Java, xor in Pascal).
Examples
Input
3 4
Output
82
Input
2000000 8
Output
339310063
Note
Explanation of the example:
Since the number of coprime arrays is large, we will list the arrays that are non-coprime, but contain only elements in range [1, i]:
For i = 1, the only array is coprime. b1 = 1.
For i = 2, array [2, 2, 2] is not coprime. b2 = 7.
For i = 3, arrays [2, 2, 2] and [3, 3, 3] are not coprime. b3 = 25.
For i = 4, arrays [2, 2, 2], [3, 3, 3], [2, 2, 4], [2, 4, 2], [2, 4, 4], [4, 2, 2], [4, 2, 4], [4, 4, 2] and [4, 4, 4] are not coprime. b4 = 55.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <class T, class U>
ostream& operator<<(ostream& o, const pair<T, U>& p) {
o << "(" << p.first << "," << p.second << ")";
return o;
}
template <class T>
ostream& operator<<(ostream& o, const vector<T>& v) {
o << "[";
for (T t : v) {
o << t << ",";
}
o << "]";
return o;
}
const ll mod = 1e9 + 7;
ll mod_pow(ll x, ll n) {
ll ret = 1;
while (n) {
if (n & 1) (ret *= x) %= mod;
(x *= x) %= mod;
n >>= 1;
}
return ret;
}
const int N = 2000002;
ll pw[N];
bool p[N];
int mu[N];
ll f[N];
vector<int> upd[N];
int main() {
int n, k;
cin >> n >> k;
fill(p, p + N, true);
fill(mu, mu + N, 1);
p[0] = p[1] = false;
for (int i = 2; i < N; ++i)
if (p[i]) {
mu[i] = -1;
for (int j = 2 * i; j < N; j += i) {
p[j] = false;
mu[j] = -mu[j];
}
if ((ll)i * i < N) {
for (int j = i * i; j < N; j += i * i) mu[j] = false;
}
}
for (int(i) = 0; (i) < (int)(N); ++(i)) pw[i] = mod_pow(i, n);
for (int i = 1; i <= k; ++i)
if (mu[i] != 0) {
for (int j = i; j <= k; j += i) upd[j].push_back(i);
}
ll ans = 0;
ll now = 0;
for (int i = 1; i <= k; ++i) {
for (int j : upd[i]) {
now -= f[j];
now += mod;
f[j] = mu[j] * pw[i / j];
now += f[j];
now += mod;
now %= mod;
}
ans += now ^ i;
ans %= mod;
}
cout << ans << "\n";
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Arkady is playing Battleship. The rules of this game aren't really important.
There is a field of n Γ n cells. There should be exactly one k-decker on the field, i. e. a ship that is k cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. For each cell Arkady knows if it is definitely empty or can contain a part of the ship.
Consider all possible locations of the ship. Find such a cell that belongs to the maximum possible number of different locations of the ship.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 100) β the size of the field and the size of the ship.
The next n lines contain the field. Each line contains n characters, each of which is either '#' (denotes a definitely empty cell) or '.' (denotes a cell that can belong to the ship).
Output
Output two integers β the row and the column of a cell that belongs to the maximum possible number of different locations of the ship.
If there are multiple answers, output any of them. In particular, if no ship can be placed on the field, you can output any cell.
Examples
Input
4 3
#..#
#.#.
....
.###
Output
3 2
Input
10 4
#....##...
.#...#....
..#..#..#.
...#.#....
.#..##.#..
.....#...#
...#.##...
.#...#.#..
.....#..#.
...#.#...#
Output
6 1
Input
19 6
##..............###
#......#####.....##
.....#########.....
....###########....
...#############...
..###############..
.#################.
.#################.
.#################.
.#################.
#####....##....####
####............###
####............###
#####...####...####
.#####..####..#####
...###........###..
....###########....
.........##........
#.................#
Output
1 8
Note
The picture below shows the three possible locations of the ship that contain the cell (3, 2) in the first sample.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct data {
int i, j, val;
};
int main() {
data mx = {0, 0, 0};
int n, k, last, i, j, a, b, c, x, y;
scanf("%d %d", &n, &k);
char ara[n][n];
int ans[n][n];
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
ans[i][j] = 0;
}
}
for (i = 0; i < n; i++) {
scanf("%s", ara[i]);
}
for (i = 0; i < n; i++) {
last = -1;
for (j = 0; j < n; j++) {
if (ara[i][j] == '#') {
for (a = last + 1; j - a >= k; a++) {
for (b = a, c = 0; c < k; c++, b++) {
ans[i][b]++;
}
}
last = j;
}
}
for (a = last + 1; n - a >= k; a++) {
for (b = a, c = 0; c < k; c++, b++) {
ans[i][b]++;
}
}
}
for (i = 0; i < n; i++) {
last = -1;
for (j = 0; j < n; j++) {
if (ara[j][i] == '#') {
for (a = last + 1; j - a >= k; a++) {
for (b = a, c = 0; c < k; c++, b++) {
ans[b][i]++;
}
}
last = j;
}
}
for (a = last + 1; n - a >= k; a++) {
for (b = a, c = 0; c < k; c++, b++) {
ans[b][i]++;
}
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (ans[i][j] > mx.val) {
mx = {i, j, ans[i][j]};
}
}
}
printf("%d %d\n", mx.i + 1, mx.j + 1);
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
We'll call a sequence of integers a good k-d sequence if we can add to it at most k numbers in such a way that after the sorting the sequence will be an arithmetic progression with difference d.
You got hold of some sequence a, consisting of n integers. Your task is to find its longest contiguous subsegment, such that it is a good k-d sequence.
Input
The first line contains three space-separated integers n, k, d (1 β€ n β€ 2Β·105; 0 β€ k β€ 2Β·105; 0 β€ d β€ 109). The second line contains n space-separated integers: a1, a2, ..., an ( - 109 β€ ai β€ 109) β the actual sequence.
Output
Print two space-separated integers l, r (1 β€ l β€ r β€ n) show that sequence al, al + 1, ..., ar is the longest subsegment that is a good k-d sequence.
If there are multiple optimal answers, print the one with the minimum value of l.
Examples
Input
6 1 2
4 3 2 8 6 2
Output
3 5
Note
In the first test sample the answer is the subsegment consisting of numbers 2, 8, 6 β after adding number 4 and sorting it becomes sequence 2, 4, 6, 8 β the arithmetic progression with difference 2.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 2e5;
int n, k, d, a[N];
struct Tree {
int l, r, v, lazy;
Tree *left, *right;
};
int mc;
Tree memory[400000], *root;
map<int, int> hash;
Tree *Build(int l, int r) {
Tree *ret = &memory[mc++];
ret->l = l, ret->r = r;
if (l == r)
ret->v = l;
else {
ret->left = Build(l, (l + r) / 2);
ret->right = Build((l + r) / 2 + 1, r);
ret->v = min(ret->left->v, ret->right->v);
}
return ret;
}
void PushDown(Tree *t) {
t->v += t->lazy;
if (t->l < t->r) {
t->left->lazy += t->lazy;
t->right->lazy += t->lazy;
}
t->lazy = 0;
}
void Modify(Tree *t, int l, int r, int v) {
PushDown(t);
if (t->l == l && t->r == r)
t->lazy += v;
else {
if (r <= t->left->r)
Modify(t->left, l, r, v);
else if (l >= t->right->l)
Modify(t->right, l, r, v);
else
Modify(t->left, l, t->left->r, v), Modify(t->right, t->right->l, r, v);
t->v = min(t->left->v + t->left->lazy, t->right->v + t->right->lazy);
}
}
int Query(Tree *t, int l, int r, int v) {
PushDown(t);
if (t->l == t->r) return t->v <= v ? l : -1;
if (t->left->v + t->left->lazy <= v && l <= t->left->r) {
int tmp = Query(t->left, l, min(r, t->left->r), v);
if (tmp != -1) return tmp;
}
if (t->right->v + t->right->lazy <= v && r >= t->right->l)
return Query(t->right, max(l, t->right->l), r, v);
return -1;
}
int ansl, ansr;
inline void Submit(int l, int r) {
if (r - l > ansr - ansl || (r - l == ansr - ansl && l < ansl))
ansl = l, ansr = r;
}
int pre[N];
void Solve(int l, int r) {
map<int, int> hash;
for (int i = l; i <= r; i++) a[i] /= d;
for (int i = l; i <= r; i++) {
map<int, int>::iterator iter = hash.find(a[i]);
if (iter == hash.end())
hash.insert(make_pair(a[i], i));
else
pre[i] = iter->second + 1, iter->second = i;
}
stack<pair<int, int> > maxi, mini;
int p = l;
for (int i = l; i <= r; i++) {
p = max(p, pre[i]);
while (!mini.empty() && a[i] <= mini.top().first) {
pair<int, int> tmp = mini.top();
mini.pop();
if (mini.empty() && p > tmp.second) continue;
Modify(root, mini.empty() ? p : mini.top().second + 1, tmp.second,
tmp.first - a[i]);
}
while (!maxi.empty() && a[i] >= maxi.top().first) {
pair<int, int> tmp = maxi.top();
maxi.pop();
if (maxi.empty() && p > tmp.second) continue;
Modify(root, maxi.empty() ? p : maxi.top().second + 1, tmp.second,
a[i] - tmp.first);
}
mini.push(make_pair(a[i], i));
maxi.push(make_pair(a[i], i));
int tmp = Query(root, p, i, i + k);
if (tmp != -1) Submit(tmp, i);
}
}
int main() {
scanf("%d%d%d", &n, &k, &d);
for (int i = 0; i < n; ++i) {
scanf("%d", a + i);
a[i] += 1000000000;
}
if (d == 0)
for (int i = 0; i < n;) {
int r = i + 1;
while (r < n && a[i] == a[r]) r++;
Submit(i, r - 1);
i = r;
}
else {
root = Build(0, n - 1);
for (int i = 0; i < n;) {
int r = i + 1;
while (r < n && a[i] % d == a[r] % d) r++;
Solve(i, r - 1);
i = r;
}
}
cout << ansl + 1 << ' ' << ansr + 1 << endl;
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Ignoring the air resistance, velocity of a freely falling object $v$ after $t$ seconds and its drop $y$ in $t$ seconds are represented by the following formulas:
$ v = 9.8 t $
$ y = 4.9 t^2 $
A person is trying to drop down a glass ball and check whether it will crack. Your task is to write a program to help this experiment.
You are given the minimum velocity to crack the ball. Your program should print the lowest possible floor of a building to crack the ball. The height of the $N$ floor of the building is defined by $5 \times N - 5$.
Input
The input consists of multiple datasets. Each dataset, a line, consists of the minimum velocity v (0 < v < 200) to crack the ball. The value is given by a decimal fraction, with at most 4 digits after the decimal point. The input ends with EOF. The number of datasets is less than or equal to 50.
Output
For each dataset, print the lowest possible floor where the ball cracks.
Example
Input
25.4
25.4
Output
8
8
### Response
```cpp
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double v;
while (cin >> v) {
cout << floor(v*v/98 + 2) << endl;
}
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Once upon a time a child got a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: A, B, C and D. Each choice has a description, and the child should find out the only one that is correct.
Fortunately the child knows how to solve such complicated test. The child will follow the algorithm:
* If there is some choice whose description at least twice shorter than all other descriptions, or at least twice longer than all other descriptions, then the child thinks the choice is great.
* If there is exactly one great choice then the child chooses it. Otherwise the child chooses C (the child think it is the luckiest choice).
You are given a multiple-choice questions, can you predict child's choose?
Input
The first line starts with "A." (without quotes), then followed the description of choice A. The next three lines contains the descriptions of the other choices in the same format. They are given in order: B, C, D. Please note, that the description goes after prefix "X.", so the prefix mustn't be counted in description's length.
Each description is non-empty and consists of at most 100 characters. Each character can be either uppercase English letter or lowercase English letter, or "_".
Output
Print a single line with the child's choice: "A", "B", "C" or "D" (without quotes).
Examples
Input
A.VFleaKing_is_the_author_of_this_problem
B.Picks_is_the_author_of_this_problem
C.Picking_is_the_author_of_this_problem
D.Ftiasch_is_cute
Output
D
Input
A.ab
B.abcde
C.ab
D.abc
Output
C
Input
A.c
B.cc
C.c
D.c
Output
B
Note
In the first sample, the first choice has length 39, the second one has length 35, the third one has length 37, and the last one has length 15. The choice D (length 15) is twice shorter than all other choices', so it is great choice. There is no other great choices so the child will choose D.
In the second sample, no choice is great, so the child will choose the luckiest choice C.
In the third sample, the choice B (length 2) is twice longer than all other choices', so it is great choice. There is no other great choices so the child will choose B.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
vector<string> A(4);
for (int i = 0; i < 4; i++) {
cin >> A[i];
A[i] = A[i].substr(2);
}
vector<int> B;
for (int i = 0; i < 4; i++) {
bool flag1 = true, flag2 = true;
for (int j = 0; j < 4; j++) {
if (i == j) continue;
if (A[i].size() < A[j].size() * 2) flag1 = false;
}
for (int j = 0; j < 4; j++) {
if (i == j) continue;
if (A[i].size() * 2 > A[j].size()) flag2 = false;
}
if (flag1 || flag2) B.push_back(i);
}
if (B.size() == 1)
cout << (char)('A' + B[0]) << endl;
else
cout << "C\n";
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle.
Ivar has n warriors, he places them on a straight line in front of the main gate, in a way that the i-th warrior stands right after (i-1)-th warrior. The first warrior leads the attack.
Each attacker can take up to a_i arrows before he falls to the ground, where a_i is the i-th warrior's strength.
Lagertha orders her warriors to shoot k_i arrows during the i-th minute, the arrows one by one hit the first still standing warrior. After all Ivar's warriors fall and all the currently flying arrows fly by, Thor smashes his hammer and all Ivar's warriors get their previous strengths back and stand up to fight again. In other words, if all warriors die in minute t, they will all be standing to fight at the end of minute t.
The battle will last for q minutes, after each minute you should tell Ivar what is the number of his standing warriors.
Input
The first line contains two integers n and q (1 β€ n, q β€ 200 000) β the number of warriors and the number of minutes in the battle.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9) that represent the warriors' strengths.
The third line contains q integers k_1, k_2, β¦, k_q (1 β€ k_i β€ 10^{14}), the i-th of them represents Lagertha's order at the i-th minute: k_i arrows will attack the warriors.
Output
Output q lines, the i-th of them is the number of standing warriors after the i-th minute.
Examples
Input
5 5
1 2 1 2 1
3 10 1 1 1
Output
3
5
4
4
3
Input
4 4
1 2 3 4
9 1 10 6
Output
1
4
4
1
Note
In the first example:
* after the 1-st minute, the 1-st and 2-nd warriors die.
* after the 2-nd minute all warriors die (and all arrows left over are wasted), then they will be revived thus answer is 5 β all warriors are alive.
* after the 3-rd minute, the 1-st warrior dies.
* after the 4-th minute, the 2-nd warrior takes a hit and his strength decreases by 1.
* after the 5-th minute, the 2-nd warrior dies.
### Response
```cpp
#include <bits/stdc++.h>
int Set(int N, int pos) { return N = N | (1 << pos); }
int reset(int N, int pos) { return N = N & ~(1 << pos); }
bool check(int N, int pos) { return (bool)(N & (1 << pos)); }
using namespace std;
const long long maxx = 2e5 + 10;
long long arr[maxx + 5], krr[maxx + 5], sum[maxx + 5];
vector<long long> v;
vector<long long>::iterator upper;
int main() {
long long n, q;
cin >> n >> q;
for (int i = 0; i < n; i++) {
long long x;
cin >> x;
arr[i] = x;
sum[i] = x;
if (i != 0) {
sum[i] += sum[i - 1];
}
v.push_back(sum[i]);
}
for (int i = 0; i < q; i++) {
long long x;
cin >> x;
krr[i] = x;
}
long long arrow = 0;
for (int i = 0; i < q; i++) {
arrow += krr[i];
upper = upper_bound(v.begin(), v.end(), arrow);
int dead = (upper - v.begin());
if (dead == n) {
arrow = 0;
dead = 0;
}
cout << n - dead << endl;
}
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
You've got an n Γ m table (n rows and m columns), each cell of the table contains a "0" or a "1".
Your task is to calculate the number of rectangles with the sides that are parallel to the sides of the table and go along the cell borders, such that the number one occurs exactly k times in the rectangle.
Input
The first line contains three space-separated integers n, m and k (1 β€ n, m β€ 2500, 0 β€ k β€ 6) β the sizes of the table and the required number of numbers one.
Next n lines each contains m characters "0" or "1". The i-th character of the j-th line corresponds to the character that is in the j-th row and the i-th column of the table.
Output
Print a single number β the number of rectangles that contain exactly k numbers one.
Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
3 3 2
101
000
101
Output
8
Input
5 5 1
00000
00000
00100
00000
00000
Output
81
Input
5 5 6
01010
10101
01010
10101
01010
Output
12
Input
3 3 0
001
010
000
Output
15
Input
4 4 0
0000
0101
0000
0000
Output
52
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline char gc() {
static char buf[100000], *p1 = buf, *p2 = buf;
return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2)
? EOF
: *p1++;
}
inline int read() {
char c = getchar();
int tot = 1;
while ((c < '0' || c > '9') && c != '-') c = getchar();
if (c == '-') {
tot = -1;
c = getchar();
}
int sum = 0;
while (c >= '0' && c <= '9') {
sum = sum * 10 + c - '0';
c = getchar();
}
return sum * tot;
}
inline void wr(long long x) {
if (x < 0) {
putchar('-');
wr(-x);
return;
}
if (x >= 10) wr(x / 10);
putchar(x % 10 + '0');
}
inline void wrn(long long x) {
wr(x);
putchar('\n');
}
inline void wri(int x) {
wr(x);
putchar(' ');
}
inline void wrn(int x, int y) {
wri(x);
wrn(y);
}
inline void wrn(int a, int b, int c) {
wri(a);
wrn(b, c);
}
int n, m, K;
long long ans;
int s[3055][3055], up[8], down[8];
inline int sum(int x1, int x2, int y1, int y2) {
return s[x2][y2] - s[x2][y1] - s[x1][y2] + s[x1][y1];
}
void work(int x1, int x2, int y1, int y2, bool dir) {
if (x1 == x2 || y1 == y2) return;
if ((x1 + 1 == x2) && (y1 + 1 == y2)) {
ans += sum(x1, x2, y1, y2) == K;
return;
}
if (dir) {
int mid = ((x1 + x2) >> 1);
work(x1, mid, y1, y2, !dir);
work(mid, x2, y1, y2, !dir);
for (int i = y1; i < y2; i++) {
up[0] = down[0] = mid;
for (int k = 1; k <= K + 1; k++) up[k] = x1, down[k] = x2;
for (int j = i + 1; j <= y2; j++) {
for (int k = 1; k <= K + 1; k++)
while (sum(up[k], mid, i, j) >= k) up[k]++;
for (int k = 1; k <= K + 1; k++)
while (sum(mid, down[k], i, j) >= k) down[k]--;
for (int k = 0; k <= K; k++)
ans += (up[k] - up[k + 1]) * (down[K - k + 1] - down[K - k]);
}
}
} else {
int mid = ((y1 + y2) >> 1);
work(x1, x2, y1, mid, !dir);
work(x1, x2, mid, y2, !dir);
for (int i = x1; i < x2; i++) {
up[0] = down[0] = mid;
for (int k = 1; k <= K + 1; k++) up[k] = y1, down[k] = y2;
for (int j = i + 1; j <= x2; j++) {
for (int k = 1; k <= K + 1; k++)
while (sum(i, j, up[k], mid) >= k) up[k]++;
for (int k = 1; k <= K + 1; k++)
while (sum(i, j, mid, down[k]) >= k) down[k]--;
for (int k = 0; k <= K; k++)
ans += (up[k] - up[k + 1]) * (down[K - k + 1] - down[K - k]);
}
}
}
}
char str[3055];
int main() {
n = read();
m = read();
K = read();
for (int i = (1); i <= (n); i++) {
scanf("%s", str + 1);
for (int j = (1); j <= (m); j++)
s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + str[j] - '0';
}
work(0, n, 0, m, 0);
wrn(ans);
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
The only difference between easy and hard versions is constraints.
Nauuo is a girl who loves random picture websites.
One day she made a random picture website by herself which includes n pictures.
When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal probability. The i-th picture has a non-negative weight w_i, and the probability of the i-th picture being displayed is \frac{w_i}{β_{j=1}^nw_j}. That is to say, the probability of a picture to be displayed is proportional to its weight.
However, Nauuo discovered that some pictures she does not like were displayed too often.
To solve this problem, she came up with a great idea: when she saw a picture she likes, she would add 1 to its weight; otherwise, she would subtract 1 from its weight.
Nauuo will visit the website m times. She wants to know the expected weight of each picture after all the m visits modulo 998244353. Can you help her?
The expected weight of the i-th picture can be denoted by \frac {q_i} {p_i} where \gcd(p_i,q_i)=1, you need to print an integer r_i satisfying 0β€ r_i<998244353 and r_iβ
p_iβ‘ q_i\pmod{998244353}. It can be proved that such r_i exists and is unique.
Input
The first line contains two integers n and m (1β€ nβ€ 50, 1β€ mβ€ 50) β the number of pictures and the number of visits to the website.
The second line contains n integers a_1,a_2,β¦,a_n (a_i is either 0 or 1) β if a_i=0 , Nauuo does not like the i-th picture; otherwise Nauuo likes the i-th picture. It is guaranteed that there is at least one picture which Nauuo likes.
The third line contains n integers w_1,w_2,β¦,w_n (1β€ w_iβ€50) β the initial weights of the pictures.
Output
The output contains n integers r_1,r_2,β¦,r_n β the expected weights modulo 998244353.
Examples
Input
2 1
0 1
2 1
Output
332748119
332748119
Input
1 2
1
1
Output
3
Input
3 3
0 1 1
4 3 5
Output
160955686
185138929
974061117
Note
In the first example, if the only visit shows the first picture with a probability of \frac 2 3, the final weights are (1,1); if the only visit shows the second picture with a probability of \frac1 3, the final weights are (2,2).
So, both expected weights are \frac2 3β
1+\frac 1 3β
2=\frac4 3 .
Because 332748119β
3β‘ 4\pmod{998244353}, you need to print 332748119 instead of \frac4 3 or 1.3333333333.
In the second example, there is only one picture which Nauuo likes, so every time Nauuo visits the website, w_1 will be increased by 1.
So, the expected weight is 1+2=3.
Nauuo is very naughty so she didn't give you any hint of the third example.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long int;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using vint = vector<int>;
constexpr int MOD = 998244353LL;
ll ppow(ll a, ll b) {
ll ans = 1;
while (b) {
if (b & 1) {
ans = (ans * a) % MOD;
}
b /= 2;
a = (a * a) % MOD;
}
return ans;
}
vector<ll> mods;
ll modinv(ll k) { return mods[k]; }
class solver {
private:
int n, m;
vector<int> likes;
vector<int> weights;
ll all_sum;
ll all_likes;
ll all_unlikes;
vector<vector<vector<ll>>> cc[2][2];
ll dp(int like, int likes_delta, int unlikes_delta, int cur, int ost) {
if (likes_delta > 50 || unlikes_delta > 50 || cur > 100) {
return 0;
}
if (ost == 0) {
return cur;
}
ll &ans = cc[ost % 2][like][likes_delta][unlikes_delta][cur];
if (ans != -1) {
return ans;
}
ans = 0;
ll all_count = all_sum + likes_delta - unlikes_delta;
if (all_count < 0) {
return 0;
}
ll choose_cur_ver = cur;
ll unlike_count = all_unlikes - unlikes_delta - (like == 0 ? cur : 0);
ans += dp(like, likes_delta, unlikes_delta + 1, cur, ost - 1) *
((unlike_count * modinv(all_count)) % MOD);
ll like_count = all_likes + likes_delta - (like == 1 ? cur : 0);
ans += dp(like, likes_delta + 1, unlikes_delta, cur, ost - 1) *
((like_count * modinv(all_count)) % MOD);
if (like) {
ans += dp(like, likes_delta + 1, unlikes_delta, cur + 1, ost - 1) *
((cur * modinv(all_count)) % MOD);
} else if (!like && cur > 0) {
ans += dp(like, likes_delta, unlikes_delta + 1, cur - 1, ost - 1) *
((cur * modinv(all_count)) % MOD);
}
ans %= MOD;
return ans;
}
public:
void solve(int n) {
this->n = n;
cin >> m;
likes.resize(n);
weights.resize(n);
for (auto &it : likes) {
cin >> it;
}
for (auto &it : weights) {
cin >> it;
}
all_sum = 0;
all_likes = 0;
all_unlikes = 0;
for (int i = 0; i < n; i++) {
all_sum += weights[i];
if (likes[i]) {
all_likes += weights[i];
} else {
all_unlikes += weights[i];
}
}
for (int a = 0; a < 2; a++) {
for (int b = 0; b < 2; b++) {
cc[a][b].resize(51);
for (int z = 0; z < 51; z++) {
cc[a][b][z].resize(51);
for (int s = 0; s < 51; s++) {
cc[a][b][z][s].resize(101, -1);
}
}
}
}
for (int ost = 0; ost < m; ost++) {
for (int b = 0; b < 2; b++) {
for (int z = 0; z < 51; z++) {
for (int s = 0; s < 51; s++) {
fill(cc[ost % 2][b][z][s].begin(), cc[ost % 2][b][z][s].end(), -1);
}
}
}
for (int b = 0; b < 2; b++) {
for (int ld = 0; ld <= 50; ld++) {
for (int ud = 0; ud <= 50; ud++) {
for (int cur = 0; cur <= 100; cur++) {
dp(b, ld, ud, cur, ost);
}
}
}
}
}
for (int i = 0; i < n; i++) {
for (int b = 0; b < 2; b++) {
for (int z = 0; z < 51; z++) {
for (int s = 0; s < 51; s++) {
fill(cc[m % 2][b][z][s].begin(), cc[m % 2][b][z][s].end(), -1);
}
}
}
cout << dp(likes[i], 0, 0, weights[i], m) << endl;
}
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
mods.resize(300000);
for (int i = 0; i < mods.size(); i++) {
mods[i] = ppow(i, MOD - 2);
}
int n;
while (cin >> n) {
solver s;
s.solve(n);
}
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
We have three boxes A, B, and C, each of which contains an integer.
Currently, the boxes A, B, and C contain the integers X, Y, and Z, respectively.
We will now do the operations below in order. Find the content of each box afterward.
* Swap the contents of the boxes A and B
* Swap the contents of the boxes A and C
Constraints
* 1 \leq X,Y,Z \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y Z
Output
Print the integers contained in the boxes A, B, and C, in this order, with space in between.
Examples
Input
1 2 3
Output
3 1 2
Input
100 100 100
Output
100 100 100
Input
41 59 31
Output
31 41 59
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(void){
int x,y,z; cin>>x>>y>>z;
printf("%d %d %d",z,x,y);
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l β€ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
Input
The first line of input contains two integers n and k (1 β€ n β€ 100, 1 β€ k β€ 109). The next line contains n integers p1, p2, ..., pn β the given permutation. All pi are different and in range from 1 to n.
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem G1 (3 points), the constraints 1 β€ n β€ 6, 1 β€ k β€ 4 will hold.
* In subproblem G2 (5 points), the constraints 1 β€ n β€ 30, 1 β€ k β€ 200 will hold.
* In subproblem G3 (16 points), the constraints 1 β€ n β€ 100, 1 β€ k β€ 109 will hold.
Output
Output the answer with absolute or relative error no more than 1e - 9.
Examples
Input
3 1
1 2 3
Output
0.833333333333333
Input
3 4
1 3 2
Output
1.458333333333334
Note
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <class T>
inline void smn(T &a, const T &b) {
if (b < a) a = b;
}
template <class T>
inline void smx(T &a, const T &b) {
if (b > a) a = b;
}
const double eps = 1e-8;
const int MN = 100 + 100;
int n, k;
double dp[MN][MN][MN];
bool mark[MN][MN][MN];
double all;
int perm[MN];
int fix(int now, int s, int e) {
if (e < now || s > now) return now;
return (e - (now - s));
}
double fnd(int s, int e, int t) {
if (t == 0) return (s > e) ? 1 : 0;
if (mark[s][e][t]) return dp[s][e][t];
mark[s][e][t] = 1;
double &res = dp[s][e][t];
res = 0;
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++) {
res += 1 / all * fnd(fix(s, i, j), fix(e, i, j), t - 1);
}
return res;
}
int main() {
ios_base::sync_with_stdio(false);
cin >> n >> k;
all = n * (n + 1) / 2;
for (int i = 0; i < n; i++) cin >> perm[i];
double res = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (perm[i] < perm[j])
res += fnd(i, j, k);
else
res += (1 - fnd(i, j, k));
cout << fixed << setprecision(11) << res << '\n';
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Innovation technologies are on a victorious march around the planet. They integrate into all spheres of human activity!
A restaurant called "Dijkstra's Place" has started thinking about optimizing the booking system.
There are n booking requests received by now. Each request is characterized by two numbers: ci and pi β the size of the group of visitors who will come via this request and the total sum of money they will spend in the restaurant, correspondingly.
We know that for each request, all ci people want to sit at the same table and are going to spend the whole evening in the restaurant, from the opening moment at 18:00 to the closing moment.
Unfortunately, there only are k tables in the restaurant. For each table, we know ri β the maximum number of people who can sit at it. A table can have only people from the same group sitting at it. If you cannot find a large enough table for the whole group, then all visitors leave and naturally, pay nothing.
Your task is: given the tables and the requests, decide which requests to accept and which requests to decline so that the money paid by the happy and full visitors was maximum.
Input
The first line of the input contains integer n (1 β€ n β€ 1000) β the number of requests from visitors. Then n lines follow. Each line contains two integers: ci, pi (1 β€ ci, pi β€ 1000) β the size of the group of visitors who will come by the i-th request and the total sum of money they will pay when they visit the restaurant, correspondingly.
The next line contains integer k (1 β€ k β€ 1000) β the number of tables in the restaurant. The last line contains k space-separated integers: r1, r2, ..., rk (1 β€ ri β€ 1000) β the maximum number of people that can sit at each table.
Output
In the first line print two integers: m, s β the number of accepted requests and the total money you get from these requests, correspondingly.
Then print m lines β each line must contain two space-separated integers: the number of the accepted request and the number of the table to seat people who come via this request. The requests and the tables are consecutively numbered starting from 1 in the order in which they are given in the input.
If there are multiple optimal answers, print any of them.
Examples
Input
3
10 50
2 100
5 30
3
4 6 9
Output
2 130
2 1
3 2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
inline void INP() {}
bool check(string &s) {
int i = 0, j = s.length() - 1;
while (i <= j) {
if (s[i] != s[j]) return false;
i++;
j--;
}
return true;
}
int binary(vector<pair<int, int>> &tables, int num) {
int i = 0, j = tables.size() - 1;
int ans = tables.size();
while (i <= j) {
int mid = (i + j) / 2;
int value = tables[mid].first;
if (value < num) {
i = mid + 1;
} else {
ans = mid;
j = mid - 1;
}
}
return ans;
}
void solve() {
int n;
cin >> n;
vector<pair<int, pair<int, int>>> v;
for (int i = 0; i < (n); ++i) {
int c, p;
cin >> c >> p;
v.push_back(make_pair(p, make_pair(c, i)));
}
sort(v.begin(), v.end(), greater<pair<int, pair<int, int>>>());
int k;
cin >> k;
vector<pair<int, int>> tables(k);
for (int i = 0; i < (k); ++i) {
int a;
cin >> a;
tables[i] = make_pair(a, (int)i);
}
sort(tables.begin(), tables.end());
int index[k];
for (int i = 0; i < (k); ++i) index[i] = -1;
for (int i = 0; i < (v.size()); ++i) {
int idx = v[i].second.second;
int size = v[i].second.first;
int pos = binary(tables, size);
if (pos != tables.size()) {
if (index[tables[pos].second] == -1) {
index[tables[pos].second] = i;
} else {
while (pos < tables.size() && index[tables[pos].second] != -1) {
pos++;
}
if (pos != tables.size()) {
if (index[tables[pos].second] == -1) {
index[tables[pos].second] = i;
}
}
}
}
}
int count = 0;
int money = 0;
for (int i = 0; i < (k); ++i) {
if (index[i] != -1) {
count++;
money += v[index[i]].first;
}
}
cout << count << " ";
cout << money << '\n';
for (int i = 0; i < (k); ++i) {
if (index[i] != -1) {
cout << v[index[i]].second.second + 1 << " ";
cout << i + 1 << '\n';
}
}
}
int main() {
int t = 1;
while (t--) {
solve();
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Little Petya likes to play very much. And most of all he likes to play the following game:
He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math, so he asks for your help.
The sequence a is called non-decreasing if a1 β€ a2 β€ ... β€ aN holds, where N is the length of the sequence.
Input
The first line of the input contains single integer N (1 β€ N β€ 5000) β the length of the initial sequence. The following N lines contain one integer each β elements of the sequence. These numbers do not exceed 109 by absolute value.
Output
Output one integer β minimum number of steps required to achieve the goal.
Examples
Input
5
3 2 -1 2 11
Output
4
Input
5
2 1 1 1 1
Output
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct IO {
char buf[(1 << 20)], *p1, *p2;
char pbuf[(1 << 20)], *pp;
IO() : p1(buf), p2(buf), pp(pbuf) {}
inline char gc() {
return getchar();
if (p1 == p2) p2 = (p1 = buf) + fread(buf, 1, (1 << 20), stdin);
return p1 == p2 ? ' ' : *p1++;
}
inline bool blank(char ch) {
return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t';
}
template <class T>
inline void read(T &x) {
register double tmp = 1;
register bool sign = 0;
x = 0;
register char ch = gc();
for (; !(ch >= '0' && ch <= '9'); ch = gc())
if (ch == '-') sign = 1;
for (; (ch >= '0' && ch <= '9'); ch = gc()) x = x * 10 + (ch - '0');
if (ch == '.')
for (ch = gc(); (ch >= '0' && ch <= '9'); ch = gc())
tmp /= 10.0, x += tmp * (ch - '0');
if (sign) x = -x;
}
inline void read(char *s) {
register char ch = gc();
for (; blank(ch); ch = gc())
;
for (; !blank(ch); ch = gc()) *s++ = ch;
*s = 0;
}
inline void read(char &c) {
for (c = gc(); blank(c); c = gc())
;
}
template <class t>
inline void write(t x) {
if (x < 0)
putchar('-'), write(-x);
else {
if (x > 9) write(x / 10);
putchar('0' + x % 10);
}
}
} io;
const long long mod = 1e9 + 7;
const long long mo = 998244353;
const long long N = 5005;
long long n, m, a[N], b[N], f[2][N], g[2][N], ans;
signed main() {
io.read(n);
for (long long i = (1); i <= (n); i++) io.read(b[i]), a[i] = b[i];
sort(b + 1, b + n + 1);
for (long long i = (1); i <= (n); i++) f[0][i] = 0, g[0][i] = 0;
for (long long i = (1); i <= (n); i++) {
memset(f[i & 1], 88, sizeof(f[i & 1]));
memset(g[i & 1], 88, sizeof(g[i & 1]));
for (long long j = (1); j <= (n); j++)
f[i & 1][j] = min(f[i & 1][j], g[(i - 1) & 1][j] + abs(a[i] - b[j]));
for (long long j = (1); j <= (n); j++)
g[i & 1][j] = min(g[i & 1][j - 1], f[i & 1][j]);
}
ans = 1e14;
for (long long i = (1); i <= (n); i++) ans = min(ans, f[n & 1][i]);
printf("%lld\n", ans);
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Polycarp wants to cook a soup. To do it, he needs to buy exactly n liters of water.
There are only two types of water bottles in the nearby shop β 1-liter bottles and 2-liter bottles. There are infinitely many bottles of these two types in the shop.
The bottle of the first type costs a burles and the bottle of the second type costs b burles correspondingly.
Polycarp wants to spend as few money as possible. Your task is to find the minimum amount of money (in burles) Polycarp needs to buy exactly n liters of water in the nearby shop if the bottle of the first type costs a burles and the bottle of the second type costs b burles.
You also have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 500) β the number of queries.
The next q lines contain queries. The i-th query is given as three space-separated integers n_i, a_i and b_i (1 β€ n_i β€ 10^{12}, 1 β€ a_i, b_i β€ 1000) β how many liters Polycarp needs in the i-th query, the cost (in burles) of the bottle of the first type in the i-th query and the cost (in burles) of the bottle of the second type in the i-th query, respectively.
Output
Print q integers. The i-th integer should be equal to the minimum amount of money (in burles) Polycarp needs to buy exactly n_i liters of water in the nearby shop if the bottle of the first type costs a_i burles and the bottle of the second type costs b_i burles.
Example
Input
4
10 1 3
7 3 2
1 1000 1
1000000000000 42 88
Output
10
9
1000
42000000000000
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long int t, n, a, b;
cin >> t;
for (int i = 0; i < t; i++) {
cin >> n >> a >> b;
if ((double)(a) < (double)(b / 2.0)) {
cout << n * a << endl;
} else {
if (n % 2 == 0) {
cout << n / 2 * b << endl;
} else {
cout << ((n - 1) / 2 * b) + a << endl;
}
}
}
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Extended Euclid Algorithm
Given positive integers a and b, find the integer solution (x, y) to ax + by = gcd(a, b), where gcd(a, b) is the greatest common divisor of a and b.
Constraints
* 1 β€ a, b β€ 109
Input
a b
Two positive integers a and b are given separated by a space in a line.
Output
Print two integers x and y separated by a space. If there are several pairs of such x and y, print that pair for which |x| + |y| is the minimal (primarily) and x β€ y (secondarily).
Examples
Input
4 12
Output
1 0
Input
3 8
Output
3 -1
### Response
```cpp
#include <iostream>
using namespace std;
template<typename T>
T extgcd(T a, T b, T& x, T& y){
T g = a; x = 1; y = 0;
if(b){
g = extgcd(b, a % b, y, x);
y -= (a / b) * x;
}
return g;
}
int main(){
int a, b, x, y;
cin >> a >> b;
extgcd(a, b, x, y);
cout << x << ' ' << y << '\n';
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
We have a grid with H rows and W columns of squares. Snuke is painting these squares in colors 1, 2, ..., N. Here, the following conditions should be satisfied:
* For each i (1 β€ i β€ N), there are exactly a_i squares painted in Color i. Here, a_1 + a_2 + ... + a_N = H W.
* For each i (1 β€ i β€ N), the squares painted in Color i are 4-connected. That is, every square painted in Color i can be reached from every square painted in Color i by repeatedly traveling to a horizontally or vertically adjacent square painted in Color i.
Find a way to paint the squares so that the conditions are satisfied. It can be shown that a solution always exists.
Constraints
* 1 β€ H, W β€ 100
* 1 β€ N β€ H W
* a_i β₯ 1
* a_1 + a_2 + ... + a_N = H W
Input
Input is given from Standard Input in the following format:
H W
N
a_1 a_2 ... a_N
Output
Print one way to paint the squares that satisfies the conditions. Output in the following format:
c_{1 1} ... c_{1 W}
:
c_{H 1} ... c_{H W}
Here, c_{i j} is the color of the square at the i-th row from the top and j-th column from the left.
Examples
Input
2 2
3
2 1 1
Output
1 1
2 3
Input
3 5
5
1 2 3 4 5
Output
1 4 4 4 3
2 5 4 5 3
2 5 5 5 3
Input
1 1
1
1
Output
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int H, W;
cin >>H >>W;
int N;
cin >>N;
int a;
vector<int> A(0);
for (int i=0; i<N; i++) {
cin >>a;
for (int j=0; j<a; j++)
A.push_back(i+1);
}
vector<vector<int>> C(H, vector<int>(W, 0));
for (int i=0; i<H*W; i++) {
int h=i/W;
int w=i%W;
if (0!=h%2)
w=W-w-1;
C.at(h).at(w)=A.at(i);
}
for (int i=0; i<H; i++) {
for (int j=0; j<W; j++)
cout <<C.at(i).at(j) <<' ';
cout <<endl;
}
return 0;
};
``` |
Subsets and Splits