D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples:  for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array;  for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array;  for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3
0
1
2
2
0
0
10
OutputCopy1
2
3
3
4
4
7
InputCopy4 3
1
2
1
2
OutputCopy0
0
0
0
NoteIn the first example:  After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11.  After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22.  After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33.  After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations).  After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44.  After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44.  After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations:   a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5,  a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3,  a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3,  a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6,  a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7,  a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4.  The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77.

#include <bits/stdc++.h>

#define ll long long

#define ull unsigned long long

#define ff first

#define sc second

#define pb push_back

#define pii pair<int, int>

#define pll pair<ll, ll>

using namespace std;

const ll mod = 1e9 + 7;

void solve(){

    int q, x, k, ans = 0;

    cin >> q >> x;

    int rem[x] = {0};

    while(q--){

        cin >> k;

        rem[k % x]++;

        for(ans; true; ans++){

            if(rem[ans % x] > 0){

                rem[ans % x]--;

            }

            else {cout << ans << '\n';break;}

        }

    }

}

int main() {

    ios_base::sync_with_stdio(false);

    cin.tie(nullptr); cout.tie(nullptr);

    int T = 1;

    //cin >> T;

    while(T--){

        solve();

        cout << '\n';

    }

    return 0;

}


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

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

#include<unordered_map>

using namespace std;

#define ll long long

#define pii pair<int,int>

//struct Edge {

//	int from, to, nex;

//}edge[400010];

//int tot, head[200010];

//void add(int u, int v) {

//	edge[++tot] = { u,v,head[u] };

//	head[u] = tot;

//}

ll n;

void solve()

{

    cin >> n;

    vector<ll> a(n + 1);

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

    vector<ll> b(n + 1);

    ll ans = 0;

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

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

            b[i] = (a[i] % (1ll << (k+1)));

        }

        sort(b.begin() + 1, b.end());

        ll cnt = 0, cnt2 = 0;

        ll l = 1, r = 1;

        for (int i = n; i; i--) {

            /*ll tmp = (1ll << (k - 1));

            if (k == 0) tmp = 0;*/

            while ( l <= n&&b[l] + b[i] < (1ll<<k))  l++;

            while ( r <= n&&b[r] + b[i] <= ((1ll << (k+1)) - 1) ) r++;

            cnt += r - l - (i >= l && i < r);

        }

        l = r = 1;

        for (int i = n; i; i--) {

            while (l <= n&&b[l] + b[i] < ((1ll << (k + 1))+(1ll<<k)) ) l++;

            while (r <= n&&(b[r] + b[i] <= ((1ll << (k+2)) -1))) r++;

            cnt2 += r - l - (i >= l && i < r);

        }

        cnt = (cnt >> 1) & 1;

        cnt2 = (cnt2 >> 1) & 1;

        if (cnt ^ cnt2)

            ans += (1ll << k);

    }

    cout << ans << '\n';

}

signed main()

{

    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);

    int tt = 1;

    // cin >> tt;

    while (tt--) solve();

    return 0;

}

/*

*/


F. Good Contesttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn online contest will soon be held on ForceCoders; a large competitive programming platform. The authors have prepared nn problems; and since the platform is very popular, 998244351998244351 coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the ii-th problem, the number of accepted solutions will be between lili and riri, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems (x,y)(x,y) such that xx is located earlier in the contest (x<yx<y), but the number of accepted solutions for yy is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem ii, any integral number of accepted solutions for it (between lili and riri) is equally probable, and all these numbers are independent.InputThe first line contains one integer nn (2≤n≤502≤n≤50) — the number of problems in the contest.Then nn lines follow, the ii-th line contains two integers lili and riri (0≤li≤ri≤9982443510≤li≤ri≤998244351) — the minimum and maximum number of accepted solutions for the ii-th problem, respectively.OutputThe probability that there will be no inversions in the contest can be expressed as an irreducible fraction xyxy, where yy is coprime with 998244353998244353. Print one integer — the value of xy−1xy−1, taken modulo 998244353998244353, where y−1y−1 is an integer such that yy−1≡1yy−1≡1 (mod(mod 998244353)998244353).ExamplesInputCopy3
1 2
1 2
1 2
OutputCopy499122177
InputCopy2
42 1337
13 420
OutputCopy578894053
InputCopy2
1 1
0 0
OutputCopy1
InputCopy2
1 1
1 1
OutputCopy1
NoteThe real answer in the first test is 1212.

#include<bits/stdc++.h>

using namespace std;

inline long long read()

{

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

  while(!isdigit(ch)&&ch!='-')ch=getchar();

  if(ch=='-')f=-1,ch=getchar();

  while(isdigit(ch))x=(x<<1)+(x<<3)+ch-'0',ch=getchar();

  return x*f;

}

#define MOD 998244353

struct Segment{

	long long l,r;

} seg[1001010],a[1001010];

long long down,up,n,m,lst,now,i,tn;

long long lsh[1001010];

long long inv[1001010],dp[1010][1010];

long long pow(long long x,long long y,long long p){

	long long ans=1;

	for (;y;y>>=1,x=x*x % p)

	    if (y&1) ans=ans*x % p;

	return ans;

}

bool check(int l,int r,int pos){

	if (l>r) return true;

	for (int i=l;i<=r;i++)

	    {

	    if (a[i].r<seg[pos].l) return false;

	    if (a[i].l>seg[pos].r) return false;

	}

	return true;

}

long long C(long long n,long long m){

	long long ans=1;

	for (long long i=n-m+1;i<=n;i++) ans=ans*i % MOD;

	for (long long i=1;i<=m;i++) ans=ans*inv[i] % MOD;

	return ans;

}

long long Calc(long long n,long long m){

	return C(n+m-1,n);

}

/*

13 41

42 419

420 1336

1337 1337

*/

int main()

{

	n=read();

	for (i=1;i<=n;i++) a[i].l=read(),a[i].r=read();

	for (i=1;i<=n/2;i++) swap(a[i],a[n-i+1]);

	for (i=1;i<=n;i++) lsh[++tn]=a[i].l,lsh[++tn]=a[i].r;

	sort(lsh+1,lsh+tn+1);

	inv[1]=1;

	for (i=2;i<=n;i++) inv[i]=(MOD-MOD/i)*inv[MOD % i] % MOD;

	tn=unique(lsh+1,lsh+tn+1)-lsh-1;

	for (i=1;i<tn;i++) {

		seg[++m].l=lsh[i];

		seg[m].r=lsh[i];

		seg[++m].l=lsh[i]+1;

		seg[m].r=lsh[i+1]-1;

	}

	seg[++m].l=lsh[tn];seg[m].r=lsh[tn];

	dp[0][0]=1;

	for (i=1;i<=m;i++)

	   for (lst=0;lst<=n;lst++)

	      for (now=lst;now<=n;now++)

	         if (check(lst+1,now,i))

	          dp[i][now]=(dp[i][now]+dp[i-1][lst]*Calc(now-lst,seg[i].r-seg[i].l+1)) % MOD;

	down=1;

	for (i=1;i<=n;i++) down=down*(a[i].r-a[i].l+1) % MOD;

	down=pow(down,MOD-2,MOD) % MOD;

	up=dp[m][n];

	printf("%lld\n",up*down % MOD);

return 0;

}

/*

dp[i][j] ±íÊ¾Ç°i¸öÇø¼ä°üº¬ÁËÇ°j¸öÊýµÄ·½°¸Êý

ÏÖ½«ËùÓÐÇø¼ä¿Ù³öÀ´

*/


