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;

}


C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3
-2 1
OutputCopy3 1 2 InputCopy5
1 1 1 1
OutputCopy1 2 3 4 5 InputCopy4
-1 2 2
OutputCopy-1

#include <bits/stdc++.h>

#include <ext/pb_ds/tree_policy.hpp>

#include <ext/pb_ds/assoc_container.hpp>

#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);

#define ll long long

#define ld long double

#define el "\n"

#define matrix vector<vector<int>>

#define pt complex<ld>

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

#define ordered_multiset tree<ll, null_type,less_equal<ll>, rb_tree_tag, tree_order_statistics_node_update>

using namespace __gnu_pbds;

using namespace std;

const ll N = 2e5 + 7, LOG = 20;

const ld pi = acos(-1);

const ll mod = 1e9 + 7;

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

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

ll n, m, k, x, y;

int a[N];

void dowork() {

    cin >> n;

    set<int> st;

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

        cin >> a[i];

        st.insert(i);

    }

    st.insert(n);

    int sum = 0;

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

        sum += a[i];

        while (st.size() && sum + *st.rbegin() > n) {

            st.erase(prev(st.end()));

        }

        while (st.size() && sum + *st.begin() < 1) {

            st.erase(st.begin());

        }

    }

    if (st.size() == 0) {

        cout << -1 << el;

        return;

    }

    vector<int> ans;

    ans.push_back(*st.begin());

    st.clear();

    st.insert(ans.back());

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

        st.insert(ans.back() + a[i]);

        ans.push_back(ans.back() + a[i]);

    }

    if (st.size() != n || *st.rbegin() > n || *st.begin() < 1) {

        cout << -1 << el;

        return;

    }

    for (auto j: ans) {

        cout << j << " ";

    }

    cout << el;

}

int main() {

    fast

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

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

    int t = 1;

    //cin >> t;

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

        dowork();

    }

}


E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j  — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres  — the maximum possible strength of the club.ExamplesInputCopy4 1 2
1 16 10 3
18
19
13
15
OutputCopy44
InputCopy6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
OutputCopy377
InputCopy3 2 1
500 498 564
100002 3
422332 2
232323 1
OutputCopy422899
NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1.

#include <bits/stdc++.h>
#include <bit>
#include <bitset>
#include <cstdint>
#define all(v) v.begin() ,v.end()
#define ll long long
using namespace std ;
ll dp[100005][(1<<7)+5]  ;
vector<pair <int , int>>all ;
int n, p ,  k ;
int s[100005][7] ;

ll solve (int idx ,  int msk){
    int cnt  = idx-__builtin_popcount(msk) ;
     ll &ans  =  dp[idx][msk] ;

    if (idx==n){
        if (msk==((1<<p)-1))return ans =  0 ;
                       return ans = -1e15 ;
    }
    if (~ans)return ans  ;
        ans  = 0 ;
          if (cnt<k)
          ans = solve(idx+1  ,msk)+all[idx].first ;
        else ans = solve(idx+1 , msk) ;
       for (int i = 0 ; i < p ; i++){
        if ((msk&(1<<i))==0){
            ans =  max (ans , solve(idx+1 , (msk|(1<<i)))+ s[all[idx].second][i]) ;
        }
    }
    return ans  ;
}
void acc(){
   cin>>n >>p>>k ;
    for (int i =0 ; i <n ; i++){
      int x ;cin>>x;
      all.push_back({x,i}) ;
    }
    sort(all(all)) ;
    reverse(all(all)) ;
    for (int i =0 ; i < n ; i++){
        for (int j =0 ; j < p ; j++){
            cin >>s[i][j] ;
        }
    }
    memset(dp,-1 , sizeof dp) ;
    cout <<solve(0,0) ;

}
int main (){
    int t =1 ;
    //cin >>t;
    while (t--)acc() ;

}


B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2
3
3 2 1
6
3 1 4 1 5 9
OutputCopy3
5
NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9].

#include <bits/stdc++.h>

using namespace std;

#define ll long long

int main() {

    ios_base::sync_with_stdio(false);

    cin.tie(0);

    int t;

    cin >> t;

    while (t--) {

        unordered_set<int> ue;

        int n;

        cin >> n;

        while (n--) {

            int v;

            cin >> v;

            ue.insert(v);

        }

        cout << ue.size() << "\n";

    }

}


