C2. Madhouse (Hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries:   ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled.  ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ (⌈x⌉⌈x⌉ is xx rounded up).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use:   fflush(stdout) or cout.flush() in C++;  System.out.flush() in Java;  flush(output) in Pascal;  stdout.flush() in Python;  see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict. Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4

a
aa
a

cb
b
c

cOutputCopy? 1 2

? 3 4

? 4 4

! aabc

#include<cstdio>

#include<cstring>

#include<cstdlib>

#include<utility>

#include<assert.h>

#include<vector>

struct edge

{

	int to;std::pair<int,int> s;

	edge(int to=0,std::pair<int,int> s=std::make_pair(0,0)){this->to=to,this->s=s;}

};

int n,f[105][30],p[105],q[105],ans[105];

char st[105];

std::vector<edge> a[105];

void print()

{

	printf("! ");

	for (int i=1;i<=n;i++) printf("%c",ans[i]+96);

	puts("");

	fflush(stdout);

}

void add(int x,int y,std::pair<int,int> s){/*printf("%d %d (%c,%c)\n",x,y,s.first+96,s.second+96);*/a[x].push_back(edge(y,s));a[y].push_back(edge(x,s));}

void solve(int x,int y)

{

	int len=(y-x+1),ss=len*(len+1)/2;

//	printf("ss = %d\n",len);

	assert(1<=x&&x<=y&&y<=n);

	printf("? %d %d\n",x,y);

	fflush(stdout);

	for (int i=0;i<=len+1;i++) for (int ch=1;ch<=26;ch++) f[i][ch]=0;

	for (int i=0;i<=len+1;i++) p[i]=q[i]=0;

	for (int i=1;i<=ss;i++)

	{

		scanf("%s",st+1);

		if (st[1]=='-') exit(0);

		int m=std::strlen(st+1);

		if (m>(len+1)/2) continue;

		for (int k=1;k<=m;k++) ++f[m][st[k]-96];

	}

	for (int s=(len+1)/2;s>=1;s--)

		for (int ch=1;ch<=26;ch++)

			f[s][ch]=f[s][ch]-f[s-1][ch];

	for (int s=1;s<=(len+1)/2;s++)

		for (int ch=1;ch<=26;ch++)

			f[s][ch]=f[s][ch]-f[s+1][ch];

//	for (int s=1;s<=(len+1)/2;s++)

//	{

//		for (int ch=1;ch<=26;ch++) printf("%d ",f[s][ch]);

//		puts("");

//	}

	for (int s=1;s<=(len+1)/1;s++)

		for (int ch=1;ch<=26;ch++)

		{

			if (!f[s][ch]) continue;

			if (f[s][ch]>1){p[s]=q[s]=ch;continue;}

//			printf("%d:%d\n",s,ch);

			if (p[s]) q[s]=ch;else p[s]=ch;

		}

	fflush(stdout);

}

void dfs(int v)

{

//	printf("dfs %d\n",v);

	for (int i=0;i<(int)a[v].size();i++)

	{

		int u=a[v][i].to;

		std::pair<int,int> pp=a[v][i].s;

		if (ans[u]!=-1) continue;

		if (ans[v]==pp.first) ans[u]=pp.second;

		else ans[u]=pp.first;

		dfs(u);

	}

}

int main()

{

	scanf("%d",&n);

	if (n==1)

	{

		printf("? 1 1\n");

		fflush(stdout);

		char st[10];

		scanf("%s",st+1);

		if (st[1]=='-') exit(0);

		printf("! %c\n",st[1]);

		fflush(stdout);

		return 0;

	}

	if (n==2)

	{

		printf("? 1 1\n");

		fflush(stdout);

		char st[10];

		scanf("%s",st+1);

		if (st[1]=='-') exit(0);

		printf("? 2 2\n");

		fflush(stdout);

		scanf("%s",st+2);

		if (st[2]=='-') exit(0);

		printf("! %c%c\n",st[1],st[2]);

		fflush(stdout);

		return 0;

	}

	if (n==3)

	{

		printf("? 1 1\n");

		fflush(stdout);

		char st[10];

		scanf("%s",st+1);

		if (st[1]=='-') exit(0);

		printf("? 2 2\n");

		fflush(stdout);

		scanf("%s",st+2);

		if (st[2]=='-') exit(0);

		printf("? 3 3\n");

		fflush(stdout);

		scanf("%s",st+3);

		if (st[2]=='-') exit(0);

		printf("! %c%c%c\n",st[1],st[2],st[3]);

		fflush(stdout);

		return 0;

	}

	int kk=n-n/3;

	if (n<=5) kk=n;

	if (n==6) kk=5;

	int l1=kk-(n-kk),r1=n;

//	printf("%d %d\n",l1,r1);

	int l2=l1-1,r2=n;

	int l3=1,r3=(n>2?2*(l2-2)+1:1);

	if (r3>n) r3=n;

	int pt=0;

	solve(l1,r1);

	for (int i=1;i<=n;i++) ans[i]=-1;

	for (int i=1;i<=(r1-l1)/2+1;i++)

	{

		int x=l1+i-1,y=r1-i+1;

		if (x!=y) add(x,y,std::make_pair(p[i],q[i]));

		else if (x==y) ans[x]=p[i],pt=x;

	}

	solve(l2,r2);

	for (int i=1;i<=(r2-l2)/2+1;i++)

	{

		int x=l2+i-1,y=r2-i+1;

		if (x!=y) add(x,y,std::make_pair(p[i],q[i]));

		else if (x==y) ans[x]=p[i];

	}

	solve(l3,r3);

	for (int i=1;i<=(r3-l3)/2+1;i++)

	{

		int x=l3+i-1,y=r3-i+1;

		if (x!=y) add(x,y,std::make_pair(p[i],q[i]));

		else if (x==y) ans[x]=p[i];

	}

//	printf("%d\n",pt);

	assert(pt);

	dfs(pt);

	print();

	return 0;

}


D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules:  He starts at the top-left cell in the grid;  In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to:   in the case 'U' to the cell (i−1,j)(i−1,j);  in the case 'D' to the cell (i+1,j)(i+1,j);  in the case 'L' to the cell (i,j−1)(i,j−1);  in the case 'R' to the cell (i,j+1)(i,j+1);   He wants to run exactly kk kilometers, so he wants to make exactly kk moves;  Bashar can finish in any cell of the grid;  He can't go out of the grid so at any moment of the time he should be on some cell;  Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4
OutputCopyYES
2
2 R
2 L
InputCopy3 3 1000000000
OutputCopyNO
InputCopy3 3 8
OutputCopyYES
3
2 R
2 D
1 LLRR
InputCopy4 4 9
OutputCopyYES
1
3 RLD
InputCopy3 4 16
OutputCopyYES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):

#include <algorithm>

#include <cassert>

#include <cstdio>

#include <cstring>

#include <iomanip>

#include <iostream>

#include <map>

#include <numeric>

#include <queue>

#include <ranges>

#include <set>

#include <string>

#include <vector>

using namespace std;

#define all(x) (x).begin(), (x).end()

#define rall(x) (x).rbegin(), (x).rend()

void __print(int x) { cerr << x; }

void __print(long x) { cerr << x; }

void __print(long long x) { cerr << x; }

void __print(unsigned x) { cerr << x; }

void __print(unsigned long x) { cerr << x; }

void __print(unsigned long long x) { cerr << x; }

void __print(float x) { cerr << x; }

void __print(double x) { cerr << x; }

void __print(long double x) { cerr << x; }

void __print(char x) { cerr << '\'' << x << '\''; }

void __print(const char *x) { cerr << '\"' << x << '\"'; }

void __print(const string &x) { cerr << '\"' << x << '\"'; }

void __print(bool x) { cerr << (x ? "true" : "false"); }

template <typename T, typename V>

void __print(const pair<T, V> &x) {

    cerr << '{';

    __print(x.first);

    cerr << ',';

    __print(x.second);

    cerr << '}';

}

template <typename T>

void __print(const T &x) {

    int f = 0;

    cerr << '{';

    for (auto &i : x) cerr << (f++ ? "," : ""), __print(i);

    cerr << "}";

}

void _print() { cerr << "]\n"; }

template <typename T, typename... V>

void _print(T t, V... v) {

    __print(t);

    if (sizeof...(v)) cerr << ", ";

    _print(v...);

}

#ifdef DUPA

#define debug(x...)               \

    cerr << "[" << #x << "] = ["; \

    _print(x)

#else

#define debug(x, ...)

#endif

typedef long long LL;

// HMMMM

#define int LL

typedef pair<int, int> PII;

typedef pair<int, PII> PIII;

const int INF = 1e18 + 1;

int n, m, k;

void solve() {

    cin >> n >> m >> k;

    vector<pair<char, int>> res;

    if (n == 1) {

        res.push_back({'R', m - 1});

        res.push_back({'L', m - 1});

    } else if (m == 1) {

        res.push_back({'D', n - 1});

        res.push_back({'U', n - 1});

    } else {

        for (int i = 0; i < n - 1; i++) {

            res.push_back({'R', m - 1});

            res.push_back({'L', m - 1});

            res.push_back({'D', 1});

        }

        res.push_back({'R', m - 1});

        for (int j = m - 1; j > 0; j--) {

            res.push_back({'U', n - 1});

            res.push_back({'D', n - 1});

            res.push_back({'L', 1});

        }

        res.push_back({'U', n - 1});

    }

    int sum = 0;

    for (auto [_, x] : res) {

        sum += x;

    }

    assert(sum == 4 * n * m - 2 * n - 2 * m);

    if (k > sum) {

        cout << "NO " << endl;

        return;

    }

    while (sum != k) {

        res.back().second--;

        sum--;

        if (res.back().second == 0) res.pop_back();

    }

    assert(res.size() <= 3000);

    cout << "YES" << endl;

    cout << res.size() << endl;

    for (auto [y, x] : res) cout << x << " " << y << endl;

}