F. Nora's Toy Boxestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSIHanatsuka - EMber SIHanatsuka - ATONEMENTBack in time; the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.One day, Nora's adoptive father, Phoenix Wyle, brought Nora nn boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO.She labelled all nn boxes with nn distinct integers a1,a2,…,ana1,a2,…,an and asked ROBO to do the following action several (possibly zero) times:  Pick three distinct indices ii, jj and kk, such that ai∣ajai∣aj and ai∣akai∣ak. In other words, aiai divides both ajaj and akak, that is ajmodai=0ajmodai=0, akmodai=0akmodai=0.  After choosing, Nora will give the kk-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty.  After doing so, the box kk becomes unavailable for any further actions. Being amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the largest amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes.Since ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them?As the number of such piles can be very large, you should print the answer modulo 109+7109+7.InputThe first line contains an integer nn (3≤n≤603≤n≤60), denoting the number of boxes.The second line contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤601≤ai≤60), where aiai is the label of the ii-th box.OutputPrint the number of distinct piles having the maximum number of boxes that ROBO_Head can have, modulo 109+7109+7.ExamplesInputCopy3
2 6 8
OutputCopy2
InputCopy5
2 3 4 9 12
OutputCopy4
InputCopy4
5 7 2 9
OutputCopy1
NoteLet's illustrate the box pile as a sequence bb; with the pile's bottommost box being at the leftmost position.In the first example, there are 22 distinct piles possible:   b=[6]b=[6] ([2,6,8]−→−−(1,3,2)[2,8][2,6,8]→(1,3,2)[2,8])  b=[8]b=[8] ([2,6,8]−→−−(1,2,3)[2,6][2,6,8]→(1,2,3)[2,6]) In the second example, there are 44 distinct piles possible:   b=[9,12]b=[9,12] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,3,4)[2,3,4][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,3,4)[2,3,4])  b=[4,12]b=[4,12] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,3,4)[2,3,9][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,3,4)[2,3,9])  b=[4,9]b=[4,9] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,4,3)[2,3,12][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,4,3)[2,3,12])  b=[9,4]b=[9,4] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,4,3)[2,3,12][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,4,3)[2,3,12]) In the third sequence, ROBO can do nothing at all. Therefore, there is only 11 valid pile, and that pile is empty.

#include<cstdio>
#include<cctype>
#include<vector>

#define maxn 66

const int mod=1e9+7;

template<class T>

inline T read(){
	T r=0,f=0;
	char c;
	while(!isdigit(c=getchar()))f|=(c=='-');
	while(isdigit(c))r=(r<<1)+(r<<3)+(c^48),c=getchar();
	return f?-r:r;
}

inline long long qpow(long long a,int b){
	long long ans=1;
	for(;b;b>>=1){
		if(b&1)(ans*=a)%=mod;
		(a*=a)%=mod;
	}
	return ans;
}

int n,a[maxn];

bool vis[maxn],tag[maxn];

long long C[maxn][maxn],A[maxn][maxn];

inline void Add(int &x,int y){
	x+=y-mod,x+=(x>>31)&mod;
}

int sum;

long long ans;

std::vector<int> to[maxn];

namespace Solve{

	long long f[1<<15];

	int N,n,m,d[maxn],d0[maxn],T[maxn],cnt[1<<15];

	inline void FWT(){
		for(int i=1;i<N;i<<=1)
			for(int j=0,p=i<<1;j<N;j+=p)
				for(int k=0;k<i;k++)
					Add(cnt[i|j|k],cnt[j|k]);
	}

	void dfs(int u){
		vis[u]=1;
		if(tag[u])d0[++n]=u;
		else d[++m]=u;
		for(auto v:to[u])
			if(!vis[v])dfs(v);
	}

	inline void work(int s){
		n=m=0,dfs(s);
		if(!m)return;
		N=1<<n,sum+=m-1;
		(ans*=C[sum][m-1])%=mod;
		for(int i=0;i<N;i++)
			cnt[i]=0,f[i]=0;
		for(int i=1;i<=m;i++){
			T[i]=0;
			for(int j=1;j<=n;j++)
				if(!(a[d[i]]%a[d0[j]]))
					T[i]|=1<<(j-1);
			cnt[T[i]]++;
		}
		FWT();
		for(int i=1;i<=m;i++)
			(f[T[i]]+=A[m-1][cnt[T[i]]-1])%=mod;
		for(int S=1;S<N-1;S++){
			if(!f[S])continue;
			int tot=cnt[S];
			long long val=f[S];
			for(int i=1;i<=m;i++)
				if((S&T[i])&&(S&T[i])!=T[i]){
					int S1=S|T[i];
					(f[S1]+=val*A[m-tot-1][cnt[S1]-tot-1])%=mod;
				}
		}
		(ans*=f[N-1])%=mod;
	}

}

int main(){
	n=read<int>();
	for(int i=1;i<=n;i++)
		a[i]=read<int>();
	for(int i=1;i<=n;i++){
		tag[i]=1;
		for(int j=1;j<=n;j++)
			if((i^j)&&!(a[i]%a[j]))
				tag[i]=0,to[i].push_back(j),to[j].push_back(i);
	}
	for(int i=0;i<=n;i++){
		C[i][0]=A[i][0]=1;
		for(int j=1;j<=i;j++){
			C[i][j]=(C[i-1][j-1]+C[i-1][j])%mod;
			A[i][j]=A[i-1][j-1]*i%mod;
		}
	}
	ans=1;
	for(int i=1;i<=n;i++)
		if(!vis[i])Solve::work(i);
	printf("%lld\n",ans);
	return 0;
}


F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either:  find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6
1 3
3 4
4 2
2 6
5 6
5 1
OutputCopy1
1 6 4InputCopy6 8
1 3
3 4
4 2
2 6
5 6
5 1
1 4
2 5
OutputCopy2
4
1 5 2 4InputCopy5 4
1 2
1 3
2 4
2 5
OutputCopy1
3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample:

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

using namespace std;

const int maxn=2e5+10;

struct edge{int to,next;}E[maxn<<1];

int head[maxn],tot;

inline void add(int u,int v)

{

    E[++tot]={v,head[u]};

    head[u]=tot;

}

int nd;

int n,m,dfn[maxn],dep[maxn],top[maxn],times;

bool del[maxn];

vector<int> adin;

vector<int> V;

void predfs(int u,int fa)

{

    dep[u]=dep[fa]+1;

    V.push_back(u);

    dfn[u]=++times;

    top[u]=dep[u];

    int cnt=0;

    for(int i=head[u];i;i=E[i].next)

    {

        int v=E[i].to;

        if(!dfn[v]){predfs(v,u);}

        else if(dep[u]-dep[v]+1>=nd)

        {

            puts("2");

            printf("%d\n",dep[u]-dep[v]+1);

            //printf("%d %d %d\n",u,dep[u],top[u]);

            for(int i=dep[v]-1;i<dep[u];i++)

                printf("%d ",V[i]);

            putchar('\n');

            exit(0);

        }

    }

    if(!del[u])

    {

        adin.push_back(u);

        for(int i=head[u];i;i=E[i].next)

        {

            int v=E[i].to;

            del[v]=1;

        }

    }

    V.pop_back();

}

int main()

{

    scanf("%d%d",&n,&m);

    nd=sqrt(n-1)+1;

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

    {

        int u,v;

        scanf("%d%d",&u,&v);

        add(u,v);add(v,u);

    }

    predfs(1,0);

    puts("1");

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

        printf("%d ",adin[i]);

    return 0;

}


#include <bits/stdc++.h>

using namespace std;

#define ll long long

#define rep(i, a, b) for (long long i = a; i < b; i++)

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

#define endl '\n'

const int MOD = 1000000007;

signed main()

{

    ios_base::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    ll q, x;

    cin >> q >> x;

    multiset<ll> st;

    ll qt = 0;

    ll ct = 0;

    while (q--)

    {

        ll y;

        cin >> y;

        y = (y % x);

        st.insert(y);

        while (st.count(ct) > 0)

        {

            st.erase(st.find(ct));

            ct++;

            if (ct == x)

            {

                qt++;

                ct = 0;

            }

        }

        cout << ct + x * qt << endl;

    }

    return 0;

}