G. Seollaltime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIt is only a few days until Seollal (Korean Lunar New Year); and Jaehyun has invited his family to his garden. There are kids among the guests. To make the gathering more fun for the kids, Jaehyun is going to run a game of hide-and-seek.The garden can be represented by a n×mn×m grid of unit cells. Some (possibly zero) cells are blocked by rocks, and the remaining cells are free. Two cells are neighbors if they share an edge. Each cell has up to 4 neighbors: two in the horizontal direction and two in the vertical direction. Since the garden is represented as a grid, we can classify the cells in the garden as either "black" or "white". The top-left cell is black, and two cells which are neighbors must be different colors. Cell indices are 1-based, so the top-left corner of the garden is cell (1,1)(1,1).Jaehyun wants to turn his garden into a maze by placing some walls between two cells. Walls can only be placed between neighboring cells. If the wall is placed between two neighboring cells aa and bb, then the two cells aa and bb are not neighboring from that point. One can walk directly between two neighboring cells if and only if there is no wall directly between them. A maze must have the following property. For each pair of free cells in the maze, there must be exactly one simple path between them. A simple path between cells aa and bb is a sequence of free cells in which the first cell is aa, the last cell is bb, all cells are distinct, and any two consecutive cells are neighbors which are not directly blocked by a wall.At first, kids will gather in cell (1,1)(1,1), and start the hide-and-seek game. A kid can hide in a cell if and only if that cell is free, it is not (1,1)(1,1), and has exactly one free neighbor. Jaehyun planted roses in the black cells, so it's dangerous if the kids hide there. So Jaehyun wants to create a maze where the kids can only hide in white cells.You are given the map of the garden as input. Your task is to help Jaehyun create a maze.InputYour program will be judged in multiple test cases.The first line contains the number of test cases tt. (1≤t≤1001≤t≤100). Afterward, tt test cases with the described format will be given.The first line of a test contains two integers n,mn,m (2≤n,m≤202≤n,m≤20), the size of the grid.In the next nn line of a test contains a string of length mm, consisting of the following characters (without any whitespace):   O: A free cell.  X: A rock. It is guaranteed that the first cell (cell (1,1)(1,1)) is free, and every free cell is reachable from (1,1)(1,1). If t≥2t≥2 is satisfied, then the size of the grid will satisfy n≤10,m≤10n≤10,m≤10. In other words, if any grid with size n>10n>10 or m>10m>10 is given as an input, then it will be the only input on the test case (t=1t=1).OutputFor each test case, print the following:If there are no possible mazes, print a single line NO.Otherwise, print a single line YES, followed by a grid of size (2n−1)×(2m−1)(2n−1)×(2m−1) denoting the found maze. The rules for displaying the maze follows. All cells are indexed in 1-base.  For all 1≤i≤n,1≤j≤m1≤i≤n,1≤j≤m, if the cell (i,j)(i,j) is free cell, print 'O' in the cell (2i−1,2j−1)(2i−1,2j−1). Otherwise, print 'X' in the cell (2i−1,2j−1)(2i−1,2j−1).  For all 1≤i≤n,1≤j≤m−11≤i≤n,1≤j≤m−1, if the neighboring cell (i,j),(i,j+1)(i,j),(i,j+1) have wall blocking it, print ' ' in the cell (2i−1,2j)(2i−1,2j). Otherwise, print any printable character except spaces in the cell (2i−1,2j)(2i−1,2j). A printable character has an ASCII code in range [32,126][32,126]: This includes spaces and alphanumeric characters.  For all 1≤i≤n−1,1≤j≤m1≤i≤n−1,1≤j≤m, if the neighboring cell (i,j),(i+1,j)(i,j),(i+1,j) have wall blocking it, print ' ' in the cell (2i,2j−1)(2i,2j−1). Otherwise, print any printable character except spaces in the cell (2i,2j−1)(2i,2j−1)  For all 1≤i≤n−1,1≤j≤m−11≤i≤n−1,1≤j≤m−1, print any printable character in the cell (2i,2j)(2i,2j). Please, be careful about trailing newline characters or spaces. Each row of the grid should contain exactly 2m−12m−1 characters, and rows should be separated by a newline character. Trailing spaces must not be omitted in a row.ExampleInputCopy4
2 2
OO
OO
3 3
OOO
XOO
OOO
4 4
OOOX
XOOX
OOXO
OOOO
5 6
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OutputCopyYES
OOO
  O
OOO
NO
YES
OOOOO X
  O O
X O O X
  O
OOO X O
O O   O
O OOOOO
YES
OOOOOOOOOOO
  O   O   O
OOO OOO OOO
O   O   O
OOO OOO OOO
  O   O   O
OOO OOO OOO
O   O   O
OOO OOO OOO

#include<bits/stdc++.h>

using namespace std;

typedef long long LL;

typedef unsigned long long uLL;

typedef pair<LL,LL> pii;

#define MAXN 100005

#define pb push_back

#define mkpr make_pair

#define fir first

#define sec second

#define lson (rt<<1)

#define rson (rt<<1|1)

#define lowbit(x) (x&-x)

const int mo=998244353;

const int inv2=5e8+4;

const int jzm=2333;

const int zero=15;

const int INF=0x3f3f3f3f;

const double Pi=acos(-1.0);

const double eps=1e-9;

const int orG=3,ivG=332748118;

template<typename _T>

_T Fabs(_T x){return x<0?-x:x;}

template<typename _T>

void read(_T &x){

    _T f=1;x=0;char s=getchar();

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

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

    x*=f;

}

int add(int x,int y,int p){return x+y<p?x+y:x+y-p;}

void Add(int &x,int y,int p){x=add(x,y,p);}

int qkpow(int a,int s,int p){int t=1;while(s){if(s&1)t=1ll*a*t%p;a=1ll*a*a%p;s>>=1;}return t;}

int n,m,TT,id[25][25],idx,col[405],cnt,head[1005],tot;

int dis[1005],cntp,S,T,deg[405],fa[405],pre[405];

char maze[25][25],ans[45][45];bool used[1005],lk[405],answered[105];queue<int>q;

struct ming{int u,v,x,y;}s[1005];

struct edge{int to,nxt;}e[MAXN*10];

void addEdge(int u,int v){e[++tot]=(edge){v,head[u]};head[u]=tot;}