#undef int

int main() {

    ios::sync_with_stdio(false);

    cin.exceptions(cin.failbit);

    cin.tie(0);

    int t = 1;

#ifdef DUPA

    cin >> t;

#endif

    for (int i = 0; i < t; i++) solve();

}


B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)Here x⊕yx⊕y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2≤n≤4000002≤n≤400000) — the number of integers in the array.The second line contains integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).OutputPrint a single integer — xor of all pairwise sums of integers in the given array.ExamplesInputCopy2
1 2
OutputCopy3InputCopy3
1 2 3
OutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112⊕1002⊕1012=01020112⊕1002⊕1012=0102, thus the answer is 2.⊕⊕ is the bitwise xor operation. To define x⊕yx⊕y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012⊕00112=0110201012⊕00112=01102.

// LUOGU_RID: 102594463
#include <bits/stdc++.h>

#define IOS std::ios::sync_with_stdio(false);std::cin.tie(0);std::cout.tie(0);

#define endl '\n'

using ll = long long;

#define int long long

using pll = std::pair<int, int>;

using namespace std;

signed main()

{

//#ifdef LOCAL

//    freopen("in.txt","r",stdin);

//    freopen("out.txt","w",stdout);

//#endif

    IOS;///

    int n;

    cin >> n;

    vector<int>a(n + 7), b(n + 7);

    for (int i = 1;i <= n;++i)cin >> a[i];

    auto calc = [&](int L, int R) ->bool {

        if (L > R) return 0;

        ll ret = 0;

        for (int i = n, l = 1, r = 1; i; i--) {

            while (l <= n && b[i] + b[l] < L) ++l;

            while (r <= n && b[i] + b[r] <= R) ++r;

            ret += r - l - (l <= i && i < r);

        }

        return (ret >> 1) & 1;

    };

    int ans = 0;

    for (int k = 0;k <= 26;++k) {

        for (int i = 1;i <= n;++i) {

            b[i] = a[i] & ((1 << (k + 1) ) - 1);

        }

        sort(&b[1], &b[1 + n]);

        int g = (calc(1 << k, (1 << (k + 1)) - 1) ^ calc(3 << k, (1 << (k + 2)) - 2));

        ans |= (g << k);

    }

    cout << ans << '\n';

    return 0;

}


A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.

#include <iostream>

#include <iomanip>

#include <cstdio>

#include <vector>

#include <math.h>

#include <algorithm>

#include <map>

using namespace std;

int main()

{

     cout.tie(nullptr);

    std::ios::sync_with_stdio(false);

int t; cin >> t;

while(t--){

int n,s,k;

cin >> n >> s >> k;

vector<int> v;

for(int i=0;i<k;i++){

    int a; cin >> a;

    v.push_back(a);

}

int ans=0;

for (int i=0; i<=k; i++) {

		if (s+i<=n) {

                if(find(v.begin(),v.end(),s+i)==v.end()){

                ans=i; break;

                }

        }

        if (s-i>=1){

            if(find(v.begin(),v.end(),s-i)==v.end()){

               ans=i; break;

        }

		}

	}

cout << ans << '\n';

}

 return 0;

}


A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing 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 xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb.  For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.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.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — 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.OutputFor 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−1.ExampleInputCopy5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
OutputCopy2
-1
10
-1
1
NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 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.


F. Battalion Strengthtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn officers in the Army of Byteland. Each officer has some power associated with him. The power of the ii-th officer is denoted by pipi. As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these nn officers and calls this subset a battalion.(All 2n2n subsets of the nn officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be a1,a2,…,aka1,a2,…,ak, where a1≤a2≤⋯≤aka1≤a2≤⋯≤ak. The strength of this battalion is equal to a1a2+a2a3+⋯+ak−1aka1a2+a2a3+⋯+ak−1ak. (If the size of Battalion is ≤1≤1, then the strength of this battalion is 00).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be qq changes. Each one of the form ii xx indicating that pipi is changed to xx.You need to find the strength of the army initially and after each of these qq updates.Note that the changes are permanent.The strength should be found by modulo 109+7109+7. Formally, let M=109+7M=109+7. It can be shown that the answer can be expressed as an irreducible fraction p/qp/q, where pp and qq are integers and q≢0modMq≢0modM). Output the integer equal to p⋅q−1modMp⋅q−1modM. In other words, output such an integer xx that 0≤x<M0≤x<M and x⋅q≡pmodMx⋅q≡pmodM).InputThe first line of the input contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105)  — the number of officers in Byteland's Army.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤1091≤pi≤109).The third line contains a single integer qq (1≤q≤3⋅1051≤q≤3⋅105)  — the number of updates.Each of the next qq lines contains two integers ii and xx (1≤i≤n1≤i≤n, 1≤x≤1091≤x≤109), indicating that pipi is updated to xx .OutputIn the first line output the initial strength of the army.In ii-th of the next qq lines, output the strength of the army after ii-th update.ExamplesInputCopy2
1 2
2
1 2
2 1
OutputCopy500000004
1
500000004
InputCopy4
1 2 3 4
4
1 5
2 5
3 5
4 5
OutputCopy625000011
13
62500020
375000027
62500027
NoteIn first testcase; initially; there are four possible battalions   {} Strength = 00  {11} Strength = 00  {22} Strength = 00  {1,21,2} Strength = 22  So strength of army is 0+0+0+240+0+0+24 = 1212After changing p1p1 to 22, strength of battallion {1,21,2} changes to 44, so strength of army becomes 11.After changing p2p2 to 11, strength of battalion {1,21,2} again becomes 22, so strength of army becomes 1212.

#include<bits/stdc++.h>

using namespace std;

#define pb  push_back

#define ll  long long

#define vi  vector<int>

#define vvi vector<vi >

#define all(x) x.begin(), x.end()

ll mod = 1e9 + 7;

vi tw, in;

struct pt {

    ll val, cnt, lva, rva;

    pt() {};

    pt(ll k, ll x) {

        cnt = k;

        val = (x * x % mod) * (k * in[1] % mod + mod - 1 + in[k]) % mod;

        lva = (tw[k] + mod - 1) * x % mod;

        rva = (1 + mod - in[k]) * x % mod;

    }

    pt(ll val, ll cnt, ll lva, ll rva) : val(val), cnt(cnt), lva(lva), rva(rva) {};

};

pt operator+(pt x, pt y) {

    return pt((x.val + y.val + (x.lva * y.rva % mod) * in[x.cnt]) % mod, x.cnt + y.cnt,

              (x.lva + y.lva * tw[x.cnt]) % mod, (x.rva + y.rva * in[x.cnt]) % mod);

}

ll n, m, q;

vi p, x, I, X;

vector<pt> t;

ll po(ll x, ll p) {

    ll res = 1;

    for (; p; p /= 2) {

        if (p % 2)

            res = (res * x) % mod;

        x = (x * x) % mod;

    }

    return res;

}

ll inv(ll x) { return po(x, mod - 2); }

void add(ll i, ll x) {

    ll k = t[i].cnt + 1;

    t[i] = pt(k, x);

    for (i /= 2; i > 0; i /= 2)

        t[i] = (t[i + i] + t[i + i + 1]);

}

void del(ll i, ll x) {

    ll k = t[i].cnt - 1;

    t[i] = pt(k, x);

    for (i /= 2; i > 0; i /= 2)

        t[i] = (t[i + i] + t[i + i + 1]);

}

int main() {

    ios_base::sync_with_stdio(false); cin.tie(0);

    cin >> n;

    ll inv2 = inv(2);

    tw.assign(n + 5, 1);

    in.assign(n + 5, 1);

    for (ll i = 1; i < in.size(); ++i) {

        in[i] = (in[i - 1] * inv2) % mod;

        tw[i] = (tw[i - 1] * 2) % mod;

    }

    p.resize(n);

    for (auto& el : p) {

        cin >> el; x.pb(el);

    }

    cin >> q;

    I = X = vi(q);

    for (ll e = 0; e < q; ++e) {

        cin >> I[e] >> X[e]; --I[e];

        x.pb(X[e]);

    }

    sort(all(x));

    x.resize(unique(all(x)) - x.begin());

    m = 1;

    while (m < x.size())

        m *= 2;

    t.assign(2 * m, pt(0, 0, 0, 0));

    for (auto el : p) {

        ll e = lower_bound(all(x), el) - x.begin();

        add(e + m, el);

    }

    cout << t[1].val << "\n";

    for (ll o = 0; o < q; ++o) {

        ll i = I[o];

        ll to = X[o]; ll eto = lower_bound(all(x), to) - x.begin();

        ll fr = p[i]; ll efr = lower_bound(all(x), fr) - x.begin();

        p[i] = to;

        del(efr + m, fr);

        add(eto + m, to);

        cout << t[1].val << "\n";

    }

    return 0;

}