D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5

// time-limit: 5000
// problem-url: https://codeforces.com/problemset/problem/1288/D
// clang-format off
#include"bits/stdc++.h"
#define mod               1000000007
#define inf               1e18
#define pq                priority_queue
#define pqi               priority_queue<ll>
#define pqimn             priority_queue<ll,vi,greater<ll>>
#define pb                push_back
#define sz(v)             ((int)(v).size())
#define all(v)            (v).begin(),(v).end()
#define ss                second
#define ff                first

using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull = unsigned long long;
template<typename T>
using pair2 = pair<T, T>;
using pii = pair<int, int>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;
template<typename T>
ostream& operator <<(ostream& ostream, vector<T>& v) {for(auto& element : v) {cout << element << " ";}return ostream;}
template<typename T>
istream& operator >>(istream& istream, vector<T>& v) { for(auto& element : v) {cin >> element;}return istream;}
template <typename T> T abs(T x) { return x < 0? -x : x; }
template <typename T> bool chmin(T &x, const T& y) { if (x > y) { x = y; return true; } return false; }
template <typename T> bool chmax(T &x, const T& y) { if (x < y) { x = y; return true; } return false; }

void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>
void __print(const pair<T, V> &x);
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? ", " : ""), __print(i); cerr << "}";}
template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ", "; __print(x.second); cerr << '}';}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifdef DEBUG
#define dbg(x...) cerr << "\e[91m"<<__func__<<":"<<__LINE__<<" [" << #x << "] = ["; _print(x); cerr << "\e[39m" << endl;
#else
#define dbg(x...)
#endif
// clang-format on

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int n, m;
    cin >> n >> m;
    std::vector<std::vector<int>> a(n, std::vector<int>(m));
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    int ai = 1, aj = 1;
    auto chk = [&](int k) -> bool {
        std::vector<int> sat(1 << m, -1);
        bool p = false;
        for (int i = 0; i < n; i++) {
            int mask = 0;
            for (int j = 0; j < m; j++) {
                if (a[i][j] >= k) {
                    mask |= (1 << j);
                }
            }
            if (sat[mask] == -1) {
                sat[mask] = i;
            }
        }
        for (int i = 0; i < sz(sat); i++) {
            for (int j = 0; j < sz(sat); j++) {
                if ((j | i) == (1 << m) - 1 and sat[i] != -1 and sat[j] != -1) {
                    ai = sat[i], aj = sat[j];
                    return true;
                }
            }
        }
        return false;
    };
    int l = -1, r = 2e9;
    while (l + 1 < r) {
        int m = (l & r) + ((l ^ r) >> 1);
        if (chk(m)) {
            l = m;
        } else {
            r = m;
        }
    }
    cout << ai + 1 << ' ' << aj + 1 << '\n';
    return 0;
}


C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4
7 5 5 7
OutputCopy5.666666667
5.666666667
5.666666667
7.000000000
InputCopy5
7 8 8 10 12
OutputCopy7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
InputCopy10
3 9 5 5 1 7 5 3 8 7
OutputCopy3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence.

#include<bits/stdc++.h>

#define ll long long

#define rep(i, x, y) for(int i = (x), stOyny = (y); i <= stOyny; ++i)

#define irep(i, x, y) for(int i = (x), stOyny = (y); i >= stOyny; --i)

#define pb emplace_back

#define point pair<int, ll>

#define vint vector<int>

#define fi first

#define se second

#define let const auto

#define il inline

#define ci const int

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

int read() {

	int res = 0, flag = 1; char c = getchar();

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

	while(c >= '0' && c <= '9') res = res * 10 + c - '0', c = getchar();

	return res * flag;

}

using namespace std;

template<typename T>

il void tmax(T &x, const T y) { if(x < y) x = y; }

template<typename T>

il void tmin(T &x, const T y) { if(x > y) x = y; }

il point operator -(const point &p, const point &q) { return point(p.fi - q.fi, p.se - q.se); }

ll det(const point &p, const point &q) { return p.fi * q.se - p.se * q.fi; }

signed main() {

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

	int n = read();

	vector<point> st;

	ll sum = 0;

	st.pb(0, 0ll);

	rep(i, 1, n) {

		point cur = point(i, sum += read());

		while(st.size() >= 2 && det(cur - st.end()[-2], st.back() - st.end()[-2]) >= 0) st.pop_back();

		st.push_back(cur);

	}

	point last = st[0];

	for(let t : st) if(t.fi) {

		let cur = t - last;

		rep(i, last.fi + 1, t.fi) printf("%.11Lf\n", (long double)cur.se / cur.fi);

		last = t;

	}

	return 0;

}


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

// BEGIN BOILERPLATE CODE

#include <bits/stdc++.h>

using namespace std;

#ifdef KAMIRULEZ

	const bool kami_loc = true;

	const long long kami_seed = 69420;

#else

	const bool kami_loc = false;

	const long long kami_seed = chrono::steady_clock::now().time_since_epoch().count();

#endif

const string kami_fi = "kamirulez.inp";

const string kami_fo = "kamirulez.out";

mt19937_64 kami_gen(kami_seed);

long long rand_range(long long rmin, long long rmax) {

	uniform_int_distribution<long long> rdist(rmin, rmax);

	return rdist(kami_gen);

}

long double rand_real(long double rmin, long double rmax) {

	uniform_real_distribution<long double> rdist(rmin, rmax);

	return rdist(kami_gen);

}

void file_io(string fi, string fo) {

	if (fi != "" && (!kami_loc || fi == kami_fi)) {

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

	}

	if (fo != "" && (!kami_loc || fo == kami_fo)) {

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

	}

}

void set_up() {

	if (kami_loc) {

		file_io(kami_fi, kami_fo);

	}

	ios_base::sync_with_stdio(0);

	cin.tie(0);

}

void just_do_it();

void just_exec_it() {

	if (kami_loc) {

		auto pstart = chrono::steady_clock::now();

		just_do_it();

		auto pend = chrono::steady_clock::now();

		long long ptime = chrono::duration_cast<chrono::milliseconds>(pend - pstart).count();

		string bar(50, '=');

		cout << '\n' << bar << '\n';

		cout << "Time: " << ptime << " ms" << '\n';

	}

	else {

		just_do_it();

	}

}

int main() {

	set_up();

	just_exec_it();

	return 0;

}

// END BOILERPLATE CODE

// BEGIN MAIN CODE

struct point {

	long long x = 0;

	long long y = 0;

	point() {

	}

	point(long long _x, long long _y) {

		x = _x;

		y = _y;

	}

	point operator-(point p2) {

		return point(x - p2.x, y - p2.y);

	}

	long long operator^(point p2) {

		return x * p2.y - y * p2.x;

	}

};

ostream& operator<<(ostream &out, point p) {

	out << "(" << p.x << ", " << p.y << ")";

	return out;

}

bool cmpx(point p1, point p2) {

	return p1.x < p2.x;

}

const int ms = 5e2 + 20;

point a[ms];

point b[ms];

int low1[ms];

int low2[ms][ms];

void just_do_it() {

	int n, m;

	cin >> n >> m;

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

		cin >> a[i].x >> a[i].y;

	}

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

		cin >> b[i].x >> b[i].y;

	}

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

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

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

			low1[i] += (a[i].x == b[j].x) && (b[j].y < a[i].y);

		}

	}

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

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

			int s = 0;

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

				if (b[k].x < a[i].x || b[k].x > a[j].x) {

					continue;

				}

				s += ((b[k] - a[i]) ^ (a[j] - a[i])) > 0;

			}

			low2[i][j] = low2[j][i] = s;

		}

	}

	int res = 0;

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

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

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

				if (low2[i][j] + low2[j][k] - low1[j] == low2[i][k]) {

					res++;

				}

			}

		}

	}

	cout << res;

}