void makeSet(int x){for(int i=1;i<=x;i++)fa[i]=i;}

int findSet(int x){return x==fa[x]?x:fa[x]=findSet(fa[x]);}

void unionSet(int x,int y){int u=findSet(x),v=findSet(y);if(fa[u]^v)fa[u]=v;}

int main(){

    read(TT);int allTT=TT;

    while(TT--){

        read(n);read(m);

        for(int i=1;i<=n;i++)scanf("%s",maze[i]+1);

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

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

                if(maze[i][j]=='O')

                    id[i][j]=++idx,col[idx]=(i+j)&1;

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

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

                if(id[i][j]&&id[i][j+1])

                    s[++cntp]=(ming){id[i][j],id[i][j+1],i+i-1,j+j};

                if(id[i][j]&&id[i+1][j])

                    s[++cntp]=(ming){id[i][j],id[i+1][j],i+i,j+j-1};

            }

        cnt=cntp;S=++cnt;T=++cnt;

        //puts("over init");

        while(1){

            //puts("extending");

            for(int i=1;i<=cnt;i++)head[i]=0;tot=0;

            for(int i=1;i<=idx;i++)deg[i]=0;makeSet(idx);

            for(int i=1;i<=cntp;i++)if(used[i])

                unionSet(s[i].u,s[i].v),deg[s[i].u]++,deg[s[i].v]++;

            for(int i=1;i<=cntp;i++)if(!used[i]){

                int u=s[i].u,v=s[i].v;if(findSet(u)!=findSet(v))addEdge(S,i);

                if((col[u]||deg[u]<2)&&(col[v]||deg[v]<2)&&u!=1)addEdge(i,T);

            }

            for(int i=1;i<=cntp;i++)if(used[i]){

                makeSet(idx);deg[s[i].u]--;deg[s[i].v]--;

                for(int j=1;j<=cntp;j++)if(used[j]&&i!=j)unionSet(s[j].u,s[j].v);

                for(int j=1;j<=cntp;j++)if(!used[j]){

                    int u=s[j].u,v=s[j].v;if(u==1)continue;

                    if(findSet(u)!=findSet(v))addEdge(i,j);

                    if((col[u]||deg[u]<2)&&(col[v]||deg[v]<2))addEdge(j,i);

                }

                deg[s[i].u]++;deg[s[i].v]++;

            }

            //puts("over graph building");

            for(int i=1;i<=cnt;i++)dis[i]=pre[i]=0;dis[S]=1;

            while(!q.empty())q.pop();q.push(S);

            while(!q.empty()){

                int u=q.front();q.pop();

                for(int i=head[u];i;i=e[i].nxt){

                    int v=e[i].to;if(dis[v])continue;

                    q.push(v);dis[v]=dis[u]+1;pre[v]=u;

                }

            }

            //puts("over bfs");

            if(!dis[T])break;int now=pre[T];

            while(now^S)used[now]^=1,now=pre[now];

        }

        //puts("over solve");

        for(int i=1;i<=idx;i++)deg[i]=0;makeSet(idx);

        for(int i=1;i<=cntp;i++)if(used[i])

            deg[s[i].u]++,deg[s[i].v]++,unionSet(s[i].u,s[i].v);

            //printf("use edge %d %d\n",s[i].u,s[i].v);

        //for(int i=1;i<=idx;i++)printf("%d ",col[i]);puts("");

        //for(int i=1;i<=idx;i++)printf("%d ",deg[i]);puts("");

        bool flag=0;for(int i=2;i<=idx;i++)if(!col[i])flag|=(deg[i]<2);

        if(flag){

            //if(allTT!=100||!answered[6]||answered[5]||answered[4])

                puts("NO");

            //else if(allTT-TT==87){

            //    for(int i=1;i<=n;i++,puts(""))

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

            //            printf("%c",maze[i][j]);

            //}

        }

        else{

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

                for(int j=1;j<m+m;j++)ans[i][j]=' ';

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

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

                    ans[i+i-1][j+j-1]=maze[i][j];

            //for(int i=1;i<n+n;i++,puts(""))

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

            //        printf("%c",ans[i][j]);

            //for(int i=1;i<=idx;i++)printf("%d ",col[i]);puts("");

            for(int i=1;i<=cntp;i++)if(findSet(s[i].u)^findSet(s[i].v))

                used[i]=1,unionSet(s[i].u,s[i].v);

            for(int i=1;i<=cntp;i++)if(used[i])

                ans[s[i].x][s[i].y]='O';

            //answered[allTT-TT]=1;

            //if(allTT!=100||!answered[6]||answered[5]||answered[4]){

                puts("YES");

                for(int i=1;i<n+n;i++,puts(""))

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

                        printf("%c",ans[i][j]),ans[i][j]=0;

            //}

        }

        for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)id[i][j]=maze[i][j]=0;

        for(int i=1;i<=cntp;i++)used[i]=lk[i]=0;

        for(int i=1;i<=idx;i++)col[i]=0;idx=cntp=cnt=0;

    }

    return 0;

}


C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109),  — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109)  — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2)  — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2
1 1 2
2 1
OutputCopy1
InputCopy2 2 999999937
2 1
3 1
OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.