E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red; the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of nn rows and mm columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh qq options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 00.Warawreh couldn't find the best option himself so he asked you for help, can you help him?InputThe first line of input contains three integers nn, mm and qq (1≤n,m≤500,1≤q≤3⋅105)(1≤n,m≤500,1≤q≤3⋅105)  — the number of row, the number columns and the number of options.For the next nn lines, every line will contain mm characters. In the ii-th line the jj-th character will contain the color of the cell at the ii-th row and jj-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.For the next qq lines, the input will contain four integers r1r1, c1c1, r2r2 and c2c2 (1≤r1≤r2≤n,1≤c1≤c2≤m)(1≤r1≤r2≤n,1≤c1≤c2≤m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r1,c1)(r1,c1) and with the bottom-right corner in the cell (r2,c2)(r2,c2).OutputFor every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 00.ExamplesInputCopy5 5 5
RRGGB
RRGGY
YYBBG
YYBBR
RBBRG
1 1 5 5
2 2 5 5
2 2 3 3
1 1 3 5
4 4 5 5
OutputCopy16
4
4
4
0
InputCopy6 10 5
RRRGGGRRGG
RRRGGGRRGG
RRRGGGYYBB
YYYBBBYYBB
YYYBBBRGRG
YYYBBBYBYB
1 1 6 10
1 3 3 10
2 2 6 6
1 7 6 10
2 1 5 10
OutputCopy36
4
16
16
16
InputCopy8 8 8
RRRRGGGG
RRRRGGGG
RRRRGGGG
RRRRGGGG
YYYYBBBB
YYYYBBBB
YYYYBBBB
YYYYBBBB
1 1 8 8
5 2 5 7
3 1 8 6
2 3 5 8
1 2 6 8
2 1 5 5
2 1 7 7
6 5 7 5
OutputCopy64
0
16
4
16
4
36
0
NotePicture for the first test:The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black; the border of the sub-square with the maximal possible size; that can be cut is marked with gray.

#include <bits/stdc++.h>

using namespace std;

template<class A, class B> bool maximize(A& x, B y) {if (x < y) return x = y, true; else return false;}

template<class A, class B> bool minimize(A& x, B y) {if (x >= y) return x = y, true; else return false;}

void __print(int x) {cerr << x;}

void __print(long x) {cerr << x;}

void __print(long long x) {cerr << x;}

void __print(unsigned x) {cerr << x;}

void __print(unsigned long x) {cerr << x;}

void __print(unsigned long long x) {cerr << x;}

void __print(float x) {cerr << x;}

void __print(double x) {cerr << x;}

void __print(long double x) {cerr << x;}

void __print(char x) {cerr << '\'' << x << '\'';}

void __print(const char *x) {cerr << '\"' << x << '\"';}

void __print(const string &x) {cerr << '\"' << x << '\"';}

void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>

void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ", "; __print(x.second); cerr << '}';}

template<typename T>

void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? ", " : ""), __print(i); cerr << "}";}

void _print() {cerr << " ]\n";}

template <typename T, typename... V>

void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}

#define     deb(x...)             cerr << "[ in " <<__func__<< "() : line " <<__LINE__<< " ] : [ " << #x << " ] = [ "; _print(x); cerr << '\n';

typedef     long long             ll;

typedef     unsigned long long    ull;

typedef     double                db;

typedef     long double           ld;

typedef     pair<db, db>          pdb;

typedef     pair<ld, ld>          pld;

typedef     pair<int, int>        pii;

typedef     pair<ll, ll>          pll;

typedef     pair<ll, int>         plli;

typedef     pair<int, ll>         pill;

#define     all(a)                a.begin(), a.end()

#define     pb(a)                 push_back(a)

#define     pf(a)                 push_front(a)

#define     fi                    first

#define     se                    second

// #define     int                   long long

const int MAX_N = 500 + 5;

int n, m, q;

string a[MAX_N];

int prefSum[4][MAX_N][MAX_N];

int b[MAX_N][MAX_N];

int rmq[10][MAX_N][10][MAX_N];

int convert(const char& h) {

	if (h == 'R') return 0;

	if (h == 'G') return 1;

	if (h == 'Y') return 2;

	return 3;

}

bool inside(const int& x, const int& y) {

	return x > 0 && x <= n && y > 0 && y <= m;

}

int get(int t, int x, int y, int u, int v) {

	if (x > u) swap(x, u);

	if (y > v) swap(y, v);

	return prefSum[t][u][v] - prefSum[t][u][y - 1] - prefSum[t][x - 1][v] + prefSum[t][x - 1][y - 1];

}

int getMax(int x, int y, int u, int v) {

	int k1 = __lg(u - x + 1);

	int k2 = __lg(v - y + 1);

	int mx1 = max(rmq[k1][x][k2][y], rmq[k1][x][k2][v - (1 << k2) + 1]);

	int mx2 = max(rmq[k1][u - (1 << k1) + 1][k2][y], rmq[k1][u - (1 << k1) + 1][k2][v - (1 << k2) + 1]);

	return max(mx1, mx2);

}

signed main() {

	ios_base::sync_with_stdio(false);

	cin.tie(nullptr);

	cin >> n >> m >> q;

	for (int i = 1; i <= n; i++) {

		cin >> a[i];

		a[i] = ' ' + a[i];

	}

	for (int i = 1; i <= n; i++) {

		for (int j = 1; j <= m; j++) {

			for (int t = 0; t < 4; t++) {

				prefSum[t][i][j] = prefSum[t][i - 1][j] + prefSum[t][i][j - 1] - prefSum[t][i - 1][j - 1];

			}

			prefSum[convert(a[i][j])][i][j]++;

		}

	}

	for (int i = 1; i < n; i++) {

		for (int j = 1; j < m; j++) {

			if (a[i][j] == 'R' && a[i][j + 1] == 'G' && a[i + 1][j] == 'Y' && a[i + 1][j + 1] == 'B') {

				int low = 1, high = min(n, m);

				while (low <= high) {

					int mid = (low + high) >> 1;

					if (inside(i - mid + 1, j - mid + 1) && inside(i - mid + 1, j + mid) && inside(i + mid, j - mid + 1) && inside(i + mid, j + mid) && get(0, i - mid + 1, j - mid + 1, i, j) == mid * mid && get(1, i, j + 1, i - mid + 1, j + mid) == mid * mid && get(2, i + 1, j, i + mid, j - mid + 1) == mid * mid && get(3, i + 1, j + 1, i + mid, j + mid) == mid * mid) {

						b[i][j] = mid;

						low = mid + 1;

					}

					else {

						high = mid - 1;

					}

				}

			}

		}

	}

	for (int ir = 1; ir <= n; ir++) {

		for (int ic = 1; ic <= m; ic++) {

			rmq[0][ir][0][ic] = b[ir][ic];

		}

		for (int jc = 1; jc < 10; jc++) {

			for (int ic = 1; ic <= m; ic++) {

				if (ic + (1 << jc) > m) break;

				rmq[0][ir][jc][ic] = max(rmq[0][ir][jc - 1][ic], rmq[0][ir][jc - 1][ic + (1 << (jc - 1))]);

			}

		}

	}

	for (int jc = 0; jc < 10; jc++) {

		for (int ic = 1; ic <= m; ic++) {

			if (ic + (1 << jc) > m) break;

			for (int jr = 1; jr < 10; jr++) {

				for (int ir = 1; ir <= n; ir++) {

					if (ir + (1 << jr) > n) break;

					rmq[jr][ir][jc][ic] = max(rmq[jr - 1][ir][jc][ic], rmq[jr - 1][ir + (1 << (jr - 1))][jc][ic]);

				}

			}

		}

	}

	while (q--) {

		int x1, y1, x2, y2;

		cin >> x1 >> y1 >> x2 >> y2;

		int low = 1, high = min(n, m);

		int ans = 0;

		while (low <= high) {

			int mid = (low + high) >> 1;

			int u1 = x1 + mid - 1;

			int v1 = y1 + mid - 1;

			int u2 = x2 - mid;

			int v2 = y2 - mid;

			if (u1 <= u2 && v1 <= v2 && getMax(u1, v1, u2, v2) >= mid) {

				ans = mid;

				low = mid + 1;

			}

			else {

				high = mid - 1;

			}

		}

		cout << 4 * ans * ans << '\n';

	}

	return 0;

}

/*

*/