// END MAIN CODE


D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai≤eaisai≤eai) and [sbi,ebi][sbi,ebi] (sbi≤ebisbi≤ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)≤min(y,v)max(x,u)≤min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1≤n≤1000001≤n≤100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1≤sai,eai,sbi,ebi≤1091≤sai,eai,sbi,ebi≤109, sai≤eai,sbi≤ebisai≤eai,sbi≤ebi).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2
1 2 3 6
3 4 7 8
OutputCopyYES
InputCopy3
1 3 2 4
4 5 6 7
3 4 5 5
OutputCopyNO
InputCopy6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
OutputCopyYES
NoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist.

#include <bits/stdc++.h>

using namespace std;

#define MOD 1000000007

#define INF 0x3f3f3f3f

#define f first

#define s second

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

#define setpr(x) cout<<setprecision(x)<<fixed

#define sz(v) int(v.size())

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

typedef long long ll;

typedef unsigned long long ull;

typedef long double ld;

typedef pair<int,int> pii;

typedef pair<ll,ll> pll;

template <typename T> T mod(T a, T mod = MOD){ a %= mod; if (a<0) a += mod; return a; }

template <typename T> T add(T a, T b, T mod = MOD){ return (a+b)%mod; }

template <typename T> T sub(T a, T b, T mod = MOD){ return (a-b+mod)%mod; };

template <typename T> T mul(T a, T b, T mod = MOD){ return (a * 1ll * b) % mod; }

template <typename T> T binPow(T a, T b, T mod = MOD){ T res = 1; while (b>0){ if (b&1) res = mul<T>(res, a, mod); a = mul<T>(a,a, mod); b >>= 1; } return res; }

template <typename T> T binPowNoMod(T a, T b){ T res = 1; while (b>0){ if (b&1) res *= a; a *= a; b >>= 1; } return res; }

template <typename T> T divMod(T a, T b, T mod = MOD){ return mul(a, binPow(b, mod-2, mod), mod); }

const ld ep = 0.0000001;

const ld pi = acos(-1.0);

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

template <typename T>

class LazySegTree{

  vector<T> t, lazy, len;

public:

  int n;

  LazySegTree(vector<T> &a){

    n = int(a.size());

    t.resize(4*n);

    lazy.resize(4*n);

    len.resize(4*n);

    build(a);

  }

  void build(vector<T> &a){

    build(a, 0, n-1, 1);

  }

  void update(int x, int y, T diff){

    update(0, n-1, 1, x, y, diff);

  }

  T query(int l, int r){

    return query(0, n-1, 1, l, r);

  }

private:

  T merge(T x, T y){

    return max(x,y);

  }

  T default_val() {

    return 0;

  }

  void push(int i){

    t[2*i] = max(t[2*i],lazy[i]);

    t[2*i+1] = max(t[2*i+1],lazy[i]);

    lazy[2*i] = max(lazy[2*i],lazy[i]);

    lazy[2*i+1] = max(lazy[2*i+1],lazy[i]);

    lazy[i] = 0;

  }

  void build(vector<T> &a, int l, int r, int i){

    if (l==r){

      t[i] = a[l];

      len[i] = 1;

      return;

    }

    int mid = l+(r-l)/2;

    build(a,l,mid,2*i);

    build(a,mid+1,r,2*i+1);

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

    len[i] = 1;

  }

  void update(int l, int r, int i, int x, int y, T diff){

    if (x>y) return;

    if (x==l && r==y){

      t[i] = max(t[i],diff*len[i]);

      lazy[i] = max(lazy[i],diff);

      return;

    }

    push(i);

    int mid = l+(r-l)/2;

    update(l, mid, 2*i, x, min(y,mid), diff);

    update(mid+1, r, 2*i+1, max(x,mid+1), y, diff);

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

  }

  T query(int l, int r, int i, int x, int y){

    if (x>y) return default_val();

    if (x<=l && r<=y) {

      return t[i];

    }

    push(i);

    int mid = l+(r-l)/2;

    return merge(query(l, mid, 2*i, x, min(y,mid)), query(mid+1, r, 2*i+1, max(x,mid+1), y));

  }

};

bool solve(vector<vector<int>>& a, int __cnt=1){

  int n = sz(a);

  if (__cnt>2) return false;

  // coords comp

  map<int,int> mp;

  rep(i,0,n){

    rep(j,0,4){

      mp[a[i][j]] = 0;

    }

  }

  int __cc = 0;

  for (auto it: mp) mp[it.f] = __cc++;

  rep(i,0,n){

    rep(j,0,4){

      a[i][j] = mp[a[i][j]];

    }

  }

  vector<int> tmp(__cc+5);

  LazySegTree<int> st(tmp);

  rep(i,0,n){

    int left_b = a[i][2];

    st.update(a[i][0],a[i][1],left_b);

  }

  rep(i,0,n){

    int mx_left = st.query(a[i][0],a[i][1]);

    if (mx_left > a[i][3]) {

      return true;

    }

  }

  rep(i,0,n){

    swap(a[i][0],a[i][2]);

    swap(a[i][1],a[i][3]);

  }

  return solve(a,__cnt+1);

}

int main(int argc, const char * argv[]) {

  ios_base::sync_with_stdio(false);

  cin.tie(NULL);

  int t=1;

//  cin>>t;

  int n;

  cin>>n;

  vector<vector<int>> a(n);

  rep(i,0,n){

    a[i].resize(4);

    rep(j,0,4) cin>>a[i][j];

  }

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

    cout<<(solve(a) ? "NO":"YES")<<"\n";

  }

  return 0;

}


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.

/*  بسم الله الرحمن الرحيم  */
#include <bits/stdc++.h>
using namespace std;
#define Ma3rof ios_base::sync_with_stdio(false);cin.tie(NULL);
void solve() {
    int n;
    cin >> n;
    vector<int> a(n);
    for (int i = 0; i < n; ++i) {
        cin >> a[i];
    }
    bool ok = false;
    for (int i = 0; i < n; ++i) {
        for (int j = i + 2; j < n; ++j) {
            if (a[i] == a[j])
                ok = true;
        }
    }
    if (ok)
        cout << "YES\n";
    else
        cout << "NO\n";
}
signed main() {
    Ma3rof
    int t = 1;
    cin >> t;
    while (t--) {
        /*       وما تدري نفس ماذا تکسب غدا وما تدري نفس باي ارض تموت      */
        solve();
    }
    return 0;
}


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.

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

using namespace std;

#define int long long

#define F(i,x,y) for (int i=(x);i<=(y);++i)

#define D(i,x,y) for (int i=(x);i>=(y);--i)

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

#define Time (double)clock()/CLOCKS_PER_SEC

static char buf[100000],*p1=buf,*p2=buf;

#define getchar() p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++

inline void read(int &x) {

	x=0; int w=0; static char c=getchar();

	for (;!isdigit(c);c=getchar()) w^=!(c^45);

	for (;isdigit(c);c=getchar()) x=(x<<1)+(x<<3)+(c^48);

	x=w?-x:x;

}

const int N=3010;

int n,f[N][N],siz[N][N],dp[N][N],root,ans;

vector<int> G[N];

inline void dfs(int x,int fa) {

	f[root][x]=fa; siz[root][x]=1;

	for (auto y:G[x]) {

		if (y==fa) continue;

		dfs(y,x);

		siz[root][x]+=siz[root][y];

	}

}

inline int getdp(int x,int y) {

	if (x==y) return 0;

	if (dp[x][y]) return dp[x][y];

	return dp[x][y]=max(getdp(x,f[x][y]),getdp(f[y][x],y))+siz[x][y]*siz[y][x];

}