#include<bits/stdc++.h>
using namespace std;
#define int long long
int n, m, p;
signed main()
{
cin.sync_with_stdio(false);
cin.tie(0);
cin >> n >> m >> p;
int a = -1, b = -1;
for(int x, i = 0; i < n; i++)
{
cin >> x;
if(x % p && a == -1) a = i;
}
for(int x, i = 0; i < m; i++)
{
cin >> x;
if(x % p && b == -1) b = i;
}
cout << a + b;
return 0;
}


D. Tourismtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha lives in a country with nn cities numbered from 11 to nn. She lives in the city number 11. There is a direct train route between each pair of distinct cities ii and jj, where i≠ji≠j. In total there are n(n−1)n(n−1) distinct routes. Every route has a cost, cost for route from ii to jj may be different from the cost of route from jj to ii.Masha wants to start her journey in city 11, take exactly kk routes from one city to another and as a result return to the city 11. Masha is really careful with money, so she wants the journey to be as cheap as possible. To do so Masha doesn't mind visiting a city multiple times or even taking the same route multiple times.Masha doesn't want her journey to have odd cycles. Formally, if you can select visited by Masha city vv, take odd number of routes used by Masha in her journey and return to the city vv, such journey is considered unsuccessful.Help Masha to find the cheapest (with minimal total cost of all taken routes) successful journey.InputFirst line of input had two integer numbers n,kn,k (2≤n≤80;2≤k≤102≤n≤80;2≤k≤10): number of cities in the country and number of routes in Masha's journey. It is guaranteed that kk is even.Next nn lines hold route descriptions: jj-th number in ii-th line represents the cost of route from ii to jj if i≠ji≠j, and is 0 otherwise (there are no routes i→ii→i). All route costs are integers from 00 to 108108.OutputOutput a single integer — total cost of the cheapest Masha's successful journey.ExamplesInputCopy5 8
0 1 2 2 0
0 0 1 1 2
0 1 0 0 0
2 1 1 0 0
2 0 1 2 0
OutputCopy2
InputCopy3 2
0 1 1
2 0 1
2 2 0
OutputCopy3

#include <bits/stdc++.h>

using namespace std;

#define int long long

#define mid ((l+r)>>1)

#define mod (998244353)

#define eps (1e-8)

#define mk make_pair

#define tim (double)clock()/CLOCKS_PER_SEC

#define For(i,a,b) for(int i=(a);i<=(b);++i)

#define rep(i,a,b) for(int i=(a);i>=(b);--i)

inline namespace IO{

	inline int read(){

		int x=0,f=1;char ch;

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

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

		return x*f;

	}

	void write(char x){putchar(x);}

	void write(const char *x){for(;*x;++x)putchar(*x);}

	void write(char *x){for(;*x;++x)putchar(*x);}

	void write(signed x){

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

		if(x>9)write(x/10); putchar('0'+x-x/10*10);

	}

	void write(long long x){

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

		if(x>9)write(x/10); putchar('0'+x-x/10*10);

	}

	void write(unsigned long long x){

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

		putchar('0'+x-x/10*10);

	}

	void write(double x){printf("%0.9lf",x);}

	template<typename type1,typename type2,typename ...typen>

	void write(type1 a1,type2 a2,typen ...an){

		write(a1);

		write(a2,an...);

	}

}using namespace IO;

inline int gcd(int x,int y){return y==0?x:gcd(y,x%y);}

inline int lcm(int x,int y){return x/gcd(x,y)*y;}

inline int lowbit(int x){return x&(-x);}

mt19937 rnd(time(NULL)^clock());

inline int rad(int x,int y){return rnd()%(y-x+1)+x;}

const int N=105;

int n,k;

int a[N][N];

int c[N];

int dis[N][12],vis[N][12];

int ans=1e18;

queue<pair<int,int>> q;

inline void spfa(int s){

	while(!q.empty())q.pop();

	memset(dis,0x3f,sizeof(dis));

	memset(vis,0,sizeof(vis));

	q.push(mk(s,0)); vis[s][0]=1,dis[s][0]=0;

	while(!q.empty()){

		int x=q.front().first,t=q.front().second; q.pop();

		vis[x][t]=0;

		if(t==k)continue;

		For(y,1,n)if(c[x]!=c[y]&&y!=x){

			int w=a[x][y];

			if(t+1==k&&y==1)ans=min(ans,dis[x][t]+w);

			if(dis[y][t+1]>dis[x][t]+w){

				dis[y][t+1]=dis[x][t]+w;

				if(!vis[y][t+1]){vis[y][t+1]=1;q.push(mk(y,t+1));}

			}

		}

	}

}

signed main()

{

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

	For(i,1,n)For(j,1,n)a[i][j]=read();

	For(t,1,5000){

		For(i,1,n)c[i]=rad(0,1);

		spfa(1);

	}

	write(ans,'\n');

	return 0;

}

/*

*/


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>

#define f first

#define s second

#define int long long

#define pii pair<int,int>

using namespace std;

const int N = 6e5 + 5, mod = 1e9 + 7; // !

int  pos[N], a[N], P[N];

vector<pair<int,int>> x;

pair<int,int> p[N];

struct node {

    int c, pr, sf, ans;

} t[4 * N];

node merge(node a, node b) {

    node c;

    c.c = a.c + b.c;

    c.pr = (a.pr + b.pr * P[a.c]) % mod;

    c.sf = (b.sf + a.sf * P[b.c]) % mod;

    c.ans = (a.ans * P[b.c] % mod + b.ans * P[a.c] % mod + a.pr * b.sf % mod) % mod;

    return c;

}

