text
stringlengths 424
69.5k
|
---|
### Prompt
Develop a solution in Cpp to the problem described below:
Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, β¦, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation.
For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2].
The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, β¦, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation.
Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque.
Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides.
Input
The first line contains two integers n and q (2 β€ n β€ 10^5, 0 β€ q β€ 3 β
10^5) β the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 β€ a_i β€ 10^9) β the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 β€ m_j β€ 10^{18}).
Output
For each teacher's query, output two numbers A and B β the numbers that Valeriy pulls out of the deque for the m_j-th operation.
Examples
Input
5 3
1 2 3 4 5
1
2
10
Output
1 2
2 3
5 2
Input
2 0
0 0
Output
Note
Consider all 10 steps for the first test in detail:
1. [1, 2, 3, 4, 5] β on the first operation, A and B are 1 and 2, respectively.
So, 2 we write to the beginning of the deque, and 1 β to the end.
We get the following status of the deque: [2, 3, 4, 5, 1].
2. [2, 3, 4, 5, 1] β A = 2, B = 3.
3. [3, 4, 5, 1, 2]
4. [4, 5, 1, 2, 3]
5. [5, 1, 2, 3, 4]
6. [5, 2, 3, 4, 1]
7. [5, 3, 4, 1, 2]
8. [5, 4, 1, 2, 3]
9. [5, 1, 2, 3, 4]
10. [5, 2, 3, 4, 1] β A = 5, B = 2.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long int n, q, i;
cin >> n >> q;
long long a[n + 1], b[q], a1[q], b1[q], mxa[n], mx, idx, aux[n];
for (i = 0; i < n; i++) cin >> a[i];
for (i = 0; i < q; i++) cin >> b[i];
mx = a[0];
mxa[0] = mx;
idx = 0;
for (i = 1; i < n; i++) {
if (a[i] > mx) {
mx = a[i];
idx = i;
}
mxa[i] = mx;
}
long long g, h, itr = 0;
g = a[0];
h = a[1];
for (i = idx + 1; i < n; i++) {
aux[itr] = a[i];
itr++;
}
for (i = 0; i < idx; i++) {
h = a[i + 1];
if (h > g) {
aux[itr] = g;
itr++;
g = h;
h = a[i + 2];
} else {
aux[itr] = h;
itr++;
h = a[i + 2];
}
}
for (i = 0; i < q; i++) {
if (b[i] > idx) {
long long temp = b[i] - idx;
a1[i] = mx;
b1[i] = aux[(temp - 1) % (n - 1)];
} else {
a1[i] = mxa[b[i] - 1];
b1[i] = a[b[i]];
}
}
for (i = 0; i < q; i++) {
cout << a1[i] << " " << b1[i] << endl;
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Snuke has N integers: 1,2,\ldots,N. He will choose K of them and give those to Takahashi.
How many ways are there to choose K consecutive integers?
Constraints
* All values in input are integers.
* 1 \leq K \leq N \leq 50
Input
Input is given from Standard Input in the following format:
N K
Output
Print the answer.
Examples
Input
3 2
Output
2
Input
13 3
Output
11
### Response
```cpp
#include<stdio.h>
int main()
{
int k,n;
scanf("%d%d",&n,&k);
printf("%d\n",n-k+1);
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline.
You are given string s consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk (1 β€ p1 < p2 < ... < pk β€ |s|) a subsequence of string s = s1s2... s|s|, where |s| is the length of string s. For example, strings "abcb", "b" and "abacaba" are subsequences of string "abacaba".
String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y| if either |x| > |y| and x1 = y1, x2 = y2, ..., x|y| = y|y|, or there exists such number r (r < |x|, r < |y|) that x1 = y1, x2 = y2, ..., xr = yr and xr + 1 > yr + 1. Characters in the strings are compared according to their ASCII codes. For example, string "ranger" is lexicographically larger than string "racecar" and string "poster" is lexicographically larger than string "post".
String s = s1s2... s|s| is a palindrome if it matches string rev(s) = s|s|s|s| - 1... s1. In other words, a string is a palindrome if it reads the same way from left to right and from right to left. For example, palindromic strings are "racecar", "refer" and "z".
Input
The only input line contains a non-empty string s consisting of lowercase English letters only. Its length does not exceed 10.
Output
Print the lexicographically largest palindromic subsequence of string s.
Examples
Input
radar
Output
rr
Input
bowwowwow
Output
wwwww
Input
codeforces
Output
s
Input
mississipp
Output
ssss
Note
Among all distinct subsequences of string "radar" the following ones are palindromes: "a", "d", "r", "aa", "rr", "ada", "rar", "rdr", "raar" and "radar". The lexicographically largest of them is "rr".
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const unsigned int m = 1e9 + 7;
inline void solve() {
string s;
cin >> s;
sort(s.begin(), s.end(), greater<char>());
for (int i = 0; i < s.size(); i++) {
if (s[i] == s[0]) cout << s[0];
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
solve();
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
We have an integer sequence A, whose length is N.
Find the number of the non-empty contiguous subsequences of A whose sums are 0. Note that we are counting the ways to take out subsequences. That is, even if the contents of some two subsequences are the same, they are counted individually if they are taken from different positions.
Constraints
* 1 \leq N \leq 2 \times 10^5
* -10^9 \leq A_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Find the number of the non-empty contiguous subsequences of A whose sum is 0.
Examples
Input
6
1 3 -4 2 2 -2
Output
3
Input
7
1 -1 1 -1 1 -1 1
Output
12
Input
5
1 -2 3 -4 5
Output
0
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
int n;
cin >> n;
map<ll, ll> p;
p[0] = 1;
ll sum = 0;
ll ans = 0;
while (n--) {
int temp;
cin >> temp;
sum += temp;
ans += p[sum];
p[sum]++;
}
cout << ans << "\n";
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Gargari is jealous that his friend Caisa won the game from the previous problem. He wants to prove that he is a genius.
He has a n Γ n chessboard. Each cell of the chessboard has a number written on it. Gargari wants to place two bishops on the chessboard in such a way that there is no cell that is attacked by both of them. Consider a cell with number x written on it, if this cell is attacked by one of the bishops Gargari will get x dollars for it. Tell Gargari, how to place bishops on the chessboard to get maximum amount of money.
We assume a cell is attacked by a bishop, if the cell is located on the same diagonal with the bishop (the cell, where the bishop is, also considered attacked by it).
Input
The first line contains a single integer n (2 β€ n β€ 2000). Each of the next n lines contains n integers aij (0 β€ aij β€ 109) β description of the chessboard.
Output
On the first line print the maximal number of dollars Gargari will get. On the next line print four integers: x1, y1, x2, y2 (1 β€ x1, y1, x2, y2 β€ n), where xi is the number of the row where the i-th bishop should be placed, yi is the number of the column where the i-th bishop should be placed. Consider rows are numbered from 1 to n from top to bottom, and columns are numbered from 1 to n from left to right.
If there are several optimal solutions, you can print any of them.
Examples
Input
4
1 1 1 1
2 1 1 0
1 1 1 0
1 0 0 1
Output
12
2 2 3 2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long int p[2003][2003], r[2003][2003], l[2003][2003];
int n, rgenap, cgenap, rganjil, cganjil;
long long int calc(int col, int row) {
int mini;
mini = min(n - col, n - row);
long long int a = r[col + mini][row + mini];
mini = min(col - 1, n - row);
long long int b = l[col - mini][row + mini];
return a + b - p[col][row];
}
int main(void) {
scanf("%d", &n);
for (int j = 1; j <= n; j++)
for (int i = 1; i <= n; i++) scanf("%I64d", &p[i][j]);
for (int j = 1; j <= n; j++)
for (int i = 1; i <= n; i++) r[i][j] = p[i][j] + r[i - 1][j - 1];
for (int j = 1; j <= n; j++)
for (int i = n; i >= 1; i--) l[i][j] = p[i][j] + l[i + 1][j - 1];
rgenap = cgenap = 1;
rganjil = 1;
cganjil = 2;
for (int j = 1; j <= n; j++)
for (int i = 1; i <= n; i++) {
if ((i + j) % 2 == 1) {
if (calc(i, j) > calc(cganjil, rganjil)) {
cganjil = i;
rganjil = j;
}
} else {
if (calc(i, j) > calc(cgenap, rgenap)) {
cgenap = i;
rgenap = j;
}
}
}
printf("%I64d\n", calc(cganjil, rganjil) + calc(cgenap, rgenap));
printf("%d %d %d %d\n", rganjil, cganjil, rgenap, cgenap);
}
``` |
### 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;
map<string, int> s;
void del(long long x) {
string cc(18, '0');
long long tmp, cn = 0;
while (1) {
tmp = x % 10;
x /= 10;
cc[cn] = (char)(tmp % 2 + '0');
if (x == 0) break;
++cn;
}
--s[cc];
}
void ins(long long x) {
string cc(18, '0');
long long tmp, cn = 0;
while (1) {
tmp = x % 10;
x /= 10;
cc[cn] = (char)(tmp % 2 + '0');
if (x == 0) break;
++cn;
}
++s[cc];
}
int cnt(string st) {
string cc(18, '0');
int cn = 0;
for (long long i = (long long)(st.size()) - 1; i >= 0; --i) {
cc[cn] = st[i];
++cn;
}
return s[cc];
}
int main() {
long long n, x;
char c[10];
string st;
while (cin >> n) {
s.clear();
for (long long i = 0; i < n; ++i) {
scanf("%s", c);
if (c[0] == '+') {
scanf("%I64d", &x);
ins(x);
} else if (c[0] == '-') {
scanf("%I64d", &x);
del(x);
} else {
cin >> st;
printf("%d\n", cnt(st));
}
}
}
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya and his friend Vasya play an interesting game. Petya randomly chooses an integer p from the interval [pl, pr] and Vasya chooses an integer v from the interval [vl, vr] (also randomly). Both players choose their integers equiprobably. Find the probability that the interval [min(v, p), max(v, p)] contains exactly k lucky numbers.
Input
The single line contains five integers pl, pr, vl, vr and k (1 β€ pl β€ pr β€ 109, 1 β€ vl β€ vr β€ 109, 1 β€ k β€ 1000).
Output
On the single line print the result with an absolute error of no more than 10 - 9.
Examples
Input
1 10 1 10 2
Output
0.320000000000
Input
5 6 8 10 1
Output
1.000000000000
Note
Consider that [a, b] denotes an interval of integers; this interval includes the boundaries. That is, <image>
In first case there are 32 suitable pairs: (1, 7), (1, 8), (1, 9), (1, 10), (2, 7), (2, 8), (2, 9), (2, 10), (3, 7), (3, 8), (3, 9), (3, 10), (4, 7), (4, 8), (4, 9), (4, 10), (7, 1), (7, 2), (7, 3), (7, 4), (8, 1), (8, 2), (8, 3), (8, 4), (9, 1), (9, 2), (9, 3), (9, 4), (10, 1), (10, 2), (10, 3), (10, 4). Total number of possible pairs is 10Β·10 = 100, so answer is 32 / 100.
In second case Petya always get number less than Vasya and the only lucky 7 is between this numbers, so there will be always 1 lucky number.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#pragma comment(linker, "/STACK:64000000")
template <class T>
inline T sqr(T x) {
return x * x;
}
vector<int> lucky;
void precalc() {
lucky.clear();
for (int len = 1; len <= 9; ++len) {
for (int mask = 0; mask < (1 << len); ++mask) {
int cur = 0;
for (int i = 0; i < len; ++i) {
if (mask & (1 << i))
cur = cur * 10 + 4;
else
cur = cur * 10 + 7;
}
lucky.push_back(cur);
}
}
sort((lucky).begin(), (lucky).end());
}
int l1, r1;
int l2, r2;
int n;
inline pair<int, int> intersect(pair<int, int> a, pair<int, int> b) {
if (a.first > a.second || b.first > b.second) return pair<int, int>();
int L = max(a.first, b.first);
int R = min(a.second, b.second);
return L <= R ? make_pair(L, R) : pair<int, int>();
}
int main() {
precalc();
cin >> l1 >> r1 >> l2 >> r2 >> n;
double res = 0.0;
for (int i = 0; i + n - 1 < (int)((lucky).size()); ++i) {
int l = lucky[i];
int r = lucky[i + n - 1];
int left, right;
pair<int, int> a, b;
left = i ? max(lucky[i - 1] + 1, l1) : l1;
right = i + n < (int)((lucky).size()) ? min(lucky[i + n] - 1, r2) : r2;
a = make_pair(left, min(l, r1));
b = make_pair(max(r, l2), right);
left = max(min(l, r1) - left + 1, 0);
right = max(right - max(r, l2) + 1, 0);
res += left * 1ll * right;
pair<int, int> c = intersect(a, b);
left = i ? max(lucky[i - 1] + 1, l2) : l2;
right = i + n < (int)((lucky).size()) ? min(lucky[i + n] - 1, r1) : r1;
a = make_pair(left, min(l, r2));
b = make_pair(max(r, l1), right);
left = max(min(l, r2) - left + 1, 0);
right = max(right - max(r, l1) + 1, 0);
res += left * 1ll * right;
c = intersect(c, intersect(a, b));
if (c.first) {
res -= c.second - c.first + 1;
}
}
res /= (r1 - l1 + 1);
res /= (r2 - l2 + 1);
printf("%.15lf\n", res);
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.
Here, a ACGT string is a string that contains no characters other than `A`, `C`, `G` and `T`.
Constraints
* S is a string of length between 1 and 10 (inclusive).
* Each character in S is an uppercase English letter.
Input
Input is given from Standard Input in the following format:
S
Output
Print the length of the longest ACGT string that is a substring of S.
Examples
Input
ATCODER
Output
3
Input
HATAGAYA
Output
5
Input
SHINJUKU
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main()
{
int m=0,now=0;
string s;
cin >> s;
for (int i=0;i < s.size();i++){
if (s[i]!='A' && s[i]!='T' && s[i]!='G' && s[i]!='C'){
now=0;
}
else{
now++;
}
m=max(m,now);
}
cout << m << endl;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
After all the events in Orlando we all know, Sasha and Roma decided to find out who is still the team's biggest loser. Thankfully, Masha found somewhere a revolver with a rotating cylinder of n bullet slots able to contain exactly k bullets, now the boys have a chance to resolve the problem once and for all.
Sasha selects any k out of n slots he wishes and puts bullets there. Roma spins the cylinder so that every of n possible cylinder's shifts is equiprobable. Then the game starts, the players take turns, Sasha starts: he puts the gun to his head and shoots. If there was no bullet in front of the trigger, the cylinder shifts by one position and the weapon is given to Roma for make the same move. The game continues until someone is shot, the survivor is the winner.
Sasha does not want to lose, so he must choose slots for bullets in such a way as to minimize the probability of its own loss. Of all the possible variant he wants to select the lexicographically minimal one, where an empty slot is lexicographically less than a charged one.
More formally, the cylinder of n bullet slots able to contain k bullets can be represented as a string of n characters. Exactly k of them are "X" (charged slots) and the others are "." (uncharged slots).
Let us describe the process of a shot. Suppose that the trigger is in front of the first character of the string (the first slot). If a shot doesn't kill anyone and the cylinder shifts, then the string shifts left. So the first character becomes the last one, the second character becomes the first one, and so on. But the trigger doesn't move. It will be in front of the first character of the resulting string.
Among all the strings that give the minimal probability of loss, Sasha choose the lexicographically minimal one. According to this very string, he charges the gun. You have to help Sasha to charge the gun. For that, each xi query must be answered: is there a bullet in the positions xi?
Input
The first line contains three integers n, k and p (1 β€ n β€ 1018, 0 β€ k β€ n, 1 β€ p β€ 1000) β the number of slots in the cylinder, the number of bullets and the number of queries. Then follow p lines; they are the queries. Each line contains one integer xi (1 β€ xi β€ n) the number of slot to describe.
Please do not use the %lld specificator to read or write 64-bit numbers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Output
For each query print "." if the slot should be empty and "X" if the slot should be charged.
Examples
Input
3 1 3
1
2
3
Output
..X
Input
6 3 6
1
2
3
4
5
6
Output
.X.X.X
Input
5 2 5
1
2
3
4
5
Output
...XX
Note
The lexicographical comparison of is performed by the < operator in modern programming languages. The a string is lexicographically less that the b string, 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;
int main() {
long long n, k, p, d, x;
cin >> n >> k >> d;
p = n - k;
for (int i = 0; i < d; i++) {
cin >> x;
x--;
if (p <= k) {
if (x % 2 == 0 && x / 2 < p) {
cout << ".";
} else {
cout << "X";
}
} else {
if (n % 2 == 0) {
if ((x % 2 == 1) && (n - 1 - x) / 2 < k) {
cout << "X";
} else {
cout << ".";
}
} else {
if (x != n - 1) {
if ((x % 2 == 1) && (n - 2 - x) / 2 < (k - 1)) {
cout << "X";
} else {
cout << ".";
}
} else {
if (k > 0)
cout << "X";
else
cout << ".";
}
}
}
}
return 0;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
Takahashi is solving quizzes. He has easily solved all but the last one.
The last quiz has three choices: 1, 2, and 3.
With his supernatural power, Takahashi has found out that the choices A and B are both wrong.
Print the correct choice for this problem.
Constraints
* Each of the numbers A and B is 1, 2, or 3.
* A and B are different.
Input
Input is given from Standard Input in the following format:
A
B
Output
Print the correct choice.
Examples
Input
3
1
Output
2
Input
1
2
Output
3
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main()
{
int s=0,a,b;
cin>>a>>b;
s=a+b;
cout<<6-s;
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
For a dynamic array $A = \\{a_0, a_1, ...\\}$ of integers, perform a sequence of the following operations:
* push($d$, $x$): Add element $x$ at the begining of $A$, if $d = 0$. Add element $x$ at the end of $A$, if $d = 1$.
* randomAccess($p$): Print element $a_p$.
* pop($d$): Delete the first element of $A$, if $d = 0$. Delete the last element of $A$, if $d = 1$.
$A$ is a 0-origin array and it is empty in the initial state.
Constraints
* $1 \leq q \leq 400,000$
* $0 \leq p < $ the size of $A$
* $-1,000,000,000 \leq x \leq 1,000,000,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $d$ $x$
or
1 $p$
or
2 $d$
where the first digits 0, 1 and 2 represent push, randomAccess and pop operations respectively.
randomAccess and pop operations will not be given for an empty array.
Output
For each randomAccess, print $a_p$ in a line.
Example
Input
11
0 0 1
0 0 2
0 1 3
1 0
1 1
1 2
2 0
2 1
0 0 4
1 0
1 1
Output
2
1
3
4
1
### Response
```cpp
#include <iostream>
#include <deque>
using namespace std;
int main(){
int q;
deque <int> a;
cin>>q;
for(int i=0;i<q;i++){
int n,d;
cin>>n>>d;
if(!n){
int x;
cin>>x;
if(d) a.push_back(x);
else a.push_front(x);
}
else if(n==1){
cout<<a[d]<<endl;
}
else {
if(d) a.pop_back();
else a.pop_front();
}
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it.
That element can store information about the matrix of integers size n Γ m. There are n + m inputs in that element, i.e. each row and each column can get the signal. When signal comes to the input corresponding to some row, this row cyclically shifts to the left, that is the first element of the row becomes last element, second element becomes first and so on. When signal comes to the input corresponding to some column, that column shifts cyclically to the top, that is first element of the column becomes last element, second element becomes first and so on. Rows are numbered with integers from 1 to n from top to bottom, while columns are numbered with integers from 1 to m from left to right.
Artem wants to carefully study this element before using it. For that purpose he is going to set up an experiment consisting of q turns. On each turn he either sends the signal to some input or checks what number is stored at some position of the matrix.
Artem has completed his experiment and has written down the results, but he has lost the chip! Help Artem find any initial matrix that will match the experiment results. It is guaranteed that experiment data is consistent, which means at least one valid matrix exists.
Input
The first line of the input contains three integers n, m and q (1 β€ n, m β€ 100, 1 β€ q β€ 10 000) β dimensions of the matrix and the number of turns in the experiment, respectively.
Next q lines contain turns descriptions, one per line. Each description starts with an integer ti (1 β€ ti β€ 3) that defines the type of the operation. For the operation of first and second type integer ri (1 β€ ri β€ n) or ci (1 β€ ci β€ m) follows, while for the operations of the third type three integers ri, ci and xi (1 β€ ri β€ n, 1 β€ ci β€ m, - 109 β€ xi β€ 109) are given.
Operation of the first type (ti = 1) means that signal comes to the input corresponding to row ri, that is it will shift cyclically. Operation of the second type (ti = 2) means that column ci will shift cyclically. Finally, operation of the third type means that at this moment of time cell located in the row ri and column ci stores value xi.
Output
Print the description of any valid initial matrix as n lines containing m integers each. All output integers should not exceed 109 by their absolute value.
If there are multiple valid solutions, output any of them.
Examples
Input
2 2 6
2 1
2 2
3 1 1 1
3 2 2 2
3 1 2 8
3 2 1 8
Output
8 2
1 8
Input
3 3 2
1 2
3 2 2 5
Output
0 0 0
0 0 5
0 0 0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > v;
int main() {
int r, c, q, x, a, b, _c, i, j;
cin >> r >> c >> q;
int matrix[r + 1][c + 1];
for (i = 1; i <= r; i++)
for (j = 1; j <= c; j++) matrix[i][j] = 0;
while (q--) {
cin >> x >> a;
if (x < 3) {
v.push_back(make_pair(x, a));
if (x == 1) {
b = matrix[a][1];
for (j = 2; j <= c; j++) matrix[a][j - 1] = matrix[a][j];
matrix[a][c] = b;
} else {
b = matrix[1][a];
for (j = 2; j <= r; j++) matrix[j - 1][a] = matrix[j][a];
matrix[r][a] = b;
}
} else {
cin >> b >> _c;
matrix[a][b] = _c;
}
}
for (i = v.size() - 1; i >= 0; i--) {
x = v[i].second;
if (v[i].first == 1) {
b = matrix[x][c];
for (j = c; j > 1; j--) matrix[x][j] = matrix[x][j - 1];
matrix[x][1] = b;
} else {
b = matrix[r][x];
for (j = r; j > 1; j--) matrix[j][x] = matrix[j - 1][x];
matrix[1][x] = b;
}
}
for (i = 1; i <= r; i++) {
for (j = 1; j <= c; j++) cout << matrix[i][j] << " ";
cout << endl;
}
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
You're given a row with n chairs. We call a seating of people "maximal" if the two following conditions hold:
1. There are no neighbors adjacent to anyone seated.
2. It's impossible to seat one more person without violating the first rule.
The seating is given as a string consisting of zeros and ones (0 means that the corresponding seat is empty, 1 β occupied). The goal is to determine whether this seating is "maximal".
Note that the first and last seats are not adjacent (if n β 2).
Input
The first line contains a single integer n (1 β€ n β€ 1000) β the number of chairs.
The next line contains a string of n characters, each of them is either zero or one, describing the seating.
Output
Output "Yes" (without quotation marks) if the seating is "maximal". Otherwise print "No".
You are allowed to print letters in whatever case you'd like (uppercase or lowercase).
Examples
Input
3
101
Output
Yes
Input
4
1011
Output
No
Input
5
10001
Output
No
Note
In sample case one the given seating is maximal.
In sample case two the person at chair three has a neighbour to the right.
In sample case three it is possible to seat yet another person into chair three.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int b[100], a[1000000];
vector<int> g;
int main() {
int n, i, k = 0, j;
string s;
cin >> n;
cin >> s;
for (i = 0; i < n; i++) {
if ((i == 0 && i < n - 1 && s[i] == '0' && s[i + 1] == '0') ||
(i > 0 && i < n - 1 && s[i - 1] == '0' && s[i] == '0' &&
s[i + 1] == '0') ||
(i > 0 && i == n - 1 && s[i - 1] == '0' && s[i] == '0') ||
(n == 1 && s[i] == '0') ||
(i < n - 1 && s[i] == '1' && s[i + 1] == '1')) {
k++;
break;
}
}
if (k)
cout << "No";
else
cout << "Yes";
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.
There are exactly two exits from Mr. Black's house, let's name them left and right exits. There are several doors in each of the exits, so each door in Mr. Black's house is located either in the left or in the right exit. You know where each door is located. Initially all the doors are closed. Mr. Black can exit the house if and only if all doors in at least one of the exits is open. You are given a sequence in which Mr. Black opened the doors, please find the smallest index k such that Mr. Black can exit the house after opening the first k doors.
We have to note that Mr. Black opened each door at most once, and in the end all doors became open.
Input
The first line contains integer n (2 β€ n β€ 200 000) β the number of doors.
The next line contains n integers: the sequence in which Mr. Black opened the doors. The i-th of these integers is equal to 0 in case the i-th opened door is located in the left exit, and it is equal to 1 in case it is in the right exit.
It is guaranteed that there is at least one door located in the left exit and there is at least one door located in the right exit.
Output
Print the smallest integer k such that after Mr. Black opened the first k doors, he was able to exit the house.
Examples
Input
5
0 0 1 0 0
Output
3
Input
4
1 0 0 1
Output
3
Note
In the first example the first two doors are from the left exit, so when Mr. Black opened both of them only, there were two more closed door in the left exit and one closed door in the right exit. So Mr. Black wasn't able to exit at that moment.
When he opened the third door, all doors from the right exit became open, so Mr. Black was able to exit the house.
In the second example when the first two doors were opened, there was open closed door in each of the exit.
With three doors opened Mr. Black was able to use the left exit.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(int argc, char const *argv[]) {
int n;
cin >> n;
int nsave = 0;
int arr[n];
while (nsave < n) {
cin >> arr[nsave];
nsave++;
}
int tmp = arr[n - 1];
for (int i = n - 1; i >= 0; i--) {
if (arr[i] != tmp) {
cout << i + 1;
exit(0);
}
}
cout << n;
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes.
Let's call a sequence of non-negative integers v1, v2, ..., vn a plan, if v1 + v2 + ... + vn = m. The programmers follow the plan like that: in the beginning the first programmer writes the first v1 lines of the given task, then the second programmer writes v2 more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most b bugs in total.
Your task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer mod.
Input
The first line contains four integers n, m, b, mod (1 β€ n, m β€ 500, 0 β€ b β€ 500; 1 β€ mod β€ 109 + 7) β the number of programmers, the number of lines of code in the task, the maximum total number of bugs respectively and the modulo you should use when printing the answer.
The next line contains n space-separated integers a1, a2, ..., an (0 β€ ai β€ 500) β the number of bugs per line for each programmer.
Output
Print a single integer β the answer to the problem modulo mod.
Examples
Input
3 3 3 100
1 1 1
Output
10
Input
3 6 5 1000000007
1 2 3
Output
0
Input
3 5 6 11
1 2 1
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n, m, b, mod, ans;
long long a[510], dp[510][510];
int main() {
scanf("%lld%lld%lld%lld", &n, &m, &b, &mod);
for (register int i = 1; i <= n; i++) scanf("%lld", &a[i]);
dp[0][0] = 1;
for (register int i = 1; i <= n; i++)
for (register int j = 1; j <= m; j++)
for (register int k = a[i]; k <= b; k++)
dp[j][k] = (dp[j][k] + dp[j - 1][k - a[i]]) % mod;
for (register int i = 0; i <= b; i++) ans = (ans + dp[m][i]) % mod;
printf("%lld\n", ans);
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Vasya the Great Magician and Conjurer loves all kinds of miracles and wizardry. In one wave of a magic wand he can turn an object into something else. But, as you all know, there is no better magic in the Universe than the magic of numbers. That's why Vasya adores math and spends a lot of time turning some numbers into some other ones.
This morning he has n cards with integers lined up in front of him. Each integer is not less than 1, but not greater than l. When Vasya waves his magic wand, two rightmost cards vanish from the line and a new card magically appears in their place. It contains the difference between the left and the right numbers on the two vanished cards. Vasya was very interested to know what would happen next, and so he waved with his magic wand on and on, until the table had a single card left.
Suppose that Vasya originally had the following cards: 4, 1, 1, 3 (listed from left to right). Then after the first wave the line would be: 4, 1, -2, and after the second one: 4, 3, and after the third one the table would have a single card with number 1.
Please note that in spite of the fact that initially all the numbers on the cards were not less than 1 and not greater than l, the numbers on the appearing cards can be anything, no restrictions are imposed on them.
It is now evening. Vasya is very tired and wants to return everything back, but does not remember which cards he had in the morning. He only remembers that there were n cards, they contained integers from 1 to l, and after all magical actions he was left with a single card containing number d.
Help Vasya to recover the initial set of cards with numbers.
Input
The single line contains three space-separated integers: n (2 β€ n β€ 100) β the initial number of cards on the table, d (|d| β€ 104) β the number on the card that was left on the table after all the magical actions, and l (1 β€ l β€ 100) β the limits for the initial integers.
Output
If Vasya is mistaken, that is, if there doesn't exist a set that meets the requirements given in the statement, then print a single number -1, otherwise print the sought set containing n integers from 1 to l. Separate the integers by spaces. Print the integers in the order, in which they were written on the cards from left to right. If there are several suitable sets of numbers, you can print any of them.
Examples
Input
3 3 2
Output
2 1 2
Input
5 -4 3
Output
-1
Input
5 -4 4
Output
2 4 1 4 1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, d, l;
int ans[101];
int s = 0;
cin >> n >> d >> l;
for (int i = 0; i < n; ++i) {
ans[i] = (i & 1) ? -1 : 1;
s += ans[i];
}
bool sw = false;
while (true) {
if (s == d) break;
sw = false;
if (s < d) {
for (int i = 0; i < n; ++i) {
if (ans[i] < l and ans[i] > 0) {
ans[i]++;
s++;
sw = true;
break;
}
}
} else if (s > d) {
for (int i = 0; i < n; ++i) {
if (ans[i] < 0 and ans[i] > -l) {
ans[i]--;
s--;
sw = true;
break;
}
}
}
if (!sw) return cout << -1, 0;
}
for (int i = 0; i < n; ++i) cout << abs(ans[i]) << " ";
return 0;
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
Example
Input
7
>>
Output
7
### Response
```cpp
/* template.cpp {{{ */
#include <bits/stdc++.h>
using namespace std;
#define get_macro(a, b, c, d, name, ...) name
#define rep(...) get_macro(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__)
#define rrep(...) get_macro(__VA_ARGS__, rrep4, rrep3, rrep2, rrep1)(__VA_ARGS__)
#define rep1(n) rep2(i_, n)
#define rep2(i, n) rep3(i, 0, n)
#define rep3(i, a, b) rep4(i, a, b, 1)
#define rep4(i, a, b, s) for (ll i = (a); i < (ll)(b); i += (ll)(s))
#define rrep1(n) rrep2(i_, n)
#define rrep2(i, n) rrep3(i, 0, n)
#define rrep3(i, a, b) rrep4(i, a, b, 1)
#define rrep4(i, a, b, s) for (ll i = (ll)(b) - 1; i >= (ll)(a); i -= (ll)(s))
#define each(x, c) for (auto &&x : c)
#define fs first
#define sc second
#define all(c) begin(c), end(c)
using ui = unsigned;
using ll = long long;
using ul = unsigned long long;
using ld = long double;
const int inf = 1e9 + 10;
const ll inf_ll = 1e18 + 10;
const ll mod = 1e9 + 7;
const ll mod9 = 1e9 + 9;
const int dx[]{-1, 0, 1, 0, -1, 1, 1, -1};
const int dy[]{0, -1, 0, 1, -1, -1, 1, 1};
template<class T, class U> void chmin(T &x, const U &y){ x = min<T>(x, y); }
template<class T, class U> void chmax(T &x, const U &y){ x = max<T>(x, y); }
//struct prepare_ { prepare_(){ cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(12); } } prepare__;
/* }}} */
int n;
string s;
int main(){
cin >> n;
cin >> s;
deque<int> l, r;
rep(i, n) if (s[i] == '<') r.push_back(i);
int res = 0;
rep(i, n){
if (r.size() && r[0] == i) r.pop_front();
if (s[i] == '>'){
if (r.empty()) chmax(res, n - i);
else if (l.size() >= r.size()) chmax(res, n - l[r.size() - 1]);
else chmax(res, r[l.size()] + 1);
}
else {
if (l.empty()) chmax(res, i + 1);
else if (l.size() <= r.size()) chmax(res, r[l.size() - 1] + 1);
else chmax(res, n - l[r.size()]);
}
if (s[i] == '>') l.push_front(i);
}
cout << res << endl;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Little X has met the following problem recently.
Let's define f(x) as the sum of digits in decimal representation of number x (for example, f(1234) = 1 + 2 + 3 + 4). You are to calculate <image>
Of course Little X has solved this problem quickly, has locked it, and then has tried to hack others. He has seen the following C++ code:
ans = solve(l, r) % a;
if (ans <= 0)
ans += a;
This code will fail only on the test with <image>. You are given number a, help Little X to find a proper test for hack.
Input
The first line contains a single integer a (1 β€ a β€ 1018).
Output
Print two integers: l, r (1 β€ l β€ r < 10200) β the required test data. Leading zeros aren't allowed. It's guaranteed that the solution exists.
Examples
Input
46
Output
1 10
Input
126444381000032
Output
2333333 2333333333333
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long a, mx = 1e18 + 1;
signed main() {
cin >> a;
long long l, r;
l = a - mx % a * 9 % a * 9 % a, r = mx + l - 1;
cout << l << " " << r << endl;
return 0;
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and an integer $K$, find the smallest sub-array size (smallest window length) where the elements in the sub-array contains all integers in range [$1, 2, ..., K$]. If there is no such sub-array, report 0.
Constraints
* $1 \leq N \leq 10^5$
* $1 \leq K \leq 10^5$
* $1 \leq a_i \leq 10^5$
Input
The input is given in the following format.
$N$ $K$
$a_1$ $a_2$ ... $a_N$
Output
Print the smallest sub-array size in a line.
Examples
Input
6 2
4 1 2 1 3 5
Output
2
Input
6 3
4 1 2 1 3 5
Output
3
Input
3 4
1 2 3
Output
0
### Response
```cpp
#include <bits/stdc++.h>
using ll = long long;
using namespace std;
const int inf = 1e9;
const ll linf = 1e18;
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
int n, k; cin >> n >> k;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i], a[i]--;
int res = inf;
int l = 0, r = 0, s = 0;
vector<int> count(k, 0);
for (; l < n; l++) {
while (r < n && s < k) {
if (a[r] < k && ++count[a[r]] == 1) s++;
r++;
}
if (s < k) break;
res = min(res, r - l);
if (a[l] < k && --count[a[l]] == 0) s--;
}
cout << (res <= n ? res : 0) << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
Game field is represented by a line of n square cells. In some cells there are packmen, in some cells there are asterisks and the rest of the cells are empty. Packmen eat asterisks.
Before the game starts you can choose a movement direction, left or right, for each packman. Once the game begins all the packmen simultaneously start moving according their directions. A packman can't change the given direction.
Once a packman enters a cell containing an asterisk, packman immediately eats the asterisk. Once the packman leaves the cell it becomes empty. Each packman moves at speed 1 cell per second. If a packman enters a border cell, the packman stops. Packmen do not interfere with the movement of other packmen; in one cell there can be any number of packmen moving in any directions.
Your task is to assign a direction to each packman so that they eat the maximal number of asterisks. If there are multiple ways to assign directions to eat the maximal number of asterisks, you should choose the way which minimizes the time to do that.
Input
The first line contains integer number n (2 β€ n β€ 1 000 000) β the number of cells in the game field.
The second line contains n characters. If the i-th character is '.', the i-th cell is empty. If the i-th character is '*', the i-th cell contains an asterisk. If the i-th character is 'P', the i-th cell contains a packman.
The field contains at least one asterisk and at least one packman.
Output
Print two integer numbers β the maximal number of asterisks packmen can eat and the minimal time to do it.
Examples
Input
6
*.P*P*
Output
3 4
Input
8
*...P..*
Output
1 3
Note
In the first example the leftmost packman should move to the right, the rightmost packman should move to the left. All the asterisks will be eaten, the last asterisk will be eaten after 4 seconds.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
int n, p[1000010], sum[1000010], cnt = 0, f[1000010][2], r[1000010];
char s[1000010];
bool chk(int x) {
f[0][0] = f[0][1] = r[0];
for (int i = 1; i <= cnt; i++) {
f[i][1] = max(f[i - 1][0], f[i - 1][1]) >= p[i]
? r[min(n + 1, p[i] + x + 1)]
: max(f[i - 1][0], f[i - 1][1]);
f[i][0] = r[0];
if (f[i - 1][0] >= p[i] - x)
f[i][0] = max({f[i][0], f[i - 1][0], r[p[i] + 1]});
else
f[i][0] = max(f[i][0], f[i - 1][0]);
if (f[i - 1][1] >= p[i] - x)
f[i][0] =
max(f[i][0], r[min(n + 1, max({0, p[i - 1] + x + 1, p[i] + 1}))]);
else
f[i][0] = max(f[i][0], f[i - 1][1]);
}
return max(f[cnt][0], f[cnt][1]) == n + 1;
}
int main() {
scanf("%d%s", &n, s + 1);
p[0] = -inf;
for (int i = 1; i <= n; i++) {
sum[i] = sum[i - 1];
if (s[i] == 'P')
p[++cnt] = i;
else if (s[i] == '*')
sum[i]++;
}
r[n + 1] = n + 1;
for (int i = n; i >= 0; i--)
if (s[i] == '*')
r[i] = i;
else
r[i] = r[i + 1];
if (cnt == 1) {
int l = 1, r = n;
while (s[l] != '*') l++;
while (s[r] != '*') r--;
pair<int, int> ans = max(make_pair(sum[p[1] - 1], l - p[1]),
make_pair(sum[n] - sum[p[1]], p[1] - r));
printf("%d %d\n", ans.first, -ans.second);
return 0;
}
printf("%d ", sum[n]);
int l = 1, len = n;
while (len) {
int md = l + (len >> 1);
if (!chk(md)) {
l = md + 1;
len = len - (len >> 1) - 1;
} else
len >>= 1;
}
printf("%d\n", l);
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
The Metropolis computer network consists of n servers, each has an encryption key in the range from 0 to 2^k - 1 assigned to it. Let c_i be the encryption key assigned to the i-th server. Additionally, m pairs of servers are directly connected via a data communication channel. Because of the encryption algorithms specifics, a data communication channel can only be considered safe if the two servers it connects have distinct encryption keys. The initial assignment of encryption keys is guaranteed to keep all data communication channels safe.
You have been informed that a new virus is actively spreading across the internet, and it is capable to change the encryption key of any server it infects. More specifically, the virus body contains some unknown number x in the same aforementioned range, and when server i is infected, its encryption key changes from c_i to c_i β x, where β denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Sadly, you know neither the number x nor which servers of Metropolis are going to be infected by the dangerous virus, so you have decided to count the number of such situations in which all data communication channels remain safe. Formally speaking, you need to find the number of pairs (A, x), where A is some (possibly empty) subset of the set of servers and x is some number in the range from 0 to 2^k - 1, such that when all servers from the chosen subset A and none of the others are infected by a virus containing the number x, all data communication channels remain safe. Since this number can be quite big, you are asked to find its remainder modulo 10^9 + 7.
Input
The first line of input contains three integers n, m and k (1 β€ n β€ 500 000, 0 β€ m β€ min((n(n - 1))/(2), 500 000), 0 β€ k β€ 60) β the number of servers, the number of pairs of servers directly connected by a data communication channel, and the parameter k, which defines the range of possible values for encryption keys.
The next line contains n integers c_i (0 β€ c_i β€ 2^k - 1), the i-th of which is the encryption key used by the i-th server.
The next m lines contain two integers u_i and v_i each (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that those servers are connected by a data communication channel. It is guaranteed that each pair of servers appears in this list at most once.
Output
The only output line should contain a single integer β the number of safe infections of some subset of servers by a virus with some parameter, modulo 10^9 + 7.
Examples
Input
4 4 2
0 1 0 1
1 2
2 3
3 4
4 1
Output
50
Input
4 5 3
7 1 7 2
1 2
2 3
3 4
4 1
2 4
Output
96
Note
Consider the first example.
Possible values for the number x contained by the virus are 0, 1, 2 and 3.
For values 0, 2 and 3 the virus can infect any subset of the set of servers, which gives us 16 pairs for each values. A virus containing the number 1 can infect either all of the servers, or none. This gives us 16 + 2 + 16 + 16 = 50 pairs in total.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10, mod = 1e9 + 7;
long long val[maxn], pw[maxn];
vector<int> adj[maxn];
inline int ad(int x, int y) { return (x + y) % mod; }
inline int mu(int x, int y) { return 1LL * x * y % mod; }
bool mark[maxn];
int Tot = 0;
void dfs(int v) {
if (mark[v]) return;
mark[v] = 1;
Tot++;
for (auto u : adj[v]) dfs(u);
}
int32_t main() {
ios::sync_with_stdio(0), cin.tie(0);
int n, m, k;
cin >> n >> m >> k;
for (int i = 0; i < n; i++) cin >> val[i];
pw[0] = 1;
for (int i = 1; i < maxn; i++) pw[i] = ad(pw[i - 1], pw[i - 1]);
vector<pair<long long, pair<int, int> > > ed;
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
u--, v--;
ed.push_back({val[u] ^ val[v], {u, v}});
}
sort(ed.begin(), ed.end());
int ted = 0, ans = 0;
for (int i = 0; i < m; i++) {
if (!i || ed[i].first != ed[i - 1].first) {
vector<int> seen;
int cnt = 0;
for (int j = i; ed[j].first == ed[i].first; j++) {
int u = ed[j].second.first;
int v = ed[j].second.second;
seen.push_back(u);
seen.push_back(v);
adj[u].push_back(v);
adj[v].push_back(u);
}
Tot = 0;
for (auto ver : seen) {
if (!mark[ver]) cnt++, dfs(ver);
}
for (auto ver : seen) mark[ver] = 0, adj[ver].clear();
cnt += (n - Tot);
ans = ad(ans, pw[cnt]);
ted++;
}
}
int lef = ad(pw[k], mod - ted);
ans = ad(ans, mu(lef, pw[n]));
cout << ans << '\n';
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
The Little Elephant has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai.
The Little Elephant wants to count, how many pairs of integers l and r are there, such that 1 β€ l < r β€ n and sequence b = a1a2... alarar + 1... an has no more than k inversions.
An inversion in sequence b is a pair of elements of the sequence b, that change their relative order after a stable sorting of the sequence. In other words, an inversion is a pair of integers i and j, such that 1 β€ i < j β€ |b| and bi > bj, where |b| is the length of sequence b, and bj is its j-th element.
Help the Little Elephant and count the number of the described pairs.
Input
The first line contains two integers n and k (2 β€ n β€ 105, 0 β€ k β€ 1018) β the size of array a and the maximum allowed number of inversions respectively. The next line contains n positive integers, separated by single spaces, a1, a2, ..., an (1 β€ ai β€ 109) β elements of array a.
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
In a single line print a single number β the answer to the problem.
Examples
Input
3 1
1 3 2
Output
3
Input
5 2
1 3 2 1 7
Output
6
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000 * 100 + 100;
struct fenwick {
long long tree[maxn];
fenwick() { memset(tree, 0, sizeof tree); }
long long C(long long i) {
long long ret = 0;
for (; i > 0; i -= i & (-i)) ret += tree[i];
return ret;
}
long long sum(int i, int j) { return C(j) - C(i - 1); }
void update(long long x, long long val) {
for (; x < maxn; x += x & (-x)) tree[x] += val;
}
};
long long n, k, ans, l, r, x, y, z, t = 1, a[maxn], b[maxn], d[maxn], m;
map<long long, long long> mp;
fenwick f, c;
bool flag;
int main() {
ios::sync_with_stdio(false);
cin >> n >> k;
for (int i = 1; i <= n; i++) {
cin >> d[i];
a[i] = d[i];
}
sort(d + 1, d + n + 1);
for (int i = 1; i <= n; i++)
if (!mp[d[i]]) mp[d[i]] = t++;
for (int i = 1; i <= n; i++) b[i] = mp[a[i]];
for (int i = 1; i <= n; i++) {
x = f.sum(b[i] + 1, n);
m += x;
f.update(b[i], 1);
}
if (m <= k) {
cout << (n * (n - 1)) / 2 << endl;
return 0;
}
for (int i = 1; i <= n; i++) {
x = 0;
if (i != 1) {
if (b[i - 1] != 1) m += f.sum(1, b[i - 1] - 1);
m += c.sum(b[i - 1] + 1, n);
c.update(b[i - 1], 1);
}
while (m > k) {
x = 0;
if (r == n) {
flag = 1;
break;
}
if (b[r + 1] != 1) m -= f.sum(1, b[r + 1] - 1);
m -= c.sum(b[r + 1] + 1, n);
f.update(b[++r], -1);
}
if (flag) break;
if (i != 1) ans += (n - r);
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
We have N logs of lengths A_1,A_2,\cdots A_N.
We can cut these logs at most K times in total. When a log of length L is cut at a point whose distance from an end of the log is t (0<t<L), it becomes two logs of lengths t and L-t.
Find the shortest possible length of the longest log after at most K cuts, and print it after rounding up to an integer.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq K \leq 10^9
* 1 \leq A_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_1 A_2 \cdots A_N
Output
Print an integer representing the answer.
Examples
Input
2 3
7 9
Output
4
Input
3 0
3 4 5
Output
5
Input
10 10
158260522 877914575 602436426 24979445 861648772 623690081 433933447 476190629 262703497 211047202
Output
292638192
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
signed main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int n, k;
cin >> n >> k;
vector<int> a(n);
for (auto &x : a) {
cin >> x;
}
int L = 0, R = *max_element(a.begin(), a.end()) + 1;
while (R - L > 1) {
int mid = (L + R) / 2;
ll cnt = 0;
for (int i = 0; i < n; i++) {
cnt += (a[i] - 1) / mid;
}
(cnt > k ? L : R) = mid;
}
cout << R << '\n';
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down.
Vasya knows that the durability of the i-th can is a_i. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (a_i β
x + 1) shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down.
Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible.
Input
The first line of the input contains one integer n (2 β€ n β€ 1 000) β the number of cans.
The second line of the input contains the sequence a_1, a_2, ..., a_n (1 β€ a_i β€ 1 000), where a_i is the durability of the i-th can.
Output
In the first line print the minimum number of shots required to knock each of the n given cans down exactly once.
In the second line print the sequence consisting of n distinct integers from 1 to n β the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them.
Examples
Input
3
20 10 20
Output
43
1 3 2
Input
4
10 10 10 10
Output
64
2 1 4 3
Input
6
5 4 5 4 4 5
Output
69
6 1 3 5 2 4
Input
2
1 4
Output
3
2 1
Note
In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots 20 β
1 + 1 = 21 times. After that only second can remains. To knock it down Vasya shoots 10 β
2 + 1 = 21 times. So the total number of shots is 1 + 21 + 21 = 43.
In the second example the order of shooting does not matter because all cans have the same durability.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long double PI = (long double)(3.1415926535897932384626433832795);
int parity_check(int n) {
int par = n;
par = par ^ (par >> 1);
par = par ^ (par >> 2);
par = par ^ (par >> 4);
par = par ^ (par >> 8);
par = par ^ (par >> 16);
if (par % 2 == 1) {
return 1;
} else {
return 0;
}
}
int lcs(string X, string Y, int m, int n) {
int L[m + 1][n + 1];
int i, j;
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X[i - 1] == Y[j - 1] && i != j)
L[i][j] = L[i - 1][j - 1] + 1;
else
L[i][j] = max(L[i - 1][j], L[i][j - 1]);
}
}
return L[m][n];
}
int long long gcd(int long long a, int long long b) {
if (a == 0) {
return b;
}
return gcd(b % a, a);
}
int long long lcm(int long long a, int long long b) {
int long long pro = a * b;
int long long ans = gcd(a, b);
pro = pro / ans;
return pro;
}
int long long fast_power(int long long a, int long long b, int long long p) {
if (b == 0) {
return (1 % p);
}
int long long t = fast_power(a, b / 2, p);
int long long ans = (t * t) % p;
if (b % 2) {
ans = (ans * (a % p)) % p;
}
return ans;
}
bool prime_check(int long long n) {
int long long i, j;
if (n == 1) {
return false;
}
for (i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
int long long fact(int long long n, int long long mod) {
int long long prod = 1;
for (int long long i = 1; i <= n; i++) {
prod = (prod * i) % mod;
}
return prod;
}
void mera_sieve() {
bool prime[6000013];
memset(prime, true, sizeof(prime));
for (int long long p = 2; p * p <= 6000012; p++) {
if (prime[p] == true) {
for (int long long i = p * p; i <= 6000012; i += p) prime[i] = false;
}
}
for (int long long i = 2; i <= 6000012; i++) {
if (prime[i]) {
}
}
}
void solve() {
int n;
cin >> n;
vector<pair<int, int>> v;
int long long ans = 0;
for (int i = 0; i < n; i++) {
int t;
cin >> t;
v.push_back(make_pair(t, i + 1));
}
sort(v.begin(), v.end());
for (int i = 0; i < n; i++) {
ans += (v[n - i - 1].first * i + 1);
}
cout << ans << "\n";
for (int i = n - 1; i >= 0; i--) cout << v[i].second << " ";
}
int main() {
int t;
t = 1;
while (t--) {
solve();
}
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Consider sequences \\{A_1,...,A_N\\} of length N consisting of integers between 1 and K (inclusive).
There are K^N such sequences. Find the sum of \gcd(A_1, ..., A_N) over all of them.
Since this sum can be enormous, print the value modulo (10^9+7).
Here \gcd(A_1, ..., A_N) denotes the greatest common divisor of A_1, ..., A_N.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq K \leq 10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
Output
Print the sum of \gcd(A_1, ..., A_N) over all K^N sequences, modulo (10^9+7).
Examples
Input
3 2
Output
9
Input
3 200
Output
10813692
Input
100000 100000
Output
742202979
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int n,k;
long long s,s1,m=1e9+7,b[100001];
int xar(int n, int p){
long long s;
if ( p==1 )
return n;
long long l=xar(n, p/2);
if (p%2==1)
s=(((l*l)%m)*n)%m;
else
s=(l*l)%m;
return s%m;
}
int main()
{
ios::sync_with_stdio(0);
cin >> n >> k;
for (int i=k; i>=1; i--){
int j=i+i;
while(j<=k){
s+=b[j];
s%=m;
j+=i;
}
b[i]=((xar(k/i, n) % m)-s)%m;
b[i]=(b[i]+m)%m;
s=0;
s1=0;
}
for (int i=1; i<=k; i++){
s+=(b[i]*i)%m;
//cout << b[i] << " ";
s%=m;
s=(s+m)%m;
}
cout << s << endl;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
The official capital and the cultural capital of Berland are connected by a single road running through n regions. Each region has a unique climate, so the i-th (1 β€ i β€ n) region has a stable temperature of ti degrees in summer.
This summer a group of m schoolchildren wants to get from the official capital to the cultural capital to visit museums and sights. The trip organizers transport the children between the cities in buses, but sometimes it is very hot. Specifically, if the bus is driving through the i-th region and has k schoolchildren, then the temperature inside the bus is ti + k degrees.
Of course, nobody likes it when the bus is hot. So, when the bus drives through the i-th region, if it has more than Ti degrees inside, each of the schoolchild in the bus demands compensation for the uncomfortable conditions. The compensation is as large as xi rubles and it is charged in each region where the temperature in the bus exceeds the limit.
To save money, the organizers of the trip may arbitrarily add or remove extra buses in the beginning of the trip, and between regions (of course, they need at least one bus to pass any region). The organizers can also arbitrarily sort the children into buses, however, each of buses in the i-th region will cost the organizers costi rubles. Please note that sorting children into buses takes no money.
Your task is to find the minimum number of rubles, which the organizers will have to spend to transport all schoolchildren.
Input
The first input line contains two integers n and m (1 β€ n β€ 105; 1 β€ m β€ 106) β the number of regions on the way and the number of schoolchildren in the group, correspondingly. Next n lines contain four integers each: the i-th line contains ti, Ti, xi and costi (1 β€ ti, Ti, xi, costi β€ 106). The numbers in the lines are separated by single spaces.
Output
Print the only integer β the minimum number of roubles the organizers will have to spend to transport all schoolchildren.
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.
Examples
Input
2 10
30 35 1 100
20 35 10 10
Output
120
Input
3 100
10 30 1000 1
5 10 1000 3
10 40 1000 100000
Output
200065
Note
In the first sample the organizers will use only one bus to travel through the first region. However, the temperature in the bus will equal 30 + 10 = 40 degrees and each of 10 schoolchildren will ask for compensation. Only one bus will transport the group through the second region too, but the temperature inside won't exceed the limit. Overall, the organizers will spend 100 + 10 + 10 = 120 rubles.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
long long ans = 0;
for (int i = (0); i < (n); ++i) {
long long t, T, x, cost;
cin >> t >> T >> x >> cost;
if (t >= T) {
ans += cost + m * x;
continue;
}
long long aux1 = cost;
if (m > (T - t)) aux1 += m * x;
long long aux2 = (long long)ceil((double)(m - (T - t)) / (T - t)) + 1;
aux2 *= cost;
ans += min(aux1, aux2);
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
Input
You are given 8 pairs of integers, a pair per line β the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
Output
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct.
If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
Examples
Input
0 0
10 11
10 0
0 11
1 1
2 2
2 1
1 2
Output
YES
5 6 7 8
1 2 3 4
Input
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
Output
NO
Input
0 0
4 4
4 0
0 4
1 2
2 3
3 2
2 1
Output
YES
1 2 3 4
5 6 7 8
Note
Pay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
### Response
```cpp
#include <bits/stdc++.h>
const int MAXINT = 2147483640;
const long long MAXLL = 9223372036854775800LL;
const long long MAXN = 1e6;
const double eps = 1e-9;
const long long mod = 1e9 + 7;
using namespace std;
bool f1(vector<pair<long long, pair<long double, long double>>> v) {
sort(v.begin(), v.end());
do {
long double ans1 = sqrt((v[0].second.first - v[2].second.first) *
(v[0].second.first - v[2].second.first) +
(v[0].second.second - v[2].second.second) *
(v[0].second.second - v[2].second.second));
long double ans2 = sqrt((v[1].second.first - v[3].second.first) *
(v[1].second.first - v[3].second.first) +
(v[1].second.second - v[3].second.second) *
(v[1].second.second - v[3].second.second));
if (abs(ans1 - ans2) <= eps) {
long double ans3 = sqrt((v[0].second.first - v[1].second.first) *
(v[0].second.first - v[1].second.first) +
(v[0].second.second - v[1].second.second) *
(v[0].second.second - v[1].second.second));
long double ans4 = sqrt((v[1].second.first - v[2].second.first) *
(v[1].second.first - v[2].second.first) +
(v[1].second.second - v[2].second.second) *
(v[1].second.second - v[2].second.second));
long double ans5 = sqrt((v[2].second.first - v[3].second.first) *
(v[2].second.first - v[3].second.first) +
(v[2].second.second - v[3].second.second) *
(v[2].second.second - v[3].second.second));
long double ans6 = sqrt((v[0].second.first - v[3].second.first) *
(v[0].second.first - v[3].second.first) +
(v[0].second.second - v[3].second.second) *
(v[0].second.second - v[3].second.second));
if (ans3 * ans4 > 0 && abs(ans3 - ans4) <= eps &&
abs(ans4 - ans5) <= eps && abs(ans5 - ans6) <= eps &&
abs(ans6 - ans3) <= eps)
return 1;
}
} while (next_permutation(v.begin(), v.end()));
return 0;
}
bool f2(vector<pair<long long, pair<long double, long double>>> v) {
sort(v.begin(), v.end());
do {
long double ans1 = sqrt((v[0].second.first - v[2].second.first) *
(v[0].second.first - v[2].second.first) +
(v[0].second.second - v[2].second.second) *
(v[0].second.second - v[2].second.second));
long double ans2 = sqrt((v[1].second.first - v[3].second.first) *
(v[1].second.first - v[3].second.first) +
(v[1].second.second - v[3].second.second) *
(v[1].second.second - v[3].second.second));
if (abs(ans1 - ans2) <= eps) {
long double ans3 = sqrt((v[0].second.first - v[1].second.first) *
(v[0].second.first - v[1].second.first) +
(v[0].second.second - v[1].second.second) *
(v[0].second.second - v[1].second.second));
long double ans4 = sqrt((v[1].second.first - v[2].second.first) *
(v[1].second.first - v[2].second.first) +
(v[1].second.second - v[2].second.second) *
(v[1].second.second - v[2].second.second));
long double ans5 = sqrt((v[2].second.first - v[3].second.first) *
(v[2].second.first - v[3].second.first) +
(v[2].second.second - v[3].second.second) *
(v[2].second.second - v[3].second.second));
long double ans6 = sqrt((v[0].second.first - v[3].second.first) *
(v[0].second.first - v[3].second.first) +
(v[0].second.second - v[3].second.second) *
(v[0].second.second - v[3].second.second));
if (abs(ans3 - ans5) <= eps && abs(ans4 - ans6) <= eps && ans3 * ans4 > 0)
return 1;
}
} while (next_permutation(v.begin(), v.end()));
return 0;
}
long double x[MAXN], y[MAXN];
int main() {
srand(time(0));
ios_base::sync_with_stdio(0);
cin.tie(0);
;
for (int i = 0; i < 8; ++i) {
cin >> x[i] >> y[i];
}
for (int mask = 0; mask < (1ll << 8); ++mask) {
if (__builtin_popcount(mask) == 4) {
vector<pair<long long, pair<long double, long double>>> v1, v2;
for (int j = 0; j < 8; ++j)
if (((1ll << j) & mask) == 0)
v2.push_back(make_pair(j, make_pair(x[j], y[j])));
else
v1.push_back(make_pair(j, make_pair(x[j], y[j])));
if (f1(v1) && f2(v2)) {
cout << "YES"
<< "\n";
for (auto j : v1) cout << j.first + 1 << " ";
cout << "\n";
for (auto j : v2) cout << j.first + 1 << " ";
cout << "\n";
return 0;
}
}
}
cout << "NO"
<< "\n";
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
Sherlock Holmes found a mysterious correspondence of two VIPs and made up his mind to read it. But there is a problem! The correspondence turned out to be encrypted. The detective tried really hard to decipher the correspondence, but he couldn't understand anything.
At last, after some thought, he thought of something. Let's say there is a word s, consisting of |s| lowercase Latin letters. Then for one operation you can choose a certain position p (1 β€ p < |s|) and perform one of the following actions:
* either replace letter sp with the one that alphabetically follows it and replace letter sp + 1 with the one that alphabetically precedes it;
* or replace letter sp with the one that alphabetically precedes it and replace letter sp + 1 with the one that alphabetically follows it.
Let us note that letter "z" doesn't have a defined following letter and letter "a" doesn't have a defined preceding letter. That's why the corresponding changes are not acceptable. If the operation requires performing at least one unacceptable change, then such operation cannot be performed.
Two words coincide in their meaning iff one of them can be transformed into the other one as a result of zero or more operations.
Sherlock Holmes needs to learn to quickly determine the following for each word: how many words can exist that coincide in their meaning with the given word, but differs from the given word in at least one character? Count this number for him modulo 1000000007 (109 + 7).
Input
The input data contains several tests. The first line contains the only integer t (1 β€ t β€ 104) β the number of tests.
Next t lines contain the words, one per line. Each word consists of lowercase Latin letters and has length from 1 to 100, inclusive. Lengths of words can differ.
Output
For each word you should print the number of different other words that coincide with it in their meaning β not from the words listed in the input data, but from all possible words. As the sought number can be very large, print its value modulo 1000000007 (109 + 7).
Examples
Input
1
ab
Output
1
Input
1
aaaaaaaaaaa
Output
0
Input
2
ya
klmbfxzb
Output
24
320092793
Note
Some explanations about the operation:
* Note that for each letter, we can clearly define the letter that follows it. Letter "b" alphabetically follows letter "a", letter "c" follows letter "b", ..., "z" follows letter "y".
* Preceding letters are defined in the similar manner: letter "y" precedes letter "z", ..., "a" precedes letter "b".
* Note that the operation never changes a word's length.
In the first sample you can obtain the only other word "ba". In the second sample you cannot obtain any other word, so the correct answer is 0.
Consider the third sample. One operation can transform word "klmbfxzb" into word "klmcexzb": we should choose p = 4, and replace the fourth letter with the following one ("b" β "c"), and the fifth one β with the preceding one ("f" β "e"). Also, we can obtain many other words from this one. An operation can transform word "ya" only into one other word "xb".
Word "ya" coincides in its meaning with words "xb", "wc", "vd", ..., "ay" (overall there are 24 other words). The word "klmbfxzb has many more variants β there are 3320092814 other words that coincide with in the meaning. So the answer for the first word equals 24 and for the second one equals 320092793 β the number 3320092814 modulo 109 + 7
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long dp[110][3100];
void init() {
int i, j;
memset(dp, 0, sizeof(dp));
for (i = 0; i < 26; i++) dp[1][i]++;
for (i = 2; i < 110; i++) {
for (j = 0; j < 26; j++) {
for (int k = j; k < 3100; k++) {
dp[i][k] = (dp[i][k] + dp[i - 1][k - j]) % 1000000007;
}
}
}
}
int main() {
char str[110];
int n, i;
init();
scanf("%d", &n);
while (n--) {
int sum = 0;
scanf("%s", str);
int len = strlen(str);
for (i = 0; i < len; i++) sum += str[i] - 'a';
if (dp[len][sum] == 0)
printf("%lld\n", 1000000007 - 1);
else
printf("%lld\n", dp[len][sum] - 1);
}
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
The Smart Beaver from ABBYY started cooperating with the Ministry of Defence. Now they train soldiers to move armoured columns. The training involves testing a new type of tanks that can transmit information. To test the new type of tanks, the training has a special exercise, its essence is as follows.
Initially, the column consists of n tanks sequentially numbered from 1 to n in the order of position in the column from its beginning to its end. During the whole exercise, exactly n messages must be transferred from the beginning of the column to its end.
Transferring one message is as follows. The tank that goes first in the column transmits the message to some tank in the column. The tank which received the message sends it further down the column. The process is continued until the last tank receives the message. It is possible that not all tanks in the column will receive the message β it is important that the last tank in the column should receive the message.
After the last tank (tank number n) receives the message, it moves to the beginning of the column and sends another message to the end of the column in the same manner. When the message reaches the last tank (tank number n - 1), that tank moves to the beginning of the column and sends the next message to the end of the column, and so on. Thus, the exercise is completed when the tanks in the column return to their original order, that is, immediately after tank number 1 moves to the beginning of the column.
If the tanks were initially placed in the column in the order 1, 2, ..., n, then after the first message their order changes to n, 1, ..., n - 1, after the second message it changes to n - 1, n, 1, ..., n - 2, and so on.
The tanks are constructed in a very peculiar way. The tank with number i is characterized by one integer ai, which is called the message receiving radius of this tank.
Transferring a message between two tanks takes one second, however, not always one tank can transmit a message to another one. Let's consider two tanks in the column such that the first of them is the i-th in the column counting from the beginning, and the second one is the j-th in the column, and suppose the second tank has number x. Then the first tank can transmit a message to the second tank if i < j and i β₯ j - ax.
The Ministry of Defense (and soon the Smart Beaver) faced the question of how to organize the training efficiently. The exercise should be finished as quickly as possible. We'll neglect the time that the tanks spend on moving along the column, since improving the tanks' speed is not a priority for this training.
You are given the number of tanks, as well as the message receiving radii of all tanks. You must help the Smart Beaver and organize the transferring of messages in a way that makes the total transmission time of all messages as small as possible.
Input
The first line contains integer n β the number of tanks in the column. Each of the next n lines contains one integer ai (1 β€ ai β€ 250000, 1 β€ i β€ n) β the message receiving radii of the tanks in the order from tank 1 to tank n (let us remind you that initially the tanks are located in the column in ascending order of their numbers).
To get the full points for the first group of tests it is sufficient to solve the problem with 2 β€ n β€ 300.
To get the full points for the second group of tests it is sufficient to solve the problem with 2 β€ n β€ 10000.
To get the full points for the third group of tests it is sufficient to solve the problem with 2 β€ n β€ 250000.
Output
Print a single integer β the minimum possible total time of transmitting the messages.
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
3
2
1
1
Output
5
Input
5
2
2
2
2
2
Output
10
Note
In the first sample the original order of tanks is 1, 2, 3. The first tank sends a message to the second one, then the second tank sends it to the third one β it takes two seconds. The third tank moves to the beginning of the column and the order of tanks now is 3, 1, 2. The third tank sends a message to the first one, then the first one sends it to the second one β it takes two more seconds. The second tank moves to the beginning and the order of the tanks is now 2, 3, 1. With this arrangement, the second tank can immediately send a message to the first one, since the message receiving radius of the first tank is large enough β it takes one second. Finally, the tanks return to their original order 1, 2, 3. In total, the exercise takes 5 seconds.
In the second sample, all five tanks are the same and sending a single message takes two seconds, so in total the exercise takes 10 seconds.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
pair<int, int> ST[500500][20];
long long Ans;
int Log2[500500], n, a[500500], F[500500][20], head[500500], cnt;
struct Edge {
int to, next;
} edge[500500 << 1];
void AddEdge(int u, int v) { edge[++cnt] = (Edge){v, head[u]}, head[u] = cnt; }
void Dfs(int u, int fa, int dep) {
F[u][0] = fa;
for (int i = 1; 1 << i < dep; i++) F[u][i] = F[F[u][i - 1]][i - 1];
for (int i = head[u]; i; i = edge[i].next) Dfs(edge[i].to, u, dep + 1);
}
pair<int, int> Min(int l, int r) {
int len = r - l + 1, Log = Log2[len];
return min(ST[l][Log], ST[r - (1 << Log) + 1][Log]);
}
int Calc(int u, int tar) {
int ret = 0;
if (a[u] <= tar) return 1;
for (int i = 19; i >= 0; i--)
if (a[F[u][i]] > tar) u = F[u][i], ret += 1 << i;
return ret + 2;
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", a + i), a[i + n] = a[i];
for (int i = 1; i <= 2 * n; i++) a[i] = max(i - a[i], 1);
for (int i = 1; i <= 2 * n; i++) ST[i][0] = make_pair(a[i], i);
for (int i = 1; i <= 19; i++)
for (int j = 1; j <= 2 * n; j++)
ST[j][i] = min(ST[j][i - 1], ST[j + (1 << (i - 1))][i - 1]);
for (int i = 2; i <= n; i++) Log2[i] = Log2[i >> 1] + 1;
for (int i = 2; i <= 2 * n; i++) AddEdge(Min(a[i], i - 1).second, i);
Dfs(1, 0, 1);
for (int i = 1; i <= n; i++) Ans += Calc(i + n - 1, i);
printf("%I64d\n", Ans);
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
There are N strings arranged in a row. It is known that, for any two adjacent strings, the string to the left is lexicographically smaller than the string to the right. That is, S_1<S_2<...<S_N holds lexicographically, where S_i is the i-th string from the left.
At least how many different characters are contained in S_1,S_2,...,S_N, if the length of S_i is known to be A_i?
Constraints
* 1 \leq N \leq 2\times 10^5
* 1 \leq A_i \leq 10^9
* A_i is an integer.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible number of different characters contained in the strings.
Examples
Input
3
3 2 1
Output
2
Input
5
2 3 2 1 2
Output
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n,a[200005];
inline bool check(int x){
if(x==1){
bool flag=1;
for(int i=1;i<n;i++) if(a[i+1]<=a[i]) flag=0;
return flag;
}
map<int,int> mp;
int cur=0;
for(register int i=1;i<=n;i++){
if(a[i]<=cur){
cur=a[i];
while(1){
if(mp[cur]<x-1) break;
mp[cur]=0;
cur--;
}
mp[cur]++;
if(cur<=0) return 0;
}
else cur=a[i];
mp.erase(mp.upper_bound(cur),mp.end());
}
return 1;
}
int main(){
cin>>n;
for(int i=1;i<=n;i++) cin>>a[i];
int l=1,r=300000,ans;
while(l<=r){
int mid=(l+r)>>1;
if(check(mid)) ans=mid,r=mid-1;
else l=mid+1;
}
cout<<ans<<endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
Little girl Susie went shopping with her mom and she wondered how to improve service quality.
There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed.
Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.
Input
The first line contains integer n (1 β€ n β€ 105).
The next line contains n integers ti (1 β€ ti β€ 109), separated by spaces.
Output
Print a single number β the maximum number of not disappointed people in the queue.
Examples
Input
5
15 2 1 5 3
Output
4
Note
Value 4 is achieved at such an arrangement, for example: 1, 2, 3, 5, 15. Thus, you can make everything feel not disappointed except for the person with time 5.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long x, y = 0, z = 0, arr[(long long)1e5];
cin >> x;
for (int i = 0; i < x; i++) {
cin >> arr[i];
}
sort(arr, arr + x);
for (int i = 0; i < x; i++) {
if (arr[i] >= y) {
y += arr[i];
z++;
}
}
cout << z << endl;
return 0;
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
Given a simple graph, output the number of simple cycles in it. A simple cycle is a cycle with no repeated vertices or edges.
Input
The first line of input contains two integers n and m (1 β€ n β€ 19, 0 β€ m) β respectively the number of vertices and edges of the graph. Each of the subsequent m lines contains two integers a and b, (1 β€ a, b β€ n, a β b) indicating that vertices a and b are connected by an undirected edge. There is no more than one edge connecting any pair of vertices.
Output
Output the number of cycles in the given graph.
Examples
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
7
Note
The example graph is a clique and contains four cycles of length 3 and three cycles of length 4.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n, m;
vector<long long> G[20];
long long ans;
bool f[20];
long long dp[(1 << 19) + 5][20];
signed main() {
long long a, b;
scanf("%lld", &(n));
scanf("%lld", &(m));
for (long long i = 1; i <= m; i++) {
scanf("%lld", &(a));
scanf("%lld", &(b));
a--;
b--;
G[a].push_back(b);
G[b].push_back(a);
}
for (long long i = 0; i < n; i++) {
memset(dp, 0, sizeof dp);
for (long long j = i; j < n; j++) {
dp[1 << j][j] = 1;
}
for (long long k = 1; k <= (1 << n) - 1; k++) {
for (long long w = i; w < n; w++) {
if (dp[k][w])
for (long long x = 0; x < G[w].size(); x++) {
long long y = G[w][x];
if (((k & -k) == 1 << i) && y == i && ((k >> i) & 1)) {
ans += dp[k][w];
} else if (((k >> y) & 1) == 0 && y > i)
dp[k | (1 << y)][y] += dp[k][w];
}
}
}
}
cout << (ans - m) / 2 << '\n';
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
Vanya got n cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1 + 2 = 3 cubes, the third level must have 1 + 2 + 3 = 6 cubes, and so on. Thus, the i-th level of the pyramid must have 1 + 2 + ... + (i - 1) + i cubes.
Vanya wants to know what is the maximum height of the pyramid that he can make using the given cubes.
Input
The first line contains integer n (1 β€ n β€ 104) β the number of cubes given to Vanya.
Output
Print the maximum possible height of the pyramid in the single line.
Examples
Input
1
Output
1
Input
25
Output
4
Note
Illustration to the second sample:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n2[100];
n2[0] = 1;
for (int i = 1; i < 100; i++) {
n2[i] = n2[i - 1] + i + 1;
}
int n;
while (cin >> n) {
double count = 0.0;
for (int i = 0; i < 100; i++) {
count += n2[i];
if (n < count) {
cout << i << endl;
break;
}
}
}
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya.
On the way from Denis's house to the girl's house is a road of n lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.
Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up g seconds green, and then r seconds red, then again g seconds green and so on.
Formally, the road can be represented as a segment [0, n]. Initially, Denis is at point 0. His task is to get to point n in the shortest possible time.
He knows many different integers d_1, d_2, β¦, d_m, where 0 β€ d_i β€ n β are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.
Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed:
* He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by Β± 1 in 1 second. While doing so, he must always stay inside the segment [0, n].
* He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by +1 and he walked on a safety island, then he can change his position by Β± 1. Otherwise, he can change his position only by +1. Similarly, if in the previous second he changed his position by -1, on a safety island he can change position by Β± 1, and at any other point by -1.
* At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on.
Denis has crossed the road as soon as his coordinate becomes equal to n.
This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do.
Input
The first line contains two integers n and m (1 β€ n β€ 10^6, 2 β€ m β€ min(n + 1, 10^4)) β road width and the number of safety islands.
The second line contains m distinct integers d_1, d_2, β¦, d_m (0 β€ d_i β€ n) β the points where the safety islands are located. It is guaranteed that there are 0 and n among them.
The third line contains two integers g, r (1 β€ g, r β€ 1000) β the time that the green light stays on and the time that the red light stays on.
Output
Output a single integer β the minimum time for which Denis can cross the road with obeying all the rules.
If it is impossible to cross the road output -1.
Examples
Input
15 5
0 3 7 14 15
11 11
Output
45
Input
13 4
0 3 7 13
9 9
Output
-1
Note
In the first test, the optimal route is:
* for the first green light, go to 7 and return to 3. In this case, we will change the direction of movement at the point 7, which is allowed, since there is a safety island at this point. In the end, we will be at the point of 3, where there is also a safety island. The next 11 seconds we have to wait for the red light.
* for the second green light reaches 14. Wait for the red light again.
* for 1 second go to 15. As a result, Denis is at the end of the road.
In total, 45 seconds are obtained.
In the second test, it is impossible to cross the road according to all the rules.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
int n, m, d[10010], g, r, dist[10010], ans;
bool vis[10010][1010];
vector<int> v;
queue<int> q;
void dfs(int pos, int lft) {
if (vis[pos][lft]) return;
vis[pos][lft] = true;
if (lft == 0) {
v.push_back(pos);
return;
}
if (pos - 1 >= 0 && lft - (d[pos] - d[pos - 1]) >= 0)
dfs(pos - 1, lft - (d[pos] - d[pos - 1]));
if (pos + 1 < m && lft - (d[pos + 1] - d[pos]) >= 0)
dfs(pos + 1, lft - (d[pos + 1] - d[pos]));
}
int main() {
cin >> n >> m;
for (int i = 0; i < m; i++) scanf("%d", &d[i]);
sort(d, d + m);
cin >> g >> r;
vis[0][0] = true;
q.push(0);
while (!q.empty()) {
int i = q.front();
q.pop();
v.clear();
dfs(i, g);
for (int j = 0; j < v.size(); j++) {
dist[v[j]] = dist[i] + g + r;
q.push(v[j]);
}
}
ans = dist[m - 1] - r;
for (int i = 0; i < m - 1; i++)
if (d[m - 1] - d[i] <= g && (dist[i] > 0 || i == 0)) {
if (ans < 0)
ans = dist[i] + d[m - 1] - d[i];
else
ans = min(ans, dist[i] + d[m - 1] - d[i]);
}
if (ans < 0)
puts("-1");
else
cout << ans << endl;
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Each segment has one of two colors: the i-th segment's color is t_i.
Let's call a pair of segments i and j bad if the following two conditions are met:
* t_i β t_j;
* the segments [l_i, r_i] and [l_j, r_j] intersect, embed or touch, i. e. there exists an integer x such that x β [l_i, r_i] and x β [l_j, r_j].
Calculate the maximum number of segments that can be selected from the given ones, so that there is no bad pair among the selected ones.
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β number of segments.
The next n lines contains three integers l_i, r_i, t_i (1 β€ l_i β€ r_i β€ 10^9; t_i β \{1, 2\}) β description of the i-th segment.
Output
Print the maximum number of segments that can be selected, so that there is no bad pair among the selected segments.
Examples
Input
3
1 3 1
4 6 2
2 5 1
Output
2
Input
5
5 8 1
1 3 2
3 4 2
6 6 1
2 10 2
Output
4
Input
7
19 20 1
13 15 2
6 11 2
4 10 1
14 17 1
13 13 2
5 9 1
Output
5
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using pii = pair<int, int>;
using pi3 = pair<int, pii>;
const int NN = 502020;
int st[NN], ed[NN], t[NN];
set<pii> ss[4];
int main() {
int n;
cin >> n;
vector<pi3> vec;
for (int i = 1; i <= n; i++) {
scanf("%d %d %d", st + i, ed + i, t + i);
vec.push_back(pi3(st[i], pii(1, i)));
vec.push_back(pi3(ed[i], pii(2, i)));
}
sort(vec.begin(), vec.end());
int ans = 0;
for (auto p : vec) {
if (p.second.first == 2) {
int i = p.second.second;
int j = t[i];
int k = 3 - j;
if (ss[j].count(pii(ed[i], i)) && ss[k].size()) {
ans++;
ss[k].erase(ss[k].begin());
}
if (ss[j].count(pii(ed[i], i))) {
ss[j].erase(ss[j].find(pii(ed[i], i)));
}
} else {
ss[t[p.second.second]].insert(pii(ed[p.second.second], p.second.second));
}
}
cout << n - ans << endl;
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
You are given a string S of length 2 or 3 consisting of lowercase English letters. If the length of the string is 2, print it as is; if the length is 3, print the string after reversing it.
Constraints
* The length of S is 2 or 3.
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
If the length of S is 2, print S as is; if the length is 3, print S after reversing it.
Examples
Input
abc
Output
cba
Input
ac
Output
ac
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
string S;
cin >> S;
if (S.length() == 3){
reverse(S.begin(), S.end());
cout << S << endl;
}
else{
cout << S;
}
}
``` |
### Prompt
Generate a CPP solution to the following problem:
There is data that records the customer number of the business partner and the trading date on a monthly basis. Please create a program that reads this month's data and last month's data and outputs the customer number of the company with which you have transactions and the number of transactions for two consecutive months from last month. However, the number of monthly business partners is 1,000 or less.
Input
This month's data and last month's data are given separated by one blank line. Each data is given in the following format.
c1, d1
c2, d2
...
...
ci (1 β€ ci β€ 1,000) is an integer representing the customer number, and di (1 β€ di β€ 31) is an integer representing the trading day.
Output
For companies that have transactions for two consecutive months, the customer number and the total number of transactions are output separated by a blank in ascending order of customer number.
Example
Input
123,10
56,12
34,14
123,3
56,4
123,5
Output
56 2
123 3
### Response
```cpp
#include <iostream>
#include <cstdio>
#include <map>
#include <string>
using namespace std;
int ID(string str){
int num = 0;
for(int i = 0; i < 500; i++){
if(str[i] == ','){
break;
}
num *= 10;
num += (str[i] - '0');
}
return num;
}
// ??????????????§??????????????’?´’?????????????????????
int main(){
map<int, int> m;
map<int, int>::iterator ite;
string str;
int id;
while(true){
getline(cin, str);
if(str.size() == 0){
break;
}
id = ID(str);
ite = m.find(id);
if(ite != m.end()){
ite -> second++;
}else{
m.insert(make_pair(id, 1));
}
}
while(true){
cin >> str;
if(cin.eof()){
break;
}
id = ID(str);
ite = m.find(id);
if(ite != m.end()){
if(ite -> second < 10000){
ite -> second += 10000;
}
ite -> second++;
}
}
for(ite = m.begin(); ite != m.end(); ite++){
if(ite -> second > 10000){
cout << ite -> first << " " << ite -> second - 10000 << endl;
}
}
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved.
This is an interactive problem.
You are given a tree consisting of n nodes numbered with integers from 1 to n. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query:
* Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes.
Recall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them.
More formally, let's define two hidden nodes as s and f. In one query you can provide the set of nodes \\{a_1, a_2, β¦, a_c\} of the tree. As a result, you will get two numbers a_i and dist(a_i, s) + dist(a_i, f). The node a_i is any node from the provided set, for which the number dist(a_i, s) + dist(a_i, f) is minimal.
You can ask no more than 14 queries.
Input
The first line contains a single integer t (1 β€ t β€ 10) β the number of test cases. Please note, how the interaction process is organized.
The first line of each test case consists of a single integer n (2 β€ n β€ 1000) β the number of nodes in the tree.
The next n - 1 lines consist of two integers u, v (1 β€ u, v β€ n, u β v) β the edges of the tree.
Interaction
To ask a query print a single line:
* In the beginning print "? c " (without quotes) where c (1 β€ c β€ n) denotes the number of nodes being queried, followed by c distinct integers in the range [1, n] β the indices of nodes from the list.
For each query, you will receive two integers x, d β the node (among the queried nodes) with the minimum sum of distances to the hidden nodes and the sum of distances from that node to the hidden nodes. If the subset of nodes queried is invalid or you exceeded the number of queries then you will get x = d = -1. In this case, you should terminate the program immediately.
When you have guessed the hidden nodes, print a single line "! " (without quotes), followed by two integers in the range [1, n] β the hidden nodes. You can output the hidden nodes in any order.
After this, you should read a string. If you guess the nodes correctly, you will receive the string "Correct". In this case, you should continue solving the remaining test cases or terminate the program, if all test cases were solved. Otherwise, you will receive the string "Incorrect". In this case, you should terminate the program immediately.
Guessing the hidden nodes does not count towards the number of queries asked.
The interactor is not adaptive. The hidden nodes do not change with queries.
Do not forget to read the string "Correct" / "Incorrect" after guessing the hidden nodes.
You need to solve each test case before receiving the input for the next test case.
The limit of 14 queries applies to each test case and not to the entire input.
After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
To hack the solution, use the following test format:
The first line should contain a single integer t (1 β€ t β€ 10) β the number of test cases. The description of the test cases follows.
The first line of each test case should contain a single integer n (2 β€ n β€ 1000) β the number of nodes in the tree. The second line should contain two distinct integers in the range [1, n] β the hidden nodes. The next n - 1 lines should contain two integers u, v (1 β€ u, v β€ n, u β v) β the edges of the tree.
Example
Input
1
3
1 2
1 3
1 1
2 3
3 1
3 1
Correct
Output
? 1 1
? 1 2
? 1 3
? 2 2 3
! 1 3
Note
The tree from the first test is shown below, and the hidden nodes are 1 and 3.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int b[1005];
int ans[1005];
int n, k;
void valid(int x) {
if (x == -1) exit(0);
}
int query2(vector<int> v) {
cout << "? " << v.size() << " ";
for (int i = 0; i < v.size(); i++) cout << v[i] << " ";
cout << endl;
int maks;
cin >> maks;
valid(maks);
return maks;
}
int query1(int l, int r) {
int sz = r - l + 1;
cout << "? " << sz << " ";
for (int i = l; i <= r; i++) cout << i << " ";
cout << endl;
int maks;
cin >> maks;
valid(maks);
return maks;
}
void odgovor() {
cout << "! ";
for (int i = 1; i <= k; i++) cout << ans[i] << " ";
cout << endl;
string odg;
cin >> odg;
if (odg == "Incorrect") exit(0);
}
int nadjibinarno(int l, int r, int x) {
if (l == r) return l;
int mid = (l + r) / 2;
int y = query1(l, mid);
if (y == x) return nadjibinarno(l, mid, x);
return nadjibinarno(mid + 1, r, x);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cerr.tie(0);
int t;
cin >> t;
while (t--) {
cin >> n >> k;
for (int i = 1; i <= n; i++) b[i] = 0;
for (int i = 1; i <= k; i++) {
int c;
cin >> c;
for (int j = 1; j <= c; j++) {
int x;
cin >> x;
b[x] = i;
}
}
int l1 = 1;
int r1 = n / 2;
int l2 = r1 + 1;
int r2 = n;
int x = query1(l1, r1);
int y = query1(l2, r2);
int pos;
if (x > y)
pos = nadjibinarno(l1, r1, x);
else
pos = nadjibinarno(l2, r2, y);
int bc = b[pos];
if (bc == 0)
for (int i = 1; i <= k; i++) ans[i] = max(x, y);
else {
for (int i = 1; i <= k; i++)
if (i != bc) ans[i] = max(x, y);
vector<int> v;
for (int i = 1; i <= n; i++)
if (b[i] != bc) v.push_back(i);
ans[bc] = query2(v);
}
odgovor();
}
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
You invited n guests to dinner! You plan to arrange one or more circles of chairs. Each chair is going to be either occupied by one guest, or be empty. You can make any number of circles.
Your guests happen to be a little bit shy, so the i-th guest wants to have a least l_i free chairs to the left of his chair, and at least r_i free chairs to the right. The "left" and "right" directions are chosen assuming all guests are going to be seated towards the center of the circle. Note that when a guest is the only one in his circle, the l_i chairs to his left and r_i chairs to his right may overlap.
What is smallest total number of chairs you have to use?
Input
First line contains one integer n β number of guests, (1 β©½ n β©½ 10^5).
Next n lines contain n pairs of space-separated integers l_i and r_i (0 β©½ l_i, r_i β©½ 10^9).
Output
Output a single integer β the smallest number of chairs you have to use.
Examples
Input
3
1 1
1 1
1 1
Output
6
Input
4
1 2
2 1
3 5
5 3
Output
15
Input
1
5 6
Output
7
Note
In the second sample the only optimal answer is to use two circles: a circle with 5 chairs accomodating guests 1 and 2, and another one with 10 chairs accomodationg guests 3 and 4.
In the third sample, you have only one circle with one person. The guest should have at least five free chairs to his left, and at least six free chairs to his right to the next person, which is in this case the guest herself. So, overall number of chairs should be at least 6+1=7.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> v, v1;
for (int i = 0; i < n; i++) {
int t, y;
cin >> t >> y;
v.push_back(t);
v1.push_back(y);
}
sort(v.begin(), v.end());
sort(v1.begin(), v1.end());
long long ans = n;
for (int i = 0; i < n; i++) {
ans += max(v[i], v1[i]);
}
cout << ans;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Xenia the horse breeder has n (n > 1) horses that stand in a row. Each horse has its own unique number. Initially, the i-th left horse has number i. That is, the sequence of numbers of horses in a row looks as follows (from left to right): 1, 2, 3, ..., n.
Xenia trains horses before the performance. During the practice sessions, she consistently gives them commands. Each command is a pair of numbers l, r (1 β€ l < r β€ n). The command l, r means that the horses that are on the l-th, (l + 1)-th, (l + 2)-th, ..., r-th places from the left must be rearranged. The horses that initially stand on the l-th and r-th places will swap. The horses on the (l + 1)-th and (r - 1)-th places will swap. The horses on the (l + 2)-th and (r - 2)-th places will swap and so on. In other words, the horses that were on the segment [l, r] change their order to the reverse one.
For example, if Xenia commanded l = 2, r = 5, and the sequence of numbers of horses before the command looked as (2, 1, 3, 4, 5, 6), then after the command the sequence will be (2, 5, 4, 3, 1, 6).
We know that during the practice Xenia gave at most three commands of the described form. You have got the final sequence of numbers of horses by the end of the practice. Find what commands Xenia gave during the practice. Note that you do not need to minimize the number of commands in the solution, find any valid sequence of at most three commands.
Input
The first line contains an integer n (2 β€ n β€ 1000) β the number of horses in the row. The second line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ n), where ai is the number of the i-th left horse in the row after the practice.
Output
The first line should contain integer k (0 β€ k β€ 3) β the number of commads Xenia gave during the practice. In each of the next k lines print two integers. In the i-th line print numbers li, ri (1 β€ li < ri β€ n) β Xenia's i-th command during the practice.
It is guaranteed that a solution exists. If there are several solutions, you are allowed to print any of them.
Examples
Input
5
1 4 3 2 5
Output
1
2 4
Input
6
2 1 4 3 6 5
Output
3
1 2
3 4
5 6
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 7;
const int INF = 1e9 + 7;
int n, a[N];
pair<int, int> ans[3];
bool check() {
for (int i = (1); i < (n + 1); ++i)
if (a[i] != i) return false;
return true;
}
bool f(int i) {
return (a[i] != i) && (abs(a[i] - a[i - 1]) > 1 || abs(a[i + 1] - a[i]) > 1);
}
bool dfs(int dep) {
if (check()) {
printf("%d\n", dep);
for (int i = (0); i < (dep); ++i)
printf("%d %d\n", ans[dep - 1 - i].first, ans[dep - 1 - i].second);
return true;
}
if (dep >= 3) return false;
for (int l = (1); l < (n + 1); ++l) {
if (!f(l)) continue;
for (int r = (l + 1); r < (n + 1); ++r) {
if (!f(r)) continue;
reverse(a + l, a + r + 1);
ans[dep] = make_pair(l, r);
if (dfs(dep + 1)) return true;
reverse(a + l, a + r + 1);
}
}
return false;
}
int main() {
scanf("%d", &n);
a[0] = a[n + 1] = INF;
for (int i = (1); i < (n + 1); ++i) scanf("%d", &a[i]);
dfs(0);
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Dima got into number sequences. Now he's got sequence a1, a2, ..., an, consisting of n positive integers. Also, Dima has got a function f(x), which can be defined with the following recurrence:
* f(0) = 0;
* f(2Β·x) = f(x);
* f(2Β·x + 1) = f(x) + 1.
Dima wonders, how many pairs of indexes (i, j) (1 β€ i < j β€ n) are there, such that f(ai) = f(aj). Help him, count the number of such pairs.
Input
The first line contains integer n (1 β€ n β€ 105). The second line contains n positive integers a1, a2, ..., an (1 β€ ai β€ 109).
The numbers in the lines are separated by single spaces.
Output
In a single line print the answer to the problem.
Please, don't use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2 4
Output
3
Input
3
5 3 1
Output
1
Note
In the first sample any pair (i, j) will do, so the answer is 3.
In the second sample only pair (1, 2) will do.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n, m[33], x, ans, answer;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 0; i < n; i++) {
ans = 0;
cin >> x;
while (x >= 1) {
if (x % 2 == 1) {
ans++;
}
x /= 2;
}
m[ans]++;
}
for (int i = 1; i <= 31; i++) {
answer += (m[i] - 1) * (m[i]) / 2;
}
cout << answer << endl;
return 0;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
This problem was deleted from the contest, because it was used previously at another competition.
Input
Output
Examples
Input
1 1
1 2 100
Output
6
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100050, maxp = 1000, maxps = 200;
int pr[maxps], whe[maxn] = {0}, ps = 0;
long long n, m, L, R, p, ans = 0;
int fa[maxps], fs = 0;
int Sqrt(long long x) {
if (x < 0)
return 0;
else if (x > m * m)
return m;
return sqrt(x);
}
void init() {
int i, j;
for (i = 2; i < maxp; i++) {
if (!whe[i]) pr[ps++] = i;
for (j = 0; j < ps && i * pr[j] < maxn; j++) {
whe[i * pr[j]] = 1;
if (!(i % pr[j])) break;
}
}
}
int dfs(int k, bool u, int cur, int now) {
int i;
long long s = 0;
if (cur == fs) {
long long t = k / now;
s = (t * (m + 1) - t * (t + 1) / 2 * now);
return (-2 * u + 1) * s % p;
}
s = dfs(k, u, cur + 1, now);
s += dfs(k, !u, cur + 1, now * fa[cur]);
return s % p;
}
int calc(int x, int k) {
int i, x0 = x;
if (!k) return 0;
fs = 0;
memset(fa, 0, sizeof(fa));
for (i = 0; i < ps; i++)
if (!(x0 % pr[i])) {
while (!(x0 % pr[i])) x0 /= pr[i];
fa[fs++] = pr[i];
}
if (x0 > 1) fa[fs++] = x0;
return dfs(k, 0, 0, 1);
}
int main() {
long long x;
init();
scanf("%I64d%I64d%I64d%I64d%I64d", &n, &m, &L, &R, &p);
for (x = 1; x <= min(n, R - 1); x++) {
int l = Sqrt(L * L - x * x - 1), r = Sqrt(R * R - x * x);
ans += (n - x + 1) * (calc(x, r) - calc(x, l)) % p;
ans %= p;
}
ans *= 2;
if (L == 1) ans += n * (m + 1) + m * (n + 1);
ans %= p;
if (ans < 0) ans += p;
printf("%I64d\n", ans);
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
The Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail.
We assume that the hash table consists of h cells numbered from 0 to h - 1. Objects are added to and removed from it. Every object has its own unique identifier. In addition, every object has a corresponding hash value β an integer between 0 and h - 1, inclusive. When an object is added to the table, if the cell corresponding to the hash value of the object is free, then this object goes there. If the cell is already occupied by another object, there is a collision. When an object is deleted from the table, the cell which it occupied becomes empty.
The Smart Beaver has recently learned about the method of linear probing to resolve collisions. It is as follows. Let's say that the hash value for the added object equals t and cell t of the table is already occupied. Then we try to add this object to cell (t + m) mod h. If it is also occupied, then we try cell (t + 2Β·m) mod h, then cell (t + 3Β·m) mod h, and so on. Note that in some cases it's possible that the new object can not be added to the table. It is guaranteed that the input for this problem doesn't contain such situations.
The operation a mod b means that we take the remainder of the division of number a by number b.
This technique immediately seemed very inoptimal to the Beaver, and he decided to assess its inefficiency. So, you are given a sequence of operations, each of which is either an addition of an object to the table or a deletion of an object from the table. When adding a new object, a sequence of calls to the table is performed. Calls to occupied cells are called dummy. In other words, if the result of the algorithm described above is the object being added to cell (t + iΒ·m) mod h (i β₯ 0), then exactly i dummy calls have been performed.
Your task is to calculate the total number of dummy calls to the table for the given sequence of additions and deletions. When an object is deleted from the table, assume that no dummy calls are performed. The table is empty before performing the operations, that is, initially it doesn't contain any objects.
Input
The first line of input contains three integers h, m and n (1 β€ m < h), separated by spaces, where h is the size of the hash table, m is the number that is used to resolve collisions, n is the number of operations.
The following n lines contains the descriptions of the operations. Their execution order corresponds to the order in which they appear in the input file. Each operation is described by a single line. The operations are described as follows:
* "+ id hash"
This is the format of the operation that adds an object to the table. The first character is "+" (ASCII 43), followed by a single space, then the object identifier id (0 β€ id β€ 109), then another space, and the hash value of the given object hash (0 β€ hash < h). The object identifier and the hash value of this object are integers.
* "- id"
This is the format of the operation that deletes an object from the table. The first character is "-" (ASCII 45), followed by a single space, then the object identifier id (0 β€ id β€ 109). The object identifier is an integer.
It is guaranteed that for all addition operations the value of id is unique. It is also guaranteed that the initial data is correct, that is, it's always possible to add an object to the hash table and there won't be any deletions of nonexisting objects.
The input limitations for getting 20 points are:
* 1 β€ h β€ 5000
* 1 β€ n β€ 5000
The input limitations for getting 50 points are:
* 1 β€ h β€ 5Β·104
* 1 β€ n β€ 5Β·104
The input limitations for getting 100 points are:
* 1 β€ h β€ 2Β·105
* 1 β€ n β€ 2Β·105
Output
Print a single number β the total number of dummy calls to the hash table.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams and the %I64d specifier.
Examples
Input
10 2 7
+ 11 0
+ 22 2
+ 33 6
+ 44 0
+ 55 0
- 22
+ 66 0
Output
7
Input
5 1 6
+ 123 0
+ 234 1
+ 345 2
- 234
+ 456 0
+ 567 0
Output
4
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[200000], b[200000][2], f[200000][2];
int bit[1 << 18];
vector<vector<int> > v;
map<int, int> mp;
int sum(int i) {
int s = 0;
while (i > 0) {
s += bit[i];
i -= i & -i;
}
return s;
}
void add(int i, int x) {
while (i < (1 << 18)) {
bit[i] += x;
i += i & -i;
}
}
int insert(int x, int y) {
int p, q, l, r, m;
p = b[f[y][0]][0] + f[y][1];
q = b[f[y][0]][1];
if (sum(q + 1) - sum(p) < q - p + 1) {
l = p;
r = q;
m = (l + r) / 2;
while (r - l > 1) {
if (sum(m + 1) - sum(p) < m - p + 1) {
r = m;
m = (l + r) / 2;
} else {
l = m;
m = (l + r) / 2;
}
}
if (a[v[f[y][0]][l - b[f[y][0]][0]]] == 0) {
a[v[f[y][0]][l - b[f[y][0]][0]]] = 1;
mp[x] = v[f[y][0]][l - b[f[y][0]][0]];
add(l + 1, 1);
return l - p;
} else {
a[v[f[y][0]][r - b[f[y][0]][0]]] = 1;
mp[x] = v[f[y][0]][r - b[f[y][0]][0]];
add(r + 1, 1);
return r - p;
}
} else {
p = b[f[y][0]][0];
l = p;
r = l + f[y][1] - 1;
m = (l + r) / 2;
while (r - l > 1) {
if (sum(m + 1) - sum(p) < m - p + 1) {
r = m;
m = (l + r) / 2;
} else {
l = m;
m = (l + r) / 2;
}
}
if (a[v[f[y][0]][l - p]] == 0) {
a[v[f[y][0]][l - p]] = 1;
mp[x] = v[f[y][0]][l - p];
add(l + 1, 1);
return q - b[f[y][0]][0] - f[y][1] + l - p + 1;
} else {
a[v[f[y][0]][r - p]] = 1;
mp[x] = v[f[y][0]][r - p];
add(r + 1, 1);
return q - b[f[y][0]][0] - f[y][1] + r - p + 1;
}
}
}
int main() {
int h, m, n, p = 0, i, j;
long long ans = 0;
scanf("%d %d %d", &h, &m, &n);
for (i = 0; i < h; i++) f[i][0] = -1;
for (i = 0; i < h; i++) {
if (f[i][0] == -1) {
int c = 0;
vector<int> w;
b[v.size()][0] = p;
for (j = i;; j = (j + m) % h, c++, p++) {
if (f[j][0] >= 0) break;
f[j][0] = v.size();
f[j][1] = c;
w.push_back(j);
}
b[v.size()][1] = p - 1;
v.push_back(w);
}
}
for (i = 0; i < n; i++) {
int x, y;
char s[2];
scanf("%s %d", s, &x);
if (s[0] == '+') {
scanf("%d", &y);
ans += insert(x, y);
} else {
y = mp[x];
a[y] = 0;
mp.erase(x);
add(b[f[y][0]][0] + f[y][1] + 1, -1);
}
}
printf("%I64d\n", ans);
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
Once upon a time in a kingdom far, far awayβ¦ Okay, letβs start at the point where Ivan the Fool met Gorynych the Dragon. Ivan took out his magic sword and the battle began. First Gorynych had h heads and t tails. With each strike of the sword Ivan can either cut off several heads (from 1 to n, but not more than Gorynych has at the moment), or several tails (from 1 to m, but not more than Gorynych has at the moment). At the same time, horrible though it seems, Gorynych the Dragon can also grow new heads and tails. And the number of growing heads and tails is determined uniquely by the number of heads or tails cut by the current strike. When the total number of heads and tails exceeds R, Gorynych the Dragon strikes its final blow and destroys Ivan the Fool. Thatβs why Ivan aims to cut off all the dragonβs heads and tails as quickly as possible and win. The events can also develop in a third way: neither of the opponents can win over the other one and they will continue fighting forever.
The tale goes like this; easy to say, hard to do. Your task is to write a program that will determine the battleβs outcome. Consider that Ivan strikes consecutively. After each blow Gorynych grows a number of new heads and tails depending on the number of cut ones. Gorynych the Dragon is defeated if after the blow he loses all his heads and tails and canβt grow new ones. Ivan fights in the optimal way (fools are lucky), i.e.
* if Ivan can win, he wins having struck the least number of blows;
* if it is impossible to defeat Gorynych, but is possible to resist him for an infinitely long period of time, then thatβs the strategy Ivan chooses;
* if Gorynych wins in any case, Ivan aims to resist him for as long as possible.
Input
The first line contains three integers h, t and R (0 β€ h, t, R β€ 200, 0 < h + t β€ R) which represent the initial numbers of Gorynychβs heads and tails and the largest total number of heads and tails with which Gorynych the Dragon does not yet attack. The next line contains integer n (1 β€ n β€ 200). The next n contain pairs of non-negative numbers "hi ti" which represent the number of heads and the number of tails correspondingly, that will grow if Gorynych has i heads (1 β€ i β€ n) cut. The next line contains an integer m (1 β€ m β€ 200) and then β the description of Gorynychβs behavior when his tails are cut off in the format identical to the one described above. All the numbers in the input file do not exceed 200.
Output
Print "Ivan" (without quotes) in the first line if Ivan wins, or "Zmey" (that means a dragon in Russian) if Gorynych the Dragon wins. In the second line print a single integer which represents the number of blows Ivan makes. If the battle will continue forever, print in the first line "Draw".
Examples
Input
2 2 4
2
1 0
0 1
3
0 1
0 1
0 0
Output
Ivan
2
Input
2 2 4
1
0 1
1
1 0
Output
Draw
Input
2 2 5
1
1 1
1
3 0
Output
Zmey
2
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 200 + 7;
int sh, st, lim;
int n, m;
int addh[N][2], addt[N][2];
vector<pair<pair<int, int>, pair<int, int> > > ad, rad;
int dis[N][N];
bool ok(int x, int y) { return (x >= 0 && y >= 0 && x + y <= lim); }
void bfs() {
queue<pair<int, int> > q;
q.push({sh, st});
dis[sh][st] = 1;
while (q.size()) {
int x = q.front().first;
int y = q.front().second;
q.pop();
if (x == 0 && y == 0) {
cout << "Ivan" << endl << dis[0][0] - 1;
exit(0);
}
for (auto p : ad) {
int nx = x + p.first.first;
int ny = y + p.first.second;
int lx = p.second.first;
int ly = p.second.second;
if (x >= lx && y >= ly && ok(nx, ny) && !dis[nx][ny]) {
q.push({nx, ny});
dis[nx][ny] = dis[x][y] + 1;
}
}
}
}
bool mrk[N][N];
int in[N][N];
vector<pair<int, int> > com;
void dfs(int x, int y) {
mrk[x][y] = 1;
com.push_back({x, y});
for (auto p : ad) {
int nx = x + p.first.first;
int ny = y + p.first.second;
int lx = p.second.first;
int ly = p.second.second;
if (x < lx || y < ly || !ok(nx, ny)) continue;
if (!mrk[nx][ny]) {
dfs(nx, ny);
}
}
}
int go[N][N];
int dp[N][N];
int main() {
cin >> sh >> st >> lim;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> addh[i][0] >> addh[i][1];
ad.push_back({{addh[i][0] - i, addh[i][1]}, {i, 0}});
rad.push_back({{-addh[i][0] + i, -addh[i][1]}, {addh[i][0], 0}});
}
cin >> m;
for (int i = 1; i <= m; i++) {
cin >> addt[i][0] >> addt[i][1];
ad.push_back({{addt[i][0], addt[i][1] - i}, {0, i}});
rad.push_back({{-addt[i][0], i - addt[i][1]}, {0, addt[i][1]}});
}
bfs();
dfs(sh, st);
for (auto p : com) {
int x = p.first;
int y = p.second;
for (auto pp : ad) {
int nx = x + pp.first.first;
int ny = y + pp.first.second;
int lx = pp.second.first;
int ly = pp.second.second;
if (x >= lx && y >= ly && ok(nx, ny)) {
in[nx][ny]++;
go[x][y]++;
}
}
}
queue<pair<int, int> > q;
for (auto p : com) {
if (!in[p.first][p.second]) q.push({p.first, p.second});
}
int cnt = 0;
while (q.size()) {
int x = q.front().first;
int y = q.front().second;
cnt++;
q.pop();
for (auto p : ad) {
int nx = x + p.first.first;
int ny = y + p.first.second;
int lx = p.second.first;
int ly = p.second.second;
if (x >= lx && y >= ly && ok(nx, ny)) {
in[nx][ny]--;
if (!in[nx][ny]) q.push({nx, ny});
}
}
}
if (cnt < com.size()) {
cout << "Draw";
return 0;
}
for (auto p : com) {
if (!go[p.first][p.second]) {
q.push({p.first, p.second});
dp[p.first][p.second] = 1;
}
}
while (q.size()) {
int x = q.front().first;
int y = q.front().second;
q.pop();
for (auto p : rad) {
int nx = x + p.first.first;
int ny = y + p.first.second;
int lx = p.second.first;
int ly = p.second.second;
if (x >= lx && y >= ly && ok(nx, ny)) {
go[nx][ny]--;
dp[nx][ny] = max(dp[nx][ny], dp[x][y] + 1);
if (!go[nx][ny]) q.push({nx, ny});
}
}
}
cout << "Zmey" << endl;
cout << dp[sh][st];
return 0;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Snuke has N integers: 1,2,\ldots,N. He will choose K of them and give those to Takahashi.
How many ways are there to choose K consecutive integers?
Constraints
* All values in input are integers.
* 1 \leq K \leq N \leq 50
Input
Input is given from Standard Input in the following format:
N K
Output
Print the answer.
Examples
Input
3 2
Output
2
Input
13 3
Output
11
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int a,b;
cin>>a>>b;
cout<<a-b+1<<endl;
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l β€ x β€ r.
Segments can be placed arbitrarily β be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.
Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:
* if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100];
* if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6].
Obviously, a union is a set of pairwise non-intersecting segments.
You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.
For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then:
* erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union;
* erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union.
Thus, you are required to erase the third segment to get answer 2.
Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases in the test. Then the descriptions of t test cases follow.
The first of each test case contains a single integer n (2 β€ n β€ 2β
10^5) β the number of segments in the given set. Then n lines follow, each contains a description of a segment β a pair of integers l_i, r_i (-10^9 β€ l_i β€ r_i β€ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively.
The segments are given in an arbitrary order.
It is guaranteed that the sum of n over all test cases does not exceed 2β
10^5.
Output
Print t integers β the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Example
Input
3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
Output
2
1
5
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int INF = 1e9;
int main() {
int t;
cin >> t;
vector<int> ans(t);
vector<int> a;
for (int i = 0; i < (int)t; i++) {
int n;
cin >> n;
a.clear();
int l[n], r[n];
set<int> s;
for (int j = 0; j < (int)n; j++) {
cin >> l[j] >> r[j];
if (s.find(l[j]) == s.end()) a.push_back(l[j]);
s.insert(l[j]);
if (s.find(r[j]) == s.end()) a.push_back(r[j]);
s.insert(r[j]);
}
sort(a.begin(), a.end());
int v = s.size();
map<int, int> m;
for (int j = 0; j < (int)v; j++) m[a[j]] = j * 2 + 1;
vector<int> seg(2 * v + 1, 0);
vector<int> one(2 * v + 1, 0);
for (int j = 0; j < (int)n; j++) {
seg[m[l[j]]]++;
seg[m[r[j]] + 1]--;
}
for (int j = 1; j <= 2 * v; j++) seg[j] += seg[j - 1];
int p = 1;
for (int j = 1; j < 2 * v; j++) {
if (seg[j] == 0) p++;
}
for (int j = 1; j <= 2 * v; j++) {
one[j] += one[j - 1];
if (j % 2 == 0 && seg[j] == 1) one[j]++;
}
int b = -INF;
for (int j = 0; j < (int)n; j++) {
int dif = one[m[r[j]]] - one[m[l[j]]];
if (seg[m[r[j]] + 1] == 0 && seg[m[r[j]]] == 1 && seg[m[r[j]] - 1] == 1)
dif--;
if (seg[m[l[j]] - 1] == 0 && seg[m[l[j]]] == 1 && seg[m[l[j]] + 1] == 1)
dif--;
if (r[j] == l[j] && seg[m[r[j]]] == 1 && seg[m[r[j]] + 1] == 0 &&
seg[m[l[j]] - 1] == 0)
dif--;
b = max(b, dif);
}
ans[i] = p + b;
}
for (auto k : ans) cout << k << endl;
return 0;
}
``` |
### Prompt
Develop a solution in Cpp to the problem described below:
A sweet little monster Om Nom loves candies very much. One day he found himself in a rather tricky situation that required him to think a bit in order to enjoy candies the most. Would you succeed with the same task if you were on his place?
<image>
One day, when he came to his friend Evan, Om Nom didn't find him at home but he found two bags with candies. The first was full of blue candies and the second bag was full of red candies. Om Nom knows that each red candy weighs Wr grams and each blue candy weighs Wb grams. Eating a single red candy gives Om Nom Hr joy units and eating a single blue candy gives Om Nom Hb joy units.
Candies are the most important thing in the world, but on the other hand overeating is not good. Om Nom knows if he eats more than C grams of candies, he will get sick. Om Nom thinks that it isn't proper to leave candy leftovers, so he can only eat a whole candy. Om Nom is a great mathematician and he quickly determined how many candies of what type he should eat in order to get the maximum number of joy units. Can you repeat his achievement? You can assume that each bag contains more candies that Om Nom can eat.
Input
The single line contains five integers C, Hr, Hb, Wr, Wb (1 β€ C, Hr, Hb, Wr, Wb β€ 109).
Output
Print a single integer β the maximum number of joy units that Om Nom can get.
Examples
Input
10 3 5 2 3
Output
16
Note
In the sample test Om Nom can eat two candies of each type and thus get 16 joy units.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
map<long long int, long long int> dp;
int k = 0;
long long int func(long long int c, long long int a1, long long int a2,
long long int b1, long long int b2) {
long long int ans = 0, j;
for (int i = 0; b1 * i <= c && i < 100000; i++) {
j = (c - (b1 * i)) / b2;
ans = max(ans, a1 * i + a2 * j);
}
for (int i = 0; b2 * i <= c && i < 100000; i++) {
j = (c - (b2 * i)) / b1;
ans = max(ans, a2 * i + a1 * j);
}
return ans;
}
int main() {
long long int c, a1, a2, b1, b2;
cin >> c >> a1 >> a2 >> b1 >> b2;
cout << func(c, a1, a2, b1, b2);
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
Takahashi has a strong stomach. He never gets a stomachache from eating something whose "best-by" date is at most X days earlier. He gets a stomachache if the "best-by" date of the food is X+1 or more days earlier, though.
Other than that, he finds the food delicious if he eats it not later than the "best-by" date. Otherwise, he does not find it delicious.
Takahashi bought some food A days before the "best-by" date, and ate it B days after he bought it.
Write a program that outputs `delicious` if he found it delicious, `safe` if he did not found it delicious but did not get a stomachache either, and `dangerous` if he got a stomachache.
Constraints
* 1 β€ X,A,B β€ 10^9
Input
Input is given from Standard Input in the following format:
X A B
Output
Print `delicious` if Takahashi found the food delicious; print `safe` if he neither found it delicious nor got a stomachache; print `dangerous` if he got a stomachache.
Examples
Input
4 3 6
Output
safe
Input
6 5 1
Output
delicious
Input
3 7 12
Output
dangerous
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int a,b,x;cin>>x>>a>>b;
string s;
if(a>=b) s="delicious";
if(b>a && b<=x+a) s="safe";
if(b>x+a) s="dangerous";
cout<<s<<endl;
}
``` |
### Prompt
Your challenge is to write a CPP solution to the following problem:
We have a set S of N points in a two-dimensional plane. The coordinates of the i-th point are (x_i, y_i). The N points have distinct x-coordinates and distinct y-coordinates.
For a non-empty subset T of S, let f(T) be the number of points contained in the smallest rectangle, whose sides are parallel to the coordinate axes, that contains all the points in T. More formally, we define f(T) as follows:
* f(T) := (the number of integers i (1 \leq i \leq N) such that a \leq x_i \leq b and c \leq y_i \leq d, where a, b, c, and d are the minimum x-coordinate, the maximum x-coordinate, the minimum y-coordinate, and the maximum y-coordinate of the points in T)
Find the sum of f(T) over all non-empty subset T of S. Since it can be enormous, print the sum modulo 998244353.
Constraints
* 1 \leq N \leq 2 \times 10^5
* -10^9 \leq x_i, y_i \leq 10^9
* x_i \neq x_j (i \neq j)
* y_i \neq y_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
:
x_N y_N
Output
Print the sum of f(T) over all non-empty subset T of S, modulo 998244353.
Examples
Input
3
-1 3
2 1
3 -2
Output
13
Input
4
1 4
2 1
3 3
4 2
Output
34
Input
10
19 -11
-3 -12
5 3
3 -15
8 -14
-9 -20
10 -9
0 2
-7 17
6 -6
Output
7222
### Response
```cpp
// F - Enclosed Points
#include <bits/stdc++.h>
using namespace std;
#define MOD 998244353
long long mpow(long long x, long long n)
{
long long r = 1;
for ( ; n > 0; x = x * x % MOD, n >>= 1) if (n & 1) r = r * x % MOD;
return r;
}
void fen_update(vector<int> &tree, int i, int val)
{
for ( ; i > 0 && i < tree.size(); i += i & -i) tree[i] += val;
}
int fen_get(vector<int> &tree, int i)
{
int sum = 0;
for ( ; i > 0; i &= i - 1) sum += tree[i];
return sum;
}
int main(int argc, char *argv[])
{
ios::sync_with_stdio(false); cin.tie(0);
long long n;
cin >> n;
vector<int> b;
vector<pair<int, int> > a(n);
for (int i = 0; i < n; i++) cin >> a[i].first >> a[i].second, b.push_back(a[i].second);
sort(a.begin(), a.end());
sort(b.begin(), b.end());
map<int, int> m;
for (int i = 0; i < b.size(); i++) m[b[i]] = i;
vector<long long> tp(n + 1, 1);
for (int i = 1; i <= n; i++) tp[i] = tp[i - 1] * 2 % MOD;
long long ans = n * tp[n - 1] % MOD;
vector<int> l(n + 1), r(n + 1);
for (int i = 0; i < n; i++) fen_update(r, i + 1, 1);
for (int i = 0; i < n; i++) {
int y = m[a[i].second];
fen_update(r, y + 1, -1);
long long l1 = fen_get(l, y), l2 = i - l1;
long long r1 = fen_get(r, y), r2 = n - 1 - i - r1;
long long t1 = (tp[l1] - 1 + MOD) % MOD * (tp[r2] - 1 + MOD) % MOD * tp[l2 + r1] % MOD;
long long t2 = (tp[l2] - 1 + MOD) % MOD * (tp[r1] - 1 + MOD) % MOD * tp[l1 + r2] % MOD;
long long d = (tp[l1] - 1 + MOD) % MOD * (tp[r2] - 1 + MOD) % MOD * (tp[l2] - 1 + MOD) % MOD * (tp[r1] - 1 + MOD) % MOD;
ans = (ans + t1 + t2 -d + MOD) % MOD;
fen_update(l, y + 1, 1);
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Generate a cpp solution to the following problem:
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a Γ b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for n students must have the area of at least 6n square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all n students could live in it and the total area of the room was as small as possible.
Input
The first line contains three space-separated integers n, a and b (1 β€ n, a, b β€ 109) β the number of students and the sizes of the room.
Output
Print three integers s, a1 and b1 (a β€ a1; b β€ b1) β the final area of the room and its sizes. If there are multiple optimal solutions, print any of them.
Examples
Input
3 3 5
Output
18
3 6
Input
2 4 4
Output
16
4 4
### Response
```cpp
#include <bits/stdc++.h>
#pragma warning(disable : 4996)
using namespace std;
long long n, a, b;
long long mi = ((1ll << 62) - 1);
long long mi1, mi2;
int main() {
long long i, j, k;
scanf("%I64d%I64d%I64d", &n, &a, &b);
for (i = a; i <= a + 10000000; i++) {
long long b1 = max((6 * n + i - 1) / i, b);
if (b1 * i < mi) {
mi = b1 * i;
mi1 = i, mi2 = b1;
}
}
for (i = b; i <= b + 10000000; i++) {
long long a1 = max((6 * n + i - 1) / i, a);
if (a1 * i < mi) {
mi = a1 * i;
mi1 = a1, mi2 = i;
}
}
printf("%I64d\n%I64d %I64d", mi, mi1, mi2);
return 0;
}
``` |
### Prompt
Your challenge is to write a Cpp solution to the following problem:
Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved.
This is an interactive problem.
You are given a tree consisting of n nodes numbered with integers from 1 to n. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query:
* Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes.
Recall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them.
More formally, let's define two hidden nodes as s and f. In one query you can provide the set of nodes \\{a_1, a_2, β¦, a_c\} of the tree. As a result, you will get two numbers a_i and dist(a_i, s) + dist(a_i, f). The node a_i is any node from the provided set, for which the number dist(a_i, s) + dist(a_i, f) is minimal.
You can ask no more than 11 queries.
Input
The first line contains a single integer t (1 β€ t β€ 10) β the number of test cases. Please note, how the interaction process is organized.
The first line of each test case consists of a single integer n (2 β€ n β€ 1000) β the number of nodes in the tree.
The next n - 1 lines consist of two integers u, v (1 β€ u, v β€ n, u β v) β the edges of the tree.
Interaction
To ask a query print a single line:
* In the beginning print "? c " (without quotes) where c (1 β€ c β€ n) denotes the number of nodes being queried, followed by c distinct integers in the range [1, n] β the indices of nodes from the list.
For each query, you will receive two integers x, d β the node (among the queried nodes) with the minimum sum of distances to the hidden nodes and the sum of distances from that node to the hidden nodes. If the subset of nodes queried is invalid or you exceeded the number of queries then you will get x = d = -1. In this case, you should terminate the program immediately.
When you have guessed the hidden nodes, print a single line "! " (without quotes), followed by two integers in the range [1, n] β the hidden nodes. You can output the hidden nodes in any order.
After this, you should read a string. If you guess the nodes correctly, you will receive the string "Correct". In this case, you should continue solving the remaining test cases or terminate the program, if all test cases were solved. Otherwise, you will receive the string "Incorrect". In this case, you should terminate the program immediately.
Guessing the hidden nodes does not count towards the number of queries asked.
The interactor is not adaptive. The hidden nodes do not change with queries.
Do not forget to read the string "Correct" / "Incorrect" after guessing the hidden nodes.
You need to solve each test case before receiving the input for the next test case.
The limit of 11 queries applies to each test case and not to the entire input.
After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
To hack the solution, use the following test format:
The first line should contain a single integer t (1 β€ t β€ 10) β the number of test cases. The description of the test cases follows.
The first line of each test case should contain a single integer n (2 β€ n β€ 1000) β the number of nodes in the tree. The second line should contain two distinct integers in the range [1, n] β the hidden nodes. The next n - 1 lines should contain two integers u, v (1 β€ u, v β€ n, u β v) β the edges of the tree.
Example
Input
1
3
1 2
1 3
1 1
2 3
3 1
3 1
Correct
Output
? 1 1
? 1 2
? 1 3
? 2 2 3
! 1 3
Note
The tree from the first test is shown below, and the hidden nodes are 1 and 3.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2005;
const int maxm = 55;
const int inf = 2147483647;
const long long p = 1000000007;
const double eps = 1e-9;
const long long INF = 9223372036854775807ll;
int dep[maxn], maxdep;
vector<int> g[maxn];
vector<int> gdep[maxn];
pair<int, int> query(vector<int> &a) {
if (a.empty()) return make_pair(-1, -1);
printf("? %d", (int)a.size());
for (register int i = (0); i < (a.size()); ++i) printf(" %d", a[i]);
printf("\n");
fflush(stdout);
int ans1, ans2;
scanf("%d%d", &ans1, &ans2);
return make_pair(ans1, ans2);
}
void answer(int a, int b) {
printf("! %d %d\n", a, b);
fflush(stdout);
char c[15];
scanf("%s", c);
if (strcmp(c, "Incorrect") == 0) exit(0);
}
void dfs(int u, int f) {
dep[u] = dep[f] + 1;
maxdep = max(maxdep, dep[u]);
gdep[dep[u]].push_back(u);
for (register int i = (0); i < (g[u].size()); ++i) {
if (g[u][i] != f) dfs(g[u][i], u);
}
}
void dfs2(int u, int f, int deep, int len, vector<int> &a) {
if (deep == len) a.push_back(u);
for (register int i = (0); i < (g[u].size()); ++i) {
if (g[u][i] != f) dfs2(g[u][i], u, deep + 1, len, a);
}
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d", &n);
for (register int i = (0); i < (n - 1); ++i) {
int u, v;
scanf("%d%d", &u, &v);
g[u].push_back(v);
g[v].push_back(u);
}
vector<int> node;
for (register int i = (1); i < (n + 1); ++i) node.push_back(i);
maxdep = 0;
int rt, len;
pair<int, int> xx;
xx = query(node);
rt = xx.first, len = xx.second;
dep[0] = -1;
dfs(rt, 0);
int l = (len + 1) / 2, r = min(maxdep, len), s = 0;
while (l <= r) {
int mid = l + r >> 1;
int le, ts;
xx = query(gdep[mid]);
ts = xx.first, le = xx.second;
if (le != len) {
r = mid - 1;
} else
l = mid + 1, s = ts;
}
node.clear();
dfs2(s, 0, 0, len, node);
int tt;
if (node.size() == 1)
tt = node[0];
else
tt = query(node).first;
answer(tt, s);
for (register int i = (0); i < (n + 1); ++i) {
g[i].clear();
gdep[i].clear();
}
}
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same.
The boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him.
Input
The first line of the input contains four space-separated positive integer numbers not exceeding 100 β lengthes of the sticks.
Output
Output TRIANGLE if it is possible to construct a non-degenerate triangle. Output SEGMENT if the first case cannot take place and it is possible to construct a degenerate triangle. Output IMPOSSIBLE if it is impossible to construct any triangle. Remember that you are to use three sticks. It is not allowed to break the sticks or use their partial length.
Examples
Input
4 2 1 3
Output
TRIANGLE
Input
7 2 2 4
Output
SEGMENT
Input
3 5 9 1
Output
IMPOSSIBLE
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[4];
cin >> arr[0] >> arr[1] >> arr[2] >> arr[3];
sort(arr, arr + 4);
if (arr[2] + arr[1] > arr[3] || arr[0] + arr[1] > arr[2])
return cout << "TRIANGLE\n", 0;
else {
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
if (j != i)
for (int z = 0; z < 4; z++)
if (arr[i] + arr[j] == arr[z]) return cout << "SEGMENT\n", 0;
}
cout << "IMPOSSIBLE\n";
return 0;
}
``` |
### Prompt
Please formulate a CPP solution to the following problem:
You are given an array [a_1, a_2, ..., a_n] such that 1 β€ a_i β€ 10^9. Let S be the sum of all elements of the array a.
Let's call an array b of n integers beautiful if:
* 1 β€ b_i β€ 10^9 for each i from 1 to n;
* for every pair of adjacent integers from the array (b_i, b_{i + 1}), either b_i divides b_{i + 1}, or b_{i + 1} divides b_i (or both);
* 2 β _{i = 1}^{n} |a_i - b_i| β€ S.
Your task is to find any beautiful array. It can be shown that at least one beautiful array always exists.
Input
The first line contains one integer t (1 β€ t β€ 1000) β the number of test cases.
Each test case consists of two lines. The first line contains one integer n (2 β€ n β€ 50).
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9).
Output
For each test case, print the beautiful array b_1, b_2, ..., b_n (1 β€ b_i β€ 10^9) on a separate line. It can be shown that at least one beautiful array exists under these circumstances. If there are multiple answers, print any of them.
Example
Input
4
5
1 2 3 4 5
2
4 6
2
1 1000000000
6
3 4 8 1 2 3
Output
3 3 3 3 3
3 6
1 1000000000
4 4 8 1 3 3
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
void solve()
{
long long int n,s=0,sum=0,k;
cin>>n;
long long int arr[n+1];
for(int i=1;i<=n;i++)
{
cin>>arr[i];
if(i%2==1)
sum=sum+arr[i];
else
s=s+arr[i];}
if(sum>=s)
{
for(int i=1;i<=n;i++)
{
if(i%2==1)
cout<<arr[i]<<" ";
else
cout<<"1"<<" ";
}
}
else
{
for(int i=1;i<=n;i++)
{
if(i%2==0)
cout<<arr[i]<<" ";
else
cout<<"1"<<" ";
}
}
cout<<endl;
}
int main() {
int t=1;
cin >> t;
while(t--) {
solve();
}
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
The New Year tree is an infinite perfect binary tree rooted in the node 1. Each node v has two children: nodes indexed (2Β·v) and (2Β·v + 1).
<image>
Polar bears love decorating the New Year tree and Limak is no exception. As he is only a little bear, he was told to decorate only one simple path between some pair of nodes. Though he was given an opportunity to pick the pair himself! Now he wants to know the number of unordered pairs of indices (u, v) (u β€ v), such that the sum of indices of all nodes along the simple path between u and v (including endpoints) is equal to s. Can you help him and count this value?
Input
The only line of the input contains a single integer s (1 β€ s β€ 1015).
Output
Print one integer, denoting the number of unordered pairs of nodes indices defining simple paths with the sum of indices of vertices equal to s.
Example
Input
10
Output
4
Note
In sample test, there are 4 paths with the sum of indices equal to 10:
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 55;
const int maxx = 50;
long long dp[2][maxn * 2][2];
long long s;
inline long long pow2(long long x) { return (1ll << x); }
int main() {
cin >> s;
long long res = 0;
for (int h1 = 0; h1 <= 50; h1++) {
for (int h2 = 0; h2 <= 50; h2++) {
long long curt = (pow2(h1 + 1) - 2 + pow2(h2 + 1) - 2 + 1);
if (curt > s) continue;
if (curt > s - pow2(h2) + 1) continue;
if (h1 <= 1 && h2 <= 1) {
long long lca = (s - pow2(h2) + 1) / curt;
long long n = s - lca * curt - (pow2(h2) - 1);
if (n == 0) {
res++;
}
continue;
}
if (h2 == 0) {
long long lca = (s - pow2(h2) + 1) / curt;
if (lca <= 0) continue;
if (lca > s) continue;
for (int cnt = 0; cnt <= h1 - 1; cnt++) {
long long n = s - lca * curt - (pow2(h2) - 1) + cnt;
if (n < 0) continue;
if (n >= pow2(h1)) continue;
int c = 0;
if (n % 2 == 1) continue;
for (int i = 1; i <= h1 - 1; i++) {
if ((n >> i) & 1) c++;
}
if (cnt == c) {
res++;
}
}
continue;
}
if (h1 == 0) {
long long lca = (s - pow2(h2) + 1) / curt;
if (lca <= 0) continue;
if (lca > s) continue;
for (int cnt = 0; cnt <= h2 - 1; cnt++) {
long long n = s - lca * curt - (pow2(h2) - 1) + cnt;
if (n >= pow2(h2)) continue;
if (n < 0) continue;
int c = 0;
for (int i = 1; i <= h2 - 1; i++) {
if ((n >> i) & 1) c++;
}
if (n % 2 == 1) continue;
if (cnt == c) {
res++;
}
}
continue;
}
long long lca = (s - pow2(h2) + 1) / curt;
if (lca <= 0) continue;
if (lca > s) continue;
for (int cnt = 0; cnt <= h1 + h2 - 2; cnt++) {
long long n = s - lca * curt - (pow2(h2) - 1) + cnt;
if (n < 0) continue;
if (n % 2 == 1) continue;
if (n > pow2(h1) - 2 + pow2(h2) - 2) continue;
memset(dp, 0, sizeof(dp));
int top1 = 0, top2 = 0;
if (h1 >= 2) top1 = 1;
if (h2 >= 2) top2 = 1;
for (int a = 0; a <= top1; a++) {
for (int b = 0; b <= top2; b++) {
if ((a + b) % 2 == ((n >> 1) & 1)) {
dp[1][a + b][(a + b) / 2]++;
}
}
}
for (int d = 1; d <= max(h1, h2) - 1; d++) {
int ct = d % 2, ot = (d + 1) % 2;
memset(dp[ot], 0, sizeof(dp[ot]));
int sp = ((n >> (d + 1)) & 1);
top1 = top2 = 0;
if (h1 >= d + 2) top1 = 1;
if (h2 >= d + 2) top2 = 1;
for (int j = 0; j <= cnt && j <= (d + 1) * 2; j++) {
for (int c = 0; c <= 1; c++) {
if (dp[ct][j][c] == 0) continue;
for (int a = 0; a <= top1; a++) {
for (int b = 0; b <= top2; b++) {
if ((a + b + c) % 2 != sp) continue;
if (j + a + b > cnt) continue;
dp[ot][j + a + b][(c + a + b) / 2] += dp[ct][j][c];
}
}
}
}
}
res += dp[(max(h1, h2)) % 2][cnt][0];
}
}
}
cout << res << endl;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m).
In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points.
Searchlight j can see a robber i if a_i β€ c_j and b_i β€ d_j.
A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i).
What is the minimum number of moves you need to perform to reach a safe configuration?
Input
The first line of input contains two integers n and m (1 β€ n, m β€ 2000): the number of robbers and the number of searchlight.
Each of the next n lines contains two integers a_i, b_i (0 β€ a_i, b_i β€ 10^6), coordinates of robbers.
Each of the next m lines contains two integers c_i, d_i (0 β€ c_i, d_i β€ 10^6), coordinates of searchlights.
Output
Print one integer: the minimum number of moves you need to perform to reach a safe configuration.
Examples
Input
1 1
0 0
2 3
Output
3
Input
2 3
1 6
6 1
10 1
1 10
7 7
Output
4
Input
1 2
0 0
0 0
0 0
Output
1
Input
7 3
0 8
3 8
2 7
0 10
5 5
7 0
3 5
6 6
3 11
11 5
Output
6
Note
In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0).
The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2.
In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3).
It's easy the see that the configuration of the robbers is safe.
It can be proved that you can't reach a safe configuration using no more than 3 moves.
### Response
```cpp
#include <bits/stdc++.h>
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
const int maxN = 2010;
const int N = 1e6 + 10;
pair<int, int> a[maxN];
int dp[N];
struct node {
int x, add;
node(int x = -1e9, int add = -1e9) : x(x), add(add) {}
};
node t[4 * N];
struct segmentTree {
int getV(int v) { return max(t[v].add, t[v].x); }
void push(int v) {
t[2 * v + 1].add = max(t[2 * v + 1].add, t[v].add);
t[2 * v + 2].add = max(t[2 * v + 2].add, t[v].add);
t[v].add = -1e9;
}
void recalc(int v) { t[v].x = max(getV(2 * v + 1), getV(2 * v + 2)); }
void add(int L, int R, int x, int v = 0, int tl = 0, int tr = N) {
if (R <= tl || L >= tr || tr - tl < 1)
return;
else if (L <= tl && tr <= R)
t[v].add = max(t[v].add, x);
else {
push(v);
int mid = (tl + tr) / 2;
add(L, R, x, 2 * v + 1, tl, mid);
add(L, R, x, 2 * v + 2, mid, tr);
recalc(v);
}
}
int get(int ind, int v = 0, int tl = 0, int tr = N) {
if (tr - tl == 1)
return getV(v);
else {
push(v);
int mid = (tl + tr) / 2;
int ans = 0;
if (ind >= mid)
ans = get(ind, 2 * v + 2, mid, tr);
else
ans = get(ind, 2 * v + 1, tl, mid);
recalc(v);
return ans;
}
}
} tree;
int n, m;
int getCnt(int mid) {
int ans = 0;
for (int i = 0; i < n; ++i) {
int ny = a[i].second + mid;
int pans = -1e9;
if (ny < N) pans = dp[ny];
ans = max(ans, pans - a[i].first + 1);
}
return mid + ans;
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for (int i = 0; i < n; ++i) cin >> a[i].first >> a[i].second;
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
tree.add(0, b + 1, a);
}
for (int i = 0; i < N; ++i) dp[i] = tree.get(i);
int ans = 1e9;
for (int i = 0; i < 1e5; ++i) ans = min(ans, getCnt(i));
for (int i = 1e6; i >= 1e6 - 1e5; --i) ans = min(ans, getCnt(i));
cout << ans << "\n";
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β₯ a_{i-1} holds) and an integer k.
You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray.
Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to β_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13.
Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 3 β
10^5).
The second line contains n integers a_1, a_2, ..., a_n ( 1 β€ a_i β€ 10^9, a_i β₯ a_{i-1}).
Output
Print the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays.
Examples
Input
6 3
4 8 15 16 23 42
Output
12
Input
4 4
1 3 3 7
Output
0
Input
8 1
1 1 2 3 5 8 13 21
Output
20
Note
In the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42].
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool marked[3 * 100000 + 10] = {0};
vector<long long int> a(3 * 100000 + 10);
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long int n, k, ans;
cin >> n >> k;
vector<long long int> pref(n - 1);
for (long long int i = 0; i < n; ++i) {
cin >> a[i];
if (i > 0) {
pref[i] = pref[i - 1] + a[i];
} else if (i < n - 1) {
pref[i] = a[i];
}
}
ans = k * (pref[n - 2] + a[n - 1]);
sort((pref).begin(), (pref).end());
for (long long int i = 0; i < k - 1; ++i) {
ans -= pref[i];
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
There are n problems prepared for the next Codeforces round. They are arranged in ascending order by their difficulty, and no two problems have the same difficulty. Moreover, there are m pairs of similar problems. Authors want to split problems between two division according to the following rules:
* Problemset of each division should be non-empty.
* Each problem should be used in exactly one division (yes, it is unusual requirement).
* Each problem used in division 1 should be harder than any problem used in division 2.
* If two problems are similar, they should be used in different divisions.
Your goal is count the number of ways to split problem between two divisions and satisfy all the rules. Two ways to split problems are considered to be different if there is at least one problem that belongs to division 1 in one of them and to division 2 in the other.
Note, that the relation of similarity is not transitive. That is, if problem i is similar to problem j and problem j is similar to problem k, it doesn't follow that i is similar to k.
Input
The first line of the input contains two integers n and m (2 β€ n β€ 100 000, 0 β€ m β€ 100 000) β the number of problems prepared for the round and the number of pairs of similar problems, respectively.
Each of the following m lines contains a pair of similar problems ui and vi (1 β€ ui, vi β€ n, ui β vi). It's guaranteed, that no pair of problems meets twice in the input.
Output
Print one integer β the number of ways to split problems in two divisions.
Examples
Input
5 2
1 4
5 2
Output
2
Input
3 3
1 2
2 3
1 3
Output
0
Input
3 2
3 1
3 2
Output
1
Note
In the first sample, problems 1 and 2 should be used in division 2, while problems 4 and 5 in division 1. Problem 3 may be used either in division 1 or in division 2.
In the second sample, all pairs of problems are similar and there is no way to split problem between two divisions without breaking any rules.
Third sample reminds you that the similarity relation is not transitive. Problem 3 is similar to both 1 and 2, but 1 is not similar to 2, so they may be used together.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
while (scanf("%d%d", &n, &m) != EOF) {
int l = 1, r = n;
for (int i = 0; i < m; i++) {
int a, b;
scanf("%d%d", &a, &b);
if (a > b) swap(a, b);
l = max(l, a);
r = min(r, b);
}
if (r - l < 0)
printf("0\n");
else
printf("%d\n", r - l);
}
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
All our characters have hobbies. The same is true for Fedor. He enjoys shopping in the neighboring supermarket.
The goods in the supermarket have unique integer ids. Also, for every integer there is a product with id equal to this integer. Fedor has n discount coupons, the i-th of them can be used with products with ids ranging from li to ri, inclusive. Today Fedor wants to take exactly k coupons with him.
Fedor wants to choose the k coupons in such a way that the number of such products x that all coupons can be used with this product x is as large as possible (for better understanding, see examples). Fedor wants to save his time as well, so he asks you to choose coupons for him. Help Fedor!
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 3Β·105) β the number of coupons Fedor has, and the number of coupons he wants to choose.
Each of the next n lines contains two integers li and ri ( - 109 β€ li β€ ri β€ 109) β the description of the i-th coupon. The coupons can be equal.
Output
In the first line print single integer β the maximum number of products with which all the chosen coupons can be used. The products with which at least one coupon cannot be used shouldn't be counted.
In the second line print k distinct integers p1, p2, ..., pk (1 β€ pi β€ n) β the ids of the coupons which Fedor should choose.
If there are multiple answers, print any of them.
Examples
Input
4 2
1 100
40 70
120 130
125 180
Output
31
1 2
Input
3 2
1 12
15 20
25 30
Output
0
1 2
Input
5 2
1 10
5 15
14 50
30 70
99 100
Output
21
3 4
Note
In the first example if we take the first two coupons then all the products with ids in range [40, 70] can be bought with both coupons. There are 31 products in total.
In the second example, no product can be bought with two coupons, that is why the answer is 0. Fedor can choose any two coupons in this example.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline bool scan_d(int &num) {
char in;
bool IsN = false;
in = getchar();
if (in == EOF) return false;
while (in != '-' && (in < '0' || in > '9')) in = getchar();
if (in == '-') {
IsN = true;
num = 0;
} else
num = in - '0';
while (in = getchar(), in >= '0' && in <= '9') {
num *= 10, num += in - '0';
}
if (IsN) num = -num;
return true;
}
void Out(int a) {
if (a < 0) {
putchar('-');
a = -a;
}
if (a >= 10) {
Out(a / 10);
}
putchar(a % 10 + '0');
}
struct note {
int r;
int l;
int id;
} x[3000005];
int cmp(note a, note b) { return a.l < b.l; }
int main() {
int n, k;
int flag = 0;
int tail, end;
scan_d(n);
scan_d(k);
for (int i = 1; i <= n; i++) {
scan_d(x[i].l);
scan_d(x[i].r);
x[i].id = i;
}
sort(x + 1, x + n + 1, cmp);
priority_queue<int, vector<int>, greater<int> > que;
int len = 0;
int len1, num = 0;
for (int i = 1; i <= n; i++) {
que.push(x[i].r);
if (que.size() > k) {
que.pop();
}
len1 = que.top() - x[i].l + 1;
if (que.size() == k && len < len1) {
len = len1;
num = x[i].l;
}
}
Out(len);
puts("");
if (len == 0) {
Out(1);
for (int i = 2; i <= k; ++i) printf(" %d", i);
} else {
for (int i = 1; i <= n && k; ++i) {
if (num >= x[i].l && len + num - 1 <= x[i].r) {
if (k >= 1)
printf("%d ", x[i].id);
else
printf("%d", x[i].id);
k--;
}
}
}
puts("");
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
Input
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.
Output
Output a single string β alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.
Examples
Input
harry potter
Output
hap
Input
tom riddle
Output
tomr
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string first, second;
cin >> first >> second;
cout << first[0];
for (int i = 1; i < first.size(); i++) {
if (first[i] < second[0])
cout << first[i];
else
break;
}
cout << second[0];
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
The only difference between easy and hard versions is the length of the string.
You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s).
For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".
You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s.
If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 ... s_{l-1} s_{r+1} s_{r+2} ... s_{|s|-1} s_{|s|} (where |s| is the length of s).
Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s.
Input
The first line of the input contains one string s consisting of at least 1 and at most 200 lowercase Latin letters.
The second line of the input contains one string t consisting of at least 1 and at most 200 lowercase Latin letters.
It is guaranteed that t is a subsequence of s.
Output
Print one integer β the maximum possible length of the substring you can remove so that t is still a subsequence of s.
Examples
Input
bbaba
bb
Output
3
Input
baaba
ab
Output
2
Input
abcde
abcde
Output
0
Input
asdfasdf
fasd
Output
3
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string s, t;
cin >> s >> t;
long long int j = 0;
vector<long long int> a, b;
for (long long int i = 0; i < s.size(), j < t.size(); i++) {
if (t[j] == s[i]) {
a.push_back(i);
j++;
}
}
j = t.size() - 1;
for (long long int i = s.size() - 1; i >= 0, j >= 0; i--) {
if (t[j] == s[i]) {
b.push_back(i);
j--;
}
}
long long int ans = 0;
for (long long int i = 0; i < t.size() - 1; i++) {
ans = max(ans, b[t.size() - i - 2] - a[i] - 1);
}
long long int k = b[t.size() - 1];
ans = max(ans, k);
k = s.size() - 1 - a[t.size() - 1];
ans = max(ans, k);
cout << ans;
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
E869120's and square1001's 16-th birthday is coming soon.
Takahashi from AtCoder Kingdom gave them a round cake cut into 16 equal fan-shaped pieces.
E869120 and square1001 were just about to eat A and B of those pieces, respectively,
when they found a note attached to the cake saying that "the same person should not take two adjacent pieces of cake".
Can both of them obey the instruction in the note and take desired numbers of pieces of cake?
Constraints
* A and B are integers between 1 and 16 (inclusive).
* A+B is at most 16.
Input
Input is given from Standard Input in the following format:
A B
Output
If both E869120 and square1001 can obey the instruction in the note and take desired numbers of pieces of cake, print `Yay!`; otherwise, print `:(`.
Examples
Input
5 4
Output
Yay!
Input
8 8
Output
Yay!
Input
11 4
Output
:(
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int A,B;
cin>>A>>B;
if(A<=8 && B<=8)
puts("Yay!");
else
puts(":(");
}
``` |
### Prompt
In cpp, your task is to solve the following problem:
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
Input
The first input line contains 3 space-separated integer numbers n, m, v (3 β€ n β€ 105, 0 β€ m β€ 105, 1 β€ v β€ n), n β amount of servers, m β amount of direct connections, v β index of the server that fails and leads to the failure of the whole system.
Output
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β description of all the direct connections in the system. Each direct connection is described by two numbers β indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
Examples
Input
5 6 3
Output
1 2
2 3
3 4
4 5
1 3
3 5
Input
6 100 1
Output
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > ans;
vector<int> v1, v2;
int n, m, v;
void addE(int a, int b) {
ans.push_back({a, b});
--m;
}
void solve() {
scanf("%d %d %d", &n, &m, &v);
if (m < n - 1) {
printf("-1");
return;
}
int p = n - 2;
for (int i = 1; i <= n; ++i) {
if (i == v) {
continue;
}
if (p > 0) {
v1.push_back(i);
} else {
v2.push_back(i);
}
--p;
}
v1.push_back(v);
v2.push_back(v);
for (int i = 0; i + 1 < v1.size(); ++i) {
addE(v1[i], v1[i + 1]);
}
for (int i = 0; i + 1 < v2.size(); ++i) {
addE(v2[i], v2[i + 1]);
}
for (int i = 0; i < v1.size() && m > 0; ++i) {
for (int j = i + 2; j < v1.size() && m > 0; ++j) {
addE(v1[i], v1[j]);
}
}
if (m > 0) {
printf("-1");
return;
}
for (auto it : ans) {
int a, b;
tie(a, b) = it;
printf("%d %d\n", a, b);
}
}
int main() {
int tt = 1;
while (tt--) {
solve();
}
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Recall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
A sequence a is a subsegment of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l, r], where l, r are two integers with 1 β€ l β€ r β€ n. This indicates the subsegment where l-1 elements from the beginning and n-r elements from the end are deleted from the sequence.
For a permutation p_1, p_2, β¦, p_n, we define a framed segment as a subsegment [l,r] where max\\{p_l, p_{l+1}, ..., p_r\} - min\\{p_l, p_{l+1}, ..., p_r\} = r - l. For example, for the permutation (6, 7, 1, 8, 5, 3, 2, 4) some of its framed segments are: [1, 2], [5, 8], [6, 7], [3, 3], [8, 8]. In particular, a subsegment [i,i] is always a framed segments for any i between 1 and n, inclusive.
We define the happiness of a permutation p as the number of pairs (l, r) such that 1 β€ l β€ r β€ n, and [l, r] is a framed segment. For example, the permutation [3, 1, 2] has happiness 5: all segments except [1, 2] are framed segments.
Given integers n and m, Jongwon wants to compute the sum of happiness for all permutations of length n, modulo the prime number m. Note that there exist n! (factorial of n) different permutations of length n.
Input
The only line contains two integers n and m (1 β€ n β€ 250 000, 10^8 β€ m β€ 10^9, m is prime).
Output
Print r (0 β€ r < m), the sum of happiness for all permutations of length n, modulo a prime number m.
Examples
Input
1 993244853
Output
1
Input
2 993244853
Output
6
Input
3 993244853
Output
32
Input
2019 993244853
Output
923958830
Input
2020 437122297
Output
265955509
Note
For sample input n=3, let's consider all permutations of length 3:
* [1, 2, 3], all subsegments are framed segment. Happiness is 6.
* [1, 3, 2], all subsegments except [1, 2] are framed segment. Happiness is 5.
* [2, 1, 3], all subsegments except [2, 3] are framed segment. Happiness is 5.
* [2, 3, 1], all subsegments except [2, 3] are framed segment. Happiness is 5.
* [3, 1, 2], all subsegments except [1, 2] are framed segment. Happiness is 5.
* [3, 2, 1], all subsegments are framed segment. Happiness is 6.
Thus, the sum of happiness is 6+5+5+5+5+6 = 32.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long power(long long num, long long g) {
if (g == 0) return 1;
if (g % 2 == 1) return (num * power((num * num), g / 2));
return power((num * num), g / 2);
}
long long mod;
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long n;
cin >> n >> mod;
long long fact[n + 1];
fact[0] = 1;
for (long long i = 1; i <= n; i++) {
fact[i] = fact[i - 1] * i;
fact[i] %= mod;
}
long long ans = 0;
for (long long i = 1; i <= n; i++) {
long long g = n + 1LL - i;
g *= g;
g %= mod;
g *= fact[i];
g %= mod;
g *= fact[n - i];
g %= mod;
ans += g;
ans %= mod;
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
In this problem you have to solve a simple classification task: given an image, determine whether it depicts a Fourier doodle.
You are given a set of 50 images with ids 1 through 50. You are also given a text file labels.txt containing the labels for images with ids 1 through 20, which comprise the learning data set.
You have to output the classification results for images with ids 21 through 50 in the same format.
Input
[Download the images and the training labels](http://tc-alchemy.progopedia.com/fourier-doodles.zip)
Each line of the file labels.txt contains a single integer 0 or 1. Line i (1-based) contains the label of the image {i}.png. Label 1 means that the image depicts a Fourier doodle, label 0 - that it does not.
Output
Output 30 lines, one line per image 21 through 50. Line i (1-based) should contain the classification result for the image {i + 20}.png.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
for (int i = 21; i <= 50; ++i)
cout << ((min(i, 25) + i) % (2 + i % 3) > 0) << '\n';
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
A famous gang of pirates, Sea Dogs, has come back to their hideout from one of their extravagant plunders. They want to split their treasure fairly amongst themselves, that is why You, their trusted financial advisor, devised a game to help them:
All of them take a sit at their round table, some of them with the golden coins they have just stolen. At each iteration of the game if one of them has equal or more than 2 coins, he is eligible to the splitting and he gives one coin to each pirate sitting next to him. If there are more candidates (pirates with equal or more than 2 coins) then You are the one that chooses which one of them will do the splitting in that iteration. The game ends when there are no more candidates eligible to do the splitting.
Pirates can call it a day, only when the game ends. Since they are beings with a finite amount of time at their disposal, they would prefer if the game that they are playing can end after finite iterations, and if so, they call it a good game. On the other hand, if no matter how You do the splitting, the game cannot end in finite iterations, they call it a bad game. Can You help them figure out before they start playing if the game will be good or bad?
Input
The first line of input contains two integer numbers n and k (1 β€ n β€ 10^{9}, 0 β€ k β€ 2β
10^5), where n denotes total number of pirates and k is the number of pirates that have any coins.
The next k lines of input contain integers a_i and b_i (1 β€ a_i β€ n, 1 β€ b_i β€ 10^{9}), where a_i denotes the index of the pirate sitting at the round table (n and 1 are neighbours) and b_i the total number of coins that pirate a_i has at the start of the game.
Output
Print 1 if the game is a good game: There is a way to do the splitting so the game ends after finite number of iterations.
Print -1 if the game is a bad game: No matter how You do the splitting the game does not end in finite number of iterations.
Examples
Input
4 2
1 2
2 2
Output
1
Input
6 2
2 3
4 1
Output
1
Input
3 2
1 1
2 2
Output
-1
Note
In the third example the game has no end, because You always only have only one candidate, after whose splitting you end up in the same position as the starting one.
### Response
```cpp
#include <bits/stdc++.h>
using ll = long long;
using ld = long double;
std::mt19937 rnd(
std::chrono::high_resolution_clock::now().time_since_epoch().count());
const double PI = atan2(0.0, -1.0);
const int INF = 0x3f3f3f3f;
const ll LINF = (ll)2e18;
void run() {
int n, k;
scanf("%d%d", &n, &k);
ll sum1 = 0, sum2 = 0;
ll sum = 0;
sum1 = 1ll * n * (n - 1) / 2;
while (k--) {
int pos, val;
scanf("%d%d", &pos, &val);
sum += val;
sum2 += 1ll * (pos - 1) * val;
}
if (sum > n) {
printf("-1\n");
} else if (sum < n) {
printf("1\n");
} else {
if (sum1 % n != sum2 % n) {
printf("-1\n");
} else {
printf("1\n");
}
}
}
int main(void) {
auto start = std::chrono::high_resolution_clock::now();
run();
auto end = std::chrono::high_resolution_clock::now();
return 0;
}
``` |
### Prompt
Please create a solution in CPP to the following problem:
We have N+M balls, each of which has an integer written on it.
It is known that:
* The numbers written on N of the balls are even.
* The numbers written on M of the balls are odd.
Find the number of ways to choose two of the N+M balls (disregarding order) so that the sum of the numbers written on them is even.
It can be shown that this count does not depend on the actual values written on the balls.
Constraints
* 0 \leq N,M \leq 100
* 2 \leq N+M
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
Output
Print the answer.
Examples
Input
2 1
Output
1
Input
4 3
Output
9
Input
1 1
Output
0
Input
13 3
Output
81
Input
0 3
Output
3
### Response
```cpp
#include<stdio.h>
int main(){
int a,b;
scanf("%d%d",&a,&b);
int s=a*(a-1)/2+b*(b-1)/2;
printf("%d",s);
}
``` |
### Prompt
Construct a CPP code solution to the problem outlined:
AtCoDeer the deer has found two positive integers, a and b. Determine whether the concatenation of a and b in this order is a square number.
Constraints
* 1 β€ a,b β€ 100
* a and b are integers.
Input
Input is given from Standard Input in the following format:
a b
Output
If the concatenation of a and b in this order is a square number, print `Yes`; otherwise, print `No`.
Examples
Input
1 21
Output
Yes
Input
100 100
Output
No
Input
12 10
Output
No
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
string a,b,c;
int n;
int main()
{
cin>>a>>b;
c+=a;
c+=b;
n=atol(c.c_str());
for (int i=1;i<=sqrt(n);i++)
if (i*i==n)
{
cout<<"Yes";
return 0;
}
cout<<"No";
return 0;
}
``` |
### Prompt
Generate a Cpp solution to the following problem:
The Little Elephant very much loves sums on intervals.
This time he has a pair of integers l and r (l β€ r). The Little Elephant has to find the number of such integers x (l β€ x β€ r), that the first digit of integer x equals the last one (in decimal notation). For example, such numbers as 101, 477474 or 9 will be included in the answer and 47, 253 or 1020 will not.
Help him and count the number of described numbers x for a given pair l and r.
Input
The single line contains a pair of integers l and r (1 β€ l β€ r β€ 1018) β the boundaries of the interval.
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
On a single line print a single integer β the answer to the problem.
Examples
Input
2 47
Output
12
Input
47 1024
Output
98
Note
In the first sample the answer includes integers 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long p(long long l) {
if (l < 10) return l;
long long f, t, ret;
t = l % 10;
f = l;
while (f >= 10) f /= 10;
ret = l / 10 + 9;
if (t < f) ret--;
return ret;
}
int main() {
long long l, r;
cin >> l >> r;
cout << p(r) - p(l - 1) << endl;
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 β€ a β€ b β€ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set:
<image>
Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph.
When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots.
How many dominoes at most can Anadi place on the edges of his graph?
Input
The first line contains two integers n and m (1 β€ n β€ 7, 0 β€ m β€ (nβ
(n-1))/(2)) β the number of vertices and the number of edges in the graph.
The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 β€ a, b β€ n, a β b) and denote that there is an edge which connects vertices a_i and b_i.
The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices.
Output
Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph.
Examples
Input
4 4
1 2
2 3
3 4
4 1
Output
4
Input
7 0
Output
0
Input
3 1
1 3
Output
1
Input
7 21
1 2
1 3
1 4
1 5
1 6
1 7
2 3
2 4
2 5
2 6
2 7
3 4
3 5
3 6
3 7
4 5
4 6
4 7
5 6
5 7
6 7
Output
16
Note
Here is an illustration of Anadi's graph from the first sample test:
<image>
And here is one of the ways to place a domino on each of its edges:
<image>
Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
pair<int, int> G[21];
int n, m, a, b;
int v[7];
int cal() {
set<pair<int, int> > s;
for (int i = 0; i < m; i++) {
a = v[G[i].first];
b = v[G[i].second];
if (a > b) {
swap(a, b);
}
s.insert(pair<int, int>(a, b));
}
return s.size();
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m;
for (int i = 0; i < m; i++) {
cin >> a >> b;
a--;
b--;
if (a > b) swap(a, b);
G[i] = pair<int, int>(a, b);
}
int ans = 0;
if (n == 7) {
for (int i = 1; i < 7; i++) {
for (int j = 0; j < 7; j++) {
if (j >= i) {
v[j] = j - 1;
} else {
v[j] = j;
}
}
do {
ans = max(ans, cal());
} while (next_permutation(v, v + n));
}
} else {
for (int i = 0; i < n; i++) {
v[i] = i;
}
do {
ans = max(ans, cal());
} while (next_permutation(v, v + n));
}
cout << ans << '\n';
return 0;
}
``` |
### Prompt
Please provide a cpp coded solution to the problem described below:
The competitors of Bubble Cup X gathered after the competition and discussed what is the best way to get to know the host country and its cities.
After exploring the map of Serbia for a while, the competitors came up with the following facts: the country has V cities which are indexed with numbers from 1 to V, and there are E bi-directional roads that connect the cites. Each road has a weight (the time needed to cross that road). There are N teams at the Bubble Cup and the competitors came up with the following plan: each of the N teams will start their journey in one of the V cities, and some of the teams share the starting position.
They want to find the shortest time T, such that every team can move in these T minutes, and the number of different cities they end up in is at least K (because they will only get to know the cities they end up in). A team doesn't have to be on the move all the time, if they like it in a particular city, they can stay there and wait for the time to pass.
Please help the competitors to determine the shortest time T so it's possible for them to end up in at least K different cities or print -1 if that is impossible no matter how they move.
Note that there can exist multiple roads between some cities.
Input
The first line contains four integers: V, E, N and K (1 β€ V β€ 600, 1 β€ E β€ 20000, 1 β€ N β€ min(V, 200), 1 β€ K β€ N), number of cities, number of roads, number of teams and the smallest number of different cities they need to end up in, respectively.
The second line contains N integers, the cities where the teams start their journey.
Next E lines contain information about the roads in following format: Ai Bi Ti (1 β€ Ai, Bi β€ V, 1 β€ Ti β€ 10000), which means that there is a road connecting cities Ai and Bi, and you need Ti minutes to cross that road.
Output
Output a single integer that represents the minimal time the teams can move for, such that they end up in at least K different cities or output -1 if there is no solution.
If the solution exists, result will be no greater than 1731311.
Example
Input
6 7 5 4
5 5 2 2 5
1 3 3
1 5 2
1 6 5
2 5 4
2 6 7
3 4 11
3 5 3
Output
3
Note
Three teams start from city 5, and two teams start from city 2. If they agree to move for 3 minutes, one possible situation would be the following: Two teams in city 2, one team in city 5, one team in city 3 , and one team in city 1. And we see that there are four different cities the teams end their journey at.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m, s, k, x, y, z, S, T, sl, fh, st[1010], cur[1010], dep[1010],
f[610][610];
int t, head[1010], to[1000010], nxt[1000010], val[1000010];
queue<int> q;
int rd() {
sl = 0;
fh = 1;
char ch = getchar();
while (ch < '0' || '9' < ch) {
if (ch == '-') fh = -1;
ch = getchar();
}
while ('0' <= ch && ch <= '9') sl = sl * 10 + ch - '0', ch = getchar();
return sl * fh;
}
void add(int u, int v, int w) {
to[t] = v;
val[t] = w;
nxt[t] = head[u];
head[u] = t++;
}
bool bfs() {
while (!q.empty()) q.pop();
memset(dep, 0, sizeof(dep));
q.push(S);
dep[S] = 1;
int u, v;
while (!q.empty()) {
u = q.front();
q.pop();
for (int i = head[u]; i != -1; i = nxt[i])
if (!dep[v = to[i]] && val[i] > 0) {
dep[v] = dep[u] + 1;
if (v == T) return 1;
q.push(v);
}
}
return 0;
}
int dfs(int u, int f) {
if (f <= 0) return 0;
if (u == T) return f;
int v, q = 0, tmp;
for (int &i = cur[u]; i != -1; i = nxt[i])
if (dep[v = to[i]] == dep[u] + 1) {
tmp = dfs(v, min(f, val[i]));
if (!tmp) continue;
f -= tmp;
q += tmp;
val[i] -= tmp;
val[i ^ 1] += tmp;
if (!f) return q;
}
return q;
}
bool check(int len) {
memset(head, -1, sizeof(head));
t = 0;
for (int i = 1; i <= s; ++i) add(S, i, 1), add(i, S, 0);
for (int i = 1; i <= n; ++i) add(s + i, T, 1), add(T, s + i, 0);
for (int i = 1; i <= s; ++i)
for (int j = 1; j <= n; ++j)
if (f[st[i]][j] <= len) add(i, j + s, 1), add(j + s, i, 0);
int sum, ans = 0;
while (bfs()) {
for (int i = 0; i <= s + n + 1; ++i) cur[i] = head[i];
while (sum = dfs(S, 0x7fffffff)) ans += sum;
}
return ans >= k;
}
int main() {
n = rd();
m = rd();
s = rd();
k = rd();
memset(f, 127 / 3, sizeof(f));
for (int i = 1; i <= s; ++i) st[i] = rd();
for (int i = 1; i <= m; ++i) {
x = rd();
y = rd();
z = rd();
f[x][y] = f[y][x] = min(f[x][y], z);
}
for (int i = 1; i <= n; ++i) f[i][i] = 0;
for (int k = 1; k <= n; ++k)
for (int i = 1; i <= n; ++i)
if (i != k)
for (int j = 1; j <= n; ++j)
if (i != j && j != k) f[i][j] = min(f[i][j], f[i][k] + f[k][j]);
int mid, ans = -1, l = 0, r = 1731311;
S = 0, T = s + n + 1;
while (l <= r) {
mid = (l + r) >> 1;
if (check(mid))
r = mid - 1, ans = mid;
else
l = mid + 1;
}
printf("%d\n", ans);
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
Write a program which computes the greatest common divisor (GCD) and the least common multiple (LCM) of given a and b.
Constraints
* 0 < a, b β€ 2,000,000,000
* LCM(a, b) β€ 2,000,000,000
* The number of data sets β€ 50
Input
Input consists of several data sets. Each data set contains a and b separated by a single space in a line. The input terminates with EOF.
Output
For each data set, print GCD and LCM separated by a single space in a line.
Example
Input
8 6
50000000 30000000
Output
2 24
10000000 150000000
### Response
```cpp
#include "bits/stdc++.h"
using namespace std;
long long GCD(long long X, long long Y) {
if (Y == 0) return X;
return GCD(Y, X % Y);
}
int main() {
long long A, B;
while (cin >> A >> B) {
cout << GCD(A, B) << " " << A * (B / GCD(A, B)) << endl;
}
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
Snuke has a string x of length N. Initially, every character in x is `0`.
Snuke can do the following two operations any number of times in any order:
* Choose A consecutive characters in x and replace each of them with `0`.
* Choose B consecutive characters in x and replace each of them with `1`.
Find the number of different strings that x can be after Snuke finishes doing operations. This count can be enormous, so compute it modulo (10^9+7).
Constraints
* 1 \leq N \leq 5000
* 1 \leq A,B \leq N
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
Print the number of different strings that x can be after Snuke finishes doing operations, modulo (10^9+7).
Examples
Input
4 2 3
Output
11
Input
10 7 2
Output
533
Input
1000 100 10
Output
828178524
### Response
```cpp
#include <iostream>
#include<set>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
const int mod=1000000007;
int add(int a, int b)
{
int c=a+b;
if(c>=mod)c-=mod;
return c;
}
int dif(int a, int b)
{
int c=a-b;
if(c<0)c+=mod;
return c;
}
int mlt(int a, int b)
{
long long c=a*1LL*b;
return c%mod;
}
int bp(int a, int b)
{
if(b==0)return 1;
if(b%2==0)
{
int val=bp(a, b/2);
return mlt(val, val);
}
if(b%2==1)
{
int val=bp(a, b-1);
return mlt(val, a);
}
}
int inv(int a)
{
return bp(a, mod-2);
}
void outp(vector<vector<int>>&v)
{
for(int i=0; i<v.size(); i++)
{
for(int j=0; j<v[i].size(); j++)cout<<v[i][j]<<' ';
cout<<endl;
}
cout<<endl;
}
int main()
{
int n, a, b;
cin >> n >> a >> b;
if (a > b)
{
int c = a;
a = b;
b = c;
}
vector<vector<int>> dpa(n + 1, vector<int>(n + 1)),
dpb(n + 1, vector<int>(n + 1));
dpb[0][0]=1;
for(int i=1; i<=n; i++)
{
for(int j=max(0, i-b+1); j<i; j++)
{
if(i>=j+a)
{
if (i >= a)
{
dpa[i][j] = add(dpa[i - 1][j], dpb[i - a][j]);
}
else dpa[i][j] = dpa[i - 1][j];
}
dpb[i][j] = add(dpa[i - 1][j], dpb[i - 1][j]);
}
dpa[i][i]=dpa[i-1][i-1];
for(int j=i-1; j>=0; j--)dpa[i][i]=add(dpa[i][i], dpb[i-1][j]);
if(i>=a)
{
for (int j = i - a; j >= 0; j--)
{
dpa[i][i] = dif(dpa[i][i], dpb[i - a][j]);
}
}
}
for(int i=1; i<=n; i++)
{
for(int j=0; j<=n; j++)
{
// cout<<i<<' '<<j<<' '<<dpa[i][j]<<' '<<dpb[i][j]<<endl;
}
}
int ans=bp(2, n);
for(int i=0; i<=n; i++)
{
ans=dif(ans, dpa[n][i]);
ans=dif(ans, dpb[n][i]);
}
if(a>1)
{
cout << ans << endl;
}
else cout<<bp(2,n)<<endl;
}
``` |
### Prompt
Develop a solution in CPP to the problem described below:
ZS the Coder has a large tree. It can be represented as an undirected connected graph of n vertices numbered from 0 to n - 1 and n - 1 edges between them. There is a single nonzero digit written on each edge.
One day, ZS the Coder was bored and decided to investigate some properties of the tree. He chose a positive integer M, which is coprime to 10, i.e. <image>.
ZS consider an ordered pair of distinct vertices (u, v) interesting when if he would follow the shortest path from vertex u to vertex v and write down all the digits he encounters on his path in the same order, he will get a decimal representaion of an integer divisible by M.
Formally, ZS consider an ordered pair of distinct vertices (u, v) interesting if the following states true:
* Let a1 = u, a2, ..., ak = v be the sequence of vertices on the shortest path from u to v in the order of encountering them;
* Let di (1 β€ i < k) be the digit written on the edge between vertices ai and ai + 1;
* The integer <image> is divisible by M.
Help ZS the Coder find the number of interesting pairs!
Input
The first line of the input contains two integers, n and M (2 β€ n β€ 100 000, 1 β€ M β€ 109, <image>) β the number of vertices and the number ZS has chosen respectively.
The next n - 1 lines contain three integers each. i-th of them contains ui, vi and wi, denoting an edge between vertices ui and vi with digit wi written on it (0 β€ ui, vi < n, 1 β€ wi β€ 9).
Output
Print a single integer β the number of interesting (by ZS the Coder's consideration) pairs.
Examples
Input
6 7
0 1 2
4 2 4
2 0 1
3 0 9
2 5 7
Output
7
Input
5 11
1 2 3
2 0 3
3 0 3
4 3 3
Output
8
Note
In the first sample case, the interesting pairs are (0, 4), (1, 2), (1, 5), (3, 2), (2, 5), (5, 2), (3, 5). The numbers that are formed by these pairs are 14, 21, 217, 91, 7, 7, 917 respectively, which are all multiples of 7. Note that (2, 5) and (5, 2) are considered different.
<image>
In the second sample case, the interesting pairs are (4, 0), (0, 4), (3, 2), (2, 3), (0, 1), (1, 0), (4, 1), (1, 4), and 6 of these pairs give the number 33 while 2 of them give the number 3333, which are all multiples of 11.
<image>
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
struct Edge {
int v, d;
};
vector<Edge> edge[N];
map<int, int> cnt;
bool centroid[N];
int sz[N];
int up[N];
int pw[N], ipw[N];
int n, m;
long long ans;
int pow_mod(int x, int n) {
int ret = 1;
for (; n; n >>= 1) {
if (n & 1) ret = (long long)ret * x % m;
x = (long long)x * x % m;
}
return ret;
}
int Phi(int n) {
int ret = n, m = (int)sqrt(n + 0.5);
for (int i = 2; i <= m; ++i) {
if (n % i == 0) {
while (n % i == 0) n /= i;
ret = ret / i * (i - 1);
}
}
if (n > 1) ret = ret / n * (n - 1);
return ret;
}
void init() {
int phi = Phi(m);
pw[0] = ipw[0] = 1;
for (int i = 1; i <= 100000; ++i) {
pw[i] = (long long)pw[i - 1] * 10 % m;
ipw[i] = pow_mod(pw[i], phi - 1);
}
}
void DFS_size(int u, int fa = -1) {
sz[u] = 1;
for (auto it : edge[u])
if (!(it.v == fa || centroid[it.v])) {
DFS_size(it.v, u);
sz[u] += sz[it.v];
}
}
pair<int, int> DFS_centroid(int u, int fa, int t) {
pair<int, int> ret = pair<int, int>(INT_MAX, -1);
int mx = 0, s = 1;
for (auto it : edge[u])
if (!(it.v == fa || centroid[it.v])) {
ret = min(ret, DFS_centroid(it.v, u, t));
mx = max(mx, sz[it.v]);
s += sz[it.v];
}
mx = max(mx, t - s);
ret = min(ret, pair<int, int>(mx, u));
return ret;
}
bool rev;
void DFS_digit_up(int u, int fa, int len) {
if (!rev && !up[u]) ans++;
if (cnt.count(up[u])) ans += cnt[up[u]];
for (auto it : edge[u])
if (!(it.v == fa || centroid[it.v])) {
up[it.v] = ((long long)it.d * pw[len] % m + up[u]) % m;
DFS_digit_up(it.v, u, len + 1);
}
}
void DFS_digit_down(int u, int fa, int d, int len) {
if (!rev && !d) ans++;
int x = (long long)(m - d) * ipw[len] % m;
cnt[x]++;
for (auto it : edge[u])
if (!(it.v == fa || centroid[it.v])) {
DFS_digit_down(it.v, u, ((long long)d * 10 % m + it.d) % m, len + 1);
}
}
void DFS(int u) {
DFS_size(u);
int s = DFS_centroid(u, -1, sz[u]).second;
centroid[s] = true;
for (auto it : edge[s])
if (!centroid[it.v]) DFS(it.v);
cnt.clear();
rev = false;
for (int v, i = 0; i < edge[s].size(); ++i)
if (!centroid[v = edge[s][i].v]) {
up[v] = edge[s][i].d;
DFS_digit_up(v, s, 1);
DFS_digit_down(v, s, edge[s][i].d, 1);
}
cnt.clear();
rev = true;
for (int v, i = (int)edge[s].size() - 1; i >= 0; --i)
if (!centroid[v = edge[s][i].v]) {
up[v] = edge[s][i].d;
DFS_digit_up(v, s, 1);
DFS_digit_down(v, s, edge[s][i].d, 1);
}
centroid[s] = false;
}
int main() {
ios::sync_with_stdio(false);
cin >> n >> m;
init();
for (int i = 1; i < n; ++i) {
int u, v, d;
cin >> u >> v >> d;
d %= m;
edge[u].push_back(Edge{v, d});
edge[v].push_back(Edge{u, d});
}
DFS(0);
cout << ans << '\n';
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Nikola owns a large warehouse which is illuminated by N light bulbs, numbered 1 to N. At the exit of the warehouse, there are S light switches, numbered 1 to S. Each switch swaps the on/off state for some light bulbs, so if a light bulb is off, flipping the switch turns it on, and if the light bulb is on, flipping the switch turns it off.
At the end of the day, Nikola wants to turn all the lights off. To achieve this, he will flip some of the light switches at the exit of the warehouse, but since Nikola is lazy, he wants to flip the _minimum_ number of switches required to turn all the lights off. Since Nikola was not able to calculate the minimum number of switches, he asked you to help him. During a period of D days, Nikola noted which light bulbs were off and which were on at the end of each day. He wants you to tell him the minimum number of switches he needed to flip to turn all the lights off for each of the D days or tell him that it's impossible.
Input
First line contains three integers, N, S and D (1 β€ N β€ 10^3, 1 β€ S β€ 30, 1 β€ D β€ 10^3) β representing number of light bulbs, the number of light switches, and the number of days respectively.
The next S lines contain the description of each light switch as follows: The first number in the line, C_i (1 β€ C_i β€ N), represents the number of light bulbs for which the on/off state is swapped by light switch i, the next C_i numbers (sorted in increasing order) represent the indices of those light bulbs.
The next D lines contain the description of light bulbs for each day as follows: The first number in the line, T_i (1 β€ T_i β€ N), represents the number of light bulbs which are on at the end of day i, the next T_i numbers (sorted in increasing order) represent the indices of those light bulbs.
Output
Print D lines, one for each day. In the i^{th} line, print the minimum number of switches that need to be flipped on day i, or -1 if it's impossible to turn all the lights off.
Example
Input
4 3 4
2 1 2
2 2 3
1 2
1 1
2 1 3
3 1 2 3
3 1 2 4
Output
2
2
3
-1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM =
chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
const long long INF = 1e18;
const int MAX = 1005;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
long long rand(long long a, long long b) {
return uniform_int_distribution<long long>(a, b)(rng);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, s, d;
cin >> n >> s >> d;
long long hash[n], sw[s];
for (int i = 0; i < n; i++) hash[i] = rand(1, INF);
for (int i = 0; i < s; i++) {
int k;
cin >> k;
sw[i] = 0;
while (k--) {
int x;
cin >> x;
sw[i] ^= hash[x - 1];
}
}
unordered_map<long long, int, custom_hash> left_sz;
int left = min(s / 2, 10);
for (int mask = 0; mask < (1 << left); mask++) {
long long cur = 0;
for (int bit = 0; bit < left; bit++) {
if (!((mask >> bit) & 1)) continue;
cur ^= sw[bit];
}
if (!left_sz.count(cur))
left_sz[cur] = __builtin_popcountll(mask);
else
left_sz[cur] = min(left_sz[cur], __builtin_popcountll(mask));
}
unordered_map<long long, int, custom_hash> right_sz;
int right = s - left;
for (int mask = 0; mask < (1 << right); mask++) {
long long cur = 0;
for (int bit = 0; bit < right; bit++) {
if (!((mask >> bit) & 1)) continue;
cur ^= sw[bit + left];
}
if (!right_sz.count(cur))
right_sz[cur] = __builtin_popcountll(mask);
else
right_sz[cur] = min(right_sz[cur], __builtin_popcountll(mask));
}
while (d--) {
long long cur = 0;
int sz;
cin >> sz;
for (int i = 0; i < sz; i++) {
int x;
cin >> x;
cur ^= hash[x - 1];
}
int ans = 100;
for (auto p : left_sz) {
long long tmp = cur ^ p.first;
if (right_sz.count(tmp)) ans = min(ans, p.second + right_sz[tmp]);
if (left_sz.count(tmp)) {
if (tmp == p.first)
ans = 0;
else
ans = min(ans, p.second + left_sz[tmp]);
}
}
cout << (ans == 100 ? -1 : ans) << "\n";
}
return 0;
}
``` |
### Prompt
Create a solution in Cpp for the following problem:
You are given an array a consisting of n integers, and additionally an integer m. You have to choose some sequence of indices b1, b2, ..., bk (1 β€ b1 < b2 < ... < bk β€ n) in such a way that the value of <image> is maximized. Chosen sequence can be empty.
Print the maximum possible value of <image>.
Input
The first line contains two integers n and m (1 β€ n β€ 35, 1 β€ m β€ 109).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print the maximum possible value of <image>.
Examples
Input
4 4
5 2 4 1
Output
3
Input
3 20
199 41 299
Output
19
Note
In the first example you can choose a sequence b = {1, 2}, so the sum <image> is equal to 7 (and that's 3 after taking it modulo 4).
In the second example you can choose a sequence b = {3}.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n, m, a;
scanf("%lld %lld", &n, &m);
vector<long long> a1, a2;
for (long long i = 0; i < n; i++) {
scanf("%lld", &a);
a %= m;
if (i % 2)
a2.push_back(a);
else
a1.push_back(a);
}
long long i, j, sum;
set<long long> s1, s2;
n = a1.size();
for (i = 0; i < (1 << n); i++) {
sum = 0;
for (j = n - 1; j >= 0; j--) {
if (i & (1 << j)) sum += a1[j];
}
s1.insert(sum % m);
}
n = a2.size();
for (i = 0; i < (1 << n); i++) {
sum = 0;
for (j = n - 1; j >= 0; j--) {
if (i & (1 << j)) sum += a2[j];
}
s2.insert(sum % m);
}
set<long long>::iterator it, pt;
long long ans = 0;
for (it = s1.begin(); it != s1.end(); it++) {
sum = *it;
pt = s2.lower_bound(m - sum);
pt--;
ans = max(ans, (sum + *pt) % m);
pt = s2.end();
pt--;
ans = max(ans, (sum + *pt) % m);
}
cout << ans << endl;
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Pablo Squarson is a well-known cubism artist. This year's theme for Pablo Squarson is "Squares". Today we are visiting his studio to see how his masterpieces are given birth.
At the center of his studio, there is a huuuuuge table and beside it are many, many squares of the same size. Pablo Squarson puts one of the squares on the table. Then he places some other squares on the table in sequence. It seems his methodical nature forces him to place each square side by side to the one that he already placed on, with machine-like precision.
Oh! The first piece of artwork is done. Pablo Squarson seems satisfied with it. Look at his happy face.
Oh, what's wrong with Pablo? He is tearing his hair! Oh, I see. He wants to find a box that fits the new piece of work but he has trouble figuring out its size. Let's help him!
Your mission is to write a program that takes instructions that record how Pablo made a piece of his artwork and computes its width and height. It is known that the size of each square is 1. You may assume that Pablo does not put a square on another.
I hear someone murmured "A smaller box will do". No, poor Pablo, shaking his head, is grumbling "My square style does not seem to be understood by illiterates".
<image>
Input
The input consists of a number of datasets. Each dataset represents the way Pablo made a piece of his artwork. The format of a dataset is as follows.
> N
n1 d1
n2 d2
...
nN-1 dN-1
The first line contains the number of squares (= N) used to make the piece of artwork. The number is a positive integer and is smaller than 200.
The remaining (N-1) lines in the dataset are square placement instructions. The line "ni di" indicates placement of the square numbered i (β€ N-1). The rules of numbering squares are as follows. The first square is numbered "zero". Subsequently placed squares are numbered 1, 2, ..., (N-1). Note that the input does not give any placement instruction to the first square, which is numbered zero.
A square placement instruction for the square numbered i, namely "ni di", directs it to be placed next to the one that is numbered ni, towards the direction given by di, which denotes leftward (= 0), downward (= 1), rightward (= 2), and upward (= 3).
For example, pieces of artwork corresponding to the four datasets shown in Sample Input are depicted below. Squares are labeled by their numbers.
<image>
The end of the input is indicated by a line that contains a single zero.
Output
For each dataset, output a line that contains the width and the height of the piece of artwork as decimal numbers, separated by a space. Each line should not contain any other characters.
Sample Input
1
5
0 0
0 1
0 2
0 3
12
0 0
1 0
2 0
3 1
4 1
5 1
6 2
7 2
8 2
9 3
10 3
10
0 2
1 2
2 2
3 2
2 1
5 1
6 1
7 1
8 1
0
Output for the Sample Input
1 1
3 3
4 4
5 6
Example
Input
1
5
0 0
0 1
0 2
0 3
12
0 0
1 0
2 0
3 1
4 1
5 1
6 2
7 2
8 2
9 3
10 3
10
0 2
1 2
2 2
3 2
2 1
5 1
6 1
7 1
8 1
0
Output
1 1
3 3
4 4
5 6
### Response
```cpp
#include <iostream>
using namespace std;
int main(void){
while(1){
int n;
cin>>n;
if(n == 0) break;
int x[n],y[n];
x[0] = y[0] = 0;
int minX=0,minY=0,maxX=0,maxY=0;
for(int i=1;i<n;i++){
int a,b;
cin>>a>>b;
//γε΅γ«γε γ
if(b == 0){
x[i] = x[a] - 1;
y[i] = y[a];
}
//γε―γ³γε γ
else if(b == 1){
x[i] = x[a];
y[i] = y[a] - 1;
}
//γε³γε γ
else if(b == 2){
x[i] = x[a] + 1;
y[i] = y[a];
}
//γζΉγγε γ
else if(b == 3){
x[i] = x[a];
y[i] = y[a] + 1;
}
if(minX > x[i]) minX = x[i];
if(minY > y[i]) minY = y[i];
if(maxX < x[i]) maxX = x[i];
if(maxY < y[i]) maxY = y[i];
}
cout<<maxX - minX + 1<<" "<<maxY - minY + 1<<endl;
}
return 0;
}
``` |
### Prompt
Your task is to create a Cpp solution to the following problem:
One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. Two pairs are considered different, if they contain different substrings of string s or different subsequences of string t. Read the whole statement to understand the definition of different substrings and subsequences.
The length of string s is the number of characters in it. If we denote the length of the string s as |s|, we can write the string as s = s1s2... s|s|.
A substring of s is a non-empty string x = s[a... b] = sasa + 1... sb (1 β€ a β€ b β€ |s|). For example, "code" and "force" are substrings or "codeforces", while "coders" is not. Two substrings s[a... b] and s[c... d] are considered to be different if a β c or b β d. For example, if s="codeforces", s[2...2] and s[6...6] are different, though their content is the same.
A subsequence of s is a non-empty string y = s[p1p2... p|y|] = sp1sp2... sp|y| (1 β€ p1 < p2 < ... < p|y| β€ |s|). For example, "coders" is a subsequence of "codeforces". Two subsequences u = s[p1p2... p|u|] and v = s[q1q2... q|v|] are considered different if the sequences p and q are different.
Input
The input consists of two lines. The first of them contains s (1 β€ |s| β€ 5000), and the second one contains t (1 β€ |t| β€ 5000). Both strings consist of lowercase Latin letters.
Output
Print a single number β the number of different pairs "x y" such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. As the answer can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
aa
aa
Output
5
Input
codeforces
forceofcode
Output
60
Note
Let's write down all pairs "x y" that form the answer in the first sample: "s[1...1] t[1]", "s[2...2] t[1]", "s[1...1] t[2]","s[2...2] t[2]", "s[1...2] t[1 2]".
### Response
```cpp
#include <bits/stdc++.h>
int c[5001][5001] = {0};
const int mod = 1000000007;
int main() {
char s[5000 + 1], t[5000 + 1];
scanf("%s%s", s, t);
int sl = strlen(s), tl = strlen(t);
c[0][0] = (s[0] == t[0]);
for (int j = 1; j < tl; j++)
if (s[0] == t[j])
c[0][j] = c[0][j - 1] + 1;
else
c[0][j] = c[0][j - 1];
for (int i = 1; i < sl; i++) {
if (s[i] == t[0])
c[i][0] = 1;
else
c[i][0] = 0;
for (int j = 1; j < tl; j++)
if (s[i] == t[j])
c[i][j] = (c[i - 1][j - 1] + c[i][j - 1] + 1) % mod;
else
c[i][j] = c[i][j - 1];
}
int r = 0;
for (int i = 0; i < sl; i++) r = (r + c[i][tl - 1]) % mod;
printf("%d\n", r);
return 0;
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
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(){
int a,b,c,x;
cin>>a>>b>>c;
x=a+b+c;
cout<<x-max(a,max(b,c));
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
There is a bookshelf which can fit n books. The i-th position of bookshelf is a_i = 1 if there is a book on this position and a_i = 0 otherwise. It is guaranteed that there is at least one book on the bookshelf.
In one move, you can choose some contiguous segment [l; r] consisting of books (i.e. for each i from l to r the condition a_i = 1 holds) and:
* Shift it to the right by 1: move the book at index i to i + 1 for all l β€ i β€ r. This move can be done only if r+1 β€ n and there is no book at the position r+1.
* Shift it to the left by 1: move the book at index i to i-1 for all l β€ i β€ r. This move can be done only if l-1 β₯ 1 and there is no book at the position l-1.
Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).
For example, for a = [0, 0, 1, 0, 1] there is a gap between books (a_4 = 0 when a_3 = 1 and a_5 = 1), for a = [1, 1, 0] there are no gaps between books and for a = [0, 0,0] there are also no gaps between books.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 200) β 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 places on a bookshelf. The second line of the test case contains n integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 1), where a_i is 1 if there is a book at this position and 0 otherwise. It is guaranteed that there is at least one book on the bookshelf.
Output
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).
Example
Input
5
7
0 0 1 0 1 0 1
3
1 0 0
5
1 1 0 0 1
6
1 0 0 0 0 1
5
1 1 0 1 1
Output
2
0
2
4
1
Note
In the first test case of the example, you can shift the segment [3; 3] to the right and the segment [4; 5] to the right. After all moves, the books form the contiguous segment [5; 7]. So the answer is 2.
In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.
In the third test case of the example, you can shift the segment [5; 5] to the left and then the segment [4; 4] to the left again. After all moves, the books form the contiguous segment [1; 3]. So the answer is 2.
In the fourth test case of the example, you can shift the segment [1; 1] to the right, the segment [2; 2] to the right, the segment [6; 6] to the left and then the segment [5; 5] to the left. After all moves, the books form the contiguous segment [3; 4]. So the answer is 4.
In the fifth test case of the example, you can shift the segment [1; 2] to the right. After all moves, the books form the contiguous segment [2; 5]. So the answer is 1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t, n;
cin >> t;
int a[100010];
while (t--) {
cin >> n;
int ans = 0;
bool one = false;
int temp;
for (int j = 0; j < n; j++) {
cin >> a[j];
}
for (int i = 0; i < n; i++) {
if (a[i] == 1 && one) {
ans += (i - temp) - 1;
temp = i;
}
if (a[i] == 1) {
one = true;
temp = i;
}
}
cout << ans << endl;
}
}
``` |
### Prompt
Please provide a Cpp coded solution to the problem described below:
One department of some software company has n servers of different specifications. Servers are indexed with consecutive integers from 1 to n. Suppose that the specifications of the j-th server may be expressed with a single integer number c_j of artificial resource units.
In order for production to work, it is needed to deploy two services S_1 and S_2 to process incoming requests using the servers of the department. Processing of incoming requests of service S_i takes x_i resource units.
The described situation happens in an advanced company, that is why each service may be deployed using not only one server, but several servers simultaneously. If service S_i is deployed using k_i servers, then the load is divided equally between these servers and each server requires only x_i / k_i (that may be a fractional number) resource units.
Each server may be left unused at all, or be used for deploying exactly one of the services (but not for two of them simultaneously). The service should not use more resources than the server provides.
Determine if it is possible to deploy both services using the given servers, and if yes, determine which servers should be used for deploying each of the services.
Input
The first line contains three integers n, x_1, x_2 (2 β€ n β€ 300 000, 1 β€ x_1, x_2 β€ 10^9) β the number of servers that the department may use, and resource units requirements for each of the services.
The second line contains n space-separated integers c_1, c_2, β¦, c_n (1 β€ c_i β€ 10^9) β the number of resource units provided by each of the servers.
Output
If it is impossible to deploy both services using the given servers, print the only word "No" (without the quotes).
Otherwise print the word "Yes" (without the quotes).
In the second line print two integers k_1 and k_2 (1 β€ k_1, k_2 β€ n) β the number of servers used for each of the services.
In the third line print k_1 integers, the indices of the servers that will be used for the first service.
In the fourth line print k_2 integers, the indices of the servers that will be used for the second service.
No index may appear twice among the indices you print in the last two lines. If there are several possible answers, it is allowed to print any of them.
Examples
Input
6 8 16
3 5 2 9 8 7
Output
Yes
3 2
1 2 6
5 4
Input
4 20 32
21 11 11 12
Output
Yes
1 3
1
2 3 4
Input
4 11 32
5 5 16 16
Output
No
Input
5 12 20
7 8 4 11 9
Output
No
Note
In the first sample test each of the servers 1, 2 and 6 will will provide 8 / 3 = 2.(6) resource units and each of the servers 5, 4 will provide 16 / 2 = 8 resource units.
In the second sample test the first server will provide 20 resource units and each of the remaining servers will provide 32 / 3 = 10.(6) resource units.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, x1, x2, x;
cin >> n >> x1 >> x2;
vector<pair<int, int> > v(n);
vector<pair<int, int> > ansa;
vector<pair<int, int> > ansb;
for (int i = 0; i < n; ++i) {
cin >> x;
v[i] = pair<int, int>(x, i + 1);
}
bool swapped = false;
if (x1 > x2) {
swap(x1, x2);
swapped = true;
}
bool poss = false;
sort((v).begin(), (v).end());
for (int i = 0; i < n; ++i) {
int nec = (x1 - 1) / v[i].first + 1;
if (nec <= n - i) {
if (i + nec >= n) {
if (i + nec < v.size() &&
(x2 - 1) / v[i + nec].first + 1 <= v.size() - (i + nec)) {
poss = true;
for (int j = 0, k = i; j < nec; ++j, ++k) ansa.push_back(v[k]);
for (int j = 0, k = i + nec; j < (x2 - 1) / v[i + nec].first + 1;
++j, ++k)
ansb.push_back(v[k]);
break;
} else
v.push_back(v[i]);
} else {
if ((x2 - 1) / v[i + nec].first + 1 <= n - (i + nec)) {
poss = true;
for (int j = 0, k = i; j < nec; ++j, ++k) ansa.push_back(v[k]);
for (int j = 0, k = i + nec; j < (x2 - 1) / v[i + nec].first + 1;
++j, ++k)
ansb.push_back(v[k]);
break;
} else
v.push_back(v[i]);
}
}
}
if (poss) {
cout << "Yes" << '\n';
if (!swapped) {
cout << ansa.size() << " " << ansb.size() << '\n';
for (auto i : ansa) cout << i.second << " ";
cout << '\n';
for (auto i : ansb) cout << i.second << " ";
cout << '\n';
} else {
cout << ansb.size() << " " << ansa.size() << '\n';
for (auto i : ansb) cout << i.second << " ";
cout << '\n';
for (auto i : ansa) cout << i.second << " ";
cout << '\n';
}
} else
cout << "No" << '\n';
return 0;
}
``` |
### Prompt
Your challenge is to write a cpp solution to the following problem:
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.
Input
The first line contains two positive integers n, m (1 β€ n, m β€ 300 000), denoting that the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.
Then m lines follow. Each line contains two integers x, y (1 β€ x, y β€ n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
Examples
Input
5 4
abaca
1 2
1 3
3 4
4 5
Output
3
Input
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
Output
-1
Input
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7
Output
4
Note
In the first sample, the path with largest value is 1 β 3 β 4 β 5. The value is 3 because the letter 'a' appears 3 times.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int q, n;
long long int ans, sum;
long long int gcd(long long int a, long long int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
long long int powe(long long int a, long long int b) {
long long int res = 1;
while (b > 0) {
if (b % 2 == 1) {
res = (res * a);
}
a = (a * a);
b /= 2;
}
return res;
}
long long int power(long long int a, long long int b, long long int M) {
a %= M;
long long int res = 1;
while (b > 0) {
if (b % 2 == 1) {
res = (res * a) % M;
}
a = (a * a) % M;
b /= 2;
}
return res;
}
long long int extendedEuclid(long long int A, long long int B, long long int &x,
long long int &y) {
if (B == 0) {
x = 1;
y = 0;
return A;
} else {
long long int x1, y1;
long long int gcd = extendedEuclid(B, A % B, x1, y1);
y = x1 - (A / B) * y1;
x = y1;
return gcd;
}
}
long long int mi(long long int A, long long int M) {
long long int x, y;
extendedEuclid(A, M, x, y);
if (x < 0) {
x += (long long int)1000000007;
}
return x;
}
vector<bool> sieve(1000000, true);
void Sieve() {
sieve[0] = false;
sieve[1] = false;
for (long long int i = 2; i * i <= 1000000; i++) {
if (sieve[i] == true) {
for (long long int j = i * i; j < 1000000; j += i) sieve[j] = false;
}
}
}
vector<long long int> sieve_spf;
void Sieve_spf() {
const long long int n = 1e6 + 5;
sieve_spf.resize(n);
for (int i = 0; i < n; i++) sieve_spf[i] = i;
sieve_spf[0] = -1;
sieve_spf[1] = 1;
for (int i = 2; i <= n; i += 2) sieve_spf[i] = 2;
for (int i = 3; i <= n; i += 2)
if (sieve_spf[i] == i)
for (int j = i * i; j <= n; j += i)
if (sieve_spf[j] == j) sieve_spf[j] = i;
}
bool isUpcase(char c) {
if (c >= 'A' && c <= 'Z')
return true;
else
return false;
}
bool islowcase(char c) {
if (c >= 'a' && c <= 'z')
return true;
else
return false;
}
void the_happiest_place_on_earth() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
;
}
bool comp(const pair<int, int> &a, const pair<int, int> &b) {
if (a.first > b.first)
return true;
else if (a.first == b.first && a.second < b.second)
return true;
else
return false;
}
const int N = 310055;
long long int b[N], a[N], dis[N], p[N];
vector<int> graph[N], graph1[N];
bool vis[N];
int dag;
void gra(long long int m) {
for (int i = 0; i < m; i++) {
long long int x, y;
cin >> x >> y;
x--, y--;
graph[x].push_back(y);
}
}
string second;
long long int color[N], dp[N][30];
void dfs(int node) {
vis[node] = true;
color[node] = 1;
for (auto x : graph[node]) {
if (color[x] == 1) {
cout << -1;
exit(0);
}
if (!vis[x]) dfs(x);
for (int i = 0; i < 26; i++) dp[node][i] = max(dp[node][i], dp[x][i]);
}
dp[node][second[node] - 'a']++;
for (int i = 0; i < 26; i++) ans = max(dp[node][i], ans);
color[node] = 0;
}
void testcase() {
long long int m;
cin >> n >> m >> second;
gra(m);
memset(color, 0, sizeof(color));
for (int i = 0; i < n; i++)
if (!vis[i]) dfs(i);
cout << ans;
return;
}
int main() {
the_happiest_place_on_earth();
q = 1;
while (q--) {
testcase();
}
cerr << "Time : " << 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC
<< "ms\n";
return 0;
}
``` |
### Prompt
Please create a solution in Cpp to the following problem:
You are given a permutation p=[p_1, p_2, β¦, p_n] of integers from 1 to n. Let's call the number m (1 β€ m β€ n) beautiful, if there exists two indices l, r (1 β€ l β€ r β€ n), such that the numbers [p_l, p_{l+1}, β¦, p_r] is a permutation of numbers 1, 2, β¦, m.
For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numbers 1, 3, 5, 6 are beautiful and 2, 4 are not. It is because:
* if l = 3 and r = 3 we will have a permutation [1] for m = 1;
* if l = 3 and r = 5 we will have a permutation [1, 3, 2] for m = 3;
* if l = 1 and r = 5 we will have a permutation [4, 5, 1, 3, 2] for m = 5;
* if l = 1 and r = 6 we will have a permutation [4, 5, 1, 3, 2, 6] for m = 6;
* it is impossible to take some l and r, such that [p_l, p_{l+1}, β¦, p_r] is a permutation of numbers 1, 2, β¦, m for m = 2 and for m = 4.
You are given a permutation p=[p_1, p_2, β¦, p_n]. For all m (1 β€ m β€ n) determine if it is a beautiful number or not.
Input
The first line contains the only integer t (1 β€ t β€ 1000) β the number of test cases in the input. The next lines contain the description of test cases.
The first line of a test case contains a number n (1 β€ n β€ 2 β
10^5) β the length of the given permutation p. The next line contains n integers p_1, p_2, β¦, p_n (1 β€ p_i β€ n, all p_i are different) β the given permutation p.
It is guaranteed, that the sum of n from all test cases in the input doesn't exceed 2 β
10^5.
Output
Print t lines β the answers to test cases in the order they are given in the input.
The answer to a test case is the string of length n, there the i-th character is equal to 1 if i is a beautiful number and is equal to 0 if i is not a beautiful number.
Example
Input
3
6
4 5 1 3 2 6
5
5 3 1 2 4
4
1 4 3 2
Output
101011
11111
1001
Note
The first test case is described in the problem statement.
In the second test case all numbers from 1 to 5 are beautiful:
* if l = 3 and r = 3 we will have a permutation [1] for m = 1;
* if l = 3 and r = 4 we will have a permutation [1, 2] for m = 2;
* if l = 2 and r = 4 we will have a permutation [3, 1, 2] for m = 3;
* if l = 2 and r = 5 we will have a permutation [3, 1, 2, 4] for m = 4;
* if l = 1 and r = 5 we will have a permutation [5, 3, 1, 2, 4] for m = 5.
### Response
```cpp
#include <bits/stdc++.h>
#pragma GCC optimize("O2")
using namespace std;
const double PI = atan(1.0) * 4;
const int di[4] = {-1, 0, 1, 0};
const int dj[4] = {0, -1, 0, 1};
const long long INF = (long long)2e18 + 50;
const int maximum = numeric_limits<int>::min();
const int minimum = numeric_limits<int>::max();
const long long mod = 1e9 + 7;
long long power(long long a, long long e) {
long long res = 1LL;
while (e > 0) {
if (e % 2 == 1) res = res * a;
a = a * a;
e /= 2;
}
return res;
}
bool isBalanced(const string &exp) {
bool flag = true;
int count = 0;
for (int i = 0; i < exp.length(); i++) {
if (exp[i] == '(') {
count++;
} else {
count--;
}
if (count < 0) {
flag = false;
break;
}
}
if (count != 0) {
flag = false;
}
return flag;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> p(n);
vector<int> pos(n);
for (int i = 0; i < n; i++) {
cin >> p[i];
--p[i];
pos[p[i]] = i;
}
int pos_max = -1, pos_min = n + 1;
vector<int> res(n);
for (int i = 0; i < n; i++) {
pos_max = max(pos_max, pos[i]);
pos_min = min(pos_min, pos[i]);
if (pos_max - pos_min == i)
res[i] = 1;
else
res[i] = 0;
}
for (auto i : res) {
cout << i;
}
cout << "\n";
}
return 0;
}
``` |
### Prompt
Your task is to create a CPP solution to the following problem:
Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it?
The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper.
There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not.
Input
The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font:
<image>
Output
Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes).
Examples
Input
AHA
Output
YES
Input
Z
Output
NO
Input
XO
Output
NO
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
map<char, int> m;
m['A'] = 1;
m['H'] = 1;
m['I'] = 1;
m['M'] = 1;
m['O'] = 1;
m['T'] = 1;
m['U'] = 1;
m['V'] = 1;
m['W'] = 1;
m['X'] = 1;
m['Y'] = 1;
string s1;
for (int i = 0; i < s.size(); i++) {
if (!(m.count(s[i]) > 0)) {
cout << "NO" << endl;
return 0;
} else
s1.push_back(s[i]);
}
string s2 = s1;
reverse(s2.begin(), s2.end());
if (s2 == s1)
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
A bitstring is a string that contains only the characters 0 and 1.
Koyomi Kanou is working hard towards her dream of becoming a writer. To practice, she decided to participate in the Binary Novel Writing Contest. The writing prompt for the contest consists of three bitstrings of length 2n. A valid novel for the contest is a bitstring of length at most 3n that contains at least two of the three given strings as subsequences.
Koyomi has just received the three prompt strings from the contest organizers. Help her write a valid novel for the contest.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero) characters.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5).
Each of the following three lines contains a bitstring of length 2n. It is guaranteed that these three strings are pairwise distinct.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, print a single line containing a bitstring of length at most 3n that has at least two of the given bitstrings as subsequences.
It can be proven that under the constraints of the problem, such a bitstring always exists.
If there are multiple possible answers, you may output any of them.
Example
Input
2
1
00
11
01
3
011001
111010
010001
Output
010
011001010
Note
In the first test case, the bitstrings 00 and 01 are subsequences of the output string: 010 and 010. Note that 11 is not a subsequence of the output string, but this is not required.
In the second test case all three input strings are subsequences of the output string: 011001010, 011001010 and 011001010.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define rep(i, j, k) for (LL i = j; i < k; ++i)
typedef long long int LL;
#define F first
#define S second
#define N 312345
string s[3];
int major_char_value[3];
int n;
vector<char> vec[N];
inline void match(int x, int y) {
char major_char = (major_char_value[x] == 0 ? '0' : '1');
rep (i, 0, n + 1) vec[i].clear();
int id = 0;
rep (i, 0, n + n) {
if (id < n) {
if (s[x][i] == major_char) {
id++;
continue;
}
}
vec[id].push_back(s[x][i]);
}
id = 0;
rep (i, 0, n + n) {
if (id < n) {
if (s[y][i] == major_char) {
id++;
continue;
}
}
vec[id].push_back(s[y][i]);
}
rep (i, 0, n + 1) {
rep (j, 0, vec[i].size()) cout << vec[i][j];
if (i < n) cout << major_char;
}
cout << '\n';
}
inline void solve () {
cin >> n;
rep (i, 0, 3) {
cin >> s[i];
int zc = 0;
rep (j, 0, n + n) if (s[i][j] == '0') zc++;
if (zc >= n) {
major_char_value[i] = 0;
} else {
major_char_value[i] = 1;
}
}
if (major_char_value[0] == major_char_value[1]) {
match(0, 1);
} else if (major_char_value[0] == major_char_value[2]) {
match(0, 2);
} else {
match(1, 2);
}
}
int main() {
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
``` |
### Prompt
Generate a CPP solution to the following problem:
The year of 2012 is coming...
According to an ancient choradrican legend in this very year, in 2012, Diablo and his brothers Mephisto and Baal will escape from hell, and innumerable hordes of demons will enslave the human world. But seven brave heroes have already gathered on the top of a mountain Arreat to protect us mere mortals from the effect of this terrible evil.
The seven great heroes are: amazon Anka, barbarian Chapay, sorceress Cleo, druid Troll, necromancer Dracul, paladin Snowy and a professional hit girl Hexadecimal. Heroes already know how much experience will be given for each of the three megabosses: a for Mephisto, b for Diablo and c for Baal.
Here's the problem: heroes are as much as seven and megabosses are only three! Then our heroes decided to split into three teams, where each team will go to destroy their own megaboss. Each team member will receive a <image> of experience, rounded down, where x will be the amount of experience for the killed megaboss and y β the number of people in the team.
Heroes do not want to hurt each other's feelings, so they want to split into teams so that the difference between the hero who received the maximum number of experience and the hero who received the minimum number of experience were minimal. Since there can be several divisions into teams, then you need to find the one in which the total amount of liking in teams were maximum.
It is known that some heroes like others. But if hero p likes hero q, this does not mean that the hero q likes hero p. No hero likes himself.
The total amount of liking in teams is the amount of ordered pairs (p, q), such that heroes p and q are in the same group, and hero p likes hero q (but it is not important if hero q likes hero p). In case of heroes p and q likes each other and they are in the same group, this pair should be counted twice, as (p, q) and (q, p).
A team can consist even of a single hero, but it is important that every megaboss was destroyed. All heroes must be involved in the campaign against evil. None of the heroes can be in more than one team.
It is guaranteed that every hero is able to destroy any megaboss alone.
Input
The first line contains a single non-negative integer n (0 β€ n β€ 42) β amount of liking between the heroes. Next n lines describe liking in the form "p likes q", meaning that the hero p likes the hero q (p β q). Every liking is described in the input exactly once, no hero likes himself.
In the last line are given three integers a, b and c (1 β€ a, b, c β€ 2Β·109), separated by spaces: the experience for Mephisto, the experience for Diablo and experience for Baal.
In all the pretests, except for examples from the statement, the following condition is satisfied: a = b = c.
Output
Print two integers β the minimal difference in the experience between two heroes who will receive the maximum and minimum number of experience points, and the maximal total amount of liking in teams (the number of friendships between heroes that end up in one team).
When calculating the second answer, the team division should satisfy the difference-minimizing contraint. I.e. primary you should minimize the difference in the experience and secondary you should maximize the total amount of liking.
Examples
Input
3
Troll likes Dracul
Dracul likes Anka
Snowy likes Hexadecimal
210 200 180
Output
30 3
Input
2
Anka likes Chapay
Chapay likes Anka
10000 50 50
Output
1950 2
Note
A note to first example: it the first team should be Dracul, Troll and Anka, in the second one Hexadecimal and Snowy, and in the third Cleo ΠΈ Chapay.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
bool like[10][10];
int main() {
map<string, int> mp;
mp["Anka"] = 1;
mp["Chapay"] = 2;
mp["Cleo"] = 3;
mp["Troll"] = 4;
mp["Dracul"] = 5;
mp["Snowy"] = 6;
mp["Hexadecimal"] = 7;
int n, i, j, k, l, x, y;
string str1, str2, str3;
cin >> n;
for (i = 0; i < n; i++) {
cin >> str1 >> str2 >> str3;
like[mp[str1]][mp[str3]] = 1;
}
int a[5], b[5];
cin >> a[0] >> a[1] >> a[2];
sort(a, a + 3);
int ans = 1e9;
for (i = 1; i <= 5; i++)
for (j = 1; j <= 5; j++) {
k = 7 - i - j;
b[0] = i;
b[1] = j;
b[2] = k;
if (k <= 0) continue;
sort(b, b + 3);
int mx = 0, mn = 1e9;
for (l = 0; l < 3; l++) {
mn = min(mn, a[l] / b[l]);
mx = max(mx, a[l] / b[l]);
}
if (mx - mn < ans) ans = mx - mn;
}
int ans2 = 0;
for (i = 1; i <= 5; i++)
for (j = 1; j <= 5; j++) {
k = 7 - i - j;
b[0] = i;
b[1] = j;
b[2] = k;
sort(b, b + 3);
if (k <= 0) continue;
int mn1 = 1e9, mx1 = 0;
for (l = 0; l < 3; l++) {
mn1 = min(mn1, a[l] / b[l]);
mx1 = max(mx1, a[l] / b[l]);
}
if (mx1 - mn1 == ans) {
int arr[10];
for (l = 0; l < 7; l++) arr[l] = l + 1;
do {
int c = 0;
for (x = 0; x < b[0]; x++) {
for (y = 0; y < b[0]; y++) {
if (like[arr[x]][arr[y]] == 1) c++;
}
}
for (x = b[0]; x < b[0] + b[1]; x++) {
for (y = b[0]; y < b[0] + b[1]; y++) {
if (like[arr[x]][arr[y]] == 1) c++;
}
}
for (x = b[0] + b[1]; x < b[0] + b[1] + b[2]; x++) {
for (y = b[0] + b[1]; y < b[0] + b[1] + b[2]; y++) {
if (like[arr[x]][arr[y]] == 1) c++;
}
}
if (c > ans2) ans2 = c;
} while (next_permutation(arr, arr + 7));
}
}
cout << ans << " " << ans2 << endl;
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas).
Vasya has come up with an algorithm he will follow while writing a letter. First he chooses two strings, s1 anf s2, consisting of uppercase English letters. Then the boy makes string sk, using a recurrent equation sn = sn - 2 + sn - 1, operation '+' means a concatenation (that is, the sequential record) of strings in the given order. Then Vasya writes down string sk on a piece of paper, puts it in the envelope and sends in to Santa.
Vasya is absolutely sure that Santa will bring him the best present if the resulting string sk has exactly x occurrences of substring AC (the short-cut reminds him ΠΎf accepted problems). Besides, Vasya decided that string s1 should have length n, and string s2 should have length m. Vasya hasn't decided anything else.
At the moment Vasya's got urgent New Year business, so he asks you to choose two strings for him, s1 and s2 in the required manner. Help Vasya.
Input
The first line contains four integers k, x, n, m (3 β€ k β€ 50; 0 β€ x β€ 109; 1 β€ n, m β€ 100).
Output
In the first line print string s1, consisting of n uppercase English letters. In the second line print string s2, consisting of m uppercase English letters. If there are multiple valid strings, print any of them.
If the required pair of strings doesn't exist, print "Happy new year!" without the quotes.
Examples
Input
3 2 2 2
Output
AC
AC
Input
3 3 2 2
Output
Happy new year!
Input
3 0 2 2
Output
AA
AA
Input
4 3 2 1
Output
Happy new year!
Input
4 2 2 1
Output
Happy new year!
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n, m, k, x, j, i, a[100], b[100], f[100], res, len1, len2;
long long nm[100], mn[100], mm[100], nn[100], mask;
char get(int x, int y) {
if (!y) return 'B';
if (x) return 'C';
return 'A';
}
string getAns(bool a, bool b, int n, int k, int a1, int b1) {
int i;
string ans = "";
if (n == 1) return ans = get(a, a1);
if (a == 0 && a1) {
for (i = 0; i < k; i++) ans += "AC";
if (k * 2 != n) {
for (i = 0; i < n - 2 * k; i++) ans += get(b, b1);
}
return ans;
}
if (b == 1 && b1) {
for (i = 0; i < k; i++) ans += "AC";
if (k * 2 != n) {
for (i = 0; i < n - 2 * k; i++) ans = get(a, a1) + ans;
}
return ans;
}
for (i = 0; i < k; i++) ans += "AC";
while (ans.size() + 2 < n) ans += "B";
return get(a, a1) + ans + get(b, b1);
}
int main() {
cin >> k >> x >> n >> m;
a[0] = 0;
b[0] = 0;
a[1] = 1;
b[1] = 1;
f[0] = 1;
f[1] = 1;
for (i = 2; i < k; i++) {
if (b[i - 2] == 0 && a[i - 1] == 0) nn[i]++;
if (b[i - 2] == 1 && a[i - 1] == 1) mm[i]++;
if (b[i - 2] == 0 && a[i - 1] == 1) nm[i]++;
if (b[i - 2] == 1 && a[i - 1] == 0) mn[i]++;
f[i] = f[i - 1] + f[i - 2];
nm[i] += nm[i - 1] + nm[i - 2];
mn[i] += mn[i - 1] + mn[i - 2];
mm[i] += mm[i - 1] + mm[i - 2];
nn[i] += nn[i - 1] + nn[i - 2];
a[i] = a[i - 2];
b[i] = b[i - 1];
}
k--;
for (mask = 0; mask < (1 << 8); mask++) {
if (n == 1 && (bool(mask & 1) ^ bool(mask & 2))) continue;
if (n == 1 && (bool(mask & 16) ^ bool(mask & 32))) continue;
if (m == 1 && (bool(mask & 4) ^ bool(mask & 8))) continue;
if (m == 1 && (bool(mask & 64) ^ bool(mask & 128))) continue;
if ((mask & 16) && (mask & 32) && !(mask & 1) && (mask & 2))
len1 = n / 2;
else {
if ((!(mask & 1) && (mask & 16)) || ((mask & 2) && (mask & 32)))
len1 = (n - 1) / 2;
else
len1 = (n - 2) / 2;
}
if ((mask & 64) && (mask & 128) && !(mask & 4) && (mask & 8))
len2 = m / 2;
else {
if ((!(mask & 4) && (mask & 64)) || ((mask & 8) && (mask & 128)))
len2 = (m - 1) / 2;
else
len2 = (m - 2) / 2;
}
for (i = 0; i <= len1; i++) {
for (j = 0; j <= len2; j++) {
res = f[k - 2] * i + f[k - 1] * j;
if ((mask & 16) && (mask & 32))
res += ((mask & 1) && !(mask & 2)) * nn[k];
if ((mask & 64) && (mask & 128))
res += ((mask & 4) && !(mask & 8)) * mm[k];
if ((mask & 32) && (mask & 64))
res += (!(mask & 2) && (mask & 4)) * nm[k];
if ((mask & 16) && (mask & 128))
res += (!(mask & 8) && (mask & 1)) * mn[k];
if (res == x) {
cout << getAns(mask & 1, mask & 2, n, i, mask & 16, mask & 32)
<< endl;
cout << getAns(mask & 4, mask & 8, m, j, mask & 64, mask & 128);
return 0;
}
}
}
}
cout << "Happy new year!";
return 0;
}
``` |
### Prompt
Please formulate a Cpp solution to the following problem:
Problem Statement
We have planted $N$ flower seeds, all of which come into different flowers. We want to make all the flowers come out together.
Each plant has a value called vitality, which is initially zero. Watering and spreading fertilizers cause changes on it, and the $i$-th plant will come into flower if its vitality is equal to or greater than $\mathit{th}_i$. Note that $\mathit{th}_i$ may be negative because some flowers require no additional nutrition.
Watering effects on all the plants. Watering the plants with $W$ liters of water changes the vitality of the $i$-th plant by $W \times \mathit{vw}_i$ for all $i$ ($1 \le i \le n$), and costs $W \times \mathit{pw}$ yen, where $W$ need not be an integer. $\mathit{vw}_i$ may be negative because some flowers hate water.
We have $N$ kinds of fertilizers, and the $i$-th fertilizer effects only on the $i$-th plant. Spreading $F_i$ kilograms of the $i$-th fertilizer changes the vitality of the $i$-th plant by $F_i \times \mathit{vf}_i$, and costs $F_i \times \mathit{pf}_i$ yen, where $F_i$ need not be an integer as well. Each fertilizer is specially made for the corresponding plant, therefore $\mathit{vf}_i$ is guaranteed to be positive.
Of course, we also want to minimize the cost. Formally, our purpose is described as "to minimize $W \times \mathit{pw} + \sum_{i=1}^{N}(F_i \times \mathit{pf}_i)$ under $W \times \mathit{vw}_i + F_i \times \mathit{vf}_i \ge \mathit{th}_i$, $W \ge 0$, and $F_i \ge 0$ for all $i$ ($1 \le i \le N$)". Your task is to calculate the minimum cost.
Input
The input consists of multiple datasets. The number of datasets does not exceed $100$, and the data size of the input does not exceed $20\mathrm{MB}$. Each dataset is formatted as follows.
> $N$
> $\mathit{pw}$
> $\mathit{vw}_1$ $\mathit{pf}_1$ $\mathit{vf}_1$ $\mathit{th}_1$
> :
> :
> $\mathit{vw}_N$ $\mathit{pf}_N$ $\mathit{vf}_N$ $\mathit{th}_N$
The first line of a dataset contains a single integer $N$, number of flower seeds. The second line of a dataset contains a single integer $\mathit{pw}$, cost of watering one liter. Each of the following $N$ lines describes a flower. The $i$-th line contains four integers, $\mathit{vw}_i$, $\mathit{pf}_i$, $\mathit{vf}_i$, and $\mathit{th}_i$, separated by a space.
You can assume that $1 \le N \le 10^5$, $1 \le \mathit{pw} \le 100$, $-100 \le \mathit{vw}_i \le 100$, $1 \le \mathit{pf}_i \le 100$, $1 \le \mathit{vf}_i \le 100$, and $-100 \le \mathit{th}_i \le 100$.
The end of the input is indicated by a line containing a zero.
Output
For each dataset, output a line containing the minimum cost to make all the flowers come out. The output must have an absolute or relative error at most $10^{-4}$.
Sample Input
3
10
4 3 4 10
5 4 5 20
6 5 6 30
3
7
-4 3 4 -10
5 4 5 20
6 5 6 30
3
1
-4 3 4 -10
-5 4 5 -20
6 5 6 30
3
10
-4 3 4 -10
-5 4 5 -20
-6 5 6 -30
0
Output for the Sample Input
43.5
36
13.5
0
Example
Input
3
10
4 3 4 10
5 4 5 20
6 5 6 30
3
7
-4 3 4 -10
5 4 5 20
6 5 6 30
3
1
-4 3 4 -10
-5 4 5 -20
6 5 6 30
3
10
-4 3 4 -10
-5 4 5 -20
-6 5 6 -30
0
Output
43.5
36
13.5
0
### Response
```cpp
#include<iostream>
#include<iomanip>
using namespace std;
int N;
double pw;
double vw[1<<17],pf[1<<17],wf[1<<17],th[1<<17];
double calc(double W)
{
double cost=W*pw;
for(int i=0;i<N;i++)
{
double now=th[i]-W*vw[i];
if(now>0)cost+=now/wf[i]*pf[i];
}
return cost;
}
int main()
{
while(cin>>N,N)
{
cin>>pw;
for(int i=0;i<N;i++)cin>>vw[i]>>pf[i]>>wf[i]>>th[i];
double L=0,R=1e9;
for(int ccc=0;ccc<200;ccc++)
{
double M1=(L*2+R)/3;
double M2=(L+R*2)/3;
double c1=calc(M1);
double c2=calc(M2);
if(c1<c2)R=M2;
else L=M1;
}
cout<<fixed<<setprecision(16)<<calc(L)<<endl;
}
}
``` |
### Prompt
Develop a solution in cpp to the problem described below:
Sorting algorithms for sorting data are basic algorithms indispensable in computer science. For example, as shown in the figure below, the operation of "sorting the elements of an array of integer values ββin ascending order" is alignment.
<image>
Many alignment algorithms have been devised, but one of the basic algorithms is bubble sort. As an example, let's arrange an array of given integer values ββin ascending order by bubble sort.
<image>
In bubble sort, each calculation step divides the array into "sorted parts" and "unsorted parts". Initially, the entire array will be the unsorted part.
From the beginning of the unsorted part, compare the adjacent elements (green element in the figure) and swap them so that the larger value is to the right. If the two values ββare equal, they will not be exchanged.
<image>
Repeat this process until the end of the unsorted part (white element in the figure). Finally, add the end to the sorted part (blue element in the figure) to complete one step.
Repeat this step until the unsorted part has a length of 1.
<image>
<image>
<image>
When the length of the unsorted part becomes 1, the sorting process ends.
Now, let's create a program that takes an array of n numbers as input, sorts the numbers in ascending order from the beginning of the array by the above bubble sort procedure, and outputs the number of exchanges of the required array elements. Please give me.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
a1
a2
::
an
The first line gives the number n (1 β€ n β€ 100), and the following n lines give the i-th number ai (1 β€ ai β€ 1000000).
The number of datasets does not exceed 20.
Output
Outputs the number of data element exchanges (integer) for each data set on one line.
Example
Input
5
5
3
2
1
4
6
1
2
3
4
5
6
3
3
2
1
0
Output
7
0
3
### Response
```cpp
#include <iostream>
using namespace std;
int n,a[100],ans=0;
void solve() {
int fin = n-1;
while(fin != 0) {
for(int i=0;i<fin;i++) {
if(a[i] > a[i+1]) {
swap(a[i],a[i+1]);
ans++;
}
}
fin--;
}
return;
}
int main() {
while(cin >> n) {
if(n==0) break;
for(int i=0;i<n;i++) {
cin >> a[i];
}
solve();
cout << ans << endl;
ans = 0;
}
return 0;
}
``` |
### Prompt
In Cpp, your task is to solve the following problem:
It is only six months until Christmas, and AtCoDeer the reindeer is now planning his travel to deliver gifts.
There are N houses along TopCoDeer street. The i-th house is located at coordinate a_i. He has decided to deliver gifts to all these houses.
Find the minimum distance to be traveled when AtCoDeer can start and end his travel at any positions.
Constraints
* 1 β€ N β€ 100
* 0 β€ a_i β€ 1000
* a_i is an integer.
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum distance to be traveled.
Examples
Input
4
2 3 7 9
Output
7
Input
8
3 1 4 1 5 9 2 6
Output
8
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int N;
cin>>N;
int k=1000,l=0;
for(int i=0;i<N;i++){
int a;
cin>>a;
k=min(k,a);
l=max(l,a);
}
cout<<l-k<<endl;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard.
If at least one of these n people has answered that the problem is hard, the coordinator decides to change the problem. For the given responses, check if the problem is easy enough.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of people who were asked to give their opinions.
The second line contains n integers, each integer is either 0 or 1. If i-th integer is 0, then i-th person thinks that the problem is easy; if it is 1, then i-th person thinks that the problem is hard.
Output
Print one word: "EASY" if the problem is easy according to all responses, or "HARD" if there is at least one person who thinks the problem is hard.
You may print every letter in any register: "EASY", "easy", "EaSY" and "eAsY" all will be processed correctly.
Examples
Input
3
0 0 1
Output
HARD
Input
1
0
Output
EASY
Note
In the first example the third person says it's a hard problem, so it should be replaced.
In the second example the problem easy for the only person, so it doesn't have to be replaced.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a, count = 0;
cin >> a;
int arr[a];
for (int i = 0; i < a; i++) {
cin >> arr[i];
}
for (int j = 0; j < a; j++) {
if (arr[j] == 1) {
count++;
}
}
if (count > 0) {
cout << "HARD";
} else {
cout << "EASY";
}
return 0;
}
``` |
### Prompt
Your task is to create a cpp solution to the following problem:
The weight of a sequence is defined as the number of unordered pairs of indexes (i,j) (here i < j) with same value (a_{i} = a_{j}). For example, the weight of sequence a = [1, 1, 2, 2, 1] is 4. The set of unordered pairs of indexes with same value are (1, 2), (1, 5), (2, 5), and (3, 4).
You are given a sequence a of n integers. Print the sum of the weight of all subsegments of a.
A sequence b is a subsegment of a sequence a if b can be obtained from a by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 10^5). Description of the test cases follows.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5).
The second line of each test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case, print a single integer β the sum of the weight of all subsegments of a.
Example
Input
2
4
1 2 1 1
4
1 2 3 4
Output
6
0
Note
* In test case 1, all possible subsegments of sequence [1, 2, 1, 1] having size more than 1 are:
1. [1, 2] having 0 valid unordered pairs;
2. [2, 1] having 0 valid unordered pairs;
3. [1, 1] having 1 valid unordered pair;
4. [1, 2, 1] having 1 valid unordered pairs;
5. [2, 1, 1] having 1 valid unordered pair;
6. [1, 2, 1, 1] having 3 valid unordered pairs.
Answer is 6.
* In test case 2, all elements of the sequence are distinct. So, there is no valid unordered pair with the same value for any subarray. Answer is 0.
### Response
```cpp
//#include <bits/stdc++.h>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <unordered_map>
#include <map>
using namespace std;
const int N = 500010,M = 80010;
typedef long long ll;
int n,m;
int a[N],h[N];
vector<int> re[N];int t = 0;
int find(int x)
{
return lower_bound(h+1,h+1+t,x)-h;
}
void slove()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
re[i].clear();
h[i] = a[i];
}
sort(h+1,h+1+n);
t = unique(h+1,h+1+n)-h-1;
for(int i=1;i<=n;i++) a[i] = find(a[i]);;
//for(int i=1;i<=n;i++) cout<<a[i]<<" ";
ll da = 0;
for(int i=1;i<=n;i++) re[a[i]].push_back(i);
//system("pause");
for(int i=1;i<=t;i++)
{
ll res = 0;
for(auto x:re[i])
{
da+=(n-x+1)*res;
res+=x;
}
}
cout<<da<<"\n";
}
int main()
{
int T;cin>>T;
while(T--)
{
slove();
}
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.
He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position x, and the shorter rabbit is currently on position y (x < y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by a, and the shorter rabbit hops to the negative direction by b.
<image>
For example, let's say x=0, y=10, a=2, and b=3. At the 1-st second, each rabbit will be at position 2 and 7. At the 2-nd second, both rabbits will be at position 4.
Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 1000).
Each test case contains exactly one line. The line consists of four integers x, y, a, b (0 β€ x < y β€ 10^9, 1 β€ a,b β€ 10^9) β the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.
Output
For each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.
If the two rabbits will never be at the same position simultaneously, print -1.
Example
Input
5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
Output
2
-1
10
-1
1
Note
The first case is explained in the description.
In the second case, each rabbit will be at position 3 and 7 respectively at the 1-st second. But in the 2-nd second they will be at 6 and 4 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
const double eps = 1e-10;
const int mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
long long t, x, y, a, b;
int main(void) {
scanf("%d", &t);
while (t--) {
scanf("%lld%lld%lld%lld", &x, &y, &a, &b);
if ((y - x) % (a + b) == 0) {
printf("%lld\n", (y - x) / (a + b));
} else
puts("-1");
}
return 0;
}
``` |
### Prompt
Please create a solution in cpp to the following problem:
Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them.
Recently, she was presented with an array a of the size of 10^9 elements that is filled as follows:
* a_1 = -1
* a_2 = 2
* a_3 = -3
* a_4 = 4
* a_5 = -5
* And so on ...
That is, the value of the i-th element of the array a is calculated using the formula a_i = i β
(-1)^i.
She immediately came up with q queries on this array. Each query is described with two numbers: l and r. The answer to a query is the sum of all the elements of the array at positions from l to r inclusive.
Margarita really wants to know the answer to each of the requests. She doesn't want to count all this manually, but unfortunately, she couldn't write the program that solves the problem either. She has turned to you β the best programmer.
Help her find the answers!
Input
The first line contains a single integer q (1 β€ q β€ 10^3) β the number of the queries.
Each of the next q lines contains two integers l and r (1 β€ l β€ r β€ 10^9) β the descriptions of the queries.
Output
Print q lines, each containing one number β the answer to the query.
Example
Input
5
1 3
2 5
5 5
4 4
2 3
Output
-2
-2
-5
4
-1
Note
In the first query, you need to find the sum of the elements of the array from position 1 to position 3. The sum is equal to a_1 + a_2 + a_3 = -1 + 2 -3 = -2.
In the second query, you need to find the sum of the elements of the array from position 2 to position 5. The sum is equal to a_2 + a_3 + a_4 + a_5 = 2 -3 + 4 - 5 = -2.
In the third query, you need to find the sum of the elements of the array from position 5 to position 5. The sum is equal to a_5 = -5.
In the fourth query, you need to find the sum of the elements of the array from position 4 to position 4. The sum is equal to a_4 = 4.
In the fifth query, you need to find the sum of the elements of the array from position 2 to position 3. The sum is equal to a_2 + a_3 = 2 - 3 = -1.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int i, z, y, n, x[10000][2];
int main() {
cin >> n;
for (i = 0; i < n; i++) {
cin >> x[i][0] >> x[i][1];
x[i][0]--;
}
for (i = 0; i < n; i++) {
if (x[i][1] % 2 == 0)
z = x[i][1] / 2;
else
z = (x[i][1] / 2 + 1) * -1;
if (x[i][0] == 0)
y = 0;
else if (x[i][0] % 2 == 0)
y = x[i][0] / 2;
else
y = (x[i][0] / 2 + 1) * -1;
cout << z - y << endl;
}
return 0;
}
``` |
### Prompt
Please formulate a cpp solution to the following problem:
Your task is to write a program of a simple dictionary which implements the following instructions:
* insert str: insert a string str in to the dictionary
* find str: if the distionary contains str, then print 'yes', otherwise print 'no'
Notes
Template in C
Constraints
* A string consists of 'A', 'C', 'G', or 'T'
* 1 β€ length of a string β€ 12
* n β€ 1000000
Input
In the first line n, the number of instructions is given. In the following n lines, n instructions are given in the above mentioned format.
Output
Print yes or no for each find instruction in a line.
Examples
Input
5
insert A
insert T
insert C
find G
find A
Output
no
yes
Input
13
insert AAA
insert AAC
insert AGA
insert AGG
insert TTT
find AAA
find CCC
find CCC
insert CCC
find CCC
insert T
find TTT
find T
Output
yes
no
no
yes
yes
yes
### Response
```cpp
#include <iostream>
#include <set>
int main() {
int n;
std::cin >> n;
std::string command, str;
std::set<std::string> dic;
for (int i = 0; i < n; i++) {
std::cin >> command >> str;
if (command == "insert") {
dic.insert(str);
} else if (command == "find") {
if (dic.count(str) == 0) {
std::cout << "no\n";
} else {
std::cout << "yes\n";
}
}
}
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 1026 (... 10000000010_2) and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.
Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with [bitwise exclusive or](https://en.wikipedia.org/wiki/Exclusive_or) of all elements equal to 0.
For the given sequence a_1, a_2, β¦, a_n Vasya'd like to calculate number of integer pairs (l, r) such that 1 β€ l β€ r β€ n and sequence a_l, a_{l + 1}, ..., a_r is good.
Input
The first line contains a single integer n (1 β€ n β€ 3 β
10^5) β length of the sequence.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{18}) β the sequence a.
Output
Print one integer β the number of pairs (l, r) such that 1 β€ l β€ r β€ n and the sequence a_l, a_{l + 1}, ..., a_r is good.
Examples
Input
3
6 7 14
Output
2
Input
4
1 2 1 16
Output
4
Note
In the first example pairs (2, 3) and (1, 3) are valid. Pair (2, 3) is valid since a_2 = 7 β 11, a_3 = 14 β 11 and 11 β 11 = 0, where β β bitwise exclusive or. Pair (1, 3) is valid since a_1 = 6 β 3, a_2 = 7 β 13, a_3 = 14 β 14 and 3 β 13 β 14 = 0.
In the second example pairs (1, 2), (2, 3), (3, 4) and (1, 4) are valid.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 3e5 + 5;
template <typename T>
void chkmax(T &x, T y) {
x = max(x, y);
}
template <typename T>
void chkmin(T &x, T y) {
x = min(x, y);
}
template <typename T>
void read(T &x) {
x = 0;
int f = 1;
char c = getchar();
for (; !isdigit(c); c = getchar())
if (c == '-') f = -f;
for (; isdigit(c); c = getchar()) x = x * 10 + c - '0';
x *= f;
}
template <typename T>
void write(T x) {
if (x < 0) x = -x, putchar('-');
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
template <typename T>
void writeln(T x) {
write(x);
puts("");
}
int a[MAXN], s[MAXN][2], sum[MAXN], nxt[MAXN];
int main() {
int n;
read(n);
for (int i = 1; i <= n; i++) {
long long tmp;
read(tmp);
while (tmp) {
a[i] += tmp & 1;
tmp >>= 1;
}
}
for (int i = 1; i <= n; i++) {
sum[i] = sum[i - 1] + a[i];
s[i][1] = s[i - 1][1];
s[i][0] = s[i - 1][0];
if (sum[i] % 2 == 1)
s[i][1]++;
else
s[i][0]++;
}
int las = n + 1;
for (int i = n; i >= 0; i--) {
nxt[i] = las;
if (a[i] != 0) las = i;
}
long long ans = 0;
for (int i = 1; i <= n; i++) {
int tmp = sum[i - 1] % 2;
int las = i, Max = a[i], sum = a[i];
for (int j = 1; j <= 128; j++) {
int id = nxt[las];
if (sum / 2 >= Max) {
ans = ans + s[id - 1][tmp] - s[las - 1][tmp];
}
Max = max(a[id], Max);
sum = sum + a[id];
las = id;
if (las > n) break;
}
ans = ans + s[n][tmp] - s[las - 1][tmp];
}
writeln(ans);
return 0;
}
``` |
### Prompt
Create a solution in cpp for the following problem:
Even if the world is full of counterfeits, I still regard it as wonderful.
Pile up herbs and incense, and arise again from the flames and ashes of its predecessor β as is known to many, the phoenix does it like this.
The phoenix has a rather long lifespan, and reincarnates itself once every a! years. Here a! denotes the factorial of integer a, that is, a! = 1 Γ 2 Γ ... Γ a. Specifically, 0! = 1.
Koyomi doesn't care much about this, but before he gets into another mess with oddities, he is interested in the number of times the phoenix will reincarnate in a timespan of b! years, that is, <image>. Note that when b β₯ a this value is always integer.
As the answer can be quite large, it would be enough for Koyomi just to know the last digit of the answer in decimal representation. And you're here to provide Koyomi with this knowledge.
Input
The first and only line of input contains two space-separated integers a and b (0 β€ a β€ b β€ 1018).
Output
Output one line containing a single decimal digit β the last digit of the value that interests Koyomi.
Examples
Input
2 4
Output
2
Input
0 10
Output
0
Input
107 109
Output
2
Note
In the first example, the last digit of <image> is 2;
In the second example, the last digit of <image> is 0;
In the third example, the last digit of <image> is 2.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
long long int a, b;
scanf("%lld %lld", &a, &b);
long long int diff = b - a + 1;
if (diff < 10) {
long long int ans = 1;
for (long long int i = b; i >= a + 1; i--) ans = (ans * i) % 10;
printf("%lld\n", ans);
} else
printf("0\n");
return 0;
}
``` |
### Prompt
Please provide a CPP coded solution to the problem described below:
There is unrest in the Galactic Senate. Several thousand solar systems have declared their intentions to leave the Republic. Master Heidi needs to select the Jedi Knights who will go on peacekeeping missions throughout the galaxy. It is well-known that the success of any peacekeeping mission depends on the colors of the lightsabers of the Jedi who will go on that mission.
Heidi has n Jedi Knights standing in front of her, each one with a lightsaber of one of m possible colors. She knows that for the mission to be the most effective, she needs to select some contiguous interval of knights such that there are exactly k1 knights with lightsabers of the first color, k2 knights with lightsabers of the second color, ..., km knights with lightsabers of the m-th color. Help her find out if this is possible.
Input
The first line of the input contains n (1 β€ n β€ 100) and m (1 β€ m β€ n). The second line contains n integers in the range {1, 2, ..., m} representing colors of the lightsabers of the subsequent Jedi Knights. The third line contains m integers k1, k2, ..., km (with <image>) β the desired counts of lightsabers of each color from 1 to m.
Output
Output YES if an interval with prescribed color counts exists, or output NO if there is none.
Example
Input
5 2
1 1 2 2 1
1 2
Output
YES
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
int n, m;
cin >> n >> m;
vector<int> v(n);
for (int i = 0; i < n; ++i) {
cin >> v[i];
--v[i];
}
vector<int> k(m);
int l = 0;
int u = 0;
for (int i = 0; i < m; ++i) {
cin >> k[i];
if (k[i] != 0) {
++l;
}
}
int best = 10000000;
int j = 0;
for (int i = 0; i < n; ++i) {
--k[v[i]];
if (k[v[i]] == 0) {
--l;
} else if (k[v[i]] < 0) {
++u;
}
while (l == 0) {
best = min(best, u);
++k[v[j]];
if (k[v[j]] == 1) {
++l;
} else {
--u;
}
++j;
}
}
if (best == 10000000) {
best = -1;
}
cout << best << endl;
return 0;
}
``` |
### Prompt
Construct a Cpp code solution to the problem outlined:
You are given a sequence of positive integers a1, a2, ..., an.
While possible, you perform the following operation: find a pair of equal consecutive elements. If there are more than one such pair, find the leftmost (with the smallest indices of elements). If the two integers are equal to x, delete both and insert a single integer x + 1 on their place. This way the number of elements in the sequence is decreased by 1 on each step.
You stop performing the operation when there is no pair of equal consecutive elements.
For example, if the initial sequence is [5, 2, 1, 1, 2, 2], then after the first operation you get [5, 2, 2, 2, 2], after the second β [5, 3, 2, 2], after the third β [5, 3, 3], and finally after the fourth you get [5, 4]. After that there are no equal consecutive elements left in the sequence, so you stop the process.
Determine the final sequence after you stop performing the operation.
Input
The first line contains a single integer n (2 β€ n β€ 2Β·105) β the number of elements in the sequence.
The second line contains the sequence of integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
In the first line print a single integer k β the number of elements in the sequence after you stop performing the operation.
In the second line print k integers β the sequence after you stop performing the operation.
Examples
Input
6
5 2 1 1 2 2
Output
2
5 4
Input
4
1000000000 1000000000 1000000000 1000000000
Output
1
1000000002
Input
7
4 10 22 11 12 5 6
Output
7
4 10 22 11 12 5 6
Note
The first example is described in the statements.
In the second example the initial sequence is [1000000000, 1000000000, 1000000000, 1000000000]. After the first operation the sequence is equal to [1000000001, 1000000000, 1000000000]. After the second operation the sequence is [1000000001, 1000000001]. After the third operation the sequence is [1000000002].
In the third example there are no two equal consecutive elements initially, so the sequence does not change.
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
std::ios::sync_with_stdio(false);
int n;
cin >> n;
int *x = new int[n];
int len = n;
int i = 0;
for (int j = 0; j < n; ++j, ++i) {
cin >> x[i];
if (i) {
if (x[i] == x[i - 1]) {
x[i - 1]++;
--i;
--len;
while (i > 0 && x[i - 1] == x[i]) {
x[i - 1]++;
--i;
--len;
}
}
}
}
cout << len << endl;
for (int i = 0; i < len; ++i) {
cout << x[i] << " ";
}
return 0;
}
``` |
### Prompt
Create a solution in CPP for the following problem:
Roma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.
Roma has a choice to buy exactly one of n different weapons and exactly one of m different armor sets. Weapon i has attack modifier a_i and is worth ca_i coins, and armor set j has defense modifier b_j and is worth cb_j coins.
After choosing his equipment Roma can proceed to defeat some monsters. There are p monsters he can try to defeat. Monster k has defense x_k, attack y_k and possesses z_k coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster k can be defeated with a weapon i and an armor set j if a_i > x_k and b_j > y_k. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.
Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.
Help Roma find the maximum profit of the grind.
Input
The first line contains three integers n, m, and p (1 β€ n, m, p β€ 2 β
10^5) β the number of available weapons, armor sets and monsters respectively.
The following n lines describe available weapons. The i-th of these lines contains two integers a_i and ca_i (1 β€ a_i β€ 10^6, 1 β€ ca_i β€ 10^9) β the attack modifier and the cost of the weapon i.
The following m lines describe available armor sets. The j-th of these lines contains two integers b_j and cb_j (1 β€ b_j β€ 10^6, 1 β€ cb_j β€ 10^9) β the defense modifier and the cost of the armor set j.
The following p lines describe monsters. The k-th of these lines contains three integers x_k, y_k, z_k (1 β€ x_k, y_k β€ 10^6, 1 β€ z_k β€ 10^3) β defense, attack and the number of coins of the monster k.
Output
Print a single integer β the maximum profit of the grind.
Example
Input
2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
Output
1
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
const long long N = (long long)2e5 + 7;
long long n, m, p;
struct T {
long long x;
long long c;
};
struct M {
long long x;
long long y;
long long p;
};
bool operator<(T a, T b) { return a.x < b.x; }
bool operator<(M a, M b) { return a.x < b.x; }
T a[N], b[N];
M mon[N];
const long long L = (long long)1e6 + 7;
long long aint[4 * L];
long long lazy[4 * L];
void push(long long v, long long tl, long long tr) {
if (lazy[v]) {
aint[v] += lazy[v];
if (tl < tr) {
lazy[2 * v] += lazy[v];
lazy[2 * v + 1] += lazy[v];
}
lazy[v] = 0;
}
}
void add(long long v, long long tl, long long tr, long long l, long long r,
long long x) {
push(v, tl, tr);
if (tr < l || r < tl) {
return;
}
if (l <= tl && tr <= r) {
lazy[v] += x;
push(v, tl, tr);
return;
}
long long tm = (tl + tr) / 2;
add(2 * v, tl, tm, l, r, x);
add(2 * v + 1, tm + 1, tr, l, r, x);
aint[v] = max(aint[2 * v], aint[2 * v + 1]);
}
long long get(long long v, long long tl, long long tr, long long l,
long long r) {
push(v, tl, tr);
if (tr < l || r < tl) {
return -(long long)1e18;
}
if (l <= tl && tr <= r) {
return aint[v];
}
long long tm = (tl + tr) / 2;
return max(get(2 * v, tl, tm, l, r), get(2 * v + 1, tm + 1, tr, l, r));
}
long long best[L];
int32_t main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m >> p;
for (long long i = 1; i <= n; i++) {
cin >> a[i].x >> a[i].c;
}
for (long long i = 0; i < L; i++) {
best[i] = (long long)1e18;
}
for (long long i = 1; i <= m; i++) {
cin >> b[i].x >> b[i].c;
best[b[i].x] = min(best[b[i].x], b[i].c);
}
sort(a + 1, a + n + 1);
for (long long i = 1; i <= p; i++) {
cin >> mon[i].x >> mon[i].y >> mon[i].p;
mon[i].x++;
mon[i].y++;
}
sort(mon + 1, mon + p + 1);
for (long long i = 0; i < L; i++) {
add(1, 1, L - 1, i, i, -best[i]);
}
long long ans = -(long long)1e18;
long long cur_mon = 1;
for (long long i = 1; i <= n; i++) {
while (cur_mon <= p && mon[cur_mon].x <= a[i].x) {
add(1, 1, L - 1, mon[cur_mon].y, L - 1, mon[cur_mon].p);
cur_mon++;
}
ans = max(ans, get(1, 1, L - 1, 1, L - 1) - a[i].c);
}
cout << ans << "\n";
}
``` |
### Prompt
Construct a cpp code solution to the problem outlined:
You are enthusiastic about the popular web game "Moonlight Ranch". The purpose of this game is to grow crops in the fields, sell them to earn income, and use that income to grow the ranch.
You wanted to grow the field quickly. Therefore, we decided to arrange the crops that can be grown in the game based on the income efficiency per hour.
You have to buy seeds to grow crops. Here, the name of the species of crop i is given by Li, and the price is given by Pi. When seeds are planted in the field, they sprout after time Ai. Young leaves appear 2 hours after the buds emerge. The leaves grow thick after Ci. The flowers bloom 10 hours after the leaves grow. Fruits come out time Ei after the flowers bloom. One seed produces Fi fruits, each of which sells at the price of Si. Some crops are multi-stage crops and bear a total of Mi fruit. In the case of a single-stage crop, it is represented by Mi = 1. Multi-season crops return to leaves after fruiting until the Mith fruit. The income for a seed is the amount of money sold for all the fruits of that seed minus the price of the seed. In addition, the income efficiency of the seed is the value obtained by dividing the income by the time from planting the seed to the completion of all the fruits.
Your job is to write a program that sorts and outputs crop information given as input, sorted in descending order of income efficiency.
Input
The input is a sequence of datasets, and each dataset is given in the following format.
> N
> L1 P1 A1 B1 C1 D1 E1 F1 S1 M1
> L2 P2 A2 B2 C2 D2 E2 F2 S2 M2
> ...
> LN PN AN BN CN DN EN FN SN MN
>
The first line is the number of crops N in the dataset (1 β€ N β€ 50).
The N lines that follow contain information about one crop in each line. The meaning of each variable is as described in the problem statement. The crop name Li is a string of up to 20 characters consisting of only lowercase letters, and 1 β€ Pi, Ai, Bi, Ci, Di, Ei, Fi, Si β€ 100, 1 β€ Mi β€ 5. It can be assumed that no crop has the same name in one case.
The end of the input is represented by a line containing only one zero.
Output
For each dataset, output the crop names, one for each row, in descending order of income efficiency. For crops with the same income efficiency, output their names in ascending dictionary order.
After the output of each data set, output one line consisting of only "#".
Example
Input
5
apple 1 1 1 1 1 1 1 10 1
banana 1 2 2 2 2 2 1 10 1
carrot 1 2 2 2 2 2 1 10 2
durian 1 3 3 3 3 3 1 10 1
eggplant 1 3 3 3 3 3 1 100 1
4
enoki 1 3 3 3 3 3 1 10 1
tomato 1 3 3 3 3 3 1 10 1
potato 1 3 3 3 3 3 1 10 1
onion 1 3 3 3 3 3 1 10 1
3
a 10 1 1 1 1 1 1 10 1
b 10 2 2 2 2 2 2 10 1
c 10 2 2 2 2 2 2 10 1
0
Output
eggplant
apple
carrot
banana
durian
#
enoki
onion
potato
tomato
#
b
c
a
#
### Response
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
int time(int a,int b,int c,int d,int e,int m){
int ret = a+b+c+d+e;
rep(i,m-1){
ret += d+e;
}
return ret;
}
bool cmp(const pair<double,string>&a,const pair<double,string>&b){
if( fabs(a.first-b.first) < 1e-8){
return a.second < b.second;
}
return a.first > b.first;
}
int main(){
int n;
while(cin >> n , n){
vector< pair<double,string> > data(n);
rep(i,n){
string l; int p,a,b,c,d,e,f,s,m;
cin >> l >> p >> a >> b >> c >> d >> e >> f >> s >> m;
data[i].first = (double)(f*s*m-p)/time(a,b,c,d,e,m);
data[i].second = l;
}
sort(data.begin(),data.end(),cmp);
rep(i,n){
cout << data[i].second << endl;
}
cout << "#" << endl;
}
}
``` |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.