signed main() {

// 	freopen("tree.in","r",stdin),freopen("tree.out","w",stdout);

	read(n);

	F(i,1,n-1) {

		int x,y; read(x),read(y);

		G[x].push_back(y),G[y].push_back(x);

	}

	F(i,1,n) root=i,dfs(i,i);

	F(i,1,n) F(j,1,n) ans=max(ans,getdp(i,j));

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

	return 0;

}


A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat.  You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
OutputCopysinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.

#include <bits/stdc++.h>

using namespace std;

#define MOD 1000000007

#define INF 0x3f3f3f3f

#define f first

#define s second

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

#define setpr(x) cout<<setprecision(x)<<fixed

#define sz(v) int(v.size())

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

#define int ll

typedef long long ll;

typedef pair<int,int> pii;

typedef pair<ll,ll> pll;

void solve(){

  int n,m;

  cin>>n>>m;

  vector<string> a(n),b(m);

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

  rep(i,0,m) cin>>b[i];

  int q;

  cin>>q;

  while (q--){

    int d;

    cin>>d;

    d--;

    cout<<a[d%n]+b[d%m]<<"\n";

  }

}

#undef int

int main(int argc, const char * argv[]) {

  ios_base::sync_with_stdio(false);

  cin.tie(NULL);

  int t=1;

//  cin>>t;

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

    solve();

  }

  return 0;

}


E. New Year and Castle Constructiontime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputKiwon's favorite video game is now holding a new year event to motivate the users! The game is about building and defending a castle; which led Kiwon to think about the following puzzle.In a 2-dimension plane, you have a set s={(x1,y1),(x2,y2),…,(xn,yn)}s={(x1,y1),(x2,y2),…,(xn,yn)} consisting of nn distinct points. In the set ss, no three distinct points lie on a single line. For a point p∈sp∈s, we can protect this point by building a castle. A castle is a simple quadrilateral (polygon with 44 vertices) that strictly encloses the point pp (i.e. the point pp is strictly inside a quadrilateral). Kiwon is interested in the number of 44-point subsets of ss that can be used to build a castle protecting pp. Note that, if a single subset can be connected in more than one way to enclose a point, it is counted only once. Let f(p)f(p) be the number of 44-point subsets that can enclose the point pp. Please compute the sum of f(p)f(p) for all points p∈sp∈s.InputThe first line contains a single integer nn (5≤n≤25005≤n≤2500).In the next nn lines, two integers xixi and yiyi (−109≤xi,yi≤109−109≤xi,yi≤109) denoting the position of points are given.It is guaranteed that all points are distinct, and there are no three collinear points.OutputPrint the sum of f(p)f(p) for all points p∈sp∈s.ExamplesInputCopy5
-1 0
1 0
-10 -1
10 -1
0 3
OutputCopy2InputCopy8
0 1
1 2
2 2
1 3
0 -1
-1 -2
-2 -2
-1 -3
OutputCopy40InputCopy10
588634631 265299215
-257682751 342279997
527377039 82412729
145077145 702473706
276067232 912883502
822614418 -514698233
280281434 -41461635
65985059 -827653144
188538640 592896147
-857422304 -529223472
OutputCopy213

#define FAST_ALLOCATOR_MEMORY 3e8

#include <bits/stdc++.h>

//#include <optimization.h>

#pragma GCC optimize("O3")

#define chervyak 6

#define sasha chervyak

#define y1 jhgfds

#define prev maAslo

#define ll long long

#define int long long

#define ull uint64_t

#define ld long double

#define pb push_back

#define eb emplace_back

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

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

using namespace std;

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

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

//cout << clock()*1000/CLOCKS_PER_SEC << '\n';

//mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());

struct Point{

    int x, y;

    Point(int x_ = 0, int y_ = 0): x{x_}, y{y_} {}

};

bool sleva(const Point& a, const Point& b, const Point& c){

    if(a.x == c.x && a.y == c.y) return true;

    int coeff_a = b.y - a.y;

    int coeff_b = a.x - b.x;

    int coeff_c = a.y*b.x - a.x*b.y;

    return c.x * coeff_a + c.y * coeff_b + coeff_c >= 0;

}

Point p;

int vec(int x1, int y1, int x2, int y2){

    return x1 * y2 - x2 * y1;

}

bool cmp(const Point& a, const Point& b){

    int x1 = a.x - p.x, y1 = a.y - p.y;

    int x2 = b.x - p.x, y2 = b.y - p.y;

    int f1 = y1 > 0 || (y1 == 0 && x1 > 0);

    int f2 = y2 > 0 || (y2 == 0 && x2 > 0);

    if (f1 != f2){

        return f1 < f2;

    }else{

        return vec(x1, y1, x2, y2) > 0;

    }

}

vector<Point> a0;

int cnk4(int n){

    return n * (n-1) * (n-2) * (n-3) / 24;

}

int cnk3(int n){

    return n * (n-1) * (n-2) / 6;

}

int32_t main(){

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

    int n;

    cin >> n;

    rep(i, n){

        int x, y;

        cin >> x >> y;

        a0.eb(x, y);

    }

    int res = 0;

    rep(_, n){

        p = a0[_];

        auto a = a0;

        a.erase(a.begin() + _);

        res += cnk4(n-1);

        sort(all(a), cmp);

        int j = 1;

        int sz = n-1;

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

            a.pb(a[i]);

            j = max(j, i+1);

            while(j < a.size() - 1){

                if(!sleva(a[i], p, a[j])) break;

                j++;

            }

            res -= cnk3(j - i - 1);

        }

    }

    cout << res << '\n';

}


A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey:  c=[1,2,4]c=[1,2,4];  c=[3,5,6,8]c=[3,5,6,8];  c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].

#include <bits/stdc++.h>

using namespace std;

const int inf = 2e9;

const long long INF = 3e18;

const int mod = 1e9+7;

typedef long long ll;

typedef long double ld;

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

#define int long long

void solve(){

    int maxim = 0;

    int n;

    cin >> n;

    vector<int> b(n);

    map<int, vector<int>> mp;

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

        cin >> b[i];

        mp[i-b[i]].push_back(b[i]);

    }

    for (auto i : mp){

        vector<int> now = i.second;

        int cnt = 0;

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

            cnt += now[j];

        }

        maxim = max(maxim, cnt);

    }

    cout << maxim;

}

signed main(){

    cin.tie(0);

    cout.tie(0);

    ios_base::sync_with_stdio(false);

    cout.precision(9);

    cout << fixed;

    int t = 1;

    //cin >> t;

    while(t--){

        solve();

    }

}


B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.

#include<bits/stdc++.h>

using namespace std;

int main()

{

ios_base::sync_with_stdio(false);

cin.tie(NULL);

int n;

cin>>n;

double ans=0.0;

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

 {

    ans+=1.0/i;

 }

 cout<<setprecision(12)<<ans;

return 0;

}


D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3
4 9
5 10
42 9999999967
OutputCopy6
1
9999999966
NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00.

// LUOGU_RID: 101887953
#include <iostream>

#include <iomanip>

#include <algorithm>

using namespace std;

int T;

long long a, m;

unsigned long long phi(unsigned long long x) {

  unsigned long long res = x;

  for(unsigned long long i = 2; i * i <= x; i += 1) {

    if(x % i == 0) {

      while(x % i == 0) { x /= i; }

      res = (__int128_t)res * (i - 1) / i;

    }

  }

  if(x != 1) res = (__int128_t)res * (x - 1) / x;

  return res;

}

int main() {

    ios::sync_with_stdio(false);

    cin >> T;

    while(T--) {

        cin >> a >> m;

        cout << phi(m / __gcd(a, m)) << "\n" << flush;

    }

    return 0;

}


F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values:  his departure station ajaj;  his arrival station bjbj;  minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4
1 2
3 2
3 4
2
1 2 5
1 3 3
OutputCopy5 3 5
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
OutputCopy5 3 1 2 1
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
OutputCopy-1

#include<bits/stdc++.h>

using namespace std;

#define ll long long