void upd(int u, int id, int l, int r) {

    if(l > id || r < id) return;

    if(l == r) {

        t[u].c ^= 1;

        t[u].pr = t[u].sf = pos[l * t[u].c];

        return;

    }

    int mid = (l + r) / 2;

    upd(2 * u, id, l, mid); upd(2 * u + 1, id, mid + 1, r);

    t[u] = merge(t[2 * u], t[2 * u + 1]);

}

int ID(int a, int b) {

    return (lower_bound(x.begin(), x.end(), make_pair(a, b)) - x.begin() + 1);

}

int pwr(int u, int v) {

    int ans = 1;

    while(v) {

        if(v % 2) ans = ans * u  % mod;

        v /= 2;

        u = u * u % mod;

    }

    return ans;

}

main(){

    int n;

    cin >> n; P[0] = 1;

    for(int i = 1; i <= n; i++) cin >> a[i], P[i] = P[i - 1] * 2 % mod, x.push_back({a[i], i});

    int q; cin >> q;

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

        cin >> p[i].f >> p[i].s;

        x.push_back({p[i].s, p[i].f});

//        P[i] = P[i - 1] * 2 % mod;

    }

    sort(x.begin(), x.end());

    x.erase(unique(x.begin(), x.end()), x.end());

    for(int i = 0; i < x.size(); i++) pos[i + 1] = x[i].f;

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

//        cout << ID(a[i], i) << " _ " << pos[ID(a[i], i)]<< endl;

        upd(1, ID(a[i], i), 1, (int)x.size());

//        cout << t[1].ans << endl;

    }

    int D =  pwr(P[n], mod - 2);

    cout << t[1].ans * D % mod << "\n";

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

        upd(1, ID(a[p[i].f], p[i].f), 1, x.size());

        a[p[i].f] = p[i].s;

        upd(1, ID(a[p[i].f], p[i].f), 1, x.size());

        cout << t[1].ans * D % mod << "\n";

    }

 }


B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.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.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6
1
10
19
9876
12345
1000000000
OutputCopy1
11
21
10973
13716
1111111111

#include <bits/stdc++.h>

using namespace std;

int main(){

    int n;

    cin >> n;

    while(n--){

        int a;

        cin >> a;

        int sisa=0;

        int ans=0;

        while((a+sisa)>=10){

            sisa=a/10;

            ans+=(a/10)*10;

            a%=10;

            a+=sisa;

        }

        cout << ans+a << endl;

    }

}


A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way:  Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x;  choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.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. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.

#include <iostream>

#include <queue>

#include <cmath>

#include <cstring>

#define int long long int

const int M = 86028121 ;

using namespace std ;

int32_t main()

{

        int t ;

        cin >> t ;

        while(t--)

        {

            int a , b ;

            cin >> a >> b ;

            if(a==b)

            {

                cout << 0 << endl ;

            }

            else if(a<b)

            {

                int d = b-a ;

                if(d%2==1)

                {

                    cout << 1 << endl ;

                }

                else

                {

                    cout << 2 << endl ;

                }

            }

            else

            {

                int d = a-b ;

                 if(d%2==0)

                {

                    cout << 1 << endl ;

                }

                else

                {

                    cout << 2 << endl ;

                }

            }

        }

    return 0 ;

}


B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3
SET
ETS
TSE
OutputCopy1InputCopy3 4
SETE
ETSE
TSES
OutputCopy0InputCopy5 4
SETT
TEST
EEET
ESTE
STES
OutputCopy2NoteIn the third example test; these two triples of cards are sets:  "SETT"; "TEST"; "EEET"  "TEST"; "ESTE", "STES"

#include<bits/stdc++.h>

#define ll long long

#define mod (ll)1000000007

using namespace std;

unordered_map<string,vector<int>> f;

int main()

{

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    int n,k;

    cin>>n>>k;

    string s;

    vector<string> a(n);

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

        cin>>s;

        f[s].push_back(i);

        a[i] = s;

    }

    ll ans = 0;

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

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

            // cout<<"a[i]:"<<a[i]<<",a[j]:"<<a[j]<<"\n";

            string t = "";

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

                int S = 0, E = 0, T= 0;

                if(a[i][p] == 'S')

                    S++;

                else if(a[i][p] == 'E') E++;

                else

                    T++;

                if(a[j][p] == 'S')

                    S++;

                else if(a[j][p] == 'E')

                    E++;

                else

                    T++;

                // cout<<"S:"<<S<<",T:"<<T<<",E:"<<E<<"\n";

                if(S == 2){

                    t+='S';

                }

                else if(T == 2){

                    t+='T';

                }

                else if(E == 2){

                    t+= 'E';

                }

                else if(S == 1 && E == 1){

                    t += 'T';

                }

                else if(S == 1 && T == 1){

                    t+='E';

                }

                else

                    t+='S';

            }

            // f[a[i]]--;

            // f[a[j]]--;

            if(f.find(t) != f.end()){

                int ft = upper_bound(f[t].begin(),f[t].end(),j) - f[t].begin();

                ans += (int)f[t].size()-ft;

            }

            // cout<<"t:"<<t<<"\n";

            // f[a[i]]++;

            // f[a[j]]--;

        }

    }

    cout<<ans<<"\n";

    return 0;

}


