text
stringlengths 424
69.5k
|
---|
### Prompt
Construct a cpp code solution to the problem outlined:
Fafa has an array A of n positive integers, the function f(A) is defined as <image>. He wants to do q queries of two types:
* 1 l r x β find the maximum possible value of f(A), if x is to be added to one element in the range [l, r]. You can choose to which element to add x.
* 2 l r x β increase all the elements in the range [l, r] by value x.
Note that queries of type 1 don't affect the array elements.
Input
The first line contains one integer n (3 β€ n β€ 105) β the length of the array.
The second line contains n positive integers a1, a2, ..., an (0 < ai β€ 109) β the array elements.
The third line contains an integer q (1 β€ q β€ 105) β the number of queries.
Then q lines follow, line i describes the i-th query and contains four integers ti li ri xi <image>.
It is guaranteed that at least one of the queries is of type 1.
Output
For each query of type 1, print the answer to the query.
Examples
Input
5
1 1 1 1 1
5
1 2 4 1
2 2 3 1
2 4 4 2
2 3 4 1
1 3 3 2
Output
2
8
Input
5
1 2 3 4 5
4
1 2 4 2
2 2 4 1
2 3 4 1
1 2 4 2
Output
6
10
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int inf = pow(10, 14), inf2 = pow(10, 12);
long long int n;
long long int arr[100005], diff[100005];
map<long long int, long long int> maxima, minima;
struct node {
long long int max1, min1;
};
node tr[7 * 100005];
node findSum(long long int qs, long long int qe, long long int ss,
long long int se, long long int si) {
long long int mid = (ss + se) >> 1;
node temp;
temp.max1 = -inf, temp.min1 = inf;
if (ss >= qs && se <= qe) {
return tr[si];
}
if (ss > se || ss > qe || se < qs) return temp;
node left, right;
left = findSum(qs, qe, ss, mid, 2 * si + 1);
right = findSum(qs, qe, mid + 1, se, 2 * si + 2);
temp.max1 = max(left.max1, right.max1);
temp.min1 = min(left.min1, right.min1);
return temp;
}
node findSumUtil(long long int qs, long long int qe) {
return findSum(qs, qe, 0, n - 2, 0);
}
void update(long long int ss, long long int se, long long int q,
long long int val, long long int si) {
if (se < q || ss > q || se < ss) return;
if (ss == se) {
tr[si].min1 = inf;
tr[si].max1 = -inf;
if (val > 0)
tr[si].min1 = val;
else if (val < 0)
tr[si].max1 = val;
else {
tr[si].max1 = 0, tr[si].min1 = 0;
}
return;
}
long long int mid = (ss + se) >> 1;
update(ss, mid, q, val, 2 * si + 1);
update(mid + 1, se, q, val, 2 * si + 2);
tr[si].max1 = max(tr[2 * si + 1].max1, tr[2 * si + 2].max1);
tr[si].min1 = min(tr[2 * si + 1].min1, tr[2 * si + 2].min1);
}
void createUtil(long long int ss, long long int se, long long int si) {
long long int mid = (ss + se) >> 1;
if (ss == se) {
tr[si].min1 = inf;
tr[si].max1 = -inf;
if (diff[ss] > 0)
tr[si].min1 = diff[ss];
else if (diff[ss] < 0)
tr[si].max1 = diff[ss];
else {
tr[si].max1 = 0, tr[si].min1 = 0;
}
return;
}
if (ss > se) return;
createUtil(ss, mid, 2 * si + 1);
createUtil(mid + 1, se, 2 * si + 2);
tr[si].max1 = max(tr[2 * si + 1].max1, tr[2 * si + 2].max1);
tr[si].min1 = min(tr[2 * si + 1].min1, tr[2 * si + 2].min1);
}
void createSegment(long long int n) {
long long int x = ceil(log(n) / log(2));
createUtil(0, n - 1, 0);
}
long long int findMaxima(long long int l, long long int r) {
auto it = maxima.upper_bound(l);
if (it == maxima.end()) return -1;
if (it->first >= r) return -1;
return it->first;
}
long long int findMinima(long long int l, long long int r) {
auto it = minima.upper_bound(l);
if (it == minima.end()) return -1;
if (it->first >= r) return -1;
return it->first;
}
long long int case2(long long int l, long long int r, long long int x) {
if (l > r) return -inf;
node res = findSumUtil(l, r);
long long int curr = -inf;
if (res.max1 > (-inf2)) {
curr = 2 * max(0ll, x - (long long int)(abs(res.max1)));
}
if (res.min1 < inf2) {
curr = max(curr, 2 * max(0ll, x - res.min1));
}
return curr;
}
void updateMaxMin(long long int i) {
if ((i == (n - 1)) or (i == 0)) return;
maxima.erase(i);
minima.erase(i);
if (diff[i - 1] <= 0 && diff[i] >= 0) maxima[i];
if (diff[i - 1] > 0 && diff[i] < 0) minima[i];
}
long long int changeSingle(long long int i, long long int x) {
if (i == 0) {
return abs(diff[i] + x) - abs(diff[i]);
}
if (i == (n - 1)) {
return abs(diff[i - 1] - x) - abs(diff[i - 1]);
}
return abs(diff[i] + x) + abs(diff[i - 1] - x) - abs(diff[i]) -
abs(diff[i - 1]);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n;
for (long long int i = 0; i < n; i += 1) cin >> arr[i];
long long int ans = 0;
for (long long int i = 0; i < n - 1; i += 1) {
diff[i] = arr[i] - arr[i + 1];
ans += abs(diff[i]);
}
for (long long int i = 1; i < n - 1; i += 1) {
if (diff[i - 1] <= 0 && diff[i] >= 0) maxima[i];
if (diff[i - 1] > 0 && diff[i] < 0) minima[i];
}
createSegment(n - 1);
long long int q, a, l, r, x;
cin >> q;
while (q--) {
cin >> a >> l >> r >> x;
l--, r--;
if (a == 2) {
maxima.erase(l - 1);
maxima.erase(r);
minima.erase(l - 1);
minima.erase(r);
if (r != (n - 1)) {
ans -= abs(diff[r]);
diff[r] += x;
ans += abs(diff[r]);
update(0, n - 2, r, diff[r], 0);
}
if (l != 0) {
ans -= abs(diff[l - 1]);
diff[l - 1] -= x;
ans += abs(diff[l - 1]);
update(0, n - 2, l - 1, diff[l - 1], 0);
}
updateMaxMin(l);
updateMaxMin(l - 1);
updateMaxMin(r);
updateMaxMin(r + 1);
} else {
if ((r - l) <= 100) {
if (l == r) {
cout << changeSingle(l, x) + ans << endl;
continue;
}
long long int val = -inf;
for (long long int i = l; i < r + 1; i += 1) {
long long int curr = changeSingle(i, x);
val = max(val, curr);
}
cout << val + ans << endl;
continue;
}
long long int localMax = findMaxima(l, r);
if (localMax != -1) {
cout << (ans + 2 * x) << endl;
continue;
}
long long int localMin = findMinima(l, r);
if (localMin == -1) {
long long int curr = case2(l + 1, r - 1, x);
curr = max(curr, max(changeSingle(l, x), changeSingle(r, x)));
for (long long int i = l; i < l + 5; i += 1)
curr = max(curr, changeSingle(i, x));
for (long long int j = r; j > (r - 5); j--)
curr = max(curr, changeSingle(j, x));
cout << curr + ans << endl;
} else {
long long int curr = -inf, i = localMin;
long long int val1 = min(abs(diff[i - 1]), abs(diff[i]));
long long int val2 = max(abs(diff[i - 1]), abs(diff[i]));
curr = 2 * max(0ll, x - val2) - 2 * min(x, val1);
curr = max(curr, max(changeSingle(l, x), changeSingle(r, x)));
curr = max(curr, max(case2(l + 1, localMin - 2, x),
case2(localMin + 1, r - 1, x)));
for (long long int i = l; i < l + 5; i += 1)
curr = max(curr, changeSingle(i, x));
for (long long int j = r; j > (r - 5); j--)
curr = max(curr, changeSingle(j, x));
cout << curr + ans << endl;
}
}
}
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Paul is at the orchestra. The string section is arranged in an r Γ c rectangular grid and is filled with violinists with the exception of n violists. Paul really likes violas, so he would like to take a picture including at least k of them. Paul can take a picture of any axis-parallel rectangle in the orchestra. Count the number of possible pictures that Paul can take.
Two pictures are considered to be different if the coordinates of corresponding rectangles are different.
Input
The first line of input contains four space-separated integers r, c, n, k (1 β€ r, c, n β€ 10, 1 β€ k β€ n) β the number of rows and columns of the string section, the total number of violas, and the minimum number of violas Paul would like in his photograph, respectively.
The next n lines each contain two integers xi and yi (1 β€ xi β€ r, 1 β€ yi β€ c): the position of the i-th viola. It is guaranteed that no location appears more than once in the input.
Output
Print a single integer β the number of photographs Paul can take which include at least k violas.
Examples
Input
2 2 1 1
1 2
Output
4
Input
3 2 3 3
1 1
3 1
2 2
Output
1
Input
3 2 3 2
1 1
3 1
2 2
Output
4
Note
We will use '*' to denote violinists and '#' to denote violists.
In the first sample, the orchestra looks as follows
*#
**
Paul can take a photograph of just the viola, the 1 Γ 2 column containing the viola, the 2 Γ 1 row containing the viola, or the entire string section, for 4 pictures total.
In the second sample, the orchestra looks as follows
#*
*#
#*
Paul must take a photograph of the entire section.
In the third sample, the orchestra looks the same as in the second sample.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int r, c, n, k;
int calc(int x1, int x2, int y1, int y2, vector<string>& m) {
int res = 0;
for (int i = x1; i <= x2; i++)
for (int j = y1; j <= y2; j++)
if (m[i][j] == '*') res++;
return res;
}
int main() {
cin >> r >> c >> n >> k;
vector<string> m(r, string(c, '#'));
for (int i = 0; i < n; i++) {
int x, y;
cin >> x >> y;
m[x - 1][y - 1] = '*';
}
int res = 0;
for (int x1 = 0; x1 < r; x1++)
for (int y1 = 0; y1 < c; y1++)
for (int x2 = x1; x2 < r; x2++)
for (int y2 = y1; y2 < c; y2++) {
if (calc(x1, x2, y1, y2, m) >= k) res++;
}
cout << res;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together. He cannot do any other calculation.
Given are two integers A and B.
If Takahashi can calculate A \times B, print the result; if he cannot, print `-1` instead.
Constraints
* 1 \leq A \leq 20
* 1 \leq B \leq 20
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B
Output
If Takahashi can calculate A \times B, print the result; if he cannot, print `-1`.
Examples
Input
2 5
Output
10
Input
5 10
Output
-1
Input
9 9
Output
81
### Response
```cpp
#include<bits/stdc++.h>
int main()
{
int a,b;
std::cin>>a>>b;
std::cout<<(a<10&&b<10?a*b:-1)<<std::endl;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
To become a millionaire, M-kun has decided to make money by trading in the next N days. Currently, he has 1000 yen and no stocks - only one kind of stock is issued in the country where he lives.
He is famous across the country for his ability to foresee the future. He already knows that the price of one stock in the next N days will be as follows:
* A_1 yen on the 1-st day, A_2 yen on the 2-nd day, ..., A_N yen on the N-th day.
In the i-th day, M-kun can make the following trade any number of times (possibly zero), within the amount of money and stocks that he has at the time.
* Buy stock: Pay A_i yen and receive one stock.
* Sell stock: Sell one stock for A_i yen.
What is the maximum possible amount of money that M-kun can have in the end by trading optimally?
Constraints
* 2 \leq N \leq 80
* 100 \leq A_i \leq 200
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 \cdots A_N
Output
Print the maximum possible amount of money that M-kun can have in the end, as an integer.
Examples
Input
7
100 130 130 130 115 115 150
Output
1685
Input
6
200 180 160 140 120 100
Output
1000
Input
2
157 193
Output
1216
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
long long ans = 1000;
for (int i = 0; i < n - 1; i++)
{
if(a[i] < a[i + 1])ans += (a[i + 1] - a[i]) * (ans / a[i]);
}
cout << ans << endl;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
You are given n segments on a coordinate line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.
Your task is the following: for every k β [1..n], calculate the number of points with integer coordinates such that the number of segments that cover these points equals k. A segment with endpoints l_i and r_i covers point x if and only if l_i β€ x β€ r_i.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of segments.
The next n lines contain segments. The i-th line contains a pair of integers l_i, r_i (0 β€ l_i β€ r_i β€ 10^{18}) β the endpoints of the i-th segment.
Output
Print n space separated integers cnt_1, cnt_2, ..., cnt_n, where cnt_i is equal to the number of points such that the number of segments that cover these points equals to i.
Examples
Input
3
0 3
1 3
3 8
Output
6 2 1
Input
3
1 3
2 4
5 7
Output
5 2 0
Note
The picture describing the first example:
<image>
Points with coordinates [0, 4, 5, 6, 7, 8] are covered by one segment, points [1, 2] are covered by two segments and point [3] is covered by three segments.
The picture describing the second example:
<image>
Points [1, 4, 5, 6, 7] are covered by one segment, points [2, 3] are covered by two segments and there are no points covered by three segments.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
map<long long, long long> mp, ans;
int main(void) {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) {
long long in1, in2;
cin >> in1 >> in2;
mp[in1]++;
mp[in2 + 1]--;
}
long long now = 0;
for (map<long long, long long>::iterator it = mp.begin();
next(it) != mp.end(); it++) {
now += it->second;
long long l = it->first;
long long r = next(it)->first;
if (now > 0) ans[now] += r - l;
}
for (int i = 1; i <= n; i++) cout << ans[i] << " ";
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
Input
The first line contains a positive integer N (1 β€ N β€ 100 000), representing the length of the input array.
Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array.
The total number of characters in the input array will be less than 1 000 000.
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
Note
The first example:
1. aa + bb β abba.
The second example:
1. aab + abcac = aababcac β aabccbaa
2. aab + aa = aabaa
3. abcac + aa = abcacaa β aacbcaa
4. dffe + ed = dffeed β fdeedf
5. dffe + aade = dffeaade β adfaafde
6. ed + aade = edaade β aeddea
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
map<long long, int> st;
long long ans = 0;
for (int i = 0; i < n; i++) {
string str;
cin >> str;
int c[26];
for (int j = 0; j < 26; j++) c[j] = 0;
for (int j = 0; j < str.length(); j++) c[str[j] - 'a']++;
long long btv = 0;
for (int j = 0; j < 26; j++) {
btv *= 2;
btv += c[j] % 2;
}
ans += st[btv];
for (int j = 0; j < 26; j++) ans += st[btv ^ (1ll << j)];
st[btv]++;
}
cout << ans;
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
We have a string S of length N consisting of `R`, `G`, and `B`.
Find the number of triples (i,~j,~k)~(1 \leq i < j < k \leq N) that satisfy both of the following conditions:
* S_i \neq S_j, S_i \neq S_k, and S_j \neq S_k.
* j - i \neq k - j.
Constraints
* 1 \leq N \leq 4000
* S is a string of length N consisting of `R`, `G`, and `B`.
Input
Input is given from Standard Input in the following format:
N
S
Output
Print the number of triplets in question.
Examples
Input
4
RRGB
Output
1
Input
39
RBRBGRBGGBBRRGBBRRRBGGBRBGBRBGBRBBBGBBB
Output
1800
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int a,k;
string s;
cin>>a>>s;
long long color , l=0, r=0,g=0,b=0;
for(int i=0;i<a;i++){
if(s.at(i)=='R')r++;
else if(s.at(i)=='G')g++;
else b++;
}
color=r*g*b;
for(int i=0;i<a;i++){
for(int j=i+1;j<a;j++){
k=2*j-i;
if(k>=a || s.at(i)==s.at(k) || s.at(j)==s.at(k) || s.at(i)==s.at(j))continue;
l++;
}
}
cout <<color - l<<endl;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem.
We define function f(x, l, r) as a bitwise OR of integers xl, xl + 1, ..., xr, where xi is the i-th element of the array x. You are given two arrays a and b of length n. You need to determine the maximum value of sum f(a, l, r) + f(b, l, r) among all possible 1 β€ l β€ r β€ n.
<image>
Input
The first line of the input contains a single integer n (1 β€ n β€ 1000) β the length of the arrays.
The second line contains n integers ai (0 β€ ai β€ 109).
The third line contains n integers bi (0 β€ bi β€ 109).
Output
Print a single integer β the maximum value of sum f(a, l, r) + f(b, l, r) among all possible 1 β€ l β€ r β€ n.
Examples
Input
5
1 2 4 3 2
2 3 3 12 1
Output
22
Input
10
13 2 7 11 8 4 9 8 5 1
5 7 18 9 2 3 0 11 8 6
Output
46
Note
Bitwise OR of two non-negative integers a and b is the number c = a OR b, such that each of its digits in binary notation is 1 if and only if at least one of a or b have 1 in the corresponding position in binary notation.
In the first sample, one of the optimal answers is l = 2 and r = 4, because f(a, 2, 4) + f(b, 2, 4) = (2 OR 4 OR 3) + (3 OR 3 OR 12) = 7 + 15 = 22. Other ways to get maximum value is to choose l = 1 and r = 4, l = 1 and r = 5, l = 2 and r = 4, l = 2 and r = 5, l = 3 and r = 4, or l = 3 and r = 5.
In the second sample, the maximum value is obtained for l = 1 and r = 9.
### Response
```cpp
#include <bits/stdc++.h>
const double EPS = 1e-6;
const int INF = 0x3fffffff;
const long long LINF = INF * 1ll * INF;
const double PI = acos(-1.0);
using namespace std;
int A[1005];
int B[1005];
int preA[1005];
int preB[1005];
int main() {
int n;
A[0] = B[0] = 1;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> A[i];
preA[i] = preA[i - 1] | A[i];
}
for (int i = 1; i <= n; i++) {
cin >> B[i];
preB[i] = preB[i - 1] | B[i];
}
int ans = 0;
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j++) {
int tempA = preA[j] | preA[i] | A[i];
int tempB = preB[j] | preB[i] | B[i];
ans = max(ans, tempA + tempB);
}
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Andrey needs one more problem to conduct a programming contest. He has n friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends β the probability that this friend will come up with a problem if Andrey asks him.
Help Andrey choose people to ask. As he needs only one problem, Andrey is going to be really upset if no one comes up with a problem or if he gets more than one problem from his friends. You need to choose such a set of people that maximizes the chances of Andrey not getting upset.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of Andrey's friends. The second line contains n real numbers pi (0.0 β€ pi β€ 1.0) β the probability that the i-th friend can come up with a problem. The probabilities are given with at most 6 digits after decimal point.
Output
Print a single real number β the probability that Andrey won't get upset at the optimal choice of friends. The answer will be considered valid if it differs from the correct one by at most 10 - 9.
Examples
Input
4
0.1 0.2 0.3 0.8
Output
0.800000000000
Input
2
0.1 0.2
Output
0.260000000000
Note
In the first sample the best strategy for Andrey is to ask only one of his friends, the most reliable one.
In the second sample the best strategy for Andrey is to ask all of his friends to come up with a problem. Then the probability that he will get exactly one problem is 0.1Β·0.8 + 0.9Β·0.2 = 0.26.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n;
double m[101], s = 0, pr = 1, sn = 0, answer;
int main() {
cin >> n;
for (int i = 1; i <= n; ++i) cin >> m[i];
sort(&m[1], &m[n + 1]);
if (m[n] == 1)
answer = 1;
else {
for (int i = n; i > 0; --i) {
if (s < 1) {
s += m[i] / (1 - m[i]);
pr *= (1 - m[i]);
} else
break;
}
answer = s * pr;
}
cout << fixed;
cout.precision(12);
cout << answer;
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
You are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n.
A path from u to v is a sequence of edges such that:
* vertex u is the start of the first edge in the path;
* vertex v is the end of the last edge in the path;
* for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on.
We will assume that the empty sequence of edges is a path from u to u.
For each vertex v output one of four values:
* 0, if there are no paths from 1 to v;
* 1, if there is only one path from 1 to v;
* 2, if there is more than one path from 1 to v and the number of paths is finite;
* -1, if the number of paths from 1 to v is infinite.
Let's look at the example shown in the figure.
<image>
Then:
* the answer for vertex 1 is 1: there is only one path from 1 to 1 (path with length 0);
* the answer for vertex 2 is 0: there are no paths from 1 to 2;
* the answer for vertex 3 is 1: there is only one path from 1 to 3 (it is the edge (1, 3));
* the answer for vertex 4 is 2: there are more than one paths from 1 to 4 and the number of paths are finite (two paths: [(1, 3), (3, 4)] and [(1, 4)]);
* the answer for vertex 5 is -1: the number of paths from 1 to 5 is infinite (the loop can be used in a path many times);
* the answer for vertex 6 is -1: the number of paths from 1 to 6 is infinite (the loop can be used in a path many times).
Input
The first contains an integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line.
The first line of the test case contains two integers n and m (1 β€ n β€ 4 β
10^5, 0 β€ m β€ 4 β
10^5) β numbers of vertices and edges in graph respectively. The next m lines contain edges descriptions. Each line contains two integers a_i, b_i (1 β€ a_i, b_i β€ n) β the start and the end of the i-th edge. The vertices of the graph are numbered from 1 to n. The given graph can contain loops (it is possible that a_i = b_i), but cannot contain multi-edges (it is not possible that a_i = a_j and b_i = b_j for i β j).
The sum of n over all test cases does not exceed 4 β
10^5. Similarly, the sum of m over all test cases does not exceed 4 β
10^5.
Output
Output t lines. The i-th line should contain an answer for the i-th test case: a sequence of n integers from -1 to 2.
Example
Input
5
6 7
1 4
1 3
3 4
4 5
2 1
5 5
5 6
1 0
3 3
1 2
2 3
3 1
5 0
4 4
1 2
2 3
1 4
4 3
Output
1 0 1 2 -1 -1
1
-1 -1 -1
1 0 0 0 0
1 1 2 1
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
typedef int64_t ll;
typedef uint64_t ull;
typedef long double ld;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll>vll;
#define sf scanf
#define pf printf
#define nl printf("\n")
#define si(x) scanf("%d",&x)
#define sii(x,y) scanf("%d%d",&x,&y)
#define siii(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define sl(x) scanf("%lld",&x)
#define sll(x,y) scanf("%lld%lld",&x,&y)
#define slll(x,y,z) scanf("%lld%lld%lld",&x,&y,&z)
#define FOR(i,n) for(int i=0;i<n;i++)
#define sz(x) (int)x.size()
#define all(x) x.begin(),x.end()
#define chk cerr<<"CAME HERE"<<endl
#define dbug(x) cerr<<"value of "<<#x<<" = "<<x<<endl
#define popcount(x) __builtin_popcount(x)
#define popcountll(x) __builtin_popcountll(x)
mt19937 rng((uint64_t) chrono::duration_cast<chrono::nanoseconds>(chrono::high_resolution_clock::now().time_since_epoch()).count());
inline int rand(int l, int r){uniform_int_distribution<int> RNG(l,r);return RNG(rng);}
const int N = 4e5+5;
vector<int>graph[N],dag[N],rgraph[N];
int discovery_time[N],parent[N];
int Time=0,scc=0;
stack<int>curTree;
bool inTree[N]={0};
bool selfloop[N]={0};
bool cmploop[N]={0};
ll cnt2[N]={0},cnt[N]={0};
pll dp[N];
void resetAll(int n){
while(!curTree.empty())curTree.pop();
for(int i=0; i<=n; i++){
discovery_time[i]=0;
selfloop[i]=0;
parent[i]=0;
cnt[i]=0;
cmploop[i]=0;
graph[i].clear();
rgraph[i].clear();
dag[i].clear();
cnt2[i]=0;
dp[i]={-1,0};
}
Time=0;
scc=1;
}
int tarjan_scc(int u){
int low=discovery_time[u]=++Time;
curTree.push(u);
inTree[u]=1;
for(int v:graph[u])
if(!discovery_time[v])
low=min(low,tarjan_scc(v));
else if(inTree[v])
low=min(low,discovery_time[v]);
if(low==discovery_time[u]){
int top;
do{
top=curTree.top();
cnt[scc]++;
curTree.pop();
inTree[top]=0;
parent[top]=scc;
}while(u!=top && !curTree.empty());
scc++;
}
return low;
}
int target;
pll f(int u){
if(u==target)return pll(1,cmploop[u] || cnt[u]>1);
pll &ret = dp[u];
if(ret.first!=-1)return ret;
ret=pll(0,cmploop[u] || cnt[u]>1);
for(int v:rgraph[u]){
pll x = f(v);
ret.first+=x.first;
if(x.first>0)ret.second|=x.second;
if(ret.first>=2)ret.first=2;
}
return ret;
}
void solve(int casenum){
int n,m;
sii(n,m);
if(casenum==1)resetAll(n);
for(int i=0,u,v; i<m; i++){
sii(u,v);
if(u==v)selfloop[u]=1;
else{
graph[u].push_back(v);
}
}
for(int i=1; i<=n; i++)if(!discovery_time[i])tarjan_scc(i);
for(int i=1; i<=n; i++){
if(selfloop[i])cmploop[parent[i]]=1;
for(int v:graph[i]){
if(parent[i]!=parent[v]){
dag[parent[i]].push_back(parent[v]);
rgraph[parent[v]].push_back(parent[i]);
}
}
}
target=parent[1];
for(int i=1; i<=n; i++){
int x = parent[i];
//pf("zzfsd %d %d %d %d %d\n",i,parent[i],cnt[x],cnt2[x],cnt3[x]);
pll p = f(x);
if(p.first==0)pf("0 ");
else {
if(p.second || cmploop[x])pf("-1 ");
else if(p.first>1)pf("2 ");
else pf("1 ");
}
}
nl;
resetAll(n);
}
int main(){
//ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
int T=1;
scanf("%d",&T);
//cin>>T;
for(int i=1; i<=T; i++)
solve(i);
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
There are N robots and M exits on a number line. The N + M coordinates of these are all integers and all distinct. For each i (1 \leq i \leq N), the coordinate of the i-th robot from the left is x_i. Also, for each j (1 \leq j \leq M), the coordinate of the j-th exit from the left is y_j.
Snuke can repeatedly perform the following two kinds of operations in any order to move all the robots simultaneously:
* Increment the coordinates of all the robots on the number line by 1.
* Decrement the coordinates of all the robots on the number line by 1.
Each robot will disappear from the number line when its position coincides with that of an exit, going through that exit. Snuke will continue performing operations until all the robots disappear.
When all the robots disappear, how many combinations of exits can be used by the robots? Find the count modulo 10^9 + 7. Here, two combinations of exits are considered different when there is a robot that used different exits in those two combinations.
Constraints
* 1 \leq N, M \leq 10^5
* 1 \leq x_1 < x_2 < ... < x_N \leq 10^9
* 1 \leq y_1 < y_2 < ... < y_M \leq 10^9
* All given coordinates are integers.
* All given coordinates are distinct.
Input
Input is given from Standard Input in the following format:
N M
x_1 x_2 ... x_N
y_1 y_2 ... y_M
Output
Print the number of the combinations of exits that can be used by the robots when all the robots disappear, modulo 10^9 + 7.
Examples
Input
2 2
2 3
1 4
Output
3
Input
3 4
2 5 10
1 3 7 13
Output
8
Input
4 1
1 2 4 5
3
Output
1
Input
4 5
2 5 7 11
1 3 6 9 13
Output
6
Input
10 10
4 13 15 18 19 20 21 22 25 27
1 5 11 12 14 16 23 26 29 30
Output
22
### Response
```cpp
#include<algorithm>
#include<cstdio>
#define N 100001
#define p 1000000007
using namespace std;
inline int mod(int x){return x<p?x:x-p;}
int a[N],b[N],c[N],d[N],e[N],f[N],i,j,m,n,s,t,x;
inline bool cmpd(int u,int v){return d[u]<d[v];}
inline bool cmpc(int u,int v){return c[u]==c[v]?d[v]<d[u]:c[u]<c[v];}
inline void add(int u,int v){while(u<=j)f[u]=mod(f[u]+v),u+=u&-u;}
inline int sum(int u)
{
int v=0;
while(u)v=mod(v+f[u]),u^=u&-u;
return v;
}
int main()
{
scanf("%d%d",&m,&n);
for(i=1;i<=m;i++)scanf("%d",a+i);
for(i=1;i<=n;i++)scanf("%d",b+i);
for(i=1,j=0;i<=m;j&&j<n?c[++t]=a[i]-b[j],d[t]=b[j+1]-a[i],e[t]=t:0,i++)while(j<n&&b[j+1]<a[i])j++;
for(sort(e+1,e+t+1,cmpd),i=1,j=0;i<=t;i++)d[e[i]]=d[e[i]]!=j?j=d[e[i]],d[e[i-1]]+1:d[e[i-1]];
for(j=d[e[t]],sort(e+1,e+t+1,cmpc),i=x=1;i<=t;i++)if(c[e[i]]!=c[e[i-1]]||d[e[i]]!=d[e[i-1]])s=mod(sum(d[e[i]]-1)+1),x=mod(x+s),add(d[e[i]],s);
return 0&printf("%d\n",x);
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a) to the end of a. For example, <image>.
* Remove the first character of a. For example, <image>. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Input
The first line contains the string a and the second line contains the string b (1 β€ |a|, |b| β€ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
Output
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
Examples
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
Note
In the first sample, the steps are as follows: 01011 β 1011 β 011 β 0110
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string a, b;
int A = 0, B = 0, mx, i;
cin >> a >> b;
for (i = 0; i < a.size(); i++)
if (a[i] == '1') A++;
for (i = 0; i < b.size(); i++)
if (b[i] == '1') B++;
mx = A + (A % 2);
if (mx >= B)
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and the contest is not carried out;
2. on this day the gym is closed and the contest is carried out;
3. on this day the gym is open and the contest is not carried out;
4. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the number of days of Vasya's vacations.
The second line contains the sequence of integers a1, a2, ..., an (0 β€ ai β€ 3) separated by space, where:
* ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;
* ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;
* ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;
* ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.
Output
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
* to do sport on any two consecutive days,
* to write the contest on any two consecutive days.
Examples
Input
4
1 3 2 0
Output
2
Input
7
1 3 3 2 1 2 3
Output
0
Input
2
2 2
Output
1
Note
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[102], dp[102][5];
int main() {
ios::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
dp[0][0] = 0;
dp[0][1] = 0;
dp[2][0] = 0;
for (int i = 1; i <= n; i++) {
dp[i][0] = max(dp[i - 1][0], max(dp[i - 1][1], dp[i - 1][2]));
if (a[i] == 1 || a[i] == 3) {
dp[i][1] = max(dp[i - 1][0], dp[i - 1][2]) + 1;
} else
dp[i][1] = dp[i - 1][1];
if (a[i] == 2 || a[i] == 3) {
dp[i][2] = max(dp[i - 1][0], dp[i - 1][1]) + 1;
} else
dp[i][2] = dp[i - 1][2];
}
cout << (n - max(dp[n][0], max(dp[n][1], dp[n][2]))) << '\n';
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Suppose you are given a sequence S of k pairs of integers (a_1, b_1), (a_2, b_2), ..., (a_k, b_k).
You can perform the following operations on it:
1. Choose some position i and increase a_i by 1. That can be performed only if there exists at least one such position j that i β j and a_i = a_j. The cost of this operation is b_i;
2. Choose some position i and decrease a_i by 1. That can be performed only if there exists at least one such position j that a_i = a_j + 1. The cost of this operation is -b_i.
Each operation can be performed arbitrary number of times (possibly zero).
Let f(S) be minimum possible x such that there exists a sequence of operations with total cost x, after which all a_i from S are pairwise distinct.
Now for the task itself ...
You are given a sequence P consisting of n pairs of integers (a_1, b_1), (a_2, b_2), ..., (a_n, b_n). All b_i are pairwise distinct. Let P_i be the sequence consisting of the first i pairs of P. Your task is to calculate the values of f(P_1), f(P_2), ..., f(P_n).
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of pairs in sequence P.
Next n lines contain the elements of P: i-th of the next n lines contains two integers a_i and b_i (1 β€ a_i β€ 2 β
10^5, 1 β€ b_i β€ n). It is guaranteed that all values of b_i are pairwise distinct.
Output
Print n integers β the i-th number should be equal to f(P_i).
Examples
Input
5
1 1
3 3
5 5
4 2
2 4
Output
0
0
0
-5
-16
Input
4
2 4
2 3
2 2
1 1
Output
0
3
7
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long kq, cd, p[500005], cur, mn[500005], done[500005];
long long aug[500005], red[500005];
vector<pair<long long, long long> > block[500005];
struct custom_hash {
size_t operator()(long long x) const { return x; }
};
unordered_map<long long, pair<long long, long long> > a[500005];
pair<long long, long long> get(long long u, long long i) {
pair<long long, long long> kq = pair<long long, long long>(0, 0);
while (i > 0) {
if (a[u].find(i) != a[u].end())
kq.first += a[u][i].first, kq.second += a[u][i].second;
i -= i & -i;
}
return kq;
}
void update(long long u, long long i, long long val) {
while (i <= cd) a[u][i].first += val, a[u][i].second += 1, i += i & -i;
}
long long dad(long long u) {
while (p[u] != 0) u = p[u];
return u;
}
void add(long long u, pair<long long, long long> key) {
long long val = key.first, v = key.second;
pair<long long, long long> sp = get(u, val);
kq -= (-red[u] + aug[u]);
if (block[u].size() == 0) mn[u] = v;
if (mn[u] > v) red[u] += get(u, cd).first * (mn[u] - v), mn[u] = v;
red[u] += val * (v - mn[u]);
aug[u] += val * (block[u].size() - sp.second) + sp.first;
kq += (-red[u] + aug[u]);
update(u, val, val);
block[u].push_back(key);
done[mn[u] + block[u].size() - 1] = 1;
if (mn[u] + block[u].size() - 1 != u) p[mn[u] + block[u].size() - 1] = u;
}
void fused(long long u, long long v) {
if (block[u].size() < block[v].size()) swap(u, v);
p[v] = u;
if (block[v].size() == 0) return;
kq -= (-red[v] + aug[v]);
for (auto x : block[v]) add(u, x);
long long nx = mn[u] + block[u].size();
long long dadnx = dad(nx);
if (done[nx] == 1 && dadnx != u) fused(u, dadnx);
}
void inp() { cin >> cd; }
void do_it() {
long long u, v;
for (long long i = 1; i <= cd; i++) {
cin >> u >> v;
done[u] = 1;
if (u != 1 && done[u - 1] != 0) {
long long dadu = dad(u), dadu1 = dad(u - 1);
if (dadu != dadu1) fused(dadu, dadu1);
}
if (u != cd && done[u + 1] != 0) {
long long dadu = dad(u), dadu1 = dad(u + 1);
if (dadu != dadu1) fused(dadu, dadu1);
}
add(dad(u), pair<long long, long long>(v, u));
long long dadu = dad(u);
long long nx = mn[dadu] + block[dadu].size();
long long dadnx = dad(nx);
if (done[nx] == 1 && dadnx != dadu) fused(dadu, dadnx);
cout << kq << '\n';
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
inp();
do_it();
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
You are given n points on the plane. You need to delete exactly k of them (k < n) so that the diameter of the set of the remaining n - k points were as small as possible. The diameter of a set of points is the maximum pairwise distance between the points of the set. The diameter of a one point set equals zero.
Input
The first input line contains a pair of integers n, k (2 β€ n β€ 1000, 1 β€ k β€ 30, k < n) β the numbers of points on the plane and the number of points to delete, correspondingly.
Next n lines describe the points, one per line. Each description consists of a pair of integers xi, yi (0 β€ xi, yi β€ 32000) β the coordinates of the i-th point. The given points can coincide.
Output
Print k different space-separated integers from 1 to n β the numbers of points to delete. The points are numbered in the order, in which they are given in the input from 1 to n. You can print the numbers in any order. If there are multiple solutions, print any of them.
Examples
Input
5 2
1 2
0 0
2 2
1 1
3 3
Output
5 2
Input
4 1
0 0
0 0
1 1
1 1
Output
3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct Point {
int x, y;
} p[1010];
int n, k, cnt, d[1000010], g[1010][1010], vis[1010];
vector<int> Map[1010];
int dis(int i, int j) {
return (p[i].x - p[j].x) * (p[i].x - p[j].x) +
(p[i].y - p[j].y) * (p[i].y - p[j].y);
}
bool dfs(int cnt, int m) {
if (cnt > n) return 1;
if (vis[cnt]) return dfs(cnt + 1, m);
int Len = Map[cnt].size();
for (int(i) = (0); (i) <= (Len - 1); (i)++) {
m += !vis[Map[cnt][i]];
vis[Map[cnt][i]]++;
}
if (m <= k && dfs(cnt + 1, m)) return 1;
int temp = m;
for (int(i) = (0); (i) <= (Len - 1); (i)++) {
vis[Map[cnt][i]]--;
m -= !vis[Map[cnt][i]];
}
if (Map[cnt].size() != 1) {
vis[cnt]++;
if (m + 1 <= k && m + 1 < temp && dfs(cnt + 1, m + 1)) return true;
vis[cnt]--;
}
return false;
}
bool check(int Dis) {
memset(vis, 0, sizeof vis);
for (int(i) = (1); (i) <= (n); (i)++) Map[i].clear();
for (int(i) = (1); (i) <= (n); (i)++)
for (int(j) = (i + 1); (j) <= (n); (j)++)
if (g[i][j] > Dis) {
Map[i].push_back(j);
Map[j].push_back(i);
}
return dfs(1, 0);
}
int Two_Find(int left, int right) {
while (left < right) {
int mid = (left + right) >> 1;
if (check(d[mid]))
right = mid;
else
left = mid + 1;
}
return left;
}
int main() {
scanf("%d %d", &n, &k);
for (int(i) = (1); (i) <= (n); (i)++) scanf("%d %d", &p[i].x, &p[i].y);
for (int(i) = (1); (i) <= (n); (i)++)
for (int(j) = (1); (j) <= (n); (j)++) d[++cnt] = g[i][j] = dis(i, j);
sort(d, d + cnt + 1);
int num = unique(d, d + cnt + 1) - d - 1;
int mx = Two_Find(0, num);
check(d[mx]);
bool first = false;
for (int i = n; i >= 1; --i)
if (vis[i]) {
if (first) putchar(' ');
printf("%d", i);
k--;
first = true;
}
for (int i = n; i >= 1 && k > 0; --i)
if (!vis[i]) {
if (first) putchar(' ');
printf("%d", i);
k--;
first = true;
}
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
You are given three integers n, d and k.
Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible.
An undirected tree is a connected undirected graph with n - 1 edges.
Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.
Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree).
Input
The first line of the input contains three integers n, d and k (1 β€ n, d, k β€ 4 β
10^5).
Output
If there is no tree satisfying the conditions above, print only one word "NO" (without quotes).
Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1
Examples
Input
6 3 3
Output
YES
3 1
4 1
1 2
5 2
2 6
Input
6 2 3
Output
NO
Input
10 4 3
Output
YES
2 9
2 10
10 3
3 1
6 10
8 2
4 3
5 6
6 7
Input
8 5 3
Output
YES
2 5
7 2
3 7
3 1
1 6
8 7
4 3
### Response
```cpp
#include <bits/stdc++.h>
long long inf = 1LL << 62;
long long mod = 1000000007;
using namespace std;
int n, k, d, label;
int seen[400010], out[400010];
vector<int> g[400010];
void dfs(int cur, int depth) {
if (depth == 0 || label == n + 1 || seen[cur]) return;
seen[cur] = 1;
for (int i = 0; i < out[cur]; i++) {
if (label == n + 1) return;
g[cur].push_back(label);
g[label].push_back(cur);
out[label]--;
label++;
}
for (int i = 0; i < g[cur].size(); i++) {
if (!seen[g[cur][i]]) dfs(g[cur][i], depth - 1);
}
}
void print(int cur, int par) {
for (int i = 0; i < g[cur].size(); i++) {
if (g[cur][i] != par)
cout << cur << " " << g[cur][i] << endl, print(g[cur][i], cur);
}
}
int main(void) {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> d >> k;
if (d > n) {
cout << "NO";
return 0;
}
for (int i = 1; i <= n; i++) out[i] = k;
for (int i = 1; i <= d; i++) {
out[i]--, out[i + 1]--;
seen[i] = seen[i + 1] = 1;
if (out[i] < 0 || out[i + 1] < 0) {
cout << "NO";
return 0;
}
g[i].push_back(i + 1);
g[i + 1].push_back(i);
}
label = d + 2;
for (int i = 1; i <= d + 1; i++) {
int depth = min(i - 1, d + 1 - i);
if (label == n + 1) break;
seen[i] = 0;
dfs(i, depth);
}
if (label < n + 1) {
cout << "NO";
return 0;
}
cout << "YES\n";
print(1, 0);
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Polycarp likes numbers that are divisible by 3.
He has a huge number s. Polycarp wants to cut from it the maximum number of numbers that are divisible by 3. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after m such cuts, there will be m+1 parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by 3.
For example, if the original number is s=3121, then Polycarp can cut it into three parts with two cuts: 3|1|21. As a result, he will get two numbers that are divisible by 3.
Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.
What is the maximum number of numbers divisible by 3 that Polycarp can obtain?
Input
The first line of the input contains a positive integer s. The number of digits of the number s is between 1 and 2β
10^5, inclusive. The first (leftmost) digit is not equal to 0.
Output
Print the maximum number of numbers divisible by 3 that Polycarp can get by making vertical cuts in the given number s.
Examples
Input
3121
Output
2
Input
6
Output
1
Input
1000000000000000000000000000000000
Output
33
Input
201920181
Output
4
Note
In the first example, an example set of optimal cuts on the number is 3|1|21.
In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by 3.
In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and 33 digits 0. Each of the 33 digits 0 forms a number that is divisible by 3.
In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers 0, 9, 201 and 81 are divisible by 3.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int val(char ch) { return (ch - '0') % 3; }
int main() {
string s;
cin >> s;
int a[s.size()];
for (int i = 0; i < s.size(); i++) {
a[i] = val(s[i]);
}
int p = 0, c = 0;
map<int, int> m;
for (int i = 0; i < s.size(); i++) {
if (a[i] != 0) {
p += a[i];
if (p % 3 == 0 || m[(p % 3)] > 0) {
p = 0;
m.clear();
c++;
} else {
m[p % 3]++;
}
} else {
m.clear();
p = 0;
c++;
}
}
cout << c;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
The farmer Polycarp has a warehouse with hay, which can be represented as an n Γ m rectangular table, where n is the number of rows, and m is the number of columns in the table. Each cell of the table contains a haystack. The height in meters of the hay located in the i-th row and the j-th column is equal to an integer ai, j and coincides with the number of cubic meters of hay in the haystack, because all cells have the size of the base 1 Γ 1. Polycarp has decided to tidy up in the warehouse by removing an arbitrary integer amount of cubic meters of hay from the top of each stack. You can take different amounts of hay from different haystacks. Besides, it is allowed not to touch a stack at all, or, on the contrary, to remove it completely. If a stack is completely removed, the corresponding cell becomes empty and no longer contains the stack.
Polycarp wants the following requirements to hold after the reorganization:
* the total amount of hay remaining in the warehouse must be equal to k,
* the heights of all stacks (i.e., cells containing a non-zero amount of hay) should be the same,
* the height of at least one stack must remain the same as it was,
* for the stability of the remaining structure all the stacks should form one connected region.
The two stacks are considered adjacent if they share a side in the table. The area is called connected if from any of the stack in the area you can get to any other stack in this area, moving only to adjacent stacks. In this case two adjacent stacks necessarily belong to the same area.
Help Polycarp complete this challenging task or inform that it is impossible.
Input
The first line of the input contains three integers n, m (1 β€ n, m β€ 1000) and k (1 β€ k β€ 1018) β the number of rows and columns of the rectangular table where heaps of hay are lain and the required total number cubic meters of hay after the reorganization.
Then n lines follow, each containing m positive integers ai, j (1 β€ ai, j β€ 109), where ai, j is equal to the number of cubic meters of hay making the hay stack on the i-th row and j-th column of the table.
Output
In the first line print "YES" (without quotes), if Polycarpus can perform the reorganisation and "NO" (without quotes) otherwise. If the answer is "YES" (without quotes), then in next n lines print m numbers β the heights of the remaining hay stacks. All the remaining non-zero values should be equal, represent a connected area and at least one of these values shouldn't be altered.
If there are multiple answers, print any of them.
Examples
Input
2 3 35
10 4 9
9 9 7
Output
YES
7 0 7
7 7 7
Input
4 4 50
5 9 1 1
5 1 1 5
5 1 5 5
5 5 7 1
Output
YES
5 5 0 0
5 0 0 5
5 0 5 5
5 5 5 0
Input
2 4 12
1 1 3 1
1 6 2 4
Output
NO
Note
In the first sample non-zero values make up a connected area, their values do not exceed the initial heights of hay stacks. All the non-zero values equal 7, and their number is 5, so the total volume of the remaining hay equals the required value k = 7Β·5 = 35. At that the stack that is on the second line and third row remained unaltered.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<long long> dsu, sz;
vector<bool> used;
vector<vector<long long>> v;
void init(long long n) {
used.resize(n);
dsu.resize(n);
sz.resize(n, 1);
for (long long i = 0; i < n; i++) dsu[i] = i;
}
long long Find(long long a) {
return (dsu[a] == a ? a : dsu[a] = Find(dsu[a]));
}
void Unite(long long a, long long b) {
a = Find(a);
b = Find(b);
if (rand() % 2) swap(a, b);
dsu[b] = a;
sz[a] += sz[b];
}
void Add(long long a, long long n, long long m) {
long long c1 = -1, c2 = -1, c3 = -1, c4 = -1;
if (a % m > 0) c4 = a - 1;
if ((a + 1) % m > 0) c2 = a + 1;
if (a - m >= 0) c1 = a - m;
if (a + m < m * n) c3 = a + m;
used[a] = true;
if (c1 != -1 && used[c1] && Find(a) != Find(c1)) Unite(a, c1);
if (c2 != -1 && used[c2] && Find(a) != Find(c2)) Unite(a, c2);
if (c3 != -1 && used[c3] && Find(a) != Find(c3)) Unite(a, c3);
if (c4 != -1 && used[c4] && Find(a) != Find(c4)) Unite(a, c4);
}
long long delnow = 0, delall;
vector<bool> usedindfs;
void dfs(long long ver, long long n, long long m) {
usedindfs[ver] = true;
long long c1 = -1, c2 = -1, c3 = -1, c4 = -1;
if (ver % m > 0) c4 = ver - 1;
if ((ver + 1) % m > 0) c2 = ver + 1;
if (ver - m >= 0) c1 = ver - m;
if (ver + m < m * n) c3 = ver + m;
if (c1 != -1 && Find(c1) == Find(ver) && !usedindfs[c1]) dfs(c1, n, m);
if (c2 != -1 && Find(c2) == Find(ver) && !usedindfs[c2]) dfs(c2, n, m);
if (c3 != -1 && Find(c3) == Find(ver) && !usedindfs[c3]) dfs(c3, n, m);
if (c4 != -1 && Find(c4) == Find(ver) && !usedindfs[c4]) dfs(c4, n, m);
if (delnow < delall) {
v[ver / m][ver % m] = 0;
delnow++;
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long n, m, k;
cin >> n >> m >> k;
v.resize(n, vector<long long>(m));
init(n * m);
vector<pair<long long, long long>> lens;
for (long long i = 0; i < n; i++) {
for (long long j = 0; j < m; j++) {
cin >> v[i][j];
lens.push_back({v[i][j], i * m + j});
}
}
sort(lens.rbegin(), lens.rend());
vector<long long> eq;
long long len = -1, del = 0, delincomp = 0, ind;
for (long long i = 0; i < lens.size(); i++) {
if (i < lens.size() - 1 && lens[i].first == lens[i + 1].first) {
Add(lens[i].second, n, m);
eq.push_back(lens[i].second);
continue;
}
Add(lens[i].second, n, m);
eq.push_back(lens[i].second);
if (lens[i].first * (i + 1) < k) {
eq.clear();
continue;
}
if (lens[i].first * (i + 1) == k && sz[Find(lens[i].second)] == (i + 1)) {
len = lens[i].first;
break;
} else if (lens[i].first * (i + 1) == k || k % lens[i].first != 0) {
eq.clear();
continue;
}
long long delnum = i + 1 - k / lens[i].first;
bool flag = false;
for (long long j = 0; j < eq.size(); j++) {
if ((i + 1) - sz[Find(eq[j])] <= delnum) {
if ((i + 1) - sz[Find(eq[j])] < delnum)
delincomp = delnum - ((i + 1) - sz[Find(eq[j])]);
flag = true;
len = lens[i].first;
del = delnum;
ind = eq[j];
break;
}
}
if (flag) break;
eq.clear();
}
if (len == -1) {
cout << "NO";
return 0;
}
if (del != 0) {
if (delincomp != 0) {
delall = delincomp;
usedindfs.resize(n * m);
dfs(ind, n, m);
}
for (long long i = 0; i < n; i++) {
for (long long j = 0; j < m; j++) {
if (v[i][j] < len || Find(i * m + j) != Find(ind))
v[i][j] = 0;
else
v[i][j] = len;
}
}
} else {
for (long long i = 0; i < n; i++) {
for (long long j = 0; j < m; j++) {
if (v[i][j] < len)
v[i][j] = 0;
else
v[i][j] = len;
}
}
}
cout << "YES" << endl;
for (long long i = 0; i < n; i++) {
for (long long j = 0; j < m; j++) {
cout << v[i][j] << " ";
}
cout << endl;
}
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
In some other world, today is December D-th.
Write a program that prints `Christmas` if D = 25, `Christmas Eve` if D = 24, `Christmas Eve Eve` if D = 23 and `Christmas Eve Eve Eve` if D = 22.
Constraints
* 22 \leq D \leq 25
* D is an integer.
Input
Input is given from Standard Input in the following format:
D
Output
Print the specified string (case-sensitive).
Examples
Input
25
Output
Christmas
Input
22
Output
Christmas Eve Eve Eve
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int i,a;cin>>a;
printf("Christmas");
for(i=0;i<25-a;i++){
printf(" Eve");
}
printf("\n");
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.
Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.
Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) β (1 or 2 = 3, 3 or 4 = 7) β (3 xor 7 = 4). The result is v = 4.
You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
Input
The first line contains two integers n and m (1 β€ n β€ 17, 1 β€ m β€ 105). The next line contains 2n integers a1, a2, ..., a2n (0 β€ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 β€ pi β€ 2n, 0 β€ bi < 230) β the i-th query.
Output
Print m integers β the i-th integer denotes value v for sequence a after the i-th query.
Examples
Input
2 4
1 6 3 5
1 4
3 4
1 2
1 2
Output
1
3
3
3
Note
For more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int *buildTree(long long int *arr, int n) {
long long int *nod;
nod = new long long int[2 * ((int)pow(2, n))];
int index = pow(2, n);
for (int i = 0; i < pow(2, n); i++) nod[index + i] = arr[i];
n--;
int type = 0;
while (n >= 0) {
index = pow(2, n);
for (int i = index; i < 2 * index; i++) {
if (type == 1)
nod[i] = nod[2 * i] ^ nod[2 * i + 1];
else
nod[i] = nod[2 * i] | nod[2 * i + 1];
}
if (type == 1)
type = 0;
else
type = 1;
n--;
}
return nod;
}
void updateTree(long long int *nod, int n, pair<int, long long int> query) {
int index = pow(2, n) + query.first - 1;
nod[index] = query.second;
int type = 0;
index /= 2;
while (index != 0) {
if (type == 0) {
nod[index] = nod[2 * index] | nod[2 * index + 1];
type = 1;
} else {
nod[index] = nod[2 * index] ^ nod[2 * index + 1];
type = 0;
}
index /= 2;
}
}
int main() {
ios_base::sync_with_stdio(0);
int n, m;
long long int *arr;
pair<int, long long int> *query;
cin >> n >> m;
int nArr = pow(2, n);
arr = new long long int[nArr];
query = new pair<int, long long int>[m];
for (int i = 0; i < nArr; i++) cin >> arr[i];
long long int *tree;
tree = buildTree(arr, n);
for (int i = 0; i < m; i++) cin >> query[i].first >> query[i].second;
for (int i = 0; i < m; i++) {
updateTree(tree, n, query[i]);
cout << tree[1] << endl;
}
delete[] arr;
delete[] query;
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
The Fair Nut is going to travel to the Tree Country, in which there are n cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city u and go by a simple path to city v. He hasn't determined the path, so it's time to do it. Note that chosen path can consist of only one vertex.
A filling station is located in every city. Because of strange law, Nut can buy only w_i liters of gasoline in the i-th city. We can assume, that he has infinite money. Each road has a length, and as soon as Nut drives through this road, the amount of gasoline decreases by length. Of course, Nut can't choose a path, which consists of roads, where he runs out of gasoline. He can buy gasoline in every visited city, even in the first and the last.
He also wants to find the maximum amount of gasoline that he can have at the end of the path. Help him: count it.
Input
The first line contains a single integer n (1 β€ n β€ 3 β
10^5) β the number of cities.
The second line contains n integers w_1, w_2, β¦, w_n (0 β€ w_{i} β€ 10^9) β the maximum amounts of liters of gasoline that Nut can buy in cities.
Each of the next n - 1 lines describes road and contains three integers u, v, c (1 β€ u, v β€ n, 1 β€ c β€ 10^9, u β v), where u and v β cities that are connected by this road and c β its length.
It is guaranteed that graph of road connectivity is a tree.
Output
Print one number β the maximum amount of gasoline that he can have at the end of the path.
Examples
Input
3
1 3 3
1 2 2
1 3 2
Output
3
Input
5
6 3 2 5 0
1 2 10
2 3 3
2 4 1
1 5 1
Output
7
Note
The optimal way in the first example is 2 β 1 β 3.
<image>
The optimal way in the second example is 2 β 4.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long N = 3e5 + 10;
const long long M = 1e9 + 7;
int n, x, y, z;
int last[N], to[2 * N], w[2 * N], num, nxt[2 * N];
long long a[N];
long long ans;
void Add(int u, int v, int c) {
nxt[++num] = last[u];
to[num] = v;
w[num] = c;
last[u] = num;
}
long long dp[N];
long long dfs(int u, int f) {
long long max1, max2;
max1 = max2 = 0;
for (int i = last[u]; i; i = nxt[i]) {
int v = to[i];
if (v == f) continue;
dfs(v, u);
long long now = dp[v] - w[i];
if (now >= max1) {
max2 = max1;
max1 = now;
} else if (now > max2)
max2 = now;
}
long long tot = max1 + max2 + a[u];
ans = max(ans, tot);
return dp[u] = max(max1, max2) + a[u];
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; ++i) scanf("%lld", a + i);
for (int i = 1; i <= n - 1; ++i) {
scanf("%d%d%d", &x, &y, &z);
Add(x, y, z);
Add(y, x, z);
}
dfs(1, 0);
printf("%lld\n", ans);
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
A boy named Ayrat lives on planet AMI-1511. Each inhabitant of this planet has a talent. Specifically, Ayrat loves running, moreover, just running is not enough for him. He is dreaming of making running a real art.
First, he wants to construct the running track with coating t. On planet AMI-1511 the coating of the track is the sequence of colored blocks, where each block is denoted as the small English letter. Therefore, every coating can be treated as a string.
Unfortunately, blocks aren't freely sold to non-business customers, but Ayrat found an infinite number of coatings s. Also, he has scissors and glue. Ayrat is going to buy some coatings s, then cut out from each of them exactly one continuous piece (substring) and glue it to the end of his track coating. Moreover, he may choose to flip this block before glueing it. Ayrat want's to know the minimum number of coating s he needs to buy in order to get the coating t for his running track. Of course, he also want's to know some way to achieve the answer.
Input
First line of the input contains the string s β the coating that is present in the shop. Second line contains the string t β the coating Ayrat wants to obtain. Both strings are non-empty, consist of only small English letters and their length doesn't exceed 2100.
Output
The first line should contain the minimum needed number of coatings n or -1 if it's impossible to create the desired coating.
If the answer is not -1, then the following n lines should contain two integers xi and yi β numbers of ending blocks in the corresponding piece. If xi β€ yi then this piece is used in the regular order, and if xi > yi piece is used in the reversed order. Print the pieces in the order they should be glued to get the string t.
Examples
Input
abc
cbaabc
Output
2
3 1
1 3
Input
aaabrytaaa
ayrat
Output
3
1 1
6 5
8 7
Input
ami
no
Output
-1
Note
In the first sample string "cbaabc" = "cba" + "abc".
In the second sample: "ayrat" = "a" + "yr" + "at".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
char s1[2201], s2[2201];
bool mark1[200];
long long prefixhash[2201];
long long invbase[2201];
long long inv;
long long suffixhash[2201];
long long power(long long a, long long b, long long m = 1000000007) {
a %= m;
long long x = 1;
while (b) {
if ((1 & b)) x = x * a % 1000000007;
a = a * a % 1000000007;
b >>= 1;
}
return x;
}
void hash2(int n) {
prefixhash[0] = 0;
invbase[0] = 1;
inv = power(29, 1000000007 - 2, 1000000007);
long long b = 29;
for (int i = 1; i <= n; i++) {
prefixhash[i] = prefixhash[i - 1];
long long x = s2[i - 1] * b;
b *= 29;
b %= 1000000007;
invbase[i] = (invbase[i - 1] * inv) % 1000000007;
prefixhash[i] = (prefixhash[i] + x) % 1000000007;
}
b = 29;
suffixhash[n + 1] = 0;
for (int i = n; i >= 1; i--) {
suffixhash[i] = suffixhash[i + 1];
long long x = s2[i - 1] * b;
b *= 29;
b %= 1000000007;
suffixhash[i] = (suffixhash[i] + x) % 1000000007;
}
}
long long rangef(long long i, long long j) {
long long ans = 1000000007 + prefixhash[j] - prefixhash[i - 1];
if (ans >= 1000000007) ans -= 1000000007;
return (ans * invbase[i - 1]) % 1000000007;
}
int tn;
long long rangeb(long long i, long long j) {
long long ans = 1000000007 + suffixhash[i] - suffixhash[j + 1];
if (ans >= 1000000007) ans -= 1000000007;
return (ans * invbase[tn - j]) % 1000000007;
}
long long prefixhash1[2201];
long long invbase1[2201];
long long inv1;
long long suffixhash1[2201];
void hash1(int n) {
prefixhash1[0] = 0;
invbase1[0] = 1;
inv1 = power(29, 1000000007 - 2, 1000000007);
long long b = 29;
for (int i = 1; i <= n; i++) {
prefixhash1[i] = prefixhash1[i - 1];
long long x = s1[i - 1] * b;
b *= 29;
b %= 1000000007;
invbase1[i] = (invbase1[i - 1] * inv1) % 1000000007;
prefixhash1[i] = (prefixhash1[i] + x) % 1000000007;
}
b = 29;
suffixhash1[n + 1] = 0;
for (int i = n; i >= 1; i--) {
suffixhash1[i] = suffixhash1[i + 1];
long long x = s1[i - 1] * b;
b *= 29;
b %= 1000000007;
suffixhash1[i] = (suffixhash1[i] + x) % 1000000007;
}
}
long long rangef1(long long i, long long j) {
long long ans = 1000000007 + prefixhash1[j] - prefixhash1[i - 1];
if (ans >= 1000000007) ans -= 1000000007;
return (ans * invbase1[i - 1]) % 1000000007;
}
int t1;
long long rangeb1(long long i, long long j) {
long long ans = 1000000007 + suffixhash1[i] - suffixhash1[j + 1];
if (ans >= 1000000007) ans -= 1000000007;
return (ans * invbase1[tn - j]) % 1000000007;
}
bool pos(long long got, long long x) {
for (int i = 0; i + x - 1 < t1; i++) {
if (rangef1(i + 1, i + x) == got) return true;
}
return false;
}
bool can(int s, int e) {
if (pos(rangef(s + 1, e + 1), e - s + 1)) return true;
if (pos(rangeb(s + 1, e + 1), e - s + 1)) return true;
return false;
}
vector<pair<int, int> > my;
bool pos1(long long got, long long x, bool flag) {
if (flag == 0) {
for (int i = 0; i + x - 1 < t1; i++) {
if (rangef1(i + 1, i + x) == got) {
my.push_back(make_pair(i + 1, i + x));
return true;
}
}
return false;
} else {
for (int i = 0; i + x - 1 < t1; i++) {
if (rangef1(i + 1, i + x) == got) {
my.push_back(make_pair(i + x, i + 1));
return true;
}
}
return false;
}
}
void mysearch(int s, int e) {
if (pos1(rangef(s + 1, e + 1), e - s + 1, 0)) return;
pos1(rangeb(s + 1, e + 1), e - s + 1, 1);
}
int main() {
scanf("%s", s1);
scanf("%s", s2);
int l1 = strlen(s1), l2 = strlen(s2);
hash2(l2);
tn = l2;
t1 = l1;
hash1(l1);
for (int i = 0; i < 200; i++) mark1[i] = false;
for (int i = 0; i < l1; i++) {
mark1[s1[i]] = 1;
}
string fuck = "-1";
for (int i = 0; i < l2; i++) {
if (!mark1[s2[i]]) {
cout << fuck << endl;
return 0;
}
}
int found = 0, moves = 0, end;
for (int i = 1; i < l2; i++) {
if (can(found, i)) continue;
end = i - 1;
moves++;
mysearch(found, end);
found = i;
}
end = l2 - 1;
moves++;
mysearch(found, end);
printf("%d\n", moves);
for (int i = 0; i < my.size(); i++) {
cout << my[i].first << " " << my[i].second << endl;
}
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
For given two sequneces $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}\\}$, determine whether all elements of $B$ are included in $A$. Note that, elements of $A$ and $B$ are sorted by ascending order respectively.
Constraints
* $1 \leq n, m \leq 200,000$
* $-1,000,000,000 \leq a_0 < a_1 < ... < a_{n-1} \leq 1,000,000,000$
* $-1,000,000,000 \leq b_0 < b_1 < ... < b_{m-1} \leq 1,000,000,000$
Input
The input is given in the following format.
$n$
$a_0 \; a_1 \; ,..., \; a_{n-1}$
$m$
$b_0 \; b_1 \; ,..., \; b_{m-1}$
The number of elements in $A$ and its elements $a_i$ are given in the first and second lines respectively. The number of elements in $B$ and its elements $b_i$ are given in the third and fourth lines respectively.
Output
Print 1, if $A$ contains all elements of $B$, otherwise 0.
Examples
Input
4
1 2 3 4
2
2 4
Output
1
Input
4
1 2 3 4
3
1 2 5
Output
0
### Response
```cpp
#include <bits/stdc++.h>
#define rep(i ,n) for(int i=0;i<(int)(n);++i)
using namespace std;
typedef long long int int64;
typedef unsigned long long uint64;
int n;
bool binary_search(vector<int> &a ,int k){
int x , y , z;
x = 0;
z = n - 1;
while( x <= z ){
y = (x + z) / 2;
if(k == a[y]) return true;
else if(k < a[y]) z = y - 1;
else x = y + 1;
}
return false;
}
int main(){
bool ans = true;
cin >> n;
vector<int> a(n);
rep(i ,n) cin >> a[i];
int m; cin >> m;
vector<int> b(m);
rep(i ,m) cin >> b[i];
rep(i , m){
if(!binary_search(a,b[i])) {
ans = false; break;
}
}
cout << ( ans ? 1 : 0) << endl;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
In the year 2500 the annual graduation ceremony in the German University in Cairo (GUC) has run smoothly for almost 500 years so far.
The most important part of the ceremony is related to the arrangement of the professors in the ceremonial hall.
Traditionally GUC has n professors. Each professor has his seniority level. All seniorities are different. Let's enumerate the professors from 1 to n, with 1 being the most senior professor and n being the most junior professor.
The ceremonial hall has n seats, one seat for each professor. Some places in this hall are meant for more senior professors than the others. More specifically, m pairs of seats are in "senior-junior" relation, and the tradition requires that for all m pairs of seats (ai, bi) the professor seated in "senior" position ai should be more senior than the professor seated in "junior" position bi.
GUC is very strict about its traditions, which have been carefully observed starting from year 2001. The tradition requires that:
* The seating of the professors changes every year.
* Year 2001 ceremony was using lexicographically first arrangement of professors in the ceremonial hall.
* Each consecutive year lexicographically next arrangement of the professors is used.
The arrangement of the professors is the list of n integers, where the first integer is the seniority of the professor seated in position number one, the second integer is the seniority of the professor seated in position number two, etc.
Given n, the number of professors, y, the current year and m pairs of restrictions, output the arrangement of the professors for this year.
Input
The first line contains three integers n, y and m (1 β€ n β€ 16, 2001 β€ y β€ 1018, 0 β€ m β€ 100) β the number of professors, the year for which the arrangement should be computed, and the number of pairs of seats for which the seniority relation should be kept, respectively.
The next m lines contain one pair of integers each, "ai bi", indicating that professor on the ai-th seat is more senior than professor on the bi-th seat (1 β€ ai, bi β€ n, ai β bi). Some pair may be listed more than once.
Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin stream (you may also use the %I64d specificator).
Output
Print the order in which the professors should be seated in the requested year.
If by this year the GUC would have ran out of arrangements, or the given "senior-junior" relation are contradictory, print "The times have changed" (without quotes).
Examples
Input
3 2001 2
1 2
2 3
Output
1 2 3
Input
7 2020 6
1 2
1 3
2 4
2 5
3 6
3 7
Output
1 2 3 7 4 6 5
Input
10 3630801 0
Output
The times have changed
Input
3 2001 3
1 2
2 3
3 1
Output
The times have changed
Note
In the first example the lexicographically first order of seating is 1 2 3.
In the third example the GUC will run out of arrangements after the year 3630800.
In the fourth example there are no valid arrangements for the seating.
The lexicographical comparison of arrangements is performed by the < operator in modern programming languages. The arrangement a is lexicographically less that the arrangement b, if there exists such i (1 β€ i β€ n), that ai < bi, and for any j (1 β€ j < i) aj = bj.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int BIT = (1 << 17), M = 110, N = 25;
int n, m, cnt[BIT], a[M];
long long f[BIT][N], b[N], p[N], year;
void solve(int x) {
memset(f, 0, sizeof(f));
f[0][0] = 1;
int maxb = (1 << n);
for (int i = 0; i < maxb; i++) {
for (int j = 0; j <= n; j++) {
int y = cnt[i] + 1;
if (b[y]) {
if ((a[b[y]] & i) != a[b[y]]) continue;
if ((1 << (b[y] - 1) & i) == (1 << b[y] - 1)) continue;
f[i | (1 << b[y] - 1)][j] += f[i][j];
} else {
for (int k = 1; k <= n; k++) {
if (!(i & (1 << k - 1))) {
if ((a[k] & i) != a[k]) continue;
if (k == x)
f[i | (1 << k - 1)][y] += f[i][j];
else
f[i | (1 << k - 1)][j] += f[i][j];
}
}
}
}
}
}
int main() {
scanf("%d%lld%d", &n, &year, &m);
year -= 2000;
for (int i = 1; i < BIT; i++) cnt[i] = cnt[i ^ (i & (-i))] + 1;
for (int i = 1; i <= m; i++) {
int x, y;
scanf("%d%d", &x, &y);
a[y] |= (1 << x - 1);
}
for (int i = 1; i <= n; i++) {
solve(i);
long long sum = 0;
for (int j = 1; j <= n; j++) {
if (!b[j] && sum + f[(1 << n) - 1][j] >= year) {
b[j] = i;
p[i] = j;
year -= sum;
break;
}
sum += f[(1 << n) - 1][j];
}
if (!p[i]) {
puts("The times have changed");
return 0;
}
}
for (int i = 1; i <= n; i++) printf("%lld ", p[i]);
puts("");
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Donghyun's new social network service (SNS) contains n users numbered 1, 2, β¦, n. Internally, their network is a tree graph, so there are n-1 direct connections between each user. Each user can reach every other users by using some sequence of direct connections. From now on, we will denote this primary network as T_1.
To prevent a possible server breakdown, Donghyun created a backup network T_2, which also connects the same n users via a tree graph. If a system breaks down, exactly one edge e β T_1 becomes unusable. In this case, Donghyun will protect the edge e by picking another edge f β T_2, and add it to the existing network. This new edge should make the network be connected again.
Donghyun wants to assign a replacement edge f β T_2 for as many edges e β T_1 as possible. However, since the backup network T_2 is fragile, f β T_2 can be assigned as the replacement edge for at most one edge in T_1. With this restriction, Donghyun wants to protect as many edges in T_1 as possible.
Formally, let E(T) be an edge set of the tree T. We consider a bipartite graph with two parts E(T_1) and E(T_2). For e β E(T_1), f β E(T_2), there is an edge connecting \\{e, f\} if and only if graph T_1 - \\{e\} + \\{f\} is a tree. You should find a maximum matching in this bipartite graph.
Input
The first line contains an integer n (2 β€ n β€ 250 000), the number of users.
In the next n-1 lines, two integers a_i, b_i (1 β€ a_i, b_i β€ n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T_1.
In the next n-1 lines, two integers c_i, d_i (1 β€ c_i, d_i β€ n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T_2.
It is guaranteed that both edge sets form a tree of size n.
Output
In the first line, print the number m (0 β€ m < n), the maximum number of edges that can be protected.
In the next m lines, print four integers a_i, b_i, c_i, d_i. Those four numbers denote that the edge (a_i, b_i) in T_1 is will be replaced with an edge (c_i, d_i) in T_2.
All printed edges should belong to their respective network, and they should link to distinct edges in their respective network. If one removes an edge (a_i, b_i) from T_1 and adds edge (c_i, d_i) from T_2, the network should remain connected. The order of printing the edges or the order of vertices in each edge does not matter.
If there are several solutions, you can print any.
Examples
Input
4
1 2
2 3
4 3
1 3
2 4
1 4
Output
3
3 2 4 2
2 1 1 3
4 3 1 4
Input
5
1 2
2 4
3 4
4 5
1 2
1 3
1 4
1 5
Output
4
2 1 1 2
3 4 1 3
4 2 1 4
5 4 1 5
Input
9
7 9
2 8
2 1
7 5
4 7
2 4
9 6
3 9
1 8
4 8
2 9
9 5
7 6
1 3
4 6
5 3
Output
8
4 2 9 2
9 7 6 7
5 7 5 9
6 9 4 6
8 2 8 4
3 9 3 5
2 1 1 8
7 4 1 3
### Response
```cpp
#include <bits/stdc++.h>
int ch[250001][2], mn[250001], mx[250001], fa[250001];
bool lazy[250001];
bool son(int x) { return ch[fa[x]][1] == x; }
bool isroot(int x) { return ch[fa[x]][0] != x && ch[fa[x]][1] != x; }
void pushup(int x) {
mn[x] = mn[ch[x][0]] ? mn[ch[x][0]] : x;
mx[x] = mx[ch[x][1]] ? mx[ch[x][1]] : x;
}
void Rotate(int x) {
int faz = fa[x], fazz = fa[faz], g = son(x);
fa[x] = fazz;
if (!isroot(faz)) ch[fazz][son(faz)] = x;
fa[ch[x][!g]] = faz;
ch[faz][g] = ch[x][!g];
ch[x][!g] = faz;
fa[faz] = x;
pushup(faz);
pushup(x);
}
void pushdown(int x) {
if (!x) return;
lazy[x] ^= 1;
std::swap(ch[x][0], ch[x][1]);
std::swap(mn[x], mx[x]);
}
void spread(int x) {
if (lazy[x]) pushdown(ch[x][0]), pushdown(ch[x][1]), lazy[x] = 0;
}
void clear(int x) {
if (!isroot(x)) clear(fa[x]);
spread(x);
}
void splay(int x) {
clear(x);
while (!isroot(x)) {
if (!isroot(fa[x]))
if (son(x) ^ son(fa[x]))
Rotate(x);
else
Rotate(fa[x]);
Rotate(x);
}
}
void access(int x) {
for (int y = 0; x; y = x, x = fa[x]) splay(x), ch[x][1] = y, pushup(x);
}
void mroot(int x) {
access(x);
splay(x);
pushdown(x);
}
void split(int x, int y) {
mroot(x);
access(y);
splay(y);
}
void link(int x, int y) {
mroot(x);
fa[x] = y;
}
void cut(int x, int y) {
split(x, y);
ch[y][0] = fa[x] = 0;
pushup(y);
}
int head[250001], nxt[500001], b[500001], k, dfn[250001], end[250001], now, n;
void push(int s, int t) {
nxt[++k] = head[s];
head[s] = k;
b[k] = t;
}
void dfs(int x, int f) {
dfn[x] = ++now;
for (int i = head[x]; i; i = nxt[i])
if (b[i] != f) dfs(b[i], x);
end[x] = now;
}
bool in(int x, int y) { return dfn[x] >= dfn[y] && dfn[x] <= end[y]; }
void getedge(int x, int c1, int c2) {
spread(x);
if (ch[x][0] && in(mx[ch[x][0]], c1) ^ in(x, c1)) {
printf("%d %d %d %d\n", c1, c2, x, mx[ch[x][0]]);
cut(x, mx[ch[x][0]]);
link(c1, c2);
return;
}
if (ch[x][1] && in(mn[ch[x][1]], c1) ^ in(x, c1)) {
printf("%d %d %d %d\n", c1, c2, x, mn[ch[x][1]]);
cut(x, mn[ch[x][1]]);
link(c1, c2);
return;
}
if (ch[x][0] && in(mn[ch[x][0]], c1) ^ in(x, c1))
getedge(ch[x][0], c1, c2);
else
getedge(ch[x][1], c1, c2);
}
void dfs(int x) {
if (!x) return;
spread(x);
dfs(ch[x][0]);
printf("%d ", x);
dfs(ch[x][1]);
}
int tot;
int xx[250001], yy[250001];
void getans(int x, int f) {
if (f) {
xx[++tot] = x;
yy[tot] = f;
}
for (int i = head[x]; i; i = nxt[i])
if (b[i] != f) getans(b[i], x);
}
int main() {
scanf("%d", &n);
for (int i = 1, u, v; i < n; i++) {
scanf("%d%d", &u, &v);
push(u, v);
push(v, u);
}
dfs(1, 0);
for (int i = 1, u, v; i < n; i++) {
scanf("%d%d", &u, &v);
link(u, v);
}
printf("%d\n", n - 1);
getans(1, 0);
for (int i = 1; i < n; ++i) b[i] = i;
std::random_shuffle(b + 1, b + n);
for (int i = 1; i < n; ++i) {
int x(xx[i]), f(yy[i]);
split(x, f);
getedge(f, x, f);
}
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Problem statement
You and AOR Ika are preparing for a graph problem in competitive programming. Generating input cases is AOR Ika-chan's job. The input case for that problem is a directed graph of the $ N $ vertices. The vertices are numbered from $ 1 $ to $ N $. Edges may contain self-loops, but not multiple edges.
However, AOR Ika suddenly lost communication and couldn't get the original graph. All that remains is the following information:
* The number of vertices with degree $ i $ is $ a_i $. That is, the number of vertices ending in $ i $ is $ a_i $.
* The number of vertices with degree $ i $ is $ b_i $. That is, the number of vertices starting from $ i $ is $ b_i $.
Is there a directed graph that is consistent with the information left behind? Judge it, output YES if it exists, and then output one consistent directed graph. If there are more than one, any one may be output. If it does not exist, output NO.
Input constraints
$ 1 \ leq n \ leq 50 $
$ 0 \ leq a_i \ leq n $
$ 0 \ leq b_i \ leq n $
sample
Sample input 1
3
1 2 0 0
1 2 0 0
Sample output 1
YES YES
0 1 0
0 0 1
0 0 0
Sample input 2
1
Ten
Ten
Sample output 2
YES YES
0
Sample input 3
2
0 2 0
0 2 0
Sample output 3
YES YES
0 1
Ten
Sample input 4
Four
1 3 0 0 0
3 0 0 1 0
Sample output 4
YES YES
0 1 1 1
0 0 0 0
0 0 0 0
0 0 0 0
Sample input 5
1
1 1
0 0
Sample output 5
NO
input
$ n $
$ a_0 \ cdots a_n $
$ b_0 \ cdots b_n $
output
If there is a graph that meets the conditions, output it in the following format. $ e_ {ij} $ should be 1 if there is a directed edge from $ i $ to $ j $, or 0 otherwise. Be careful not to print a blank at the end of the line.
YES YES
$ e_ {11} \ e_ {12} \ cdots e_ {1n} $
$ e_ {21} \ e_ {22} \ cdots e_ {2n} $
$ \ vdots $
$ e_ {n1} \ e_ {n2} \ cdots e_ {nn} $
If not, output as follows.
NO
Example
Input
3
1 2 0 0
1 2 0 0
Output
YES
0 1 0
0 0 1
0 0 0
### Response
```cpp
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <utility>
#include <cstring>
#include <iomanip>
#include <numeric>
#include <cmath>
#include <cassert>
#include <complex>
#include <queue>
#define repi(i, x, n) for(int i = x; i < n; i++)
#define rep(i, n) repi(i, 0, n)
#define endl "\n"
#define int long long
using namespace std;
const int INF = 1<<30;
const int MOD = (int)1e9 + 7;
const int MAX_N = (int)1e5 + 5;
#define debug(x) cout << #x << ": " << x << endl
#define MAX 55
signed main(void)
{
cin.tie(0);
ios::sync_with_stdio(false);
int n;
int num;
int s1 = 0, s2 = 0;
priority_queue<pair<int,int>> a, b;
static int ans[MAX][MAX];
cin>>n;
for(int i = 0, sum = 0; i <= n; i++){
cin>>num;
s1 += num;
for(int j = 0; j < num; j++){
a.push(make_pair(i,sum++));
}
}
for(int j = 0, sum = 0; j <= n; j++){
cin>>num;
s2 += num;
for(int k = 0; k < num; k++){
b.push(make_pair(j,sum++));
}
}
if(s1 =! s2 || s1 != n){
cout<<"NO"<<endl;
return 0;
}
while(!a.empty()){
pair<int,int> A = a.top(); a.pop();
vector<pair<int,int>> temp;
if(A.first == 0) break;
for(int i = 0; i < A.first; i++){
if(b.size() == 0){
cout<<"NO"<<endl;
return 0;
}
pair<int,int> B = b.top(); b.pop();
if(B.first == 0){
cout<<"NO"<<endl;
return 0;
}
if(B.first-1 > 0)temp.push_back(make_pair(B.first-1,B.second));
ans[B.second][A.second]++;
}
for(int j = 0; j < temp.size(); j++){
b.push(temp[j]);
}
}
cout<<"YES"<<endl;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(j) cout<<" ";
cout<<ans[i][j];
}
cout<<endl;
}
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Caracal is fighting with a monster.
The health of the monster is H.
Caracal can attack by choosing one monster. When a monster is attacked, depending on that monster's health, the following happens:
* If the monster's health is 1, it drops to 0.
* If the monster's health, X, is greater than 1, that monster disappears. Then, two new monsters appear, each with the health of \lfloor X/2 \rfloor.
(\lfloor r \rfloor denotes the greatest integer not exceeding r.)
Caracal wins when the healths of all existing monsters become 0 or below.
Find the minimum number of attacks Caracal needs to make before winning.
Constraints
* 1 \leq H \leq 10^{12}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H
Output
Find the minimum number of attacks Caracal needs to make before winning.
Examples
Input
2
Output
3
Input
4
Output
7
Input
1000000000000
Output
1099511627775
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
long long H;
long long ans_=1;
cin>>H;
while(H!=0){
ans_*=2;
H=H/2;
}
cout<<ans_-1<<endl;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
An n Γ n table a is defined as follows:
* The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n.
* Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defined by the formula ai, j = ai - 1, j + ai, j - 1.
These conditions define all the values in the table.
You are given a number n. You need to determine the maximum value in the n Γ n table defined by the rules above.
Input
The only line of input contains a positive integer n (1 β€ n β€ 10) β the number of rows and columns of the table.
Output
Print a single line containing a positive integer m β the maximum value in the table.
Examples
Input
1
Output
1
Input
5
Output
70
Note
In the second test the rows of the table look as follows:
{1, 1, 1, 1, 1}, {1, 2, 3, 4, 5}, {1, 3, 6, 10, 15}, {1, 4, 10, 20, 35}, {1, 5, 15, 35, 70}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 3;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long t, i, j, n, m, l, r;
cin >> n;
long long a[n + 1][n + 1];
for (i = 0; i < n; i++) a[0][i] = a[i][0] = 1;
for (i = 1; i < n; i++) {
for (j = 1; j < n; j++) {
a[i][j] = a[i - 1][j] + a[i][j - 1];
}
}
cout << a[n - 1][n - 1] << "\n";
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
You are given a rooted tree with n vertices. The vertices are numbered from 1 to n, the root is the vertex number 1.
Each vertex has a color, let's denote the color of vertex v by cv. Initially cv = 0.
You have to color the tree into the given colors using the smallest possible number of steps. On each step you can choose a vertex v and a color x, and then color all vectices in the subtree of v (including v itself) in color x. In other words, for every vertex u, such that the path from root to u passes through v, set cu = x.
It is guaranteed that you have to color each vertex in a color different from 0.
You can learn what a rooted tree is using the link: https://en.wikipedia.org/wiki/Tree_(graph_theory).
Input
The first line contains a single integer n (2 β€ n β€ 104) β the number of vertices in the tree.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi means that there is an edge between vertices i and pi.
The third line contains n integers c1, c2, ..., cn (1 β€ ci β€ n), where ci is the color you should color the i-th vertex into.
It is guaranteed that the given graph is a tree.
Output
Print a single integer β the minimum number of steps you have to perform to color the tree into given colors.
Examples
Input
6
1 2 2 1 5
2 1 1 1 1 1
Output
3
Input
7
1 1 2 3 1 4
3 3 1 1 1 2 3
Output
5
Note
The tree from the first sample is shown on the picture (numbers are vetices' indices):
<image>
On first step we color all vertices in the subtree of vertex 1 into color 2 (numbers are colors):
<image>
On seond step we color all vertices in the subtree of vertex 5 into color 1:
<image>
On third step we color all vertices in the subtree of vertex 2 into color 1:
<image>
The tree from the second sample is shown on the picture (numbers are vetices' indices):
<image>
On first step we color all vertices in the subtree of vertex 1 into color 3 (numbers are colors):
<image>
On second step we color all vertices in the subtree of vertex 3 into color 1:
<image>
On third step we color all vertices in the subtree of vertex 6 into color 2:
<image>
On fourth step we color all vertices in the subtree of vertex 4 into color 1:
<image>
On fith step we color all vertices in the subtree of vertex 7 into color 3:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, i, j, k, t;
scanf("%d", &n);
vector<int> v[n + 1];
for (i = 2; i <= n; i++) {
int x;
scanf("%d", &x);
v[i].push_back(x);
v[x].push_back(i);
}
int colour[n + 1];
for (i = 0; i <= n; i++) colour[i] = 0;
int req[n + 1];
for (i = 1; i <= n; i++) scanf("%d", &req[i]);
queue<int> q1, q2;
q2.push(1);
int dist[n + 1], visited[n + 1], visi[n + 1];
for (i = 0; i <= n; i++) {
dist[i] = 0;
visited[i] = 0;
visi[i] = 0;
}
visited[1] = 1;
while (!q2.empty()) {
int x = q2.front();
q2.pop();
for (auto l : v[x]) {
if (visited[l] == 0) {
visited[l] = 1;
dist[l] = dist[x] + 1;
q2.push(l);
}
}
}
q2.push(1);
int count = 0;
while (!q2.empty()) {
int x = q2.front();
q2.pop();
if (req[x] != colour[x]) {
count++;
colour[x] = req[x];
q1.push(x);
for (i = 0; i <= n; i++) {
visited[i] = 0;
}
visited[x] = 1;
while (!q1.empty()) {
int y = q1.front();
q1.pop();
for (auto l : v[y]) {
if (dist[l] >= dist[x] && visited[l] == 0) {
visited[l] = 1;
colour[l] = req[x];
q1.push(l);
}
}
}
}
for (auto l : v[x]) {
if (visi[l] == 0) {
visi[l] = 1;
q2.push(l);
}
}
}
cout << count << endl;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
After a long day, Alice and Bob decided to play a little game. The game board consists of n cells in a straight line, numbered from 1 to n, where each cell contains a number a_i between 1 and n. Furthermore, no two cells contain the same number.
A token is placed in one of the cells. They take alternating turns of moving the token around the board, with Alice moving first. The current player can move from cell i to cell j only if the following two conditions are satisfied:
* the number in the new cell j must be strictly larger than the number in the old cell i (i.e. a_j > a_i), and
* the distance that the token travels during this turn must be a multiple of the number in the old cell (i.e. |i-j|mod a_i = 0).
Whoever is unable to make a move, loses. For each possible starting position, determine who wins if they both play optimally. It can be shown that the game is always finite, i.e. there always is a winning strategy for one of the players.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of numbers.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n). Furthermore, there are no pair of indices i β j such that a_i = a_j.
Output
Print s β a string of n characters, where the i-th character represents the outcome of the game if the token is initially placed in the cell i. If Alice wins, then s_i has to be equal to "A"; otherwise, s_i has to be equal to "B".
Examples
Input
8
3 6 5 4 2 7 1 8
Output
BAAAABAB
Input
15
3 11 2 5 10 9 7 13 15 8 4 12 6 1 14
Output
ABAAAABBBAABAAB
Note
In the first sample, if Bob puts the token on the number (not position):
* 1: Alice can move to any number. She can win by picking 7, from which Bob has no move.
* 2: Alice can move to 3 and 5. Upon moving to 5, Bob can win by moving to 8. If she chooses 3 instead, she wins, as Bob has only a move to 4, from which Alice can move to 8.
* 3: Alice can only move to 4, after which Bob wins by moving to 8.
* 4, 5, or 6: Alice wins by moving to 8.
* 7, 8: Alice has no move, and hence she loses immediately.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline void read(T &x) {
x = 0;
char c = getchar(), f = 0;
for (; c < '0' || c > '9'; c = getchar())
if (!(c ^ 45)) f = 1;
for (; c >= '0' && c <= '9'; c = getchar())
x = (x << 1) + (x << 3) + (c ^ 48);
if (f) x = -x;
}
int n, a[100005], dp[100005];
pair<int, int> p[100005];
int main() {
read(n), memset(dp, -1, sizeof(dp));
for (int i = 1; i <= n; i++) read(a[i]), p[i] = make_pair(a[i], i);
sort(p + 1, p + n + 1, greater<pair<int, int> >());
for (int i = 1; i <= n; i++) {
int id = p[i].second;
dp[id] = 0;
for (int j = id % a[id]; j <= n; j += a[id])
if (j != id && !dp[j]) {
dp[id] = 1;
break;
}
}
for (int i = 1; i <= n; i++) putchar(66 - dp[i]);
return putchar('\n'), 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
As you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n - 1 two-way roads. The cities are numbered from 1 to n. You can get from one city to another moving along the roads.
The Β«Two PathsΒ» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities).
It is known that the profit, the Β«Two PathsΒ» company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company.
Input
The first line contains an integer n (2 β€ n β€ 200), where n is the amount of cities in the country. The following n - 1 lines contain the information about the roads. Each line contains a pair of numbers of the cities, connected by the road ai, bi (1 β€ ai, bi β€ n).
Output
Output the maximum possible profit.
Examples
Input
4
1 2
2 3
3 4
Output
1
Input
7
1 2
1 3
1 4
1 5
1 6
1 7
Output
0
Input
6
1 2
2 3
2 4
5 4
6 4
Output
4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
struct Sync_stdio {
Sync_stdio() {
cin.tie(NULL);
ios_base::sync_with_stdio(false);
}
} _sync_stdio;
struct FAIL {
FAIL() {
cout << "CHANGE!!!"
<< "\n";
}
};
vector<vector<int>> g;
vector<int> used1;
vector<int> used2;
vector<int> used3;
int maxc = 0;
int maxi = -1;
int res = 0;
int n;
void dfs3(int x, int h = 0) {
used3[x] = 1;
if (h >= maxc) {
maxc = h;
maxi = x;
}
for (auto i : g[x]) {
if (used3[i]) {
continue;
}
dfs3(i, h + 1);
}
}
void dfs2(int x, int h = 0) {
used2[x] = 1;
used3[x] = 1;
auto t = used3;
vector<int> last(n, -1);
for (int i = (0); i < (n); ++i) {
if (!used3[i]) {
maxc = -1;
dfs3(i);
last[i] = maxi;
}
}
used3 = t;
for (int i = (0); i < (n); ++i) {
if (last[i] != -1) {
maxc = -1;
dfs3(last[i]);
res = max(res, h * maxc);
}
}
used3 = t;
for (auto i : g[x]) {
if (used2[i]) {
continue;
}
dfs2(i, h + 1);
}
used3[x] = 0;
}
void dfs1(int x) {
used1[x] = 1;
used2.assign(n, 0);
dfs2(x);
for (auto i : g[x]) {
if (used1[i]) {
continue;
}
dfs1(i);
}
}
int main() {
cin >> n;
g.resize(n);
used1.resize(n);
used2.resize(n);
used3.resize(n);
for (int i = (0); i < (n - 1); ++i) {
int x, y;
cin >> x >> y;
--x, --y;
g[x].push_back(y);
g[y].push_back(x);
}
dfs1(0);
cout << res;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.
The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1).
Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.
Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9.
Input
The first line contains number m (2 β€ m β€ 105).
The following m lines contain the coordinates of the cubes xi, yi ( - 109 β€ xi β€ 109, 0 β€ yi β€ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable.
No two cubes occupy the same place.
Output
In the only line print the answer to the problem.
Examples
Input
3
2 1
1 0
0 1
Output
19
Input
5
0 0
0 1
0 2
0 3
0 4
Output
2930
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct BLOCK {
int id, outdegree;
int x, y;
vector<int> above;
vector<int> below;
bool alive;
BLOCK() {}
BLOCK(int id) : id(id) {
alive = true;
outdegree = 0;
}
} block[100005];
int m;
int trans[100005];
const long long MOD = 1e9 + 9;
map<pair<int, int>, int> pos_to_id;
void preprocess() {
for (int i = 0; i < m; ++i) {
pair<int, int> now;
now.first = block[i].x;
now.second = block[i].y;
pair<int, int> tmp = now;
tmp.second--;
if (pos_to_id.count(tmp) != 0) {
++block[i].outdegree;
block[i].below.push_back(pos_to_id[tmp]);
block[pos_to_id[tmp]].above.push_back(pos_to_id[now]);
}
--tmp.first;
if (pos_to_id.count(tmp) != 0) {
++block[i].outdegree;
block[i].below.push_back(pos_to_id[tmp]);
block[pos_to_id[tmp]].above.push_back(pos_to_id[now]);
}
tmp.first += 2;
if (pos_to_id.count(tmp) != 0) {
++block[i].outdegree;
block[i].below.push_back(pos_to_id[tmp]);
block[pos_to_id[tmp]].above.push_back(pos_to_id[now]);
}
}
}
bool cmp(const BLOCK& x, const BLOCK& y) {
if (x.y > y.y) return true;
if (x.y < y.y) return false;
if (x.x < y.x) return true;
if (x.x > y.x) return false;
return false;
}
bool cmp2(const BLOCK& x, const BLOCK& y) { return x.id > y.id; }
void print() {
cout << "===" << endl;
for (int i = 0; i < m; ++i) {
cout << block[i].id << " outdegree: " << block[i].outdegree << endl;
for (int j = 0; j < block[i].above.size(); ++j) {
cout << block[i].above[i] << " ";
}
cout << endl;
}
cout << "===" << endl;
}
bool availible(int block_code) {
for (int i = 0; i < block[block_code].above.size(); ++i) {
int target = trans[block[block_code].above[i]];
if (!block[target].alive) continue;
if (block[target].outdegree == 1) return false;
}
return true;
}
void take(int block_code, long long& ans,
priority_queue<int, vector<int>, less<int> >& gpq,
priority_queue<int, vector<int>, greater<int> >& lpq) {
ans = (ans * m + block[block_code].id) % MOD;
for (int i = 0; i < block[block_code].above.size(); ++i) {
--block[trans[block[block_code].above[i]]].outdegree;
}
block[block_code].alive = false;
for (int i = 0; i < block[block_code].below.size(); ++i) {
int target = trans[block[block_code].below[i]];
if (!block[target].alive) continue;
if (availible(target)) {
gpq.push(block[block_code].below[i]);
lpq.push(block[block_code].below[i]);
}
}
}
void solve() {
int last = m;
long long ans = 0;
priority_queue<int, vector<int>, less<int> > gpq;
priority_queue<int, vector<int>, greater<int> > lpq;
for (int i = 0; i < m; ++i) {
if (availible(i)) {
gpq.push(block[i].id);
lpq.push(block[i].id);
}
}
while (last) {
while (gpq.size()) {
int now = gpq.top();
gpq.pop();
int target = trans[now];
if (!block[target].alive) continue;
if (!availible(target)) continue;
take(target, ans, gpq, lpq);
break;
}
--last;
if (last == 0) break;
while (lpq.size()) {
int now = lpq.top();
lpq.pop();
int target = trans[now];
if (!block[target].alive) continue;
if (!availible(target)) continue;
take(target, ans, gpq, lpq);
break;
}
--last;
}
cout << ans << endl;
}
void make_table() {
for (int i = 0; i < m; ++i) {
trans[block[i].id] = i;
}
}
int main() {
scanf("%d", &m);
for (int i = 0; i < m; ++i) {
block[i] = BLOCK(i);
pair<int, int> tmp;
scanf("%d%d", &tmp.first, &tmp.second);
block[i].x = tmp.first;
block[i].y = tmp.second;
pos_to_id[tmp] = i;
}
preprocess();
sort(block, block + m, cmp2);
make_table();
solve();
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
One day Polycarp decided to rewatch his absolute favourite episode of well-known TV series "Tufurama". He was pretty surprised when he got results only for season 7 episode 3 with his search query of "Watch Tufurama season 3 episode 7 online full hd free". This got Polycarp confused β what if he decides to rewatch the entire series someday and won't be able to find the right episodes to watch? Polycarp now wants to count the number of times he will be forced to search for an episode using some different method.
TV series have n seasons (numbered 1 through n), the i-th season has ai episodes (numbered 1 through ai). Polycarp thinks that if for some pair of integers x and y (x < y) exist both season x episode y and season y episode x then one of these search queries will include the wrong results. Help Polycarp to calculate the number of such pairs!
Input
The first line contains one integer n (1 β€ n β€ 2Β·105) β the number of seasons.
The second line contains n integers separated by space a1, a2, ..., an (1 β€ ai β€ 109) β number of episodes in each season.
Output
Print one integer β the number of pairs x and y (x < y) such that there exist both season x episode y and season y episode x.
Examples
Input
5
1 2 3 4 5
Output
0
Input
3
8 12 7
Output
3
Input
3
3 2 1
Output
2
Note
Possible pairs in the second example:
1. x = 1, y = 2 (season 1 episode 2 <image> season 2 episode 1);
2. x = 2, y = 3 (season 2 episode 3 <image> season 3 episode 2);
3. x = 1, y = 3 (season 1 episode 3 <image> season 3 episode 1).
In the third example:
1. x = 1, y = 2 (season 1 episode 2 <image> season 2 episode 1);
2. x = 1, y = 3 (season 1 episode 3 <image> season 3 episode 1).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long ep[200005];
long long tree[400010], res;
vector<long long> vt[200005];
int n;
inline long long lowbit(int x) { return x & (-x); }
long long query(int pos) {
long long ans = 0;
while (pos) {
ans += tree[pos];
pos -= lowbit(pos);
}
return ans;
}
void update(int pos, int val) {
while (pos < 200005) {
tree[pos] += val;
pos += lowbit(pos);
}
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> ep[i];
ep[i] = min(ep[i], (long long)n);
vt[min((long long)i - 1, ep[i])].push_back(i);
}
for (int i = 1; i <= n; i++) {
update(ep[i], 1);
for (auto it : vt[i]) res += query(n) - query(it - 1);
}
cout << res << endl;
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
A permutation p of size n is the sequence p1, p2, ..., pn, consisting of n distinct integers, each of them is from 1 to n (1 β€ pi β€ n).
A lucky permutation is such permutation p, that any integer i (1 β€ i β€ n) meets this condition ppi = n - i + 1.
You have integer n. Find some lucky permutation p of size n.
Input
The first line contains integer n (1 β€ n β€ 105) β the required permutation size.
Output
Print "-1" (without the quotes) if the lucky permutation p of size n doesn't exist.
Otherwise, print n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) after a space β the required permutation.
If there are multiple answers, you can print any of them.
Examples
Input
1
Output
1
Input
2
Output
-1
Input
4
Output
2 4 1 3
Input
5
Output
2 5 3 1 4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int ara[100005];
int main() {
int n;
cin >> n;
if (n % 4 <= 1) {
int in = 2;
for (int i = 1; i <= n / 2; i += 2, in += 2) {
ara[i] = in;
ara[n - i + 1] = n - in + 1;
}
in = n;
for (int i = 2; i <= n / 2; i += 2, in -= 2) {
ara[i] = in;
ara[n - i + 1] = n + 1 - in;
}
if (n % 4 == 1) ara[n / 2 + 1] = n / 2 + 1;
for (int i = 1; i <= n; i++) cout << ara[i] << " ";
} else {
cout << -1;
}
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.
Note that the order of the points inside the group of three chosen points doesn't matter.
Input
The first line contains two integers: n and d (1 β€ n β€ 105; 1 β€ d β€ 109). The next line contains n integers x1, x2, ..., xn, their absolute value doesn't exceed 109 β the x-coordinates of the points that Petya has got.
It is guaranteed that the coordinates of the points in the input strictly increase.
Output
Print a single integer β the number of groups of three points, where the distance between two farthest points doesn't exceed d.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
4 3
1 2 3 4
Output
4
Input
4 2
-3 -2 -1 0
Output
2
Input
5 19
1 10 20 30 50
Output
1
Note
In the first sample any group of three points meets our conditions.
In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.
In the third sample only one group does: {1, 10, 20}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long inf = (long long)2 * 1e9;
const long long MOD = (long long)1e9 + 7;
const long long MAX_N = 100000;
const long double pi = 3.1415926;
const long double eps = 1e-6;
long long a[MAX_N];
long long bin_search(long long x, long long* a, long long n) {
long long l = 0, r = n, mid;
while (r - l > 1) {
mid = (l + r) / 2;
if (x >= a[mid])
l = mid;
else
r = mid;
}
return l;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
long long n, d;
cin >> n >> d;
for (long long i = 0; i < n; i++) cin >> a[i];
long long ans = 0;
for (long long i = 0; i < n; i++) {
long long j = bin_search(a[i] + d, a, n);
long long cnt = j - i;
ans += cnt * (cnt - 1) / 2;
}
cout << ans;
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
The determinant of a matrix 2 Γ 2 is defined as follows:
<image>
A matrix is called degenerate if its determinant is equal to zero.
The norm ||A|| of a matrix A is defined as a maximum of absolute values of its elements.
You are given a matrix <image>. Consider any degenerate matrix B such that norm ||A - B|| is minimum possible. Determine ||A - B||.
Input
The first line contains two integers a and b (|a|, |b| β€ 109), the elements of the first row of matrix A.
The second line contains two integers c and d (|c|, |d| β€ 109) the elements of the second row of matrix A.
Output
Output a single real number, the minimum possible value of ||A - B||. Your answer is considered to be correct if its absolute or relative error does not exceed 10 - 9.
Examples
Input
1 2
3 4
Output
0.2000000000
Input
1 0
0 1
Output
0.5000000000
Note
In the first sample matrix B is <image>
In the second sample matrix B is <image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#pragma comment(linker, "/STACK:128000000")
vector<double> a;
pair<double, double> interv(double x1, double x2, double dsjfksdj_fks,
double alksaad_sa) {
double val = x1 * dsjfksdj_fks;
double mn = val, mx = val;
val = x2 * dsjfksdj_fks;
mn = min(mn, val);
mx = max(mx, val);
val = x1 * alksaad_sa;
mn = min(mn, val);
mx = max(mx, val);
val = x2 * alksaad_sa;
mn = min(mn, val);
mx = max(mx, val);
if ((x1 <= 0.0 && x2 >= 0.0) || (dsjfksdj_fks <= 0.0 && alksaad_sa >= 0.0)) {
val = 0;
mn = min(mn, val);
mx = max(mx, val);
}
return make_pair(mn, mx);
}
inline int check(double x) {
pair<double, double> p1 = interv(a[0] - x, a[0] + x, a[3] - x, a[3] + x);
pair<double, double> p2 = interv(a[1] - x, a[1] + x, a[2] - x, a[2] + x);
double L = max(p1.first, p2.first);
double R = min(p1.second, p2.second);
return (L <= R);
}
int main() {
a.resize(4);
for (int i = 0; i < 4; ++i) cin >> a[i];
double l = 0.0, r = 2e+9;
for (int it = 0; it < 128; ++it) {
double mid = (l + r) / 2.0;
if (check(mid))
r = mid;
else
l = mid;
}
double res = (l + r) / 2.0;
cout.precision(15);
cout << fixed << res << endl;
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
Find the sum of weights of edges of the Minimum Spanning Tree for a given weighted undirected graph G = (V, E).
Constraints
* 1 β€ |V| β€ 10,000
* 0 β€ |E| β€ 100,000
* 0 β€ wi β€ 10,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0 w0
s1 t1 w1
:
s|E|-1 t|E|-1 w|E|-1
, where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target verticess of i-th edge (undirected) and wi represents the weight of the i-th edge.
Output
Print the sum of the weights of the Minimum Spanning Tree.
Examples
Input
4 6
0 1 2
1 2 1
2 3 1
3 0 1
0 2 3
1 3 5
Output
3
Input
6 9
0 1 1
0 2 3
1 2 1
1 3 7
2 4 1
1 4 3
3 4 1
3 5 1
4 5 6
Output
5
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pll;
int main() {
ll v,e;
cin >> v >> e;
vector<map<ll,ll>> E(v);
for(ll i=0;i<e;i++) {
ll s,t,dis;
cin >> s >> t >> dis;
E[s][t]=dis;
E[t][s]=dis;
}
set<ll> al;
al.insert(0);
priority_queue<pll,vector<pll>,greater<pll>> q;
for(auto p:E[0]) {
q.push(pll(p.second,p.first));
}
ll ans=0;
while(al.size()<v) {
auto p=q.top();
q.pop();
if(al.count(p.second)) continue;
ans+=p.first;
al.insert(p.second);
for(auto pp:E[p.second]) {
q.push(pll(pp.second,pp.first));
}
}
cout << ans << endl;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Toad Pimple has an array of integers a_1, a_2, β¦, a_n.
We say that y is reachable from x if x<y and there exists an integer array p such that x = p_1 < p_2 < β¦ < p_k=y, and a_{p_i} \& a_{p_{i+1}} > 0 for all integers i such that 1 β€ i < k.
Here \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
You are given q pairs of indices, check reachability for each of them.
Input
The first line contains two integers n and q (2 β€ n β€ 300 000, 1 β€ q β€ 300 000) β the number of integers in the array and the number of queries you need to answer.
The second line contains n space-separated integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 300 000) β the given array.
The next q lines contain two integers each. The i-th of them contains two space-separated integers x_i and y_i (1 β€ x_i < y_i β€ n). You need to check if y_i is reachable from x_i.
Output
Output q lines. In the i-th of them print "Shi" if y_i is reachable from x_i, otherwise, print "Fou".
Example
Input
5 3
1 3 0 2 1
1 3
2 4
1 4
Output
Fou
Shi
Shi
Note
In the first example, a_3 = 0. You can't reach it, because AND with it is always zero. a_2 \& a_4 > 0, so 4 is reachable from 2, and to go from 1 to 4 you can use p = [1, 2, 4].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 5;
const int K = 20;
long long a[N];
int nextClosest[N][K];
int last[K];
int main() {
ios_base ::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, q;
cin >> n >> q;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 0; i < K; i++) nextClosest[n + 1][i] = n + 1, last[i] = n + 1;
for (int i = n; i >= 1; i--) {
for (int j = 0; j < K; j++) {
nextClosest[i][j] = n + 1;
}
for (int j = 0; j < K; j++) {
if ((1 << j) & a[i]) {
for (int k = 0; k < K; k++) {
nextClosest[i][k] = min(nextClosest[i][k], nextClosest[last[j]][k]);
}
last[j] = i;
nextClosest[i][j] = i;
}
}
}
int x, y;
while (q--) {
cin >> x >> y;
bool flag = 0;
for (int i = 0; i < K; i++) {
if ((1 << i) & a[y]) {
if (nextClosest[x][i] <= y) flag = 1;
}
}
if (flag)
cout << "Shi\n";
else
cout << "Fou\n";
}
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
M-kun is a competitor in AtCoder, whose highest rating is X.
In this site, a competitor is given a kyu (class) according to his/her highest rating. For ratings from 400 through 1999, the following kyus are given:
* From 400 through 599: 8-kyu
* From 600 through 799: 7-kyu
* From 800 through 999: 6-kyu
* From 1000 through 1199: 5-kyu
* From 1200 through 1399: 4-kyu
* From 1400 through 1599: 3-kyu
* From 1600 through 1799: 2-kyu
* From 1800 through 1999: 1-kyu
What kyu does M-kun have?
Constraints
* 400 \leq X \leq 1999
* X is an integer.
Input
Input is given from Standard Input in the following format:
X
Output
Print the kyu M-kun has, as an integer. For example, if he has 8-kyu, print `8`.
Examples
Input
725
Output
7
Input
1600
Output
2
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main()
{
int N;
cin>>N;
N/=200;
cout<<10-N<<endl;
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.
2. - ai β delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.
3. ? s β count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
Input
The first line of the input contains an integer t (1 β€ t β€ 100 000) β the number of operation Sonya has to perform.
Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci β the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 β€ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.
It's guaranteed that there will be at least one query of type '?'.
It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
Output
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
Examples
Input
12
+ 1
+ 241
? 1
+ 361
- 241
? 0101
+ 101
? 101
- 101
? 101
+ 4000
? 0
Output
2
1
2
1
1
Input
4
+ 200
+ 200
- 200
? 0
Output
1
Note
Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.
1. 1 and 241.
2. 361.
3. 101 and 361.
4. 361.
5. 4000.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n, a[1000010];
long long calc(string s) {
long long ans = 0, cnt = 1;
for (long long i = s.length() - 1; i >= 0; i--)
ans += ((s[i] - '0') % 2) * cnt, cnt *= 2;
return ans;
}
signed main() {
scanf("%lld", &n);
for (long long i = 1; i <= n; i++) {
char c;
cin >> c;
string s;
cin >> s;
long long t = calc(s);
if (c == '+') a[t]++;
if (c == '-') a[t]--;
if (c == '?') printf("%lld\n", a[t]);
}
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game.
Input
The first line of the input contains one integer n (1 β€ n β€ 90) β the number of interesting minutes.
The second line contains n integers t1, t2, ..., tn (1 β€ t1 < t2 < ... tn β€ 90), given in the increasing order.
Output
Print the number of minutes Limak will watch the game.
Examples
Input
3
7 20 88
Output
35
Input
9
16 20 30 40 50 60 70 80 90
Output
15
Input
9
15 20 30 40 50 60 70 80 90
Output
90
Note
In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int M = 1000000007;
int main() {
long long n, i;
cin >> n;
long long A = 90, t, p = 0;
for (i = 0; i < n; i++) {
cin >> t;
if ((t - p) > 15) {
A = p + 15;
break;
}
p = t;
}
if (i == n && t < 76) A = t + 15;
cout << min(A, (long long)90) << endl;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
You have a string of decimal digits s. Let's define bij = siΒ·sj. Find in matrix b the number of such rectangles that the sum bij for all cells (i, j) that are the elements of the rectangle equals a in each rectangle.
A rectangle in a matrix is a group of four integers (x, y, z, t) (x β€ y, z β€ t). The elements of the rectangle are all cells (i, j) such that x β€ i β€ y, z β€ j β€ t.
Input
The first line contains integer a (0 β€ a β€ 109), the second line contains a string of decimal integers s (1 β€ |s| β€ 4000).
Output
Print a single integer β the answer to a problem.
Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
10
12345
Output
6
Input
16
439873893693495623498263984765
Output
40
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int mx = 4000 + 5;
const int mx1 = 36000;
bool vis[mx1];
map<int, long long int> mapa;
int main() {
int i, j, k, n;
long long int a;
string s;
cin >> a >> s;
n = s.size();
int sum;
int nint = 0;
for (i = 0; i < n; i++) {
sum = 0;
for (j = i; j < n; j++) {
sum += s[j] - '0';
if (mapa.count(sum) == 0)
mapa[sum] = 1;
else
mapa[sum]++;
nint++;
}
}
long long int ans = 0;
map<int, long long int>::iterator iti, itj;
for (iti = mapa.begin(); iti != mapa.end(); iti++) {
int suma = iti->first;
if (suma != 0 && a % suma == 0) {
int b = a / suma;
if (mapa.count(b) != 0) {
ans += mapa[suma] * mapa[b];
}
}
}
if (a == 0) ans = 2 * ans + mapa[0] * mapa[0];
cout << ans << endl;
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
The scientists have recently discovered wormholes β objects in space that allow to travel very long distances between galaxies and star systems.
The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i, j) and in exactly one galaxy day you will find yourself in galaxy j.
Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day.
Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists.
Input
The first line of the input contains a single integer n (1 β€ n β€ 1000) β the number of galaxies within reach.
Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100.
Output
Print a single real value β the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>.
Examples
Input
3
100 50 50
0 100 80
0 0 100
Output
1.750000000000000
Input
2
100 30
40 100
Output
3.333333333333333
Note
In the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is <image>.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 5;
int n;
double p[N][N], E[N], g[N], f[N];
bool vis[N];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) scanf("%lf", &p[i][j]), p[i][j] /= 100.0;
for (int i = 1; i <= n; i++) g[i] = 1 - p[i][n];
vis[n] = 1;
for (int i = 1; i <= n; i++) {
double mn = 1e18;
int id = 0;
for (int j = 1; j <= n; j++)
if (!vis[j] && (f[j] + 1) / (1 - g[j]) < mn) {
mn = (f[j] + 1) / (1 - g[j]);
id = j;
}
vis[id] = 1;
E[id] = (f[id] + 1) / (1 - g[id]);
for (int j = 1; j <= n; j++)
if (!vis[j])
f[j] += g[j] * p[j][id] * E[id], g[j] = g[j] * (1 - p[j][id]);
}
printf("%.6lf\n", E[1]);
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.
There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki people. The j-th person standing in the queue to the i-th cashier has mi, j items in the basket. Vasya knows that:
* the cashier needs 5 seconds to scan one item;
* after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change.
Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.
Input
The first line contains integer n (1 β€ n β€ 100) β the number of cashes in the shop. The second line contains n space-separated integers: k1, k2, ..., kn (1 β€ ki β€ 100), where ki is the number of people in the queue to the i-th cashier.
The i-th of the next n lines contains ki space-separated integers: mi, 1, mi, 2, ..., mi, ki (1 β€ mi, j β€ 100) β the number of products the j-th person in the queue for the i-th cash has.
Output
Print a single integer β the minimum number of seconds Vasya needs to get to the cashier.
Examples
Input
1
1
1
Output
20
Input
4
1 4 3 2
100
1 2 2 3
1 9 1
7 8
Output
100
Note
In the second test sample, if Vasya goes to the first queue, he gets to the cashier in 100Β·5 + 15 = 515 seconds. But if he chooses the second queue, he will need 1Β·5 + 2Β·5 + 2Β·5 + 3Β·5 + 4Β·15 = 100 seconds. He will need 1Β·5 + 9Β·5 + 1Β·5 + 3Β·15 = 100 seconds for the third one and 7Β·5 + 8Β·5 + 2Β·15 = 105 seconds for the fourth one. Thus, Vasya gets to the cashier quicker if he chooses the second or the third queue.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, q[105], val[105], a;
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &q[i]);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < q[i]; j++) {
scanf("%d", &a);
val[i] += (a * 5) + 15;
}
}
sort(val, val + n);
printf("%d\n", val[0]);
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
One day Vasya heard a story: "In the city of High Bertown a bus number 62 left from the bus station. It had n grown-ups and m kids..."
The latter events happen to be of no importance to us. Vasya is an accountant and he loves counting money. So he wondered what maximum and minimum sum of money these passengers could have paid for the ride.
The bus fare equals one berland ruble in High Bertown. However, not everything is that easy β no more than one child can ride for free with each grown-up passenger. That means that a grown-up passenger who rides with his k (k > 0) children, pays overall k rubles: a ticket for himself and (k - 1) tickets for his children. Also, a grown-up can ride without children, in this case he only pays one ruble.
We know that in High Bertown children can't ride in a bus unaccompanied by grown-ups.
Help Vasya count the minimum and the maximum sum in Berland rubles, that all passengers of this bus could have paid in total.
Input
The input file consists of a single line containing two space-separated numbers n and m (0 β€ n, m β€ 105) β the number of the grown-ups and the number of the children in the bus, correspondingly.
Output
If n grown-ups and m children could have ridden in the bus, then print on a single line two space-separated integers β the minimum and the maximum possible total bus fare, correspondingly.
Otherwise, print "Impossible" (without the quotes).
Examples
Input
1 2
Output
2 2
Input
0 5
Output
Impossible
Input
2 2
Output
2 3
Note
In the first sample a grown-up rides with two children and pays two rubles.
In the second sample there are only children in the bus, so the situation is impossible.
In the third sample there are two cases:
* Each of the two grown-ups rides with one children and pays one ruble for the tickets. In this case the passengers pay two rubles in total.
* One of the grown-ups ride with two children's and pays two rubles, the another one rides alone and pays one ruble for himself. So, they pay three rubles in total.
### Response
```cpp
#include <bits/stdc++.h>
int main() {
int n, m;
scanf("%d%d", &n, &m);
if (n == 0 && m == 0)
printf("%d\n%d", n, m);
else if (n == 0)
printf("Impossible");
else if (m == 0)
printf("%d\n%d", n, n);
else if (m > n)
printf("%d\n%d", m, n + m - 1);
else
printf("%d\n%d", n, n + m - 1);
return (0);
}
``` |
### Prompt
Create a solution in CPP for the following problem:
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
Input
The first line contains two integers n and m (2 β€ n, m β€ 100) β the number of employees and the number of languages.
Then n lines follow β each employee's language list. At the beginning of the i-th line is integer ki (0 β€ ki β€ m) β the number of languages the i-th employee knows. Next, the i-th line contains ki integers β aij (1 β€ aij β€ m) β the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces.
Output
Print a single integer β the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
Examples
Input
5 5
1 2
2 2 3
2 3 4
2 4 5
1 5
Output
0
Input
8 7
0
3 1 2 3
1 1
2 5 4
2 6 7
1 3
2 7 4
1 1
Output
2
Input
2 2
1 2
0
Output
1
Note
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n, m, vis[102];
vector<long long> lang[102], e[102];
void dfs(long long u) {
vis[u] = 1;
for (auto i : e[u]) {
if (!vis[i]) dfs(i);
}
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for (long long i = 1; i <= n; i++) {
long long t, x;
cin >> t;
for (long long j = 0; j < t; j++) cin >> x, lang[x].push_back(i);
}
bool ok = false;
for (long long i = 1; i <= m; i++) {
if (!lang[i].empty()) ok = true;
for (long long j = 0; j < (long long)lang[i].size(); j++) {
for (long long k = j + 1; k < (long long)lang[i].size(); k++) {
e[lang[i][j]].push_back(lang[i][k]);
e[lang[i][k]].push_back(lang[i][j]);
}
}
}
if (!ok) return cout << n << endl, 0;
long long comps = 0;
for (long long i = 1; i <= n; i++) {
if (!vis[i]) dfs(i), comps++;
}
cout << comps - 1 << endl;
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
There are 3^N people dancing in circle. We denote with 0,1,\dots, 3^{N}-1 the positions in the circle, starting from an arbitrary position and going around clockwise. Initially each position in the circle is occupied by one person.
The people are going to dance on two kinds of songs: salsa and rumba.
* When a salsa is played, the person in position i goes to position j, where j is the number obtained replacing all digits 1 with 2 and all digits 2 with 1 when reading i in base 3 (e.g., the person in position 46 goes to position 65).
* When a rumba is played, the person in position i moves to position i+1 (with the identification 3^N = 0).
You are given a string T=T_1T_2\cdots T_{|T|} such that T_i=`S` if the i-th song is a salsa and T_i=`R` if it is a rumba. After all the songs have been played, the person that initially was in position i is in position P_i. Compute the array P_0,P_1,\dots, P_{3^N-1}.
Constraints
* 1 \le N \le 12
* 1 \le |T| \le 200,000
* T contains only the characters `S` and `R`.
Input
Input is given from Standard Input in the following format:
N
T
Output
You should print on Standard Output:
P_0 P_1 \cdots P_{3^N-1}
Output
You should print on Standard Output:
P_0 P_1 \cdots P_{3^N-1}
Examples
Input
1
SRS
Output
2 0 1
Input
2
RRSRSSSSR
Output
3 8 1 0 5 7 6 2 4
Input
3
SRSRRSRRRSRRRR
Output
23 9 22 8 3 7 20 24 19 5 18 4 17 12 16 2 6 1 14 0 13 26 21 25 11 15 10
### Response
```cpp
#include <cstdio>
#include <cstring>
const int MN = 531441, MM = 200005;
int N, M, c;
char T[MM];
int A[MN], B[MN], V[MM];
int main() {
scanf("%d%s", &N, T + 1), M = strlen(T + 1), c = 1;
for (int i = 1; i <= M; ++i) V[i] = 0;
for (int i = 1; i <= N; ++i, c *= 3) {
int rev = 0;
for (int j = 0; j < c; ++j)
for (int d = 0; d < 3; ++d)
B[j + d * c] = d;
for (int j = 1; j <= M; ++j) {
if (T[j] == 'R') {
int lst = V[j];
for (int d = 0; d < 3; ++d) {
int p = lst + d * c;
if (B[p] + rev == 2) V[j] = p;
B[p] = (B[p] + rev + 1) % 3;
}
} else rev ^= 1;
}
for (int j = 0; j < c; ++j) {
int a = A[j];
for (int d = 0; d < 3; ++d) {
int p = j + d * c;
A[p] = a + (rev ? 3 - B[p] : B[p]) % 3 * c;
}
}
}
for (int i = 0; i < c; ++i) printf("%d%c", A[i], " \n"[i == c - 1]);
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
One cold winter evening Alice and her older brother Bob was sitting at home near the fireplace and giving each other interesting problems to solve. When it was Alice's turn, she told the number n to Bob and said:
βShuffle the digits in this number in order to obtain the smallest possible number without leading zeroes.
βNo problem! β said Bob and immediately gave her an answer.
Alice said a random number, so she doesn't know whether Bob's answer is correct. Help her to find this out, because impatient brother is waiting for the verdict.
Input
The first line contains one integer n (0 β€ n β€ 109) without leading zeroes. The second lines contains one integer m (0 β€ m β€ 109) β Bob's answer, possibly with leading zeroes.
Output
Print OK if Bob's answer is correct and WRONG_ANSWER otherwise.
Examples
Input
3310
1033
Output
OK
Input
4
5
Output
WRONG_ANSWER
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
char n[10], ans[10];
int l, i;
char c;
cin >> n >> ans;
l = strlen(n);
sort(n + 0, n + l);
for (i = 0; i < l; i++)
if (n[i] != '0' || i + 1 >= l) break;
c = n[i];
n[i] = n[0];
n[0] = c;
if (strcmp(n, ans) == 0)
cout << "OK" << endl;
else
cout << "WRONG_ANSWER" << endl;
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
We have a board with H horizontal rows and W vertical columns of squares. There is a bishop at the top-left square on this board. How many squares can this bishop reach by zero or more movements?
Here the bishop can only move diagonally. More formally, the bishop can move from the square at the r_1-th row (from the top) and the c_1-th column (from the left) to the square at the r_2-th row and the c_2-th column if and only if exactly one of the following holds:
* r_1 + c_1 = r_2 + c_2
* r_1 - c_1 = r_2 - c_2
For example, in the following figure, the bishop can move to any of the red squares in one move:
<image>
Constraints
* 1 \leq H, W \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H \ W
Output
Print the number of squares the bishop can reach.
Examples
Input
4 5
Output
10
Input
7 3
Output
11
Input
1000000000 1000000000
Output
500000000000000000
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
long long h,w,ans;cin>>h>>w;
ans=w*(h/2);
if(h%2) ans+=(w+1)/2;
if(h==1||w==1) ans=1;
cout<<ans;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Write a program which reads an integer n and prints the factorial of n. You can assume that n β€ 20.
Input
An integer n (1 β€ n β€ 20) in a line.
Output
Print the factorial of n in a line.
Example
Input
5
Output
120
### Response
```cpp
#include<iostream>
using namespace std;
int main(){
int n,i;
unsigned long long int ans=1;
cin>>n;
for(i=2;i<=n;i++){
ans*=i;
}
cout<<ans<<endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Again, there are hard times in Berland! Many towns have such tensions that even civil war is possible.
There are n towns in Reberland, some pairs of which connected by two-way roads. It is not guaranteed that it is possible to reach one town from any other town using these roads.
Towns s and t announce the final break of any relationship and intend to rule out the possibility of moving between them by the roads. Now possibly it is needed to close several roads so that moving from s to t using roads becomes impossible. Each town agrees to spend money on closing no more than one road, therefore, the total number of closed roads will be no more than two.
Help them find set of no more than two roads such that there will be no way between s and t after closing these roads. For each road the budget required for its closure was estimated. Among all sets find such that the total budget for the closure of a set of roads is minimum.
Input
The first line of the input contains two integers n and m (2 β€ n β€ 1000, 0 β€ m β€ 30 000) β the number of towns in Berland and the number of roads.
The second line contains integers s and t (1 β€ s, t β€ n, s β t) β indices of towns which break up the relationships.
Then follow m lines, each of them contains three integers xi, yi and wi (1 β€ xi, yi β€ n, 1 β€ wi β€ 109) β indices of towns connected by the i-th road, and the budget on its closure.
All roads are bidirectional. It is allowed that the pair of towns is connected by more than one road. Roads that connect the city to itself are allowed.
Output
In the first line print the minimum budget required to break up the relations between s and t, if it is allowed to close no more than two roads.
In the second line print the value c (0 β€ c β€ 2) β the number of roads to be closed in the found solution.
In the third line print in any order c diverse integers from 1 to m β indices of closed roads. Consider that the roads are numbered from 1 to m in the order they appear in the input.
If it is impossible to make towns s and t disconnected by removing no more than 2 roads, the output should contain a single line -1.
If there are several possible answers, you may print any of them.
Examples
Input
6 7
1 6
2 1 6
2 3 5
3 4 9
4 6 4
4 6 5
4 5 1
3 1 3
Output
8
2
2 7
Input
6 7
1 6
2 3 1
1 2 2
1 3 3
4 5 4
3 6 5
4 6 6
1 5 7
Output
9
2
4 5
Input
5 4
1 5
2 1 3
3 2 1
3 4 4
4 5 2
Output
1
1
2
Input
2 3
1 2
1 2 734458840
1 2 817380027
1 2 304764803
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > G[1000];
pair<int, pair<int, int> > E[1000];
bool V[30000], B[30000], B2[30000], vis[1000], P[30000], found = false,
initB = true;
int N, M, S, T, C[30000], td[1000], low[1000], K = 0, edges[1000][1000], ans, a,
b;
void predfs(int v) {
vis[v] = true;
if (v == T) {
found = true;
return;
}
for (int i = 0; i < (int)G[v].size(); i++) {
int u = G[v][i].first;
if (!vis[u]) predfs(u);
if (found) {
P[G[v][i].second] = true;
E[K++] = {G[v][i].second, {v, u}};
return;
}
}
}
void tarj(int u, int p) {
low[u] = td[u];
for (int i = 0; i < (int)G[u].size(); i++) {
int v = G[u][i].first;
if (!V[G[u][i].second]) continue;
if (v == p || td[v] > td[u]) continue;
if (td[v] == -1) {
td[v] = td[u] + 1;
tarj(v, u);
low[u] = min(low[u], low[v]);
if (low[v] == td[v] && edges[u][v] == 1) {
if (initB)
B[G[u][i].second] = true;
else {
if (!P[G[u][i].second]) B2[G[u][i].second] = true;
}
}
} else
low[u] = min(low[u], td[v]);
}
}
int main() {
scanf("%d %d", &N, &M);
scanf("%d %d", &S, &T);
S--;
T--;
memset(td, -1, sizeof(td));
for (int i = 0; i < (int)M; i++) {
int v, u, w;
scanf("%d %d %d", &v, &u, &w);
v--;
u--;
G[v].push_back({u, i});
G[u].push_back({v, i});
C[i] = w;
V[i] = true;
edges[v][u]++;
edges[u][v]++;
}
td[S] = 0;
tarj(S, -1);
initB = false;
predfs(S);
if (!found)
printf("0\n0\n");
else {
ans = 2100000000;
int id;
for (int k = 0; k < (int)K; k++) {
id = E[k].first;
if (B[id]) {
if (ans > C[id]) {
ans = C[id];
a = id;
b = id;
}
} else {
V[id] = false;
memset(B2, false, sizeof(B2));
memset(td, -1, sizeof(td));
td[S] = 0;
edges[E[k].second.first][E[k].second.second]--;
edges[E[k].second.second][E[k].second.first]--;
tarj(S, -1);
for (int i = 0; i < (int)M; i++) {
if (B2[i] && !B[i]) {
if (ans > C[id] + C[i]) {
ans = C[id] + C[i];
a = id;
b = i;
}
}
}
V[id] = true;
edges[E[k].second.first][E[k].second.second]++;
edges[E[k].second.second][E[k].second.first]++;
}
}
if (ans == 2100000000)
printf("-1\n");
else if (a == b)
printf("%d\n1\n%d\n", ans, a + 1);
else
printf("%d\n2\n%d %d\n", ans, a + 1, b + 1);
}
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Gerald bought two very rare paintings at the Sotheby's auction and he now wants to hang them on the wall. For that he bought a special board to attach it to the wall and place the paintings on the board. The board has shape of an a1 Γ b1 rectangle, the paintings have shape of a a2 Γ b2 and a3 Γ b3 rectangles.
Since the paintings are painted in the style of abstract art, it does not matter exactly how they will be rotated, but still, one side of both the board, and each of the paintings must be parallel to the floor. The paintings can touch each other and the edges of the board, but can not overlap or go beyond the edge of the board. Gerald asks whether it is possible to place the paintings on the board, or is the board he bought not large enough?
Input
The first line contains two space-separated numbers a1 and b1 β the sides of the board. Next two lines contain numbers a2, b2, a3 and b3 β the sides of the paintings. All numbers ai, bi in the input are integers and fit into the range from 1 to 1000.
Output
If the paintings can be placed on the wall, print "YES" (without the quotes), and if they cannot, print "NO" (without the quotes).
Examples
Input
3 2
1 3
2 1
Output
YES
Input
5 5
3 3
3 3
Output
NO
Input
4 2
2 3
1 2
Output
YES
Note
That's how we can place the pictures in the first test:
<image>
And that's how we can do it in the third one.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a, b;
int c, d, x, y;
cin >> a >> b;
cin >> c >> d >> x >> y;
if (c + x <= a && max(d, y) <= b) {
cout << "YES";
} else if (c + y <= a && max(d, x) <= b) {
cout << "YES";
} else if (c + x <= b && max(d, y) <= a) {
cout << "YES";
} else if (c + y <= b && max(d, x) <= a) {
cout << "YES";
} else if (d + x <= a && max(c, y) <= b) {
cout << "YES";
} else if (d + y <= a && max(c, x) <= b) {
cout << "YES";
} else if (d + x <= b && max(c, y) <= a) {
cout << "YES";
} else if (d + y <= b && max(c, x) <= a) {
cout << "YES";
} else {
cout << "NO";
}
cout << endl;
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Vasya has the sequence consisting of n integers. Vasya consider the pair of integers x and y k-interesting, if their binary representation differs from each other exactly in k bits. For example, if k = 2, the pair of integers x = 5 and y = 3 is k-interesting, because their binary representation x=101 and y=011 differs exactly in two bits.
Vasya wants to know how many pairs of indexes (i, j) are in his sequence so that i < j and the pair of integers ai and aj is k-interesting. Your task is to help Vasya and determine this number.
Input
The first line contains two integers n and k (2 β€ n β€ 105, 0 β€ k β€ 14) β the number of integers in Vasya's sequence and the number of bits in which integers in k-interesting pair should differ.
The second line contains the sequence a1, a2, ..., an (0 β€ ai β€ 104), which Vasya has.
Output
Print the number of pairs (i, j) so that i < j and the pair of integers ai and aj is k-interesting.
Examples
Input
4 1
0 3 2 1
Output
4
Input
6 0
200 100 100 100 200 200
Output
6
Note
In the first test there are 4 k-interesting pairs:
* (1, 3),
* (1, 4),
* (2, 3),
* (2, 4).
In the second test k = 0. Consequently, integers in any k-interesting pair should be equal to themselves. Thus, for the second test there are 6 k-interesting pairs:
* (1, 5),
* (1, 6),
* (2, 3),
* (2, 4),
* (3, 4),
* (5, 6).
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int nums[10001];
int bitnum(int a) {
int c = 0;
while (a > 0) {
c += a % 2;
a /= 2;
}
return c;
}
int main() {
int n, k;
scanf("%d%d", &n, &k);
for (int i = 0; i < n; i++) {
int a;
scanf("%d", &a);
nums[a]++;
}
long long ans = 0;
for (int i = 0; i <= 10000; i++)
for (int j = i; j <= 10000; j++)
if (bitnum(i ^ j) == k)
if (i == j) {
long long temp = nums[i];
temp *= temp;
temp -= nums[i];
temp /= 2;
ans += temp;
} else {
long long temp = nums[i];
temp *= nums[j];
ans += temp;
}
cout << ans << endl;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M β S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a β b.
Kate is a very neat girl and for each k β \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k.
Please, help Kate to find I_2, I_3, ..., I_n.
Input
The first and only line in the input consists of only one integer n (2β€ n β€ 5 β
10^5) β the size of the given set S.
Output
Output contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.
Examples
Input
2
Output
1
Input
3
Output
1 1
Note
First sample: answer is 1, because gcd(1, 2) = 1.
Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
namespace {
const int MAXN = 500000;
int mn[MAXN + 13];
void preprocess() {
for (int i = 1; i <= MAXN; ++i) {
mn[i] = i;
}
for (int i = 2; i * i <= MAXN; ++i) {
if (mn[i] != i) continue;
for (int j = i * i; j <= MAXN; j += i) {
mn[j] = min(mn[j], i);
}
}
}
void test() {
int n;
cin >> n;
vector<int> v(n);
for (int i = 0; i < n; ++i) v[i] = i + 1;
sort(v.begin(), v.end(),
[](int i, int j) { return (i / mn[i]) < (j / mn[j]); });
for (int i = 1; i < n; ++i) {
cout << (v[i] / mn[v[i]]) << ' ';
}
return void(cout << ("\n") << endl);
}
} // namespace
int main() {
preprocess();
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t = 1;
while (t--) test();
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
The Little Elephant loves to play with color cards.
He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered).
Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β colors of both sides. The first number in a line is the color of the front of the card, the second one β of the back. The color of the front of the card may coincide with the color of the back of the card.
The numbers in the lines are separated by single spaces.
Output
On a single line print a single integer β the sought minimum number of moves. If it is impossible to make the set funny, print -1.
Examples
Input
3
4 7
4 7
7 4
Output
0
Input
5
4 7
7 4
2 11
9 7
1 1
Output
2
Note
In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0.
In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
map<int, int> mpu, mpd, eq;
int main() {
int n;
scanf("%d", &n);
int um = -1, dm = -1;
for (int i = 0; i < n; i++) {
int u, d;
scanf("%d%d", &u, &d);
mpu[u]++;
mpd[d]++;
if (u == d) eq[u]++;
um = max(um, mpu[u]);
dm = max(dm, mpd[d]);
}
int hf;
int ans = 0x7f7f7f7f;
if (n % 2)
hf = n / 2 + 1;
else
hf = n / 2;
if (um >= hf) {
printf("0\n");
} else {
for (auto e : mpu) {
if (mpd.find(e.first) != mpd.end()) {
int dif = 0;
if (eq.find(e.first) != eq.end()) dif = eq[e.first];
int num = e.second + mpd[e.first] - dif;
if (num >= hf) ans = min(ans, hf - mpu[e.first]);
}
}
if (ans == 0x7f7f7f7f) {
if (dm >= hf)
ans = hf;
else
ans = -1;
}
printf("%d\n", ans);
}
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
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 <bits/stdc++.h>
using namespace std;
int main(void){
int N,A,B;
cin>>N>>A>>B;
cout<<min(min(A+N,B+N),A+B)<<endl;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l β€ r) are integers. Weβll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1).
A substring s[l... r] (1 β€ l β€ r β€ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr.
Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 β€ l β€ r β€ |p|) such that p[l... r] = t.
Weβll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] β s[z... w].
Input
The first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 β€ li β€ ri β€ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters.
The input limits for scoring 30 points are (subproblem G1):
* 0 β€ n β€ 10.
* The length of string s and the maximum length of string p is β€ 200.
The input limits for scoring 70 points are (subproblems G1+G2):
* 0 β€ n β€ 10.
* The length of string s and the maximum length of string p is β€ 2000.
The input limits for scoring 100 points are (subproblems G1+G2+G3):
* 0 β€ n β€ 10.
* The length of string s and the maximum length of string p is β€ 50000.
Output
Print a single integer β the number of good substrings of string s.
Examples
Input
aaab
2
aa 0 0
aab 1 1
Output
3
Input
ltntlnen
3
n 0 0
ttlneenl 1 4
lelllt 1 1
Output
2
Input
a
0
Output
1
Note
There are three good substrings in the first sample test: Β«aabΒ», Β«abΒ» and Β«bΒ».
In the second test only substrings Β«eΒ» and Β«tΒ» are good.
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
const int maxn = 2e3 + 10, maxm = 1e3 + 10;
const long long mod = 1e9 + 12341;
int n, m;
const long long decm = 128;
long long pw[maxn];
void init(int n = maxn - 5) {
pw[0] = 1;
for (int i = 1; i <= n; ++i) pw[i] = pw[i - 1] * decm % mod;
}
class strhash {
public:
long long hs[maxn], len;
long long calhs(string &s, int n) {
len = n;
for (int i = 0; i <= len - 1; ++i) hs[i + 1] = (hs[i] * decm + s[i]) % mod;
return hs[len];
}
inline long long geths(int a, int b) {
return (hs[b] - (hs[a - 1] * pw[b - a + 1]) % mod + mod) % mod;
}
} mps, mpt[20];
int l[20], r[20];
vector<long long> h;
unordered_map<long long, int> cnt[20];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
init(maxn - 5);
string s;
cin >> s;
cin >> n;
mps.calhs(s, s.size());
m = s.size();
for (int i = 1; i <= m; ++i)
for (int j = i; j <= m; ++j) h.push_back(mps.geths(i, j));
sort(h.begin(), h.end());
h.erase(unique(h.begin(), h.end()), h.end());
for (int i = 1; i <= n; ++i) {
string t;
cin >> t >> l[i] >> r[i];
mpt[i].calhs(t, t.size());
int len = t.size();
for (int j = 1; j <= len; ++j)
for (int k = j; k <= len; ++k) cnt[i][mpt[i].geths(j, k)]++;
}
long long ans = 0;
for (auto hs : h) {
int flag = 0;
for (int i = 1; i <= n; ++i) {
int num = cnt[i][hs];
if (num >= l[i] && num <= r[i]) flag++;
}
if (flag == n) ans++;
}
cout << ans << '\n';
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
The king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square t. As the king is not in habit of wasting his time, he wants to get from his current position s to square t in the least number of moves. Help him to do this.
<image>
In one move the king can get to the square that has a common side or a common vertex with the square the king is currently in (generally there are 8 different squares he can move to).
Input
The first line contains the chessboard coordinates of square s, the second line β of square t.
Chessboard coordinates consist of two characters, the first one is a lowercase Latin letter (from a to h), the second one is a digit from 1 to 8.
Output
In the first line print n β minimum number of the king's moves. Then in n lines print the moves themselves. Each move is described with one of the 8: L, R, U, D, LU, LD, RU or RD.
L, R, U, D stand respectively for moves left, right, up and down (according to the picture), and 2-letter combinations stand for diagonal moves. If the answer is not unique, print any of them.
Examples
Input
a8
h1
Output
7
RD
RD
RD
RD
RD
RD
RD
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
char a[5];
for (int i = 0; i < 5; i++) a[i] = getchar();
int x = a[3] - a[0];
int y = a[4] - a[1];
int ans = max(fabs(x), fabs(y));
printf("%d\n", ans);
while (x != 0) {
if (x > 0)
if (y > 0) {
printf("RU\n");
x--;
y--;
} else if (y < 0) {
printf("RD\n");
x--;
y++;
} else {
printf("R\n");
x--;
}
else if (y > 0) {
printf("LU\n");
x++;
y--;
} else if (y < 0) {
printf("LD\n");
x++;
y++;
} else {
printf("L\n");
x++;
}
}
while (y != 0) {
if (y > 0) {
y--;
printf("U\n");
} else {
y++;
printf("D\n");
}
}
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
You are a paparazzi working in Manhattan.
Manhattan has r south-to-north streets, denoted by numbers 1, 2,β¦, r in order from west to east, and r west-to-east streets, denoted by numbers 1,2,β¦,r in order from south to north. Each of the r south-to-north streets intersects each of the r west-to-east streets; the intersection between the x-th south-to-north street and the y-th west-to-east street is denoted by (x, y). In order to move from the intersection (x,y) to the intersection (x', y') you need |x-x'|+|y-y'| minutes.
You know about the presence of n celebrities in the city and you want to take photos of as many of them as possible. More precisely, for each i=1,..., n, you know that the i-th celebrity will be at the intersection (x_i, y_i) in exactly t_i minutes from now (and he will stay there for a very short time, so you may take a photo of him only if at the t_i-th minute from now you are at the intersection (x_i, y_i)). You are very good at your job, so you are able to take photos instantaneously. You know that t_i < t_{i+1} for any i=1,2,β¦, n-1.
Currently you are at your office, which is located at the intersection (1, 1). If you plan your working day optimally, what is the maximum number of celebrities you can take a photo of?
Input
The first line of the input contains two positive integers r, n (1β€ rβ€ 500, 1β€ nβ€ 100,000) β the number of south-to-north/west-to-east streets and the number of celebrities.
Then n lines follow, each describing the appearance of a celebrity. The i-th of these lines contains 3 positive integers t_i, x_i, y_i (1β€ t_iβ€ 1,000,000, 1β€ x_i, y_iβ€ r) β denoting that the i-th celebrity will appear at the intersection (x_i, y_i) in t_i minutes from now.
It is guaranteed that t_i<t_{i+1} for any i=1,2,β¦, n-1.
Output
Print a single integer, the maximum number of celebrities you can take a photo of.
Examples
Input
10 1
11 6 8
Output
0
Input
6 9
1 2 6
7 5 1
8 5 5
10 3 1
12 4 4
13 6 2
17 6 6
20 1 4
21 5 4
Output
4
Input
10 4
1 2 1
5 10 9
13 8 8
15 9 9
Output
1
Input
500 10
69 477 122
73 186 235
341 101 145
372 77 497
390 117 440
494 471 37
522 300 498
682 149 379
821 486 359
855 157 386
Output
3
Note
Explanation of the first testcase: There is only one celebrity in the city, and he will be at intersection (6,8) exactly 11 minutes after the beginning of the working day. Since you are initially at (1,1) and you need |1-6|+|1-8|=5+7=12 minutes to reach (6,8) you cannot take a photo of the celebrity. Thus you cannot get any photo and the answer is 0.
Explanation of the second testcase: One way to take 4 photos (which is the maximum possible) is to take photos of celebrities with indexes 3, 5, 7, 9 (see the image for a visualization of the strategy):
* To move from the office at (1,1) to the intersection (5,5) you need |1-5|+|1-5|=4+4=8 minutes, so you arrive at minute 8 and you are just in time to take a photo of celebrity 3.
* Then, just after you have taken a photo of celebrity 3, you move toward the intersection (4,4). You need |5-4|+|5-4|=1+1=2 minutes to go there, so you arrive at minute 8+2=10 and you wait until minute 12, when celebrity 5 appears.
* Then, just after you have taken a photo of celebrity 5, you go to the intersection (6,6). You need |4-6|+|4-6|=2+2=4 minutes to go there, so you arrive at minute 12+4=16 and you wait until minute 17, when celebrity 7 appears.
* Then, just after you have taken a photo of celebrity 7, you go to the intersection (5,4). You need |6-5|+|6-4|=1+2=3 minutes to go there, so you arrive at minute 17+3=20 and you wait until minute 21 to take a photo of celebrity 9.
<image>
Explanation of the third testcase: The only way to take 1 photo (which is the maximum possible) is to take a photo of the celebrity with index 1 (since |2-1|+|1-1|=1, you can be at intersection (2,1) after exactly one minute, hence you are just in time to take a photo of celebrity 1).
Explanation of the fourth testcase: One way to take 3 photos (which is the maximum possible) is to take photos of celebrities with indexes 3, 8, 10:
* To move from the office at (1,1) to the intersection (101,145) you need |1-101|+|1-145|=100+144=244 minutes, so you can manage to be there when the celebrity 3 appears (at minute 341).
* Then, just after you have taken a photo of celebrity 3, you move toward the intersection (149,379). You need |101-149|+|145-379|=282 minutes to go there, so you arrive at minute 341+282=623 and you wait until minute 682, when celebrity 8 appears.
* Then, just after you have taken a photo of celebrity 8, you go to the intersection (157,386). You need |149-157|+|379-386|=8+7=15 minutes to go there, so you arrive at minute 682+15=697 and you wait until minute 855 to take a photo of celebrity 10.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 7;
int ans[N], ma[N];
int t[N], x[N], y[N];
int main() {
int i, j, k;
int n, m, r;
scanf("%d%d", &r, &n);
for (i = 1; i <= n; i++) {
scanf("%d%d%d", &t[i], &x[i], &y[i]);
}
t[0] = 0;
x[0] = 1;
y[0] = 1;
ans[0] = 1;
ma[0] = 1;
for (i = 1; i <= n; i++) {
for (j = i - 1; j >= 0; j--) {
if (t[i] - t[j] > 1000) break;
int step = abs(x[i] - x[j]) + abs(y[i] - y[j]);
if (t[i] - t[j] >= step && ans[j] != 0) ans[i] = max(ans[i], ans[j] + 1);
}
if (j >= 0 && ma[j] > 0) ans[i] = max(ans[i], ma[j] + 1);
ma[i] = max(ma[i - 1], ans[i]);
}
printf("%d\n", max(ma[n] - 1, 0));
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
You are given a program you want to execute as a set of tasks organized in a dependency graph. The dependency graph is a directed acyclic graph: each task can depend on results of one or several other tasks, and there are no directed circular dependencies between tasks. A task can only be executed if all tasks it depends on have already completed.
Some of the tasks in the graph can only be executed on a coprocessor, and the rest can only be executed on the main processor. In one coprocessor call you can send it a set of tasks which can only be executed on it. For each task of the set, all tasks on which it depends must be either already completed or be included in the set. The main processor starts the program execution and gets the results of tasks executed on the coprocessor automatically.
Find the minimal number of coprocessor calls which are necessary to execute the given program.
Input
The first line contains two space-separated integers N (1 β€ N β€ 105) β the total number of tasks given, and M (0 β€ M β€ 105) β the total number of dependencies between tasks.
The next line contains N space-separated integers <image>. If Ei = 0, task i can only be executed on the main processor, otherwise it can only be executed on the coprocessor.
The next M lines describe the dependencies between tasks. Each line contains two space-separated integers T1 and T2 and means that task T1 depends on task T2 (T1 β T2). Tasks are indexed from 0 to N - 1. All M pairs (T1, T2) are distinct. It is guaranteed that there are no circular dependencies between tasks.
Output
Output one line containing an integer β the minimal number of coprocessor calls necessary to execute the program.
Examples
Input
4 3
0 1 0 1
0 1
1 2
2 3
Output
2
Input
4 3
1 1 1 0
0 1
0 2
3 0
Output
1
Note
In the first test, tasks 1 and 3 can only be executed on the coprocessor. The dependency graph is linear, so the tasks must be executed in order 3 -> 2 -> 1 -> 0. You have to call coprocessor twice: first you call it for task 3, then you execute task 2 on the main processor, then you call it for for task 1, and finally you execute task 0 on the main processor.
In the second test, tasks 0, 1 and 2 can only be executed on the coprocessor. Tasks 1 and 2 have no dependencies, and task 0 depends on tasks 1 and 2, so all three tasks 0, 1 and 2 can be sent in one coprocessor call. After that task 3 is executed on the main processor.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m;
bool imp[100005];
vector<int> g[100005];
int sol[100005], id[100005];
void toposort() {
queue<int> q;
for (int it = 0; it < n; it++) {
if (!id[it]) {
q.push(it);
sol[it] = imp[it];
}
}
while (!q.empty()) {
int t = q.front();
q.pop();
for (int i = 0; i < g[t].size(); i++) {
int v = g[t][i];
id[v]--;
sol[v] = max(sol[v], sol[t] + ((imp[t] == 0) && (imp[v] == 1)));
if (id[v] == 0) {
q.push(v);
}
}
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> imp[i];
}
for (int i = 0; i < m; i++) {
pair<int, int> a;
cin >> a.first >> a.second;
g[a.first].push_back(a.second);
id[a.second]++;
}
toposort();
int ans = 0;
for (int i = 0; i < n; i++) {
ans = max(ans, sol[i]);
}
cout << ans;
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
The Squareland national forest is divided into equal 1 Γ 1 square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates (x, y) of its south-west corner.
Three friends, Alice, Bob, and Charlie are going to buy three distinct plots of land A, B, C in the forest. Initially, all plots in the forest (including the plots A, B, C) are covered by trees. The friends want to visit each other, so they want to clean some of the plots from trees. After cleaning, one should be able to reach any of the plots A, B, C from any other one of those by moving through adjacent cleared plots. Two plots are adjacent if they share a side.
<image> For example, A=(0,0), B=(1,1), C=(2,2). The minimal number of plots to be cleared is 5. One of the ways to do it is shown with the gray color.
Of course, the friends don't want to strain too much. Help them find out the smallest number of plots they need to clean from trees.
Input
The first line contains two integers x_A and y_A β coordinates of the plot A (0 β€ x_A, y_A β€ 1000). The following two lines describe coordinates (x_B, y_B) and (x_C, y_C) of plots B and C respectively in the same format (0 β€ x_B, y_B, x_C, y_C β€ 1000). It is guaranteed that all three plots are distinct.
Output
On the first line print a single integer k β the smallest number of plots needed to be cleaned from trees. The following k lines should contain coordinates of all plots needed to be cleaned. All k plots should be distinct. You can output the plots in any order.
If there are multiple solutions, print any of them.
Examples
Input
0 0
1 1
2 2
Output
5
0 0
1 0
1 1
1 2
2 2
Input
0 0
2 0
1 1
Output
4
0 0
1 0
1 1
2 0
Note
The first example is shown on the picture in the legend.
The second example is illustrated with the following image:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<int> di = {0, 0, 1, -1};
vector<int> dj = {1, -1, 0, 0};
int main() {
ios::sync_with_stdio(0), cin.tie(0);
vector<vector<int>> dpa(1001, vector<int>(1001, 2140000000));
vector<vector<int>> dpb(1001, vector<int>(1001, 2140000000));
vector<vector<int>> dpc(1001, vector<int>(1001, 2140000000));
vector<vector<pair<int, int>>> pa(
1001, vector<pair<int, int>>(1001, {2140000000, 0}));
vector<vector<pair<int, int>>> pb(
1001, vector<pair<int, int>>(1001, {2140000000, 0}));
vector<vector<pair<int, int>>> pc(
1001, vector<pair<int, int>>(1001, {2140000000, 0}));
int xa, ya;
cin >> xa >> ya;
dpa[xa][ya] = 0;
int xb, yb;
cin >> xb >> yb;
dpb[xb][yb] = 0;
int xc, yc;
cin >> xc >> yc;
dpc[xc][yc] = 0;
queue<pair<int, int>> q;
q.push({xa, ya});
while (!q.empty()) {
int vx = q.front().first;
int vy = q.front().second;
q.pop();
for (int i = 0; i < 4; i++) {
int tx = vx + di[i];
int ty = vy + dj[i];
if (tx >= 0 && tx <= 1000 && ty >= 0 && ty <= 1000 &&
dpa[tx][ty] == 2140000000) {
q.push({tx, ty});
dpa[tx][ty] = dpa[vx][vy] + 1;
pa[tx][ty] = {vx, vy};
}
}
}
q.push({xb, yb});
while (!q.empty()) {
int vx = q.front().first;
int vy = q.front().second;
q.pop();
for (int i = 0; i < 4; i++) {
int tx = vx + di[i];
int ty = vy + dj[i];
if (tx >= 0 && tx <= 1000 && ty >= 0 && ty <= 1000 &&
dpb[tx][ty] == 2140000000) {
q.push({tx, ty});
dpb[tx][ty] = dpb[vx][vy] + 1;
pb[tx][ty] = {vx, vy};
}
}
}
q.push({xc, yc});
while (!q.empty()) {
int vx = q.front().first;
int vy = q.front().second;
q.pop();
for (int i = 0; i < 4; i++) {
int tx = vx + di[i];
int ty = vy + dj[i];
if (tx >= 0 && tx <= 1000 && ty >= 0 && ty <= 1000 &&
dpc[tx][ty] == 2140000000) {
q.push({tx, ty});
dpc[tx][ty] = dpc[vx][vy] + 1;
pc[tx][ty] = {vx, vy};
}
}
}
int ans = 2140000000;
int ansx;
int ansy;
for (int i = 0; i <= 1000; i++) {
for (int j = 0; j <= 1000; j++) {
if (dpa[i][j] + dpb[i][j] + dpc[i][j] + 1 < ans) {
ans = dpa[i][j] + dpb[i][j] + dpc[i][j] + 1;
ansx = i;
ansy = j;
}
}
}
cout << ans << endl;
int sax = ansx;
int say = ansy;
int sbx = ansx;
int sby = ansy;
int scx = ansx;
int scy = ansy;
vector<vector<int>> used(1001, vector<int>(1001, 0));
while (make_pair(sax, say) != make_pair(2140000000, 0)) {
int tx = sax;
sax = pa[sax][say].first;
say = pa[tx][say].second;
if (make_pair(sax, say) != make_pair(2140000000, 0) && !used[sax][say]) {
cout << sax << ' ' << say << endl;
used[sax][say] = 1;
}
}
while (make_pair(sbx, sby) != make_pair(2140000000, 0)) {
int tx = sbx;
sbx = pb[sbx][sby].first;
sby = pb[tx][sby].second;
if (make_pair(sbx, sby) != make_pair(2140000000, 0) && !used[sbx][sby]) {
cout << sbx << ' ' << sby << endl;
used[sbx][sby] = 1;
}
}
while (make_pair(scx, scy) != make_pair(2140000000, 0)) {
int tx = scx;
scx = pc[scx][scy].first;
scy = pc[tx][scy].second;
if (make_pair(scx, scy) != make_pair(2140000000, 0) && !used[scx][scy]) {
cout << scx << ' ' << scy << endl;
used[scx][scy] = 1;
}
}
cout << ansx << ' ' << ansy << endl;
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Taro is planning a long trip by train during the summer vacation. However, in order for Taro, who is a high school student, to travel as far as possible during the summer vacation, which has only one month, he cannot make a good plan unless he finds the cheapest and the fastest way. Let's create a program to help Taro's plan so that he can enjoy a wonderful trip.
<image>
Create a program that outputs the minimum amount or the shortest time in response to inquiries by inputting track information and the number of stations.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
n m
a1 b1 cost1 time1
a2 b2 cost2 time2
::
an bn costn timen
k
p1 q1 r1
p2 q2 r2
::
pk qk rk
The first line gives the number of track information n (1 β€ n β€ 3000) and the number of stations m (1 β€ m β€ 100).
The following n lines give information on the i-th line. As information on each line, the numbers ai, bi (1 β€ ai, bi β€ m) of the two stations connecting the lines, the toll costi (1 β€ costi β€ 1000), and the travel time timei (1 β€ timei β€ 1000) are given. I will. However, each station shall be numbered in order from 1 to m. If ai and bi are connected by railroad tracks, both ai to bi and bi to ai can be moved at the same rate and time.
The following line is given the number of queries k (1 β€ k β€ 200). The next k line is given the i-th query. For each query, the departure station pi, the arrival station qi, and the type of value to output ri (0 or 1) are given. Inquiries must have a route.
The number of datasets does not exceed 50.
Output
Outputs the minimum amount or minimum time on one line for each data set. When ri is 0, the minimum amount is output, and when ri is 1, the minimum time is output.
Example
Input
6 5
1 2 200 10
1 4 400 15
1 3 250 25
2 4 100 10
4 5 150 20
3 5 300 20
2
1 5 0
1 5 1
0 0
Output
450
35
### Response
```cpp
#include <iostream>
using namespace std;
int main() {
int a, b, n, m, k, p, q, r, cost, time, datas[300][300][2];
while (cin >> n >> m, n || m) {
for (int y = 0; y < m; ++y)
for (int x = 0; x < m; ++x)
datas[y][x][0] = 10000, datas[y][x][1] = 10000;
for (int x = 0; x < m; ++x)
datas[x][x][0] = 0, datas[x][x][1] = 0;
for (int i = 0; i < n; ++i) {
cin >> a >> b >> cost >> time;
--a, --b;
datas[a][b][0] = cost, datas[a][b][1] = time;
datas[b][a][0] = cost, datas[b][a][1] = time;
}
for (int i = 0; i < m; ++i)
for (int j = 0; j < m; ++j)
for (k = 0; k < m; ++k) {
if (datas[j][i][0]+datas[i][k][0] < datas[j][k][0])
datas[j][k][0] = datas[j][i][0]+datas[i][k][0];
if (datas[j][i][1]+datas[i][k][1] < datas[j][k][1])
datas[j][k][1] = datas[j][i][1]+datas[i][k][1];
}
cin >> k;
for (int i = 0; i < k; ++i) {
cin >> p >> q >> r;
cout << datas[p-1][q-1][r] << endl;
}
}
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s.
String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".
Dr. Moriarty plans to take string s and cut out some substring from it, let's call it t. Then he needs to change the substring t zero or more times. As a result, he should obtain a fixed string u (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions:
* Insert one letter to any end of the string.
* Delete one letter from any end of the string.
* Change one letter into any other one.
Moriarty is very smart and after he chooses some substring t, he always makes the minimal number of changes to obtain u.
Help Moriarty choose the best substring t from all substrings of the string s. The substring t should minimize the number of changes Moriarty should make to obtain the string u from it.
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters. The second line contains a non-empty string u, consisting of lowercase Latin letters. The lengths of both strings are in the range from 1 to 2000, inclusive.
Output
Print the only integer β the minimum number of changes that Dr. Moriarty has to make with the string that you choose.
Examples
Input
aaaaa
aaa
Output
0
Input
abcabc
bcd
Output
1
Input
abcdef
klmnopq
Output
7
Note
In the first sample Moriarty can take any substring of length 3, and it will be equal to the required message u, so Moriarty won't have to make any changes.
In the second sample you should take a substring consisting of characters from second to fourth ("bca") or from fifth to sixth ("bc"). Then you will only have to make one change: to change or to add the last character.
In the third sample the initial string s doesn't contain any character that the message should contain, so, whatever string you choose, you will have to make at least 7 changes to obtain the required message.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a, b, c, d, e;
string s, s2;
int main() {
cin >> s;
cin >> s2;
e = 0;
for (a = 0; a < s.length(); a++) {
b = 0;
c = a;
d = 0;
while (c < s.length() && b < s2.length()) {
if (s[c] == s2[b]) d++;
b++;
c++;
}
e = max(e, d);
}
for (a = 0; a < s2.length(); a++) {
b = 0;
c = a;
d = 0;
while (c < s2.length() && b < s.length()) {
if (s2[c] == s[b]) d++;
b++;
c++;
}
e = max(e, d);
}
printf("%d\n", s2.length() - e);
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.
Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.
Peter decided to tie his car to point P and now he is wondering what is the area of ββthe region that will be cleared from snow. Help him.
Input
The first line of the input contains three integers β the number of vertices of the polygon n (<image>), and coordinates of point P.
Each of the next n lines contains two integers β coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line.
All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.
Output
Print a single real value number β the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>.
Examples
Input
3 0 0
0 1
-1 2
1 2
Output
12.566370614359172464
Input
4 1 -1
0 0
1 2
2 0
1 1
Output
21.991148575128551812
Note
In the first sample snow will be removed from that area:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct point {
double x;
double y;
};
point temp;
double dist(point p1, point p2) {
return sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2));
}
void foot(point a, point b, point c) {
temp.x = (c.x * (b.y - a.y) - c.y * (b.x - a.x) + a.y * b.x - a.x * b.y) /
(pow(b.y - a.y, 2) + pow(b.x - a.x, 2)) * (b.y - a.y) * (-1) +
c.x;
temp.y = (c.x * (b.y - a.y) - c.y * (b.x - a.x) + a.y * b.x - a.x * b.y) /
(pow(b.y - a.y, 2) + pow(b.x - a.x, 2)) * (a.x - b.x) * (-1) +
c.y;
}
double ldist(point a, point b, point c) {
return fabs(c.x * (b.y - a.y) - c.y * (b.x - a.x) + a.y * b.x - a.x * b.y) /
sqrt(pow(b.y - a.y, 2) + pow(b.x - a.x, 2));
}
int main() {
double n, min1, max1, temp2, ans, pi = 3.14159265358979;
point p;
cin >> n >> p.x >> p.y;
point poly[(int)n + 1];
for (int i = 0; i < n; i++) cin >> poly[i].x >> poly[i].y;
poly[(int)n].x = poly[0].x;
poly[(int)n].y = poly[0].y;
max1 = dist(p, poly[0]);
foot(poly[0], poly[1], p);
if (max(dist(temp, poly[0]), dist(temp, poly[1])) <= dist(poly[0], poly[1]))
min1 = ldist(poly[0], poly[1], p);
else
min1 = dist(p, poly[0]);
for (int i = 1; i < n; i++) {
max1 = max(max1, dist(p, poly[i]));
foot(poly[i], poly[i + 1], p);
if (max(dist(temp, poly[i]), dist(temp, poly[i + 1])) <=
dist(poly[i], poly[i + 1])) {
min1 = min(min1, ldist(poly[i], poly[i + 1], p));
} else
min1 = min(min1, dist(p, poly[i]));
}
ans = pi * (pow(max1, 2) - pow(min1, 2));
printf("%.15lf", ans);
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Ivan has number b. He is sorting through the numbers a from 1 to 10^{18}, and for every a writes ([a, b])/(a) on blackboard. Here [a, b] stands for least common multiple of a and b. Ivan is very lazy, that's why this task bored him soon. But he is interested in how many different numbers he would write on the board if he would finish the task. Help him to find the quantity of different numbers he would write on the board.
Input
The only line contains one integer β b (1 β€ b β€ 10^{10}).
Output
Print one number β answer for the problem.
Examples
Input
1
Output
1
Input
2
Output
2
Note
In the first example [a, 1] = a, therefore ([a, b])/(a) is always equal to 1.
In the second example [a, 2] can be equal to a or 2 β
a depending on parity of a. ([a, b])/(a) can be equal to 1 and 2.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long b, i, counter = 0, x = 0;
cin >> b;
for (i = 1; i <= sqrt(b); i++) {
if (b % i == 0) counter++;
}
x = sqrt(b);
if (x == sqrt(b))
cout << counter * 2 - 1 << endl;
else
cout << counter * 2 << endl;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
You are given an undirected graph with weighted edges. The length of some path between two vertices is the bitwise xor of weights of all edges belonging to this path (if some edge is traversed more than once, then it is included in bitwise xor the same number of times). You have to find the minimum length of path between vertex 1 and vertex n.
Note that graph can contain multiple edges and loops. It is guaranteed that the graph is connected.
Input
The first line contains two numbers n and m (1 β€ n β€ 100000, n - 1 β€ m β€ 100000) β the number of vertices and the number of edges, respectively.
Then m lines follow, each line containing three integer numbers x, y and w (1 β€ x, y β€ n, 0 β€ w β€ 108). These numbers denote an edge that connects vertices x and y and has weight w.
Output
Print one number β the minimum length of path between vertices 1 and n.
Examples
Input
3 3
1 2 3
1 3 2
3 2 0
Output
2
Input
2 2
1 1 3
1 2 3
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m, x, y, z, kk, head[500005], dis[500005], b[500005];
bool vis[500005];
struct Edge {
int nxt, to, step;
} e[500005];
inline void link(int x, int y, int z) {
e[++kk].nxt = head[x];
e[kk].to = y;
e[kk].step = z;
head[x] = kk;
}
inline void insert(int x) {
for (int i = 31; ~i; i--) {
if (x & (1 << i)) {
if (b[i])
x ^= b[i];
else {
b[i] = x;
break;
}
}
}
}
void dfs(int u, int fa) {
vis[u] = true;
for (int i = head[u]; i; i = e[i].nxt) {
int v = e[i].to;
if (v == fa) continue;
if (vis[v])
insert(dis[u] ^ dis[v] ^ e[i].step);
else
dis[v] = dis[u] ^ e[i].step, dfs(v, u);
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &x, &y, &z);
link(x, y, z);
link(y, x, z);
}
dfs(1, -1);
int ans = dis[n];
for (int i = 31; ~i; i--)
if (ans > (b[i] ^ ans)) ans ^= b[i];
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
N people are arranged in a row from left to right.
You are given a string S of length N consisting of `0` and `1`, and a positive integer K.
The i-th person from the left is standing on feet if the i-th character of S is `0`, and standing on hands if that character is `1`.
You will give the following direction at most K times (possibly zero):
Direction: Choose integers l and r satisfying 1 \leq l \leq r \leq N, and flip the l-th, (l+1)-th, ..., and r-th persons. That is, for each i = l, l+1, ..., r, the i-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.
Find the maximum possible number of consecutive people standing on hands after at most K directions.
Constraints
* N is an integer satisfying 1 \leq N \leq 10^5.
* K is an integer satisfying 1 \leq K \leq 10^5.
* The length of the string S is N.
* Each character of the string S is `0` or `1`.
Input
Input is given from Standard Input in the following format:
N K
S
Output
Print the maximum possible number of consecutive people standing on hands after at most K directions.
Examples
Input
5 1
00010
Output
4
Input
14 2
11101010110011
Output
8
Input
1 1
1
Output
1
### Response
```cpp
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int n,k;
cin >> n >> k;
string a;
cin >> a;
a=' '+a;
int now=1,ans=0;
for(int i=1;i<=n;i++)
{
if(a[i-1]!='0'&&a[i]=='0')
--k;
while(k<0&&now<=i)
{
if(a[now]=='0'&&a[now+1]=='1')
++k;
++now;
}
if(k>=0) ans=max(ans,i-now+1);
// cout << now << " " << i << "\n";
}
cout << ans;
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible.
In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line?
Let us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on.
Input
The first line of input contains a single integer n (1 β€ n β€ 500) β the number of gemstones.
The second line contains n space-separated integers, the i-th of which is ci (1 β€ ci β€ n) β the color of the i-th gemstone in a line.
Output
Print a single integer β the minimum number of seconds needed to destroy the entire line.
Examples
Input
3
1 2 1
Output
1
Input
3
1 2 3
Output
3
Input
7
1 4 4 2 3 2 1
Output
2
Note
In the first sample, Genos can destroy the entire line in one second.
In the second sample, Genos can only destroy one gemstone at a time, so destroying three gemstones takes three seconds.
In the third sample, to achieve the optimal time of two seconds, destroy palindrome 4 4 first and then destroy palindrome 1 2 3 2 1.
### Response
```cpp
#include <bits/stdc++.h>
const double PI = 3.1415926535897932384626433;
const int KL = 505;
const long long MOD = 1e9 + 7;
using namespace std;
int n, dp[KL][KL][2], s[KL];
bool vis[KL][KL][2];
int solve(int st, int en, bool ok) {
if (st > en) return 0;
if (vis[st][en][ok]) return dp[st][en][ok];
vis[st][en][ok] = 1;
int path = 1e6;
if (ok) {
if (s[st] == s[en]) path = solve(st + 1, en - 1, 1);
for (int i = st + 1; i <= en; i++) {
if (s[i] == s[en])
path = min(path, solve(st, i - 1, 0) + solve(i, en, 1));
}
for (int i = st; i < en; i++) {
if (s[st] == s[i])
path = min(path, solve(st, i, 1) + solve(i + 1, en, 0));
}
} else {
if (s[st] == s[en]) path = 1 + solve(st + 1, en - 1, 1);
for (int i = st + 1; i <= en; i++) {
if (s[i] == s[en])
path = min(path, solve(st, i - 1, 0) + solve(i, en, 0));
}
for (int i = st; i < en; i++) {
if (s[st] == s[i])
path = min(path, solve(st, i, 0) + solve(i + 1, en, 0));
}
}
return dp[st][en][ok] = path;
}
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &s[i]);
cout << solve(0, n - 1, 0) << endl;
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process.
<image>
Help the dwarfs find out how many triangle plants that point "upwards" will be in n years.
Input
The first line contains a single integer n (0 β€ n β€ 1018) β the number of full years when the plant grew.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.
Output
Print a single integer β the remainder of dividing the number of plants that will point "upwards" in n years by 1000000007 (109 + 7).
Examples
Input
1
Output
3
Input
2
Output
10
Note
The first test sample corresponds to the second triangle on the figure in the statement. The second test sample corresponds to the third one.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n;
int gdzie;
long long m[2][2][1000];
void mul(int i1, int i2) {
gdzie++;
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++)
for (int l = 0; l < 2; l++) {
m[j][k][gdzie] =
(m[j][k][gdzie] + (m[j][l][i1] * m[l][k][i2]) % 1000000007) %
1000000007;
}
}
void go(long long level) {
if (level <= 0) return;
go(level / 2);
mul(gdzie, gdzie);
if (level % 2) {
mul(gdzie, 0);
}
}
int main() {
cin >> n;
gdzie = 1;
m[0][0][0] = m[1][1][0] = 3;
m[0][1][0] = m[1][0][0] = 1;
m[0][0][1] = m[1][1][1] = 1;
m[0][1][1] = m[1][0][1] = 0;
go(n);
cout << m[0][0][gdzie] << endl;
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
You are given array ai of length n. You may consecutively apply two operations to this array:
* remove some subsegment (continuous subsequence) of length m < n and pay for it mΒ·a coins;
* change some elements of the array by at most 1, and pay b coins for each change.
Please note that each of operations may be applied at most once (and may be not applied at all) so you can remove only one segment and each number may be changed (increased or decreased) by at most 1. Also note, that you are not allowed to delete the whole array.
Your goal is to calculate the minimum number of coins that you need to spend in order to make the greatest common divisor of the elements of the resulting array be greater than 1.
Input
The first line of the input contains integers n, a and b (1 β€ n β€ 1 000 000, 0 β€ a, b β€ 109) β the length of the array, the cost of removing a single element in the first operation and the cost of changing an element, respectively.
The second line contains n integers ai (2 β€ ai β€ 109) β elements of the array.
Output
Print a single number β the minimum cost of changes needed to obtain an array, such that the greatest common divisor of all its elements is greater than 1.
Examples
Input
3 1 4
4 2 3
Output
1
Input
5 3 2
5 17 13 5 6
Output
8
Input
8 3 4
3 7 5 4 3 12 9 4
Output
13
Note
In the first sample the optimal way is to remove number 3 and pay 1 coin for it.
In the second sample you need to remove a segment [17, 13] and then decrease number 6. The cost of these changes is equal to 2Β·3 + 2 = 8 coins.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int N = 100000;
const long long MAX = 1e15;
int a[1000005], prime[100005];
set<int> ss;
bool vis[100005];
int n, c, b, cnt;
set<int>::iterator it;
long long dp[1000005][4], ans;
void prepare() {
for (int i = 2; i <= N; i++)
if (!vis[i]) {
prime[cnt++] = i;
int j = i * 2;
while (j <= N) {
vis[j] = 1;
j += i;
}
}
}
void get(int x) {
bool f = 0;
for (int i = 0; i < cnt; i++) {
f = 0;
while (x % prime[i] == 0) {
f = 1;
x /= prime[i];
}
if (f) ss.insert(prime[i]);
}
if (x > 1) ss.insert(x);
}
long long DP(int k) {
for (int i = 1; i <= n; i++)
for (int j = 0; j <= 3; j++) dp[i][j] = 1e15;
if (a[1] % k == 0)
dp[1][0] = 0;
else if ((a[1] + 1) % k == 0 || (a[1] - 1) % k == 0)
dp[1][0] = c;
dp[1][1] = b;
long long tem = 0;
for (int i = 2; i <= n; i++) {
if (a[i] % k == 0)
dp[i][0] = dp[i - 1][0];
else if ((a[i] + 1) % k == 0 || (a[i] - 1) % k == 0)
dp[i][0] = dp[i - 1][0] + c;
dp[i][1] = dp[i - 1][0] + b;
dp[i][2] = min(dp[i - 1][1], dp[i - 1][2]) + b;
tem = min(dp[i - 1][1], dp[i - 1][2]);
tem = min(dp[i - 1][3], tem);
if (a[i] % k == 0)
dp[i][3] = tem;
else if ((a[i] + 1) % k == 0 || (a[i] - 1) % k == 0)
dp[i][3] = tem + c;
dp[i][1] = min(dp[i][1], MAX);
dp[i][2] = min(dp[i][2], MAX);
dp[i][0] = min(dp[i][0], MAX);
dp[i][3] = min(dp[i][3], MAX);
}
tem = min(dp[n][0], dp[n][3]);
if (dp[n][2] != (long long)n * b || c == b) tem = min(tem, dp[n][2]);
if (dp[n][1] != (long long)n * b || b == c) tem = min(tem, dp[n][1]);
return tem;
}
void work() {
ans = 1e15;
for (it = ss.begin(); it != ss.end(); it++) {
int k = *it;
ans = min(ans, DP(k));
}
}
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
int main() {
prepare();
scanf("%d%d%d", &n, &b, &c);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
get(a[1] - 1);
get(a[1] + 1);
get(a[1]);
get(a[n] - 1);
get(a[n] + 1);
get(a[n]);
work();
cout << ans << endl;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
You are given an n Γ m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the table
abcd
edfg
hijk
we obtain the table:
acd
efg
hjk
A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
Input
The first line contains two integers β n and m (1 β€ n, m β€ 100).
Next n lines contain m small English letters each β the characters of the table.
Output
Print a single number β the minimum number of columns that you need to remove in order to make the table good.
Examples
Input
1 10
codeforces
Output
0
Input
4 4
case
care
test
code
Output
2
Input
5 4
code
forc
esco
defo
rces
Output
4
Note
In the first sample the table is already good.
In the second sample you may remove the first and third column.
In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).
Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m, i, j, ans, x;
bool w[101], ok;
string a[101];
char s;
int main() {
cin >> n >> m;
for (i = 1; i <= n; ++i)
for (j = 1; j <= m; j++) {
cin >> s;
a[j] = a[j] + s;
}
for (i = 1; i <= m; ++i) {
if (!w[i]) {
ok = false;
for (j = 1; j < n; ++j) {
if (a[i][j] < a[i][j - 1]) {
ans++;
w[i] = true;
ok = true;
break;
}
}
if (!ok) {
x = i;
for (j = 1; j < n; ++j) {
if (a[x][j] == a[x][j - 1])
for (i = x + 1; i <= m; i++)
if (!w[i]) {
if (a[i][j] == a[i][j - 1]) continue;
if (a[i][j] < a[i][j - 1]) {
ans++;
w[i] = true;
j = -1;
} else
break;
}
}
cout << ans, exit(0);
}
}
}
cout << m;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
One popular blog site edits the uploaded photos like this. It cuts a rectangular area out of them so that the ratio of height to width (i.e. the height / width quotient) can vary from 0.8 to 1.25 inclusively. Besides, at least one side of the cut area should have a size, equal to some power of number 2 (2x for some integer x). If those rules don't indicate the size of the cut are clearly, then the way with which the cut part possesses the largest area is chosen. Of course, both sides of the cut area should be integer. If there are several answers to this problem, you should choose the answer with the maximal height.
Input
The first line contains a pair of integers h and w (1 β€ h, w β€ 109) which are the height and width of the uploaded photo in pixels.
Output
Print two integers which are the height and width of the cut area.
Examples
Input
2 1
Output
1 1
Input
2 2
Output
2 2
Input
5 5
Output
5 4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long h, w, i, j, h1 = 1, h2, w1, w2 = 1;
cin >> h >> w;
h2 = h;
w1 = w;
while (h1 <= h && w > 0.8 * h1) h1 *= 2;
h1 /= 2;
if (w > 1.25 * h1) w1 = 1.25 * h1;
while (w2 <= w && h > 0.8 * w2) w2 *= 2;
w2 /= 2;
if (h > 1.25 * w2) h2 = 1.25 * w2;
if (h1 * w1 > h2 * w2 || (h1 * w1 == h2 * w2 && h1 > h2))
cout << h1 << ' ' << w1;
else
cout << h2 << ' ' << w2;
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
Let us define the FizzBuzz sequence a_1,a_2,... as follows:
* If both 3 and 5 divides i, a_i=\mbox{FizzBuzz}.
* If the above does not hold but 3 divides i, a_i=\mbox{Fizz}.
* If none of the above holds but 5 divides i, a_i=\mbox{Buzz}.
* If none of the above holds, a_i=i.
Find the sum of all numbers among the first N terms of the FizzBuzz sequence.
Constraints
* 1 \leq N \leq 10^6
Input
Input is given from Standard Input in the following format:
N
Output
Print the sum of all numbers among the first N terms of the FizzBuzz sequence.
Examples
Input
15
Output
60
Input
1000000
Output
266666333332
### Response
```cpp
#include<iostream>
#define ll long long
using namespace std;
int main()
{
ll n,sum;
cin>>n;ll x=n/3,y=n/5,z=n/15;
sum=(1+n)*n/2-(x+1)*x/2*3-(1+y)*y/2*5+(z+1)*z/2*15;
cout<<sum;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.
The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is <image>.
The pseudo code of the unexpected code is as follows:
input n
for i from 1 to n
input the i-th point's coordinates into p[i]
sort array p[] by increasing of x coordinate first and increasing of y coordinate second
d=INF //here INF is a number big enough
tot=0
for i from 1 to n
for j from (i+1) to n
++tot
if (p[j].x-p[i].x>=d) then break //notice that "break" is only to be
//out of the loop "for j"
d=min(d,distance(p[i],p[j]))
output d
Here, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.
You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
Input
A single line which contains two space-separated integers n and k (2 β€ n β€ 2000, 1 β€ k β€ 109).
Output
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| β€ 109) representing the coordinates of the i-th point.
The conditions below must be held:
* All the points must be distinct.
* |xi|, |yi| β€ 109.
* After running the given code, the value of tot should be larger than k.
Examples
Input
4 3
Output
0 0
0 1
1 0
1 1
Input
2 100
Output
no solution
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
int l = n * (n - 1);
l /= 2;
if (k >= l) {
cout << "no solution\n";
return 0;
}
pair<int, int> p;
vector<pair<int, int> > v;
int a = 0, b = 0;
for (int i = 0; i < n; i++) {
p = make_pair(b, a);
v.push_back(p);
a++;
}
for (int i = 0; i < n; i++) {
cout << v[i].first << " " << v[i].second << endl;
}
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
Palindromic characteristics of string s with length |s| is a sequence of |s| integers, where k-th number is the total number of non-empty substrings of s which are k-palindromes.
A string is 1-palindrome if and only if it reads the same backward as forward.
A string is k-palindrome (k > 1) if and only if:
1. Its left half equals to its right half.
2. Its left and right halfs are non-empty (k - 1)-palindromes.
The left half of string t is its prefix of length β|t| / 2β, and right half β the suffix of the same length. β|t| / 2β denotes the length of string t divided by 2, rounded down.
Note that each substring is counted as many times as it appears in the string. For example, in the string "aaa" the substring "a" appears 3 times.
Input
The first line contains the string s (1 β€ |s| β€ 5000) consisting of lowercase English letters.
Output
Print |s| integers β palindromic characteristics of string s.
Examples
Input
abba
Output
6 1 0 0
Input
abacaba
Output
12 4 1 0 0 0 0
Note
In the first example 1-palindromes are substring Β«aΒ», Β«bΒ», Β«bΒ», Β«aΒ», Β«bbΒ», Β«abbaΒ», the substring Β«bbΒ» is 2-palindrome. There are no 3- and 4-palindromes here.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int mod = 1e9 + 7;
long long powe(long long x, long long y) {
x = x % mod, y = y % (mod - 1);
long long ans = 1;
while (y > 0) {
if (y & 1) {
ans = (1ll * x * ans) % mod;
}
y >>= 1;
x = (1ll * x * x) % mod;
}
return ans;
}
void fun() {}
string s;
int check[5001][5001];
int dp[5001][5001];
int n;
int cnt[5001];
int ist(int left, int right) {
if (left >= right) return 1;
if (check[left][right] != -1) return check[left][right];
int ans = 0;
if (s[left] == s[right]) ans |= ist(left + 1, right - 1);
return check[left][right] = ans;
}
int fun(int left, int right) {
if (left == right) return dp[left][right] = 1;
if (dp[left][right] != -1) return dp[left][right];
int ans = ist(left, right);
if (ans) {
int num = (right - left) / 2;
int l = left + num - 1;
if ((right - left) % 2 != 0) l++;
return dp[left][right] = fun(left, l) + 1;
}
return dp[left][right] = 0;
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
fun();
cin >> s;
n = s.length();
memset(check, -1, sizeof(check));
memset(dp, -1, sizeof(dp));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i > j) continue;
if (dp[i][j] == -1) {
fun(i, j);
}
cnt[dp[i][j]]++;
}
}
for (int i = n - 1; i >= 1; i--) {
cnt[i] += cnt[i + 1];
}
for (int i = 1; i <= n; i++) {
cout << cnt[i] << " ";
}
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS:
You are given two integers d, m, find the number of arrays a, satisfying the following constraints:
* The length of a is n, n β₯ 1
* 1 β€ a_1 < a_2 < ... < a_n β€ d
* Define an array b of length n as follows: b_1 = a_1, β i > 1, b_i = b_{i - 1} β a_i, where β is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold.
Since the number of possible arrays may be too large, you need to find the answer modulo m.
Input
The first line contains an integer t (1 β€ t β€ 100) denoting the number of test cases in the input.
Each of the next t lines contains two integers d, m (1 β€ d, m β€ 10^9).
Note that m is not necessary the prime!
Output
For each test case, print the number of arrays a, satisfying all given constrains, modulo m.
Example
Input
10
1 1000000000
2 999999999
3 99999998
4 9999997
5 999996
6 99995
7 9994
8 993
9 92
10 1
Output
1
3
5
11
17
23
29
59
89
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int t, d, mod;
int main() {
ios_base ::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> t;
for (; t; t--) {
cin >> d >> mod;
int ans = 1;
for (int i = 0; (1 << i) <= d; i++)
ans = 1LL * ans * (min((1 << (i + 1)) - 1, d) - (1 << i) + 2) % mod;
cout << (ans - 1 + mod) % mod << "\n";
}
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
As you very well know, the whole Universe traditionally uses three-dimensional Cartesian system of coordinates. In this system each point corresponds to three real coordinates (x, y, z). In this coordinate system, the distance between the center of the Universe and the point is calculated by the following formula: <image>. Mushroom scientists that work for the Great Mushroom King think that the Universe isn't exactly right and the distance from the center of the Universe to a point equals xaΒ·ybΒ·zc.
To test the metric of mushroom scientists, the usual scientists offered them a task: find such x, y, z (0 β€ x, y, z; x + y + z β€ S), that the distance between the center of the Universe and the point (x, y, z) is maximum possible in the metric of mushroom scientists. The mushroom scientists aren't good at maths, so they commissioned you to do the task.
Note that in this problem, it is considered that 00 = 1.
Input
The first line contains a single integer S (1 β€ S β€ 103) β the maximum sum of coordinates of the sought point.
The second line contains three space-separated integers a, b, c (0 β€ a, b, c β€ 103) β the numbers that describe the metric of mushroom scientists.
Output
Print three real numbers β the coordinates of the point that reaches maximum value in the metrics of mushroom scientists. If there are multiple answers, print any of them that meets the limitations.
A natural logarithm of distance from the center of the Universe to the given point in the metric of mushroom scientists shouldn't differ from the natural logarithm of the maximum distance by more than 10 - 6. We think that ln(0) = - β.
Examples
Input
3
1 1 1
Output
1.0 1.0 1.0
Input
3
2 0 0
Output
3.0 0.0 0.0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
double s, x, y, z, a, b, c;
cin >> s >> a >> b >> c;
if (a == 0 && b == 0 && c == 0) {
cout << 0 << " " << 0 << " " << 0 << endl;
return 0;
}
double part = s / (a + b + c);
x = a * part;
y = b * part;
z = c * part;
cout << setprecision(15) << x << " " << y << " " << z << endl;
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Polycarp is an experienced participant in Codehorses programming contests. Now he wants to become a problemsetter.
He sent to the coordinator a set of n problems. Each problem has it's quality, the quality of the i-th problem is ai (ai can be positive, negative or equal to zero). The problems are ordered by expected difficulty, but the difficulty is not related to the quality in any way. The easiest problem has index 1, the hardest problem has index n.
The coordinator's mood is equal to q now. After reading a problem, the mood changes by it's quality. It means that after the coordinator reads a problem with quality b, the value b is added to his mood. The coordinator always reads problems one by one from the easiest to the hardest, it's impossible to change the order of the problems.
If after reading some problem the coordinator's mood becomes negative, he immediately stops reading and rejects the problemset.
Polycarp wants to remove the minimum number of problems from his problemset to make the coordinator's mood non-negative at any moment of time. Polycarp is not sure about the current coordinator's mood, but he has m guesses "the current coordinator's mood q = bi".
For each of m guesses, find the minimum number of problems Polycarp needs to remove so that the coordinator's mood will always be greater or equal to 0 while he reads problems from the easiest of the remaining problems to the hardest.
Input
The first line of input contains two integers n and m (1 β€ n β€ 750, 1 β€ m β€ 200 000) β the number of problems in the problemset and the number of guesses about the current coordinator's mood.
The second line of input contains n integers a1, a2, ..., an ( - 109 β€ ai β€ 109) β the qualities of the problems in order of increasing difficulty.
The third line of input contains m integers b1, b2, ..., bm (0 β€ bi β€ 1015) β the guesses of the current coordinator's mood q.
Output
Print m lines, in i-th line print single integer β the answer to the problem with q = bi.
Example
Input
6 3
8 -5 -4 1 -7 4
0 7 3
Output
2
0
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
void fre() {
freopen("c://test//input.in", "r", stdin);
freopen("c://test//output.out", "w", stdout);
}
template <class T1, class T2>
inline void gmax(T1 &a, T2 b) {
if (b > a) a = b;
}
template <class T1, class T2>
inline void gmin(T1 &a, T2 b) {
if (b < a) a = b;
}
const int N = 800, M = 0, Z = 1e9 + 7, inf = 0x3f3f3f3f;
template <class T1, class T2>
inline void gadd(T1 &a, T2 b) {
a = (a + b) % Z;
}
int n, m;
int a[N];
long long f[N][N];
int main() {
while (~scanf("%d%d", &n, &m)) {
for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
memset(f, 63, sizeof(f));
memset(f[n + 1], 0, sizeof(f[n + 1]));
for (int i = n; i >= 1; --i) {
for (int j = 0; j <= n; ++j) {
f[i][j] = max(f[i + 1][j] - a[i], 0ll);
if (j) gmin(f[i][j - 1], max(f[i][j] + min(a[i], 0), 0ll));
}
}
for (int i = 1; i <= m; ++i) {
long long x;
scanf("%lld", &x);
int ans = upper_bound(f[1], f[1] + n + 1, x) - f[1] - 1;
printf("%d\n", n - ans);
}
}
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
The capital of Berland looks like a rectangle of size n Γ m of the square blocks of same size.
Fire!
It is known that k + 1 blocks got caught on fire (k + 1 β€ nΒ·m). Those blocks are centers of ignition. Moreover positions of k of these centers are known and one of these stays unknown. All k + 1 positions are distinct.
The fire goes the following way: during the zero minute of fire only these k + 1 centers of ignition are burning. Every next minute the fire goes to all neighbouring blocks to the one which is burning. You can consider blocks to burn for so long that this time exceeds the time taken in the problem. The neighbouring blocks are those that touch the current block by a side or by a corner.
Berland Fire Deparment wants to estimate the minimal time it takes the fire to lighten up the whole city. Remember that the positions of k blocks (centers of ignition) are known and (k + 1)-th can be positioned in any other block.
Help Berland Fire Department to estimate the minimal time it takes the fire to lighten up the whole city.
Input
The first line contains three integers n, m and k (1 β€ n, m β€ 109, 1 β€ k β€ 500).
Each of the next k lines contain two integers xi and yi (1 β€ xi β€ n, 1 β€ yi β€ m) β coordinates of the i-th center of ignition. It is guaranteed that the locations of all centers of ignition are distinct.
Output
Print the minimal time it takes the fire to lighten up the whole city (in minutes).
Examples
Input
7 7 3
1 2
2 1
5 5
Output
3
Input
10 5 1
3 3
Output
2
Note
In the first example the last block can have coordinates (4, 4).
In the second example the last block can have coordinates (8, 3).
### Response
```cpp
#include <bits/stdc++.h>
inline int read() {
char c = getchar();
while (c != '-' && (c < '0' || c > '9')) c = getchar();
int k = 0, kk = 1;
if (c == '-') c = getchar(), kk = -1;
while (c >= '0' && c <= '9') k = k * 10 + c - '0', c = getchar();
return kk * k;
}
using namespace std;
void write(int x) {
if (x < 0) x = -x, putchar('-');
if (x / 10) write(x / 10);
putchar(x % 10 + '0');
}
void writeln(int x) {
write(x);
puts("");
}
int n, m, k, x[1000000], y[1000000], l[1000000], r[1000000], f[1000000];
struct lsg {
int x, y, d, bj;
} a[1000000], ff[1000000];
bool cmp1(lsg x, lsg y) { return x.d < y.d; }
bool cmp2(lsg x, lsg y) { return x.x < y.x; }
bool cmp3(lsg x, lsg y) { return x.y > y.y; }
bool pd(int kkk) {
int d = 0, dd = 0, ddd = 0;
memset(a, 0, sizeof(a));
for (int i = 1; i <= k; i++) {
a[++d].d = x[i] - kkk;
a[d].x = y[i] - kkk;
a[d].y = y[i] + kkk;
a[d].bj = i;
a[++d].d = x[i] + kkk + 1;
a[d].bj = -i;
}
a[++d].d = 1;
a[++d].d = n;
sort(a + 1, a + 1 + d, cmp1);
a[d + 1].d = -1e9;
for (int i = 1; i <= d; i++) {
if (a[i].bj > 0) {
ff[++dd].x = a[i].x;
ff[dd].y = a[i].y;
ff[dd].bj = a[i].bj;
} else if (a[i].bj < 0) {
int kk = 0;
for (int j = 1; j <= dd; j++)
if (ff[j].bj != -a[i].bj) ff[++kk] = ff[j];
dd = kk;
}
if (a[i].d != a[i + 1].d && a[i].d >= 1 && a[i].d <= n) {
sort(ff + 1, ff + 1 + dd, cmp2);
l[++ddd] = 1;
r[ddd] = m;
f[ddd] = a[i].d;
for (int j = 1; j <= dd; j++) {
if (l[ddd] >= ff[j].x) l[ddd] = max(l[ddd], ff[j].y + 1);
}
sort(ff + 1, ff + 1 + dd, cmp3);
for (int j = 1; j <= dd; j++) {
if (r[ddd] <= ff[j].y) r[ddd] = min(r[ddd], ff[j].x - 1);
}
}
}
int ll = 1, rr = ddd, lll = m, rrr = 1;
f[ddd + 1] = n;
f[ddd + 2] = n + 1;
while (l[ll] > r[ll] && ll <= rr) ll++;
while (l[rr] > r[rr] && ll <= rr) rr--;
if (f[rr + 1] - 1 - f[ll] > kkk * 2) return 0;
for (int i = ll; i <= rr; i++) lll = min(lll, l[i]), rrr = max(rrr, r[i]);
if (rrr - lll > kkk * 2) return 0;
return 1;
}
signed main() {
n = read();
m = read();
k = read();
for (int i = 1; i <= k; i++) x[i] = read(), y[i] = read();
int l = 0, r = max(n, m);
while (l < r) {
int m = (l + r) / 2;
if (pd(m))
r = m;
else
l = m + 1;
}
cout << l << endl;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
<image>
Some time ago Slastyona the Sweetmaid decided to open her own bakery! She bought required ingredients and a wonder-oven which can bake several types of cakes, and opened the bakery.
Soon the expenses started to overcome the income, so Slastyona decided to study the sweets market. She learned it's profitable to pack cakes in boxes, and that the more distinct cake types a box contains (let's denote this number as the value of the box), the higher price it has.
She needs to change the production technology! The problem is that the oven chooses the cake types on its own and Slastyona can't affect it. However, she knows the types and order of n cakes the oven is going to bake today. Slastyona has to pack exactly k boxes with cakes today, and she has to put in each box several (at least one) cakes the oven produced one right after another (in other words, she has to put in a box a continuous segment of cakes).
Slastyona wants to maximize the total value of all boxes with cakes. Help her determine this maximum possible total value.
Input
The first line contains two integers n and k (1 β€ n β€ 35000, 1 β€ k β€ min(n, 50)) β the number of cakes and the number of boxes, respectively.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β the types of cakes in the order the oven bakes them.
Output
Print the only integer β the maximum total value of all boxes with cakes.
Examples
Input
4 1
1 2 2 1
Output
2
Input
7 2
1 3 3 1 4 4 4
Output
5
Input
8 3
7 7 8 7 7 8 1 7
Output
6
Note
In the first example Slastyona has only one box. She has to put all cakes in it, so that there are two types of cakes in the box, so the value is equal to 2.
In the second example it is profitable to put the first two cakes in the first box, and all the rest in the second. There are two distinct types in the first box, and three in the second box then, so the total value is 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int ans = 0, fh = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') fh = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
return ans * fh;
}
const int maxn = 4e4 + 100;
struct Segment {
int p[maxn << 2], la[maxn << 2];
inline void updata(int o) { p[o] = max(p[o << 1], p[o << 1 | 1]); }
inline void pushdown(int o) {
if (!la[o]) return;
p[o << 1] += la[o], p[o << 1 | 1] += la[o];
la[o << 1] += la[o], la[o << 1 | 1] += la[o];
la[o] = 0;
}
void revise(int o, int l, int r, int ql, int qr, int qz) {
if (ql == l && qr == r) {
p[o] += qz, la[o] += qz;
return;
}
int mid = l + r >> 1;
pushdown(o);
if (ql <= mid) revise(o << 1, l, mid, ql, min(qr, mid), qz);
if (qr > mid) revise(o << 1 | 1, mid + 1, r, max(ql, mid + 1), qr, qz);
updata(o);
}
int query(int o, int l, int r, int ql, int qr) {
if (ql == l && qr == r) return p[o];
int mid = l + r >> 1, ans = 0;
pushdown(o);
if (ql <= mid) ans = query(o << 1, l, mid, ql, min(qr, mid));
if (qr > mid)
ans = max(ans, query(o << 1 | 1, mid + 1, r, max(ql, mid + 1), qr));
return ans;
}
} tre[60];
int n, k, a[maxn], qq[maxn], pos[maxn];
int main() {
n = read(), k = read();
for (int i = 1; i <= n; i++) a[i] = read();
for (int i = 1; i <= n; i++) qq[i] = pos[a[i]], pos[a[i]] = i;
int Ans = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= k; j++) {
int l = qq[i], r = i - 1;
tre[j - 1].revise(1, 0, n, l, r, 1);
int ans = tre[j - 1].query(1, 0, n, 0, i - 1);
tre[j].revise(1, 0, n, i, i, ans);
if (i == n) Ans = max(Ans, ans);
}
}
printf("%d\n", Ans);
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.
Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
Input
The first line of the input contains five positive integers n, l, v1, v2 and k (1 β€ n β€ 10 000, 1 β€ l β€ 109, 1 β€ v1 < v2 β€ 109, 1 β€ k β€ n) β the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
Output
Print the real number β the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.
Examples
Input
5 10 1 2 5
Output
5.0000000000
Input
3 6 1 2 1
Output
4.7142857143
Note
In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
double l, v1, v2;
cin >> n >> l >> v1 >> v2 >> k;
int r = n / k + (n % k == 0 ? 0 : 1);
double x = (v1 + v2) * l / (2 * v1 * r - v1 + v2);
printf("%.10f\n", (l - x) / v1 + x / v2);
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
Recently Luba bought a very interesting book. She knows that it will take t seconds to read the book. Luba wants to finish reading as fast as she can.
But she has some work to do in each of n next days. The number of seconds that Luba has to spend working during i-th day is ai. If some free time remains, she can spend it on reading.
Help Luba to determine the minimum number of day when she finishes reading.
It is guaranteed that the answer doesn't exceed n.
Remember that there are 86400 seconds in a day.
Input
The first line contains two integers n and t (1 β€ n β€ 100, 1 β€ t β€ 106) β the number of days and the time required to read the book.
The second line contains n integers ai (0 β€ ai β€ 86400) β the time Luba has to spend on her work during i-th day.
Output
Print the minimum day Luba can finish reading the book.
It is guaranteed that answer doesn't exceed n.
Examples
Input
2 2
86400 86398
Output
2
Input
2 86400
0 86400
Output
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, k;
int a[100005], b[100005], flaf[100005];
int flag;
void dfs(int HP, int p) { return; }
int main() {
int n, t, flag, temp;
while (cin >> n >> t) {
flag = 0;
for (int i = 0; i < n; i++) {
cin >> temp;
t -= (86400 - temp);
if (t <= 0 && flag == 0) {
cout << i + 1 << endl;
flag = 1;
}
}
}
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
A sequence a_1,a_2,... ,a_n is said to be /\/\/\/ when the following conditions are satisfied:
* For each i = 1,2,..., n-2, a_i = a_{i+2}.
* Exactly two different numbers appear in the sequence.
You are given a sequence v_1,v_2,...,v_n whose length is even. We would like to make this sequence /\/\/\/ by replacing some of its elements. Find the minimum number of elements that needs to be replaced.
Constraints
* 2 \leq n \leq 10^5
* n is even.
* 1 \leq v_i \leq 10^5
* v_i is an integer.
Input
Input is given from Standard Input in the following format:
n
v_1 v_2 ... v_n
Output
Print the minimum number of elements that needs to be replaced.
Examples
Input
4
3 1 3 2
Output
1
Input
6
105 119 105 119 105 119
Output
0
Input
4
1 1 1 1
Output
2
### Response
```cpp
#include<cstdio>
#include<algorithm>
using namespace std;
int n,v[100005],a[100005],b[100005];
int main(){
scanf("%d",&n);for(int i=1;i<=n;++i) scanf("%d",&v[i]);
for(int i=2;i<=n;i+=2) a[v[i]]++,b[v[i-1]]++;
int c1=0,c2=0,k1,k2;
for(int i=1;i<=100000;++i) {if(a[i]>c1) c1=a[i],k1=i;if(b[i]>c2) c2=b[i],k2=i;}
if(k1==k2) {
int c3=0,c4=0;
for(int i=1;i<=100000;++i) {if(a[i]>c3&&k1!=i) c3=a[i];if(b[i]>c4&&k1!=i) c4=b[i];}
printf("%d\n",min(n-c1-c3,n-c2-c4));
return 0;
}
printf("%d\n",n-c1-c2);
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
For an integer n not less than 0, let us define f(n) as follows:
* f(n) = 1 (if n < 2)
* f(n) = n f(n-2) (if n \geq 2)
Given is an integer N. Find the number of trailing zeros in the decimal notation of f(N).
Constraints
* 0 \leq N \leq 10^{18}
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of trailing zeros in the decimal notation of f(N).
Examples
Input
12
Output
1
Input
5
Output
0
Input
1000000000000000000
Output
124999999999999995
### Response
```cpp
#include<stdio.h>
int main(){
long long int n,a=10,ans=0;
scanf("%lld\n",&n);
if(n%2==1){
ans=0;
}
else{
while(a<=n){
ans=ans+n/a;
a=a*5;
}
}
printf("%lld\n",ans);
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges.
During one move, you can choose some gift 1 β€ i β€ n and do one of the following operations:
* eat exactly one candy from this gift (decrease a_i by one);
* eat exactly one orange from this gift (decrease b_i by one);
* eat exactly one candy and exactly one orange from this gift (decrease both a_i and b_i by one).
Of course, you can not eat a candy or orange if it's not present in the gift (so neither a_i nor b_i can become less than zero).
As said above, all gifts should be equal. This means that after some sequence of moves the following two conditions should be satisfied: a_1 = a_2 = ... = a_n and b_1 = b_2 = ... = b_n (and a_i equals b_i is not necessary).
Your task is to find the minimum number of moves required to equalize all the given gifts.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 50) β the number of gifts. 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 number of candies in the i-th gift. The third line of the test case contains n integers b_1, b_2, ..., b_n (1 β€ b_i β€ 10^9), where b_i is the number of oranges in the i-th gift.
Output
For each test case, print one integer: the minimum number of moves required to equalize all the given gifts.
Example
Input
5
3
3 5 6
3 2 3
5
1 2 3 4 5
5 4 3 2 1
3
1 1 1
2 2 2
6
1 1000000000 1000000000 1000000000 1000000000 1000000000
1 1 1 1 1 1
3
10 12 8
7 5 4
Output
6
16
0
4999999995
7
Note
In the first test case of the example, we can perform the following sequence of moves:
* choose the first gift and eat one orange from it, so a = [3, 5, 6] and b = [2, 2, 3];
* choose the second gift and eat one candy from it, so a = [3, 4, 6] and b = [2, 2, 3];
* choose the second gift and eat one candy from it, so a = [3, 3, 6] and b = [2, 2, 3];
* choose the third gift and eat one candy and one orange from it, so a = [3, 3, 5] and b = [2, 2, 2];
* choose the third gift and eat one candy from it, so a = [3, 3, 4] and b = [2, 2, 2];
* choose the third gift and eat one candy from it, so a = [3, 3, 3] and b = [2, 2, 2].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long t;
cin >> t;
while (t--) {
long long n;
cin >> n;
vector<long long> a(n);
vector<long long> b(n);
for (long long i = 0; i < n; i++) cin >> a[i];
for (long long i = 0; i < n; i++) cin >> b[i];
long long a_min = LLONG_MAX;
long long b_min = LLONG_MAX;
for (long long i = 0; i < n; i++) {
a_min = min(a_min, a[i]);
b_min = min(b_min, b[i]);
}
long long ans = 0;
for (long long i = 0; i < n; i++) {
long long counta = a[i] - a_min;
long long countb = b[i] - b_min;
ans += max(counta, countb);
}
cout << ans << endl;
}
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
For a given sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$, perform the following operations.
* count($b, e, k$): print the number of the specific values $k$ in $a_b, a_{b+1}, ..., a_{e-1}$.
Constraints
* $1 \leq n \leq 1,000$
* $-1,000,000,000 \leq a_i, k_i \leq 1,000,000,000$
* $1 \leq q \leq 1,000$
* $0 \leq b < e \leq n$
Input
The input is given in the following format.
$n$
$a_0 \; a_1, ..., \; a_{n-1}$
$q$
$b_1 \; e_1 \; k_1$
$b_2 \; e_2 \; k_2$
:
$b_q \; e_q \; k_q$
The number of elements $n$ and each element $a_i$ are given in the first line and the second line respectively. In the third line, the number of queries $q$ is given and the following $q$ lines, $q$ integers $b_i \; b_e \; k_i$ are given as queries.
Output
For each query, print the number of specified values.
Example
Input
9
1 4 1 4 2 1 3 5 6
3
0 9 1
1 6 1
3 7 5
Output
3
2
0
### Response
```cpp
//http://vivi.dyndns.org/tech/cpp/list.html#insert
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
using ll = long long;
/*auto count_a(auto b, auto e, auto k, auto a)
{
auto count_a = count(a.begin() + b, a.begin() + e, k); //size_t
return count_a;
}*/
int main()
{
ll n;
cin >> n;
vector<ll> a(n, 0);
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
ll q;
cin >> q;
for (int i = 0; i < q; i++)
{
ll b, e, k;
cin >> b >> e >> k;
cout << count(a.begin() + b, a.begin() + e, k) << endl;
}
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Input
The input contains two integers a1, a2 (0 β€ ai β€ 109), separated by a single space.
Output
Output a single integer.
Examples
Input
3 14
Output
44
Input
27 12
Output
48
Input
100 200
Output
102
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a, b, c = 0;
cin >> a >> b;
while (b) {
c = c * 10 + b % 10;
b /= 10;
}
cout << (a + c);
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape.
The pine's trunk includes several branches, located one above another and numbered from 2 to y. Some of them (more precise, from 2 to p) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppers are known for their awesome jumping skills: the grasshopper at branch x can jump to branches <image>.
Keeping this in mind, you wisely decided to choose such a branch that none of the grasshoppers could interrupt you. At the same time you wanna settle as high as possible since the view from up there is simply breathtaking.
In other words, your goal is to find the highest branch that cannot be reached by any of the grasshoppers or report that it's impossible.
Input
The only line contains two integers p and y (2 β€ p β€ y β€ 109).
Output
Output the number of the highest suitable branch. If there are none, print -1 instead.
Examples
Input
3 6
Output
5
Input
3 4
Output
-1
Note
In the first sample case grasshopper from branch 2 reaches branches 2, 4 and 6 while branch 3 is initially settled by another grasshopper. Therefore the answer is 5.
It immediately follows that there are no valid branches in second sample case.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m, koo = -1;
int pansu(int a) {
for (int i = 2; i * i <= a && i <= n; i++) {
if (a % i == 0) {
return 0;
}
}
return 1;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = m; i > n; i--) {
if (pansu(i)) {
printf("%d", i);
return 0;
}
}
printf("-1");
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Look for the Winner!
The citizens of TKB City are famous for their deep love in elections and vote counting. Today they hold an election for the next chairperson of the electoral commission. Now the voting has just been closed and the counting is going to start. The TKB citizens have strong desire to know the winner as early as possible during vote counting.
The election candidate receiving the most votes shall be the next chairperson. Suppose for instance that we have three candidates A, B, and C and ten votes. Suppose also that we have already counted six of the ten votes and the vote counts of A, B, and C are four, one, and one, respectively. At this moment, every candidate has a chance to receive four more votes and so everyone can still be the winner. However, if the next vote counted is cast for A, A is ensured to be the winner since A already has five votes and B or C can have at most four votes at the end. In this example, therefore, the TKB citizens can know the winner just when the seventh vote is counted.
Your mission is to write a program that receives every vote counted, one by one, identifies the winner, and determines when the winner gets ensured.
Input
The input consists of at most 1500 datasets, each consisting of two lines in the following format.
n
c1 c2 β¦ cn
n in the first line represents the number of votes, and is a positive integer no greater than 100. The second line represents the n votes, separated by a space. Each ci (1 β€ i β€ n) is a single uppercase letter, i.e. one of 'A' through 'Z'. This represents the election candidate for which the i-th vote was cast. Counting shall be done in the given order from c1 to cn.
You should assume that at least two stand as candidates even when all the votes are cast for one candidate.
The end of the input is indicated by a line containing a zero.
Output
For each dataset, unless the election ends in a tie, output a single line containing an uppercase letter c and an integer d separated by a space: c should represent the election winner and d should represent after counting how many votes the winner is identified. Otherwise, that is, if the election ends in a tie, output a single line containing `TIE'.
Sample Input
1
A
4
A A B B
5
L M N L N
6
K K K K K K
6
X X X Y Z X
10
A A A B A C A C C B
10
U U U U U V V W W W
0
Output for the Sample Input
A 1
TIE
TIE
K 4
X 5
A 7
U 8
Example
Input
1
A
4
A A B B
5
L M N L N
6
K K K K K K
6
X X X Y Z X
10
A A A B A C A C C B
10
U U U U U V V W W W
0
Output
A 1
TIE
TIE
K 4
X 5
A 7
U 8
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int search_maxi(int array[26]){
int maxi=0;
for(int i=0;i<26;i++){
if(array[maxi] < array[i]){
maxi=i;
}
}
return maxi;
}
bool check(int count[26],int maxi,int x){
for(int j=0;j<26;j++){
if( maxi!=j && count[j]+x >= count[maxi] ){
return false;
}
}
return true;
}
int main(){
while(1){
int n;
int count[26]={};
cin>>n;
if(n==0)break;
char ansC;
int ansI=n+1;
for(int i=0;i<n;i++){
char ch;
cin>>ch;
int id=ch-'A';
count[id]++;
int maxi=search_maxi(count);
if( check( count , maxi, n-1-i ) ){
ansC=('A' + maxi);
ansI=min(ansI,i+1);
}
}
if(ansI==n+1){
cout<<"TIE"<<endl;
}else{
cout<<ansC<<' '<<ansI<<endl;
}
}
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
There are n shovels in Polycarp's shop. The i-th shovel costs i burles, that is, the first shovel costs 1 burle, the second shovel costs 2 burles, the third shovel costs 3 burles, and so on. Polycarps wants to sell shovels in pairs.
Visitors are more likely to buy a pair of shovels if their total cost ends with several 9s. Because of this, Polycarp wants to choose a pair of shovels to sell in such a way that the sum of their costs ends with maximum possible number of nines. For example, if he chooses shovels with costs 12345 and 37454, their total cost is 49799, it ends with two nines.
You are to compute the number of pairs of shovels such that their total cost ends with maximum possible number of nines. Two pairs are considered different if there is a shovel presented in one pair, but not in the other.
Input
The first line contains a single integer n (2 β€ n β€ 109) β the number of shovels in Polycarp's shop.
Output
Print the number of pairs of shovels such that their total cost ends with maximum possible number of nines.
Note that it is possible that the largest number of 9s at the end is 0, then you should count all such ways.
It is guaranteed that for every n β€ 109 the answer doesn't exceed 2Β·109.
Examples
Input
7
Output
3
Input
14
Output
9
Input
50
Output
1
Note
In the first example the maximum possible number of nines at the end is one. Polycarp cah choose the following pairs of shovels for that purpose:
* 2 and 7;
* 3 and 6;
* 4 and 5.
In the second example the maximum number of nines at the end of total cost of two shovels is one. The following pairs of shovels suit Polycarp:
* 1 and 8;
* 2 and 7;
* 3 and 6;
* 4 and 5;
* 5 and 14;
* 6 and 13;
* 7 and 12;
* 8 and 11;
* 9 and 10.
In the third example it is necessary to choose shovels 49 and 50, because the sum of their cost is 99, that means that the total number of nines is equal to two, which is maximum possible for n = 50.
### Response
```cpp
#include <bits/stdc++.h>
const long long MOD = 1e9 + 7;
using namespace std;
long long stol(string s) {
long long number = 0;
for (int i = 0; i < s.length(); ++i)
number += (s[i] - '0') * powl(10, s.length() - 1 - i);
return number;
}
string to_string(long long number) {
string s = "";
while (number > 0) {
string l = "";
l += (number % 10) + '0';
s = l + s;
number /= 10;
}
return s;
}
int main() {
ios::sync_with_stdio(false);
cin.tie();
cout.tie();
long long n;
cin >> n;
long long temp = n;
unsigned long long mul = 0;
int maxim = 0;
if (n < 5) return cout << n * (n - 1) / 2, 0;
while (n > 0) {
if (n > 9)
maxim++;
else
maxim += (n > 4);
n /= 10;
}
n = temp;
if (maxim == ((int)log10(n) + 1)) {
long long start = powl(10, maxim) - 1;
long long lim = 5 * powl(10, maxim - 1);
for (long long i = min(start - 1, n); i >= lim; --i) mul++;
} else {
int t = 1;
long long lim = t * (long long)(powl(10, maxim)) - 1;
while (lim <= 2 * n) {
long long k = max(lim - n, (long long)1);
while (k <= lim / 2) {
k++;
mul++;
}
t++;
lim = powl(10, maxim) * t - 1;
}
}
cout << mul;
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
A permutation is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] β are permutations, and [1, 1], [4, 3, 1], [2, 3, 4] β no.
Permutation a is lexicographically smaller than permutation b (they have the same length n), if in the first index i in which they differ, a[i] < b[i]. For example, the permutation [1, 3, 2, 4] is lexicographically smaller than the permutation [1, 3, 4, 2], because the first two elements are equal, and the third element in the first permutation is smaller than in the second.
The next permutation for a permutation a of length n β is the lexicographically smallest permutation b of length n that lexicographically larger than a. For example:
* for permutation [2, 1, 4, 3] the next permutation is [2, 3, 1, 4];
* for permutation [1, 2, 3] the next permutation is [1, 3, 2];
* for permutation [2, 1] next permutation does not exist.
You are given the number n β the length of the initial permutation. The initial permutation has the form a = [1, 2, β¦, n]. In other words, a[i] = i (1 β€ i β€ n).
You need to process q queries of two types:
* 1 l r: query for the sum of all elements on the segment [l, r]. More formally, you need to find a[l] + a[l + 1] + β¦ + a[r].
* 2 x: x times replace the current permutation with the next permutation. For example, if x=2 and the current permutation has the form [1, 3, 4, 2], then we should perform such a chain of replacements [1, 3, 4, 2] β [1, 4, 2, 3] β [1, 4, 3, 2].
For each query of the 1-st type output the required sum.
Input
The first line contains two integers n (2 β€ n β€ 2 β
10^5) and q (1 β€ q β€ 2 β
10^5), where n β the length of the initial permutation, and q β the number of queries.
The next q lines contain a single query of the 1-st or 2-nd type. The 1-st type query consists of three integers 1, l and r (1 β€ l β€ r β€ n), the 2-nd type query consists of two integers 2 and x (1 β€ x β€ 10^5).
It is guaranteed that all requests of the 2-nd type are possible to process.
Output
For each query of the 1-st type, output on a separate line one integer β the required sum.
Example
Input
4 4
1 2 4
2 3
1 1 2
1 3 4
Output
9
4
6
Note
Initially, the permutation has the form [1, 2, 3, 4]. Queries processing is as follows:
1. 2 + 3 + 4 = 9;
2. [1, 2, 3, 4] β [1, 2, 4, 3] β [1, 3, 2, 4] β [1, 3, 4, 2];
3. 1 + 3 = 4;
4. 4 + 2 = 6
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 7, inf = 0x3f3f3f3f, mod = 1e9 + 7;
long long fac[20], a[maxn], t[maxn];
int lowbit(int x) { return x & (-x); }
void add(int x, int v) {
while (x < maxn) {
t[x] += v;
x += lowbit(x);
}
}
long long ask(int x) {
long long res = 0;
while (x) {
res += t[x];
x -= lowbit(x);
}
return res;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
fac[0] = 1;
for (int i = 1; i <= 15; ++i) fac[i] = fac[i - 1] * i;
int n, q;
cin >> n >> q;
vector<int> st;
int flag = inf;
for (int i = 1; i <= n; ++i) {
a[i] = i;
add(i, i);
if (n - i + 1 <= 15) {
flag = min(i, flag);
st.push_back(i);
}
}
long long now = 0;
int op, l, r, x;
int c = 0;
while (q--) {
cin >> op;
if (op == 1) {
cin >> l >> r;
cout << ask(r) - ask(l - 1) << '\n';
c++;
} else {
cin >> x;
now += x;
vector<int> tmp = st;
int sz = tmp.size();
vector<bool> vis(sz, 0);
long long cur = now;
for (int i = flag; i <= n; ++i) {
int kth = cur / fac[n - i], cnt = 0;
if (i == n) assert(cur == 0);
cur %= fac[n - i];
for (int j = 0; j < sz; ++j) {
if (vis[j]) continue;
if (cnt == kth) {
add(i, -a[i]);
a[i] = tmp[j];
add(i, a[i]);
vis[j] = 1;
break;
}
cnt++;
}
}
}
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
A divisor tree is a rooted tree that meets the following conditions:
* Each vertex of the tree contains a positive integer number.
* The numbers written in the leaves of the tree are prime numbers.
* For any inner vertex, the number within it is equal to the product of the numbers written in its children.
Manao has n distinct integers a1, a2, ..., an. He tries to build a divisor tree which contains each of these numbers. That is, for each ai, there should be at least one vertex in the tree which contains ai. Manao loves compact style, but his trees are too large. Help Manao determine the minimum possible number of vertices in the divisor tree sought.
Input
The first line contains a single integer n (1 β€ n β€ 8). The second line contains n distinct space-separated integers ai (2 β€ ai β€ 1012).
Output
Print a single integer β the minimum number of vertices in the divisor tree that contains each of the numbers ai.
Examples
Input
2
6 10
Output
7
Input
4
6 72 8 4
Output
12
Input
1
7
Output
1
Note
Sample 1. The smallest divisor tree looks this way: <image>
Sample 2. In this case you can build the following divisor tree: <image>
Sample 3. Note that the tree can consist of a single vertex.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long a[8], pro[1 << 8];
int bit_cnt[1 << 8];
vector<long long> pp;
bitset<1000000> p;
map<long long, int> H;
int N, an;
int qq(long long x) {
if (H.count(x)) return H[x];
long long X = x;
int res = 0;
for (int i = 0; i < ((int)(pp).size()) && pp[i] * pp[i] <= x; i++) {
while (x % pp[i] == 0) {
x /= pp[i];
res++;
}
}
if (x != 1) res++;
return H[X] = res;
}
int qq2(long long x) {
if (H.count(x)) {
int tmp = H[x];
if (tmp == 1) return 0;
return tmp;
}
long long X = x;
int res = 0;
for (int i = 0; i < ((int)(pp).size()) && pp[i] * pp[i] <= x; i++) {
while (x % pp[i] == 0) {
x /= pp[i];
res++;
}
}
if (x != 1) res++;
H[X] = res;
if (res == 1) return 0;
return res;
}
void dfs(int x, int mask, int v, int head) {
if (x == -1) {
if (head == 1)
an = min(an, v);
else
an = min(an, v + 1);
return;
}
if (!((mask >> x) & 1)) {
v++;
head++;
}
for (int i = 0; i < (1 << x); ++i) {
if (!i) {
dfs(x - 1, mask, v + qq2(a[x]), head);
} else if (!(mask & i) && a[x] % pro[i] == 0) {
dfs(x - 1, mask | i, v + bit_cnt[i] + qq(a[x] / pro[i]), head);
}
}
}
int main() {
for (int i = 3; i < 1000; i += 2) {
for (int j = i * i; j < 1000000; j += i + i) p[j] = 1;
}
pp.push_back(2);
for (int i = 3; i < 1000000; i += 2) {
if (!p[i]) pp.push_back(i);
}
int(n);
scanf("%d", &n);
N = n;
for (int i = 0; i < (n); ++i) cin >> a[i];
sort(a, a + n);
pro[0] = 1;
for (int i = (1); i < (1 << n); ++i) {
int k = 0;
while (!((i >> k) & 1)) k++;
bit_cnt[i] = bit_cnt[i - (1 << k)] + 1;
long long tmp1 = pro[i - (1 << k)];
long long tmp2 = a[k];
if (tmp1 > 10000000000000ll / tmp2)
pro[i] = 10000000000000ll;
else
pro[i] = tmp1 * tmp2;
}
an = 1000000;
dfs(n - 1, 0, 0, 0);
printf("%d\n", an);
return 0;
}
``` |
### Prompt
In CPP, your task is to solve the following problem:
We have a chocolate bar partitioned into H horizontal rows and W vertical columns of squares.
The square (i, j) at the i-th row from the top and the j-th column from the left is dark if S_{i,j} is `0`, and white if S_{i,j} is `1`.
We will cut the bar some number of times to divide it into some number of blocks. In each cut, we cut the whole bar by a line running along some boundaries of squares from end to end of the bar.
How many times do we need to cut the bar so that every block after the cuts has K or less white squares?
Constraints
* 1 \leq H \leq 10
* 1 \leq W \leq 1000
* 1 \leq K \leq H \times W
* S_{i,j} is `0` or `1`.
Input
Input is given from Standard Input in the following format:
H W K
S_{1,1}S_{1,2}...S_{1,W}
:
S_{H,1}S_{H,2}...S_{H,W}
Output
Print the number of minimum times the bar needs to be cut so that every block after the cuts has K or less white squares.
Examples
Input
3 5 4
11100
10001
00111
Output
2
Input
3 5 8
11100
10001
00111
Output
0
Input
4 10 4
1110010010
1000101110
0011101001
1101000111
Output
3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
typedef long long ll;
typedef pair<int, int> P;
const int INF = 1001001001;
int c[10][1001];
int main() {
int h, w, k;
cin >> h >> w >> k;
vector<string> s(h);
rep(i,h) cin >> s[i];
int ans = INF;
rep (div, 1 << (h-1)) {
int g = 0;
vector<int> id(h);
rep(i,h) {
id[i] = g;
if (div >> i & 1) g++;
}
g++;
rep(i,g)rep(j,w) c[i][j] = 0;
rep(i,h)rep(j,w) c[id[i]][j] += (s[i][j] - '0');
bool ok = true;
rep(i,g)rep(j,w) if(c[i][j] > k) ok = false;
if (!ok) continue;
int num = g-1;
vector<int> now(g);
auto add = [&](int j) {
rep(i,g) now[i] += c[i][j];
rep(i,g) if (now[i] > k) return false;
return true;
};
rep(j,w) {
if (!add(j)) {
num++;
now = vector<int>(g);
add(j);
}
}
ans = min(ans, num);
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
You are given array ai of length n. You may consecutively apply two operations to this array:
* remove some subsegment (continuous subsequence) of length m < n and pay for it mΒ·a coins;
* change some elements of the array by at most 1, and pay b coins for each change.
Please note that each of operations may be applied at most once (and may be not applied at all) so you can remove only one segment and each number may be changed (increased or decreased) by at most 1. Also note, that you are not allowed to delete the whole array.
Your goal is to calculate the minimum number of coins that you need to spend in order to make the greatest common divisor of the elements of the resulting array be greater than 1.
Input
The first line of the input contains integers n, a and b (1 β€ n β€ 1 000 000, 0 β€ a, b β€ 109) β the length of the array, the cost of removing a single element in the first operation and the cost of changing an element, respectively.
The second line contains n integers ai (2 β€ ai β€ 109) β elements of the array.
Output
Print a single number β the minimum cost of changes needed to obtain an array, such that the greatest common divisor of all its elements is greater than 1.
Examples
Input
3 1 4
4 2 3
Output
1
Input
5 3 2
5 17 13 5 6
Output
8
Input
8 3 4
3 7 5 4 3 12 9 4
Output
13
Note
In the first sample the optimal way is to remove number 3 and pay 1 coin for it.
In the second sample you need to remove a segment [17, 13] and then decrease number 6. The cost of these changes is equal to 2Β·3 + 2 = 8 coins.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline long long read() {
char i = getchar();
long long f = 1, res = 0;
while (i < '0' || i > '9') {
if (i == '-') f = -1;
i = getchar();
}
while (i >= '0' && i <= '9') {
res = res * 10 + i - '0';
i = getchar();
}
return f * res;
}
const long long inf = 1e18;
;
const int N = 1e6 + 50;
long long n, a, b, v[N];
long long dp[N][3], cost[N];
long long fac[500], res;
inline long long solve(long long x) {
memset(dp, 0, sizeof dp);
for (long long i = 1; i <= n; ++i) {
if (v[i] % x == 0)
cost[i] = 0;
else if ((v[i] + 1) % x == 0 || (v[i] - 1) % x == 0)
cost[i] = b;
else
cost[i] = inf;
}
for (long long i = 1; i <= n; ++i) {
if (cost[i] == inf) {
dp[i][0] = inf;
dp[i][1] = min(dp[i - 1][0], dp[i - 1][1]) + a;
dp[i][2] = inf;
} else {
dp[i][0] = dp[i - 1][0] + cost[i];
dp[i][1] = min(dp[i - 1][0], dp[i - 1][1]) + a;
dp[i][2] = min(dp[i - 1][2], dp[i - 1][1]) + cost[i];
}
}
return min(dp[n][0], min(dp[n][1], dp[n][2]));
}
inline void init(long long x) {
for (long long i = 2; i * i <= x; ++i) {
if (x % i) continue;
fac[res++] = i;
while (x % i == 0) x /= i;
}
if (x > 1) fac[res++] = x;
}
int main() {
while (~scanf("%I64d%I64d%I64d", &n, &a, &b)) {
for (long long i = 1; i <= n; ++i) v[i] = read();
res = 0;
init(v[1] + 1);
init(v[1]);
init(v[1] - 1);
init(v[n] + 1);
init(v[n]);
init(v[n] - 1);
sort(fac, fac + res);
res = unique(fac, fac + res) - fac;
long long ans = inf;
for (long long i = 0; i < res; ++i) ans = min(ans, solve(fac[i]));
printf("%I64d\n", ans);
}
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
The Aiz Archaeological Society has set out to investigate the ruins of the ancient nation Iwashiro, which sinks in the Hibara Sea. The ruins are somewhere in the Hibara Sea. Therefore, I decided to use an exploration radar to roughly mark the location of the ruins by radar exploration from the coastline and estimate how many meters away from the coastline should be investigated.
<image>
An observation point will be set up on the coastline represented by a straight line as shown above, and an exploration radar will be placed. The exploration radar only knows that there are archaeological sites within a semicircle of a certain size centered on the observation point. However, by combining a plurality of observation data, it is possible to narrow down to a narrower range.
Given some observational data consisting of the location of the observation point and the radius indicated by the exploration radar, write a program to find out how far you need to investigate from the coastline.
Input
The input is given in the following format.
N
x1 r1
x2 r2
::
xN rN
The first line gives the number of data N (1 β€ N β€ 100000) measured by the exploration radar. In the next N lines, the integer xi (0 β€ xi β€ 1,000,000), which indicates the position of the observation data i on the coastline in meters, and the integer ri (1 β€), which indicates how many meters the archaeological site is within a radius of that position. ri β€ 1,000,000) is given. Two or more observation data with the same observation point may be given.
If there are multiple observational data given, it can be considered that there are always points included in all of those semicircles.
Output
Outputs the actual number of meters that need to be investigated from the coastline. However, the error must not exceed plus or minus 0.001 meters. If this condition is satisfied, any number of digits after the decimal point may be displayed.
Examples
Input
2
0 2
1 2
Output
1.936
Input
3
0 3
1 2
2 1
Output
1.0
Input
2
0 1
3 2
Output
0.0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using ld = long double;
int main() {
int n; cin >> n;
vector<ld> x(n), r(n);
for(int i = 0; i < n; ++i) {
cin >> x[i] >> r[i];
}
auto check = [&] (ld y) {
ld mini = -1e18, maxi = 1e18;
for(int i = 0; i < n; ++i) {
const auto d = sqrt(r[i] * r[i] - y * y);
mini = max(mini, x[i] - d);
maxi = min(maxi, x[i] + d);
}
return mini <= maxi;
};
ld lb = 0, ub = *min_element(begin(r), end(r));
for(int lp = 0; lp <= 100; ++lp) {
const auto mid = (lb + ub) / 2;
(check(mid) ? lb : ub) = mid;
}
cout << setprecision(10) << fixed << lb << endl;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Karlsson has visited Lillebror again. They found a box of chocolates and a big whipped cream cake at Lillebror's place. Karlsson immediately suggested to divide the sweets fairly between Lillebror and himself. Specifically, to play together a game he has just invented with the chocolates. The winner will get the cake as a reward.
The box of chocolates has the form of a hexagon. It contains 19 cells for the chocolates, some of which contain a chocolate. The players move in turns. During one move it is allowed to eat one or several chocolates that lay in the neighboring cells on one line, parallel to one of the box's sides. The picture below shows the examples of allowed moves and of an unacceptable one. The player who cannot make a move loses.
<image>
Karlsson makes the first move as he is Lillebror's guest and not vice versa. The players play optimally. Determine who will get the cake.
Input
The input data contains 5 lines, containing 19 words consisting of one symbol. The word "O" means that the cell contains a chocolate and a "." stands for an empty cell. It is guaranteed that the box contains at least one chocolate. See the examples for better understanding.
Output
If Karlsson gets the cake, print "Karlsson" (without the quotes), otherwise print "Lillebror" (yet again without the quotes).
Examples
Input
. . .
. . O .
. . O O .
. . . .
. . .
Output
Lillebror
Input
. . .
. . . O
. . . O .
O . O .
. O .
Output
Karlsson
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long in() {
int32_t x;
scanf("%d", &x);
return x;
}
inline long long lin() {
long long x;
scanf("%lld", &x);
return x;
}
const long long maxn = 1e6 + 10;
long long cnt[] = {3, 4, 5, 4, 3};
long long pref[] = {0, 3, 7, 12, 16, 19};
inline long long correspond(long long row, long long col) {
return 1LL << (pref[row] + col);
}
char s[10][10];
long long dp[1 << 20];
inline long long calc(long long mask) {
if (dp[mask] + 1) return dp[mask];
dp[mask] = 1;
for (long long i = 0; i < 5; i++) {
for (long long j = 0; j < cnt[i]; j++) {
if (mask & correspond(i, j)) {
long long row = i, column = j;
long long mask2 = 0;
do {
mask2 += correspond(row, column);
long long winner = calc(mask ^ mask2);
if (winner == 1) dp[mask] = 0;
column -= (cnt[row] > cnt[row + 1]);
row++;
} while (row < 5 && column >= 0 && (mask & correspond(row, column)));
row = i, column = j, mask2 = 0;
do {
mask2 += correspond(row, column);
long long winner = calc(mask ^ mask2);
if (winner == 1) dp[mask] = 0;
column += cnt[row] < cnt[row + 1];
row++;
} while (row < 5 && column < cnt[row] &&
(mask & correspond(row, column)));
long long j2 = j;
mask2 = 0;
do {
mask2 += correspond(i, j2);
long long winner = calc(mask ^ mask2);
if (winner == 1) dp[mask] = 0;
j2++;
} while (j2 < cnt[i] && (mask & correspond(i, j2)));
}
}
}
return dp[mask];
}
int32_t main() {
memset(dp, -1, sizeof dp);
dp[0] = 1;
long long mask = 0;
string shit;
for (long long i = 0; i < 5; i++) {
getline(cin, shit);
long long cur = 0;
for (long long pt = 0; pt < shit.size(); pt++) {
if (shit[pt] == 'O' || shit[pt] == '.') s[i][cur++] = shit[pt];
}
assert(cur == cnt[i]);
for (long long j = 0; j < cnt[i]; j++)
if (s[i][j] == 'O') mask += correspond(i, j);
}
long long winner = calc(mask);
if (winner == 0)
cout << "Karlsson\n";
else
cout << "Lillebror\n";
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
You are given n intervals in form [l; r] on a number line.
You are also given m queries in form [x; y]. What is the minimal number of intervals you have to take so that every point (not necessarily integer) from x to y is covered by at least one of them?
If you can't choose intervals so that every point from x to y is covered, then print -1 for that query.
Input
The first line contains two integers n and m (1 β€ n, m β€ 2 β
10^5) β the number of intervals and the number of queries, respectively.
Each of the next n lines contains two integer numbers l_i and r_i (0 β€ l_i < r_i β€ 5 β
10^5) β the given intervals.
Each of the next m lines contains two integer numbers x_i and y_i (0 β€ x_i < y_i β€ 5 β
10^5) β the queries.
Output
Print m integer numbers. The i-th number should be the answer to the i-th query: either the minimal number of intervals you have to take so that every point (not necessarily integer) from x_i to y_i is covered by at least one of them or -1 if you can't choose intervals so that every point from x_i to y_i is covered.
Examples
Input
2 3
1 3
2 4
1 3
1 4
3 4
Output
1
2
1
Input
3 4
1 3
1 3
4 5
1 2
1 3
1 4
1 5
Output
1
1
-1
-1
Note
In the first example there are three queries:
1. query [1; 3] can be covered by interval [1; 3];
2. query [1; 4] can be covered by intervals [1; 3] and [2; 4]. There is no way to cover [1; 4] by a single interval;
3. query [3; 4] can be covered by interval [2; 4]. It doesn't matter that the other points are covered besides the given query.
In the second example there are four queries:
1. query [1; 2] can be covered by interval [1; 3]. Note that you can choose any of the two given intervals [1; 3];
2. query [1; 3] can be covered by interval [1; 3];
3. query [1; 4] can't be covered by any set of intervals;
4. query [1; 5] can't be covered by any set of intervals. Note that intervals [1; 3] and [4; 5] together don't cover [1; 5] because even non-integer points should be covered. Here 3.5, for example, isn't covered.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct pt {
int l, r;
} p[1000005];
int n, m, maxn[1000005], c[500005][22], maxm = 0, b[500005];
int pw[1005];
bool cmp(const pt x, const pt y) { return x.l == y.l ? x.r < y.r : x.l < y.l; }
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
scanf("%d%d", &p[i].l, &p[i].r), maxm = max(maxm, p[i].r);
sort(p + 1, p + n + 1, cmp);
for (int i = 1; i <= n; i++) maxn[i] = max(maxn[i - 1], p[i].r);
pw[0] = 1;
for (int i = 1; i <= 20; i++) pw[i] = pw[i - 1] * 2;
for (int i = 1; i <= n; i++) b[i] = p[i].l;
for (int i = 0; i <= maxm; i++) {
int nw = upper_bound(b + 1, b + n + 1, i) - b;
if (nw == 1)
c[i][0] = i;
else
c[i][0] = maxn[nw - 1];
}
for (int i = 1; i <= 19; i++)
for (int j = 0; j <= maxm; j++) c[j][i] = c[c[j][i - 1]][i - 1];
for (int i = 1; i <= m; i++) {
int ql, qr, x, ans = 0;
scanf("%d%d", &ql, &qr);
x = ql;
for (int j = 19; j >= 0; j--)
if (c[x][j] < qr) {
ans = ans + pw[j];
x = c[x][j];
}
if (c[x][0] < qr) {
printf("-1\n");
continue;
}
printf("%d\n", ans + 1);
}
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
During a break in the buffet of the scientific lyceum of the Kingdom of Kremland, there was formed a queue of n high school students numbered from 1 to n. Initially, each student i is on position i. Each student i is characterized by two numbers β a_i and b_i. Dissatisfaction of the person i equals the product of a_i by the number of people standing to the left of his position, add the product b_i by the number of people standing to the right of his position. Formally, the dissatisfaction of the student i, which is on the position j, equals a_i β
(j-1) + b_i β
(n-j).
The director entrusted Stas with the task: rearrange the people in the queue so that minimize the total dissatisfaction.
Although Stas is able to solve such problems, this was not given to him. He turned for help to you.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of people in the queue.
Each of the following n lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ 10^8) β the characteristic of the student i, initially on the position i.
Output
Output one integer β minimum total dissatisfaction which can be achieved by rearranging people in the queue.
Examples
Input
3
4 2
2 3
6 1
Output
12
Input
4
2 4
3 3
7 1
2 3
Output
25
Input
10
5 10
12 4
31 45
20 55
30 17
29 30
41 32
7 1
5 5
3 15
Output
1423
Note
In the first example it is optimal to put people in this order: (3, 1, 2). The first person is in the position of 2, then his dissatisfaction will be equal to 4 β
1+2 β
1=6. The second person is in the position of 3, his dissatisfaction will be equal to 2 β
2+3 β
0=4. The third person is in the position of 1, his dissatisfaction will be equal to 6 β
0+1 β
2=2. The total dissatisfaction will be 12.
In the second example, you need to put people in this order: (3, 2, 4, 1). The total dissatisfaction will be 25.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<long long> a(n), b(n);
for (int i = 0; i < n; i++) cin >> a[i] >> b[i];
vector<int> p(n);
iota(p.begin(), p.end(), 0);
sort(p.begin(), p.end(),
[&](int i1, int i2) { return a[i1] - b[i1] > a[i2] - b[i2]; });
long long sum = 0;
for (int i = 0; i < n; i++) sum += i * a[p[i]] + (n - i - 1) * b[p[i]];
cout << sum;
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.
In one operation you can choose two elements a_i and a_j (i β j) and decrease each of them by one.
You need to check whether it is possible to make all the elements equal to zero or not.
Input
The first line contains a single integer n (2 β€ n β€ 10^5) β the size of the array.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9) β the elements of the array.
Output
Print "YES" if it is possible to make all elements zero, otherwise print "NO".
Examples
Input
4
1 1 2 2
Output
YES
Input
6
1 2 3 4 5 6
Output
NO
Note
In the first example, you can make all elements equal to zero in 3 operations:
* Decrease a_1 and a_2,
* Decrease a_3 and a_4,
* Decrease a_3 and a_4
In the second example, one can show that it is impossible to make all elements equal to zero.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
long long int a[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
long long int sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i];
}
sort(a, a + n);
if (sum % 2 == 1 || a[n - 1] > sum - a[n - 1]) {
cout << "NO";
} else {
cout << "YES";
}
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Input
The only line of the input is a string of 7 characters. The first character is letter A, followed by 6 digits. The input is guaranteed to be valid (for certain definition of "valid").
Output
Output a single integer.
Examples
Input
A221033
Output
21
Input
A223635
Output
22
Input
A232726
Output
23
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
int i = 1;
int res = 0;
while (i < s.length()) {
if (s[i] != '1')
res += s[i] - '0';
else {
res += 10;
i++;
}
i++;
}
res += 1;
cout << res;
return 0;
}
``` |
Subsets and Splits