C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb 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][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33:  [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66.  [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32.

#include <iostream>
using namespace std;

const int MAXN = 2.5e5+100;
long long fact[MAXN];

int main(){
	int n,m;
	cin >> n >> m;
	fact[0] = 1;
	for(int i = 1;i <= n;i++){
		fact[i] = fact[i-1]*i;
		fact[i]%=m;
	}
	long long ans = 0;
	long long tp = 0;
	long long tp1 = 0;
	long long tp3 = 0;
	for (int len = 1;len<=n;len++){
		tp = fact[n-len]*(n-len+1);
		tp1 = fact[len]*(n-len+1);
		tp%=m;
		tp1%=m;

		// ans+=fact[n-len]*fact[len]*(n-len+1)*(n-len+1);
		tp3 = tp*tp1;
		tp3%=m;
		ans+=tp3;
		ans%=m;
	}
	cout << ans << endl;

}


C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1≤pi<n1≤pi<n) (i.e. you will press first pipi buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1m+1-th try you press all buttons right and finally perform the combo.I.e. if s=s="abca", m=2m=2 and p=[1,3]p=[1,3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow.The first line of each test case contains two integers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤2⋅1051≤m≤2⋅105) — the length of ss and the number of tries correspondingly.The second line of each test case contains the string ss consisting of nn lowercase Latin letters.The third line of each test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n) — the number of characters pressed right during the ii-th try.It is guaranteed that the sum of nn and the sum of mm both does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105, ∑m≤2⋅105∑m≤2⋅105).It is guaranteed that the answer for each letter does not exceed 2⋅1092⋅109.OutputFor each test case, print the answer — 2626 integers: the number of times you press the button 'a', the number of times you press the button 'b', ……, the number of times you press the button 'z'.ExampleInputCopy3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4
OutputCopy4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0
2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2
NoteThe first test case is described in the problem statement. Wrong tries are "a"; "abc" and the final try is "abca". The number of times you press 'a' is 44, 'b' is 22 and 'c' is 22.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 99, 'd' is 44, 'e' is 55, 'f' is 33, 'o' is 99, 'r' is 33 and 's' is 11.

#include <bits/stdc++.h>

using namespace std;

int main()

{

    int t; cin >> t;

    while(t--){

        int n, m;

        cin >> n >> m;

        string s;

        cin >> s;

        vector<int> freq(n, 0);

        for(int i=0; i<m; i++){

            int x; cin >> x;

            freq[0]++;

            freq[x]--;

        }

        freq[0]++;

        for(int i=1; i<n; i++){

            freq[i] += freq[i-1];

        }

        vector<int> c(26, 0);

        for(int i=0; i<n; i++){

            c[(s[i]-'a')]+= freq[i];

        }

        for(int i=0; i<26; i++){

            cout << c[i] << " ";

        }

        cout << endl;

    }

}


E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times:   choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|;  erase the chosen subsequence from ss (ss can become empty);  concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4
ababcd
abcba
a
b
defi
fed
xyz
x
OutputCopyYES
NO
NO
YES

#pragma GCC optimize("O2")

#pragma GCC target("avx,avx2,fma")

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace std;

using namespace __gnu_pbds;

#define ll     long long

#define test   int _TEST; cin>>_TEST; while(_TEST--)

#define ff     first

#define ss     second

#define pb     push_back

#define ppb    pop_back

#define pf     push_front

#define ppf    pop_front

template <typename T> using Ordered_Set_Tree =

        tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

template <typename T> using Ordered_Multiset_Tree =

        tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;

template <typename A, typename B> ostream& operator<<(ostream& s, const pair<A, B>& self) {s << self.first << ' ' << self.second << ' '; return s; }

template <typename T> ostream& operator<<(ostream& s, const vector<T>& self) { for (auto e : self) { s << e << '\n'; } return s; }

template <typename T> ostream& operator<<(ostream& s, tuple<T, T, T>& self) { s << get<0>(self) << ' ' << get<1>(self) << ' ' << get<2>(self); return s; }

template <typename A, typename B> istream& operator>>(istream& s, pair<A, B>& self) { s >> self.first >> self.second; return s; }

template <typename T> istream& operator>>(istream& s, tuple<T, T, T>& self) { s >> get<0>(self) >> get<1>(self) >> get<2>(self); return s; }

template <typename T> istream& operator>>(istream& s, tuple<T, T, T, T>& self) { s >> get<0>(self) >> get<1>(self) >> get<2>(self) >> get<3>(self); return s; }

template <typename T> istream& operator>>(istream& s, vector<T>& self) { for (size_t i = 0; i < self.size(); ++i) { s >> self[i]; } return s; }

///DEBUG

void _Print(int t) {cerr << t;}

void _Print(string t) {cerr << t;}

void _Print(char t) {cerr << t;}

void _Print(long long t) {cerr << t;}

void _Print(double t) {cerr << t;}

void _Print(unsigned long long t) {cerr << t;}

template <class T, class V> void _Print(pair <T, V> &p);

template <class T> void _Print(list <T> &v);

template <class T> void _Print(vector <T> &v);

template <class T> void _Print(deque <T> &v);

template <class T, class V> void _Print(T *v, V sz);

template <class T, class V, class P> void _Print(T *v, V sz, P sm);

template <class T> void _Print(set <T> &v);

template <class T, class V> void _Print(map <T, V> &v);

template <class T> void _Print(multiset <T> &v);

template <class T, class V> void _Print(pair <T, V> &p) {cerr << "{"; _Print(p.ff); cerr << ","; _Print(p.ss); cerr << "}\n\n";}

template <class T> void _Print(list <T> &v) {cerr << "[ "; for (T i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";}

template <class T> void _Print(vector <T> &v) {cerr << "[ "; for (T i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";}

template <class T> void _Print(deque <T> &v) {cerr << "[ "; for (T i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";}

template <class T, class V> void _Print(T *v, V sz) {cerr << "[ "; for(int i=0; i<sz; i++) {_Print(v[i]); cerr << " ";} cerr << "]\n\n";}

template <class T, class V, class P> void _Print(T *v, V sz, P sm) {cerr << "[\n"; for(int i=0; i<sz; i++) { for(int j=0; j<sm; j++) {_Print(v[i][j]); cerr << " ";} cerr << "\n";} cerr << "]\n\n";}

template <class T> void _Print(set <T> &v) {cerr << "[ "; for (T i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";}

template <class T> void _Print(multiset <T>& v) {cerr << "[ "; for (T i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";}

template <class T, class V> void _Print(map <T, V> &v) {cerr << "[ "; for (auto i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";}

#define debug(...) debug_out(vec_splitter(#__VA_ARGS__), 0, __LINE__, __VA_ARGS__)

vector<string> vec_splitter(string s)

{

    s += ',';

    vector<string> res;

    while(!s.empty())

    {

        res.push_back(s.substr(0, s.find(',')));

        s = s.substr(s.find(',') + 1);

    }

    return res;

}

void debug_out(vector<string> __attribute__ ((unused)) args, __attribute__ ((unused)) int idx, __attribute__ ((unused)) int LINE_NUM) { cerr << endl; }

template <typename Head, typename... Tail> void debug_out(vector<string> args, int idx, int LINE_NUM, Head H, Tail... T)

{

    if(idx > 0) cerr << ", "; else cerr << "Line(" << LINE_NUM << ") ";

    stringstream ss; ss << H;

    cerr << args[idx] << " = " << ss.str();

    debug_out(args, idx + 1, LINE_NUM, T...);

}

///DEBUG

int main()

{

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    test

    {

        string s, t;

        cin>>s>>t;

        vector<vector<int>> nextPos(s.size()+1, vector<int> (26, 1e9));

        for(int i=s.size()-1; i>=0; i--)

        {

            nextPos[i] = nextPos[i+1];

            nextPos[i][s[i]-'a'] =i;

        }

        vector<vector<int>> dp(s.size()+2, vector<int> (s.size()+2));

        auto cal = [&](string a, string b)

        {

            for(int i=0; i<=a.size(); i++)

            {

                for(int j=0; j<=b.size(); j++)

                    dp[i][j] = 1e9;

            }

            dp[0][0] = 0;

            for(int i=0; i<=a.size(); i++)

            {

                for(int j=0; j<=b.size(); j++)

                {

                    if(dp[i][j] > s.size())             continue;

                    int lenS = dp[i][j];

                    if(i<a.size() && nextPos[lenS][a[i]-'a']<1e9)

                        dp[i+1][j] = min(dp[i+1][j], nextPos[lenS][a[i]-'a']+1);

                    if(j<b.size() && nextPos[lenS][b[j]-'a']<1e9)

                        dp[i][j+1] = min(dp[i][j+1], nextPos[lenS][b[j]-'a']+1);

                }

            }

            return (dp[a.size()][b.size()] <= s.size());

        };

        int poss = 0;

        for(int i=0; i<t.size(); i++)

        {

            if(cal(t.substr(0, i), t.substr(i, t.size()-i)))

            {

                poss = 1;

                break;

            }

        }

        if(poss)            cout<<"YES\n";

        else                cout<<"NO\n";

    }

}


E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements:  The score of each problem should be a positive integer not exceeding 109109.  A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109.  The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3
OutputCopy4 5 9 13 18InputCopy8 0
OutputCopy10 11 12 13 14 15 16 17
InputCopy4 10
OutputCopy-1
NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution.   (1,2,3)(1,2,3)  (1,3,4)(1,3,4)  (2,4,5)(2,4,5)

//#pragma GCC optimize("Ofast")

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp> // Common file

#include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update

#include <ext/pb_ds/detail/standard_policies.hpp>

using namespace std;

mt19937 rng((int)std::chrono::steady_clock::now().time_since_epoch().count());

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 a) const {

        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();

        return splitmix64(a + FIXED_RANDOM);

    }

    template<class T> size_t operator()(T a) const {

        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();

        hash<T> x;

        return splitmix64(x(a) + FIXED_RANDOM);

    }

    template<class T, class H> size_t operator()(pair<T, H> a) const {

        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();

        hash<T> x;

        hash<H> y;

        return splitmix64(x(a.f) * 37 + y(a.s) + FIXED_RANDOM);

    }

};

template<class T, class H>using umap=unordered_map<T,H,custom_hash>;

const int MAXN = 2e5 + 10;

const int MOD = 998244353;

#define int long long

using namespace __gnu_pbds;

int bm(int b, int p) { // bigmod

    if(p==0) return 1;

    int r = bm(b, p/2);

    if(p&1) return (((r*r) % MOD) * b) % MOD;

    return (r*r) % MOD;

}

int inv(int b) { // modinv

    return bm(b, MOD-2);

}

int f[MAXN];

int nCr(int n, int r) { // nCr main function, requires precomputation function

    int ans = f[n]; ans *= inv(f[r]); ans %= MOD;

    ans *= inv(f[n-r]); ans %= MOD; return ans;

}

int dsu[MAXN]; // disjoint set union

int set_of(int u) {

    if(dsu[u] == u) return u;

    return dsu[u] = set_of(dsu[u]);

}

void union_(int u, int v) {

    dsu[set_of(u)] = set_of(v);

}

void precomp() { // factorials for nCr

    f[0] = 1;

    for(int i=1; i<MAXN; i++) f[i] = (f[i-1] * i) % MOD;

}

int rnd(int x, int y) { // random number generator

    int u= uniform_int_distribution<int>(x, y)(rng); return u;

}

int sd(int n) { // sum of digits

    int sum = 0;

    while(n) {

        sum += n%10;

        n /= 10;

    }

    return sum;

}

string binAdd(string a, string b) { //O(max(n,m)) time binary addition

    string result = ""; int s = 0;

    int i = a.size()-1, j = b.size()-1;

    while(i >= 0 || j >= 0 || s == 1) {

        s += ((i>=0 ? a[i] - '0':0));

        s += ((j>=0 ? b[j] - '0':0));

        result += char(s%2 + '0');

        s /= 2;

        i--, j--;

    }

    reverse(result.begin(), result.end());

    return result;

}

string binSub(string a, string b) { // O(max(n,m)) time binary subtraction, a ≥ b required

    string result = ""; int s = 0;

    int i = a.size()-1, j = b.size()-1;

    while(i >= 0 || j >= 0 || s != 0) {

        s += ((i>=0 ? a[i] - '0':0));

        s -= ((j>=0 ? b[j] - '0':0));

        result += char(abs(s)%2 + '0');

        if(s >= 0) s /= 2;

        else s = (s-1) / 2;

        i--, j--;

    }

    while(result.size() > 1 && result[result.size() - 1] == '0') {

        result.erase(result.size() - 1, 1);

    }

    reverse(result.begin(), result.end());

    return result;

}

int fastlog(int x) {

    int k = 32 - __builtin_clz(x) - 1;

    return k;

}

void stress(int tc) {

}

void solve(int tc) {

    int n, m;

    cin >> n >> m;

    int a[n+1];

    if(n == 1 || n == 2) {

        if(m == 0) {

            cout << "2022 "; //!!!

            if(n == 2) cout << "2023\n";

            return;

        }

        else {

            cout << "-1\n";

            return;

        }

    }

    a[0] = 1;

    a[1] = 1, a[2] = 2;

    for(int i=3; i<=n; i++) {

        int wow = (i+1) / 2 - 1;

        if(m >= wow) {

            m -= wow;

            a[i] = i;

        }

        else {

            int st = i+1;

            if(m > 0) a[i] = a[i-1] + a[i-m*2];

            else st = i;

            m = 0;

            for(int j=st; j<=n; j++) {

                a[j] = 1000000000 - n * (4*n) + j * (4*n);

            }

            break;

        }

    }

    if(!m) {

        for(int i=1; i<=n; i++) cout << a[i] << " ";

        cout << "\n";

    }

    else {

        cout << "-1\n";

    }

}

signed main(){

    precomp();        //Comment when not needed

//    ios::sync_with_stdio(0); cin.tie(0);

    int t = 1;

//    cin >> t;

    int cnt = 0;

    while(t--){

        stress(++cnt);

        solve(++cnt);

    }

}


G. Autocompletiontime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set of strings SS. Each string consists of lowercase Latin letters.For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the following actions:  if the current string is tt, choose some lowercase Latin letter cc and append it to the back of tt, so the current string becomes t+ct+c. This action takes 11 second;  use autocompletion. When you try to autocomplete the current string tt, a list of all strings s∈Ss∈S such that tt is a prefix of ss is shown to you. This list includes tt itself, if tt is a string from SS, and the strings are ordered lexicographically. You can transform tt into the ii-th string from this list in ii seconds. Note that you may choose any string from this list you want, it is not necessarily the string you are trying to type. What is the minimum number of seconds that you have to spend to type each string from SS?Note that the strings from SS are given in an unusual way.InputThe first line contains one integer nn (1≤n≤1061≤n≤106).Then nn lines follow, the ii-th line contains one integer pipi (0≤pi<i0≤pi<i) and one lowercase Latin character cici. These lines form some set of strings such that SS is its subset as follows: there are n+1n+1 strings, numbered from 00 to nn; the 00-th string is an empty string, and the ii-th string (i≥1i≥1) is the result of appending the character cici to the string pipi. It is guaranteed that all these strings are distinct.The next line contains one integer kk (1≤k≤n1≤k≤n) — the number of strings in SS.The last line contains kk integers a1a1, a2a2, ..., akak (1≤ai≤n1≤ai≤n, all aiai are pairwise distinct) denoting the indices of the strings generated by above-mentioned process that form the set SS — formally, if we denote the ii-th generated string as sisi, then S=sa1,sa2,…,sakS=sa1,sa2,…,sak.OutputPrint kk integers, the ii-th of them should be equal to the minimum number of seconds required to type the string saisai.ExamplesInputCopy10
0 i
1 q
2 g
0 k
1 e
5 r
4 m
5 h
3 p
3 e
5
8 9 1 10 6
OutputCopy2 4 1 3 3
InputCopy8
0 a
1 b
2 a
2 b
4 a
4 b
5 c
6 d
5
2 3 4 7 8
OutputCopy1 2 2 4 4
NoteIn the first example; SS consists of the following strings: ieh, iqgp, i, iqge, ier.

#include<bits/stdc++.h>

#define endl '\n'

#define iloveds std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);

#define all(a) a.begin(),a.end()

using namespace std;

typedef long long ll ;

const int N = 1e6 + 100;

int n, ch[N][26], k, a[N], b[N], dfn[N], ans[N], f[N];

int tot, dp[N], val;

void dfs(int x){

	if(f[x]) {

		dfn[x] = ++ tot;

	}

	for(int i = 0 ; i < 26; i ++){

		if(ch[x][i]){

			dfs(ch[x][i]);

			dfn[x] = min(dfn[x], dfn[ch[x][i]]);

		}

	}

}

void dfs2(int x){

	for(int i = 0 ; i < 26; i ++){

		int tmp = val;

		int u = ch[x][i];

		if(u) {

			if(f[u]){

				dp[u] = min(dp[x] + 1, dfn[u] + val);

			}else{

				dp[u] = dp[x] + 1;

			}

			val = min(val, dp[u] - dfn[u] + 1);

			dfs2(ch[x][i]);

		}

		val = tmp;

	}

}

int main(){

	iloveds;

	cin >> n;

	for(int i = 1; i <= n ; i ++){

		int x;

		char c;

		cin >> x >> c;

		ch[x][c - 'a'] = i;

	}

	cin >> k;

	for(int i = 1; i <= k ; i ++){

		cin >> a[i];

		f[a[i]] = 1;

	}

	for(int i = 1; i <= n ; i ++) {

		dp[i] = 0x3f3f3f3f;

		dfn[i] = 0x3f3f3f3f;

	}

	dfs(0);

	val = 0;

	dfs2(0);

	for(int i = 1; i <= k ; i ++) cout << dp[a[i]] << " ";

}


C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10
8 5
OutputCopy3InputCopy3 12
1 4 5
OutputCopy0InputCopy3 7
1 4 9
OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7.

#include<bits/stdc++.h>

#include <ext/random>

#include<ext/pb_ds/assoc_container.hpp>

#include<ext/pb_ds/tree_policy.hpp>

using namespace std;

using namespace __gnu_pbds;

#define GET(n, i) (((n) >> (i)) bitand 1)

#define LAST(n) ((n) bitand (-(n)))

#define RANGE(x, y, i, j) (i > -1 and i < x and j > -1 and j < y)

#define SET(x, k) (x | (1LL << k))

#define CLEAR(x, k) (x bitand ~ (1LL << k))

#define CHECK(x, k) (x bitand (1LL << k))

#define TOGGLE(x, k) (x ^ (1LL << k))

using LL = int64_t;

LL dx [] = {0, 1, 0, -1};

LL dy [] = {1, 0, -1, 0};

LL dxx [] = {0, 1, 0, -1, 1, 1, -1, -1};

LL dyy [] = {1, 0, -1, 0, 1, -1, 1, -1};

const LL mod = 1000000007;

#define ordered_set tree<LL, null_type, less<LL>, rb_tree_tag, tree_order_statistics_node_update>

__gnu_cxx::sfmt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());

const LL MAX = 1000;

vector<LL> fre(MAX, 0);

int main(void) {

        ios_base::sync_with_stdio(false);

        cin.tie(0); cout.tie(0);

        srand(chrono :: high_resolution_clock :: now().time_since_epoch().count());

        LL T = 1;

        for (LL qq = 0; qq < T; qq++) {

                LL n, m;

                cin >> n >> m;

                vector<LL> a(n, 0), b;

                unordered_set<LL> ss, bb;

                for (LL k = 0; k < n; k++) {

                        cin >> a[k];

                        ss.insert(a[k]);

                }

                if (ss.size() < n or n > m) {

                        cout << 0;

                        cout << '\n';

                        exit(0);

                }

                LL res = 1LL;

                for (LL k = 0; k < n; k++) {

                        for (LL j = k + 1; j < n; j++) {

                                res = res * (abs(a[k] - a[j]));

                                res = res % m;

                        }

                }

                cout << res << '\n';

                exit(0);

        }

        return 0;

}


E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.The chemical structure of this flower can be represented as a string pp. From the unencrypted papers included, Rin already knows the length nn of that string, and she can also conclude that the string contains at most three distinct letters: "C" (as in Carbon), "H" (as in Hydrogen), and "O" (as in Oxygen).At each moment, Rin can input a string ss of an arbitrary length into the artifact's terminal, and it will return every starting position of ss as a substring of pp.However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific:  The artifact only contains 7575 units of energy.  For each time Rin inputs a string ss of length tt, the artifact consumes 1t21t2 units of energy.  If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?InteractionThe interaction starts with a single integer tt (1≤t≤5001≤t≤500), the number of test cases. The interaction for each testcase is described below:First, read an integer nn (4≤n≤504≤n≤50), the length of the string pp.Then you can make queries of type "? s" (1≤|s|≤n1≤|s|≤n) to find the occurrences of ss as a substring of pp.After the query, you need to read its result as a series of integers in a line: The first integer kk denotes the number of occurrences of ss as a substring of pp (−1≤k≤n−1≤k≤n). If k=−1k=−1, it means you have exceeded the energy limit or printed an invalid query, and you need to terminate immediately, to guarantee a "Wrong answer" verdict, otherwise you might get an arbitrary verdict because your solution will continue to read from a closed stream. The following kk integers a1,a2,…,aka1,a2,…,ak (1≤a1<a2<…<ak≤n1≤a1<a2<…<ak≤n) denote the starting positions of the substrings that match the string ss.When you find out the string pp, print "! pp" to finish a test case. This query doesn't consume any energy. The interactor will return an integer 11 or 00. If the interactor returns 11, you can proceed to the next test case, or terminate the program if it was the last testcase.If the interactor returns 00, it means that your guess is incorrect, and you should to terminate to guarantee a "Wrong answer" verdict.Note that in every test case the string pp is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksFor hack, use the following format. Note that you can only hack with one test case:The first line should contain a single integer tt (t=1t=1).The second line should contain an integer nn (4≤n≤504≤n≤50) — the string's size.The third line should contain a string of size nn, consisting of characters "C", "H" and "O" only. This is the string contestants will have to find out.ExamplesInputCopy1
4

2 1 2

1 2

0

1OutputCopy

? C

? CH

? CCHO

! CCHH

InputCopy2
5

0

2 2 3

1
8

1 5

1 5

1 3

2 1 2

1OutputCopy

? O

? HHH

! CHHHH

? COO

? COOH

? HCCOO

? HH

! HHHCCOOH

NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.

#define poj

//#define zcz

#ifdef poj

#include<iostream>

#include<iomanip>

#include<cstdio>

#include<cstdlib>

#include<cmath>

#include<ctime>

#include<cstring>

#include<algorithm>

#include<queue>

#include<set>

#include<vector>

#include<string>

#include<stack>

#include<map>

#include<cassert>

#else

#include<bits/stdc++.h>

#endif

using namespace std;

#ifdef zcz

class fastin{

	private:

#ifdef poj

	static const int MAXBF=1<<20;

#else

	const int MAXBF=1<<27;

#endif

	FILE *inf;

	char *inbuf,*inst,*ined;

	inline char _getchar(){

		if(inst==ined)inst=inbuf,ined=inbuf+fread(inbuf,1,MAXBF,inf);

		return inst==ined?EOF:*inst++;

	}

	public:

	fastin(FILE*_inf=stdin){

		inbuf=new char[MAXBF],inf=_inf,inst=inbuf,ined=inbuf;

	}

	~fastin(){delete inbuf;}

	template<typename Int> fastin&operator>>(Int &n){

		static char c;

		Int t=1;

		while((c=_getchar())<'0'||c>'9')if(c=='-')t=-1;

		n=(c^48);

		while((c=_getchar())>='0'&&c<='9')n=(n<<3)+(n<<1)+(c^48);

		n*=t;

		return*this;

	}

	fastin&operator>>(char*s){

		int t=0;

		static char c;

		while((c=_getchar())!=' '&&c!='\n')s[t++]=c;

		s[t]='\0';

		return *this;

	}

}fi;

class fastout{

	private:

#ifdef poj

	static const int MAXBF=1<<20;

#else

	const int MAXBF=1<<27;

#endif

	FILE *ouf;

	char *oubuf,*oust,*oued;

	inline void _flush(){fwrite(oubuf,1,oued-oust,ouf);}

	inline void _putchar(char c){

		if(oued==oust+MAXBF)_flush(),oued=oubuf;

		*oued++=c;

	}

	public:

	fastout(FILE*_ouf=stdout){

		oubuf=new char[MAXBF],ouf=_ouf,oust=oubuf,oued=oubuf;

	}

	~fastout(){_flush();delete oubuf;}

	template<typename Int> fastout&operator<<(Int n){

		if(n<0)_putchar('-'),n=-n;

		static char S[20];

		int t=0;

		do{S[t++]='0'+n%10,n/=10;}while(n);

		for(int i=0;i<t;++i)_putchar(S[t-i-1]);

		return *this;

	}

	fastout&operator<<(char c){_putchar(c);return *this;}

	fastout&operator<<(char*s){

		for(int i=0;s[i];++i)_putchar(s[i]);

		return *this;

	}

	fastout&operator<<(const char*s){

		for(int i=0;s[i];++i)_putchar(s[i]);

		return *this;

	}

}fo;

#define cin fi

#define cout fo

#else

#define czc ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)

#endif

#define mod 1000000007

#define ll long long

#define isinf 0x3f3f3f3f

#define ilinf 0x7fffffff

#define lsinf 0x3f3f3f3f3f3f3f3f

#define llinf 0x7fffffffffffffff

#define pii pair<int,int>

#define next ___

int n,t;

char s[60];

void solve1(){

	int x;

	cout<<"? CH\n";

	cout.flush();

	cin>>t;

	assert(t!=-1);

	for(int i=1;i<=t;i++)cin>>x,s[x-1]='C',s[x]='H';

	cout<<"? CO\n";

	cout.flush();

	cin>>t;

	assert(t!=-1);

	for(int i=1;i<=t;i++)cin>>x,s[x-1]='C',s[x]='O';

	cout<<"? CC\n";

	cout.flush();

	cin>>t;

	assert(t!=-1);

	for(int i=1;i<=t;i++)cin>>x,s[x-1]=s[x]='C';

	if(s[0]=='C'){

		if(s[2]=='C'){

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//CCCC,CCCH,CCCO,CHCH,CHCO,CHCC,COCC,COCH,COCO

		}else{

			s[2]='O';s[3]='C';

			cout<<"? "<<s<<'\n';

			cout.flush();

			cin>>t;

			assert(t!=-1);

			if(t==1){

				cin>>x;

				cout<<"! "<<s<<'\n';

				cout.flush();

				return;

				//CCOC,CHOC,COOC

			}

			s[3]='O';

			cout<<"? "<<s<<'\n';

			cout.flush();

			cin>>t;

			assert(t!=-1);

			if(t==1){

				cin>>x;

				cout<<"! "<<s<<'\n';

				cout.flush();

				return;

				//CCOO,CHOO,COOO

			}

			s[3]='H';

			cout<<"? "<<s<<'\n';

			cout.flush();

			cin>>t;

			assert(t!=-1);

			if(t==1){

				cin>>x;

				cout<<"! "<<s<<'\n';

				cout.flush();

				return;

				//CCOH,CHOH,COOH

			}

			s[2]='H';s[3]='C';

			cout<<"? "<<s<<'\n';

			cout.flush();

			cin>>t;

			assert(t!=-1);

			if(t==1){

				cin>>x;

				cout<<"! "<<s<<'\n';

				cout.flush();

				return;

				//CCHC,COHC,CHHC

			}

			s[3]='O';

			cout<<"? "<<s<<'\n';

			cout.flush();

			cin>>t;

			assert(t!=-1);

			if(t==1){

				cin>>x;

				cout<<"! "<<s<<'\n';

				cout.flush();

				return;

				//CCHO,CHHO,COHO

			}

			s[3]='H';

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//CCHH,COHH,CHHH

		}

	}

	if(s[1]=='C'){

		s[0]='O';s[3]='H';

		cout<<"? "<<s<<'\n';

		cout.flush();

		cin>>t;

		assert(t!=-1);

		if(t==1){

			cin>>x;

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//OCCH,OCHH,OCOH

		}

		s[3]='C';

		cout<<"? "<<s<<'\n';

		cout.flush();

		cin>>t;

		assert(t!=-1);

		if(t==1){

			cin>>x;

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//OCHC,OCCC,OCOC

		}

		s[3]='O';

		cout<<"? "<<s<<'\n';

		cout.flush();

		cin>>t;

		assert(t!=-1);

		if(t==1){

			cin>>x;

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//OCHO,OCCO,OCOO

		}

		s[0]='H';s[3]='H';

		cout<<"? "<<s<<'\n';

		cout.flush();

		cin>>t;

		assert(t!=-1);

		if(t==1){

			cin>>x;

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//HCCH,HCOH,HCHH

		}

		s[3]='C';

		cout<<"? "<<s<<'\n';

		cout.flush();

		cin>>t;

		assert(t!=-1);

		if(t==1){

			cin>>x;

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//HCCC,HCOC,HCHC

		}

		s[3]='O';

		cout<<"! "<<s<<'\n';

		cout.flush();

		return;

		//HCCO,HCHO,HCOO

	}

	if(s[2]=='C'){

		s[0]=s[1]='O';

		cout<<"? "<<s<<'\n';

		cout.flush();

		cin>>t;

		assert(t!=-1);

		if(t==1){

			cin>>x;

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//OOCC,OOCO,OOCH

		}

		s[1]='H';

		cout<<"? "<<s<<'\n';

		cout.flush();

		cin>>t;

		assert(t!=-1);

		if(t==1){

			cin>>x;

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//OHCC,OHCO,OHCH

		}

		s[0]='H';

		cout<<"? "<<s<<'\n';

		cout.flush();

		cin>>t;

		assert(t!=-1);

		if(t==1){

			cin>>x;

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//HHCC,HHCO,HHCH

		}

		s[1]='O';

		cout<<"! "<<s<<'\n';

		cout.flush();

		return;

		//HOCC,HOCO,HOCH

	}

	cout<<"? HO\n";

	cout.flush();

	cin>>t;

	assert(t!=-1);

	for(int i=1;i<=t;i++)cin>>x,s[x-1]='H',s[x]='O';

	if(s[0]=='H'){

		if(s[2]=='H'){

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//HOHO

		}else{

			s[2]='O';s[3]='C';

			cout<<"? "<<s<<'\n';

			cout.flush();

			cin>>t;

			assert(t!=-1);

			if(t==1){

				cin>>x;

				cout<<"! "<<s<<'\n';

				cout.flush();

				return;

				//HOOC

			}

			s[3]='O';

			cout<<"? "<<s<<'\n';

			cout.flush();

			cin>>t;

			assert(t!=-1);

			if(t==1){

				cin>>x;

				cout<<"! "<<s<<'\n';

				cout.flush();

				return;

				//HOOO

			}

			s[3]='H';

			cout<<"? "<<s<<'\n';

			cout.flush();

			cin>>t;

			assert(t!=-1);

			if(t==1){

				cin>>x;

				cout<<"! "<<s<<'\n';

				cout.flush();

				return;

				//HOOH

			}

			s[2]='H';s[3]='C';

			cout<<"? "<<s<<'\n';

			cout.flush();

			cin>>t;

			assert(t!=-1);

			if(t==1){

				cin>>x;

				cout<<"! "<<s<<'\n';

				cout.flush();

				return;

				//HOHC

			}

			s[3]='H';

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//HOHH

		}

	}

	if(s[1]=='H'){

		s[0]='O';s[3]='H';

		cout<<"? "<<s<<'\n';

		cout.flush();

		cin>>t;

		assert(t!=-1);

		if(t==1){

			cin>>x;

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//OHOH

		}

		s[3]='C';

		cout<<"? "<<s<<'\n';

		cout.flush();

		cin>>t;

		assert(t!=-1);

		if(t==1){

			cin>>x;

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//OHOC

		}

		s[3]='O';

		cout<<"? "<<s<<'\n';

		cout.flush();

		cin>>t;

		assert(t!=-1);

		if(t==1){

			cin>>x;

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//OHOO

		}

		s[0]='H';s[3]='H';

		cout<<"? "<<s<<'\n';

		cout.flush();

		cin>>t;

		assert(t!=-1);

		if(t==1){

			cin>>x;

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//HHOH

		}

		s[3]='C';

		cout<<"? "<<s<<'\n';

		cout.flush();

		cin>>t;

		assert(t!=-1);

		if(t==1){

			cin>>x;

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//HHOC

		}

		s[3]='O';

		cout<<"! "<<s<<'\n';

		cout.flush();

		return;

		//HHOO

	}

	if(s[2]=='H'){

		s[0]=s[1]='O';

		cout<<"? "<<s<<'\n';

		cout.flush();

		cin>>t;

		assert(t!=-1);

		if(t==1){

			cin>>x;

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//OOHO

		}

		s[1]='H';

		cout<<"? "<<s<<'\n';

		cout.flush();

		cin>>t;

		assert(t!=-1);

		if(t==1){

			cin>>x;

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//OHHO

		}

		s[0]='H';

		cout<<"! "<<s<<'\n';

		cout.flush();

		return;

		//HHHO

	}

	cout<<"? OO\n";

	cout.flush();

	cin>>t;

	assert(t!=-1);

	for(int i=1;i<=t;i++)cin>>x,s[x-1]=s[x]='O';

	if(s[0]=='O'&&s[1]=='O'){

		if(s[3]=='O'){

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//OOOO

		}else{

			if(s[2]=='O'){

				s[3]='H';

				cout<<"? "<<s<<'\n';

				cout.flush();

				cin>>t;

				assert(t!=-1);

				if(t==1){

					cin>>x;

					cout<<"! "<<s<<'\n';

					cout.flush();

					return;

					//OOOH

				}

				s[3]='C';

				cout<<"! "<<s<<'\n';

				cout.flush();

				return;

				//OOOC

			}

			s[2]=s[3]='H';

			cout<<"? "<<s<<'\n';

			cout.flush();

			cin>>t;

			assert(t!=-1);

			if(t==1){

				cin>>x;

				cout<<"! "<<s<<'\n';

				cout.flush();

				return;

				//OOHH

			}

			s[3]='C';

			cout<<"! "<<s<<'\n';

			cout.flush();

			return;

			//OOHC

		}

	}

	s[1]=s[2]='H';

	cout<<"? HHH\n";

	cout.flush();

	cin>>t;

	assert(t!=-1);

	for(int i=1;i<=t;i++)cin>>x,s[x-1]=s[x]=s[x+1]='H';

	if(s[0]==0)s[0]='O';

	if(s[3]==0)s[3]='C';

	cout<<"! "<<s<<'\n';

	cout.flush();

	//HHHH,HHHC,OHHH,OHHC

	return;

}

void solve(){

	cin>>n;

	fill(s,s+n+1,0);

	if(n==4){

		solve1();

		goto label;

	}

	cout<<"? CH\n";

	cout.flush();

	cin>>t;

	assert(t!=-1);

	for(int i=1,x;i<=t;i++)cin>>x,s[x-1]='C',s[x]='H';

	cout<<"? CO\n";

	cout.flush();

	cin>>t;

	assert(t!=-1);

	for(int i=1,x;i<=t;i++)cin>>x,s[x-1]='C',s[x]='O';

	cout<<"? CC\n";

	cout.flush();

	cin>>t;

	assert(t!=-1);

	for(int i=1,x;i<=t;i++)cin>>x,s[x-1]=s[x]='C';

	cout<<"? HO\n";

	cout.flush();

	cin>>t;

	assert(t!=-1);

	for(int i=1,x;i<=t;i++)cin>>x,s[x-1]='H',s[x]='O';

	cout<<"? OO\n";

	cout.flush();

	cin>>t;

	assert(t!=-1);

	for(int i=1,x;i<=t;i++)cin>>x,s[x-1]=s[x]='O';

	for(int i=1;i<n-1;i++)if(s[i]==0)s[i]='H';

//	cout<<s[0]<<' '<<s[n-1]<<'\n';

	if(s[0]!=0&&s[n-1]!=0){

//		cout<<'\t'<<1<<'\n';

		cout<<"! "<<s<<'\n';

		cout.flush();

		goto label;

	}

	if(s[0]!=0){

//		cout<<'\t'<<2<<'\n';

		s[n-1]='H';

		cout<<"? "<<s<<'\n';

		cout.flush();

		cin>>t;

		assert(t!=-1);

		int x;

		if(t==1)cin>>x;

		else s[n-1]='C';

		cout<<"! "<<s<<'\n';

		cout.flush();

		goto label;

	}

	if(s[n-1]!=0){

//		cout<<'\t'<<3<<'\n';

		s[0]='H';

		cout<<"? "<<s<<'\n';

		cout.flush();

		cin>>t;

		assert(t!=-1);

		int x;

		if(t==1)cin>>x;

		else s[0]='O';

		cout<<"! "<<s<<'\n';

		cout.flush();

		goto label;

	}

//	cout<<'\t'<<4<<'\n';

	s[0]='H',s[n-1]='C';

	cout<<"? "<<s<<'\n';

	cout.flush();

	cin>>t;

	assert(t!=-1);

	int x;

	if(t==1)cin>>x,cout<<"! "<<s<<'\n',cout.flush();

	else{

		s[0]=s[n-1]='H';

		cout<<"? "<<s<<'\n';

		cout.flush();

		cin>>t;

		assert(t!=-1);

		if(t==1)cin>>x,cout<<"! "<<s<<'\n',cout.flush();

		else{

			s[0]='O',s[n-1]='H';

			cout<<"? "<<s<<'\n';

			cout.flush();

			cin>>t;

			assert(t!=-1);

			if(t==1)cin>>x,cout<<"! "<<s<<'\n',cout.flush();

			else{

				s[0]='O',s[n-1]='C';

				cout<<"! "<<s<<'\n',cout.flush();

			}

		}

	}

	label:;

	cin>>x;

	assert(x==1);

	return;

}

int main(){

	#ifndef zcz

//	czc;

	#endif

	int t=1;

	cin>>t;

	while(t--)solve();

	return 0;

}

/*

OCCCCHHHOOHHOHCOHCCOCCCHCOHHCOCC

         11111111112222222222333

12345678901234567890123456789012

CH:2 5 23

CO:4 15 19 25 29

CC:6 2 4 18 21 22 31

HO:2 8 12

OO:1 9

*/


D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
OutputCopy1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48

#include <bits/stdc++.h>

using namespace std;

int main() {

#ifdef _DEBUG

	freopen("input.txt", "r", stdin);

//	freopen("output.txt", "w", stdout);

#endif

	int t;

	cin >> t;

	while (t--) {

		int a, b, c;

		cin >> a >> b >> c;

		int ans = 1e9;

		int A = -1, B = -1, C = -1;

		for (int cA = 1; cA <= 2 * a; ++cA) {

			for (int cB = cA; cB <= 2 * b; cB += cA) {

				for (int i = 0; i < 2; ++i) {

					int cC = cB * (c / cB) + i * cB;

					int res = abs(cA - a) + abs(cB - b) + abs(cC - c);

					if (ans > res) {

						ans = res;

						A = cA;

						B = cB;

						C = cC;

					}

				}

			}

		}

		cout << ans << endl << A << " " << B << " " << C << endl;

	}

	return 0;

}


F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that:  They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li.  For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk].  The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k.   The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤15001≤n≤1500) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3

#include<bits/stdc++.h>

#define ll long long

#define flot(n) cout << setprecision(n) << setiosflags(ios::fixed) << setiosflags(ios::showpoint)

#define all(a) (a).begin() , (a).end()

#define pb push_back

#define mp make_pair

#define pii pair<int,int>

#define pll pair<ll,ll>

#define piii pair<pii,int>

#define plll pair<pll,ll>

#define R return

#define B break

#define C continue

#define SET(n , i) memset(n , i , sizeof(n))

#define SD ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)

#define rep(i , n) for(int i = 0 ; i < n ; i++)

#define repn(i , j , n) for(int i = j ; i < n ; i++)

#define repr(i,n,j) for(int i=n;i>=j;i--)

#define positive(x) ((x%mod+mod)%mod)

#define YES(f)cout<<((f)?"YES":"NO")<<endl

#define F first

#define S second

#define endl '\n'

#define vi vector<int>

//#define int ll

using namespace std;

void readFromFile(string input = "input.txt",string output="output.txt") {

    #ifndef ONLINE_JUDGE

        freopen(input.c_str(),"r",stdin);

        freopen(output.c_str(),"w",stdout);

    #endif

}

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());

ll rnd(ll x, ll y) {

    return uniform_int_distribution<ll>(x, y)(rng);

}

template <typename T> void Max(T& x,T y){x=max(x,y);}

template <typename T> void Min(T& x,T y){x=min(x,y);}

const int INF = 0x3f3f3f3f;

const ll INFLL = 0x3f3f3f3f3f3f3f3f;

const long double EPS = 1e-3;

const long double pi =  acos(-1.0);

const int mod = 998244353;

const int N =2e3+3;

ll Mul(ll x,ll y,ll mod=mod){R((x%mod)*(y%mod))%mod;}

ll Add(ll x,ll y,ll mod=mod){R((x%mod)+(y%mod)+2ll*mod)%mod;}

int n,a[N];

void solve() {

    cin >> n;

    rep(i,n)cin >> a[i];

    map<int,vector<pii>> ma;

    rep(i,n) {

        int sum=0;

        repn(j,i,n) {

            sum += a[j];

            ma[sum].pb({j,i});

        }

    }

    int ans=-1,sum=-1;

    for(auto &it:ma) {

        sort(all(it.S));

        int prv=-1,cot=0;

        for(auto &x:it.S) {

            if(x.S > prv) {

                cot++;

                prv=x.F;

            }

        }

        if(cot > ans) {

            ans = cot;

            sum=it.F;

        }

    }

    int prv=-1;

    vector<pii> v;

    for(auto &x:ma[sum]) {

        if(x.S > prv) {

            v.pb({x.S,x.F});

            prv=x.F;

        }

    }

    cout << v.size() << endl;

    for(auto [l,r]:v)cout<<l+1<<" "<<r+1<<endl;

}

int32_t main() {

    readFromFile();

    SD;

    int t = 1;

//    cin >> t;

//    scanf("%d",&t);

    rep(i,t) {

        solve();

    }

}


D. Trianglestime limit per test2 secondsmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.InputThe first line contains two non-negative integer numbers N and M (0 ≤ N ≤ 500; 0 ≤ M ≤ 500) — the number of red and blue points respectively. The following N lines contain two integer numbers each — coordinates of red points. The following M lines contain two integer numbers each — coordinates of blue points. All coordinates do not exceed 109 by absolute value.OutputOutput one integer — the number of distinct triangles with vertices in red points which do not contain any blue point inside.ExamplesInputCopy4 10 010 010 105 42 1OutputCopy2InputCopy5 55 106 18 6-6 -77 -15 -110 -4-10 -8-10 5-2 -8OutputCopy7

#include<bits/stdc++.h>

using namespace std;

inline int read(){

	int x=0,f=1;char ch=getchar();

	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}

	while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}

	return x*f;

}

const int N=1e3+5;int f[N][N];

struct node{long long x,y;}a[N],b[N];

bool cmp(node x,node y){return x.y<y.y;}

long long area(node a,node b,node c){

  return a.x*b.y-a.y*b.x+b.x*c.y-b.y*c.x+c.x*a.y-c.y*a.x;

}

bool toleft(node a,node b,node c){

  if(c.y<=a.y || c.y>b.y) return 0;

  return area(a,b,c)>0;

}

int n,m;

int main(){

	cin>>n>>m;

    for(int i=1;i<=n;++i)  scanf("%lld%lld",&a[i].x,&a[i].y);

    for(int i=1;i<=m;++i)  scanf("%lld%lld",&b[i].x,&b[i].y);

    sort(a+1,a+n+1,cmp);

	int ans=0;

    for(int i=1;i<n;++i)

      for(int j=i+1;j<=n;++j)

        for(int k=1;k<=m;++k)

          if(toleft(a[i],a[j],b[k])) f[i][j]++;

    for(int i=1;i<n;++i)

      for(int j=i+1;j<n;++j)

        for(int k=j+1;k<=n;++k)

          if(f[i][j]+f[j][k]==f[i][k]) ans++;

    printf("%d\n",ans);

    return 0;

}


B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
OutputCopy0
1
5
NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.

using namespace std;

#include <bits/stdc++.h>

#define int long long

#define repp(n) for(int i=0;i<n;i++)

#define mod 1000000007

void solve()

{

    int n;cin>>n;

    n*=2;

    int a[n+1];repp(n)cin>>a[i+1];

    a[0]=0;

    sort(a,a+n+1);

    int ans=mod;

    for(int i=1;i<n+1;i++){

        int j=2+(n-1)/2;

        //cout<<i<<" "<<j<<endl;

        if(j>i && j<n+1)

            ans=min(ans,a[j]-a[i]);

    }

    cout<<ans<<endl;

}

#define int int

int main()

{

    std::ios_base::sync_with_stdio(false);

    cin.tie(0);cout.tie(0);

    int t;cin>>t;while(t--)

    solve();

    return 0;

}


D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3
3 <<
7 >><>><
5 >>><
OutputCopy1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.

#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cmath>
#include <cstring>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <vector>

using namespace std;

#ifdef imtiyazrasool92
#include "algos/debug.h"
#else
#define dbg(...) 92
#endif

void run_case() {
    int N; string S;
    cin >> N >> S;

    vector<int> A(N);
    vector<int> B(N);

    iota(A.begin(), A.end(), 1);
    iota(B.begin(), B.end(), 1);

    reverse(A.begin(), A.end());

    for (int i = 0; i < N - 1;) {
        int end = i;
        while (end + 1 < N - 1 && S[end] == S[end + 1])
            end++;

        if (S[i] == '<')
            reverse(A.begin() + i, A.begin() + end + 2);
        else
            reverse(B.begin() + i, B.begin() + end + 2);

        i = end + 1;
    }

    for (auto &a : A)
        cout << a << ' ';

    cout << '\n';
    for (auto &b : B)
        cout << b << ' ';
}

int32_t main() {
    ios::sync_with_stdio(false);
#ifndef imtiyazrasool92
    cin.tie(nullptr);
#endif

    int tests = 1;
    cin >> tests;

    while (tests--) {
        run_case();
        cout << '\n';
    }

    return 0;
}


D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1≤n≤100000,1≤m≤109,1≤k≤81≤n≤100000,1≤m≤109,1≤k≤8) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1≤Li≤Ri≤m1≤Li≤Ri≤m) — the parameters of the ii spell.OutputPrint a single integer — the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third.

// LUOGU_RID: 97950406
//Writer: HugeWide

#include<bits/stdc++.h>

using namespace std;

typedef long long ll;

typedef double db;

inline ll read() {

	ll x=0,f=1;

	char ch=getchar();

	while(ch<'0'||ch>'9') {

		if(ch=='-') f=-f;

		ch=getchar();

	}

	while(ch>='0'&&ch<='9') {

		x=(x<<3)+(x<<1)+ch-'0';

		ch=getchar();

	}

	return x*f;

}

inline void write(ll x) {

	if(x<0) putchar('-'),x=-x;

	if(x>=10) write(x/10);

	putchar(x%10+'0');

}

#define writesp(x) write(x),putchar(' ')

#define writeln(x) write(x),putchar('\n')

#define rep(x,l,r) for(int x=l;x<=r;x++)

#define per(x,r,l) for(int x=r;x>=l;x--)

#define pb push_back

#define mp make_pair

#define all(v) v.begin(),v.end()

const int N=200200;

int n,m,k;

int l[N],r[N];

vector<int> raw;

int f[N][300];

vector<int> v[N];

bool vis[N];

int ppc(int s) {

	int r=0;

	while(s) {

		if(s&1) r++; s>>=1;

	} return r;

}

int g[300];

int main() {

	n=read(),m=read(),k=read();

	rep(i,1,n) l[i]=read()-1,r[i]=read();

	rep(i,1,n) raw.pb(l[i]),raw.pb(r[i]); raw.pb(-1e9);

	sort(all(raw)),raw.erase(unique(all(raw)),raw.end());

	rep(i,1,n) {

		l[i]=lower_bound(all(raw),l[i])-raw.begin();

		r[i]=lower_bound(all(raw),r[i])-raw.begin();

	}

	int T=(int)raw.size()-1;

	rep(i,1,n) {

		rep(j,l[i]+1,r[i]) v[j].pb(i);

	}

	rep(i,1,T) {

		int sz=v[i].size(),_sz=v[i-1].size();

		vector<int> d; d.clear(); int s=0;

		rep(j,0,sz-1) if(l[v[i][j]]+1==i) d.pb(j); int ds=d.size();

		rep(j,0,_sz-1) if(r[v[i-1][j]]!=i-1) s|=1<<j;

		rep(j,0,(1<<_sz)-1) g[j]=0;

		rep(j,0,(1<<_sz)-1) g[j&s]=max(g[j&s],f[i-1][j]);

		rep(j,0,(1<<_sz)-1) if((s&j)==j) rep(x,0,(1<<ds)-1) {

			rep(y,0,_sz-1) vis[v[i-1][y]]=(j>>y)&1;

			rep(y,0,ds-1) vis[v[i][d[y]]]=(x>>y)&1;

			int ss=0;

			rep(y,0,sz-1) if(vis[v[i][y]]) ss|=1<<y;

			f[i][ss]=max(f[i][ss],g[j]+(ppc(ss)%2)*(raw[i]-raw[i-1]));

		}

	}

	int ans=0;

	int sz=v[T].size();

	rep(i,0,(1<<sz)-1) ans=max(ans,f[T][i]);

	writeln(ans);

	return 0;

}