#include <bits/stdc++.h>

using namespace std;

const int N = 1505;

int sums[N];

void solve() {

    int n;

    cin >> n;

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

        cin >> sums[i];

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

    }

    unordered_map<int, vector<pair<int, int>>> pos;

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

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

            pos[sums[j] - sums[i - 1]].emplace_back(i, j);

        }

    }

    int cnt = 0, val = 0;

    for (auto &[v, vec] : pos) {

        if (vec.size() < cnt) continue;

        sort(vec.begin(), vec.end(), [](auto &x, auto &y) { // se越靠前越好

            return x.second < y.second;

        });

        int last = -1, cur = 0;

        for (auto &[fi, se] : vec) {

            if (fi <= last) continue;

            ++cur;

            last = se;

        }

        if (cur > cnt) {

            cnt = cur;

            val = v;

        }

    }

    cout << cnt << '\n';

    int last = -1;

    for (auto &[fi, se] : pos[val]) {

        if (fi <= last) continue;

        cout << fi << ' ' << se << '\n';

        last = se;

    }

}

int main() {

    cin.tie(0)->sync_with_stdio(0);

    solve();

    return 0;

}


C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math; so he asks for your help.The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer — minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1

#pragma optimize("Bismillahirrahmanirrahim")
//█▀█─█──█──█▀█─█─█
//█▄█─█──█──█▄█─█■█
//█─█─█▄─█▄─█─█─█─█
//Allahuekber
//ahmet23 orz...
//Sani buyuk Osman Pasa Plevneden cikmam diyor.
//FatihSultanMehmedHan
//YavuzSultanSelimHan
//AbdulhamidHan
#define author tolbi
#include <bits/stdc++.h>
#ifdef LOCAL
	#include "23.h"
#endif
#define int long long
#define endl '\n'
#define vint(x) vector<int> x
#define deci(x) int x;cin>>x;
#define decstr(x) string x;cin>>x;
#define cinarr(x) for (auto &it : x) cin>>it;
#define coutarr(x) for (auto &it : x) cout<<it<<" ";cout<<endl;
#define sortarr(x) sort(x.begin(),x.end())
#define sortrarr(x) sort(x.rbegin(),x.rend())
#define det(x) cout<<"NO\0YES"+x*3<<endl;
#define INF LONG_LONG_MAX
#define rev(x) reverse(x.begin(),x.end());
#define ios ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define tol(bi) (1LL<<((int)(bi)))
const int MOD = 1e9+7;
using namespace std;
mt19937 ayahya(chrono::high_resolution_clock().now().time_since_epoch().count());
int32_t main(){
	ios;
	int t=1;
	int tno = 0;
	if (!t) cin>>t;
	while (t-(tno++)){
		deci(n);
		vint(arr(n));
		cinarr(arr);
		vector<int> barr;
		map<int,bool> mp;
		for (int i = 0; i < n; ++i)
		{
			mp[arr[i]]=true;
		}
		for (auto it : mp) {
			barr.push_back(it.first);
		}
		vector<vector<int>> dp(2,vector<int>(barr.size(),-1));
		dp[0].back()=abs(arr.back()-barr.back());
		for (int i = barr.size()-2; i >= 0; i--){
			dp[0][i]=min(dp[0][i+1],abs(arr.back()-barr[i]));
		}
		for (int i = n-2; i >= 0; i--){
			dp[1].back()=abs(arr[i]-barr.back())+dp[0].back();
			for (int j = barr.size()-2; j >= 0; j--){
				dp[1][j] = min(dp[1][j+1],dp[0][j]+abs(arr[i]-barr[j]));
			}
			swap(dp[0],dp[1]);
		}
		cout<<dp[0][0]<<endl;
	}
}


B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.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.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5
3
1 2 1
5
1 2 2 3 2
3
1 1 2
4
1 2 2 1
10
1 1 2 2 3 3 4 4 5 5
OutputCopyYES
YES
NO
YES
NO
NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.