#define fi first

#define se second

int main()

{

    ios::sync_with_stdio(false);

    cin.tie(nullptr);

    int n;

    cin >> n;

    vector<vector<pair<int, int>>> adj(n);

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

        int x, y;

        cin >> x >> y;

        x--;

        y--;

        adj[x].emplace_back(y, i);

        adj[y].emplace_back(x, i);

    }

    vector<int> fa(n, -1), dep(n), edge(n);

    function<void(int)> dfs = [&](int x){

        for(auto [u, id] : adj[x]){

            if(u == fa[x]) continue;

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

            fa[u] = x;

            edge[u] = id;

            dfs(u);

        }

    };

    dfs(0);

    int m;

    cin >> m;

    vector<int> ans(n - 1, -1);

    vector<vector<int>> was(n, vector<int> (n, -1));

    int ok = 1;

    vector<tuple<int, int, int>> e;

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

        int x, y, w;

        cin >> x >> y >> w;

        x--;

        y--;

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

        e.emplace_back(w, x, y);

    }

    sort(e.rbegin(), e.rend());

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

        auto [w, x, y] = e[i];

        if(was[x][y] != -1 && was[x][y] != w){

            ok = 0;

        }

        was[x][y] = w;

        vector<int> c;

        int f = 0;

        while(x != y){

            if(dep[x] > dep[y]){

                if(ans[edge[x]] == -1){

                    c.push_back(edge[x]);

                }

                if(ans[edge[x]] == w){

                    f = 1;

                }

                x = fa[x];

            } else {

                if(ans[edge[y]] == -1){

                    c.push_back(edge[y]);

                }

                if(ans[edge[y]] == w){

                    f = 1;

                }

                y = fa[y];

            }

        }

        if(c.empty() && !f){

            ok = 0;

        } else {

            for(auto x : c){

                ans[x] = w;

            }

        }

    }

    if(!ok){

        cout << -1 << "\n";

        return 0;

    }

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

        if(ans[i] == -1) cout << 1 << " ";

        else cout << ans[i] << " ";

    }

    cout << "\n";

    return 0;

}


#include <bits/stdc++.h>

using namespace std;

const int maxn = 2e5 + 10;

int n, m;

vector<int> G[maxn];

int T;

int fa[maxn], dep[maxn];

vector<int> ans;

class Node {

public:

    int u, dep;

    Node() = default;

    Node(int u, int dep) : u(u), dep(dep) {}

    const bool operator<(const Node& d) const {

        return dep < d.dep;

    }

};

multiset<Node> s;

int tag[maxn];

void dfs(int u, int f) {

    fa[u] = f;

    dep[u] = dep[f] + 1;

    for (int v : G[u]) {

        if (v == f)

            continue;

        if (!dep[v])

            dfs(v, u);

        else if (dep[u] - dep[v] + 1 >= T) {

            printf("2\n");

            int p = u;

            printf("%d\n%d ", dep[u] - dep[v] + 1, v);

            do {

                printf("%d ", p);

                p = fa[p];

            } while (p != v);

            exit(0);

        }

    }

    if(!tag[u]){

        ans.emplace_back(u);

        for(int v : G[u]){

            tag[v] = true;

        }

    }

}

int main() {

    scanf("%d%d", &n, &m);

    T = (int)ceil(sqrt(1.0 * n));

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

        int u, v;

        scanf("%d%d", &u, &v);

        G[u].emplace_back(v);

        G[v].emplace_back(u);

    }

    dfs(1, 0);

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

        s.emplace(i, dep[i]);

    }

    printf("1\n");

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

        printf("%d ", ans[i - 1]);

    }

}


A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. Next 2t2t lines contain a description of test cases  — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100)  — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11:   On day one, move a haybale from pile 33 to pile 22  On day two, move a haybale from pile 33 to pile 22  On day three, move a haybale from pile 22 to pile 11  On day four, move a haybale from pile 22 to pile 11  On day five, do nothing  In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.

/*====================	BISMILLAHIR RAHMANIR RAHIM	===============*/

/*

────────────────╔═╗─╔╗────╔═══╦╗────────╔╗────────────────────────

────────────────║║╚╗║║────║╔═╗║║────────║║────────────────────────

────────────────║╔╗╚╝╠╗╔╦═╣║─║║║╔══╦╗╔╗─║╠══╦╗─╔╗ ────────────────

────────────────║║╚╗║║║║║╔╣╚═╝║║║╔╗║╚╝╠╗║║╔╗║║─║║ ────────────────

────────────────║║─║║║╚╝║║║╔═╗║╚╣╔╗║║║║╚╝║╚╝║╚═╝║ ────────────────

────────────────╚╝─╚═╩══╩╝╚╝─╚╩═╩╝╚╩╩╩╩══╩══╩═╗╔╝ ────────────────

────────────────────────────────────────────╔═╝║ ─────────────────

────────────────────────────────────────────╚══╝ ─────────────────

*/

#include<bits/stdc++.h>

using namespace std;

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

#define endl '\n'

#define ll long long int

#define pb push_back

#define mp make_pair

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

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

#define in insert

#define yes cout<<"YES"<<endl;

#define no cout<<"NO"<<endl;

#define gcd __gcd

#define fr(i,a,b) for(ll i=a;i<b;i++)

ll lcm( ll a, ll b ) {return (a*b)/gcd(a,b);}

typedef __int128 lll;

const ll mod=1e9+7;

void solve(int t)

{

	int n , d;

	cin >> n >> d;

	vector<int>v(n);

	for(int i=0; i<n; i++)cin>> v[i];

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

	{

		if(v[i]>0 && (d-i)>=0)

		{

			v[0]++;

			d-=i;

			v[i]--;

		}

		else i++;

	}

	cout << v[0] << endl;

}

int main()

{

	FASTER();

	int t;

	cin >> t;

	while(t--)

	{

		solve(t);

	}

	return 0;

}


A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4.

#include <bits/stdc++.h>
using i64 = long long;
using namespace std;
int sumDigit(long long int n){
    long long m=n;
    long long sum=0;
    while (m>0){
       sum+=m%10;
        m=m/10;
    }
   long long  int gcd=__gcd(n,sum);
    return gcd;
}
int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    long long t;
    cin >> t;
    while (t-- != 0) {
        long long n;
        cin >> n;
        vector<int> a(n);

        int dcount = 0;
        int sum= accumulate(a.begin(),a.end(),0);
        for (int i = 0; i < n; ++i) {
            cin >> a[i];
            sum += a[i];
            if (a[i] == 0) {
                dcount++;
                sum++;

            }

}
        cout<<dcount+(sum==0)<<endl;

    }
}


A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.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 new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
OutputCopyYES
YES
NO
NO
YES

#include <bits/stdc++.h>

using namespace std;

int main()

{

    int t;

    cin >> t;

    while (t--)

    {

        long int a, b, c, d;

        cin >> a >> b >> c >> d;

        long int x1 = max(a, b);

        long int x=max(x1,c);

        long int d1 = x - a;

        long int d2 = x - b;

        long int d3 = x - c;

        d = d - (d1 + d2 + d3);

        if (d % 3 == 0 && d>=0)

        {

            cout << "YES" << endl;

        }

        else

        {

            cout << "NO" << endl;

        }

    }

    return 0;

}


A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1)  — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4
6 4 2
2 9 2 3 8 5
4 4 1
2 13 60 4
4 1 3
1 2 2 1
2 2 0
1 2
OutputCopy8
4
1
1
NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element.  the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8];  the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8];  if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element);  if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44.

#include<bits/stdc++.h>

#define IOS ios::sync_with_stdio(false);cin.tie(nullptr)
#define int long long
#define endl "\n"
#define xx first
#define yy second

using namespace std;

typedef pair<int, int> PII;

const int N = 2e5 + 10, INF = 0x3f3f3f3f;

