text
stringlengths 424
69.5k
|
---|
### Prompt
Please formulate a cpp solution to the following problem:
It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces.
Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question.
Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other.
Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring.
By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure.
Input
The input consists of multiple datasets.
Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30.
There is one line containing only 0 at the end of the input.
Output
Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1.
Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day.
Example
Input
4
1 1
2 2 3
2 1 2
3 3 4 5
0
Output
3
### Response
```cpp
#include <iostream>
#include <cstring>
#include <set>
using namespace std;
bool data[55][31];
int N;
int main() {
while(cin >> N && N) {
memset(data, false, sizeof data);
for(int i=0; i<N; i++) {
int k; cin >> k;
while(k--) {
int h; cin >> h; data[i][h] = true;
}
}
bool flag = false;
set<int> st[51];
for(int i=0; i<N; i++) {
st[i].insert(i);
}
for(int i=1; i<31; i++) {
for(int j=0; j<N; j++) {
if(!data[j][i]) continue;
for(int k=j+1; k<N; k++) {
if(!data[k][i]) continue;
set<int>::iterator it = st[k].begin();
for(; it!=st[k].end(); it++) {
st[j].insert(*it);
}
st[k] = st[j];
}
if(st[j].size() == N) {
cout << i << endl;
flag = true;
goto EXIT;
}
}
}
EXIT:;
if(!flag) cout << -1 << endl;
}
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
You are a judge of a programming contest. You are preparing a dataset for a graph problem to seek for the cost of the minimum cost path. You've generated some random cases, but they are not interesting. You want to produce a dataset whose answer is a desired value such as the number representing this year 2010. So you will tweak (which means 'adjust') the cost of the minimum cost path to a given value by changing the costs of some edges. The number of changes should be made as few as possible.
A non-negative integer c and a directed graph G are given. Each edge of G is associated with a cost of a non-negative integer. Given a path from one node of G to another, we can define the cost of the path as the sum of the costs of edges constituting the path. Given a pair of nodes in G, we can associate it with a non-negative cost which is the minimum of the costs of paths connecting them.
Given a graph and a pair of nodes in it, you are asked to adjust the costs of edges so that the minimum cost path from one node to the other will be the given target cost c. You can assume that c is smaller than the cost of the minimum cost path between the given nodes in the original graph.
For example, in Figure G.1, the minimum cost of the path from node 1 to node 3 in the given graph is 6. In order to adjust this minimum cost to 2, we can change the cost of the edge from node 1 to node 3 to 2. This direct edge becomes the minimum cost path after the change.
For another example, in Figure G.2, the minimum cost of the path from node 1 to node 12 in the given graph is 4022. In order to adjust this minimum cost to 2010, we can change the cost of the edge from node 6 to node 12 and one of the six edges in the right half of the graph. There are many possibilities of edge modification, but the minimum number of modified edges is 2.
Input
The input is a sequence of datasets. Each dataset is formatted as follows.
n m c
f1 t1 c1
f2 t2 c2
.
.
.
fm tm cm
<image> | <image>
---|---
Figure G.1: Example 1 of graph
|
Figure G.2: Example 2 of graph
The integers n, m and c are the number of the nodes, the number of the edges, and the target cost, respectively, each separated by a single space, where 2 β€ n β€ 100, 1 β€ m β€ 1000 and 0 β€ c β€ 100000.
Each node in the graph is represented by an integer 1 through n.
The following m lines represent edges: the integers fi, ti and ci (1 β€ i β€ m) are the originating node, the destination node and the associated cost of the i-th edge, each separated by a single space. They satisfy 1 β€ fi, ti β€ n and 0 β€ ci β€ 10000. You can assume that fi β ti and (fi, ti) β (fj, tj) when i β j.
You can assume that, for each dataset, there is at least one path from node 1 to node n, and that the cost of the minimum cost path from node 1 to node n of the given graph is greater than c.
The end of the input is indicated by a line containing three zeros separated by single spaces.
Output
For each dataset, output a line containing the minimum number of edges whose cost(s) should be changed in order to make the cost of the minimum cost path from node 1 to node n equal to the target cost c. Costs of edges cannot be made negative. The output should not contain any other extra characters.
Example
Input
3 3 3
1 2 3
2 3 3
1 3 8
12 12 2010
1 2 0
2 3 3000
3 4 0
4 5 3000
5 6 3000
6 12 2010
2 7 100
7 8 200
8 9 300
9 10 400
10 11 500
11 6 512
10 18 1
1 2 9
1 3 2
1 4 6
2 5 0
2 6 10
2 7 2
3 5 10
3 6 3
3 7 10
4 7 6
5 8 10
6 8 2
6 9 11
7 9 3
8 9 9
8 10 8
9 10 1
8 2 1
0 0 0
Output
1
2
3
### Response
```cpp
#include<iostream>
#include<queue>
#include<cstdio>
using namespace std;
#define f first
#define s second
#define mp make_pair
#define REP(i,n) for(int i=0; i<(int)(n); i++)
int g[100][100];
bool memo[100][1000];
typedef pair<int, pair<int, int> > data;
inline data makedata(int a, int b, int c){ return make_pair(a, make_pair(b, c)); }
inline int elim(data d){ return d.f; }
inline int cost(data d){ return d.s.f; }
inline int pos(data d){ return d.s.s; }
int main(){
int n, m, c;
while(scanf("%d%d%d", &n, &m, &c), n + m + c){
REP(i,n) REP(j,n) g[i][j] = -1;
REP(i,n) REP(j,m) memo[i][j] = false;
REP(i,m){
int a, b, d;
scanf("%d%d%d", &a, &b, &d);
g[a - 1][b - 1] = d;
}
priority_queue<data, vector<data>, greater<data> > pq;
pq.push(makedata(0, 0, 0));
while(pq.size()){
data d = pq.top(); pq.pop();
int ee = elim(d);
int cc = cost(d);
int pp = pos(d);
if(memo[pp][ee]) continue;
memo[pp][ee] = true;
if(pp == n - 1 && cc <= c){
printf("%d\n", ee);
break;
}
REP(i,n) if(g[pp][i] >= 0){
if(!memo[i][ee + 1]) pq.push(makedata(ee + 1, cc, i));
if(!memo[i][ee]) pq.push(makedata(ee, cc + g[pp][i], i));
}
}
}
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Based on some criterion, Snuke divided the integers from 1 through 12 into three groups as shown in the figure below. Given two integers x and y (1 β€ x < y β€ 12), determine whether they belong to the same group.
b4ab979900ed647703389d4349eb84ee.png
Constraints
* x and y are integers.
* 1 β€ x < y β€ 12
Input
Input is given from Standard Input in the following format:
x y
Output
If x and y belong to the same group, print `Yes`; otherwise, print `No`.
Examples
Input
1 3
Output
Yes
Input
2 4
Output
No
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int x, y;
string a = "0131212112121";
cin >> x >> y;
cout << (a[x] == a[y] ? "Yes" : "No") << endl;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way:
* Four sticks represent the animal's legs, these sticks should have the same length.
* Two remaining sticks represent the animal's head and body. The bear's head stick must be shorter than the body stick. The elephant, however, has a long trunk, so his head stick must be as long as the body stick. Note that there are no limits on the relations between the leg sticks and the head and body sticks.
Your task is to find out which animal can be made from the given stick set. The zoo keeper wants the sticks back after the game, so they must never be broken, even bears understand it.
Input
The single line contains six space-separated integers li (1 β€ li β€ 9) β the lengths of the six sticks. It is guaranteed that the input is such that you cannot make both animals from the sticks.
Output
If you can make a bear from the given set, print string "Bear" (without the quotes). If you can make an elephant, print string "Elephant" (wΔ±thout the quotes). If you can make neither a bear nor an elephant, print string "Alien" (without the quotes).
Examples
Input
4 2 5 4 4 4
Output
Bear
Input
4 4 5 4 4 5
Output
Elephant
Input
1 2 3 4 5 6
Output
Alien
Note
If you're out of creative ideas, see instructions below which show how to make a bear and an elephant in the first two samples. The stick of length 2 is in red, the sticks of length 4 are in green, the sticks of length 5 are in blue.
<image>
### Response
```cpp
#include <bits/stdc++.h>
int main() {
int max = 0, min = 7, i, m[10] = {0}, a;
for (i = 0; i < 6; i++) {
scanf("%d", &a);
m[a]++;
}
for (i = 0; i < 10; i++) {
if (m[i] == 0) continue;
if (m[i] > max) max = m[i];
if (m[i] < min) min = m[i];
}
if (max > 3) {
if (max == 6 || min == 2)
printf("Elephant");
else
printf("Bear");
} else
printf("Alien");
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on β you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.
The potato pie is located in the n-th room and Vitaly needs to go there.
Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key.
In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.
Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.
Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.
Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
Input
The first line of the input contains a positive integer n (2 β€ n β€ 105) β the number of rooms in the house.
The second line of the input contains string s of length 2Β·n - 2. Let's number the elements of the string from left to right, starting from one.
The odd positions in the given string s contain lowercase Latin letters β the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter β the type of the key that lies in room number (i + 1) / 2.
The even positions in the given string contain uppercase Latin letters β the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter β the type of the door that leads from room i / 2 to room i / 2 + 1.
Output
Print the only integer β the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.
Examples
Input
3
aAbB
Output
0
Input
4
aBaCaB
Output
3
Input
5
xYyXzZaZ
Output
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
string str;
cin >> n;
cin >> str;
map<char, int> mp;
int ans = 0;
for (int i = 0; i < 2 * n - 1; ++i) {
if (isupper(str[i])) {
char ch = tolower(str[i]);
if (mp[ch] == 0) {
ans += 1;
} else
mp[ch]--;
} else
mp[str[i]]++;
}
cout << ans;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
A game field is a strip of 1 Γ n square cells. In some cells there are Packmen, in some cells β asterisks, other cells are empty.
Packman can move to neighboring cell in 1 time unit. If there is an asterisk in the target cell then Packman eats it. Packman doesn't spend any time to eat an asterisk.
In the initial moment of time all Packmen begin to move. Each Packman can change direction of its move unlimited number of times, but it is not allowed to go beyond the boundaries of the game field. Packmen do not interfere with the movement of other packmen; in one cell there can be any number of packmen moving in any directions.
Your task is to determine minimum possible time after which Packmen can eat all the asterisks.
Input
The first line contains a single integer n (2 β€ n β€ 105) β the length of the game field.
The second line contains the description of the game field consisting of n symbols. If there is symbol '.' in position i β the cell i is empty. If there is symbol '*' in position i β in the cell i contains an asterisk. If there is symbol 'P' in position i β Packman is in the cell i.
It is guaranteed that on the game field there is at least one Packman and at least one asterisk.
Output
Print minimum possible time after which Packmen can eat all asterisks.
Examples
Input
7
*..P*P*
Output
3
Input
10
.**PP.*P.*
Output
2
Note
In the first example Packman in position 4 will move to the left and will eat asterisk in position 1. He will spend 3 time units on it. During the same 3 time units Packman in position 6 will eat both of neighboring with it asterisks. For example, it can move to the left and eat asterisk in position 5 (in 1 time unit) and then move from the position 5 to the right and eat asterisk in the position 7 (in 2 time units). So in 3 time units Packmen will eat all asterisks on the game field.
In the second example Packman in the position 4 will move to the left and after 2 time units will eat asterisks in positions 3 and 2. Packmen in positions 5 and 8 will move to the right and in 2 time units will eat asterisks in positions 7 and 10, respectively. So 2 time units is enough for Packmen to eat all asterisks on the game field.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool qry(vector<int>& a, vector<int>& b, int k) {
int t = 0;
for (int i = 0; i < a.size(); i++) {
if (t == b.size() || b[t] - a[i] > k) continue;
if (a[i] - b[t] > k) return 0;
int j =
(a[i] > b[t] ? max((k - a[i] + b[t]) / 2 + a[i], k - a[i] + 2 * b[t])
: k + a[i]);
t = upper_bound(b.begin(), b.end(), j) - b.begin();
}
return (t == b.size());
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
string s;
cin >> s;
vector<int> a, b;
for (int i = 0; i < n; i++) {
if (s[i] == '*')
b.push_back(i);
else if (s[i] == 'P')
a.push_back(i);
}
int l = 1, r = n + n / 2 + 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (qry(a, b, mid))
r = mid - 1;
else
l = mid + 1;
}
cout << l << endl;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
There are N points on the 2D plane, i-th of which is located on (x_i, y_i). There can be multiple points that share the same coordinate. What is the maximum possible Manhattan distance between two distinct points?
Here, the Manhattan distance between two points (x_i, y_i) and (x_j, y_j) is defined by |x_i-x_j| + |y_i-y_j|.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq x_i,y_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the answer.
Examples
Input
3
1 1
2 4
3 2
Output
4
Input
2
1 1
1 1
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int64_t INF = (1LL << 62);
int main()
{
int64_t N, x, y;
cin >> N;
int64_t mis = INF, mas = -INF, mid = INF, mad = -INF;
for (int i = 0; i < N; i++)
{
cin >> x >> y;
mis = min(mis, x + y);
mas = max(mas, x + y);
mid = min(mid, x - y);
mad = max(mad, x - y);
}
cout << max(mas - mis, mad - mid) << endl;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
There is an airplane which has n rows from front to back. There will be m people boarding this airplane.
This airplane has an entrance at the very front and very back of the plane.
Each person has some assigned seat. It is possible for multiple people to have the same assigned seat. The people will then board the plane one by one starting with person 1. Each person can independently choose either the front entrance or back entrance to enter the plane.
When a person walks into the plane, they walk directly to their assigned seat and will try to sit in it. If it is occupied, they will continue walking in the direction they walked in until they are at empty seat - they will take the earliest empty seat that they can find. If they get to the end of the row without finding a seat, they will be angry.
Find the number of ways to assign tickets to the passengers and board the plane without anyone getting angry. Two ways are different if there exists a passenger who chose a different entrance in both ways, or the assigned seat is different. Print this count modulo 109 + 7.
Input
The first line of input will contain two integers n, m (1 β€ m β€ n β€ 1 000 000), the number of seats, and the number of passengers, respectively.
Output
Print a single number, the number of ways, modulo 109 + 7.
Example
Input
3 3
Output
128
Note
Here, we will denote a passenger by which seat they were assigned, and which side they came from (either "F" or "B" for front or back, respectively).
For example, one valid way is 3B, 3B, 3B (i.e. all passengers were assigned seat 3 and came from the back entrance). Another valid way would be 2F, 1B, 3F.
One invalid way would be 2B, 2B, 2B, since the third passenger would get to the front without finding a seat.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int mod = 1000000007;
long long ksm(long long a, long long b) {
long long x = 1;
while (b != 0) {
if (b & 1) {
x *= a;
x %= mod;
}
a *= a;
a %= mod;
b >>= 1;
}
return x;
}
int n, m;
int main() {
cin >> n >> m;
long long ans = ksm(2 * n + 2, m);
cout << (((ans) * (n + 1 - m) + mod) % mod * ksm(n + 1, mod - 2)) % mod;
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Drazil likes heap very much. So he created a problem with heap:
There is a max heap with a height h implemented on the array. The details of this heap are the following:
This heap contains exactly 2^h - 1 distinct positive non-zero integers. All integers are distinct. These numbers are stored in the array a indexed from 1 to 2^h-1. For any 1 < i < 2^h, a[i] < a[\left β{i/2}\right β].
Now we want to reduce the height of this heap such that the height becomes g with exactly 2^g-1 numbers in heap. To reduce the height, we should perform the following action 2^h-2^g times:
Choose an index i, which contains an element and call the following function f in index i:
<image>
Note that we suppose that if a[i]=0, then index i don't contain an element.
After all operations, the remaining 2^g-1 element must be located in indices from 1 to 2^g-1. Now Drazil wonders what's the minimum possible sum of the remaining 2^g-1 elements. Please find this sum and find a sequence of the function calls to achieve this value.
Input
The first line of the input contains an integer t (1 β€ t β€ 70 000): the number of test cases.
Each test case contain two lines. The first line contains two integers h and g (1 β€ g < h β€ 20). The second line contains n = 2^h-1 distinct positive integers a[1], a[2], β¦, a[n] (1 β€ a[i] < 2^{20}). For all i from 2 to 2^h - 1, a[i] < a[\left β{i/2}\right β].
The total sum of n is less than 2^{20}.
Output
For each test case, print two lines.
The first line should contain one integer denoting the minimum sum after reducing the height of heap to g. The second line should contain 2^h - 2^g integers v_1, v_2, β¦, v_{2^h-2^g}. In i-th operation f(v_i) should be called.
Example
Input
2
3 2
7 6 3 5 4 2 1
3 2
7 6 5 4 3 2 1
Output
10
3 2 3 1
8
2 1 3 1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long arr[20000020];
long long del(long long i, long long k) {
long long val = arr[i];
long long left = 2 * i;
long long right = 2 * i + 1;
if (arr[left] == 0 && arr[right] == 0) {
arr[i] = 0;
if (i < k) {
return val;
} else {
return 0;
}
} else {
if (arr[left] > arr[right]) {
long long l = arr[left];
long long x = del(left, k);
if (x) {
arr[i] = 0;
return val + x;
} else {
arr[i] = l;
return 0;
}
} else {
long long l = arr[right];
long long x = del(right, k);
if (x) {
arr[i] = 0;
return val + x;
} else {
arr[i] = l;
return 0;
}
}
}
}
int main() {
long long T;
scanf("%lld", &T);
;
while (T--) {
long long J, K;
scanf("%lld", &J);
;
scanf("%lld", &K);
;
long long qq = (1 << (J + 1));
long long n = 1 << J;
long long m = 1 << K;
long long dif = n - m;
long long sum = 0;
for (long long i = n; i < qq; i++) {
arr[i] = 0;
}
for (long long i = 1; i <= n - 1; i++) {
long long in;
scanf("%lld", &in);
;
arr[i] = in;
}
vector<long long> ans;
for (long long i = 1; i < m;) {
if (arr[i] == 0) {
i++;
continue;
}
long long x = del(i, m);
if (x) {
sum += x;
i++;
} else {
ans.push_back(i);
}
}
cout << sum << "\n";
for (auto i : ans) {
cout << i << " ";
}
puts("");
}
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
You want to perform the combo on your opponent in one popular fighting game. The combo is the string s consisting of n lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in s. I.e. if s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.
You know that you will spend m wrong tries to perform the combo and during the i-th try you will make a mistake right after p_i-th button (1 β€ p_i < n) (i.e. you will press first p_i buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1-th try you press all buttons right and finally perform the combo.
I.e. if s="abca", m=2 and p = [1, 3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.
Your task is to calculate for each button (letter) the number of times you'll press it.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 10^4) β the number of test cases.
Then t test cases follow.
The first line of each test case contains two integers n and m (2 β€ n β€ 2 β
10^5, 1 β€ m β€ 2 β
10^5) β the length of s and the number of tries correspondingly.
The second line of each test case contains the string s consisting of n lowercase Latin letters.
The third line of each test case contains m integers p_1, p_2, ..., p_m (1 β€ p_i < n) β the number of characters pressed right during the i-th try.
It is guaranteed that the sum of n and the sum of m both does not exceed 2 β
10^5 (β n β€ 2 β
10^5, β m β€ 2 β
10^5).
It is guaranteed that the answer for each letter does not exceed 2 β
10^9.
Output
For each test case, print the answer β 26 integers: the number of times you press the button 'a', the number of times you press the button 'b', ..., the number of times you press the button 'z'.
Example
Input
3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4
Output
4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0
2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2
Note
The first test case is described in the problem statement. Wrong tries are "a", "abc" and the final try is "abca". The number of times you press 'a' is 4, 'b' is 2 and 'c' is 2.
In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 9, 'd' is 4, 'e' is 5, 'f' is 3, 'o' is 9, 'r' is 3 and 's' is 1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n, M;
cin >> n >> M;
vector<char> s(n);
int m = M;
vector<int> p(m), b(n), yes(n, 0), cnt(26, 0);
for (int i = 0; i < n; i++) {
cin >> s[i];
cnt[s[i] - 'a']++;
}
for (int i = 0; i < m; i++) {
cin >> p[i];
p[i]--;
}
sort(p.begin(), p.end());
int top = 0;
for (int i = 0; i < n; i++) {
if (top >= M) break;
if (p[top] != i)
cnt[s[i] - 'a'] += m;
else {
int t = top;
while (top < M - 1 && p[top] == p[top + 1]) top++;
int c = ++top - t;
cnt[s[i] - 'a'] += m;
m -= c;
}
}
for (int i = 0; i < 26; i++) cout << cnt[i] << " ";
cout << endl;
return;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
All our characters have hobbies. The same is true for Fedor. He enjoys shopping in the neighboring supermarket.
The goods in the supermarket have unique integer ids. Also, for every integer there is a product with id equal to this integer. Fedor has n discount coupons, the i-th of them can be used with products with ids ranging from li to ri, inclusive. Today Fedor wants to take exactly k coupons with him.
Fedor wants to choose the k coupons in such a way that the number of such products x that all coupons can be used with this product x is as large as possible (for better understanding, see examples). Fedor wants to save his time as well, so he asks you to choose coupons for him. Help Fedor!
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 3Β·105) β the number of coupons Fedor has, and the number of coupons he wants to choose.
Each of the next n lines contains two integers li and ri ( - 109 β€ li β€ ri β€ 109) β the description of the i-th coupon. The coupons can be equal.
Output
In the first line print single integer β the maximum number of products with which all the chosen coupons can be used. The products with which at least one coupon cannot be used shouldn't be counted.
In the second line print k distinct integers p1, p2, ..., pk (1 β€ pi β€ n) β the ids of the coupons which Fedor should choose.
If there are multiple answers, print any of them.
Examples
Input
4 2
1 100
40 70
120 130
125 180
Output
31
1 2
Input
3 2
1 12
15 20
25 30
Output
0
1 2
Input
5 2
1 10
5 15
14 50
30 70
99 100
Output
21
3 4
Note
In the first example if we take the first two coupons then all the products with ids in range [40, 70] can be bought with both coupons. There are 31 products in total.
In the second example, no product can be bought with two coupons, that is why the answer is 0. Fedor can choose any two coupons in this example.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct range {
int l, r;
public:
range(int a, int b) {
l = a;
r = b;
}
range() {}
};
int main() {
range arr[300300];
int n, a, b, k;
cin >> n >> k;
pair<int, int> toGo[300300];
for (int i = 0; i < n; i++) {
cin >> a >> b;
arr[i] = range(a, b);
toGo[i] = make_pair(a, i);
}
sort(toGo, toGo + n);
multiset<int> ends;
int res = 0;
int sst, send;
for (int i = 0; i < n; i++) {
ends.insert(arr[toGo[i].second].r);
if (ends.size() > k) ends.erase(ends.begin());
if (ends.size() == k) {
int st = toGo[i].first;
if (*ends.begin() - toGo[i].first + 1 > res) {
res = *ends.begin() - toGo[i].first + 1;
sst = toGo[i].first;
send = *ends.begin();
}
}
}
cout << res << endl;
for (int i = 0; i < n; i++)
if ((arr[i].l <= sst && arr[i].r >= send) || res == 0) {
cout << i + 1 << " ";
k--;
if (k == 0) break;
}
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i < j β€ n must also be included in the subsegment.
Gildong wants to make all elements of a equal β he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?
Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 1000).
Each test case contains two lines. The first line of each test case consists of an integer n (2 β€ n β€ 2 β
10^5) β the number of elements of the array a.
The second line of each test case contains n integers. The i-th integer is a_i (-5 β
10^8 β€ a_i β€ 5 β
10^8).
It is guaranteed that the sum of n in all test cases does not exceed 2 β
10^5.
Output
For each test case, print one integer β the minimum number of operations Gildong has to perform in order to make all elements of the array equal.
Example
Input
7
2
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
Output
0
1
3
4
6
5
2847372102
Note
In the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.
In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.
In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94].
* Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96].
In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2].
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-3].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define fast() ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define f(i,s,n) for(i=s;i<n;i++)
#define pb push_back
#define mll map<long long,long long>
#define umll unordered_map<long long,long long>
#define pll pair<long long,long long>
#define vl vector<long long>
#define sl set<long long>
#define fi first
#define se second
#define inf 1e18
ll i,j,k;
void solve();
int main() {
fast();
ll t=1;
cin>>t;
while(t--)
{
solve();
}
return 0;
}
void solve()
{
ll n;
cin>>n;
ll a[n];
f(i,0,n)
cin>>a[i];
ll flag = 0;
f(i,1,n)
{
if(a[i]!=a[i-1])
{
flag = 1;
break;
}
}
if(flag==0)
cout<<0<<endl;
else
{
ll sum = 0;
f(i,0,n)
sum+=a[i];
double avg = (double)sum/(double)n;
ll mm = 0,b=0;
f(i,1,n)
{
mm+=abs(a[i]-a[i-1]);
}
b = mm - abs(a[0]-a[1]);
b = min(b,mm-abs(a[n-1]-a[n-2]));
ll c =0;
f(i,1,n-1)
{
c = mm;
c-= abs(a[i]-a[i-1]);
c-= abs(a[i]-a[i+1]);
c+=abs(a[i-1]-a[i+1]);
b = min(b,c);
}
cout<<b<<endl;
/*ll x = a[0],maxi=0,mini=INT_MAX,count = 0,dp[n]={0};
for(i=0;i<n;i++)
{
ll u = abs(x-a[i]);
dp[i] = u;
maxi = max(maxi,u);
mini = min(mini,u);
}
f(i,0,n)
cout<<dp[i]<<" ";
cout<<endl;
f(i,1,n)
{
dp[i] -= dp[i-1];
}
f(i,0,n)
cout<<dp[i]<<" ";
cout<<endl;
cout<<count<<endl;*/
}
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
The Little Elephant loves playing with arrays. He has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai.
Additionally the Little Elephant has m queries to the array, each query is characterised by a pair of integers lj and rj (1 β€ lj β€ rj β€ n). For each query lj, rj the Little Elephant has to count, how many numbers x exist, such that number x occurs exactly x times among numbers alj, alj + 1, ..., arj.
Help the Little Elephant to count the answers to all queries.
Input
The first line contains two space-separated integers n and m (1 β€ n, m β€ 105) β the size of array a and the number of queries to it. The next line contains n space-separated positive integers a1, a2, ..., an (1 β€ ai β€ 109). Next m lines contain descriptions of queries, one per line. The j-th of these lines contains the description of the j-th query as two space-separated integers lj and rj (1 β€ lj β€ rj β€ n).
Output
In m lines print m integers β the answers to the queries. The j-th line should contain the answer to the j-th query.
Examples
Input
7 2
3 1 2 2 3 3 7
1 7
3 4
Output
3
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
map<int, int> match;
int tree[100010], n, m, num, ans[100010], val[100010], f[100010], p[100010];
vector<int> vc[100010];
struct node {
int l, r, pos;
} op[100010];
bool cmp(node a, node b) { return a.r < b.r; }
int lowbit(int x) { return x & (-x); }
void update(int x, int val) {
for (; x <= n; x += lowbit(x)) tree[x] += val;
}
int query(int x) {
int ret = 0;
for (; x > 0; x -= lowbit(x)) ret += tree[x];
return ret;
}
int main() {
int i, j, k, pos;
scanf("%d%d", &n, &m);
for (i = 1; i <= n; i++) {
scanf("%d", &val[i]);
f[i] = val[i];
}
sort(f + 1, f + 1 + n);
for (i = 1; i <= n; i++)
if (f[i] != f[i - 1]) {
num++;
match[f[i]] = num;
}
for (i = 1; i <= m; i++) {
scanf("%d%d", &op[i].l, &op[i].r);
op[i].pos = i;
}
for (i = 1; i <= num; i++) vc[i].push_back(0);
sort(op + 1, op + 1 + m, cmp);
op[m + 1].r = 0;
pos = 1;
for (i = 1; i <= n; i++) {
k = match[val[i]];
p[k]++;
vc[k].push_back(i);
if (p[k] >= val[i]) {
update(vc[k][p[k] - val[i]] + 1, 1);
update(vc[k][p[k] - val[i] + 1] + 1, -1);
if (p[k] > val[i]) {
update(vc[k][p[k] - val[i] - 1] + 1, -1);
update(vc[k][p[k] - val[i]] + 1, 1);
}
}
while (op[pos].r == i) {
ans[op[pos].pos] = query(op[pos].l);
pos++;
}
}
for (i = 1; i <= m; i++) printf("%d\n", ans[i]);
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
For a non-negative integer K, we define a fractal of level K as follows:
* A fractal of level 0 is a grid with just one white square.
* When K > 0, a fractal of level K is a 3^K \times 3^K grid. If we divide this grid into nine 3^{K-1} \times 3^{K-1} subgrids:
* The central subgrid consists of only black squares.
* Each of the other eight subgrids is a fractal of level K-1.
For example, a fractal of level 2 is as follows:
A fractal of level 2
In a fractal of level 30, let (r, c) denote the square at the r-th row from the top and the c-th column from the left.
You are given Q quadruples of integers (a_i, b_i, c_i, d_i). For each quadruple, find the distance from (a_i, b_i) to (c_i, d_i).
Here the distance from (a, b) to (c, d) is the minimum integer n that satisfies the following condition:
* There exists a sequence of white squares (x_0, y_0), \ldots, (x_n, y_n) satisfying the following conditions:
* (x_0, y_0) = (a, b)
* (x_n, y_n) = (c, d)
* For every i (0 \leq i \leq n-1), (x_i, y_i) and (x_{i+1}, y_{i+1}) share a side.
Constraints
* 1 \leq Q \leq 10000
* 1 \leq a_i, b_i, c_i, d_i \leq 3^{30}
* (a_i, b_i) \neq (c_i, d_i)
* (a_i, b_i) and (c_i, d_i) are white squares.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
Q
a_1 \ b_1 \ c_1 \ d_1
:
a_Q \ b_Q \ c_Q \ d_Q
Output
Print Q lines. The i-th line should contain the distance from (a_i, b_i) to (c_i, d_i).
Example
Input
2
4 2 7 4
9 9 1 9
Output
5
8
### Response
```cpp
#include<iostream>
#include<string>
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<queue>
#include<ciso646>
#include<random>
#include<map>
#include<set>
#include<bitset>
#include<stack>
#include<unordered_map>
#include<utility>
#include<cassert>
#include<complex>
#include<numeric>
using namespace std;
//#define int long long
typedef long long ll;
typedef unsigned long long ul;
typedef unsigned int ui;
const ll mod = 1000000007;
const ll INF = mod * mod;
typedef pair<int, int>P;
#define stop char nyaa;cin>>nyaa;
#define rep(i,n) for(int i=0;i<n;i++)
#define per(i,n) for(int i=n-1;i>=0;i--)
#define Rep(i,sta,n) for(int i=sta;i<n;i++)
#define rep1(i,n) for(int i=1;i<=n;i++)
#define per1(i,n) for(int i=n;i>=1;i--)
#define Rep1(i,sta,n) for(int i=sta;i<=n;i++)
#define all(v) (v).begin(),(v).end()
typedef pair<ll, ll> LP;
typedef long double ld;
typedef pair<ld, ld> LDP;
const ld eps = 1e-12;
const ld pi = acos(-1.0);
//typedef vector<vector<ll>> mat;
typedef vector<int> vec;
ll mod_pow(ll a, ll n, ll m) {
ll res = 1;
while (n) {
if (n & 1)res = res * a%m;
a = a * a%m; n >>= 1;
}
return res;
}
struct modint {
ll n;
modint() :n(0) { ; }
modint(ll m) :n(m) {
if (n >= mod)n %= mod;
else if (n < 0)n = (n%mod + mod) % mod;
}
operator int() { return n; }
};
bool operator==(modint a, modint b) { return a.n == b.n; }
modint operator+=(modint &a, modint b) { a.n += b.n; if (a.n >= mod)a.n -= mod; return a; }
modint operator-=(modint &a, modint b) { a.n -= b.n; if (a.n < 0)a.n += mod; return a; }
modint operator*=(modint &a, modint b) { a.n = ((ll)a.n*b.n) % mod; return a; }
modint operator+(modint a, modint b) { return a += b; }
modint operator-(modint a, modint b) { return a -= b; }
modint operator*(modint a, modint b) { return a *= b; }
modint operator^(modint a, int n) {
if (n == 0)return modint(1);
modint res = (a*a) ^ (n / 2);
if (n % 2)res = res * a;
return res;
}
ll inv(ll a, ll p) {
return (a == 1 ? 1 : (1 - p * inv(p%a, a)) / a + p);
}
modint operator/(modint a, modint b) { return a * modint(inv(b, mod)); }
const int max_n = 1 << 18;
modint fact[max_n], factinv[max_n];
void init_f() {
fact[0] = modint(1);
for (int i = 0; i < max_n - 1; i++) {
fact[i + 1] = fact[i] * modint(i + 1);
}
factinv[max_n - 1] = modint(1) / fact[max_n - 1];
for (int i = max_n - 2; i >= 0; i--) {
factinv[i] = factinv[i + 1] * modint(i + 1);
}
}
modint comb(int a, int b) {
if (a < 0 || b < 0 || a < b)return 0;
return fact[a] * factinv[b] * factinv[a - b];
}
using mP = pair<modint, modint>;
ll t3[31];
void solve() {
t3[0] = 1;
rep(i, 30) {
t3[i + 1] = t3[i] * 3;
}
ll x[2], y[2];
cin >> x[0] >> y[0] >> x[1] >> y[1];
rep(i, 2) {
x[i]--; y[i]--;
}
if (x[0] > x[1]) {
swap(x[0], x[1]);
swap(y[0], y[1]);
}
ll ans = abs(x[1] - x[0]) + abs(y[1] - y[0]);
for (int t = 29; t >= 0; t--) {
ll dx = x[0] / t3[t+1];
ll gdx = x[1] / t3[t + 1];
ll dy = y[0] / t3[t + 1];
ll gdy = y[1] / t3[t + 1];
if (dx == gdx) {
ll rx = x[0] % t3[t + 1];
ll grx = x[1] % t3[t + 1];
if (t3[t] <= rx && rx < 2 * t3[t] && t3[t] <= grx && grx < 2 * t3[t]) {
bool prob = true;
if (dy == gdy) {
ll ry = y[0] % t3[t + 1];
ll gry = y[1] % t3[t + 1];
prob = false;
if (ry < t3[t] && gry >= 2 * t3[t])prob = true;
if (gry < t3[t] && ry >= 2 * t3[t])prob = true;
}
else {
ll yy = abs(y[1] - y[0]);
if (yy < 2 * t3[t])prob = false;
}
if (prob) {
ll ori = abs(x[1] - x[0]);
ll nexu = rx - t3[t] + 1 + grx - t3[t] + 1;
ll nexd = 2 * t3[t] - rx + 2 * t3[t] - grx;
ll ad = min(nexu, nexd) - ori;
//cout << "izyou x " << t << endl;
cout << ans + ad << endl; return;
}
}
}
if (dy == gdy) {
ll ry = y[0] % t3[t + 1];
ll gry = y[1] % t3[t + 1];
if (t3[t] <= ry && ry < 2 * t3[t] && t3[t] <= gry && gry < 2 * t3[t]) {
bool prob = true;
if (dx == gdx) {
ll rx = x[0] % t3[t + 1];
ll grx = x[1] % t3[t + 1];
prob = false;
if (rx < t3[t] && grx >= 2 * t3[t])prob = true;
if (grx < t3[t] && rx >= 2 * t3[t])prob = true;
}
else {
ll xx = abs(x[1] - x[0]);
if (xx < 2 * t3[t])prob = false;
}
if (prob) {
ll ori = abs(y[1] - y[0]);
ll nexu = ry - t3[t] + 1 + gry - t3[t] + 1;
ll nexd = 2 * t3[t] - ry + 2 * t3[t] - gry;
ll ad = min(nexu, nexd) - ori;
//cout << "izyou y " << t << endl;
cout << ans + ad << endl; return;
}
}
}
}
//cout << "hutuu" << endl;
cout << ans << endl;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
//cout << fixed << setprecision(7);
//init_f();
//init();
int t; cin >> t; rep(i, t)solve();
//solve();
stop
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
You are given the array a consisting of n elements and the integer k β€ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of a is mn then you choose such index i that a_i = mn and set a_i := a_i + 1);
* take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of a is mx then you choose such index i that a_i = mx and set a_i := a_i - 1).
Your task is to calculate the minimum number of moves required to obtain at least k equal elements in the array.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in a and the required number of equal elements.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Print one integer β the minimum number of moves required to obtain at least k equal elements in the array.
Examples
Input
6 5
1 2 2 4 2 3
Output
3
Input
7 5
3 3 2 1 1 1 3
Output
4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[]) {
vector<vector<int> > DATA(2123456);
int n, k;
cin >> n >> k;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
int cnt = 0;
while (x > 0) {
DATA[x].push_back(cnt);
cnt++;
x /= 2;
}
DATA[0].push_back(cnt);
}
int answer = 987654321;
for (int i = 0; i <= 2123456; i++) {
if (DATA[i].size() < k) {
continue;
}
sort(DATA[i].begin(), DATA[i].end());
int answer1 = 0;
for (int j = 0; j < k; j++) {
answer1 += DATA[i][j];
}
answer = min(answer, answer1);
}
cout << answer;
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
This problem only differs from the next problem in constraints.
This is an interactive problem.
Alice and Bob are playing a game on the chessboard of size n Γ m where n and m are even. The rows are numbered from 1 to n and the columns are numbered from 1 to m. There are two knights on the chessboard. A white one initially is on the position (x_1, y_1), while the black one is on the position (x_2, y_2). Alice will choose one of the knights to play with, and Bob will use the other one.
The Alice and Bob will play in turns and whoever controls the white knight starts the game. During a turn, the player must move their knight adhering the chess rules. That is, if the knight is currently on the position (x, y), it can be moved to any of those positions (as long as they are inside the chessboard):
(x+1, y+2), (x+1, y-2), (x-1, y+2), (x-1, y-2),
(x+2, y+1), (x+2, y-1), (x-2, y+1), (x-2, y-1).
We all know that knights are strongest in the middle of the board. Both knight have a single position they want to reach:
* the owner of the white knight wins if it captures the black knight or if the white knight is at (n/2, m/2) and this position is not under attack of the black knight at this moment;
* The owner of the black knight wins if it captures the white knight or if the black knight is at (n/2+1, m/2) and this position is not under attack of the white knight at this moment.
Formally, the player who captures the other knight wins. The player who is at its target square ((n/2, m/2) for white, (n/2+1, m/2) for black) and this position is not under opponent's attack, also wins.
A position is under attack of a knight if it can move into this position. Capturing a knight means that a player moves their knight to the cell where the opponent's knight is.
If Alice made 350 moves and nobody won, the game is a draw.
Alice is unsure in her chess skills, so she asks you for a help. Choose a knight and win the game for her. It can be shown, that Alice always has a winning strategy.
Interaction
The interaction starts with two integers n and m (6 β€ n,m β€ 40, n and m are even) β the dimensions of the chessboard.
The second line contains four integers x_1, y_1, x_2, y_2 (1 β€ x_1, x_2 β€ n, 1 β€ y_1, y_2 β€ m) β the positions of the white and the black knight. It is guaranteed that the two knights have different starting positions. It is also guaranteed that none of the knights are in their own target square in the beginning of the game (however, they can be on the opponent's target position).
Your program should reply with either "WHITE" or "BLACK", depending on the knight you want to play with. In case you select the white knight, you start the game.
During every your turn, you need to print two integers: x and y, the position to move the knight. If you won the game by this turn, you must terminate your program immediately.
After every turn of the opponent, you will receive two integers: x and y, the position where Bob moved his knight.
If your last move was illegal or you lost the game after jury's turn, or you made 350 moves, and haven't won, you will receive "-1 -1". In such cases, you should terminate your program and then you will get a Wrong Answer verdict.
After printing anything, do not forget to output the end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Hacks are disabled for this problem.
Jury's program is adaptive: the moves of jury may depend on the moves made by your program.
Examples
Input
8 8
2 3 1 8
Output
WHITE
4 4
Input
6 6
4 4 2 2
6 3
Output
BLACK
4 3
Note
In the first example, the white knight can reach it's target square in one move.
In the second example black knight wins, no matter what white knight moves.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int INFi = 2e9 + 5;
const int maxN = 40;
const int md = 239;
const long long INF = 2e18;
int win[maxN][maxN][maxN][maxN];
int tox[maxN][maxN][maxN][maxN];
int toy[maxN][maxN][maxN][maxN];
int deg[maxN][maxN][maxN][maxN];
bool ended[maxN][maxN][maxN][maxN];
void solve() {
int n, m;
cin >> n >> m;
for (int i = 0; i < (n); ++i)
for (int j = 0; j < (m); ++j)
for (int e = 0; e < (n); ++e)
for (int w = 0; w < (m); ++w) {
win[i][j][e][w] = tox[i][j][e][w] = toy[i][j][e][w] = -1;
}
queue<array<int, 4>> q;
vector<int> dx = {-1, 1, -2, 2, -1, 1, -2, 2};
vector<int> dy = {2, 2, 1, 1, -2, -2, -1, -1};
int X = n / 2 - 1;
int Y = m / 2 - 1;
for (int x1 = 0; x1 < (n); ++x1)
for (int y1 = 0; y1 < (m); ++y1)
for (int x2 = 0; x2 < (n); ++x2)
for (int y2 = 0; y2 < (m); ++y2) {
if (x1 == x2 && y1 == y2) {
win[x1][y1][x2][y2] = 0;
q.push({x1, y1, x2, y2});
ended[x1][y1][x2][y2] = true;
continue;
}
int xd = abs(x1 - x2);
int yd = abs(y1 - y2);
if (xd + yd == 3 && xd && yd) {
win[x1][y1][x2][y2] = 1;
tox[x1][y1][x2][y2] = x2;
toy[x1][y1][x2][y2] = y2;
q.push({x1, y1, x2, y2});
continue;
}
if (x1 == X && y1 == Y) {
win[x1][y1][x2][y2] = 1;
ended[x1][y1][x2][y2] = true;
q.push({x1, y1, x2, y2});
continue;
}
if (x2 == X + 1 && y2 == Y) {
win[x1][y1][x2][y2] = 0;
ended[x1][y1][x2][y2] = true;
q.push({x1, y1, x2, y2});
continue;
}
for (int w = 0; w < (8); ++w) {
int xx = x1 + dx[w];
int yy = y1 + dy[w];
if (xx < 0 || xx >= n || yy < 0 || yy >= m) continue;
deg[x1][y1][x2][y2]++;
}
}
while (!q.empty()) {
auto [x1, y1, x2, y2] = q.front();
q.pop();
if (win[x1][y1][x2][y2]) {
int xx1 = n - 1 - x2;
int yy1 = y2;
int xx2 = n - 1 - x1;
int yy2 = y1;
for (int w = 0; w < (8); ++w) {
int xx = xx1 + dx[w];
int yy = yy1 + dy[w];
if (xx < 0 || xx >= n || yy < 0 || yy >= m) continue;
if (win[xx][yy][xx2][yy2] != -1) continue;
if (!(--deg[xx][yy][xx2][yy2])) {
win[xx][yy][xx2][yy2] = 0;
q.push({xx, yy, xx2, yy2});
}
}
} else {
int xx1 = n - 1 - x2;
int yy1 = y2;
int xx2 = n - 1 - x1;
int yy2 = y1;
for (int w = 0; w < (8); ++w) {
int xx = xx1 + dx[w];
int yy = yy1 + dy[w];
if (xx < 0 || xx >= n || yy < 0 || yy >= m) continue;
if (win[xx][yy][xx2][yy2] != -1) continue;
win[xx][yy][xx2][yy2] = 1;
tox[xx][yy][xx2][yy2] = xx1;
toy[xx][yy][xx2][yy2] = yy1;
q.push({xx, yy, xx2, yy2});
}
}
}
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
x1--;
y1--;
x2--;
y2--;
if (win[x1][y1][x2][y2] == 1) {
cout << "WHITE" << endl;
while (true) {
assert(win[x1][y1][x2][y2] == 1);
if (ended[x1][y1][x2][y2]) return;
int x11 = tox[x1][y1][x2][y2];
int y11 = toy[x1][y1][x2][y2];
cout << x11 + 1 << ' ' << y11 + 1 << endl;
if (ended[n - 1 - x2][y2][n - 1 - x11][y11]) return;
int x22, y22;
cin >> x22 >> y22;
if (x22 == -1) exit(0);
x1 = x11;
y1 = y11;
x2 = x22 - 1;
y2 = y22 - 1;
}
} else {
cout << "BLACK" << endl;
swap(x1, x2);
swap(y1, y2);
x1 = n - 1 - x1;
x2 = n - 1 - x2;
cin >> x2 >> y2;
x2--;
y2--;
x2 = n - 1 - x2;
while (true) {
assert(win[x1][y1][x2][y2] == 1);
if (ended[x1][y1][x2][y2]) return;
int x11 = tox[x1][y1][x2][y2];
int y11 = toy[x1][y1][x2][y2];
cout << n - x11 << ' ' << y11 + 1 << endl;
if (ended[n - 1 - x2][y2][n - 1 - x11][y11]) return;
int x22, y22;
cin >> x22 >> y22;
if (x22 == -1) exit(0);
x1 = x11;
y1 = y11;
x2 = x22 - 1;
y2 = y22 - 1;
x2 = n - x2 - 1;
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int tests = 1;
for (int _ = 0; _ < (tests); ++_) {
solve();
}
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Monocarp wants to draw four line segments on a sheet of paper. He wants the i-th segment to have its length equal to a_i (1 β€ i β€ 4). These segments can intersect with each other, and each segment should be either horizontal or vertical.
Monocarp wants to draw the segments in such a way that they enclose a rectangular space, and the area of that rectangular space should be maximum possible.
For example, if Monocarp wants to draw four segments with lengths 1, 2, 3 and 4, he can do it the following way:
<image> Here, Monocarp has drawn segments AB (with length 1), CD (with length 2), BC (with length 3) and EF (with length 4). He got a rectangle ABCF with area equal to 3 that is enclosed by the segments.
Calculate the maximum area of a rectangle Monocarp can enclose with four segments.
Input
The first line contains one integer t (1 β€ t β€ 3 β
10^4) β the number of test cases.
Each test case consists of a single line containing four integers a_1, a_2, a_3, a_4 (1 β€ a_i β€ 10^4) β the lengths of the segments Monocarp wants to draw.
Output
For each test case, print one integer β the maximum area of a rectangle Monocarp can enclose with four segments (it can be shown that the answer is always an integer).
Example
Input
4
1 2 3 4
5 5 5 5
3 1 4 1
100 20 20 100
Output
3
25
3
2000
Note
The first test case of the example is described in the statement.
For the second test case, Monocarp can draw the segments AB, BC, CD and DA as follows:
<image> Here, Monocarp has drawn segments AB (with length 5), BC (with length 5), CD (with length 5) and DA (with length 5). He got a rectangle ABCD with area equal to 25 that is enclosed by the segments.
### Response
```cpp
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
while(t--) {
int a,b,c,d;
cin>>a>>b>>c>>d;
int arr[4] = {a,b,c,d};
sort(arr, arr + 4);
cout<<arr[0] * arr[2]<<endl;
}
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Berland has n cities connected by m bidirectional roads. No road connects a city to itself, and each pair of cities is connected by no more than one road. It is not guaranteed that you can get from any city to any other one, using only the existing roads.
The President of Berland decided to make changes to the road system and instructed the Ministry of Transport to make this reform. Now, each road should be unidirectional (only lead from one city to another).
In order not to cause great resentment among residents, the reform needs to be conducted so that there can be as few separate cities as possible. A city is considered separate, if no road leads into it, while it is allowed to have roads leading from this city.
Help the Ministry of Transport to find the minimum possible number of separate cities after the reform.
Input
The first line of the input contains two positive integers, n and m β the number of the cities and the number of roads in Berland (2 β€ n β€ 100 000, 1 β€ m β€ 100 000).
Next m lines contain the descriptions of the roads: the i-th road is determined by two distinct integers xi, yi (1 β€ xi, yi β€ n, xi β yi), where xi and yi are the numbers of the cities connected by the i-th road.
It is guaranteed that there is no more than one road between each pair of cities, but it is not guaranteed that from any city you can get to any other one, using only roads.
Output
Print a single integer β the minimum number of separated cities after the reform.
Examples
Input
4 3
2 1
1 3
4 3
Output
1
Input
5 5
2 1
1 3
2 3
2 5
4 3
Output
0
Input
6 5
1 2
2 3
4 5
4 6
5 6
Output
1
Note
In the first sample the following road orientation is allowed: <image>, <image>, <image>.
The second sample: <image>, <image>, <image>, <image>, <image>.
The third sample: <image>, <image>, <image>, <image>, <image>.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int dfs_(int n, vector<vector<int>> &adj_list) {
set<int> unvisited;
for (int i = 1; i <= n; i++) unvisited.insert(i);
int count = 0;
while (!unvisited.empty()) {
auto iter_set = unvisited.begin();
int start_node = *iter_set;
bool cycle = 0;
stack<int> st;
st.push(start_node);
unvisited.erase(start_node);
int prev_node = start_node;
while (!st.empty()) {
int cur_node = st.top();
st.pop();
for (auto &iter : adj_list[cur_node]) {
if (unvisited.find(iter) != unvisited.end()) {
st.push(iter);
prev_node = iter;
unvisited.erase(iter);
} else if (iter != prev_node && iter != start_node) {
cycle = true;
}
}
prev_node = cur_node;
}
if (!cycle) count++;
}
return count;
}
bool visited[100001];
int levels[100001];
int temp_count = 0;
int res_count = 0;
void dfs(int src, vector<vector<int>> &adj_list) {
visited[src] = true;
for (auto &iter : adj_list[src]) {
if (!visited[iter]) {
levels[iter] = levels[src] + 1;
dfs(iter, adj_list);
} else if (levels[iter] > levels[src] + 1) {
temp_count++;
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, m;
int x, y;
cin >> n >> m;
for (int i = 1; i <= n; i++) visited[i] = false;
for (int i = 1; i <= n; i++) levels[i] = 0;
vector<vector<int>> adj_list(n + 1);
for (int i = 0; i < m; ++i) {
cin >> x >> y;
adj_list[x].push_back(y);
adj_list[y].push_back(x);
}
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
temp_count = 0;
dfs(i, adj_list);
if (temp_count == 0) res_count++;
}
}
cout << res_count << endl;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Consider a football tournament where n teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the i-th team has color xi and the kit for away games of this team has color yi (xi β yi).
In the tournament, each team plays exactly one home game and exactly one away game with each other team (n(n - 1) games in total). The team, that plays the home game, traditionally plays in its home kit. The team that plays an away game plays in its away kit. However, if two teams has the kits of the same color, they cannot be distinguished. In this case the away team plays in its home kit.
Calculate how many games in the described tournament each team plays in its home kit and how many games it plays in its away kit.
Input
The first line contains a single integer n (2 β€ n β€ 105) β the number of teams. Next n lines contain the description of the teams. The i-th line contains two space-separated numbers xi, yi (1 β€ xi, yi β€ 105; xi β yi) β the color numbers for the home and away kits of the i-th team.
Output
For each team, print on a single line two space-separated integers β the number of games this team is going to play in home and away kits, correspondingly. Print the answers for the teams in the order they appeared in the input.
Examples
Input
2
1 2
2 1
Output
2 0
2 0
Input
3
1 2
2 1
1 3
Output
3 1
4 0
2 2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int32_t main() {
long long n;
cin >> n;
long long arr[n][2];
map<long long, long long> mp;
for (long long i = 0; i < n; i++)
cin >> arr[i][0] >> arr[i][1], mp[arr[i][0]]++;
long long brr[n][2];
for (long long i = 0; i < n; i++) brr[i][1] = n - 1, brr[i][0] = n - 1;
for (long long i = 0; i < n; i++) {
long long x = mp[arr[i][1]];
brr[i][0] += x, brr[i][1] -= x;
}
for (long long i = 0; i < n; i++)
cout << brr[i][0] << ' ' << brr[i][1] << endl;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
The only difference between easy and hard versions is constraints.
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following:
* The i-th student randomly chooses a ticket.
* if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.
* if the student finds the ticket easy, he spends exactly t_i minutes to pass the exam. After it, he immediately gets a mark and goes home.
Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.
The duration of the whole exam for all students is M minutes (max t_i β€ M), so students at the end of the list have a greater possibility to run out of time to pass the exam.
For each student i, you should count the minimum possible number of students who need to fail the exam so the i-th student has enough time to pass the exam.
For each student i, find the answer independently. That is, if when finding the answer for the student i_1 some student j should leave, then while finding the answer for i_2 (i_2>i_1) the student j student does not have to go home.
Input
The first line of the input contains two integers n and M (1 β€ n β€ 100, 1 β€ M β€ 100) β the number of students and the total duration of the exam in minutes, respectively.
The second line of the input contains n integers t_i (1 β€ t_i β€ 100) β time in minutes that i-th student spends to answer to a ticket.
It's guaranteed that all values of t_i are not greater than M.
Output
Print n numbers: the i-th number must be equal to the minimum number of students who have to leave the exam in order to i-th student has enough time to pass the exam.
Examples
Input
7 15
1 2 3 4 5 6 7
Output
0 0 0 0 0 2 3
Input
5 100
80 40 40 40 60
Output
0 1 1 2 3
Note
The explanation for the example 1.
Please note that the sum of the first five exam times does not exceed M=15 (the sum is 1+2+3+4+5=15). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are 0.
In order for the 6-th student to pass the exam, it is necessary that at least 2 students must fail it before (for example, the 3-rd and 4-th, then the 6-th will finish its exam in 1+2+5+6=14 minutes, which does not exceed M).
In order for the 7-th student to pass the exam, it is necessary that at least 3 students must fail it before (for example, the 2-nd, 5-th and 6-th, then the 7-th will finish its exam in 1+3+4+7=15 minutes, which does not exceed M).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename T>
istream &operator>>(istream &is, vector<T> &vec) {
for (auto &v : vec) is >> v;
return is;
}
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};
const int mx = 1e6 + 5;
const int INF = 1000000007;
long long power(int x, unsigned int y) {
long long res = 1;
while (y > 0) {
if (y & 1) res = res * x;
y >>= 1;
x *= x;
}
return res;
}
void solve() {
int n, m;
cin >> n >> m;
vector<long long> arr(n);
cin >> arr;
vector<long long> count(101, 0);
long long total_sum = arr[0];
count[arr[0]]++;
cout << 0 << ' ';
for (int i = 1; i < n; i++) {
long long curr_sum = total_sum + arr[i] - m;
long long ref = 0;
if (curr_sum > 0) {
for (int j = 100; j > 0; j--) {
long long x = j * count[j];
if (curr_sum <= x) {
ref += ceil(curr_sum * 1.0 / j);
break;
}
ref += count[j];
curr_sum -= x;
}
}
count[arr[i]]++;
total_sum += arr[i];
cout << ref << ' ';
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t = 1;
while (t--) {
solve();
}
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
One day Petya was solving a very interesting problem. But although he used many optimization techniques, his solution still got Time limit exceeded verdict. Petya conducted a thorough analysis of his program and found out that his function for finding maximum element in an array of n positive integers was too slow. Desperate, Petya decided to use a somewhat unexpected optimization using parameter k, so now his function contains the following code:
int fast_max(int n, int a[]) {
int ans = 0;
int offset = 0;
for (int i = 0; i < n; ++i)
if (ans < a[i]) {
ans = a[i];
offset = 0;
} else {
offset = offset + 1;
if (offset == k)
return ans;
}
return ans;
}
That way the function iteratively checks array elements, storing the intermediate maximum, and if after k consecutive iterations that maximum has not changed, it is returned as the answer.
Now Petya is interested in fault rate of his function. He asked you to find the number of permutations of integers from 1 to n such that the return value of his function on those permutations is not equal to n. Since this number could be very big, output the answer modulo 109 + 7.
Input
The only line contains two integers n and k (1 β€ n, k β€ 106), separated by a space β the length of the permutations and the parameter k.
Output
Output the answer to the problem modulo 109 + 7.
Examples
Input
5 2
Output
22
Input
5 3
Output
6
Input
6 3
Output
84
Note
Permutations from second example:
[4, 1, 2, 3, 5], [4, 1, 3, 2, 5], [4, 2, 1, 3, 5], [4, 2, 3, 1, 5], [4, 3, 1, 2, 5], [4, 3, 2, 1, 5].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long mod = 1e9 + 7;
unordered_map<int, int> cache;
int inv(int a) {
if (a == 1) return 1;
if (cache.count(a)) return cache[a];
int x = (mod + a - 1) / a;
int b = (a * x) % mod;
return cache[a] = ((long long)inv(b) * x) % mod;
}
int n, k;
long long E[1000005];
long long ES[1000005];
long long fact[1000005];
int main(void) {
fact[0] = 1;
for (int i = 1; i <= 1000000; i++) {
fact[i] = (fact[i - 1] * i) % mod;
}
scanf(" %d %d", &n, &k);
E[0] = E[1] = 0;
ES[0] = ES[1] = 0;
long long finv = 1LL;
for (int m = 2; m <= n; m++) {
finv *= inv(m - 1);
finv %= mod;
if (m - k < 1) {
E[m] = ES[m] = 0;
continue;
}
long long sum = (ES[m - 1] - ES[m - k - 1] + mod) % mod;
long long D = fact[m - 2] * (sum + max(m - 1 - k, 0));
D %= mod;
E[m] = (D * finv) % mod;
ES[m] = (ES[m - 1] + E[m]) % mod;
}
cout << (fact[n - 1] * ES[n]) % mod << endl;
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 β€ n β€ 1 000, 0 β€ m β€ 100 000, 1 β€ k β€ n) β the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 β€ ci β€ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 β€ ui, vi β€ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool isSpecial[112345] = {false};
vector<int> adj[112345];
bool vis[112345];
long long int vCnt, eCnt, maxV = 0, spare = 0;
bool spcThr = false;
void dfs(int u) {
vis[u] = true;
if (isSpecial[u]) {
spcThr = true;
}
vCnt++;
for (int i = 0; i < adj[u].size(); ++i) {
int v = adj[u][i];
if (u < v) {
eCnt++;
}
if (vis[v] == false) {
dfs(v);
}
}
}
int main() {
int n, m, k;
long long int ans = 0;
cin >> n >> m >> k;
for (int i = 0; i < k; ++i) {
int c;
scanf("%d", &c);
isSpecial[c] = true;
}
while (m--) {
int u, v;
scanf("%d", &u);
scanf("%d", &v);
adj[u].push_back(v);
adj[v].push_back(u);
}
for (int i = 1; i < n + 1; ++i) {
if (vis[i] == false) {
spcThr = false;
vCnt = 0;
eCnt = 0;
dfs(i);
ans += (vCnt * (vCnt - 1)) / 2 - eCnt;
if (spcThr) {
maxV = max(maxV, vCnt);
} else {
ans += spare * vCnt;
spare += vCnt;
}
}
}
ans += maxV * spare;
cout << ans << endl;
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of n integers a_i.
It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score 1. Now Janusz wonders, for given sequence, how much elements should the player choose?
Input
The first line contains an only integer n (1 β€ n β€ 300 000) β the number of integers in the sequence.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 300 000).
Output
If there is no subset of the given sequence with gcd equal to 1, output -1.
Otherwise, output exactly one integer β the size of the smallest subset with gcd equal to 1.
Examples
Input
3
10 6 15
Output
3
Input
3
2 4 6
Output
-1
Input
7
30 60 21 42 70 15 30
Output
3
Note
In the first example, selecting a subset of all numbers gives a gcd of 1 and for all smaller subsets the gcd is greater than 1.
In the second example, for all subsets of numbers the gcd is at least 2.
### Response
```cpp
#include <bits/stdc++.h>
const int maxn = 333333;
int np[maxn], mp[maxn], mu[maxn], pr[maxn], pn;
int a[maxn], c[maxn], g[maxn], n;
int In() {
register int c, f, s;
for (; c = getchar(), c != '-' && !isdigit(c);)
;
for (s = (f = c == '-') ? 0 : c - '0'; c = getchar(), isdigit(c);)
s = s * 10 + c - '0';
return f ? -s : s;
}
bool cmin(register int &a, register int b) { return a > b ? (a = b, 1) : 0; }
int gcd(register int a, register int b) { return b ? gcd(b, a % b) : a; }
int main() {
np[1] = 1, mu[1] = 1;
for (register int i = 2; i <= 300000; ++i) {
if (!np[i]) pr[++pn] = i, mp[i] = i, mu[i] = -1;
for (register int j = 1; j <= pn && i * pr[j] <= 300000; ++j) {
np[i * pr[j]] = 1, mp[i * pr[j]] = pr[j];
if (i % pr[j])
mu[i * pr[j]] = -mu[i];
else {
mu[i * pr[j]] = 0;
break;
}
}
}
n = In();
for (register int i = 1; i <= n; ++i) ++a[In()];
for (register int i = 1; i <= 300000; ++i) g[i] = a[i] ? 1 : 0x3f3f3f3f;
for (register int i = 1; i <= 300000; ++i)
for (register int j = i * 2; j <= 300000; j += i) a[i] += a[j];
for (register int i = 1; i <= 300000; ++i)
if (mu[i])
for (register int j = i; j <= 300000; j += i) c[j] += mu[i] * a[i];
for (register int i = 300000; i >= 1; --i)
for (register int j = i * 2; j <= 300000; j += i)
if (c[j / i]) cmin(g[i], g[j] + 1);
printf("%d\n", g[1] == 0x3f3f3f3f ? -1 : g[1]);
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Smart Beaver is careful about his appearance and pays special attention to shoes so he has a huge number of pairs of shoes from the most famous brands of the forest. He's trying to handle his shoes carefully so that each pair stood side by side. But by the end of the week because of his very active lifestyle in his dressing room becomes a mess.
Smart Beaver from ABBYY is not only the brightest beaver in the area, but he also is the most domestically oriented. For example, on Mondays the Smart Beaver cleans everything in his home.
It's Monday morning. Smart Beaver does not want to spend the whole day cleaning, besides, there is much in to do and itβs the gym day, so he wants to clean up as soon as possible. Now the floors are washed, the dust is wiped off β itβs time to clean up in the dressing room. But as soon as the Smart Beaver entered the dressing room, all plans for the day were suddenly destroyed: chaos reigned there and it seemed impossible to handle, even in a week. Give our hero some hope: tell him what is the minimum number of shoes need to change the position to make the dressing room neat.
The dressing room is rectangular and is divided into n Γ m equal squares, each square contains exactly one shoe. Each pair of shoes has a unique number that is integer from 1 to <image>, more formally, a square with coordinates (i, j) contains an integer number of the pair which is lying on it. The Smart Beaver believes that the dressing room is neat only when each pair of sneakers lies together. We assume that the pair of sneakers in squares (i1, j1) and (i2, j2) lies together if |i1 - i2| + |j1 - j2| = 1.
Input
The first line contains two space-separated integers n and m. They correspond to the dressing room size. Next n lines contain m space-separated integers each. Those numbers describe the dressing room. Each number corresponds to a snicker.
It is guaranteed that:
* nΒ·m is even.
* All numbers, corresponding to the numbers of pairs of shoes in the dressing room, will lie between 1 and <image>.
* Each number from 1 to <image> will occur exactly twice.
The input limits for scoring 30 points are (subproblem C1):
* 2 β€ n, m β€ 8.
The input limits for scoring 100 points are (subproblems C1+C2):
* 2 β€ n, m β€ 80.
Output
Print exactly one integer β the minimum number of the sneakers that need to change their location.
Examples
Input
2 3
1 1 2
2 3 3
Output
2
Input
3 4
1 3 2 6
2 1 5 6
4 4 5 3
Output
4
Note
<image> The second sample.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int dp[10][1 << 10], num[10][10];
int n, m;
void OP(int msk) {
for (int i = 0; i < m; i++)
if (1 << i & msk)
cout << 1;
else
cout << 0;
}
void shift(int &a, int b) {
if (a == -1 || a > b) a = b;
}
void dfs(int p, int flag, int i, int msk, int cost, int nmsk) {
if (p == m) {
if (flag == 0) {
shift(dp[i + 1][nmsk], cost + dp[i][msk]);
}
return;
}
if (1 << p & msk) {
if (flag == 0) {
int c = cost;
if (num[i + 1][p] != num[i][p]) c++;
dfs(p + 1, 0, i, msk, c, nmsk);
}
} else if (flag) {
int c = cost;
if (num[i + 1][p] != num[i + 1][p - 1]) c++;
dfs(p + 1, 0, i, msk, c, nmsk);
} else {
int c = cost;
dfs(p + 1, 0, i, msk, cost, nmsk | (1 << p));
c = cost;
dfs(p + 1, 1, i, msk, cost, nmsk);
}
}
int main() {
memset(dp, -1, sizeof(dp));
dp[0][0] = 0;
cin >> n >> m;
for (int i = 1; i <= n; i++)
for (int j = 0; j < m; j++) cin >> num[i][j];
for (int i = 0; i < n; i++) {
for (int msk = 0; msk < (1 << m); msk++)
if (dp[i][msk] != -1) {
dfs(0, 0, i, msk, 0, 0);
}
}
cout << dp[n][0] << endl;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
You are playing a game where your character should overcome different obstacles. The current problem is to come down from a cliff. The cliff has height h, and there is a moving platform on each height x from 1 to h.
Each platform is either hidden inside the cliff or moved out. At first, there are n moved out platforms on heights p_1, p_2, ..., p_n. The platform on height h is moved out (and the character is initially standing there).
If you character is standing on some moved out platform on height x, then he can pull a special lever, which switches the state of two platforms: on height x and x - 1. In other words, the platform you are currently standing on will hide in the cliff and the platform one unit below will change it state: it will hide if it was moved out or move out if it was hidden. In the second case, you will safely land on it. Note that this is the only way to move from one platform to another.
Your character is quite fragile, so it can safely fall from the height no more than 2. In other words falling from the platform x to platform x - 2 is okay, but falling from x to x - 3 (or lower) is certain death.
Sometimes it's not possible to come down from the cliff, but you can always buy (for donate currency) several magic crystals. Each magic crystal can be used to change the state of any single platform (except platform on height h, which is unaffected by the crystals). After being used, the crystal disappears.
What is the minimum number of magic crystal you need to buy to safely land on the 0 ground level?
Input
The first line contains one integer q (1 β€ q β€ 100) β the number of queries. Each query contains two lines and is independent of all other queries.
The first line of each query contains two integers h and n (1 β€ h β€ 10^9, 1 β€ n β€ min(h, 2 β
10^5)) β the height of the cliff and the number of moved out platforms.
The second line contains n integers p_1, p_2, ..., p_n (h = p_1 > p_2 > ... > p_n β₯ 1) β the corresponding moved out platforms in the descending order of their heights.
The sum of n over all queries does not exceed 2 β
10^5.
Output
For each query print one integer β the minimum number of magic crystals you have to spend to safely come down on the ground level (with height 0).
Example
Input
4
3 2
3 1
8 6
8 7 6 5 3 2
9 6
9 8 5 4 3 1
1 1
1
Output
0
1
2
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void READ(vector<long long> &v, long long n) {
long long a;
for (long long i = 0; i < n; i = i + 1) {
cin >> a;
v.push_back(a);
}
}
void PRINT(vector<long long> &v, long long a = 0) {
for (long long i = a; i < v.size(); i = i + 1) {
cout << v[i] << " ";
}
cout << "\n";
}
double logy(long long n, long long b) {
if (b == 0) {
return (-1);
}
if (n == 1) {
return (0);
}
return ((double)log10(n) / log10(b));
}
long long power(long long k, long long n, long long m = 1000000007) {
long long res = 1;
while (n) {
if (n % 2 != 0) {
res = (res * k) % m;
}
k = (k * k) % m;
n = n / 2;
}
return (res);
}
double power(double k, long long n) {
double res = 1;
while (n) {
if (n % 2 != 0) {
res = (res * k);
}
k = (k * k);
n = n / 2;
}
return (res);
}
double distance(pair<long long, long long> a, pair<long long, long long> b) {
return ((double)(sqrt((a.first - b.first) * (a.first - b.first) +
(a.second - b.second) * (a.second - b.second))));
}
const long long dx[8] = {-1, -1, -1, 0, 1, 1, 1, 0};
const long long dy[8] = {-1, 0, 1, 1, 1, 0, -1, -1};
vector<pair<long long, long long> > dr;
long long n, m, k, h;
bool ok = false;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
std::cout.unsetf(std::ios::floatfield);
std::cout.precision((long long)10);
long long a, b, c, d, i, j, t, x, y, z;
double p, q, r, u, w;
string str, st, str1, str2, str3, str4;
cin >> t;
while (t--) {
cin >> h >> n;
vector<long long> v;
map<long long, long long> hai;
for (i = 0; i < n; i++) {
cin >> a;
v.push_back(a);
hai[a] = 1;
}
x = 0;
for (j = 0; j < n;) {
i = v[j];
if (i <= 2) {
break;
}
if (!hai[i - 1]) {
if (i - 1 <= 2) {
break;
}
j++;
while (j < n) {
if (hai[v[j]] && hai[v[j] - 1]) {
j++;
break;
}
if (v[j] <= 1) {
break;
}
x++;
j++;
}
if (j < n && v[j] <= 1) {
break;
}
continue;
}
if (hai[i - 1] && hai[i - 2]) {
j += 2;
continue;
}
if (hai[i - 1]) {
x++;
if (i - 2 <= 2) {
break;
}
j += 2;
while (j < n) {
if (hai[v[j]] && hai[v[j] - 1]) {
j++;
break;
}
if (v[j] <= 1) {
break;
}
x++;
j++;
}
if (j < n && v[j] <= 1) {
break;
}
}
}
cout << x << "\n";
}
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
We have an N \times M grid. The square at the i-th row and j-th column will be denoted as (i,j). Particularly, the top-left square will be denoted as (1,1), and the bottom-right square will be denoted as (N,M). Takahashi painted some of the squares (possibly zero) black, and painted the other squares white.
We will define an integer sequence A of length N, and two integer sequences B and C of length M each, as follows:
* A_i(1\leq i\leq N) is the minimum j such that (i,j) is painted black, or M+1 if it does not exist.
* B_i(1\leq i\leq M) is the minimum k such that (k,i) is painted black, or N+1 if it does not exist.
* C_i(1\leq i\leq M) is the maximum k such that (k,i) is painted black, or 0 if it does not exist.
How many triples (A,B,C) can occur? Find the count modulo 998244353.
Constraints
* 1 \leq N \leq 8000
* 1 \leq M \leq 200
* N and M are integers.
Partial Score
* 1500 points will be awarded for passing the test set satisfying N\leq 300.
Constraints
* 1 \leq N \leq 8000
* 1 \leq M \leq 200
* N and M are integers.
Input
Input is given from Standard Input in the following format:
N M
Output
Print the number of triples (A,B,C), modulo 998244353.
Examples
Input
2 3
Output
64
Input
4 3
Output
2588
Input
17 13
Output
229876268
Input
5000 100
Output
57613837
### Response
```cpp
#include<bits/stdc++.h>
#define pb push_back
#define gc getchar
using namespace std;
const int N=5e4+10,mod=998244353,g=3;
typedef long long ll;
typedef double db;
int n,m,ans,f[N],h[N],t[N],frc[N],nv[N],ivg;
char cp;
template<class T>inline void rd(T &x)
{
cp=gc();x=0;int f=0;
for(;!isdigit(cp);cp=gc()) if(cp=='-') f=1;
for(;isdigit(cp);cp=gc()) x=x*10+(cp^48);
if(f) x=-x;
}
inline int fp(int x,int y)
{
int re=1;
for(;y;y>>=1,x=(ll)x*x%mod)
if(y&1) re=(ll)re*x%mod;
return re;
}
inline int ad(int x,int y){x+=y;return x>=mod?x-mod:x;}
inline int dc(int x,int y){x-=y;return x<0?x+mod:x;}
inline int C(int n,int m)
{
if(m>n) return 0;
return (ll)frc[n]*nv[m]%mod*(ll)nv[n-m]%mod;
}
namespace poly{
int rv[N],L,len;
inline void ntt(int *e,int pr)
{
int i,j,k,ix,iy,pd,ori,G=pr?g:ivg;
for(i=1;i<len;++i) if(i<rv[i]) swap(e[i],e[rv[i]]);
for(i=1;i<len;i<<=1){
ori=fp(G,(mod-1)/(i<<1));
for(j=0;j<len;j+=(i<<1)){
for(pd=1,k=0;k<i;++k,pd=(ll)pd*ori%mod){
ix=e[j+k];iy=(ll)pd*e[j+i+k]%mod;
e[j+k]=ad(ix,iy);e[i+j+k]=dc(ix,iy);
}
}
}
if(pr) return;
G=fp(len,mod-2);
for(i=0;i<len;++i) e[i]=(ll)e[i]*G%mod;
}
void mul(int *f,int *g,int n,int m)
{
int i;
for(L=0,len=1;len<=n+m;len<<=1) L++;
for(i=1;i<len;++i) rv[i]=(rv[i>>1]>>1)|((i&1)<<(L-1));
for(i=n+1;i<len;++i) f[i]=0;
for(i=m+1;i<len;++i) g[i]=0;
ntt(f,1);ntt(g,1);
for(i=0;i<len;++i) f[i]=(ll)f[i]*g[i]%mod;
ntt(f,0);
}
}
using namespace poly;
int main(){
int i,j,x,y;ivg=fp(g,mod-2);
rd(n);rd(m);
f[0]=frc[0]=nv[0]=frc[1]=nv[1]=1;
for(i=2;i<n+3;++i)
frc[i]=(ll)frc[i-1]*i%mod,
nv[i]=(ll)(mod-mod/i)*nv[mod%i]%mod;
for(i=2;i<n+3;++i) nv[i]=(ll)nv[i-1]*nv[i]%mod;
for(i=1;i<=n;++i) h[i]=nv[i+2];
for(L=0,len=1;len<=(n<<1);len<<=1) L++;
for(i=1;i<len;++i) rv[i]=((rv[i>>1]>>1)|((i&1)<<(L-1)));
ntt(h,1);
for(j=1;j<=m;++j){
for(i=0;i<=n;++i) t[i]=(ll)nv[i]*f[i]%mod;
for(i=n+1;i<len;++i) t[i]=0;
ntt(t,1);
for(i=0;i<len;++i) t[i]=(ll)h[i]*t[i]%mod;
ntt(t,0);
for(i=0;i<=n;++i)
f[i]=ad((ll)(1+C(i+1,2))*f[i]%mod,(ll)t[i]*frc[i+2]%mod);
}
for(i=0;i<=n;++i) ans=ad(ans,(ll)C(n,i)*f[i]%mod);
printf("%d",ans);
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.
The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that.
Input
The first line contains integer n (1 β€ n β€ 5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1 β€ li < ri β€ 106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1).
Output
Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order.
Examples
Input
3
3 10
20 30
1 3
Output
3
1 2 3
Input
4
3 10
20 30
1 3
1 39
Output
1
4
Input
3
1 5
2 6
3 7
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct aaa {
int l, r, num;
bool us;
};
bool comp(const aaa a, const aaa b) { return a.l < b.l; }
int main() {
aaa f[5002];
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d %d", &f[i].l, &f[i].r);
f[i].num = i;
}
sort(f + 1, f + n + 1, comp);
f[n + 1].l = 10000000;
int res = 0;
for (int i = 1; i <= n; i++) {
f[i].us = false;
bool flag = true;
for (int j = 1; j < n; j++) {
if (j != i) {
if (i == j + 1) {
if (f[j].r > f[j + 2].l) {
flag = false;
break;
}
} else {
if (f[j].r > f[j + 1].l) {
flag = false;
break;
}
}
}
}
if (flag) {
res++;
f[i].us = true;
}
}
printf("%d\n", res);
vector<int> p;
for (int i = 1; i <= n; i++) {
if (f[i].us) p.push_back(f[i].num);
}
sort(p.begin(), p.end());
for (int i = 0; i < res; i++) {
if (i == res - 1)
printf("%d\n", p[i]);
else
printf("%d ", p[i]);
}
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
We have 3N colored balls with IDs from 1 to 3N. A string S of length 3N represents the colors of the balls. The color of Ball i is red if S_i is `R`, green if S_i is `G`, and blue if S_i is `B`. There are N red balls, N green balls, and N blue balls.
Takahashi will distribute these 3N balls to N people so that each person gets one red ball, one blue ball, and one green ball. The people want balls with IDs close to each other, so he will additionally satisfy the following condition:
* Let a_j < b_j < c_j be the IDs of the balls received by the j-th person in ascending order.
* Then, \sum_j (c_j-a_j) should be as small as possible.
Find the number of ways in which Takahashi can distribute the balls. Since the answer can be enormous, compute it modulo 998244353. We consider two ways to distribute the balls different if and only if there is a person who receives different sets of balls.
Constraints
* 1 \leq N \leq 10^5
* |S|=3N
* S consists of `R`, `G`, and `B`, and each of these characters occurs N times in S.
Input
Input is given from Standard Input in the following format:
N
S
Output
Print the number of ways in which Takahashi can distribute the balls, modulo 998244353.
Examples
Input
3
RRRGGGBBB
Output
216
Input
5
BBRGRRGRGGRBBGB
Output
960
### Response
```cpp
#include<cstdio>
int n,i,j,b[3],a=1,P=998244353;int main(){scanf("%d\n",&n);for(i=3*n;--i;){char c=getchar();int &t=b[c%3],m=P;for(j=3;~--j;)m=b[j]>t&&b[j]-t<m?b[j]-t:m;a=1ll*a*(m<=n?m:1)%P*(i<=n?i:1)%P;++t;}printf("%d",a);}
``` |
### Prompt
Create a solution in cpp for the following problem:
We have sticks numbered 1, \cdots, N. The length of Stick i (1 \leq i \leq N) is L_i.
In how many ways can we choose three of the sticks with different lengths that can form a triangle?
That is, find the number of triples of integers (i, j, k) (1 \leq i < j < k \leq N) that satisfy both of the following conditions:
* L_i, L_j, and L_k are all different.
* There exists a triangle whose sides have lengths L_i, L_j, and L_k.
Constraints
* 1 \leq N \leq 100
* 1 \leq L_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
L_1 L_2 \cdots L_N
Output
Print the number of ways to choose three of the sticks with different lengths that can form a triangle.
Examples
Input
5
4 4 9 7 5
Output
5
Input
6
4 5 4 3 3 5
Output
8
Input
10
9 4 6 1 9 6 10 6 6 8
Output
39
Input
2
1 1
Output
0
### Response
```cpp
#include<cstdio>
#include<algorithm>
using namespace std;
int main(void)
{
int n,l[100],i,j,k,c=0;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&l[i]);
}
sort(l,l+n);
for(i=0;i<n-2;i++){
for(j=i+1;j<n-1;j++){
for(k=j+1;k<n;k++){
if(l[i]!=l[j]&&l[i]!=l[k]&&l[j]!=l[k]){
if(l[i]+l[j]>l[k]) c++;
}
}
}
}
printf("%d\n",c);
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
You are given a string S of length N consisting of `A`, `B` and `C`, and an integer K which is between 1 and N (inclusive). Print the string S after lowercasing the K-th character in it.
Constraints
* 1 β€ N β€ 50
* 1 β€ K β€ N
* S is a string of length N consisting of `A`, `B` and `C`.
Input
Input is given from Standard Input in the following format:
N K
S
Output
Print the string S after lowercasing the K-th character in it.
Examples
Input
3 1
ABC
Output
aBC
Input
4 3
CABA
Output
CAbA
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int N,K;
cin>>N>>K;
string S;
cin>>S;
S.at(K-1)+=0x20;
cout<<S<<endl;
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition β when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.
Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.
<image>
You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.
Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.
Note one milliliter equals to one cubic centimeter.
Input
The only line of the input contains four integer numbers d, h, v, e (1 β€ d, h, v, e β€ 104), where:
* d β the diameter of your cylindrical cup,
* h β the initial level of water in the cup,
* v β the speed of drinking process from the cup in milliliters per second,
* e β the growth of water because of rain if you do not drink from the cup.
Output
If it is impossible to make the cup empty, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line. In the second line print a real number β time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.
Examples
Input
1 2 3 100
Output
NO
Input
1 1 1 1
Output
YES
3.659792366325
Note
In the first example the water fills the cup faster than you can drink from it.
In the second example area of the cup's bottom equals to <image>, thus we can conclude that you decrease the level of water by <image> centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in <image> seconds.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const double pi = 2 * acos(0.0);
const double EPS = 1e-9;
int main() {
double d, h, v, e;
while (cin >> d >> h >> v >> e) {
double t1 = v - e * pi * (d * d / 4.0);
if (t1 < EPS) {
cout << "NO" << endl;
} else {
double t2 = h * pi * (d * d) / 4.0;
cout << "YES" << endl << t2 / t1 << endl;
}
}
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
Recently, the Fair Nut has written k strings of length n, consisting of letters "a" and "b". He calculated c β the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.
Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string s and not bigger than string t. He is interested: what is the maximum value of c that he could get.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a β b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains two integers n and k (1 β€ n β€ 5 β
10^5, 1 β€ k β€ 10^9).
The second line contains a string s (|s| = n) β the string consisting of letters "a" and "b.
The third line contains a string t (|t| = n) β the string consisting of letters "a" and "b.
It is guaranteed that string s is lexicographically not bigger than t.
Output
Print one number β maximal value of c.
Examples
Input
2 4
aa
bb
Output
6
Input
3 3
aba
bba
Output
8
Input
4 5
abbb
baaa
Output
8
Note
In the first example, Nut could write strings "aa", "ab", "ba", "bb". These 4 strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, 6 strings.
In the second example, Nut could write strings "aba", "baa", "bba".
In the third example, there are only two different strings that Nut could write. If both of them are written, c=8.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long l, r, n, k;
long long ans = 0;
char s[500010], b[500010];
int main() {
cin >> n >> k;
scanf("%s%s", s + 1, b + 1);
for (int i = 1; i <= n; ++i) {
if (s[i] == 'b') l++;
if (b[i] == 'b') r++;
ans += min((r - l + 1), k);
if ((r - l + 1) <= k + 10) l *= 2, r *= 2, r -= l, l = 0;
}
cout << ans;
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Professor GukiZ makes a new robot. The robot are in the point with coordinates (x1, y1) and should go to the point (x2, y2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal number of steps the robot should make to get the finish position.
Input
The first line contains two integers x1, y1 ( - 109 β€ x1, y1 β€ 109) β the start position of the robot.
The second line contains two integers x2, y2 ( - 109 β€ x2, y2 β€ 109) β the finish position of the robot.
Output
Print the only integer d β the minimal number of steps to get the finish position.
Examples
Input
0 0
4 5
Output
5
Input
3 4
6 1
Output
3
Note
In the first example robot should increase both of its coordinates by one four times, so it will be in position (4, 4). After that robot should simply increase its y coordinate and get the finish position.
In the second example robot should simultaneously increase x coordinate and decrease y coordinate by one three times.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
int a = abs(x1 - x2);
int b = abs(y1 - y2);
int res = max(a, b);
cout << res;
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
N tiles are arranged in a row from left to right. The initial color of each tile is represented by a string S of length N.
The i-th tile from the left is painted black if the i-th character of S is `0`, and painted white if that character is `1`.
You want to repaint some of the tiles black or white, so that any two adjacent tiles have different colors.
At least how many tiles need to be repainted to satisfy the condition?
Constraints
* 1 \leq |S| \leq 10^5
* S_i is `0` or `1`.
Input
Input is given from Standard Input in the following format:
S
Output
Print the minimum number of tiles that need to be repainted to satisfy the condition.
Examples
Input
000
Output
1
Input
10010010
Output
3
Input
0
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
string S;
cin>>S;
int n=S.size();
int ans=0;
for(int i=0;i<n;i++){
ans+=(S.at(i)+i)%2;
}
cout<<min(ans,n-ans)<<endl;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
This is an interactive problem.
Note: the XOR-sum of an array a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9) is defined as a_1 β a_2 β β¦ β a_n, where β denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Little Dormi received an array of n integers a_1, a_2, β¦, a_n for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.
The XOR machine is currently configured with a query size of k (which you cannot change), and allows you to perform the following type of query: by giving the machine k distinct indices x_1, x_2, β¦, x_k, it will output a_{x_1} β a_{x_2} β β¦ β a_{x_k}.
As Little Dormi's older brother, you would like to help him recover the XOR-sum of his array a_1, a_2, β¦, a_n by querying the XOR machine.
Little Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the minimum number of times to find the XOR-sum of his array. Formally, let d be the minimum number of queries needed to find the XOR-sum of any array of length n with a query size of k. Your program will be accepted if you find the correct XOR-sum in at most d queries.
Lastly, you also noticed that with certain configurations of the machine k and values of n, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.
The array a_1, a_2, β¦, a_n is fixed before you start querying the XOR machine and does not change with the queries.
Input
The only line of input contains the integers n and k (1 β€ n β€ 500, 1 β€ k β€ n), the length of the lost array and the configured query size of the XOR machine.
Elements of the original array satisfy 1 β€ a_i β€ 10^9.
It can be proven that that if it is possible to recover the XOR sum under the given constraints, it can be done in at most 500 queries. That is, d β€ 500.
After taking n and k, begin interaction.
Output
If it is impossible to recover the XOR-sum of the array, output -1 immediately after taking n and k. Do not begin interaction.
Otherwise, when your program finds the XOR-sum of the lost array a_1, a_2, β¦, a_n, report the answer in the following format: "! x", where x is the XOR sum of the array a_1, a_2, β¦, a_n, and terminate your program normally immediately after flushing the output stream.
Note that answering does not count as a query.
Interaction
Each query is made in the format "? b", where b is an array of exactly k distinct integers from 1 to n denoting the indices of the elements in the lost array that you want to query the XOR sum of.
You will then receive an integer x, the XOR sum of the queried elements. It can be proven that 0 β€ x β€ 2 β
10^9 will always be true.
After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If at any point you make an invalid query or try to make more than 500 queries (which is the hard limit), the interaction will terminate immediately and give you a Wrong Answer verdict. Note that if you exceed d queries, the interaction will continue normally unless you also exceed the 500 query hard limit, though you will still receive a Wrong Answer verdict either way.
Hacks
To hack a solution, use the following format.
The first line contains the integers n and k (1 β€ n β€ 500, 1 β€ k β€ n).
The second line contains the the array a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9).
Examples
Input
5 3
4
0
1
Output
? 1 2 3
? 2 3 5
? 4 1 5
! 7
Input
3 2
Output
-1
Note
In the first example interaction, the array a_1, a_2, β¦, a_n is 2, 1, 7, 5, 6 and its XOR-sum is 7.
The first query made asks for indices 1,2,3, so the response is a_1 β a_2 β a_3 = 2 β 1 β 7 = 4.
The second query made asks for indices 2,3,5, so the response is a_2 β a_3 β a_5 = 1 β 7 β 6 = 0.
The third query made asks for indices 4,1,5, so the response is a_4 β a_1 β a_5 = 5 β 2 β 6 = 1. Note that the indices may be output in any order.
Additionally, even though three queries were made in the example interaction, it is just meant to demonstrate the interaction format and does not necessarily represent an optimal strategy.
In the second example interaction, there is no way to recover the XOR-sum of Little Dormi's array no matter what is queried, so the program immediately outputs -1 and exits.
### Response
```cpp
#include <bits/stdc++.h>
using ll = long long;
#define all(x) (x).begin(), (x).end()
int main() {
// std::ios_base::sync_with_stdio(false);
// std::cin.tie(nullptr);
// std::cout.tie(nullptr);
constexpr int INF = std::numeric_limits<int>::max() / 2;
int n, k;
std::cin >> n >> k;
auto ask = [&] (std::vector<int> v) {
std::cout << "?";
for (int x : v) std::cout << " " << x + 1;
std::cout << "\n";
int res;
std::cin >> res;
return res;
};
auto link = [&] (std::vector<int> a, std::vector<int> b) {
std::vector<int> v;
for (int x : a) v.emplace_back(x);
for (int x : b) v.emplace_back(x);
return v;
};
std::vector<int> pre(n + 1, 0), dis(n + 1, INF);
std::queue<int> que;
pre[0] = -1;
dis[0] = 0;
que.emplace(0);
while (!que.empty()) {
int x = que.front();
que.pop();
for (int i = 1; i <= k; ++i) {
if (i <= n - x && k - i <= x) {
int y = x + i * 2 - k;
if (dis[y] == INF) {
dis[y] = dis[x] + 1;
pre[y] = x;
que.emplace(y);
}
}
}
}
if (dis[n] == INF) {
std::cout << "-1\n";
return 0;
}
std::vector<int> t, f(n), p;
for (int i = n; ~i; i = pre[i]) p.emplace_back(i);
std::reverse(all(p));
int ans = 0;
std::iota(all(f), 0);
for (size_t i = 0; i < p.size() - 1; ++i) {
int x = (p[i + 1] - p[i] + k) / 2, y = k - x;
std::vector<int> mt, mf;
for (int j = 0; j < x; ++j) {
mt.emplace_back(f.back());
f.pop_back();
}
for (int j = 0; j < y; ++j) {
mf.emplace_back(t.back());
t.pop_back();
}
ans ^= ask(link(mt, mf));
t.insert(t.end(), all(mt));
f.insert(f.end(), all(mf));
}
std::cout << "! " << ans << "\n";
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
JATC and his friend Giraffe are currently in their room, solving some problems. Giraffe has written on the board an array a_1, a_2, ..., a_n of integers, such that 1 β€ a_1 < a_2 < β¦ < a_n β€ 10^3, and then went to the bathroom.
JATC decided to prank his friend by erasing some consecutive elements in the array. Since he doesn't want for the prank to go too far, he will only erase in a way, such that Giraffe can still restore the array using the information from the remaining elements. Because Giraffe has created the array, he's also aware that it's an increasing array and all the elements are integers in the range [1, 10^3].
JATC wonders what is the greatest number of elements he can erase?
Input
The first line of the input contains a single integer n (1 β€ n β€ 100) β the number of elements in the array.
The second line of the input contains n integers a_i (1 β€ a_1<a_2<...<a_n β€ 10^3) β the array written by Giraffe.
Output
Print a single integer β the maximum number of consecutive elements in the array that JATC can erase.
If it is impossible to erase even a single element, print 0.
Examples
Input
6
1 3 4 5 6 9
Output
2
Input
3
998 999 1000
Output
2
Input
5
1 2 3 4 5
Output
4
Note
In the first example, JATC can erase the third and fourth elements, leaving the array [1, 3, \\_, \\_, 6, 9]. As you can see, there is only one way to fill in the blanks.
In the second example, JATC can erase the second and the third elements. The array will become [998, \\_, \\_]. Because all the elements are less than or equal to 1000, the array is still can be restored. Note, that he can't erase the first 2 elements.
In the third example, JATC can erase the first 4 elements. Since all the elements are greater than or equal to 1, Giraffe can still restore the array. Note, that he can't erase the last 4 elements.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
const int MAXN = 100;
const int MINVAL = 1;
const int MAXVAL = 1000;
int n;
int a[MAXN];
int solve() {
int ret = 0, cur = 0;
for (int i = (0); i < (n); ++i) {
if (i - 1 >= 0 && a[i - 1] < a[i] - 1 || i == 0 && a[i] - 1 >= MINVAL) {
cur = 0;
continue;
}
if (i + 1 < n && a[i + 1] > a[i] + 1 || i + 1 == n && a[i] + 1 <= MAXVAL) {
cur = 0;
continue;
}
++cur;
ret = max(ret, cur);
}
return ret;
}
void run() {
scanf("%d", &n);
for (int i = (0); i < (n); ++i) scanf("%d", &a[i]);
printf("%d\n", solve());
}
int main() {
run();
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
This is the easier version of the problem. In this version, 1 β€ n β€ 10^5 and 0 β€ a_i β€ 1. You can hack this problem only if you solve and lock both problems.
Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare n boxes of chocolate, numbered from 1 to n. Initially, the i-th box contains a_i chocolate pieces.
Since Bob is a typical nice guy, he will not send Alice n empty boxes. In other words, at least one of a_1, a_2, β¦, a_n is positive. Since Alice dislikes coprime sets, she will be happy only if there exists some integer k > 1 such that the number of pieces in each box is divisible by k. Note that Alice won't mind if there exists some empty boxes.
Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box i and put it into either box i-1 or box i+1 (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of chocolate boxes.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 1) β the number of chocolate pieces in the i-th box.
It is guaranteed that at least one of a_1, a_2, β¦, a_n is positive.
Output
If there is no way for Charlie to make Alice happy, print -1.
Otherwise, print a single integer x β the minimum number of seconds for Charlie to help Bob make Alice happy.
Examples
Input
3
1 0 1
Output
2
Input
1
1
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void swap(long long &a, long long &b) {
auto tm = a;
a = b;
b = tm;
}
const long long mod = 1000000009;
const long long mod2 = 998244353;
const long long INF = (1LL << 50) - 1;
const long long N = 1e6 + 25;
bool isp(long long x) {
for (long long i = 2; i * i <= x; ++i)
if (x % i == 0) return 0;
return 1;
}
void bheja_fry() {
long long n, x;
cin >> n;
vector<long long> a;
for (long long(i) = (0); (i) < (n); ++(i)) {
cin >> x;
if (x % 2) a.push_back(i + 1);
}
vector<long long> f;
n = (long long)(a).size();
for (long long i = 2; i <= n; ++i)
if (n % i == 0) f.push_back(i);
if ((long long)(f).size() == 0) {
cout << -1;
return;
}
vector<long long> pre(n + 1);
for (long long(i) = (1); (i) < (n + 1); ++(i)) pre[i] = pre[i - 1] + a[i - 1];
long long ans = INF;
for (auto &(p) : (f)) {
long long ct = 0;
for (long long i = 0; i < n; i += p) {
long long t = abs(pre[i + p / 2] - pre[i] - (p / 2) * a[i + p / 2]);
t += abs((p / 2 + p % 2) * a[i + p / 2] - (pre[i + p] - pre[i + p / 2]));
ct += t;
}
ans = min(ct, ans);
}
cout << ans;
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long t = 1;
for (long long(i) = (1); (i) < (t + 1); ++(i)) {
bheja_fry();
if (i < t) cout << "\n";
}
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Find the number, modulo 998244353, of sequences of length N consisting of 0, 1 and 2 such that none of their contiguous subsequences totals to X.
Constraints
* 1 \leq N \leq 3000
* 1 \leq X \leq 2N
* N and X are integers.
Input
Input is given from Standard Input in the following format:
N X
Output
Print the number, modulo 998244353, of sequences that satisfy the condition.
Examples
Input
3 3
Output
14
Input
8 6
Output
1179
Input
10 1
Output
1024
Input
9 13
Output
18402
Input
314 159
Output
459765451
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 998244353LL
ll c[6010][6010];
int n,m;
inline int rd()
{
int x=0;char ch=getchar();
for (;ch<'0'||ch>'9';ch=getchar());
for (;ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0';
return x;
}
inline ll pls(const ll &x,const ll &y) { return (x+y<mod)?x+y:x+y-mod; }
inline ll mns(const ll &x,const ll &y) { return (x-y<0)?x-y+mod:x-y; }
inline ll ksm(ll x,ll y) { ll res=1;for (;y;y>>=1,x=x*x%mod) if (y&1) res=res*x%mod;return res; }
inline void pre_gao()
{
for (int i=0;i<=6000;i++)
{
c[i][0]=1;
for (int j=1;j<=i;j++) c[i][j]=pls(c[i-1][j-1],c[i-1][j]);
}
}
inline ll calc(const int &x,const int &y) { return (x<0||y<0||x>y||y>x*2)?0:c[x][y-x]; }
inline ll gao(const int &x,const int &y)
{
if (y<m) return calc(x,y);
if (y>=m*2) return ((m&1)&&y==x*2);
int hh=y-m-1;
if (hh&1) return 0;
int hhh=m+1;
int now=x-(y-hhh)/2-1-hh/2;
return calc(now-1,hhh-hh-4);
}
int main()
{
n=rd();m=rd();pre_gao();
ll ans=0;
for (int i=0;i<=n;i++) for (int j=i;j<=i*2;j++) ans=pls(ans,gao(i,j)*c[n][i]%mod);
printf("%lld\n",ans);
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Ivan places knights on infinite chessboard. Initially there are n knights. If there is free cell which is under attack of at least 4 knights then he places new knight in this cell. Ivan repeats this until there are no such free cells. One can prove that this process is finite. One can also prove that position in the end does not depend on the order in which new knights are placed.
Ivan asked you to find initial placement of exactly n knights such that in the end there will be at least β \frac{n^{2}}{10} β knights.
Input
The only line of input contains one integer n (1 β€ n β€ 10^{3}) β number of knights in the initial placement.
Output
Print n lines. Each line should contain 2 numbers x_{i} and y_{i} (-10^{9} β€ x_{i}, y_{i} β€ 10^{9}) β coordinates of i-th knight. For all i β j, (x_{i}, y_{i}) β (x_{j}, y_{j}) should hold. In other words, all knights should be in different cells.
It is guaranteed that the solution exists.
Examples
Input
4
Output
1 1
3 1
1 5
4 4
Input
7
Output
2 1
1 2
4 1
5 2
2 6
5 7
6 6
Note
Let's look at second example:
<image>
Green zeroes are initial knights. Cell (3, 3) is under attack of 4 knights in cells (1, 2), (2, 1), (4, 1) and (5, 2), therefore Ivan will place a knight in this cell. Cell (4, 5) is initially attacked by only 3 knights in cells (2, 6), (5, 7) and (6, 6). But new knight in cell (3, 3) also attacks cell (4, 5), now it is attacked by 4 knights and Ivan will place another knight in this cell. There are no more free cells which are attacked by 4 or more knights, so the process stops. There are 9 knights in the end, which is not less than β \frac{7^{2}}{10} β = 4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline bool ckmin(T &a, const T &b) {
return b < a ? a = b, 1 : 0;
}
template <typename T>
inline bool ckmax(T &a, const T &b) {
return a < b ? a = b, 1 : 0;
}
const int inf = 1e9;
map<pair<int, int>, int> vis, used, str;
set<pair<int, int> > crd;
int n;
int dx[] = {1, 2, 2, 1, -1, -2, -2, -1}, dy[] = {-2, -1, 1, 2, 2, 1, -1, -2};
int check(vector<pair<int, int> > cd) {
used.clear(), str.clear();
for (int i = (0), _x = ((int)(cd).size() - 1); i <= _x; i++) str[cd[i]] = 1;
vis.clear(), crd.clear();
for (int i = (0), _x = ((int)(cd).size() - 1); i <= _x; i++)
vis[cd[i]] = 4, crd.insert(cd[i]);
int ans = 0;
int mnx = inf, mxx = -inf, mxy = -inf, mny = inf;
while (!crd.empty()) {
pair<int, int> u = *crd.begin();
used[u] = 1;
ckmin(mnx, u.first), ckmin(mny, u.second), ckmax(mxx, u.first),
ckmax(mxy, u.second);
ans++;
vis[u] = -inf;
crd.erase(crd.begin());
for (int i = 0; i < 8; i++) {
pair<int, int> v = u;
v.first += dx[i], v.second += dy[i];
vis[v]++;
if (vis[v] >= 4) crd.insert(v);
}
}
return ans;
}
vector<pair<int, int> > corn(int n) {
vector<pair<int, int> > id;
for (int i = (1), _x = (n / 2); i <= _x; i++) id.push_back(make_pair(i, 0));
n -= n / 2;
for (int i = (1), _x = (n); i <= _x; i++) id.push_back(make_pair(i, 1));
return id;
}
vector<pair<int, int> > test(int h) {
vector<pair<int, int> > id;
id.clear();
int m = h / 2;
for (int i = (1), _x = (m); i <= _x; i++) id.push_back(make_pair(i, 0));
for (int i = (1), _x = (h - m); i <= _x; i++) id.push_back(make_pair(i, 1));
int k = n - h, mdr = (m + 1) / 2, mdl = (h - m + 1) / 2;
int R = m / 4 - (m % 4 == 0), L = (h - m) / 4 - ((h - m) % 4 == 0);
if (k / 2 > 1) {
for (int i = (-R - k / 2), _x = (-R - 1); i <= _x; i++)
id.push_back(make_pair(mdr, i));
k -= k / 2;
}
for (int i = (L + 2), _x = (L + k + 1); i <= _x; i++)
id.push_back(make_pair(mdl, i));
return id;
}
void quit(vector<pair<int, int> > id) {
assert((int)(id).size() == n);
assert(check(id) >= n * n / 10);
for (int i = (0), _x = ((int)(id).size() - 1); i <= _x; i++)
printf("%d %d\n", id[i].first, id[i].second);
exit(0);
}
int main() {
scanf("%d", &n);
vector<pair<int, int> > id;
if (n <= 14) quit(corn(n));
if (n <= 50) {
int mx = 0;
vector<pair<int, int> > id;
for (int i = (1), _x = (n); i <= _x; i++) {
vector<pair<int, int> > tmp = test(i);
int t = check(tmp);
if (t > mx) mx = t, id = tmp;
}
quit(id);
}
int m = n * 4 / 5;
quit(test(m));
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!
She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.
Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si β ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.
Input
The first line contains an integer n (1 β€ n β€ 100): number of names.
Each of the following n lines contain one string namei (1 β€ |namei| β€ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.
Output
If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).
Otherwise output a single word "Impossible" (without quotes).
Examples
Input
3
rivest
shamir
adleman
Output
bcdefghijklmnopqrsatuvwxyz
Input
10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer
Output
Impossible
Input
10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever
Output
aghjlnopefikdmbcqrstuvwxyz
Input
7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck
Output
acbdefhijklmnogpqrstuvwxyz
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<int> top;
bool b = 1;
vector<int> G[26];
vector<int> vis(26, 0);
void dfs(int i) {
vis[i] = 1;
for (int u : G[i]) {
if (vis[u] == 1) {
b = 0;
return;
} else if (vis[u] == 0) {
dfs(u);
}
}
vis[i] = 2;
top.push_back(i);
}
int main() {
int n;
string s1, s2;
cin >> n;
cin >> s1;
for (int i = 1; i < n; i++) {
cin >> s2;
int j = 0;
while (j < (int)min(s1.size(), s2.size()) && s1[j] == s2[j]) j++;
if (j == (int)min(s1.size(), s2.size())) {
if (s1.size() > s2.size()) b = 0;
swap(s1, s2);
continue;
}
G[s1[j] - 'a'].push_back(s2[j] - 'a');
swap(s1, s2);
}
if (!b) {
cout << "Impossible\n";
return 0;
}
for (int i = 0; i < 26; i++) {
if (vis[i]) continue;
dfs(i);
if (!b) {
cout << "Impossible\n";
return 0;
}
}
reverse(top.begin(), top.end());
for (int u : top) {
char ch = 'a' + u;
cout << ch;
}
cout << '\n';
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
There are n students in a school class, the rating of the i-th student on Codehorses is a_i. You have to form a team consisting of k students (1 β€ k β€ n) such that the ratings of all team members are distinct.
If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then print k distinct numbers which should be the indices of students in the team you form. If there are multiple answers, print any of them.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 100) β the number of students and the size of the team you have to form.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 100), where a_i is the rating of i-th student.
Output
If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then print k distinct integers from 1 to n which should be the indices of students in the team you form. All the ratings of the students in the team should be distinct. You may print the indices in any order. If there are multiple answers, print any of them.
Assume that the students are numbered from 1 to n.
Examples
Input
5 3
15 13 15 15 12
Output
YES
1 2 5
Input
5 4
15 13 15 15 12
Output
NO
Input
4 4
20 10 40 30
Output
YES
1 2 3 4
Note
All possible answers for the first example:
* {1 2 5}
* {2 3 5}
* {2 4 5}
Note that the order does not matter.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
int b[101] = {0};
int d[101] = {0};
cin >> n >> k;
int c[n + 1];
int aa[k];
int hey = 0;
for (int i = 1; i <= n; i++) {
cin >> c[i];
b[c[i]]++;
d[c[i]] = i;
}
int count = 0;
for (int i = 1; i <= 100; i++) {
if (b[i] > 0) count++;
}
if (count >= k) {
cout << "YES" << endl;
for (int i = 1; i <= 100; i++) {
if (b[i] > 0) {
aa[hey] = d[i];
hey++;
}
}
sort(aa, aa + k);
for (int i = 0; i < k; i++) cout << aa[i] << " ";
cout << endl;
} else
cout << "NO" << endl;
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5Β·i minutes to solve the i-th problem.
Limak's friends organize a New Year's Eve party and Limak wants to be there at midnight or earlier. He needs k minutes to get there from his house, where he will participate in the contest first.
How many problems can Limak solve if he wants to make it to the party?
Input
The only line of the input contains two integers n and k (1 β€ n β€ 10, 1 β€ k β€ 240) β the number of the problems in the contest and the number of minutes Limak needs to get to the party from his house.
Output
Print one integer, denoting the maximum possible number of problems Limak can solve so that he could get to the party at midnight or earlier.
Examples
Input
3 222
Output
2
Input
4 190
Output
4
Input
7 1
Output
7
Note
In the first sample, there are 3 problems and Limak needs 222 minutes to get to the party. The three problems require 5, 10 and 15 minutes respectively. Limak can spend 5 + 10 = 15 minutes to solve first two problems. Then, at 20:15 he can leave his house to get to the party at 23:57 (after 222 minutes). In this scenario Limak would solve 2 problems. He doesn't have enough time to solve 3 problems so the answer is 2.
In the second sample, Limak can solve all 4 problems in 5 + 10 + 15 + 20 = 50 minutes. At 20:50 he will leave the house and go to the party. He will get there exactly at midnight.
In the third sample, Limak needs only 1 minute to get to the party. He has enough time to solve all 7 problems.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int i;
int n, k;
cin >> n >> k;
int minutes = 4 * 60 - k;
for (i = 1; i <= n; i++) {
int solve = i * 5;
if (minutes >= solve) {
minutes -= solve;
} else
break;
}
cout << i - 1 << endl;
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Consider a sequence of digits of length 2^k [a_1, a_2, β¦, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0β€ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}β₯ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.
Less formally, we partition sequence of length 2^k into 2^{k-1} pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth β¦, the last pair consists of the (2^k-1)-th and (2^k)-th numbers. For every pair such that sum of numbers in it is at least 10, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by 10 (and don't change the order of the numbers).
Perform this operation with a resulting array until it becomes of length 1. Let f([a_1, a_2, β¦, a_{2^k}]) denote the number of candies we get in this process.
For example: if the starting sequence is [8, 7, 3, 1, 7, 0, 9, 4] then:
After the first operation the sequence becomes [(8 + 7)mod 10, (3 + 1)mod 10, (7 + 0)mod 10, (9 + 4)mod 10] = [5, 4, 7, 3], and we get 2 candies as 8 + 7 β₯ 10 and 9 + 4 β₯ 10.
After the second operation the sequence becomes [(5 + 4)mod 10, (7 + 3)mod 10] = [9, 0], and we get one more candy as 7 + 3 β₯ 10.
After the final operation sequence becomes [(9 + 0) mod 10] = [9].
Therefore, f([8, 7, 3, 1, 7, 0, 9, 4]) = 3 as we got 3 candies in total.
You are given a sequence of digits of length n s_1, s_2, β¦ s_n. You have to answer q queries of the form (l_i, r_i), where for i-th query you have to output f([s_{l_i}, s_{l_i+1}, β¦, s_{r_i}]). It is guaranteed that r_i-l_i+1 is of form 2^k for some nonnegative integer k.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the length of the sequence.
The second line contains n digits s_1, s_2, β¦, s_n (0 β€ s_i β€ 9).
The third line contains a single integer q (1 β€ q β€ 10^5) β the number of queries.
Each of the next q lines contains two integers l_i, r_i (1 β€ l_i β€ r_i β€ n) β i-th query. It is guaranteed that r_i-l_i+1 is a nonnegative integer power of 2.
Output
Output q lines, in i-th line output single integer β f([s_{l_i}, s_{l_i + 1}, β¦, s_{r_i}]), answer to the i-th query.
Examples
Input
8
8 7 3 1 7 0 9 4
3
1 8
2 5
7 7
Output
3
1
0
Input
6
0 1 2 3 3 5
3
1 2
1 4
3 6
Output
0
0
1
Note
The first example illustrates an example from the statement.
f([7, 3, 1, 7]) = 1: sequence of operations is [7, 3, 1, 7] β [(7 + 3)mod 10, (1 + 7)mod 10] = [0, 8] and one candy as 7 + 3 β₯ 10 β [(0 + 8) mod 10] = [8], so we get only 1 candy.
f([9]) = 0 as we don't perform operations with it.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 314;
const int INF = 1e9;
const double PI = acos(-1);
const int MOD = 1e9 + 7;
const double eps = 1e-9;
int d[N], sum[N];
void solve() {
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> d[i];
}
sum[0] = d[0];
for (int i = 1; i < n; ++i) {
sum[i] = sum[i - 1] + d[i];
}
int q;
cin >> q;
while (q--) {
int l, r;
cin >> l >> r;
l--, r--;
cout << (sum[r] - sum[l] + d[l]) / 10 << "\n";
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t = 1;
while (t--) solve();
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
This is the hard version of the problem. You can find the easy version in the Div. 2 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.
This is an interactive problem.
You're considering moving to another city, where one of your friends already lives. There are n cafΓ©s in this city, where n is a power of two. The i-th cafΓ© produces a single variety of coffee a_i.
As you're a coffee-lover, before deciding to move or not, you want to know the number d of distinct varieties of coffees produced in this city.
You don't know the values a_1, β¦, a_n. Fortunately, your friend has a memory of size k, where k is a power of two.
Once per day, you can ask him to taste a cup of coffee produced by the cafΓ© c, and he will tell you if he tasted a similar coffee during the last k days.
You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30\ 000 times.
More formally, the memory of your friend is a queue S. Doing a query on cafΓ© c will:
* Tell you if a_c is in S;
* Add a_c at the back of S;
* If |S| > k, pop the front element of S.
Doing a reset request will pop all elements out of S.
Your friend can taste at most (3n^2)/(2k) cups of coffee in total. Find the diversity d (number of distinct values in the array a).
Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.
In some test cases the behavior of the interactor is adaptive. It means that the array a may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array a consistent with all the answers given so far.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 1024, k and n are powers of two).
It is guaranteed that (3n^2)/(2k) β€ 15\ 000.
Interaction
You begin the interaction by reading n and k.
* To ask your friend to taste a cup of coffee produced by the cafΓ© c, in a separate line output
? c
Where c must satisfy 1 β€ c β€ n. Don't forget to flush, to get the answer.
In response, you will receive a single letter Y (yes) or N (no), telling you if variety a_c is one of the last k varieties of coffee in his memory.
* To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30\ 000 times.
* When you determine the number d of different coffee varieties, output
! d
In case your query is invalid, you asked more than (3n^2)/(2k) queries of type ? or you asked more than 30\ 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.
After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Hack format
The first line should contain the word fixed
The second line should contain two integers n and k, separated by space (1 β€ k β€ n β€ 1024, k and n are powers of two).
It must hold that (3n^2)/(2k) β€ 15\ 000.
The third line should contain n integers a_1, a_2, β¦, a_n, separated by spaces (1 β€ a_i β€ n).
Examples
Input
4 2
N
N
Y
N
N
N
N
Output
? 1
? 2
? 3
? 4
R
? 4
? 1
? 2
! 3
Input
8 8
N
N
N
N
Y
Y
Output
? 2
? 6
? 4
? 5
? 2
? 5
! 6
Note
In the first example, the array is a = [1, 4, 1, 3]. The city produces 3 different varieties of coffee (1, 3 and 4).
The successive varieties of coffee tasted by your friend are 1, 4, 1, 3, 3, 1, 4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.
In the second example, the array is a = [1, 2, 3, 4, 5, 6, 6, 6]. The city produces 6 different varieties of coffee.
The successive varieties of coffee tasted by your friend are 2, 6, 4, 5, 2, 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 30006;
int n, k;
int good[maxn];
void reset() { cout << "R" << endl; }
bool query(int x) {
cout << "? " << x + 1 << endl;
cout.flush();
string s;
cin >> s;
if (s[0] == 'Y') return true;
return false;
}
int main() {
cin >> n >> k;
fill(good, good + n, 1);
if (k <= 2) {
for (int d = 1; d < n; ++d) {
for (int start = 0; start < d; ++start) {
if (start + d >= n) continue;
for (int i = 0; start + d * i < n; ++i) {
if (query(start + d * i)) good[start + d * i] = 0;
}
reset();
}
}
} else {
int nElem = k / 2;
int nBlock = 2 * n / k;
for (int d = 1; d < nBlock; ++d) {
for (int start = 0; start < d; ++start) {
if (start + d >= nBlock) continue;
for (int i = 0; start + d * i < nBlock; ++i) {
int cur = start + d * i;
for (int index = cur * nElem; index < (cur + 1) * nElem; ++index) {
if (query(index)) good[index] = 0;
}
}
reset();
}
}
}
int ans = 0;
for (int i = 0; i < n; ++i)
if (good[i]) ++ans;
cout << "! " << ans << endl;
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Bob is an active user of the social network Faithbug. On this network, people are able to engage in a mutual friendship. That is, if a is a friend of b, then b is also a friend of a. Each user thus has a non-negative amount of friends.
This morning, somebody anonymously sent Bob the following link: [graph realization problem](https://en.wikipedia.org/wiki/Graph_realization_problem) and Bob wants to know who that was. In order to do that, he first needs to know how the social network looks like. He investigated the profile of every other person on the network and noted down the number of his friends. However, he neglected to note down the number of his friends. Help him find out how many friends he has. Since there may be many possible answers, print all of them.
Input
The first line contains one integer n (1 β€ n β€ 5 β
10^5), the number of people on the network excluding Bob.
The second line contains n numbers a_1,a_2, ..., a_n (0 β€ a_i β€ n), with a_i being the number of people that person i is a friend of.
Output
Print all possible values of a_{n+1} β the amount of people that Bob can be friend of, in increasing order.
If no solution exists, output -1.
Examples
Input
3
3 3 3
Output
3
Input
4
1 1 1 1
Output
0 2 4
Input
2
0 2
Output
-1
Input
35
21 26 18 4 28 2 15 13 16 25 6 32 11 5 31 17 9 3 24 33 14 27 29 1 20 4 12 7 10 30 34 8 19 23 22
Output
13 15 17 19 21
Note
In the first test case, the only solution is that everyone is friends with everyone. That is why Bob should have 3 friends.
In the second test case, there are three possible solutions (apart from symmetries):
* a is friend of b, c is friend of d, and Bob has no friends, or
* a is a friend of b and both c and d are friends with Bob, or
* Bob is friends of everyone.
The third case is impossible to solve, as the second person needs to be a friend with everybody, but the first one is a complete stranger.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int Maxn = 2100000;
int n, d[Maxn], bj[Maxn], ans[Maxn], num;
long long pre[Maxn];
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &d[i]);
sort(d, d + n);
for (int i = 1; i <= n; i++) pre[i] = pre[i - 1] + d[i - 1];
int j = 0;
for (int k = 1; k <= n; k++) {
long long l = pre[n] - pre[n - k], r = (long long)k * (k - 1);
while (j < n && d[j] < k) j++;
r += pre[min(j, n - k)] + 1ll * max(0, n - k - j) * k;
long long now = d[n - k], diff = l - r;
if (diff <= k && diff <= now) {
bj[max(diff, 0ll)]++;
bj[now + 1]--;
}
l -= d[n - k], r += min(d[n - k], k);
diff = r - l;
if (diff >= now + 1) {
bj[now + 1]++;
bj[min(diff + 1, (long long)n + 1)]--;
}
}
j = 0;
for (int i = 0; i <= n; i++) {
j += bj[i];
if (j == n && (pre[n] + i & 1) == 0) ans[++num] = i;
}
if (num == 0)
puts("-1");
else
for (int i = 1; i <= num; i++) printf("%d ", ans[i]);
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Princess Twilight went to Celestia and Luna's old castle to research the chest from the Elements of Harmony.
<image>
A sequence of positive integers bi is harmony if and only if for every two elements of the sequence their greatest common divisor equals 1. According to an ancient book, the key of the chest is a harmony sequence bi which minimizes the following expression:
<image>
You are given sequence ai, help Princess Twilight to find the key.
Input
The first line contains an integer n (1 β€ n β€ 100) β the number of elements of the sequences a and b. The next line contains n integers a1, a2, ..., an (1 β€ ai β€ 30).
Output
Output the key β sequence bi that minimizes the sum described above. If there are multiple optimal sequences, you can output any of them.
Examples
Input
5
1 1 1 1 1
Output
1 1 1 1 1
Input
5
1 6 4 2 8
Output
1 5 3 1 8
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <class T, class T2>
inline void chkmax(T &x, const T2 &y) {
if (x < y) x = y;
}
template <class T, class T2>
inline void chkmin(T &x, const T2 &y) {
if (x > y) x = y;
}
const int MAXN = (117);
const int MAXV = 70;
vector<int> pr = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53};
int n, a[MAXN];
void read() {
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i];
}
int msk[MAXN];
int dp[MAXN][1 << 16];
int rec(int pos, int mask) {
if (pos == n) return 0;
int &memo = dp[pos][mask];
if (memo != -1) return memo;
memo = (int)1e9 + 42;
for (int v = 1; v <= MAXV; v++)
if ((mask & msk[v]) == 0)
chkmin(memo, abs(a[pos] - v) + rec(pos + 1, mask | msk[v]));
return memo;
}
void solve() {
memset(dp, -1, sizeof(dp));
for (int i = 1; i <= MAXV; i++)
for (int j = 0; j < 16; j++)
if (i % pr[j] == 0) msk[i] |= (1 << j);
int mask = 0;
for (int i = 0; i < n; i++) {
for (int v = 1; v <= MAXV; v++)
if (((mask & msk[v]) == 0) &&
rec(i, mask) == abs(a[i] - v) + rec(i + 1, mask | msk[v])) {
mask |= msk[v];
cout << v << " ";
break;
}
}
cout << '\n';
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
read();
solve();
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1, p2, ..., pn.
Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k distinct elements.
Input
The single line of the input contains two space-separated positive integers n, k (1 β€ k < n β€ 105).
Output
Print n integers forming the permutation. If there are multiple answers, print any of them.
Examples
Input
3 2
Output
1 3 2
Input
3 1
Output
1 2 3
Input
5 2
Output
1 3 2 4 5
Note
By |x| we denote the absolute value of number x.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int mas[100500];
int main() {
int n, k, p = 1, t;
bool cur = false;
char q;
string s = "", s1;
cin >> n >> k;
mas[1] = 1;
for (int i = 2; i <= n; i++) {
if (p < k) {
if (!cur)
mas[i] = n - mas[i - 1] + 1;
else
mas[i] = mas[i - 2] + 1;
if (!cur)
cur = true;
else
cur = false;
p++;
} else {
if (!cur) {
mas[i] = mas[i - 1] + 1;
} else {
mas[i] = mas[i - 1] - 1;
}
}
}
for (int i = 1; i <= n; i++) {
s1 = "";
while (mas[i] > 0) {
q = mas[i] % 10 + '0';
mas[i] /= 10;
s1 = q + s1;
}
s += s1 + ' ';
}
cout << s;
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Recently, Tokitsukaze found an interesting game. Tokitsukaze had n items at the beginning of this game. However, she thought there were too many items, so now she wants to discard m (1 β€ m β€ n) special items of them.
These n items are marked with indices from 1 to n. In the beginning, the item with index i is placed on the i-th position. Items are divided into several pages orderly, such that each page contains exactly k positions and the last positions on the last page may be left empty.
Tokitsukaze would do the following operation: focus on the first special page that contains at least one special item, and at one time, Tokitsukaze would discard all special items on this page. After an item is discarded or moved, its old position would be empty, and then the item below it, if exists, would move up to this empty position. The movement may bring many items forward and even into previous pages, so Tokitsukaze would keep waiting until all the items stop moving, and then do the operation (i.e. check the special page and discard the special items) repeatedly until there is no item need to be discarded.
<image> Consider the first example from the statement: n=10, m=4, k=5, p=[3, 5, 7, 10]. The are two pages. Initially, the first page is special (since it is the first page containing a special item). So Tokitsukaze discards the special items with indices 3 and 5. After, the first page remains to be special. It contains [1, 2, 4, 6, 7], Tokitsukaze discards the special item with index 7. After, the second page is special (since it is the first page containing a special item). It contains [9, 10], Tokitsukaze discards the special item with index 10.
Tokitsukaze wants to know the number of operations she would do in total.
Input
The first line contains three integers n, m and k (1 β€ n β€ 10^{18}, 1 β€ m β€ 10^5, 1 β€ m, k β€ n) β the number of items, the number of special items to be discarded and the number of positions in each page.
The second line contains m distinct integers p_1, p_2, β¦, p_m (1 β€ p_1 < p_2 < β¦ < p_m β€ n) β the indices of special items which should be discarded.
Output
Print a single integer β the number of operations that Tokitsukaze would do in total.
Examples
Input
10 4 5
3 5 7 10
Output
3
Input
13 4 5
7 8 9 10
Output
1
Note
For the first example:
* In the first operation, Tokitsukaze would focus on the first page [1, 2, 3, 4, 5] and discard items with indices 3 and 5;
* In the second operation, Tokitsukaze would focus on the first page [1, 2, 4, 6, 7] and discard item with index 7;
* In the third operation, Tokitsukaze would focus on the second page [9, 10] and discard item with index 10.
For the second example, Tokitsukaze would focus on the second page [6, 7, 8, 9, 10] and discard all special items at once.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const long long LINF = 0x3f3f3f3f3f3f3f3f;
const int MOD = 1e9 + 7;
template <typename S, typename T>
inline bool Min(S &a, const T &b) {
return a > b ? a = b, true : false;
}
template <typename S, typename T>
inline bool Max(S &a, const T &b) {
return a < b ? a = b, true : false;
}
template <typename S, typename T>
inline void Adm(S &a, const T &b) {
a = (a + b) % MOD;
if (a < 0) a += MOD;
}
template <typename S, typename T>
inline void Mum(S &a, const T &b) {
a = 1LL * a * b % MOD;
}
inline long long Mum(initializer_list<long long> ls) {
long long a = 1;
for (long long b : ls) a = a * b % MOD;
return a;
}
const int N = 1e5 + 100;
long long a[N];
int main() {
long long n, m, k;
cin >> n >> m >> k;
for (int i = 1; i <= m; ++i) scanf("%lld", &a[i]);
int p = 1, ans = 0;
long long q = k;
while (p <= m) {
int cnt = 0;
while (p <= m && a[p] <= q) ++p, ++cnt;
if (cnt)
q += cnt, ++ans;
else
q += (a[p] - q + k - 1) / k * k;
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
A convex polygon consisting of N vertices is given. The coordinates of each vertex are represented counterclockwise by (X1, Y1), (X2, Y2), β¦β¦, (XN, YN). No matter what straight line passes through the point P, find the coordinates of the point P so that the areas of the two convex polygons obtained after cutting are equal.
Constraints
* All inputs are integers
* 3 β€ N β€ 50
* 0 β€ | Xi |, | Yi | β€ 1000000
* The input polygon is a simple convex polygon.
* The output must satisfy max (| X-cX |, | Y-cY |) β€ 0.0001 when the output coordinates are (X, Y) and the exact solution is (cX, cY).
Input
The input is given in the following format.
> N
> X1 Y1
> X2 Y2
> β¦β¦
> XN YN
>
Output
If there is a point that satisfies the condition of the problem statement, the coordinates of that point
> X Y
>
Output in the format of. If the point does not exist, output "NA" on one line.
Examples
Input
4
100 100
0 100
0 0
100 0
Output
50.00000 50.00000
Input
3
100 100
0 100
0 0
Output
NA
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef pair<double,double> P;
int main(){
int n;cin>>n;
vector<P> v(n);
for(int i=0;i<n;i++){
double x,y;cin>>x>>y;
v[i]=P(x,y);
}
double cx,cy,ma=-1;
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
double x1=v[i].first,y1=v[i].second,x2=v[j].first,y2=v[j].second;
double tmp=(x2-x1)*(x2-x1)+(y2-y1)*(y2-y1);
if(tmp>ma){
ma=tmp;
cx=(x1+x2)/2;cy=(y1+y2)/2;
}
}
}
bool flag=true;
for(int i=0;i<n;i++){
double x1=v[i].first,y1=v[i].second;
bool ftmp=false;
for(int j=0;j<n;j++){
double x2=v[j].first,y2=v[j].second;
if(cx==(x1+x2)/2 && cy==(y1+y2)/2) ftmp=true;
}
flag&=ftmp;
}
if(flag)cout<<fixed<<setprecision(10)<<cx<<" "<<cy<<endl;
else cout<<"NA"<<endl;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
12:17 (UTC): The sample input 1 and 2 were swapped. The error is now fixed. We are very sorry for your inconvenience.
There are N children in AtCoder Kindergarten, conveniently numbered 1 through N. Mr. Evi will distribute C indistinguishable candies to the children.
If child i is given a candies, the child's happiness will become x_i^a, where x_i is the child's excitement level. The activity level of the kindergarten is the product of the happiness of all the N children.
For each possible way to distribute C candies to the children by giving zero or more candies to each child, calculate the activity level of the kindergarten. Then, calculate the sum over all possible way to distribute C candies. This sum can be seen as a function of the children's excitement levels x_1,..,x_N, thus we call it f(x_1,..,x_N).
You are given integers A_i,B_i (1β¦iβ¦N). Find <image> modulo 10^9+7.
Constraints
* 1β¦Nβ¦400
* 1β¦Cβ¦400
* 1β¦A_iβ¦B_iβ¦400 (1β¦iβ¦N)
Input
The input is given from Standard Input in the following format:
N C
A_1 A_2 ... A_N
B_1 B_2 ... B_N
Output
Print the value of <image> modulo 10^9+7.
Examples
Input
2 3
1 1
1 1
Output
4
Input
1 2
1
3
Output
14
Input
2 3
1 1
2 2
Output
66
Input
4 8
3 1 4 1
3 1 4 1
Output
421749
Input
3 100
7 6 5
9 9 9
Output
139123417
### Response
```cpp
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int mod = 1e9 + 7;
int f[405][405], a[405][405], l[405], r[405], n, c, b[405][405], ans;
inline int read()
{
char ch; int res;
while (ch = getchar(), ch < '0' || ch > '9');
res = ch - 48;
while (ch = getchar(), ch >= '0' && ch <= '9')
res = res * 10 + ch - 48;
return res;
}
int main()
{
// freopen("candy.in", "r", stdin);
// freopen("candy.out", "w", stdout);
int i, j, k;
n = read(); c = read();
for (i = 1; i <= n; i++) l[i] = read();
for (i = 1; i <= n; i++) r[i] = read();
for (i = 1; i <= n; i++)
for (int x = l[i]; x <= r[i]; x++)
{
int y = 1;
for (j = 0; j <= c; j++)
{
a[i][j] = (a[i][j] + y) % mod;
y = 1ll * y * x % mod;
}
}
f[0][0] = 1;
for (i = 1; i <= n; i++)
for (j = 0; j <= c; j++)
for (k = 0; k <= j; k++)
f[i][j] = (f[i][j] + 1ll * f[i - 1][k] * a[i][j - k]) % mod;
cout << f[n][c] << endl;
fclose(stdin);
fclose(stdout);
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.
Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.
Substring is a continuous subsequence of a string.
Input
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
Output
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
Examples
Input
intellect
tell
Output
1
Input
google
apple
Output
0
Input
sirisiri
sir
Output
2
Note
In the first sample AI's name may be replaced with "int#llect".
In the second sample Gogol can just keep things as they are.
In the third sample one of the new possible names of AI may be "s#ris#ri".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string a, b;
char c;
a = "";
int ans = 0;
while ((c = getchar()) != '\n') a += c;
cin >> b;
for (int i = 0; i < a.size(); ++i) {
int n = b.size();
if (a.substr(i, n) == b) {
ans++;
i += n - 1;
}
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
One day Ms Swan bought an orange in a shop. The orange consisted of nΒ·k segments, numbered with integers from 1 to nΒ·k.
There were k children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote the number of the segment that he would like to get: the i-th (1 β€ i β€ k) child wrote the number ai (1 β€ ai β€ nΒ·k). All numbers ai accidentally turned out to be different.
Now the children wonder, how to divide the orange so as to meet these conditions:
* each child gets exactly n orange segments;
* the i-th child gets the segment with number ai for sure;
* no segment goes to two children simultaneously.
Help the children, divide the orange and fulfill the requirements, described above.
Input
The first line contains two integers n, k (1 β€ n, k β€ 30). The second line contains k space-separated integers a1, a2, ..., ak (1 β€ ai β€ nΒ·k), where ai is the number of the orange segment that the i-th child would like to get.
It is guaranteed that all numbers ai are distinct.
Output
Print exactly nΒ·k distinct integers. The first n integers represent the indexes of the segments the first child will get, the second n integers represent the indexes of the segments the second child will get, and so on. Separate the printed numbers with whitespaces.
You can print a child's segment indexes in any order. It is guaranteed that the answer always exists. If there are multiple correct answers, print any of them.
Examples
Input
2 2
4 1
Output
2 4
1 3
Input
3 1
2
Output
3 2 1
### Response
```cpp
#include <bits/stdc++.h>
int a[1000], f[1000];
int main() {
int n, k, i, j;
while (scanf("%d%d", &n, &k) != EOF) {
memset(f, 0, sizeof(f));
for (i = 0; i < k; i++) {
scanf("%d", &a[i]);
f[a[i]] = 1;
}
j = 1;
for (i = 0; i < k; i++) {
int num = n - 1;
printf("%d", a[i]);
while (num--) {
if (f[j])
num++;
else {
f[j] = 1;
printf(" %d", j);
}
j++;
}
printf("\n");
}
}
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.)
You have completed many programming projects. In fact, there are exactly n types of programming projects, and you have completed a_i projects of type i. Your rΓ©sumΓ© has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired.
You want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired:
$$$ f(b_1,β¦,b_n)=β_{i=1}^n b_i(a_i-b_i^2). $$$
Here, b_i denotes the number of projects of type i you include in your rΓ©sumΓ©. Of course, you cannot include more projects than you have completed, so you require 0β€ b_i β€ a_i for all i.
Your rΓ©sumΓ© only has enough room for k projects, and you will absolutely not be hired if your rΓ©sumΓ© has empty space, so you require β_{i=1}^n b_i=k.
Find values for b_1,β¦, b_n that maximize the value of f(b_1,β¦,b_n) while satisfying the above two constraints.
Input
The first line contains two integers n and k (1β€ nβ€ 10^5, 1β€ kβ€ β_{i=1}^n a_i) β the number of types of programming projects and the rΓ©sumΓ© size, respectively.
The next line contains n integers a_1,β¦,a_n (1β€ a_iβ€ 10^9) β a_i is equal to the number of completed projects of type i.
Output
In a single line, output n integers b_1,β¦, b_n that achieve the maximum value of f(b_1,β¦,b_n), while satisfying the requirements 0β€ b_iβ€ a_i and β_{i=1}^n b_i=k. If there are multiple solutions, output any.
Note that you do not have to output the value f(b_1,β¦,b_n).
Examples
Input
10 32
1 2 3 4 5 5 5 5 5 5
Output
1 2 3 3 3 4 4 4 4 4
Input
5 8
4 4 8 2 1
Output
2 2 2 1 1
Note
For the first test, the optimal answer is f=-269. Note that a larger f value is possible if we ignored the constraint β_{i=1}^n b_i=k.
For the second test, the optimal answer is f=9.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <class T>
bool umin(T& a, const T& b) {
return a > b ? a = b, true : false;
}
template <class T>
bool umax(T& a, const T& b) {
return a < b ? a = b, true : false;
}
template <long long sz>
using tut = array<long long, sz>;
void usaco(string s) {
freopen((s + ".in").c_str(), "r", stdin);
freopen((s + ".out").c_str(), "w", stdout);
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
const long long N = 2e5 + 5;
const long long mod = (119 << 23) + 1;
const long long inf = LLONG_MAX;
const long double Pi = acos(-1);
void add(long long& a, long long b, long long mod = ::mod) {
a = (a + b) % mod;
}
void sub(long long& a, long long b, long long mod = ::mod) {
a = ((a - b) % mod + mod) % mod;
}
void mul(long long& a, long long b, long long mod = ::mod) {
a = (a * 1ll * b) % mod;
}
long long n, m, k, t, q, ans, res, a[N];
long long rr[N];
void solve(long long t_case) {
cin >> n >> k;
for (long long i = 1; i <= n; i++) {
cin >> a[i];
}
auto check2 = [&](long long b, long long a) -> long long {
return (a - 3ll * b * b - 3ll * b - 1);
};
auto check = [&](long long mm) -> bool {
long long cnt = 0;
for (long long i = 1; i <= n; i++) {
long long l = 0, r = a[i];
while (l < r) {
long long m = (l + r + 1) >> 1;
if (check2(m, a[i]) >= mm)
l = m;
else
r = m - 1;
}
rr[i] = l;
cnt += l;
}
return (cnt >= k);
};
long long l = -inf, r = inf;
while (l < r) {
long long m = (l + r + 1) >> 1;
if (check(m))
l = m;
else
r = m - 1;
}
check(l);
long long cnt = 0;
for (long long i = 1; i <= n; i++) cnt += rr[i];
cnt -= k;
for (long long i = 1; i <= n && cnt; i++) {
if (rr[i] && check2(rr[i], a[i]) == l) cnt--, rr[i]--;
}
for (long long i = 1; i <= n; i++) cout << rr[i] << " ";
cout << "\n";
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
if (0) {
long long t;
cin >> t;
for (long long t_case = 1; t_case <= t; t_case++) solve(t_case);
} else
solve(1);
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
You are given N points in the xy-plane. You have a circle of radius one and move it on the xy-plane, so as to enclose as many of the points as possible. Find how many points can be simultaneously enclosed at the maximum. A point is considered enclosed by a circle when it is inside or on the circle.
<image>
Fig 1. Circle and Points
Input
The input consists of a series of data sets, followed by a single line only containing a single character '0', which indicates the end of the input. Each data set begins with a line containing an integer N, which indicates the number of points in the data set. It is followed by N lines describing the coordinates of the points. Each of the N lines has two decimal fractions X and Y, describing the x- and y-coordinates of a point, respectively. They are given with five digits after the decimal point.
You may assume 1 <= N <= 300, 0.0 <= X <= 10.0, and 0.0 <= Y <= 10.0. No two points are closer than 0.0001. No two points in a data set are approximately at a distance of 2.0. More precisely, for any two points in a data set, the distance d between the two never satisfies 1.9999 <= d <= 2.0001. Finally, no three points in a data set are simultaneously very close to a single circle of radius one. More precisely, let P1, P2, and P3 be any three points in a data set, and d1, d2, and d3 the distances from an arbitrarily selected point in the xy-plane to each of them respectively. Then it never simultaneously holds that 0.9999 <= di <= 1.0001 (i = 1, 2, 3).
Output
For each data set, print a single line containing the maximum number of points in the data set that can be simultaneously enclosed by a circle of radius one. No other characters including leading and trailing spaces should be printed.
Example
Input
3
6.47634 7.69628
5.16828 4.79915
6.69533 6.20378
6
7.15296 4.08328
6.50827 2.69466
5.91219 3.86661
5.29853 4.16097
6.10838 3.46039
6.34060 2.41599
8
7.90650 4.01746
4.10998 4.18354
4.67289 4.01887
6.33885 4.28388
4.98106 3.82728
5.12379 5.16473
7.84664 4.67693
4.02776 3.87990
20
6.65128 5.47490
6.42743 6.26189
6.35864 4.61611
6.59020 4.54228
4.43967 5.70059
4.38226 5.70536
5.50755 6.18163
7.41971 6.13668
6.71936 3.04496
5.61832 4.23857
5.99424 4.29328
5.60961 4.32998
6.82242 5.79683
5.44693 3.82724
6.70906 3.65736
7.89087 5.68000
6.23300 4.59530
5.92401 4.92329
6.24168 3.81389
6.22671 3.62210
0
Output
2
5
5
11
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
typedef double D;
const D EPS= (1e-10);
#define X real()
#define Y imag()
#define SZ size()
#define PB(x) push_back(b)
#define PREV(x,i) (x[(i+x.SZ-1)%x.SZ])
#define NEXT(x,i) (x[(i+1)%x.SZ])
template<class T> using CR=const T&;
using P=complex<D>;
using G=vector<P>;
int sgn(D a,D b=0){
if(a>b+EPS)return 1;
if(a<b-EPS)return -1;
return 0;
}
D dist(P a,P b){
return abs(a-b);
}
tuple<P,P> normal_direction(P v){
D x=v.X,y=v.Y;
return tuple<P,P>(P(y,-x),P(-y,x));
}
P normalize(P v){
D x=v.X,y=v.Y;
D d=abs(v);
return P(x/d,y/d);
}
tuple<P,P> getC(P a,P b){
auto v=b-a;
auto pq=normal_direction(v);
P p,q;tie(p,q)=pq;
D d=sqrt(1-(dist(a,b)/2)*(dist(a,b)/2));
return tuple<P,P>(a+0.5*v+d*normalize(p),a+0.5*v+d*normalize(q));
}
int cnt(G& g,P c){
int n=g.size(),res=0;
for(int i=0;i<n;i++)
if(sgn(dist(c,g[i]),1.0)<=0){
res++;
}
return res;
}
int main(){
for(int n;cin>>n,n;){
G g(n);
for(int i=0;i<n;i++){\
D x,y;
cin>>x>>y;
g[i]=P(x,y);
}
int res=1;
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++)
if(sgn(dist(g[i],g[j]),2.0)<=0){
auto pq=getC(g[i],g[j]);
P p,q;tie(p,q)=pq;
res=max({res,cnt(g,p),cnt(g,q)});
}
cout<<res<<endl;
}
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
International Women's Day is coming soon! Polycarp is preparing for the holiday.
There are n candy boxes in the shop for sale. The i-th box contains d_i candies.
Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i β j) can be combined as a gift if d_i + d_j is divisible by k.
How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them.
Input
The first line of the input contains two integers n and k (1 β€ n β€ 2 β
10^5, 1 β€ k β€ 100) β the number the boxes and the number the girls.
The second line of the input contains n integers d_1, d_2, ..., d_n (1 β€ d_i β€ 10^9), where d_i is the number of candies in the i-th box.
Output
Print one integer β the maximum number of the boxes Polycarp can give as gifts.
Examples
Input
7 2
1 2 2 3 2 4 10
Output
6
Input
8 2
1 2 2 3 2 4 6 10
Output
8
Input
7 3
1 2 2 3 2 4 5
Output
4
Note
In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):
* (2, 3);
* (5, 6);
* (1, 4).
So the answer is 6.
In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):
* (6, 8);
* (2, 3);
* (1, 4);
* (5, 7).
So the answer is 8.
In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):
* (1, 2);
* (6, 7).
So the answer is 4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
srand(time(NULL));
;
long long t, n, m, k, a, b, c, d;
t = 1;
while (t--) {
cin >> n >> k;
vector<long long> v(n);
vector<long long> fr(k, 0);
for (long long i = 0; i < n; i++) {
cin >> v[i];
fr[v[i] % k]++;
}
long long ans = 0;
ans += fr[0] / 2;
for (long long i = 1; i <= k / 2; i++) {
ans += min(fr[i], fr[k - i]);
}
if (k % 2 == 0) {
ans -= fr[k / 2];
ans += fr[k / 2] / 2;
}
ans *= 2;
cout << ans << endl;
}
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 β€ n β€ 150 000, <image>) β the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 β€ ai, bi β€ n, ai β bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long int INF = 9e18L;
const long long int mod = 1e9 + 7;
long long int power(long long int x, long long int y) {
long long int res = 1;
int mod = 1e9 + 7;
while (y > 0) {
if (y & 1) (res = res * x) %= mod;
(x = x * x) %= mod;
y = y >> 1;
}
return res % mod;
}
vector<int> adj[150001], vis(150001, 0), v;
int c;
void dfs(int u) {
vis[u] = 1;
c++;
v.push_back(u);
for (auto x : adj[u]) {
if (vis[x] == 0) {
dfs(x);
}
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
int flag = 1;
for (int i = 1; i < n + 1 && flag; i++) {
if (vis[i] == 0) {
c = 0;
dfs(i);
for (auto x : v) {
if (adj[x].size() != c - 1) {
flag = 0;
break;
}
}
v.clear();
}
}
if (flag)
cout << "YES" << '\n';
else
cout << "NO" << '\n';
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
You are given three positive integers n, a and b. You have to construct a string s of length n consisting of lowercase Latin letters such that each substring of length a has exactly b distinct letters. It is guaranteed that the answer exists.
You have to answer t independent test cases.
Recall that the substring s[l ... r] is the string s_l, s_{l+1}, ..., s_{r} and its length is r - l + 1. In this problem you are only interested in substrings of length a.
Input
The first line of the input contains one integer t (1 β€ t β€ 2000) β the number of test cases. Then t test cases follow.
The only line of a test case contains three space-separated integers n, a and b (1 β€ a β€ n β€ 2000, 1 β€ b β€ min(26, a)), where n is the length of the required string, a is the length of a substring and b is the required number of distinct letters in each substring of length a.
It is guaranteed that the sum of n over all test cases does not exceed 2000 (β n β€ 2000).
Output
For each test case, print the answer β such a string s of length n consisting of lowercase Latin letters that each substring of length a has exactly b distinct letters. If there are multiple valid answers, print any of them. It is guaranteed that the answer exists.
Example
Input
4
7 5 3
6 1 1
6 6 1
5 2 2
Output
tleelte
qwerty
vvvvvv
abcde
Note
In the first test case of the example, consider all the substrings of length 5:
* "tleel": it contains 3 distinct (unique) letters,
* "leelt": it contains 3 distinct (unique) letters,
* "eelte": it contains 3 distinct (unique) letters.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 4e6 + 7;
const int maxm = 2e3 + 7;
const int mod = 998244353;
long long ans = 0, tot = 0, tot1, tot2;
long long a[maxn], b[maxn], p[maxn], last[maxm], f[maxm], dp[200][200];
bool flag[maxn], vis[maxn], vis1[maxn];
struct node {
char c;
long long x, y, z;
node(int x = 0, int y = 0, int z = 0) : x(x), y(y), z(z) {}
bool operator<(const node& n) {
if (z == n.z) return y < n.y;
return z > n.z;
}
};
node ve[maxn];
vector<int> v;
long long C[200][200];
void trangle() {
C[1][1] = C[2][1] = C[2][2] = 1;
for (register int i = 3; i <= 150; i++) {
for (register int j = 1; j <= i; j++) {
C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % mod;
}
}
}
int main() {
string s1, s2;
long long n, m, k;
long long x, y;
map<int, int> mp;
int t;
cin >> t;
while (t--) {
s1 = "";
cin >> n >> m >> k;
int f = floor(1.0 * m / k);
int s = ceil(1.0 * m / f);
for (register int i = 1; i <= s; i++) {
for (register int j = 1; j <= f; j++) {
s1 += 'a' + (i - 1) % k;
}
}
s1 = s1.substr(0, m);
int len = s1.size();
for (register int i = 1; i <= n; i++) {
cout << s1[(i - 1) % len];
}
cout << '\n';
}
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Vasiliy finally got to work, where there is a huge amount of tasks waiting for him. Vasiliy is given a matrix consisting of n rows and m columns and q tasks. Each task is to swap two submatrices of the given matrix.
For each task Vasiliy knows six integers ai, bi, ci, di, hi, wi, where ai is the index of the row where the top-left corner of the first rectangle is located, bi is the index of its column, ci is the index of the row of the top-left corner of the second rectangle, di is the index of its column, hi is the height of the rectangle and wi is its width.
It's guaranteed that two rectangles in one query do not overlap and do not touch, that is, no cell belongs to both rectangles, and no two cells belonging to different rectangles share a side. However, rectangles are allowed to share an angle.
Vasiliy wants to know how the matrix will look like after all tasks are performed.
Input
The first line of the input contains three integers n, m and q (2 β€ n, m β€ 1000, 1 β€ q β€ 10 000) β the number of rows and columns in matrix, and the number of tasks Vasiliy has to perform.
Then follow n lines containing m integers vi, j (1 β€ vi, j β€ 109) each β initial values of the cells of the matrix.
Each of the following q lines contains six integers ai, bi, ci, di, hi, wi (1 β€ ai, ci, hi β€ n, 1 β€ bi, di, wi β€ m).
Output
Print n lines containing m integers each β the resulting matrix.
Examples
Input
4 4 2
1 1 2 2
1 1 2 2
3 3 4 4
3 3 4 4
1 1 3 3 2 2
3 1 1 3 2 2
Output
4 4 3 3
4 4 3 3
2 2 1 1
2 2 1 1
Input
4 2 1
1 1
1 1
2 2
2 2
1 1 4 1 1 2
Output
2 2
1 1
2 2
1 1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1005;
int a[MAXN][MAXN];
int n, m, i, j, k, x, y, xx, yy, nn, mm, q;
int nowx, nowy, nexx, nexy;
int r[MAXN][MAXN][2];
int d[MAXN][MAXN][2];
inline int get() {
char c;
while ((c = getchar()) < 48 || c > 57)
;
int res = c - 48;
while ((c = getchar()) >= 48 && c <= 57) res = res * 10 + c - 48;
return res;
}
inline void getpoint(int a, int b, int &x, int &y) {
x = 0;
y = 0;
for (int i = 1; i <= b; i++) {
int xx = r[x][y][0], yy = r[x][y][1];
x = xx;
y = yy;
}
for (int i = 1; i <= a; i++) {
int xx = d[x][y][0], yy = d[x][y][1];
x = xx;
y = yy;
}
}
int main() {
cin >> n >> m;
cin >> q;
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++) a[i][j] = get();
for (i = 0; i <= n; i++) {
for (j = 0; j <= m; j++) r[i][j][0] = i, r[i][j][1] = j + 1;
for (j = 0; j <= m; j++) d[i][j][0] = i + 1, d[i][j][1] = j;
}
while (q--) {
int f, g;
x = get();
y = get();
xx = get();
yy = get();
nn = get();
mm = get();
int b[4][4];
getpoint(x, y - 1, b[0][0], b[0][1]);
getpoint(xx, yy - 1, b[0][2], b[0][3]);
getpoint(x, y + mm - 1, b[1][0], b[1][1]);
getpoint(xx, yy + mm - 1, b[1][2], b[1][3]);
getpoint(x - 1, y, b[2][0], b[2][1]);
getpoint(xx - 1, yy, b[2][2], b[2][3]);
getpoint(x + nn - 1, y, b[3][0], b[3][1]);
getpoint(xx + nn - 1, yy, b[3][2], b[3][3]);
nowx = b[0][0];
nowy = b[0][1];
nexx = b[0][2];
nexy = b[0][3];
for (i = 1; i <= nn; i++) {
swap(r[nowx][nowy][0], r[nexx][nexy][0]);
swap(r[nowx][nowy][1], r[nexx][nexy][1]);
f = d[nowx][nowy][0];
g = d[nowx][nowy][1];
nowx = f;
nowy = g;
f = d[nexx][nexy][0];
g = d[nexx][nexy][1];
nexx = f;
nexy = g;
}
nowx = b[1][0];
nowy = b[1][1];
nexx = b[1][2];
nexy = b[1][3];
for (i = 1; i <= nn; i++) {
swap(r[nowx][nowy][0], r[nexx][nexy][0]);
swap(r[nowx][nowy][1], r[nexx][nexy][1]);
f = d[nowx][nowy][0];
g = d[nowx][nowy][1];
nowx = f;
nowy = g;
f = d[nexx][nexy][0];
g = d[nexx][nexy][1];
nexx = f;
nexy = g;
}
nowx = b[2][0];
nowy = b[2][1];
nexx = b[2][2];
nexy = b[2][3];
for (i = 1; i <= mm; i++) {
swap(d[nowx][nowy][0], d[nexx][nexy][0]);
swap(d[nowx][nowy][1], d[nexx][nexy][1]);
f = r[nowx][nowy][0];
g = r[nowx][nowy][1];
nowx = f;
nowy = g;
f = r[nexx][nexy][0];
g = r[nexx][nexy][1];
nexx = f;
nexy = g;
}
nowx = b[3][0];
nowy = b[3][1];
nexx = b[3][2];
nexy = b[3][3];
for (i = 1; i <= mm; i++) {
swap(d[nowx][nowy][0], d[nexx][nexy][0]);
swap(d[nowx][nowy][1], d[nexx][nexy][1]);
f = r[nowx][nowy][0];
g = r[nowx][nowy][1];
nowx = f;
nowy = g;
f = r[nexx][nexy][0];
g = r[nexx][nexy][1];
nexx = f;
nexy = g;
}
}
for (i = 1; i <= n; i++) {
x = i;
y = 0;
for (j = 1; j <= m; j++) {
xx = r[x][y][0];
yy = r[x][y][1];
x = xx;
y = yy;
printf("%d ", a[x][y]);
}
puts("");
}
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
There are two rectangles whose bases are parallel to the x-axis. Read the lower left coordinates (xa1, ya1) and upper right coordinates (xa2, ya2) of rectangle A, the lower left coordinates (xb1, yb1) and upper right coordinates (xb2, yb2) of rectangle B, and rectangle A and B Create a program that outputs YES if there is any overlap, and NO if there is no overlap at all. However, assume that rectangle A and rectangle B are not the same thing. Also, the things that are in contact are considered to overlap.
<image>
Input
Given multiple datasets. The format of each dataset is as follows.
xa1 ya1 xa2 ya2 xb1 yb1 xb2 yb2
Each value entered is between -2,000 and 2,000, and each value is given as a real number, including up to five digits after the decimal point.
The number of datasets does not exceed 50.
Output
Print YES or NO on one line for each dataset.
Example
Input
0.0 0.0 5.0 5.0 1.0 1.0 4.0 4.0
0.0 0.0 4.0 5.0 1.0 1.0 5.0 5.0
0.0 0.0 4.0 4.0 -3.0 -5.0 2.0 -1.0
Output
YES
YES
NO
### Response
```cpp
#include<stdio.h>
int main()
{
double ax1,ax2,ay1,ay2,bx1,bx2,by1,by2;
while(scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&ax1,&ay1,&ax2,&ay2,&bx1,&by1,&bx2,&by2)==8)
puts(ax1<=bx2&&bx1<=ax2&&ay1<=by2&&by1<=ay2?"YES":"NO");
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
You are given an array a_1, a_2, ..., a_n consisting of n distinct integers. Count the number of pairs of indices (i, j) such that i < j and a_i β
a_j = i + j.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t cases follow.
The first line of each test case contains one integer n (2 β€ n β€ 10^5) β the length of array a.
The second line of each test case contains n space separated integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 2 β
n) β the array a. It is guaranteed that all elements are distinct.
It is guaranteed that the sum of n over all test cases does not exceed 2 β
10^5.
Output
For each test case, output the number of pairs of indices (i, j) such that i < j and a_i β
a_j = i + j.
Example
Input
3
2
3 1
3
6 1 5
5
3 1 5 9 2
Output
1
1
3
Note
For the first test case, the only pair that satisfies the constraints is (1, 2), as a_1 β
a_2 = 1 + 2 = 3
For the second test case, the only pair that satisfies the constraints is (2, 3).
For the third test case, the pairs that satisfy the constraints are (1, 2), (1, 5), and (2, 3).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long long int lli;
#define pb push_back
#define mp make_pair
#define va(a) a.begin(), a.end()
#define vd(d) d.begin(), d.end(), greater<ll>()
#define vi vector<int>
#define vll vector<long long>
#define pb push_back
#define pll pair<ll, ll>
#define si set<int>
#define sll set<long long>
#define endl "\n"
#define rep(i, a, b) for (ll i = a; i < b; i++)
#define demonb95 \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL)
void solve()
{
ll n;
cin >> n;
vector<pll> v;
rep(i, 0, n)
{
ll x;
cin >> x;
v.pb(mp(x, i + 1));
}
sort(va(v));
ll count = 0;
rep(i, 0, n)
{
rep(j, i + 1, n)
{
ll a = v[i].first * v[j].first;
ll b = v[i].second + v[j].second;
if (a == b)
count++;
if (a > 2 * n)
break;
}
}
cout << count << endl;
}
int main()
{
demonb95;
ll t;
cin >> t;
while (t--)
{
solve();
}
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
An integer sequence is called beautiful if the difference between any two consecutive numbers is equal to 1. More formally, a sequence s_1, s_2, β¦, s_{n} is beautiful if |s_i - s_{i+1}| = 1 for all 1 β€ i β€ n - 1.
Trans has a numbers 0, b numbers 1, c numbers 2 and d numbers 3. He wants to construct a beautiful sequence using all of these a + b + c + d numbers.
However, it turns out to be a non-trivial task, and Trans was not able to do it. Could you please help Trans?
Input
The only input line contains four non-negative integers a, b, c and d (0 < a+b+c+d β€ 10^5).
Output
If it is impossible to construct a beautiful sequence satisfying the above constraints, print "NO" (without quotes) in one line.
Otherwise, print "YES" (without quotes) in the first line. Then in the second line print a + b + c + d integers, separated by spaces β a beautiful sequence. There should be a numbers equal to 0, b numbers equal to 1, c numbers equal to 2 and d numbers equal to 3.
If there are multiple answers, you can print any of them.
Examples
Input
2 2 2 1
Output
YES
0 1 0 1 2 3 2
Input
1 2 3 4
Output
NO
Input
2 2 2 3
Output
NO
Note
In the first test, it is easy to see, that the sequence is beautiful because the difference between any two consecutive numbers is equal to 1. Also, there are exactly two numbers, equal to 0, 1, 2 and exactly one number, equal to 3.
It can be proved, that it is impossible to construct beautiful sequences in the second and third tests.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 4e5 + 20;
int main() {
int a, b, c, d;
cin >> a >> b >> c >> d;
if (c == d && c == 0 && a == b + 1) {
puts("YES");
cout << "0 ";
for (int i = 0; i < b; ++i) {
cout << "1 0 ";
}
} else if (a == b && a == 0 && c == d - 1) {
puts("YES");
cout << "3 ";
for (int i = 0; i < c; ++i) {
cout << "2 3 ";
}
} else if ((a <= b) && (c >= d) && (abs((b - a) - (c - d)) <= 1)) {
puts("YES");
if ((b - a) - (c - d) > 0) cout << "1 ";
for (int i = 0; i < a; ++i) {
cout << "0 1 ";
}
int num = 0;
if ((b - a) - (c - d) > 0)
num = (b - a - 1);
else if ((b - a) - (c - d) < 0)
num = (c - d - 1);
else
num = b - a;
for (int j = 0; j < num; ++j) {
cout << "2 1 ";
}
for (int k = 0; k < d; ++k) {
cout << "2 3 ";
}
if ((b - a) - (c - d) < 0) cout << "2 ";
puts("");
} else {
puts("NO");
}
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Snuke has a blackboard and a set S consisting of N integers. The i-th element in S is S_i.
He wrote an integer X on the blackboard, then performed the following operation N times:
* Choose one element from S and remove it.
* Let x be the number written on the blackboard now, and y be the integer removed from S. Replace the number on the blackboard with x \bmod {y}.
There are N! possible orders in which the elements are removed from S. For each of them, find the number that would be written on the blackboard after the N operations, and compute the sum of all those N! numbers modulo 10^{9}+7.
Constraints
* All values in input are integers.
* 1 \leq N \leq 200
* 1 \leq S_i, X \leq 10^{5}
* S_i are pairwise distinct.
Input
Input is given from Standard Input in the following format:
N X
S_1 S_2 \ldots S_{N}
Output
Print the answer.
Examples
Input
2 19
3 7
Output
3
Input
5 82
22 11 6 5 13
Output
288
Input
10 100000
50000 50001 50002 50003 50004 50005 50006 50007 50008 50009
Output
279669259
### Response
```cpp
#include <iostream>
#include <algorithm>
#include <iostream>
#include <map>
#include <numeric>
#include <set>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
const ll MOD = 1000000007;
int main(int argc, const char * argv[]) {
ll N, X; cin >> N >> X;
vector<ll> S(N);
for (int i=0; i<N; i++)
cin >> S[i];
sort(S.begin(), S.end(), greater<ll>());
vector<vector<ll>> dp(N+1, vector<ll>(X+1, 0));
dp[0][X] = 1;
for (ll n=0; n<N; n++) {
for (ll x=0; x<X+1; x++) {
if (dp[n][x] == 0) continue;
dp[n+1][x%S[n]] += dp[n][x];
dp[n+1][x%S[n]] %= MOD;
dp[n+1][x] += (N-n-1)*dp[n][x]%MOD;
dp[n+1][x] %= MOD;
}
}
ll ans = 0;
for (int i=0; i<X+1; i++){
ans += dp[N][i]*i % MOD;
ans %= MOD;
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
John Doe has an n Γ m table. John Doe can paint points in some table cells, not more than one point in one table cell. John Doe wants to use such operations to make each square subtable of size n Γ n have exactly k points.
John Doe wondered, how many distinct ways to fill the table with points are there, provided that the condition must hold. As this number can be rather large, John Doe asks to find its remainder after dividing by 1000000007 (109 + 7).
You should assume that John always paints a point exactly in the center of some cell. Two ways to fill a table are considered distinct, if there exists a table cell, that has a point in one way and doesn't have it in the other.
Input
A single line contains space-separated integers n, m, k (1 β€ n β€ 100; n β€ m β€ 1018; 0 β€ k β€ n2) β the number of rows of the table, the number of columns of the table and the number of points each square must contain.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
In a single line print a single integer β the remainder from dividing the described number of ways by 1000000007 (109 + 7).
Examples
Input
5 6 1
Output
45
Note
Let's consider the first test case:
<image> The gray area belongs to both 5 Γ 5 squares. So, if it has one point, then there shouldn't be points in any other place. If one of the white areas has a point, then the other one also must have a point. Thus, there are about 20 variants, where the point lies in the gray area and 25 variants, where each of the white areas contains a point. Overall there are 45 variants.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int modulo = 1e9 + 7;
const int max_n = 111;
const int max_k = max_n * max_n;
int bin_pow(int base, long long pw) {
if (pw == 0) return 1;
if (pw & 1) return (1LL * base * bin_pow(base, pw - 1)) % modulo;
return bin_pow((1LL * base * base) % modulo, pw >> 1);
}
int a[max_n][max_k], C[max_n][max_n], d[max_n][max_n];
int n, k;
long long m;
int main() {
ios_base::sync_with_stdio(false);
C[0][0] = 1;
for (int i = 1; i < max_n; ++i) {
C[0][i] = 0;
C[i][0] = 1;
}
for (int i = 1; i < max_n; ++i)
for (int j = 1; j < max_n; ++j)
C[i][j] = (0LL + C[i][j] + C[i - 1][j] + C[i - 1][j - 1]) % modulo;
cin >> n >> m >> k;
for (int i = 1; i <= n; ++i)
for (int j = 0; j <= n; ++j) {
long long pw = 1 + (m - i) / n;
d[i][j] = bin_pow(C[n][j], pw);
}
a[0][0] = 1;
for (int i = 1; i <= n; ++i)
for (int j = 0; j <= min(k, i * n); ++j)
for (int t = 0; t <= min(j, n); ++t)
if (a[i - 1][j - t] != 0)
a[i][j] = (a[i][j] + 1LL * a[i - 1][j - t] * d[i][t]) % modulo;
cout << a[n][k] << endl;
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants.
The magic square is a matrix of size n Γ n. The elements of this matrix are integers. The sum of numbers in each row of the matrix is equal to some number s. The sum of numbers in each column of the matrix is also equal to s. In addition, the sum of the elements on the main diagonal is equal to s and the sum of elements on the secondary diagonal is equal to s. Examples of magic squares are given in the following figure:
<image> Magic squares
You are given a set of n2 integers ai. It is required to place these numbers into a square matrix of size n Γ n so that they form a magic square. Note that each number must occur in the matrix exactly the same number of times as it occurs in the original set.
It is guaranteed that a solution exists!
Input
The first input line contains a single integer n. The next line contains n2 integers ai ( - 108 β€ ai β€ 108), separated by single spaces.
The input limitations for getting 20 points are:
* 1 β€ n β€ 3
The input limitations for getting 50 points are:
* 1 β€ n β€ 4
* It is guaranteed that there are no more than 9 distinct numbers among ai.
The input limitations for getting 100 points are:
* 1 β€ n β€ 4
Output
The first line of the output should contain a single integer s. In each of the following n lines print n integers, separated by spaces and describing the resulting magic square. In the resulting magic square the sums in the rows, columns and diagonals must be equal to s. If there are multiple solutions, you are allowed to print any of them.
Examples
Input
3
1 2 3 4 5 6 7 8 9
Output
15
2 7 6
9 5 1
4 3 8
Input
3
1 0 -1 0 2 -1 -2 0 1
Output
0
1 0 -1
-2 0 2
1 0 -1
Input
2
5 5 5 5
Output
10
5 5
5 5
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 2036;
int a[N];
int c[N], r[N], d, d2;
int sc[N], sr[N], sd, sd2;
const int ITER = 1999;
int main() {
int n;
scanf("%d", &n);
for (int i = (0); i < (int)(n * n); i++) scanf("%d", a + i);
int s = accumulate(a, a + n * n, 0) / n;
int sco = 1999;
while (sco > 0) {
int cur = 0;
memset(c, 0, sizeof(c)), memset(r, 0, sizeof(r));
d = d2 = 0;
random_shuffle(a, a + n * n);
for (int i = (0); i < (int)(n); i++)
for (int j = (0); j < (int)(n); j++) {
int id = i * n + j;
r[i] += a[id];
c[j] += a[id];
if (i == j) d += a[id];
if (i + j == n - 1) d2 += a[id];
}
sco = 0;
for (int i = (0); i < (int)(n); i++) {
sco += (sr[i] = abs(r[i] - s));
sco += (sc[i] = abs(c[i] - s));
}
sco += (sd = abs(d - s));
sco += (sd2 = abs(d2 - s));
if (sco == 0) break;
for (int iter = (0); iter < (int)(ITER); iter++) {
int first, second;
do {
first = rand() % (n * n);
second = rand() % (n * n);
} while (a[first] == a[second]);
int i1 = first / n, j1 = first % n;
int i2 = second / n, j2 = second % n;
int df = a[second] - a[first];
int nr1 = i1 == i2 ? r[i1] : r[i1] + df;
int nc1 = j1 == j2 ? c[j1] : c[j1] + df;
int nr2 = i1 == i2 ? r[i2] : r[i2] - df;
int nc2 = j1 == j2 ? c[j2] : c[j2] - df;
int nd = d + (i1 == j1 ? df : 0) + (i2 == j2 ? -df : 0);
int nd2 = d2 + (i1 + j1 == n - 1 ? df : 0) + (i2 + j2 == n - 1 ? -df : 0);
int tr1 = abs(nr1 - s) - sr[i1];
int tc1 = abs(nc1 - s) - sc[j1];
int tr2 = abs(nr2 - s) - sr[i2];
int tc2 = abs(nc2 - s) - sc[j2];
int td = abs(nd - s) - sd;
int td2 = abs(nd2 - s) - sd2;
int upd = tr1 + tc1 + tr2 + tc2 + td + td2;
if (upd < 0) {
sco += upd;
swap(a[first], a[second]);
r[i1] += df;
c[j1] += df;
r[i2] -= df;
c[j2] -= df;
if (i1 == j1) d += df;
if (i1 + j1 == n - 1) d2 += df;
if (i2 == j2) d -= df;
if (i2 + j2 == n - 1) d2 -= df;
sr[i1] += tr1;
sc[j1] += tc1;
sr[i2] += tr2;
sc[j2] += tc2;
sd += td;
sd2 += td2;
if (sco == 0) goto OUT;
}
}
}
OUT:
printf("%d\n", s);
for (int i = (0); i < (int)(n * n); i++)
printf("%d%c", a[i], i % n == n - 1 ? '\n' : ' ');
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
There are three airports A, B and C, and flights between each pair of airports in both directions.
A one-way flight between airports A and B takes P hours, a one-way flight between airports B and C takes Q hours, and a one-way flight between airports C and A takes R hours.
Consider a route where we start at one of the airports, fly to another airport and then fly to the other airport.
What is the minimum possible sum of the flight times?
Constraints
* 1 \leq P,Q,R \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
P Q R
Output
Print the minimum possible sum of the flight times.
Examples
Input
1 3 4
Output
4
Input
3 2 3
Output
5
### Response
```cpp
#include <iostream>
using namespace std;
int p, q, r;
int main() {
cin>>p>>q>>r;
cout<<p+q+r - max(p, max(q, r));
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.
To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.
George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c β₯ d), by changing limits on the input data.
However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
Input
The first line contains two integers n and m (1 β€ n, m β€ 3000) β the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 β€ a1 < a2 < ... < an β€ 106) β the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 β€ b1 β€ b2... β€ bm β€ 106) β the complexities of the problems prepared by George.
Output
Print a single integer β the answer to the problem.
Examples
Input
3 5
1 2 3
1 2 2 3 3
Output
0
Input
3 5
1 2 3
1 1 1 1 1
Output
2
Input
3 1
2 3 4
1
Output
3
Note
In the first sample the set of the prepared problems meets the requirements for a good round.
In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.
In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int k, l, n, m, q, h, kol = 0;
cin >> n >> m;
vector<int> v, u, r;
for (int i = 0; i < n; i++) {
cin >> k;
v.push_back(k);
r.push_back(1);
}
for (int i = 0; i < m; i++) {
cin >> k;
u.push_back(k);
}
h = 0;
for (int i = 0; i < n; i++) {
q = v[i];
int j = h;
int f = 1;
while ((j < m) && (f == 1)) {
l = u[j];
if (l >= q) {
kol++;
f = 0;
j++;
h++;
} else {
j++;
h++;
}
}
}
cout << max(0, n - kol);
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
problem
Given the sequence $ A $ of length $ N $. Find the maximum value of $ \ sum B_i $, where $ B $ is one of the longest increasing subsequences of the sequence $ A $.
The longest increasing subsequence of the sequence $ A $ is the longest subsequence that satisfies $ A_i <A_j $ with all $ i <j $.
output
Output the maximum value of $ \ sum B_i $, where $ B $ is one of the longest increasing subsequences of the sequence $ A $. Also, output a line break at the end.
Example
Input
4
6 4 7 8
Output
21
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> as(n);
for (int i = 0; i < n; i++) {
cin >> as[i];
}
vector<int> lis(n + 1, 1e9);
vector<vector<int>> ds(n);
for (int i = 0; i < n; i++) {
int k = lower_bound(lis.begin(), lis.end(), as[i]) - lis.begin();
lis[k] = as[i];
ds[k].push_back(as[i]);
}
long long ans = 0;
int k;
for (k = 0; k < n + 1; k++) {
if (lis[k] == 1e9) break;
}
int nax = 1e9;
for (int i = k - 1; i >= 0; i--) {
sort(ds[i].begin(), ds[i].end());
while (ds[i].back() >= nax) {
ds[i].pop_back();
}
ans += ds[i].back();
nax = ds[i].back();
}
cout << ans << endl;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:
1. x doesn't contain neither digit 0 nor digit 1.
2. <image> = <image>.
Help friends find such number.
Input
The first line contains an integer n (1 β€ n β€ 15) β the number of digits in a.
The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.
Output
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Examples
Input
4
1234
Output
33222
Input
3
555
Output
555
Note
In the first case, <image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename A, size_t N, typename T>
void Fill(A (&array)[N], const T &val) {
std::fill((T *)array, (T *)(array + N), val);
}
template <class T>
inline bool chmax(T &a, T b) {
if (a < b) {
a = b;
return true;
}
return false;
}
template <class T>
inline bool chmin(T &a, T b) {
if (a > b) {
a = b;
return true;
}
return false;
}
string p[] = {"", "2", "3", "322", "5", "53", "7", "7222", "7332"};
int main() {
int n;
cin >> n;
string s;
cin >> s;
string res;
for (int i = 0; i < (int)(n); ++i) {
if (s[i] == '0') continue;
res += p[s[i] - '1'];
}
sort(res.rbegin(), res.rend());
cout << res << endl;
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Polycarp is preparing the first programming contest for robots. There are n problems in it, and a lot of robots are going to participate in it. Each robot solving the problem i gets p_i points, and the score of each robot in the competition is calculated as the sum of p_i over all problems i solved by it. For each problem, p_i is an integer not less than 1.
Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results β or manipulating them.
For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of p_i in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of p_i will be large, it may look very suspicious β so Polycarp wants to minimize the maximum value of p_i over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?
Input
The first line contains one integer n (1 β€ n β€ 100) β the number of problems.
The second line contains n integers r_1, r_2, ..., r_n (0 β€ r_i β€ 1). r_i = 1 means that the "Robo-Coder Inc." robot will solve the i-th problem, r_i = 0 means that it won't solve the i-th problem.
The third line contains n integers b_1, b_2, ..., b_n (0 β€ b_i β€ 1). b_i = 1 means that the "BionicSolver Industries" robot will solve the i-th problem, b_i = 0 means that it won't solve the i-th problem.
Output
If "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer -1.
Otherwise, print the minimum possible value of max _{i = 1}^{n} p_i, if all values of p_i are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.
Examples
Input
5
1 1 1 0 0
0 1 1 1 1
Output
3
Input
3
0 0 0
0 0 0
Output
-1
Input
4
1 1 1 1
1 1 1 1
Output
-1
Input
9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
Output
4
Note
In the first example, one of the valid score assignments is p = [3, 1, 3, 1, 1]. Then the "Robo-Coder" gets 7 points, the "BionicSolver" β 6 points.
In the second example, both robots get 0 points, and the score distribution does not matter.
In the third example, both robots solve all problems, so their points are equal.
### Response
```cpp
#include <bits/stdc++.h>
const int mod = 1e9 + 7;
using namespace std;
template <typename T>
inline void read(T& x) {
char c;
bool nega = 0;
while ((!isdigit(c = getchar())) && c != '-')
;
if (c == '-') {
c = getchar();
nega = 1;
}
x = c - 48;
while (isdigit(c = getchar())) {
x = x * 10 + c - 48;
}
if (nega) x = -x;
}
template <typename T>
void Write(T x) {
if (x > 9) Write(x / 10);
putchar(x % 10 + 48);
}
template <typename T>
void write(T x) {
if (x < 0) {
putchar('-');
x = -x;
}
Write(x);
}
int n, a[5010], b[5010];
int main() {
read(n);
for (int i = 1; i <= n; i++) read(a[i]);
for (int i = 1; i <= n; i++) read(b[i]);
int cnt = 0, cnt1 = 0, cnta = 0;
for (int i = 1; i <= n; i++)
if (a[i] == 1 && b[i] == 0) cnt++;
for (int i = 1; i <= n; i++)
if (b[i]) {
cnt1++;
if (a[i]) cnta++;
}
if (cnt == 0)
write(-1);
else
write(((cnt1 - cnta) + cnt) / cnt);
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
A map of some object is a rectangular field consisting of n rows and n columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly k islands appear on the map. We will call a set of sand cells to be island if it is possible to get from each of them to each of them by moving only through sand cells and by moving from a cell only to a side-adjacent cell. The cells are called to be side-adjacent if they share a vertical or horizontal side. It is easy to see that islands do not share cells (otherwise they together form a bigger island).
Find a way to cover some cells with sand so that exactly k islands appear on the n Γ n map, or determine that no such way exists.
Input
The single line contains two positive integers n, k (1 β€ n β€ 100, 0 β€ k β€ n2) β the size of the map and the number of islands you should form.
Output
If the answer doesn't exist, print "NO" (without the quotes) in a single line.
Otherwise, print "YES" in the first line. In the next n lines print the description of the map. Each of the lines of the description must consist only of characters 'S' and 'L', where 'S' is a cell that is occupied by the sea and 'L' is the cell covered with sand. The length of each line of the description must equal n.
If there are multiple answers, you may print any of them.
You should not maximize the sizes of islands.
Examples
Input
5 2
Output
YES
SSSSS
LLLLL
SSSSS
LLLLL
SSSSS
Input
5 25
Output
NO
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool sorts(pair<int, double> a, pair<int, double> b) {
if (a.second == b.second)
return a.first > b.first;
else
return a.second < b.second;
}
double dist(double a, double b, double c, double d) {
double dist = sqrt(fabs(a - c) * fabs(a - c) + fabs(b - d) * fabs(b - d));
return dist;
}
int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
int main() {
int n, k;
cin >> n >> k;
if (k > ceil((double)n * n / 2.0))
cout << "NO";
else {
cout << "YES" << endl;
if (n % 2) {
bool land = true;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (land && k != 0) {
cout << "L";
land = false;
k--;
} else {
cout << "S";
land = true;
}
}
cout << "\n";
}
} else {
bool land = true;
for (int i = 0; i < n; i++) {
if (i % 2 == 0)
land = true;
else
land = false;
for (int j = 0; j < n; j++) {
if (land && k != 0) {
cout << "L";
land = false;
k--;
} else {
cout << "S";
land = true;
}
}
cout << "\n";
}
}
}
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.
In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. The generic syntax for declaring a macro is the following:
#define macro_name macro_value
After the macro has been declared, "macro_name" is replaced with "macro_value" each time it is met in the program (only the whole tokens can be replaced; i.e. "macro_name" is replaced only when it is surrounded by spaces or other non-alphabetic symbol). A "macro_value" within our model can only be an arithmetic expression consisting of variables, four arithmetic operations, brackets, and also the names of previously declared macros (in this case replacement is performed sequentially). The process of replacing macros with their values is called substitution.
One of the main problems arising while using macros β the situation when as a result of substitution we get an arithmetic expression with the changed order of calculation because of different priorities of the operations.
Let's consider the following example. Say, we declared such a #define construction:
#define sum x + y
and further in the program the expression "2 * sum" is calculated. After macro substitution is performed we get "2 * x + y", instead of intuitively expected "2 * (x + y)".
Let's call the situation "suspicious", if after the macro substitution the order of calculation changes, falling outside the bounds of some macro. Thus, your task is to find out by the given set of #define definitions and the given expression if this expression is suspicious or not.
Let's speak more formally. We should perform an ordinary macros substitution in the given expression. Moreover, we should perform a "safe" macros substitution in the expression, putting in brackets each macro value; after this, guided by arithmetic rules of brackets expansion, we can omit some of the brackets. If there exist a way to get an expression, absolutely coinciding with the expression that is the result of an ordinary substitution (character-by-character, but ignoring spaces), then this expression and the macros system are called correct, otherwise β suspicious.
Note that we consider the "/" operation as the usual mathematical division, not the integer division like in C/C++. That's why, for example, in the expression "a*(b/c)" we can omit brackets to get the expression "a*b/c".
Input
The first line contains the only number n (0 β€ n β€ 100) β the amount of #define constructions in the given program.
Then there follow n lines, each of them contains just one #define construction. Each construction has the following syntax:
#define name expression
where
* name β the macro name,
* expression β the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding 109.
All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction.
Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions.
The input lines may contain any number of spaces anywhere, providing these spaces do not break the word "define" or the names of constructions and variables. In particular, there can be any number of spaces before and after the "#" symbol.
The length of any line from the input file does not exceed 100 characters.
Output
Output "OK", if the expression is correct according to the above given criterion, otherwise output "Suspicious".
Examples
Input
1
#define sum x + y
1 * sum
Output
Suspicious
Input
1
#define sum (x + y)
sum - sum
Output
OK
Input
4
#define sum x + y
#define mul a * b
#define div a / b
#define expr sum + mul * div * mul
expr
Output
OK
Input
3
#define SumSafe (a+b)
#define DivUnsafe a/b
#define DenominatorUnsafe a*b
((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)
Output
Suspicious
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
unordered_map<string, int> mp;
int check(string s, int l, int r) {
int num = 0, flag = 0;
for (int i = r; i >= l; --i) {
if (s[i] == '(')
num++;
else if (s[i] == ')')
num--;
else if (!num && !flag && (s[i] == '*' || s[i] == '/'))
flag = i;
else if (!num && (s[i] == '+' || s[i] == '-')) {
int x = check(s, l, i - 1), y = check(s, i + 1, r);
if (x == 2 || y == 2)
return 2;
else if (s[i] == '+')
return 3;
else if (s[i] == '-') {
if (y == 3)
return 2;
else
return 3;
}
}
}
if (flag) {
int x = check(s, l, flag - 1), y = check(s, flag + 1, r);
if (x == 2 || y == 2) return 2;
if (s[flag] == '*') {
if (x == 3 || y == 3)
return 2;
else
return 4;
} else {
if (x == 3 || y == 3 || y == 4)
return 2;
else
return 4;
}
}
if (s[l] == '(' && s[r] == ')')
return check(s, l + 1, r - 1) == 2 ? 2 : 1;
else {
string t = s.substr(l, r - l + 1);
if (mp.count(t)) return mp[t];
}
}
void erase_space(string& s) {
for (int i = 0; i < s.size(); ++i) {
if (s[i] == ' ') {
s.erase(i, 1);
i--;
}
}
}
int main() {
int nums;
for (cin >> nums; nums--;) {
while (cin.get() != '#')
;
string a, s;
cin >> a >> a;
getline(cin, s);
erase_space(s);
int opt = check(s, 0, s.size() - 1);
mp[a] = opt;
}
string s;
getline(cin, s);
erase_space(s);
if (check(s, 0, s.length() - 1) != 2)
cout << "OK\n";
else
cout << "Suspicious\n";
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
One quite ordinary day Valera went to school (there's nowhere else he should go on a week day). In a maths lesson his favorite teacher Ms. Evans told students about divisors. Despite the fact that Valera loved math, he didn't find this particular topic interesting. Even more, it seemed so boring that he fell asleep in the middle of a lesson. And only a loud ringing of a school bell could interrupt his sweet dream.
Of course, the valuable material and the teacher's explanations were lost. However, Valera will one way or another have to do the homework. As he does not know the new material absolutely, he cannot do the job himself. That's why he asked you to help. You're his best friend after all, you just cannot refuse to help.
Valera's home task has only one problem, which, though formulated in a very simple way, has not a trivial solution. Its statement looks as follows: if we consider all positive integers in the interval [a;b] then it is required to count the amount of such numbers in this interval that their smallest divisor will be a certain integer k (you do not have to consider divisor equal to one). In other words, you should count the amount of such numbers from the interval [a;b], that are not divisible by any number between 2 and k - 1 and yet are divisible by k.
Input
The first and only line contains three positive integers a, b, k (1 β€ a β€ b β€ 2Β·109, 2 β€ k β€ 2Β·109).
Output
Print on a single line the answer to the given problem.
Examples
Input
1 10 2
Output
5
Input
12 23 3
Output
2
Input
6 19 5
Output
0
Note
Comments to the samples from the statement:
In the first sample the answer is numbers 2, 4, 6, 8, 10.
In the second one β 15, 21
In the third one there are no such numbers.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool isprime(int n) {
for (int i = 2; i * i <= n; ++i) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int cal(int x, int p) {
if (!isprime(p)) return 0;
if (x < p) return 0;
int res = x /= p;
for (int i = 2; i < p && i <= x; i++) {
res -= cal(x, i);
}
return res;
}
int main() {
int a, b, k;
scanf("%d%d%d", &a, &b, &k);
printf("%d", cal(b, k) - cal(a - 1, k));
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
The year of 2012 is coming...
According to an ancient choradrican legend in this very year, in 2012, Diablo and his brothers Mephisto and Baal will escape from hell, and innumerable hordes of demons will enslave the human world. But seven brave heroes have already gathered on the top of a mountain Arreat to protect us mere mortals from the effect of this terrible evil.
The seven great heroes are: amazon Anka, barbarian Chapay, sorceress Cleo, druid Troll, necromancer Dracul, paladin Snowy and a professional hit girl Hexadecimal. Heroes already know how much experience will be given for each of the three megabosses: a for Mephisto, b for Diablo and c for Baal.
Here's the problem: heroes are as much as seven and megabosses are only three! Then our heroes decided to split into three teams, where each team will go to destroy their own megaboss. Each team member will receive a <image> of experience, rounded down, where x will be the amount of experience for the killed megaboss and y β the number of people in the team.
Heroes do not want to hurt each other's feelings, so they want to split into teams so that the difference between the hero who received the maximum number of experience and the hero who received the minimum number of experience were minimal. Since there can be several divisions into teams, then you need to find the one in which the total amount of liking in teams were maximum.
It is known that some heroes like others. But if hero p likes hero q, this does not mean that the hero q likes hero p. No hero likes himself.
The total amount of liking in teams is the amount of ordered pairs (p, q), such that heroes p and q are in the same group, and hero p likes hero q (but it is not important if hero q likes hero p). In case of heroes p and q likes each other and they are in the same group, this pair should be counted twice, as (p, q) and (q, p).
A team can consist even of a single hero, but it is important that every megaboss was destroyed. All heroes must be involved in the campaign against evil. None of the heroes can be in more than one team.
It is guaranteed that every hero is able to destroy any megaboss alone.
Input
The first line contains a single non-negative integer n (0 β€ n β€ 42) β amount of liking between the heroes. Next n lines describe liking in the form "p likes q", meaning that the hero p likes the hero q (p β q). Every liking is described in the input exactly once, no hero likes himself.
In the last line are given three integers a, b and c (1 β€ a, b, c β€ 2Β·109), separated by spaces: the experience for Mephisto, the experience for Diablo and experience for Baal.
In all the pretests, except for examples from the statement, the following condition is satisfied: a = b = c.
Output
Print two integers β the minimal difference in the experience between two heroes who will receive the maximum and minimum number of experience points, and the maximal total amount of liking in teams (the number of friendships between heroes that end up in one team).
When calculating the second answer, the team division should satisfy the difference-minimizing contraint. I.e. primary you should minimize the difference in the experience and secondary you should maximize the total amount of liking.
Examples
Input
3
Troll likes Dracul
Dracul likes Anka
Snowy likes Hexadecimal
210 200 180
Output
30 3
Input
2
Anka likes Chapay
Chapay likes Anka
10000 50 50
Output
1950 2
Note
A note to first example: it the first team should be Dracul, Troll and Anka, in the second one Hexadecimal and Snowy, and in the third Cleo ΠΈ Chapay.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
map<string, int> hero;
int likes[8][8] = {0};
string str1, tmp, str2;
int a, b, c;
int perm[8] = {0, 1, 2, 3, 4, 5, 6, 7};
int main() {
hero["Anka"] = 1;
hero["Chapay"] = 2;
hero["Cleo"] = 3;
hero["Troll"] = 4;
hero["Dracul"] = 5;
hero["Snowy"] = 6;
hero["Hexadecimal"] = 7;
int n, i, minn, maxx, conta, j;
cin >> n;
for (i = 0; i < n; i++) {
cin >> str1 >> tmp >> str2;
likes[hero[str1]][hero[str2]] = 1;
}
cin >> a >> b >> c;
int minFinal = 1000000000, likeFinal = -1;
short sq1, sq2, sq3, ind;
do {
for (sq1 = 1; sq1 <= 5; sq1++)
for (sq2 = 1; sq2 <= 5; sq2++)
for (sq3 = 1; sq3 <= 5; sq3++)
if (sq1 + sq2 + sq3 == 7) {
ind = 0;
minn = a / sq1;
maxx = a / sq1;
conta = 0;
for (i = 1; i < sq1; i++) {
for (j = i + 1; j <= sq1; j++) {
if (likes[perm[ind + i]][perm[ind + j]]) conta++;
if (likes[perm[ind + j]][perm[ind + i]]) conta++;
}
}
ind += i;
minn = min(minn, b / sq2);
maxx = max(maxx, b / sq2);
for (i = 1; i < sq2; i++) {
for (j = i + 1; j <= sq2; j++) {
if (likes[perm[ind + i]][perm[ind + j]]) conta++;
if (likes[perm[ind + j]][perm[ind + i]]) conta++;
}
}
ind += i;
minn = min(minn, c / sq3);
maxx = max(maxx, c / sq3);
for (i = 1; i < sq3; i++) {
for (j = i + 1; j <= sq3; j++) {
if (likes[perm[ind + i]][perm[ind + j]]) conta++;
if (likes[perm[ind + j]][perm[ind + i]]) conta++;
}
}
if (maxx - minn < minFinal) {
minFinal = maxx - minn;
likeFinal = conta;
} else if (maxx - minn == minFinal) {
likeFinal = max(likeFinal, conta);
}
}
} while (next_permutation(perm + 1, perm + 8));
cout << minFinal << " " << likeFinal << endl;
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Nothing is eternal in the world, Kostya understood it on the 7-th of January when he saw partially dead four-color garland.
Now he has a goal to replace dead light bulbs, however he doesn't know how many light bulbs for each color are required. It is guaranteed that for each of four colors at least one light is working.
It is known that the garland contains light bulbs of four colors: red, blue, yellow and green. The garland is made as follows: if you take any four consecutive light bulbs then there will not be light bulbs with the same color among them. For example, the garland can look like "RYBGRYBGRY", "YBGRYBGRYBG", "BGRYB", but can not look like "BGRYG", "YBGRYBYGR" or "BGYBGY". Letters denote colors: 'R' β red, 'B' β blue, 'Y' β yellow, 'G' β green.
Using the information that for each color at least one light bulb still works count the number of dead light bulbs of each four colors.
Input
The first and the only line contains the string s (4 β€ |s| β€ 100), which describes the garland, the i-th symbol of which describes the color of the i-th light bulb in the order from the beginning of garland:
* 'R' β the light bulb is red,
* 'B' β the light bulb is blue,
* 'Y' β the light bulb is yellow,
* 'G' β the light bulb is green,
* '!' β the light bulb is dead.
The string s can not contain other symbols except those five which were described.
It is guaranteed that in the given string at least once there is each of four letters 'R', 'B', 'Y' and 'G'.
It is guaranteed that the string s is correct garland with some blown light bulbs, it means that for example the line "GRBY!!!B" can not be in the input data.
Output
In the only line print four integers kr, kb, ky, kg β the number of dead light bulbs of red, blue, yellow and green colors accordingly.
Examples
Input
RYBGRYBGR
Output
0 0 0 0
Input
!RGYB
Output
0 1 0 0
Input
!!!!YGRB
Output
1 1 1 1
Input
!GB!RG!Y!
Output
2 1 1 0
Note
In the first example there are no dead light bulbs.
In the second example it is obvious that one blue bulb is blown, because it could not be light bulbs of other colors on its place according to the statements.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
const int mod = 1000000007;
const double pi = acos(-1.0);
inline void gn(long long& x) {
int sg = 1;
char c;
while (((c = getchar()) < '0' || c > '9') && c != '-')
;
c == '-' ? (sg = -1, x = 0) : (x = c - '0');
while ((c = getchar()) >= '0' && c <= '9') x = x * 10 + c - '0';
x *= sg;
}
inline void gn(int& x) {
long long t;
gn(t);
x = t;
}
inline void gn(unsigned long long& x) {
long long t;
gn(t);
x = t;
}
long long gcd(long long a, long long b) { return a ? gcd(b % a, a) : b; }
long long powmod(long long a, long long x, long long mod) {
long long t = 1ll;
while (x) {
if (x & 1) t = t * a % mod;
a = a * a % mod;
x >>= 1;
}
return t;
}
string s;
int gid(char c) {
if (c == 'R') return 1;
if (c == 'B') return 2;
if (c == 'Y') return 3;
if (c == 'G') return 4;
}
int ord[5];
int tt[5];
bool check() {
int sz = s.length();
for (int i = (0); i <= (sz - 1); i++) {
if (s[i] == '!') continue;
if (gid(s[i]) != ord[i % 4]) return false;
}
return true;
}
void calc() {
memset((tt), 0, sizeof(tt));
int sz = s.length();
for (int i = (0); i <= (sz - 1); i++) {
if (s[i] == '!') {
tt[ord[i % 4]]++;
}
}
}
int main() {
cin >> s;
for (int i = (0); i <= (3); i++) ord[i] = i + 1;
do {
if (check()) {
calc();
break;
}
} while (next_permutation(ord, ord + 4));
for (int i = (1); i <= (4); i++) cout << tt[i] << " ";
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Given is an integer sequence of length N+1: A_0, A_1, A_2, \ldots, A_N. Is there a binary tree of depth N such that, for each d = 0, 1, \ldots, N, there are exactly A_d leaves at depth d? If such a tree exists, print the maximum possible number of vertices in such a tree; otherwise, print -1.
Constraints
* 0 \leq N \leq 10^5
* 0 \leq A_i \leq 10^{8} (0 \leq i \leq N)
* A_N \geq 1
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_0 A_1 A_2 \cdots A_N
Output
Print the answer as an integer.
Examples
Input
3
0 1 1 2
Output
7
Input
4
0 0 1 0 2
Output
10
Input
2
0 3 1
Output
-1
Input
1
1 1
Output
-1
Input
10
0 0 1 1 2 3 5 8 13 21 34
Output
264
### Response
```cpp
#include <iostream>
#include <vector>
int main() {
int N;
std::cin >> N;
std::vector<long long> A(N + 1);
for (int i = 0; i <= N; i++) std::cin >> A[i];
std::vector<long long> sum(N + 1);
sum[N] = A[N];
for (int i = N - 1; i >= 0; i--) {
sum[i] = sum[i + 1] + A[i];
}
long long ans = 0, res = 0;
for (int i = 0; i <= N; i++) {
res = std::min(sum[i], res * 2 - A[i] + (i == 0 ? 1 : 0));
if (res < 0) {
std::cout << "-1\n";
return 0;
}
ans += std::min(sum[i], res + A[i]);
}
std::cout << ans << "\n";
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Let N be a positive integer. You are given a string s of length N - 1, consisting of `<` and `>`.
Find the number of permutations (p_1, p_2, \ldots, p_N) of (1, 2, \ldots, N) that satisfy the following condition, modulo 10^9 + 7:
* For each i (1 \leq i \leq N - 1), p_i < p_{i + 1} if the i-th character in s is `<`, and p_i > p_{i + 1} if the i-th character in s is `>`.
Constraints
* N is an integer.
* 2 \leq N \leq 3000
* s is a string of length N - 1.
* s consists of `<` and `>`.
Input
Input is given from Standard Input in the following format:
N
s
Output
Print the number of permutations that satisfy the condition, modulo 10^9 + 7.
Examples
Input
4
<><
Output
5
Input
5
<<<<
Output
1
Input
20
>>>><>>><>><>>><<>>
Output
217136290
### Response
```cpp
#include <iostream>
using namespace std;
typedef long long ll;
ll mod = 1e9 + 7;
int main(int argc, char *argv[])
{
int N;
string s;
ll from[3005], to[3005];
ll S[3005];
cin >> N >> s;
for (int i = 0; i < N; i++) {
from[i] = 1;
}
for (int i = 0; i < N - 1; i++) {
for (int i = 0; i < N; i++) {
to[i] = 0;
}
for (int x = 0; x < N + 1; x++) {
S[x] = ((x ? S[x - 1] : 0) + from[x]) % mod;
}
for (int x = 0; x < N - 1 - i; x++) {
if (s[i] == '>') {
to[x] = (S[N] + mod - S[x]) % mod;
} else {
to[x] = S[x];
}
}
swap(from, to);
}
cout << from[0] << endl;
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
You are given two integers n and k. Find k-th smallest divisor of n, or report that it doesn't exist.
Divisor of n is any such natural number, that n can be divided by it without remainder.
Input
The first line contains two integers n and k (1 β€ n β€ 1015, 1 β€ k β€ 109).
Output
If n has less than k divisors, output -1.
Otherwise, output the k-th smallest divisor of n.
Examples
Input
4 2
Output
2
Input
5 3
Output
-1
Input
12 5
Output
6
Note
In the first example, number 4 has three divisors: 1, 2 and 4. The second one is 2.
In the second example, number 5 has only two divisors: 1 and 5. The third divisor doesn't exist, so the answer is -1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long modu = 1e9 + 7;
int noofdig(int N) { return floor(log10(N)) + 1; }
int bits_count(unsigned int u) {
unsigned int uCount;
uCount = u - ((u >> 1) & 033333333333) - ((u >> 2) & 011111111111);
return ((uCount + (uCount >> 3)) & 030707070707) % 63;
}
void solve() {
long long int n, k;
cin >> n >> k;
vector<long long int> div;
for (long long int i = 1; i * i <= n; i++) {
if (n % i == 0) {
div.push_back(i);
if (i * i != n) div.push_back(n / i);
}
}
sort(div.begin(), div.end());
if ((long long int)div.size() >= k)
cout << div[k - 1] << '\n';
else
cout << -1 << '\n';
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
srand(chrono::high_resolution_clock::now().time_since_epoch().count());
int t = 1;
while (t--) {
solve();
}
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer T separate queries.
Input
The first line contains a single integer T (1 β€ T β€ 100) β the number of queries.
Each of the next T lines contains string s (1 β€ |s| β€ 100) β the string for the next query. It is guaranteed that it contains only lowercase Latin letters.
Note that in hacks you have to set T = 1.
Output
Print T lines. The i-th line should contain the answer to the i-th query.
If the answer for the i-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
Otherwise print "No answer" for that query.
Example
Input
4
abcd
gg
codeforces
abaca
Output
cadb
gg
codfoerces
No answer
Note
In the first example answer "bdac" is also correct.
The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.
There are lots of valid answers for the third example.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
string s;
int cnt[100];
int T;
bool check(int a, int b) { return (abs(a - b) != 1); }
void print(vector<int> a, vector<int> b) {
for (int i = 0; i < a.size(); i++) {
for (int j = 0; j < cnt[a[i]]; j++) cout << char(a[i] + 'a');
}
for (int i = 0; i < b.size(); i++) {
for (int j = 0; j < cnt[b[i]]; j++) cout << char(b[i] + 'a');
}
}
int main() {
ios_base::sync_with_stdio(0);
cin >> T;
while (T--) {
cin >> s;
for (int i = 0; i < 26; i++) cnt[i] = 0;
for (int i = 0; i < s.size(); i++) cnt[s[i] - 'a']++;
vector<int> odd, even;
for (int i = 0; i < 26; i++)
if (cnt[i] > 0) {
if (i % 2 == 1)
odd.push_back(i);
else
even.push_back(i);
}
if (odd.empty() || even.empty())
print(odd, even);
else if (check(even.back(), odd[0]))
print(even, odd);
else if (check(odd.back(), even[0]))
print(odd, even);
else
cout << "No answer";
cout << '\n';
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
There are two rival donut shops.
The first shop sells donuts at retail: each donut costs a dollars.
The second shop sells donuts only in bulk: box of b donuts costs c dollars. So if you want to buy x donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts in them is greater or equal to x.
You want to determine two positive integer values:
1. how many donuts can you buy so that they are strictly cheaper in the first shop than in the second shop?
2. how many donuts can you buy so that they are strictly cheaper in the second shop than in the first shop?
If any of these values doesn't exist then that value should be equal to -1. If there are multiple possible answers, then print any of them.
The printed values should be less or equal to 10^9. It can be shown that under the given constraints such values always exist if any values exist at all.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Each of the next t lines contains three integers a, b and c (1 β€ a β€ 10^9, 2 β€ b β€ 10^9, 1 β€ c β€ 10^9).
Output
For each testcase print two positive integers. For both shops print such x that buying x donuts in this shop is strictly cheaper than buying x donuts in the other shop. x should be greater than 0 and less or equal to 10^9.
If there is no such x, then print -1. If there are multiple answers, then print any of them.
Example
Input
4
5 10 4
4 5 20
2 2 3
1000000000 1000000000 1000000000
Output
-1 20
8 -1
1 2
-1 1000000000
Note
In the first testcase buying any number of donuts will be cheaper in the second shop. For example, for 3 or 5 donuts you'll have to buy a box of 10 donuts for 4 dollars. 3 or 5 donuts in the first shop would cost you 15 or 25 dollars, respectively, however. For 20 donuts you'll have to buy two boxes for 8 dollars total. Note that 3 and 5 are also valid answers for the second shop, along with many other answers.
In the second testcase buying any number of donuts will be either cheaper in the first shop or the same price. 8 donuts cost 32 dollars in the first shop and 40 dollars in the second shop (because you have to buy two boxes). 10 donuts will cost 40 dollars in both shops, so 10 is not a valid answer for any of the shops.
In the third testcase 1 donut costs 2 and 3 dollars, respectively. 2 donuts cost 4 and 3 dollars. Thus, 1 is a valid answer for the first shop and 2 is a valid answer for the second shop.
In the fourth testcase 10^9 donuts cost 10^{18} dollars in the first shop and 10^9 dollars in the second shop.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long losn = 1e6 + 5;
const long long maxn = 1e5 + 5;
const long long minn = 1e3 + 5;
const long long tiny = 1e2 + 5;
const long long inf = 1e9;
const long long mod = 1e9 + 7;
const long long hmod = 4698571;
int main() {
long long t;
cin >> t;
while (t--) {
long long a, b, c;
cin >> a >> b >> c;
long long nums = b * 2 - 1;
long long an = nums * a;
if ((an < c * 2 && nums <= inf) || a < c) {
if (an < c * 2 && nums <= inf) {
cout << nums << " ";
} else {
cout << 1 << " ";
}
} else {
cout << -1 << " ";
}
if (a * b > c) {
cout << b << endl;
} else {
cout << -1 << endl;
}
}
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
There is a triangle formed by three points $(x_1, y_1)$, $(x_2, y_2)$, $(x_3, y_3)$ on a plain.
Write a program which prints "YES" if a point $P$ $(x_p, y_p)$ is in the triangle and "NO" if not.
Constraints
You can assume that:
* $ -100 \leq x_1, y_1, x_2, y_2, x_3, y_3, x_p, y_p \leq 100$
* 1.0 $\leq$ Length of each side of a tringle
* 0.001 $\leq$ Distance between $P$ and each side of a triangle
Input
Input consists of several datasets. Each dataset consists of:
$x_1$ $y_1$ $x_2$ $y_2$ $x_3$ $y_3$ $x_p$ $y_p$
All the input are real numbers. Input ends with EOF. The number of datasets is less than or equal to 100.
Output
For each dataset, print "YES" or "NO" in a line.
Example
Input
0.0 0.0 2.0 0.0 2.0 2.0 1.5 0.5
0.0 0.0 1.0 4.0 5.0 3.0 -1.0 3.0
Output
YES
NO
### Response
```cpp
#include<iostream>
using namespace std;
int main()
{
double x1, y1, x2, y2, x3, y3, xp, yp;
while(cin>>x1>>y1>>x2>>y2>>x3>>y3>>xp>>yp)
{
double s = ((y3-y1)*(xp-x1)+(x1-x3)*(yp-y1))/((x2-x1)*(y3-y1)-(x3-x1)*(y2-y1));
double t = ((y1-y2)*(xp-x1)+(x2-x1)*(yp-y1))/((x2-x1)*(y3-y1)-(x3-x1)*(y2-y1));
if( s>=0 && t>=0 && s+t<=1 ){cout << "YES\n";}
else{cout << "NO\n"; }
}
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
When Sasha was studying in the seventh grade, he started listening to music a lot. In order to evaluate which songs he likes more, he introduced the notion of the song's prettiness. The title of the song is a word consisting of uppercase Latin letters. The prettiness of the song is the prettiness of its title.
Let's define the simple prettiness of a word as the ratio of the number of vowels in the word to the number of all letters in the word.
Let's define the prettiness of a word as the sum of simple prettiness of all the substrings of the word.
More formally, let's define the function vowel(c) which is equal to 1, if c is a vowel, and to 0 otherwise. Let si be the i-th character of string s, and si..j be the substring of word s, staring at the i-th character and ending at the j-th character (sisi + 1... sj, i β€ j).
Then the simple prettiness of s is defined by the formula:
<image>
The prettiness of s equals
<image>
Find the prettiness of the given song title.
We assume that the vowels are I, E, A, O, U, Y.
Input
The input contains a single string s (1 β€ |s| β€ 5Β·105) β the title of the song.
Output
Print the prettiness of the song with the absolute or relative error of at most 10 - 6.
Examples
Input
IEAIAIO
Output
28.0000000
Input
BYOB
Output
5.8333333
Input
YISVOWEL
Output
17.0500000
Note
In the first sample all letters are vowels. The simple prettiness of each substring is 1. The word of length 7 has 28 substrings. So, the prettiness of the song equals to 28.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
char s[] = {"AEIOUY"};
const int MAXN = 5e5 + 10;
bool jd(char ch) {
for (int i = 0; i < 6; i++)
if (ch == s[i]) return true;
return false;
}
int n;
long double ans = 0;
long double sum[MAXN];
char a[MAXN];
void cal(int x, int y) {
if (x > y) return;
if (x == y) {
if (jd(a[x])) ans += 1;
return;
}
int mid = (x + y) / 2;
cal(x, mid);
cal(mid + 1, y);
int rl = y - mid;
long double q = 0;
for (int i = x; i <= mid; i++) {
int l = mid - i + 1;
int r = l + rl;
q += sum[r] - sum[l];
if (jd(a[i])) ans += q;
}
int ll = mid - x + 1;
q = 0;
for (int i = y; i > mid; i--) {
int l = i - mid;
int r = ll + l;
q += sum[r] - sum[l];
if (jd(a[i])) ans += q;
}
}
int main() {
cin >> a;
n = strlen(a);
sum[1] = 1;
long double p = 1;
for (int i = 2; i <= n; i++) {
sum[i] = p / i;
sum[i] += sum[i - 1];
}
cal(0, n - 1);
double x = ans;
printf("%.10f\n", x);
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Write a program which reads a word W and a text T, and prints the number of word W which appears in text T
T consists of string Ti separated by space characters and newlines. Count the number of Ti which equals to W. The word and text are case insensitive.
Constraints
* The length of W β€ 10
* W consists of lower case letters
* The length of T in a line β€ 1000
Input
In the first line, the word W is given. In the following lines, the text T is given separated by space characters and newlines.
"END_OF_TEXT" indicates the end of the text.
Output
Print the number of W in the text.
Example
Input
computer
Nurtures computer scientists and highly-skilled computer engineers
who will create and exploit "knowledge" for the new era.
Provides an outstanding computer environment.
END_OF_TEXT
Output
3
### Response
```cpp
#include <iostream>
#include <string>
int main() {
std::string s, t;
std::cin >> s;
for (char &c : s) c = tolower(c);
int ans = 0;
while (true) {
std::cin >> t;
if (t == "END_OF_TEXT") break;
for (char &c : t) c = tolower(c);
ans += (s == t);
}
std::cout << ans << '\n';
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Makes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty β a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty d on Decoforces is as hard as the problem with difficulty d on any other judge).
Makes has chosen n problems to solve on Decoforces with difficulties a1, a2, ..., an. He can solve these problems in arbitrary order. Though he can solve problem i with difficulty ai only if he had already solved some problem with difficulty <image> (no matter on what online judge was it).
Before starting this chosen list of problems, Makes has already solved problems with maximum difficulty k.
With given conditions it's easy to see that Makes sometimes can't solve all the chosen problems, no matter what order he chooses. So he wants to solve some problems on other judges to finish solving problems from his list.
For every positive integer y there exist some problem with difficulty y on at least one judge besides Decoforces.
Makes can solve problems on any judge at any time, it isn't necessary to do problems from the chosen list one right after another.
Makes doesn't have too much free time, so he asked you to calculate the minimum number of problems he should solve on other judges in order to solve all the chosen problems from Decoforces.
Input
The first line contains two integer numbers n, k (1 β€ n β€ 103, 1 β€ k β€ 109).
The second line contains n space-separated integer numbers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print minimum number of problems Makes should solve on other judges in order to solve all chosen problems on Decoforces.
Examples
Input
3 3
2 1 9
Output
1
Input
4 20
10 3 6 3
Output
0
Note
In the first example Makes at first solves problems 1 and 2. Then in order to solve the problem with difficulty 9, he should solve problem with difficulty no less than 5. The only available are difficulties 5 and 6 on some other judge. Solving any of these will give Makes opportunity to solve problem 3.
In the second example he can solve every problem right from the start.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long int n, count = 0;
double k;
cin >> n >> k;
long long int upper = 2 * k;
long long int a[n];
for (int i = 0; i < n; i++) cin >> a[i];
sort(a, a + n);
for (int i = 0; i < n; i++) {
if (upper >= a[i]) {
upper = max(upper, 2 * a[i]);
} else {
while (upper < a[i]) {
upper *= 2;
count++;
}
upper = max(upper, 2 * a[i]);
}
}
cout << count;
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems.
There are m types of discounts. We assume that the discounts are indexed from 1 to m. To use the discount number i, the customer takes a special basket, where he puts exactly qi items he buys. Under the terms of the discount system, in addition to the items in the cart the customer can receive at most two items from the supermarket for free. The number of the "free items" (0, 1 or 2) to give is selected by the customer. The only condition imposed on the selected "free items" is as follows: each of them mustn't be more expensive than the cheapest item out of the qi items in the cart.
Maxim now needs to buy n items in the shop. Count the minimum sum of money that Maxim needs to buy them, if he use the discount system optimally well.
Please assume that the supermarket has enough carts for any actions. Maxim can use the same discount multiple times. Of course, Maxim can buy items without any discounts.
Input
The first line contains integer m (1 β€ m β€ 105) β the number of discount types. The second line contains m integers: q1, q2, ..., qm (1 β€ qi β€ 105).
The third line contains integer n (1 β€ n β€ 105) β the number of items Maxim needs. The fourth line contains n integers: a1, a2, ..., an (1 β€ ai β€ 104) β the items' prices.
The numbers in the lines are separated by single spaces.
Output
In a single line print a single integer β the answer to the problem.
Examples
Input
1
2
4
50 50 100 100
Output
200
Input
2
2 3
5
50 50 50 50 50
Output
150
Input
1
1
7
1 1 1 1 1 1 1
Output
3
Note
In the first sample Maxim needs to buy two items that cost 100 and get a discount for two free items that cost 50. In that case, Maxim is going to pay 200.
In the second sample the best strategy for Maxim is to buy 3 items and get 2 items for free using the discount. In that case, Maxim is going to pay 150.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long m, n, q, a;
while (scanf("%lld", &m) == 1) {
priority_queue<long long, vector<long long>, less<long long> > Q;
long long sum = 0;
long long mini = 1000000000;
while (m--) {
scanf("%lld", &q);
mini = min(mini, q);
}
scanf("%lld", &n);
for (int i = 1; i <= n; i++) {
scanf("%lld", &a);
Q.push(a);
sum = sum + a;
}
long long zks;
while (n > 0) {
if (n >= mini) {
zks = n - mini;
if (zks > 2) zks = 2;
for (int u = 1; u <= mini; u++) Q.pop();
for (int u = 1; u <= zks; u++) {
sum = sum - Q.top();
Q.pop();
}
n = n - mini - zks;
} else
n = 0;
}
printf("%lld\n", sum);
}
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
There are n districts in the town, the i-th district belongs to the a_i-th bandit gang. Initially, no districts are connected to each other.
You are the mayor of the city and want to build n-1 two-way roads to connect all districts (two districts can be connected directly or through other connected districts).
If two districts belonging to the same gang are connected directly with a road, this gang will revolt.
You don't want this so your task is to build n-1 two-way roads in such a way that all districts are reachable from each other (possibly, using intermediate districts) and each pair of directly connected districts belong to different gangs, or determine that it is impossible to build n-1 roads to satisfy all the conditions.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 500) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (2 β€ n β€ 5000) β the number of districts. The second line of the test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9), where a_i is the gang the i-th district belongs to.
It is guaranteed that the sum of n does not exceed 5000 (β n β€ 5000).
Output
For each test case, print:
* NO on the only line if it is impossible to connect all districts satisfying the conditions from the problem statement.
* YES on the first line and n-1 roads on the next n-1 lines. Each road should be presented as a pair of integers x_i and y_i (1 β€ x_i, y_i β€ n; x_i β y_i), where x_i and y_i are two districts the i-th road connects.
For each road i, the condition a[x_i] β a[y_i] should be satisfied. Also, all districts should be reachable from each other (possibly, using intermediate districts).
Example
Input
4
5
1 2 2 1 3
3
1 1 1
4
1 1000 101 1000
4
1 2 3 4
Output
YES
1 3
3 5
5 4
1 2
NO
YES
1 2
2 3
3 4
YES
1 2
1 3
1 4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> v(n, 0);
for (int i = 0; i < n; i++) cin >> v[i];
int secondGroup = -1;
int root = 0;
set<pair<int, int>> ht;
for (int i = 1; i < n; i++) {
if (v[i] != v[root]) {
ht.insert({root + 1, i + 1});
secondGroup = i + 1;
}
}
if (secondGroup == -1) {
cout << "NO" << endl;
return;
}
cout << "YES\n";
for (int i = 1; i < n; i++) {
if (v[i] == v[root]) ht.insert({secondGroup, i + 1});
}
for (pair<int, int> edges : ht)
cout << edges.first << " " << edges.second << endl;
}
int main() {
ios::sync_with_stdio(false);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.
The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.
Please help Chloe to solve the problem!
Input
The only line contains two integers n and k (1 β€ n β€ 50, 1 β€ k β€ 2n - 1).
Output
Print single integer β the integer at the k-th position in the obtained sequence.
Examples
Input
3 2
Output
2
Input
4 8
Output
4
Note
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long power(long long a, long long b, long long m = 1000000007) {
long long ans = 1;
a = a % m;
while (b > 0) {
if (b & 1) ans = (1ll * a * ans) % m;
b >>= 1;
a = (1ll * a * a) % m;
}
return ans;
}
long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; }
bool cmp(pair<string, int> p1, pair<string, int> p2) {
return p1.second > p2.second;
}
const long long MAXN = 5 * 1000 + 10;
long long x, y, d;
void extendEuclid(long long a, long long m) {
if (m == 0) {
d = a;
x = 1;
y = 0;
} else {
extendEuclid(m, a % m);
long long temp = x;
x = y;
y = temp - (a / m) * y;
}
}
long long modInverse(long long a, long long m) {
extendEuclid(a, m);
return (x % m + m) % m;
}
long long const INF = 100000000;
vector<long long> dis(100005, LONG_LONG_MAX);
vector<long long> p(100005, 0);
long long rec(long long l, long long r, long long need, long long n) {
long long m = l + (r - l) / 2;
if (need < m)
return rec(l, m - 1, need, n - 1);
else if (need > m)
return rec(m + 1, r, need, n - 1);
else
return n;
}
int32_t main() {
long long n, k;
cin >> n >> k;
long long sz = 1;
for (long long i = 1; i < n; i++) sz = sz * 2 + 1LL;
cout << rec(1, sz, k, n);
return 0;
};
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
In this problem, we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string s starting from the l-th character and ending with the r-th character as s[l ... r]. The characters of each string are numbered from 1.
We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.
Binary string a is considered reachable from binary string b if there exists a sequence s_1, s_2, ..., s_k such that s_1 = a, s_k = b, and for every i β [1, k - 1], s_i can be transformed into s_{i + 1} using exactly one operation. Note that k can be equal to 1, i. e., every string is reachable from itself.
You are given a string t and q queries to it. Each query consists of three integers l_1, l_2 and len. To answer each query, you have to determine whether t[l_1 ... l_1 + len - 1] is reachable from t[l_2 ... l_2 + len - 1].
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the length of string t.
The second line contains one string t (|t| = n). Each character of t is either 0 or 1.
The third line contains one integer q (1 β€ q β€ 2 β
10^5) β the number of queries.
Then q lines follow, each line represents a query. The i-th line contains three integers l_1, l_2 and len (1 β€ l_1, l_2 β€ |t|, 1 β€ len β€ |t| - max(l_1, l_2) + 1) for the i-th query.
Output
For each query, print either YES if t[l_1 ... l_1 + len - 1] is reachable from t[l_2 ... l_2 + len - 1], or NO otherwise. You may print each letter in any register.
Example
Input
5
11011
3
1 3 3
1 4 2
1 2 3
Output
Yes
Yes
No
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename T>
struct outputer;
struct outputable {};
template <typename T>
inline auto sqr(T x) -> decltype(x * x) {
return x * x;
}
template <typename T1, typename T2>
inline bool umx(T1& a, T2 b) {
if (a < b) {
a = b;
return 1;
}
return 0;
}
template <typename T1, typename T2>
inline bool umn(T1& a, T2 b) {
if (b < a) {
a = b;
return 1;
}
return 0;
}
const int N = 200000;
const int Q = 200000;
struct Input {
int n;
string s;
int q;
int l1[Q], l2[Q], len[Q];
bool read() {
if (!(cin >> n)) {
return 0;
}
getline(cin, s);
getline(cin, s);
cin >> q;
for (int i = int(0); i < int(q); ++i) {
scanf("%d%d%d", &l1[i], &l2[i], &len[i]);
--l1[i];
--l2[i];
}
return 1;
}
void init(const Input& input) { *this = input; }
};
struct Data : Input {
bool ans[Q];
void write() {
for (int i = int(0); i < int(q); ++i) {
puts(ans[i] ? "Yes" : "No");
}
}
};
namespace Main {
const int K = 8;
struct Solution : Data {
vector<int> pos;
int ss;
bool a[2][N];
uint8_t b[2][K][(N + K - 1) / K];
void solve() {
for (int i = int(0); i < int(n); ++i) {
if (s[i] == '0') {
pos.emplace_back(i);
}
}
ss = ((int)(pos).size());
for (int t = int(0); t < int(2); ++t) {
for (int i = int(0); i < int(ss); ++i) {
a[t][i] = (pos[i] & 1) ^ t;
}
}
memset(b, 0, sizeof b);
for (int t = int(0); t < int(2); ++t) {
for (int j = int(0); j < int(K); ++j) {
for (int i = int(0); i < int(ss - j + 1); ++i) {
b[t][j][i / K] ^= uint8_t(a[t][j + i] << (i % K));
}
}
}
for (int i = int(0); i < int(q); ++i) {
int L1 = lower_bound((pos).begin(), (pos).end(), l1[i]) - pos.begin();
int R1 =
lower_bound((pos).begin(), (pos).end(), l1[i] + len[i]) - pos.begin();
int L2 = lower_bound((pos).begin(), (pos).end(), l2[i]) - pos.begin();
int R2 =
lower_bound((pos).begin(), (pos).end(), l2[i] + len[i]) - pos.begin();
bool t1 = l1[i] & 1;
bool t2 = l2[i] & 1;
;
;
if (R1 - L1 != R2 - L2) {
ans[i] = 0;
continue;
}
ans[i] = 1;
while ((R1 - L1) % K) {
if (a[t1][L1] != a[t2][L2]) {
ans[i] = 0;
break;
}
++L1;
++L2;
}
if (!ans[i]) {
continue;
}
ans[i] = 0 == memcmp(b[t1][L1 % K] + (L1 / K), b[t2][L2 % K] + (L2 / K),
(R1 - L1) / K);
}
}
void clear() { *this = Solution(); }
};
} // namespace Main
Main::Solution sol;
int main() {
cout.setf(ios::showpoint | ios::fixed);
cout.precision(20);
sol.read();
sol.solve();
sol.write();
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Nowadays all circuses in Berland have a round arena with diameter 13 meters, but in the past things were different.
In Ancient Berland arenas in circuses were shaped as a regular (equiangular) polygon, the size and the number of angles could vary from one circus to another. In each corner of the arena there was a special pillar, and the rope strung between the pillars marked the arena edges.
Recently the scientists from Berland have discovered the remains of the ancient circus arena. They found only three pillars, the others were destroyed by the time.
You are given the coordinates of these three pillars. Find out what is the smallest area that the arena could have.
Input
The input file consists of three lines, each of them contains a pair of numbers ββ coordinates of the pillar. Any coordinate doesn't exceed 1000 by absolute value, and is given with at most six digits after decimal point.
Output
Output the smallest possible area of the ancient arena. This number should be accurate to at least 6 digits after the decimal point. It's guaranteed that the number of angles in the optimal polygon is not larger than 100.
Examples
Input
0.000000 0.000000
1.000000 1.000000
0.000000 1.000000
Output
1.00000000
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long double EPS = 1e-4;
const int inf = 1e9;
const long double PI = acos(-1);
int mod = (int)998244353;
const int MOD7 = 1000000007;
const int MOD9 = 1000000009;
const int a228 = 18;
const long long kekmod = 1791791791;
const long long bestmod = 1148822869;
const long long secmod = (int)1e9 + 113;
vector<long long> mods = {kekmod, bestmod, mod, MOD9, 1000000007};
vector<long long> hashpows = {29, 31, 37, 43, 47, 53, 179, 229};
mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count() +
228 + 'i' + 'q' + 1337 + 1488);
long long MOD = mods[rnd() % mods.size()];
long long hashpow = hashpows[rand() % hashpows.size()];
long double hypot(long double a, long double b, long double c, long double d) {
return sqrt(((a - c) * (a - c)) + ((b - d) * (b - d)));
}
long double gcd(long double a, long double b) {
while (abs(b) > EPS) {
a -= floor(a / b) * b;
swap(a, b);
}
return a;
}
long double getang(long double a, long double b, long double c) {
return acos(-(c * c - a * a - b * b) / (2 * a * b));
}
signed main() {
ios_base::sync_with_stdio(0);
cout.tie(0);
cin.tie(0);
srand(time(NULL));
long double a, b, c;
long double x1, y1, x2, y2, x3, y3;
cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;
a = hypot(x1, y1, x2, y2);
b = hypot(x2, y2, x3, y3);
c = hypot(x3, y3, x1, y1);
long double a1 = getang(a, b, c);
long double a2 = getang(b, c, a);
long double a3 = getang(a, c, b);
long double mere = gcd(gcd(a1, a2), a3);
int n = (int)((PI + EPS) / mere);
long double R = c / sin(a1) / 2;
long double tang = PI * 2 / n;
long double ans = n * (0.5 * R * R * sin(tang));
cout << fixed << setprecision(20) << ans;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
For each of the K^{NM} ways to write an integer between 1 and K (inclusive) in every square in a square grid with N rows and M columns, find the value defined below, then compute the sum of all those K^{NM} values, modulo D.
* For each of the NM squares, find the minimum among the N+M-1 integers written in the square's row or the square's column. The value defined for the grid is the product of all these NM values.
Constraints
* 1 \leq N,M,K \leq 100
* 10^8 \leq D \leq 10^9
* N,M,K, and D are integers.
* D is prime.
Input
Input is given from Standard Input in the following format:
N M K D
Output
Print the sum of the K^{NM} values, modulo D.
Examples
Input
2 2 2 998244353
Output
35
Input
2 3 4 998244353
Output
127090
Input
31 41 59 998244353
Output
827794103
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N=105;
ll d[N][N],f[N][N],e[N][N],ifa[N];
ll expo(ll a,int b,ll p){
ll c=1ll;
while(b){
if(b&1)c=c*a%p;
b>>=1; a=a*a%p;
}
return c;
}
int main(){
ll w=1ll,ww,p;
int n,m,q,K,k,t,i,j,h;
scanf("%d%d%d%lld",&n,&m,&q,&p);t=n<m?m:n;
for(i=1;i<=t;++i)w=w*i%p;
ifa[t]=w=expo(w,p-2ll,p);
for(i=t;i;--i)ifa[i-1]=w=w*i%p;
for(i=1;i<=q;++i){
e[i][0]=w=1ll;
for(j=1;j<=t;++j)e[i][j]=w=w*i%p;
}
for(i=1;i<=q;++i){
for(j=1;j<=t;++j)if((f[i][j]=e[i][j]-e[i-1][j])<0ll)f[i][j]+=p;
}
d[0][0]=1ll;
for(k=1,K=q;K;++k,--K){
for(j=0;j<=m;++j){
w=e[K][j]*f[k][m-j]%p;
// printf("j=%d w=%lld\n",j,w);
for(i=n-1;~i;--i){
ww=d[i][j];
for(h=i+1;h<=n;++h){
ww=ww*w%p;
d[h][j]=(d[h][j]+ww*ifa[h-i])%p;
}
}
}
/*
printf("\nk=%d K=%d\n",k,K);
for(i=0;i<=n;++i){
for(j=0;j<=m;++j){
printf("%d ",d[i][j]);
}
printf("\n");
}*/
for(i=0;i<=n;++i){
w=f[K][i]*e[k][n-i]%p;
for(j=m-1;~j;--j){
ww=d[i][j];
for(h=j+1;h<=m;++h){
ww=ww*w%p;
d[i][h]=(d[i][h]+ww*ifa[h-j])%p;
}
}
}
/*
printf("\nk=%d K=%d\n",k,K);
for(i=0;i<=n;++i){
for(j=0;j<=m;++j){
printf("%d ",d[i][j]);
}
printf("\n");
}*/
}
w=d[n][m];
for(i=1;i<=n;++i)w=w*i%p;
for(i=1;i<=m;++i)w=w*i%p;
printf("%lld",w);
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game.
Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, Bob computes the values of n variables. Each variable is assigned either a constant m-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values.
Bob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose.
Input
The first line contains two integers n and m, the number of variables and bit depth, respectively (1 β€ n β€ 5000; 1 β€ m β€ 1000).
The following n lines contain descriptions of the variables. Each line describes exactly one variable. Description has the following format: name of a new variable, space, sign ":=", space, followed by one of:
1. Binary number of exactly m bits.
2. The first operand, space, bitwise operation ("AND", "OR" or "XOR"), space, the second operand. Each operand is either the name of variable defined before or symbol '?', indicating the number chosen by Peter.
Variable names are strings consisting of lowercase Latin letters with length at most 10. All variable names are different.
Output
In the first line output the minimum number that should be chosen by Peter, to make the sum of all variable values minimum possible, in the second line output the minimum number that should be chosen by Peter, to make the sum of all variable values maximum possible. Both numbers should be printed as m-bit binary numbers.
Examples
Input
3 3
a := 101
b := 011
c := ? XOR b
Output
011
100
Input
5 1
a := 1
bb := 0
cx := ? OR a
d := ? XOR ?
e := d AND bb
Output
0
0
Note
In the first sample if Peter chooses a number 0112, then a = 1012, b = 0112, c = 0002, the sum of their values is 8. If he chooses the number 1002, then a = 1012, b = 0112, c = 1112, the sum of their values is 15.
For the second test, the minimum and maximum sum of variables a, bb, cx, d and e is 2, and this sum doesn't depend on the number chosen by Peter, so the minimum Peter can choose is 0.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int NMax = 5e3 + 5;
const int MMax = 1e3 + 5;
int N, M;
char input[NMax][MMax + 101];
short bit[NMax][MMax][2];
char solMin[MMax], solMax[MMax];
map<string, int> ID;
struct elem {
bool known;
int op1, op2;
char tor;
} v[NMax];
int compute(int, int, int);
int main() {
cin.sync_with_stdio(false);
cin.tie(0);
cin >> N >> M;
cin.getline(input[0], MMax + 100);
for (int i = 1; i <= N; ++i) {
cin.getline(input[i] + 1, MMax + 100);
string name = "";
int j = 1;
while ('a' <= input[i][j] && input[i][j] <= 'z') {
name += input[i][j++];
}
ID[name] = i;
}
for (int i = 1; i <= N; ++i) {
int j = 1;
while (input[i][j] != '=') {
++j;
}
j += 2;
if (input[i][j] == '0' || input[i][j] == '1') {
v[i].known = true;
for (int k = 1; k <= M; ++k) {
bit[i][k][0] = bit[i][k][1] = input[i][j] - '0' + 1;
++j;
}
} else {
string str;
if (input[i][j] == '?') {
v[i].op1 = -1;
++j;
} else {
str = "";
while ('a' <= input[i][j] && input[i][j] <= 'z') {
str += input[i][j];
++j;
}
v[i].op1 = ID[str];
}
++j;
if (input[i][j] == 'A') {
v[i].tor = '&';
j += 3;
} else if (input[i][j] == 'O') {
v[i].tor = '|';
j += 2;
} else {
v[i].tor = '^';
j += 3;
}
++j;
if (input[i][j] == '?') {
v[i].op2 = -1;
} else {
str = "";
while ('a' <= input[i][j] && input[i][j] <= 'z') {
str += input[i][j];
++j;
}
v[i].op2 = ID[str];
}
}
}
for (int b = 1; b <= M; ++b) {
int nr1By1 = 0, nr1By0 = 0;
for (int i = 1; i <= N; ++i) {
nr1By1 += compute(i, b, 1);
nr1By0 += compute(i, b, 0);
}
if (nr1By1 > nr1By0) {
solMax[b] = '1';
} else {
solMax[b] = '0';
}
if (nr1By1 < nr1By0) {
solMin[b] = '1';
} else {
solMin[b] = '0';
}
}
cout << (solMin + 1) << '\n' << (solMax + 1);
return 0;
}
int compute(int id, int b, int val) {
if (bit[id][b][val] != 0) {
return bit[id][b][val] - 1;
}
int f1, f2;
if (v[id].op1 == -1) {
f1 = val;
} else {
f1 = compute(v[id].op1, b, val);
}
if (v[id].op2 == -1) {
f2 = val;
} else {
f2 = compute(v[id].op2, b, val);
}
int res;
if (v[id].tor == '&') {
res = f1 & f2;
} else if (v[id].tor == '|') {
res = f1 | f2;
} else {
res = f1 ^ f2;
}
bit[id][b][val] = res + 1;
return res;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
You are given a string s consisting of n lowercase Latin letters. Polycarp wants to remove exactly k characters (k β€ n) from the string s. Polycarp uses the following algorithm k times:
* if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* ...
* remove the leftmost occurrence of the letter 'z' and stop the algorithm.
This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly k times, thus removing exactly k characters.
Help Polycarp find the resulting string.
Input
The first line of input contains two integers n and k (1 β€ k β€ n β€ 4 β
10^5) β the length of the string and the number of letters Polycarp will remove.
The second line contains the string s consisting of n lowercase Latin letters.
Output
Print the string that will be obtained from s after Polycarp removes exactly k letters using the above algorithm k times.
If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
Examples
Input
15 3
cccaabababaccbc
Output
cccbbabaccbc
Input
15 9
cccaabababaccbc
Output
cccccc
Input
1 1
u
Output
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
char s[400005];
int n, k;
char c = 'a';
int T[26];
memset(T, 0, sizeof(T));
cin >> n >> k;
for (int i = 0; i < n; i++) {
scanf(" %c", &s[i]);
T[s[i] - 'a']++;
}
int maxx;
for (int i = 0; i < 26; i++) {
if (k >= T[i])
k -= T[i];
else {
maxx = i, T[i] = k;
break;
}
}
for (int i = 0; i < n; i++) {
if (s[i] - 'a' <= maxx && T[s[i] - 'a'] > 0)
T[s[i] - 'a']--, s[i] = '*';
else
printf("%c", s[i]);
}
printf("\n");
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
This problem is a little bit unusual. Here you are to implement an interaction with a testing system. That means that you can make queries and get responses in the online mode. Please be sure to use the stream flushing operation after each query's output in order not to leave part of your output in some buffer. For example, in C++ you've got to use the fflush(stdout) function, in Java β call System.out.flush(), and in Pascal β flush(output).
Bulls and Cows (also known as Cows and Bulls or Pigs and Bulls or Bulls and Cleots) is an old code-breaking paper and pencil game for two players, predating the similar commercially marketed board game Mastermind.
On a sheet of paper, the first player thinks a secret string. This string consists only of digits and has the length 4. The digits in the string must be all different, no two or more equal digits are allowed.
Then the second player tries to guess his opponent's string. For every guess the first player gives the number of matches. If the matching digits are on their right positions, they are "bulls", if on different positions, they are "cows". Thus a response is a pair of numbers β the number of "bulls" and the number of "cows". A try can contain equal digits.
More formally, let's the secret string is s and the second player are trying to guess it with a string x. The number of "bulls" is a number of such positions i (1 β€ i β€ 4) where s[i] = x[i]. The number of "cows" is a number of such digits c that s contains c in the position i (i.e. s[i] = c), x contains c, but x[i] β c.
For example, the secret string is "0427", the opponent's try is "0724", then the answer is 2 bulls and 2 cows (the bulls are "0" and "2", the cows are "4" and "7"). If the secret string is "0123", the opponent's try is "0330", then the answer is 1 bull and 1 cow.
In this problem you are to guess the string s that the system has chosen. You only know that the chosen string consists of 4 distinct digits.
You can make queries to the testing system, each query is the output of a single 4-digit string. The answer to the query is the number of bulls and number of cows. If the system's response equals "4 0", that means the interaction with your problem is over and the program must terminate. That is possible for two reasons β the program either guessed the number x or made an invalid action (for example, printed letters instead of digits).
Your program is allowed to do at most 50 queries.
You can hack solutions of other participants providing a 4-digit string containing distinct digits β the secret string.
Input
To read answers to the queries, the program must use the standard input.
The program will receive pairs of non-negative integers in the input, one pair per line. The first number in a pair is a number of bulls and the second one is a number of cows of the string s and the string xi printed by your program. If the system response equals "4 0", then your solution should terminate.
The testing system will let your program read the i-th pair of integers from the input only after your program displays the corresponding system query in the output: prints value xi in a single line and executes operation flush.
Output
The program must use the standard output to print queries.
Your program must output requests β 4-digit strings x1, x2, ..., one per line. After the output of each line the program must execute flush operation. The program should read the answer to the query from the standard input.
Your program is allowed to do at most 50 queries.
Examples
Input
0 1
2 0
1 1
0 4
2 1
4 0
Output
8000
0179
3159
3210
0112
0123
Note
The secret string s in the example is "0123".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int Ans[5];
int main() {
for (int i = 1; i <= 4; i++) {
int mx = 0, mxw = 0;
for (int j = 0; j <= 9; j++) {
for (int k = 1; k < i; k++) printf("0");
printf("%d", j);
for (int k = i + 1; k <= 4; k++) printf("0");
printf("\n");
fflush(stdout);
int x, y;
scanf("%d%d", &x, &y);
if (x > mx) mx = x, mxw = j;
}
Ans[i] = mxw;
}
for (int i = 1; i <= 4; i++) printf("%d", Ans[i]);
fflush(stdout);
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Recently Polycarpus has learned the "bitwise AND" operation (which is also called "AND") of non-negative integers. Now he wants to demonstrate the school IT teacher his superb manipulation with the learned operation.
For that Polycarpus came to school a little earlier and wrote on the board a sequence of non-negative integers a1, a2, ..., an. He also wrote a square matrix b of size n Γ n. The element of matrix b that sits in the i-th row in the j-th column (we'll denote it as bij) equals:
* the "bitwise AND" of numbers ai and aj (that is, bij = ai & aj), if i β j;
* -1, if i = j.
Having written out matrix b, Polycarpus got very happy and wiped a off the blackboard. But the thing is, the teacher will want this sequence to check whether Polycarpus' calculations were correct. Polycarus urgently needs to restore the removed sequence of integers, or else he won't prove that he can count correctly.
Help Polycarpus, given matrix b, restore the sequence of numbers a1, a2, ..., an, that he has removed from the board. Polycarpus doesn't like large numbers, so any number in the restored sequence mustn't exceed 109.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the size of square matrix b. Next n lines contain matrix b. The i-th of these lines contains n space-separated integers: the j-th number represents the element of matrix bij. It is guaranteed, that for all i (1 β€ i β€ n) the following condition fulfills: bii = -1. It is guaranteed that for all i, j (1 β€ i, j β€ n; i β j) the following condition fulfills: 0 β€ bij β€ 109, bij = bji.
Output
Print n non-negative integers a1, a2, ..., an (0 β€ ai β€ 109) β the sequence that Polycarpus wiped off the board. Separate the numbers by whitespaces.
It is guaranteed that there is sequence a that satisfies the problem conditions. If there are multiple such sequences, you are allowed to print any of them.
Examples
Input
1
-1
Output
0
Input
3
-1 18 0
18 -1 0
0 0 -1
Output
18 18 0
Input
4
-1 128 128 128
128 -1 148 160
128 148 -1 128
128 160 128 -1
Output
128 180 148 160
Note
If you do not know what is the "bitwise AND" operation please read: http://en.wikipedia.org/wiki/Bitwise_operation.
### Response
```cpp
#include <bits/stdc++.h>
int table[105][105];
unsigned int a[105];
unsigned int power2[32];
inline void set(int ind, int pos) { a[ind] = a[ind] | power2[pos]; }
inline bool is_set(int i, int j, int pos) {
if (table[i][j] & power2[pos])
return true;
else
return false;
}
void calc() {
int i;
power2[0] = 1;
for (i = 1; i < 32; i++) {
power2[i] = 2 * power2[i - 1];
}
}
int main() {
int n, i, j, k;
scanf("%d", &n);
calc();
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &table[i][j]);
}
}
for (i = 0; i < n; i++) a[i] = 0;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
for (k = 0; k < 32; k++) {
if (is_set(i, j, k)) {
set(i, k);
set(j, k);
}
}
}
}
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car.
Masha came to test these cars. She could climb into all cars, but she liked only the smallest car.
It's known that a character with size a can climb into some car with size b if and only if a β€ b, he or she likes it if and only if he can climb into this car and 2a β₯ b.
You are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars.
Input
You are given four integers V1, V2, V3, Vm(1 β€ Vi β€ 100) β sizes of father bear, mother bear, son bear and Masha, respectively. It's guaranteed that V1 > V2 > V3.
Output
Output three integers β sizes of father bear's car, mother bear's car and son bear's car, respectively.
If there are multiple possible solutions, print any.
If there is no solution, print "-1" (without quotes).
Examples
Input
50 30 10 10
Output
50
30
10
Input
100 50 10 21
Output
-1
Note
In first test case all conditions for cars' sizes are satisfied.
In second test case there is no answer, because Masha should be able to climb into smallest car (so size of smallest car in not less than 21), but son bear should like it, so maximum possible size of it is 20.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long MX = 1e10;
const int INF = 1e9 + 7;
const double EPS = 0.00000001;
int main() {
ios_base::sync_with_stdio(false);
int v1, v2, v3, vm;
cin >> v1 >> v2 >> v3 >> vm;
for (int i = 1; i <= 205; i++) {
for (int j = i + 1; j <= 205; j++) {
for (int k = j + 1; k <= 205; k++) {
if (i >= v3 && j >= v2 && k >= v1) {
if (i <= 2 * v3 && j <= 2 * v2 && k <= 2 * v1) {
if (i >= vm && j >= vm && k >= vm) {
if (i <= 2 * vm && j > 2 * vm && k > 2 * vm) {
cout << k << endl;
cout << j << endl;
cout << i << endl;
return 0;
}
}
}
}
}
}
}
cout << -1 << endl;
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Vasya owns three strings s , a and b, each of them consists only of first k Latin letters.
Let a template be such a string of length k that each of the first k Latin letters appears in it exactly once (thus there are k! distinct templates). Application of template p to the string s is the replacement of each character in string s with p_i, i is the index of this letter in the alphabet. For example, applying template "bdca" to a string "aabccd" yields string "bbdcca".
Vasya wants to know if there exists such a template which yields a string lexicographically greater than or equal to string a and lexicographically less than or equal to string b after applying it to s.
If there exist multiple suitable templates, print any of them.
String a is lexicographically less than string b if there is some i (1 β€ i β€ n) that a_i < b_i and for any j (1 β€ j < i) a_j = b_j.
You are required to answer t testcases independently.
Input
The first line contains a single integer t (1 β€ t β€ 10^6) β the number of testcases.
In hacks you can only use t = 1.
Each of the next t lines contains the description of the testcase in the following form:
The first line of the testcase contains a single integer k (1 β€ k β€ 26) β the length of the template.
The second line of the testcase contains the string s (1 β€ |s| β€ 10^6).
The third line of the testcase contains the string a.
The fourth line of the testcase contains the string b.
Strings s, a and b have the same length (|s| = |a| = |b|) and consist only of the first k Latin letters, all letters are lowercase.
It is guaranteed that string a is lexicographically less than or equal to string b.
It is also guaranteed that the total length of strings over all testcase won't exceed 3 β
10^6.
Output
Print the answers to all testcases in the following form:
If there exists no suitable template then print "NO" in the first line.
Otherwise print "YES" in the first line and the template itself in the second line (k lowercase letters, each of the first k Latin letters should appear exactly once).
If there exist multiple suitable templates, print any of them.
Example
Input
2
4
bbcb
aada
aada
3
abc
bbb
bbb
Output
YES
badc
NO
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
string s, a, b;
int n, k;
int t;
bool vis[26];
int ans[26];
bool dfs(int pos, bool lower, bool upper) {
if (pos >= n || (!lower && !upper)) return true;
if (ans[s[pos] - 'a'] != -1) {
if (lower && ans[s[pos] - 'a'] < a[pos]) return false;
if (upper && ans[s[pos] - 'a'] > b[pos]) return false;
return dfs(pos + 1, lower && (ans[s[pos] - 'a'] == a[pos]),
upper && (ans[s[pos] - 'a'] == b[pos]));
} else {
for (int j = 0; j < k; ++j) {
if (vis[j]) continue;
if (lower && j < a[pos] - 'a') continue;
if (upper && j > b[pos] - 'a') continue;
vis[j] = 1;
ans[s[pos] - 'a'] = j + 'a';
if (dfs(pos + 1, lower && (ans[s[pos] - 'a'] == a[pos]),
upper && (ans[s[pos] - 'a'] == b[pos])))
return true;
vis[j] = 0;
ans[s[pos] - 'a'] = -1;
}
}
return false;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> t;
while (t--) {
cin >> k;
cin >> s >> a >> b;
n = s.length();
memset(vis, 0, sizeof(vis));
memset(ans, -1, sizeof(ans));
if (!dfs(0, true, true)) {
cout << "NO" << endl;
continue;
}
int j = 0;
for (int i = 0; i < k; ++i) {
if (ans[i] == -1) {
while (vis[j]) j++;
ans[i] = j + 'a';
vis[j] = 1;
}
}
cout << "YES\n";
for (int i = 0; i < k; ++i) cout << char(ans[i]);
cout << "\n";
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
There was an electronic store heist last night.
All keyboards which were in the store yesterday were numbered in ascending order from some integer number x. For example, if x = 4 and there were 3 keyboards in the store, then the devices had indices 4, 5 and 6, and if x = 10 and there were 7 of them then the keyboards had indices 10, 11, 12, 13, 14, 15 and 16.
After the heist, only n keyboards remain, and they have indices a_1, a_2, ..., a_n. Calculate the minimum possible number of keyboards that have been stolen. The staff remember neither x nor the number of keyboards in the store before the heist.
Input
The first line contains single integer n (1 β€ n β€ 1 000) β the number of keyboards in the store that remained after the heist.
The second line contains n distinct integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{9}) β the indices of the remaining keyboards. The integers a_i are given in arbitrary order and are pairwise distinct.
Output
Print the minimum possible number of keyboards that have been stolen if the staff remember neither x nor the number of keyboards in the store before the heist.
Examples
Input
4
10 13 12 8
Output
2
Input
5
7 5 6 4 8
Output
0
Note
In the first example, if x=8 then minimum number of stolen keyboards is equal to 2. The keyboards with indices 9 and 11 were stolen during the heist.
In the second example, if x=4 then nothing was stolen during the heist.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void fastio() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
}
int main() {
fastio();
long long int a, b;
long long int mx = INT_MIN;
long long int n, mn = INT_MAX;
cin >> n;
long long int ar[n];
for (int i = 0; i < n; i++) {
cin >> ar[i];
mn = min(mn, ar[i]);
mx = max(ar[i], mx);
}
long long int res = mx - mn + 1;
cout << res - n;
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
Welcome to PC Koshien, players. Physical condition management is important to participate in the event. It is said that at the turn of the season when the temperature fluctuates greatly, it puts a strain on the body and it is easy to catch a cold. The day you should be careful about is the day when the difference between the maximum temperature and the minimum temperature is the largest. When the maximum and minimum temperatures of a day are given for 7 days, create a program that outputs the value obtained by subtracting the minimum temperature from the maximum temperature for each day.
input
Input data is given in the following format.
a1 b1
a2 b2
::
a7 b7
The input consists of 7 lines, and line i is given an integer representing the maximum temperature ai (-40 β€ ai β€ 40) and the minimum temperature bi (-40 β€ bi β€ 40) on day i. On all days, the maximum temperature ai is always above the minimum temperature bi.
output
Output the temperature difference for 7 days in 7 lines.
Example
Input
30 19
39 20
19 18
25 20
22 21
23 10
10 -10
Output
11
19
1
5
1
13
20
### Response
```cpp
#include <iostream>
using namespace std;
int main() {
int a, b;
while (cin >> a >> b)
if (a < b)
cout << b - a << endl;
else
cout << a - b << endl;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day.
Input
The first line contains an integer n (3 β€ n β€ 10000), representing the number of hobbits.
Output
In the first output line print a number k β the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n.
Examples
Input
4
Output
3
1 2
1 3
2 3
Input
5
Output
3
1 2
1 3
2 3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<int> a[10005];
int main() {
int n, x, k = 0;
cin >> n;
x = (sqrt(1.0 + 8 * n) + 1) / 2;
cout << x << endl;
for (int i = 1; i <= x; i++)
for (int j = i + 1; j <= x; j++) a[i].push_back(++k), a[j].push_back(k);
for (int i = 1; i <= x; i++, cout << endl)
for (int j = 0; j < a[i].size(); j++) cout << a[i][j] << " ";
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".
Sereja needs to answer m queries, each of them is described by two integers li, ri (1 β€ li β€ ri β€ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.
You can find the definitions for a subsequence and a correct bracket sequence in the notes.
Input
The first line contains a sequence of characters s1, s2, ..., sn (1 β€ n β€ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 β€ m β€ 105) β the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 β€ li β€ ri β€ n) β the description of the i-th query.
Output
Print the answer to each question on a single line. Print the answers in the order they go in the input.
Examples
Input
())(())(())(
7
1 1
2 3
1 2
1 12
8 12
5 11
2 10
Output
0
0
2
10
4
6
6
Note
A subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 β€ k1 < k2 < ... < k|x| β€ |s|).
A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.
For the third query required sequence will be Β«()Β».
For the fourth query required sequence will be Β«()(())(())Β».
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 7;
struct node {
int l, r;
int a, b, sum;
node operator+(const node m) {
node ans;
int minn = min(a, m.b);
ans.sum = sum + m.sum + minn * 2;
ans.a = a + m.a - minn;
ans.b = b + m.b - minn;
return ans;
}
} tree[4 * N];
string s;
void push_up(int x) {
int minn = min(tree[x << 1].a, tree[x << 1 | 1].b);
tree[x].sum = tree[x << 1].sum + tree[x << 1 | 1].sum + minn * 2;
tree[x].a = tree[x << 1].a + tree[x << 1 | 1].a - minn;
tree[x].b = tree[x << 1].b + tree[x << 1 | 1].b - minn;
}
void build(int x, int l, int r) {
tree[x].l = l;
tree[x].r = r;
tree[x].a = tree[x].b = tree[x].sum = 0;
if (l == r) {
if (s[l - 1] == '(')
tree[x].a = 1;
else
tree[x].b = 1;
tree[x].sum = 0;
return;
}
int m = (l + r) / 2;
build(x << 1, l, m);
build(x << 1 | 1, m + 1, r);
push_up(x);
}
node query(int x, int l, int r) {
int L = tree[x].l, R = tree[x].r;
if (l <= L && R <= r) {
return tree[x];
}
int m = (L + R) / 2;
if (r <= m)
return query(x << 1, l, r);
else if (l > m)
return query(x << 1 | 1, l, r);
else
return query(x << 1, l, r) + query(x << 1 | 1, l, r);
}
int main() {
cin >> s;
build(1, 1, (int)s.length());
int q;
cin >> q;
while (q--) {
int l, r;
cin >> l >> r;
cout << query(1, l, r).sum << endl;
}
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).
Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.
The vertex v controls the vertex u (v β u) if and only if u is in the subtree of v and dist(v, u) β€ au.
Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.
Input
The first line contains single integer n (1 β€ n β€ 2Β·105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) β the integers written in the vertices.
The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 β€ pi β€ n, 1 β€ wi β€ 109) β the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1).
It is guaranteed that the given graph is a tree.
Output
Print n integers β the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.
Examples
Input
5
2 5 1 4 6
1 7
1 1
3 5
3 6
Output
1 0 1 0 0
Input
5
9 7 8 6 5
1 1
2 1
3 1
4 1
Output
4 3 2 1 0
Note
In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
static const int maxn = 2e5 + 5;
static const int logn = 19;
struct edge {
int v;
long long w;
edge(int vv = 0, long long ww = 0) : v(vv), w(ww) {}
};
struct node {
int f;
long long cost;
node(int ff = 0, long long costt = 0) : f(ff), cost(costt) {}
};
int tnode;
long long a[maxn];
vector<edge> graph[maxn];
node father[maxn][logn];
int depth[maxn];
int sz[maxn];
void dfs(int u = 1, int p = -1) {
for (int i = 1; i < logn; i++) {
node f = father[u][i - 1];
father[u][i].f = father[f.f][i - 1].f;
father[u][i].cost = father[f.f][i - 1].cost + father[u][i - 1].cost;
}
sz[u] = 1;
for (auto &it : graph[u]) {
int v = it.v;
long long w = it.w;
if (it.v == p) continue;
father[v][0] = {u, w};
depth[v] = depth[u] + 1;
dfs(v, u);
sz[u] += sz[v];
}
}
int chainNo, chainHead[maxn], chainInd[maxn], chainPos[maxn], chainSize[maxn],
baseArray[maxn], posBase[maxn], ptr, S, E;
void hld(int u = 1, int p = -1) {
if (chainHead[chainNo] == -1) chainHead[chainNo] = u;
chainInd[u] = chainNo;
ptr++;
posBase[u] = ptr;
int bigChild(-1), mx(-1);
for (auto &it : graph[u]) {
int v = it.v;
if (v == p) continue;
if (sz[v] > mx) mx = sz[v], bigChild = v;
}
if (bigChild != -1) hld(bigChild, u);
for (auto &it : graph[u]) {
int v = it.v;
if (v == p) continue;
if (bigChild != v) {
chainNo++;
hld(v, u);
}
}
}
int tree[maxn << 2];
void update(int n, int a, int b, int i, int j) {
if (a > b || a > j || b < i) return;
if (a >= i && b <= j) {
tree[n] += 1;
return;
}
int left = n << 1;
int right = left | 1;
int mid = (a + b) >> 1;
update(left, a, mid, i, j);
update(right, mid + 1, b, i, j);
}
int sum;
void query(int n, int a, int b, int pos) {
if (a > b || a > pos || b < pos) return;
sum += tree[n];
if (a >= pos && b <= pos) return;
int left = n << 1;
int right = left | 1;
int mid = (a + b) >> 1;
query(left, a, mid, pos);
query(right, mid + 1, b, pos);
}
void updatehld(int u, int v) {
int uChain, vChain = chainInd[v];
while (true) {
uChain = chainInd[u];
if (uChain == vChain) {
int l = posBase[v];
int r = posBase[u];
if (l > r) break;
update(1, S, E, l, r);
break;
}
int l = posBase[chainHead[uChain]];
int r = posBase[u];
update(1, S, E, l, r);
u = father[chainHead[uChain]][0].f;
}
}
void goup(int u, int cc) {
int v = u;
for (int i = logn - 1; i >= 0; i--) {
node ff = father[u][i];
if (ff.f != 0 && ff.cost <= cc) {
u = ff.f;
cc -= ff.cost;
}
}
if (v == u) return;
updatehld(father[v][0].f, u);
}
void init() {
ptr = 0;
chainNo = 0;
for (int i = 0; i < maxn; i++) {
chainHead[i] = -1;
}
}
int main() {
scanf("%d", &tnode);
for (int i = 1; i <= tnode; i++) scanf("%lld", a + i);
for (int u = 2; u <= tnode; u++) {
int v;
long long w;
scanf("%d %lld", &v, &w);
graph[u].push_back(edge(v, w));
graph[v].push_back(edge(u, w));
}
init();
depth[1] = 1;
dfs();
hld();
S = 1;
E = ptr;
for (int i = 2; i <= tnode; i++) goup(i, a[i]);
for (int i = 1; i <= tnode; i++) {
sum = 0;
query(1, S, E, posBase[i]);
printf("%d ", sum);
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.