//MD SHARIQUE HUSSAIN 2112015
#include <iostream>
#include <math.h>
#include <vector>
#include <map>
#include <set>
#include<iomanip>
#include<algorithm>
#include<utility>
#include<set>
#include<unordered_set>
#include<list>
#include<iterator>
#include<deque>
#include<queue>
#include<stack>
#include<bitset>
#include<random>
#include<stdio.h>
#include<complex>
#include<cstring>
#include<chrono>
#include<string>
#include <unordered_map>
//header file ended
using namespace std;
#define INF 1e18
#define pb push_back
#define pll pair <ll,ll>
#define ppb pop_back
#define mp make_pair
#define ff first
#define ss second
#define mod1 1000000007
#define mod2 998244353
#define PI 3.141592653589793238462
#define vch vector<char>
#define vll vector<ll>
#define vbb vector<bool>
#define vst vector<string>
#define mll map<ll,ll>
#define mcl map<char,ll>
#define mlc map<ll,char>
#define msl map<string,ll>
#define si set<int>
#define usi unordered_set<int>
#define msi multiset<int>
#define  pqsmall priority_queue <ll,vll,greater<ll> >
#define  pqlarge priority_queue <ll>
#define nl '\n'
typedef long long ll;
typedef unsigned long long ull;
typedef long double lld;
#define all(x) (x).begin(), (x).end()
//--------------------------------------------------------------//// nCr starts ////---------------------------------------------------------------
ll powerM(ll a,ll b,ll m){ll res = 1;while(b){if(b & 1){res = (res * a) % m;}a = (a * a) % m;b >>= 1;}return res;}
ll modInverse(ll a , ll m){return powerM(a , m - 2 , m);}
ll nCrModPFermat(ll n , ll r , ll p){if(r == 0){return 1;}ll fac[n + 1];fac[0] = 1;for(ll i = 1; i <= n; ++i){fac[i] = (fac[i - 1] * i) % p;}return (fac[n] * modInverse(fac[r] , p) % p * modInverse(fac[n - r] , p) % p) % p;}
//--------------------------------------------------------------//// nCr ends ////-----------------------------------------------------------------
bool cmp(pair<ll,ll> a,pair<ll,ll> b){if (a.ff!=b.ff){return a.ff>b.ff;}else{return a.ss<b.ss;}}
int gcd(int a, int b){return b == 0 ? a : gcd(b, a % b);}
ll power(ll a,ll n){ll ct=0;if (!(a%n)){while (a%n==0){a/=n;ct++;}}return ct;}
int computeXOR(int n){if (n % 4 == 0)return n;if (n % 4 == 1)return 1;if (n % 4 == 2)return n + 1;return 0;}
void seive1(bool vb[],ll n) {vb[0]=vb[1]=1;for(int i=2;(i*i)<n;i++){if (vb[i]==0){for (int j = i*i; j < n; j+=i){vb[j]=1;}}}}
ll celi(ll a,ll b){return (a+b-1)/b;}
ll modulas(ll i,ll m){return ((i%m)+m)%m;}
ll flor(ll a,ll b){return (a)/b;}
ll moduler_expo(ll a,ll n,ll m){ll x=1,pow=a%m;while (n){if (n&1){x=(x*pow)%m;}pow=(pow*pow)%m;n=n>>1;}return x;}
void fact(ll n,vector<pll> &vp1){for(ll i=2;i*i<=n;i++){if(n%i==0){ll ct=0;while (n%i==0){ct++;n/=i;}vp1.pb(mp(i,ct));}}if(n>1)vp1.pb(mp(n,1));}
ll multi_inv(ll r1,ll r2){ll q,r,t1=0,t2=1,t,m=r1;while (r2 > 0){q=r1/r2;r=r1%r2;t=1-(q*t2);r1=r2;r2=r;t1=t2;t2=t;}if (t1<0){ll a=abs(t1/m);a++;a=a*m;t1=a+t1;}return t1;}
#define rsort(a) sort(a, a + n, greater<int>())
#define rvsort(a) sort(all(a), greater<int>())
#define FOR(i, a, b) for (auto i = a; i < b; i++)
#define rFOR(a, b) for (auto i = a; i >= b; i--)
#define read(a , n) for(int i = 0  ; i <  n ; i ++){cin >> a[i];}
const ll N=1e7;
void sol()
{
    ll n,flag=0;cin>>n;
    map <ll,vll> m1;
    FOR(i,0,n)
    {
        ll x;cin>>x;
        m1[x].pb(i);
        if(m1[x].size()>2)
        {
            flag=1;
        }
    }
    if(flag==1)
    {
        cout<<"YES\n";
        return;
    }
    if(m1.size()==n)
    {
        cout<<"NO\n";
        return;
    }
    for(auto &val : m1)
    {
        ll sz=val.ss.size();
        FOR(i,0,sz-1)
        {
            if(val.ss[i+1]-val.ss[i]>1)
            {
                cout<<"YES\n";
                return;
            }
        }
    }
    cout<<"NO\n";
}
int32_t main()
{
    #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w", stdout);
    #endif
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int t;
    cin>>t;
    while(t--)
    {
        sol();
    }
    return 0;
}


F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by nn castles, the ii-th castle is defended by aiai soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.Each attack must target a castle with at least one alive defender in it. There are three types of attacks:  a mixed attack decreases the number of defenders in the targeted castle by xx (or sets it to 00 if there are already less than xx defenders);  an infantry attack decreases the number of defenders in the targeted castle by yy (or sets it to 00 if there are already less than yy defenders);  a cavalry attack decreases the number of defenders in the targeted castle by zz (or sets it to 00 if there are already less than zz defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.Then, the test cases follow. Each test case is represented by two lines. The first line contains four integers nn, xx, yy and zz (1≤n≤3⋅1051≤n≤3⋅105, 1≤x,y,z≤51≤x,y,z≤5). The second line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤10181≤ai≤1018).It is guaranteed that the sum of values of nn over all test cases in the input does not exceed 3⋅1053⋅105.OutputFor each test case, print the answer to it: the number of possible options for the first attack of the White King (or 00, if the Black King can launch the last attack no matter how the White King acts).ExamplesInputCopy3
2 1 3 4
7 6
1 1 2 3
1
1 1 2 2
3
OutputCopy2
3
0
InputCopy10
6 5 4 5
2 3 2 3 1 3
1 5 2 3
10
4 4 2 3
8 10 8 5
2 2 1 4
8 5
3 5 3 5
9 2 10
4 5 5 5
2 10 4 2
2 3 1 4
1 10
3 1 5 3
9 8 7
2 5 4 5
8 8
3 5 1 4
5 5 10
OutputCopy0
2
1
2
5
12
5
0
0
2