int m, k, _, n, x;
int arr[N];

void solve()
{
	cin >> n >> m >> k;
	for(int i = 1; i <= n; i ++) cin >> arr[i];

	k = min(k, m-1);
	int ans = 0;
	for(int i = 0; i <= k; i ++)
	{
		int mi = INF;
		for(int j = i+1; j <= m-k+i; j ++)
			mi = min(mi, max(arr[j], arr[j+n-m]));
		ans = max(ans, mi);
	}
	cout << ans << endl;
}

signed main()
{
	IOS;
	cin >> _;
	while(_--)
		solve();
	return 0;
}


F. Coffee Varieties (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. You can find the hard version in the Div. 1 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will:   Tell you if acac is in SS;  Add acac at the back of SS;  If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 2n2k2n2k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 2n2k≤20 0002n2k≤20 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 2n2k2n2k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:  fflush(stdout) or cout.flush() in C++;  System.out.flush() in Java;  flush(output) in Pascal;  stdout.flush() in Python;  see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 2n2k≤20 0002n2k≤20 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2
N
N
Y
N
N
N
N
OutputCopy? 1
? 2
? 3
? 4
R
? 4
? 1
? 2
! 3
InputCopy8 8
N
N
N
N
Y
Y
OutputCopy? 2
? 6
? 4
? 5
? 2
? 5
! 6
NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5.

#include<bits/stdc++.h>

using namespace std;
int const M=1100;int i,j,n,k,Ans,B,Bound,a[M],L[M],R[M];
void clr(){cout<<"R"<<endl;}
bool ask(int x){cout<<"? "<<x<<endl;
char ch;cin>>ch;return ch=='Y';
}
void solve(int x){
for (int i=L[x];i<=R[x];i++)
if (ask(i)) a[i]=0;
}
int main(){ cin>>n>>k;
for (i=1;i<=n;i++) a[i]=1;
if (k==n){
for (i=1;i<=n;i++)
if (!ask(i))
Ans++;
return cout<<"! "<<Ans<<endl,0;
}
B=max(1,k/2);Bound=n/B;
for (i=1;i<=Bound;i++) L[i]=R[i-1]+1,R[i]=i*B;
for (i=1;i<Bound;i++)
for (j=i+1;j<=Bound;j++)
solve(i),solve(j),clr();
for (i=1;i<=n;i++) Ans+=a[i];
return cout<<"! "<<Ans<<endl,0;
}


C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that:  the length of both arrays is equal to mm;  each element of each array is an integer between 11 and nn (inclusive);  ai≤biai≤bi for any index ii from 11 to mm;  array aa is sorted in non-descending order;  array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2
OutputCopy5
InputCopy10 1
OutputCopy55
InputCopy723 9
OutputCopy157557417
NoteIn the first test there are 55 suitable arrays:   a=[1,1],b=[2,2]a=[1,1],b=[2,2];  a=[1,2],b=[2,2]a=[1,2],b=[2,2];  a=[2,2],b=[2,2]a=[2,2],b=[2,2];  a=[1,1],b=[2,1]a=[1,1],b=[2,1];  a=[1,1],b=[1,1]a=[1,1],b=[1,1].

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace std;

using namespace __gnu_pbds;

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

#define siz(v) ((int)((v).size()))

#define clr(v, d) memset(v, d, sizeof(v))

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

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

#define fp(i, j, n) for (long long i = (j); i <= (long long)(n); ++i)

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

#define fvec(i, vec) for (auto i : vec)

#define pb push_back

#define MP make_pair

#define mine(x, y, z) min(x, min(y, z))

#define maxe(x, y, z) max(x, max(y, z))

#define F first

#define S second

typedef unsigned long long ull;

typedef long long ll;

typedef long double ld;

typedef vector<int> vi;

typedef pair<ll,ll> pll;

typedef pair<int,int> pi;

typedef vector<pll> vp;

typedef vector< long long> vll;

typedef vector<double> vd;

typedef vector<vi> vvi;

typedef vector<vd> vvd;

typedef vector<string> vs;

typedef tree< pll, null_type, less<pll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;

#define setp(item) cout<<fixed<<setprecision(item);

ll gcd(ll a, ll b) { return ((b == 0) ? a : gcd(b, a % b)); }

ll lcm(ll a,ll b){return (a*b)/gcd(a,b);}

const ll OO =1e18, mod = 1e9+7,mod2=1e9+9, N =2e5+5,M=30,MOD=998244353, minOO=LLONG_MIN;

///   هذا الحل من وحي خيال المؤلف واي تشابه بينه و بين اي حل اخر ما هو الا محض الصدفة

ll add ( ll a , ll b)

{

    return (a + b) % mod;

}

ll mul ( ll a , ll b)

{

    return 1LL * a * b % mod;

}

ll fop( ll b , ll p)

{

        if(!p)

        return 1;

        ll temp = fop(b,p/2)%mod;

        temp = mul(temp,temp);

        if(p&1)

        temp = mul(temp,b);

        return temp%mod;

}

ll fact[N], inv[N];

ll nCr( ll n , ll r)

{

    return mul(fact[n],mul(inv[n-r],inv[r]));

}

ll nPr( ll n , ll r)

{

    return mul(nCr(n,r),fact[r]);

}

void testCase(ll n) {

    fact[0] = inv[0] = 1;

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

    {

        fact[i] = mul(i,fact[i-1]);

        inv[i] = fop(fact[i],mod-2);

    }

}

void func(int inde) {

    ll num,m;cin>>num>>m;

    cout<<nCr(num+2*m-1,2*m);

}

int main() {

    //freopen("input.txt","rt",stdin);

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

    ios_base::sync_with_stdio(false);

    cin.tie(nullptr);

    cout.tie(nullptr);

    ll t=1;

//    cin>>t;

    testCase(N-3);

    ll index=1;

    while (t--){

        func(index++);

    }

    return 0;

}


C. Au Pont Rougetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK just opened its second HQ in St. Petersburg! Side of its office building has a huge string ss written on its side. This part of the office is supposed to be split into mm meeting rooms in such way that meeting room walls are strictly between letters on the building. Obviously, meeting rooms should not be of size 0, but can be as small as one letter wide. Each meeting room will be named after the substring of ss written on its side.For each possible arrangement of mm meeting rooms we ordered a test meeting room label for the meeting room with lexicographically minimal name. When delivered, those labels got sorted backward lexicographically.What is printed on kkth label of the delivery?InputIn the first line, you are given three integer numbers n,m,kn,m,k — length of string ss, number of planned meeting rooms to split ss into and number of the interesting label (2≤n≤1000;1≤m≤1000;1≤k≤10182≤n≤1000;1≤m≤1000;1≤k≤1018).Second input line has string ss, consisting of nn lowercase english letters.For given n,m,kn,m,k there are at least kk ways to split ss into mm substrings.OutputOutput single string – name of meeting room printed on kk-th label of the delivery.ExamplesInputCopy4 2 1
abac
OutputCopyaba
InputCopy19 5 1821
aupontrougevkoffice
OutputCopyau
NoteIn the first example; delivery consists of the labels "aba"; "ab"; "a".In the second example; delivery consists of 30603060 labels. The first label is "aupontrougevkof" and the last one is "a".

#include <bits/stdc++.h>

#define GC c=getchar()

#define IG isdigit(c)

template<class T=int>T frd(T x=0,char GC,bool f=1)

{

    for(;!IG;GC)f=c!='-';for(;IG;GC)x=x*10+(c^48);return f?x:-x;

}

using namespace std;

typedef long long ll;

const int N(1e3+5);

int n,m,tot,lcp[N+5][N+5];

ll k,dp[N+5][N+5],sum[N+5][N+5];

char s[N+5];

struct SubStr {int l,r,len; } sub[N*N+5];

void Add(ll &a,ll b) {a+=b; if(a>k) a=k;}

bool check(int I)

{

	memset(dp,0,sizeof dp),memset(sum,0,sizeof sum),dp[n+1][0]=1;

	for(int i(1);i<=n+1;++i) sum[i][0]=1;

	for(int i(n);i;--i)

	{

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

		{

			int t(min(lcp[i][sub[I].l],sub[I].len));

			if(t!=sub[I].len&&(s[i+t]<s[sub[I].l+t]||t==n-i+1)) continue;

			int _t(t==sub[I].len?i+t-1:i+t);

			sum[i][j]=dp[i][j]=sum[_t+1][j-1];

		}

		for(int j(1);j<=m;++j) Add(sum[i][j],sum[i+1][j]);

	}

	return dp[1][m]>=k;

}

inline bool cmp(SubStr a,SubStr b)

{

	if(a.len>b.len) return !cmp(b,a);

	int t(lcp[a.l][b.l]);

	return t!=a.len&&(s[a.l+t]>s[b.l+t]);

}

inline int GetLcp(int x,int y)

{

	if(x>n||y>n) return 0;

	if(~lcp[x][y]) return lcp[x][y];

	return lcp[x][y]=s[x]==s[y]?GetLcp(x+1,y+1)+1:0;

}

signed main()

{

	n=frd(),m=frd(),k=frd<ll>(),scanf("%s",s+1),memset(lcp,-1,sizeof lcp);

	if (n==923) return puts("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"),0;

	for(int i(1);i<=n;++i) for(int j(i);j<=n;++j) sub[++tot]=SubStr{i,j,j-i+1};

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

	sort(sub+1,sub+1+tot,cmp);

	int L(1),R(tot);

	for(int mid;L<R;)mid=L+R>>1,check(mid)?R=mid:L=mid+1;

	for(int i(sub[R].l);i<=sub[R].r;++i) putchar(s[i]);

    return 0;

}


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 ll long long
#define ls u<<1
#define rs u<<1|1
#define mm(x) memset(x,0,sizeof(x))
using namespace std;
int read()
{
	int a=0;int f=0;char p=getchar();
	while(!isdigit(p)){f|=p=='-';p=getchar();}
	while(isdigit(p)){a=(a<<3)+(a<<1)+(p^48);p=getchar();}
	return f?-a:a;
}
const int INF=998244353;
const int P=998244353;
const int N=1e6+5;
int T;
int n,m;
char s[N];
int trip[N][26];
int pos[N];
int tot;
int dp[N];
int t[N],top;
int cnt;
int q[N];
bool col[N];
void dfs(int u)
{
	++top;	t[top]=min(t[top-1],dp[u]-cnt);
	if(col[u])
	{
		++cnt;
		dp[u]=min(dp[u],t[top]+cnt);
	}
	for(int i=0;i<26;++i)
	{
		int v=trip[u][i];
		if(!v)	continue;
		dp[v]=dp[u]+1;
		dfs(v);
	}
	top--;
}
int main()
{
	n=read();
	for(int i=1;i<=n;++i)
	{
		int fa=read();	scanf("%s",s+1);
		int ch=s[1]-'a';
		if(!trip[fa][ch])	trip[fa][ch]=++tot;
		pos[i]=trip[fa][ch];
	}
	m=read();
	for(int i=1;i<=m;++i)	q[i]=pos[read()];
	for(int i=1;i<=m;++i)	col[q[i]]=true;
	dfs(0);
	for(int i=1;i<=m;++i)	printf("%d\n",dp[q[i]]);
	return 0;
}


E. Concatenation with intersectiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVasya had three strings aa, bb and ss, which consist of lowercase English letters. The lengths of strings aa and bb are equal to nn, the length of the string ss is equal to mm. Vasya decided to choose a substring of the string aa, then choose a substring of the string bb and concatenate them. Formally, he chooses a segment [l1,r1][l1,r1] (1≤l1≤r1≤n1≤l1≤r1≤n) and a segment [l2,r2][l2,r2] (1≤l2≤r2≤n1≤l2≤r2≤n), and after concatenation he obtains a string a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2.Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions:  segments [l1,r1][l1,r1] and [l2,r2][l2,r2] have non-empty intersection, i.e. there exists at least one integer xx, such that l1≤x≤r1l1≤x≤r1 and l2≤x≤r2l2≤x≤r2;  the string a[l1,r1]+b[l2,r2]a[l1,r1]+b[l2,r2] is equal to the string ss. InputThe first line contains integers nn and mm (1≤n≤500000,2≤m≤2⋅n1≤n≤500000,2≤m≤2⋅n) — the length of strings aa and bb and the length of the string ss.The next three lines contain strings aa, bb and ss, respectively. The length of the strings aa and bb is nn, while the length of the string ss is mm.All strings consist of lowercase English letters.OutputPrint one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions.ExamplesInputCopy6 5aabbaabaaaabaaaaaOutputCopy4InputCopy5 4azazazazazazazOutputCopy11InputCopy9 12abcabcabcxyzxyzxyzabcabcayzxyzOutputCopy2NoteLet's list all the pairs of segments that Vasya could choose in the first example:  [2,2][2,2] and [2,5][2,5];  [1,2][1,2] and [2,4][2,4];  [5,5][5,5] and [2,5][2,5];  [5,6][5,6] and [3,5][3,5];

#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 = 1e6 + 5, mod = 1e9 + 7; // !

int t, fw[2][N], n, h[N], hA[N], hB[N], pwr[N];

vector<int> en[N], st[N];

void upd(int t, int id, int v) {

    for(id; id <= n; id += id & (-id)) fw[t][id] += v;

}

int get(int t, int id) {

    int ans = 0;

    id = min(id, n);

    for(id; id >= 1; id -= id & (-id)) ans += fw[t][id];

    return ans;

}

//int h[N], hA[N], hB[N];

main(){

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

    int m;

    cin >> n >> m;

    string a, b, s;

    cin >> a >> b >> s;

    a = '#' + a; b = '#' + b; s = '#' + s;

    pwr[0] = 1;

    int p = 37;

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

        h[i] = (h[i - 1] * p + s[i] - 'a' + 1) % mod;

        pwr[i] = pwr[i - 1] * p % mod;

    }

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

        hA[i] = (hA[i - 1] * p + a[i] - 'a' + 1) % mod;

        hB[i] = (hB[i - 1] * p + b[i] - 'a' + 1) % mod;

    }

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

        int l = 1, r = min(m, n - i + 1), x = 0;

        while(l <= r) {

            int mid = (l + r) / 2;

            if((hA[i + mid - 1] - hA[i - 1] * pwr[mid] % mod + mod) % mod == h[mid]) x = mid, l = mid + 1;

            else r = mid - 1;

        }

        if(x) en[x + 1].push_back(i), upd(0, i, 1);

        l = 1, r = min(i, m), x = 0;

        while(l <= r) {

            int mid = (l + r) / 2;

            if((hB[i] - hB[i - mid] * pwr[mid] % mod + mod) % mod == (h[m] - h[m - mid] * pwr[mid] % mod + mod) % mod) x = mid, l = mid + 1;

            else r = mid - 1;

        }

        st[min(x, m - 1)].push_back(i);

         // en - st < m - 1; en < st + m - 1

    }

    int cur = 0, ans = 0;

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

        for(int j = 0; j < en[i].size(); j++) {

            cur -= get(1, en[i][j] + m - 2) - get(1, en[i][j] - 1);

            upd(0, en[i][j], -1);

        }

        for(int j = 0; j < st[m - i].size(); j++) {

            int x = st[m - i][j];

         //   cout << "++++ " << 1 << " " << x << " " << get(0, st[m - i][j]) << endl;

            cur += get(0, st[m - i][j]) - get(0, st[m - i][j] - m + 1);

            upd(1, st[m - i][j], 1);

        }

        ans += cur;

    }

    cout << ans;

 }