#include<bits/stdc++.h>

using namespace std;

const int N = 300043;

const int K = 5;

int x, y, z, n;

long long a[N];

typedef vector<vector<int> > state;

map<state, int> d;

int cnt;

int p;

vector<vector<int> > state_log;

int mex(const vector<int>& a)

{

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

    {

        bool f = false;

        for(auto x : a)

            if(x == i)

                f = true;

        if(!f)

            return i;

    }

    return a.size();

}

state go(state s)

{

    int f1 = mex({s[0][K - x], s[1][K - y], s[2][K - z]});

    int f2 = mex({s[0][K - x], s[2][K - z]});

    int f3 = mex({s[0][K - x], s[1][K - y]});

    state nw = s;

    nw[0].push_back(f1);

    nw[1].push_back(f2);

    nw[2].push_back(f3);

    for(int i = 0; i < 3; i++)

        nw[i].erase(nw[i].begin());

    return nw;

}

void precalc()

{

    d.clear();

    state cur(3, vector<int>(K, 0));

    cnt = 0;

    state_log.clear();

    while(!d.count(cur))

    {

        d[cur] = cnt;

        state_log.push_back({cur[0].back(), cur[1].back(), cur[2].back()});

        cur = go(cur);

        cnt++;

    }

    p = cnt - d[cur];

}

int get_grundy(long long x, int t)

{

    if(x < cnt)

        return state_log[x][t];

    else

    {

        int pp = cnt - p;

        x -= pp;

        return state_log[pp + (x % p)][t];

    }

}

void read()

{

    scanf("%d %d %d %d", &n, &x, &y, &z);

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

        scanf("%lld", &a[i]);

}

int check(int x, int y)

{

    return x == y ? 1 : 0;

}

void solve()

{

    precalc();

    int ans = 0;

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

        ans ^= get_grundy(a[i], 0);

    int res = 0;

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

    {

        ans ^= get_grundy(a[i], 0);

        res += check(ans, get_grundy(max(0ll, a[i] - x), 0));

        res += check(ans, get_grundy(max(0ll, a[i] - y), 1));

        res += check(ans, get_grundy(max(0ll, a[i] - z), 2));

        ans ^= get_grundy(a[i], 0);

    }

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

}

int main()

{

    int t;

    scanf("%d", &t);

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

    {

        read();

        solve();

    }

}


C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyber world.His target is a network of nn small gangs. This network contains exactly n−1n−1 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 00 to n−2n−2 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass SS password layers, with SS being defined by the following formula:S=∑1≤u<v≤nmex(u,v)S=∑1≤u<v≤nmex(u,v)Here, mex(u,v)mex(u,v) denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang uu to gang vv.Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of SS, so that the AIs can be deployed efficiently.Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible SS before he returns?InputThe first line contains an integer nn (2≤n≤30002≤n≤3000), the number of gangs in the network.Each of the next n−1n−1 lines contains integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n; ui≠viui≠vi), indicating there's a direct link between gangs uiui and vivi.It's guaranteed that links are placed in such a way that each pair of gangs will be connected by exactly one simple path.OutputPrint the maximum possible value of SS — the number of password layers in the gangs' network.ExamplesInputCopy3
1 2
2 3
OutputCopy3
InputCopy5
1 2
1 3
1 4
3 5
OutputCopy10
NoteIn the first example; one can achieve the maximum SS with the following assignment:  With this assignment, mex(1,2)=0mex(1,2)=0, mex(1,3)=2mex(1,3)=2 and mex(2,3)=1mex(2,3)=1. Therefore, S=0+2+1=3S=0+2+1=3.In the second example, one can achieve the maximum SS with the following assignment:  With this assignment, all non-zero mex value are listed below:   mex(1,3)=1mex(1,3)=1  mex(1,5)=2mex(1,5)=2  mex(2,3)=1mex(2,3)=1  mex(2,5)=2mex(2,5)=2  mex(3,4)=1mex(3,4)=1  mex(4,5)=3mex(4,5)=3 Therefore, S=1+2+1+2+1+3=10S=1+2+1+2+1+3=10.

#include<bits/stdc++.h>

#define LL long long
using namespace std;
int n,rt,u,v,p[3005][3005],s[3005][3005];
LL f[3005][3005],ans;
vector<int> G[3005];
void build(int u)
{
s[rt][u]=1;
for(int v:G[u])
if(v^p[rt][u])
{
p[rt][v]=u;
build(v);
s[rt][u]+=s[rt][v];
}
}
LL dp(int u, int v)
{
if(u==v)return 0;
if(f[u][v])return f[u][v];
return f[u][v]=max(dp(u,p[u][v]),dp(v,p[v][u]))+s[u][v]*s[v][u];
}
signed main()
{
ios::sync_with_stdio(false);
cin>>n;
for(int i=1;i<n;i++)
{
cin>>u>>v;
G[u].push_back(v);
G[v].push_back(u);
}
for(int i=1;i<=n;i++)rt=i,build(i);;
for(int u=1;u<=n;u++)
for(int v=1;v<=n;v++)
ans=max(ans,dp(u, v));
cout<<ans;
return 0;
}