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

#include<iostream>

#include<algorithm>

using namespace std;

int tab[200006];

int main(){

int t;

cin>>t;

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

    int n;

    cin>>n;

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

        cin>>tab[i];

    }

    sort(tab,tab+2*n);

    cout<<tab[n]-tab[n-1]<<"\n";

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

        tab[i]=0;

    }

}

}


E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]:   if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2];  if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2];  if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4
3 5 1 4
OutputCopy1 3
2 5
1 4
1 5
1 5
InputCopy4 3
1 2 4
OutputCopy1 3
1 2
3 4
1 4
NoteIn the first example; Polycarp's recent chat list looks like this:   [1,2,3,4,5][1,2,3,4,5]  [3,1,2,4,5][3,1,2,4,5]  [5,3,1,2,4][5,3,1,2,4]  [1,5,3,2,4][1,5,3,2,4]  [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this:   [1,2,3,4][1,2,3,4]  [1,2,3,4][1,2,3,4]  [2,1,3,4][2,1,3,4]  [4,2,1,3][4,2,1,3]

#include <bits/stdc++.h>

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

#define file(s) if (fopen(s".in", "r")) freopen(s".in", "r", stdin), freopen(s".out", "w", stdout)

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

#define F first

#define S second

using namespace std;

using ll = long long;

const ll N = 6e5+5 , inf = 2e9 + 7;

const ll INF = 1e18 ,   mod = 1e9+7 , P = 6547;

ll a[N] , t[N*4] , mn[N] , mx[N] , p[N];

ll n , m;

void build(ll v , ll tl , ll tr){

	if(tl > n) return;

	if(tl == tr){

		t[v] = 1;

		return;

	}

	ll tm = (tl+tr) >> 1;

	build(v*2,tl,tm);

	build(v*2+1,tm+1,tr);

	t[v] = t[v*2] + t[v*2+1];

}

ll get(ll v, ll tl , ll tr , ll l){

	if(tl >= l) return t[v];

	if(tr < l) return 0;

	ll tm = (tl+tr) >> 1;

	return get(v*2,tl,tm,l) + get(v*2+1,tm+1,tr,l);

}

void upd(ll v, ll tl, ll tr , ll pos, ll val){

	if(tl == tr){

		t[v] = val;

		return;

	}

	ll tm = (tl+tr) >> 1;

	if(tm >= pos) upd(v*2,tl,tm,pos,val);

	else upd(v*2+1,tm+1,tr,pos,val);

	t[v] = t[v*2] + t[v*2+1];

}

void solve(){

	cin >> n >> m;

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

		mn[i] = i;

		mx[i] = i;

		p[i] = n-i+1;

	}

	build(1,1,n+m);

	ll nw = n+1;

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

		cin >> a[i];

		mn[a[i]] = 1;

		ll res = get(1,1,n+m,p[a[i]]);

		mx[a[i]] = max(mx[a[i]] , res);

		upd(1,1,n+m,p[a[i]],0);

		p[a[i]] = nw++;

		upd(1,1,n+m,p[a[i]],1);

	}

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

		ll res = get(1,1,n+m,p[i]);

		mx[i] = max(mx[i] , res);

	}

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

		cout << mn[i] <<" " << mx[i] <<"\n";

	}

}

/*

*/

signed main(){

	ios;

	solve();

	return 0;

}


E. Cartesian Tree time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIldar is the algorithm teacher of William and Harris. Today; Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William.A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows: If the sequence is empty, return an empty tree; Let the position of the maximum element be xx; Remove element on the position xx from the sequence and break it into the left part and the right part (which might be empty) (not actually removing it, just taking it away temporarily); Build cartesian tree for each part; Create a new vertex for the element, that was on the position xx which will serve as the root of the new tree. Then, for the root of the left part and right part, if exists, will become the children for this vertex; Return the tree we have gotten.For example, this is the cartesian tree for the sequence 4,2,7,3,5,6,14,2,7,3,5,6,1:  After teaching what the cartesian tree is, Ildar has assigned homework. He starts with an empty sequence aa.In the ii-th round, he inserts an element with value ii somewhere in aa. Then, he asks a question: what is the sum of the sizes of the subtrees for every node in the cartesian tree for the current sequence aa?Node vv is in the node uu subtree if and only if v=uv=u or vv is in the subtree of one of the vertex uu children. The size of the subtree of node uu is the number of nodes vv such that vv is in the subtree of uu.Ildar will do nn rounds in total. The homework is the sequence of answers to the nn questions.The next day, Ildar told Harris that he has to complete the homework as well. Harris obtained the final state of the sequence aa from William. However, he has no idea how to find the answers to the nn questions. Help Harris!InputThe first line contains a single integer nn (1≤n≤1500001≤n≤150000).The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n). It is guarenteed that each integer from 11 to nn appears in the sequence exactly once.OutputPrint nn lines, ii-th line should contain a single integer  — the answer to the ii-th question.ExamplesInputCopy5
2 4 1 5 3
OutputCopy1
3
6
8
11
InputCopy6
1 2 4 5 6 3
OutputCopy1
3
6
8
12
17
NoteAfter the first round; the sequence is 11. The tree is  The answer is 11.After the second round, the sequence is 2,12,1. The tree is  The answer is 2+1=32+1=3.After the third round, the sequence is 2,1,32,1,3. The tree is  The answer is 2+1+3=62+1+3=6.After the fourth round, the sequence is 2,4,1,32,4,1,3. The tree is  The answer is 1+4+1+2=81+4+1+2=8.After the fifth round, the sequence is 2,4,1,5,32,4,1,5,3. The tree is  The answer is 1+3+1+5+1=111+3+1+5+1=11.

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

#define ls 2*p

#define rs 2*p+1

#define INF 2e9

using namespace std;

void read(int &x) {

    x = 0;

    int f = 1;

    char s = getchar();

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

        if (s == '-')

            f = -1;

        s = getchar();

    }

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

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

        s = getchar();

    }

    x *= f;

}

void write(long long x) {

    if (x < 0) {

        putchar('-');

        x = (~x) + 1;

    }

    if (x > 9) {

        write(x / 10);

    }

    putchar(x % 10 + '0');

}

const int MAXN=5e5+5;

struct Seg_node{

	int Max_first;

	int Max_second;

	int Add1,Add3;

	long long sumdate;

	int Num_mx;

	int l,r;

	int Num;

}Tree[MAXN*4];

void push_up(int p)

{

	Tree[p].sumdate=Tree[ls].sumdate+Tree[rs].sumdate;

	Tree[p].Num=Tree[ls].Num+Tree[rs].Num;

	if(Tree[ls].Max_first==Tree[rs].Max_first)

	{

		Tree[p].Max_first=Tree[ls].Max_first;

		Tree[p].Num_mx=Tree[ls].Num_mx+Tree[rs].Num_mx;

		Tree[p].Max_second=max(Tree[ls].Max_second,Tree[rs].Max_second);

	}

	else if(Tree[ls].Max_first>Tree[rs].Max_first)

	{

		Tree[p].Max_first=Tree[ls].Max_first;

		Tree[p].Num_mx=Tree[ls].Num_mx;

		Tree[p].Max_second=max(Tree[ls].Max_second,Tree[rs].Max_first);

	}

	else

	{

		Tree[p].Max_first=Tree[rs].Max_first;

		Tree[p].Num_mx=Tree[rs].Num_mx;

		Tree[p].Max_second=max(Tree[rs].Max_second,Tree[ls].Max_first);

	}

	return;

}

void push_down(int p)

{

	int Mxc=max(Tree[ls].Max_first,Tree[rs].Max_first);

	if(Mxc==Tree[ls].Max_first)

	{

		if(Tree[ls].Num)

		{

			Tree[ls].Max_first+=Tree[p].Add1;

			Tree[ls].Max_second+=Tree[p].Add3;

		}

		Tree[ls].sumdate+=((long long)Tree[p].Add1*Tree[ls].Num_mx);

		Tree[ls].sumdate+=((long long)Tree[p].Add3*(Tree[ls].Num-Tree[ls].Num_mx));

		Tree[ls].Add1+=Tree[p].Add1;

		Tree[ls].Add3+=Tree[p].Add3;

	}

	else

	{

		if(Tree[ls].Num)

		{

			Tree[ls].Max_first+=Tree[p].Add3;

			Tree[ls].Max_second+=Tree[p].Add3;

		}

		Tree[ls].sumdate+=((long long)Tree[p].Add3*(Tree[ls].Num));

		Tree[ls].Add1+=Tree[p].Add3;

		Tree[ls].Add3+=Tree[p].Add3;

	}

	if(Mxc==Tree[rs].Max_first)

	{

		if(Tree[rs].Num)

		{

			Tree[rs].Max_first+=Tree[p].Add1;

			Tree[rs].Max_second+=Tree[p].Add3;

		}

		Tree[rs].sumdate+=((long long)Tree[p].Add1*Tree[rs].Num_mx);

		Tree[rs].sumdate+=((long long)Tree[p].Add3*(Tree[rs].Num-Tree[rs].Num_mx));

		Tree[rs].Add1+=Tree[p].Add1;

		Tree[rs].Add3+=Tree[p].Add3;

	}

	else

	{

		if(Tree[rs].Num)

		{

			Tree[rs].Max_first+=Tree[p].Add3;

			Tree[rs].Max_second+=Tree[p].Add3;

		}

		Tree[rs].sumdate+=((long long)Tree[p].Add3*(Tree[rs].Num));

		Tree[rs].Add1+=Tree[p].Add3;

		Tree[rs].Add3+=Tree[p].Add3;

	}

	Tree[p].Add1=0;

	Tree[p].Add3=0;

}

void Update_sum(int p,int l,int r,int v)

{

	if(l>r)

	{

		return;

	}

	if(Tree[p].l>=l&&Tree[p].r<=r)

	{

		if(Tree[p].Num)

		{

			Tree[p].Max_first+=v;

			Tree[p].Max_second+=v;

		}

		Tree[p].sumdate+=((long long)(Tree[p].Num)*v);

		Tree[p].Add1+=v;

		Tree[p].Add3+=v;

		return;

	}

	int mid=(Tree[p].l+Tree[p].r)>>1;

	push_down(p);

	if(l<=mid)

	{

		Update_sum(ls,l,r,v);

	}

	if(r>mid)

	{

		Update_sum(rs,l,r,v);

	}

	push_up(p);

}

void update_min(int p,int v)

{

	if(Tree[p].l==Tree[p].r)

	{

		Tree[p].Max_first=min(Tree[p].Max_first,v);

		Tree[p].sumdate=Tree[p].Max_first;

		return;

	}

	if(Tree[p].Max_first<v)

	{

		return;

	}

	else if(Tree[p].Max_first>=v&&Tree[p].Max_second<v)

	{

		if(Tree[p].Num)

		{

			int Detl=(Tree[p].Max_first-v);

			Tree[p].sumdate-=((long long)Detl*Tree[p].Num_mx);

			Tree[p].Add1-=Detl;

			Tree[p].Max_first=v;

		}

		return;

	}

	else

	{

		push_down(p);

		update_min(ls,v);

		update_min(rs,v);

		push_up(p);

	}

}

void Update_min(int p,int l,int r,int v)

{

	if(l>r)

	{

		return;

	}

	if(Tree[p].l>=l&&Tree[p].r<=r)

	{

		update_min(p,v);

		return;

	}

	push_down(p);

	int mid=(Tree[p].l+Tree[p].r)>>1;

	if(l<=mid)

	{

		Update_min(ls,l,r,v);

	}

	if(r>mid)

	{

		Update_min(rs,l,r,v);

	}

	push_up(p);

}

void Update(int p,int k)

{

	if(Tree[p].l==Tree[p].r)

	{

		Tree[p].Num++;

		return;

	}

	push_down(p);

	int mid=(Tree[p].l+Tree[p].r)>>1;

	if(k<=mid)

	{

		Update(ls,k);

	}

	else

	{

		Update(rs,k);

	}

	push_up(p);

}

int Query(int p,int l,int r)

{

	if(l>r)

	{

		return 0;

	}

	if(Tree[p].l>=l&&Tree[p].r<=r)

	{

		return Tree[p].Num;

	}

	push_down(p);

	int mid=(Tree[p].l+Tree[p].r)>>1;

	int drs=0;

	if(l<=mid)

	{

		drs+=Query(ls,l,r);

	}

	if(r>mid)

	{

		drs+=Query(rs,l,r);

	}

	return drs;

}

long long Query_sum(int p,int l,int r)

{

	if(l>r)

	{

		return 0;

	}

	if(Tree[p].l>=l&&Tree[p].r<=r)

	{

		return Tree[p].sumdate;

	}

	push_down(p);

	int mid=(Tree[p].l+Tree[p].r)>>1;

	long long Res=0;

	if(l<=mid)

	{

		Res+=Query_sum(ls,l,r);

	}

	if(r>mid)

	{

		Res+=Query_sum(rs,l,r);

	}

	return Res;

}

void print(int p)

{

	if(Tree[p].l==Tree[p].r)

	{

		printf("%d ",Tree[p].Max_first);

		return;

	}

	push_down(p);

	print(ls);

	print(rs);

}

void Build(int p,int l,int r)

{

	Tree[p].l=l;

	Tree[p].r=r;

	Tree[p].Add1=Tree[p].Add3=0;

	if(l==r)

	{

		Tree[p].Max_first=0;

		Tree[p].Max_second=-INF;

		Tree[p].Num_mx=1;

		Tree[p].sumdate=0;

		Tree[p].Num=0;

		return;

	}

	int mid=(l+r)>>1;

	Build(ls,l,mid);

	Build(rs,mid+1,r);

	push_up(p);

}

int n;

int a[MAXN];

int rev[MAXN];

long long Sum[MAXN];

signed main()

{

	scanf("%d",&n);

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

	{

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

		rev[a[i]]=i;

	}

	Build(1,1,n);

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

	{

		Update(1,rev[i]);

		Update_sum(1,rev[i]+1,n,1);

		Update_sum(1,rev[i],rev[i],i);

		int Rx=Query(1,1,rev[i]-1);

		Update_min(1,1,rev[i]-1,Rx);

		Sum[i]+=Query_sum(1,1,n);

	}

	reverse(a+1,a+1+n);

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

	{

		rev[a[i]]=i;

	}

	Build(1,1,n);

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

	{

		Update(1,rev[i]);

		Update_sum(1,rev[i]+1,n,1);

		int Rg=Query(1,1,n);

		Update_sum(1,rev[i],rev[i],Rg);

		int Rx=Query(1,1,rev[i]-1);

		Update_min(1,1,rev[i]-1,Rx);

		Sum[i]+=Query_sum(1,1,n);

		Sum[i]-=(long long)i*i;

		printf("%lld\n",Sum[i]);

	}

}

//5

//3 5 1 4 2


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>

using namespace std;

int const M=1000100;char ch;

int i,n,k,x,a[M],f[M],g[M],s[M];

vector<pair<char,int> >G[M];

void dfs(int x,int p){

	f[x]=f[p]+1;g[x]=min(f[x],g[p]+s[p]);

	if (s[x]) f[x]=min(f[x],g[x]+1);

	sort(G[x].begin(),G[x].end());

	for (auto v:G[x]) dfs(v.second,x);

	s[p]+=s[x];

}

int main(){

	scanf("%d",&n);

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

	  scanf("%d %c",&x,&ch);

	  G[x].push_back(make_pair(ch,i));

	  }

	scanf("%d",&k);

	for (i=1;i<=k;i++) scanf("%d",&a[i]),s[a[i]]=1;

	f[0]=-1;dfs(0,0);

	for (i=1;i<=k;i++) printf("%d ",f[a[i]]);

	return 0;

}


F. Cow and Vacationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is planning a vacation! In Cow-lifornia; there are nn cities, with n−1n−1 bidirectional roads connecting them. It is guaranteed that one can reach any city from any other city. Bessie is considering vv possible vacation plans, with the ii-th one consisting of a start city aiai and destination city bibi.It is known that only rr of the cities have rest stops. Bessie gets tired easily, and cannot travel across more than kk consecutive roads without resting. In fact, she is so desperate to rest that she may travel through the same city multiple times in order to do so.For each of the vacation plans, does there exist a way for Bessie to travel from the starting city to the destination city?InputThe first line contains three integers nn, kk, and rr (2≤n≤2⋅1052≤n≤2⋅105, 1≤k,r≤n1≤k,r≤n)  — the number of cities, the maximum number of roads Bessie is willing to travel through in a row without resting, and the number of rest stops.Each of the following n−1n−1 lines contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), meaning city xixi and city yiyi are connected by a road. The next line contains rr integers separated by spaces  — the cities with rest stops. Each city will appear at most once.The next line contains vv (1≤v≤2⋅1051≤v≤2⋅105)  — the number of vacation plans.Each of the following vv lines contain two integers aiai and bibi (1≤ai,bi≤n1≤ai,bi≤n, ai≠biai≠bi)  — the start and end city of the vacation plan. OutputIf Bessie can reach her destination without traveling across more than kk roads without resting for the ii-th vacation plan, print YES. Otherwise, print NO.ExamplesInputCopy6 2 1
1 2
2 3
2 4
4 5
5 6
2
3
1 3
3 5
3 6
OutputCopyYES
YES
NO
InputCopy8 3 3
1 2
2 3
3 4
4 5
4 6
6 7
7 8
2 5 8
2
7 1
8 1
OutputCopyYES
NO
NoteThe graph for the first example is shown below. The rest stop is denoted by red.For the first query; Bessie can visit these cities in order: 1,2,31,2,3.For the second query, Bessie can visit these cities in order: 3,2,4,53,2,4,5. For the third query, Bessie cannot travel to her destination. For example, if she attempts to travel this way: 3,2,4,5,63,2,4,5,6, she travels on more than 22 roads without resting.  The graph for the second example is shown below.

#include <bits/stdc++.h>

using namespace std;

#define Int register int

#define MAXN 400005

template <typename T> inline void read (T &t){t = 0;char c = getchar();int f = 1;while (c < '0' || c > '9'){if (c == '-') f = -f;c = getchar();}while (c >= '0' && c <= '9'){t = (t << 3) + (t << 1) + c - '0';c = getchar();} t *= f;}

template <typename T,typename ... Args> inline void read (T &t,Args&... args){read (t);read (args...);}

template <typename T> inline void write (T x){if (x < 0){x = -x;putchar ('-');}if (x > 9) write (x / 10);putchar (x % 10 + '0');}

template <typename T> inline void chkmax (T &a,T b){a = max (a,b);}

template <typename T> inline void chkmin (T &a,T b){a = min (a,b);}

int n,K,R;

vector <int> g[MAXN];

int fa[MAXN],dep[MAXN],dis[MAXN],par[MAXN][21];

void dfs1 (int u,int pat){

    par[u][0] = pat,dep[u] = dep[pat] + 1;

    for (Int i = 1;i <= 20;++ i) par[u][i] = par[par[u][i - 1]][i - 1];

    for (Int v : g[u]) if (v != pat) dfs1 (v,u);

}

int getlca (int u,int v){

    if (dep[u] < dep[v]) swap (u,v);

    for (Int i = 20,dis = dep[u] - dep[v];~i;-- i) if (dis >> i & 1) u = par[u][i];

    if (u == v) return u;

    else{

        for (Int i = 20;~i;-- i) if (par[u][i] ^ par[v][i]) u = par[u][i],v = par[v][i];

        return par[u][0];

    }

}

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

int getdist (int u,int v){

    return dep[u] + dep[v] - dep[getlca (u,v)] * 2;

}

int getclimb (int u,int t){

    for (Int i = 20;~i;-- i) if (t >> i & 1) u = par[u][i];

    return u;

}

signed main(){

    read (n,K,R);int now = n;

    for (Int x = 1;x <= 2 * n;++ x) fa[x] = x;

    for (Int i = 2,u,v;i <= n;++ i)

        read (u,v),++ now,g[u].push_back (now),g[v].push_back (now),g[now].push_back (u),g[now].push_back (v);

    queue <int> q;memset (dis,-1,sizeof (dis));

 	for (Int i = 1,x;i <= R;++ i) read (x),q.push (x),dis[x] = 0;

    while (!q.empty()){

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

        if (dis[u] == K) break;

        for (Int v : g[u]){

            fa[findSet (v)] = findSet (u);

            if (dis[v] == -1) dis[v] = dis[u] + 1,q.push (v);

        }

    }

    dfs1 (1,0);

    int Q;read (Q);

    while (Q --> 0){

        int u,v;read (u,v);int len = getdist (u,v);

        if (len <= 2 * K){puts ("YES");continue;}

        int lca = getlca (u,v);

        int tu = (dep[u] - dep[lca] >= K) ? getclimb (u,K) : getclimb (v,len - K),

            tv = (dep[v] - dep[lca] >= K) ? getclimb (v,K) : getclimb (u,len - K);

        if (findSet (tu) == findSet (tv)) puts ("YES");

        else puts ("NO");

    }

    return 0;

}


E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9
abacbecfd
OutputCopy2
1 1 2 1 2 1 2 1 2
InputCopy8
aaabbcbb
OutputCopy2
1 2 1 2 1 2 1 1
InputCopy7
abcdedc
OutputCopy3
1 1 1 1 1 2 3
InputCopy5
abcde
OutputCopy1
1 1 1 1 1

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

#define mod 1000000007

#define ll long long int

#define endl '\n'

#define mem(a,x) memset(a,x,sizeof(a))

#define EPS 1e-12

#define double long double

using namespace std;

using namespace __gnu_pbds;

typedef tree<ll, null_type, less_equal<ll>, rb_tree_tag, tree_order_statistics_node_update> pbds;

//cout << "0th element: " << *A.find_by_order(0) << endl;

//cout << "No. of elems smaller than 6: " << A.order_of_key(6) << endl;

//priority_queue <int, vector<int>, greater<int>>

ll pow1(ll a,ll b){ll ans=1; while(b>0){if(b%2==0){b=b/2;a=(a*a)%mod;}else{b--;ans=(ans*a)%mod;}}return ans;}

ll mod1=1e9+9;

ll pow2(ll a,ll b){ll ans=1; while(b>0){if(b%2==0){b=b/2;a=(a*a)%mod1;}else{b--;ans=(ans*a)%mod1;}}return ans;}

ll lcm(ll a,ll b)

{

    return (a*b)/__gcd(a,b);

}

const int N=3e5+2;

void solve()

{

    ll n,i,j,a;

    cin>>n;

    string s;

    cin>>s;

    ll ar[n+2],dp[n+2];

    ll mx[27];

    mem(mx,0);

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

    {

        ar[i]=(int)s[i]-97;

        dp[i]=1;

    }

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

    {

        for(j=25;j>ar[i];j--)

        {

            dp[i]=max(dp[i],mx[j]+1);

        }

        mx[ar[i]]=max(mx[ar[i]],dp[i]);

    }

    ll ans=0;

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

    {

        ans=max(ans,dp[i]);

    }

    cout<<ans<<endl;

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

    {

        cout<<dp[i]<<" ";

    }

    cout<<endl;

}

int main()

{

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

    int t;

    t=1;

    int cs=1;

    //cin>>t;

    while (t--)

    {

        //cout<<"Case "<<cs<<": ";

        solve();

        cs++;

    }

}


A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
OutputCopy56
6
442
1
45
80
NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window.

#include <bits/stdc++.h>

#pragma GCC optimize("Ofast")

#pragma GCC optimize("no-stack-protector")

#pragma GCC optimize("unroll-loops")

#pragma GCC target("sse,sse2,sse3,ssse3,popcnt,abm,mmx,tune=native")

#pragma GCC optimize("fast-math")

#pragma GCC optimize ("unroll-loops,Ofast,O3")

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

#define file(s) freopen(s".in", "r", stdin), freopen(s".out", "w", stdout)

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

#define int long long

#define rs(p) (p<<1|1)

#define ls(p) (p<<1)

#define pb push_back

#define endl '\n'

#define sz size()

#define F first

#define S second

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

using namespace std;

const long double eps = 1e-10;

const int MIN = LLONG_MIN;

const int M = 2e9 + 1000;

const int N = 1e5 + 100;

void solve() {

	int a, b, i, j;

	cin >> a >> b >> i >> j;

	int ans = max(b * (a - i - 1), a * (b - j - 1));

	ans = max(a * j, ans);

	ans = max(b * i, ans);

	cout << ans << endl;

}

signed main () {

	SlimShady

    int test = 1;

    cin >> test;

    while(test--) {

	    solve();

	}

}


F2. Animal Observation (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way:   On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days.  On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days.  If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤m1≤k≤m) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1:   Example 2:   Example 3:   Example 4:

#include<bits/stdc++.h>

using namespace std;

int dp[51][20009];

int a[51][20009];

int pf[51][20009];

int st[80009];

int lazy[80009];

void push(int id){

if (lazy[id]==0)return;

st[id*2]+=lazy[id];

st[id*2+1]+=lazy[id];

lazy[id*2]+=lazy[id];

lazy[id*2+1]+=lazy[id];

lazy[id]=0;

}

void update(int id,int l,int r,int u,int v,int val){

if (l>v||r<u||u>v)return;

if (u<=l&&r<=v){

    st[id]+=val;

    lazy[id]+=val;

    return;

}

int mid=(l+r)/2;

push(id);

update(id*2,l,mid,u,v,val);

update(id*2+1,mid+1,r,u,v,val);

st[id]=max(st[id*2],st[id*2+1]);

}

int get(int id,int l,int r,int u,int v){

if (l>v||r<u||u>v)return 0;

if (u<=l&&r<=v){

    return st[id];

}

push(id);

int mid=(l+r)/2;

return max(get(id*2,l,mid,u,v),get(id*2+1,mid+1,r,u,v));

}

signed main(){

	ios_base::sync_with_stdio(NULL);

	cin.tie(nullptr);

	//freopen("usaco.INP","r",stdin);

	//freopen("usaco.ANS","w",stdout);

	int n,m,k;

	cin>>n>>m>>k;

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

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

            cin>>a[i][j];

            pf[i][j]=pf[i][j-1]+a[i][j];

        }

	}

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

        dp[1][i]=pf[1][i]-pf[1][i-k];

	}

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

        deque<int>id;

        memset(st,0,sizeof(st));

        memset(lazy,0,sizeof(lazy));

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

            update(1,1,m,j,j,dp[i-1][j]);

        }

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

            while (!id.empty()&&j-1-k>=id.front())id.pop_front();

            if (!id.empty()){

                int fi=id.front(),se=id.back();

                update(1,1,m,fi,se,a[i][j-k]);

                //cerr<<fi<<" "<<se<<" "<<j<<'\n';

            }

            dp[i][j]=get(1,1,m,k,j)+pf[i][j]-pf[i][j-k];

            //if (i==4&&j==m)cerr<<pf[i][j]-pf[i][j-k]<<'\n';

            id.push_back(j);

        }

        memset(st,0,sizeof(st));

        memset(lazy,0,sizeof(lazy));

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

            update(1,1,m,j,j,dp[i-1][j]);

        }

        id.clear();

        for (int j=m;j>=k;j--){

            while (!id.empty()&&id.front()-k>=j+1)id.pop_front();

            if (!id.empty()){

                int fi=id.back(),se=id.front();

                update(1,1,m,fi,se,a[i][j+1]);

                //cerr<<fi<<" "<<se<<" "<<i<<" "<<j<<'\n';

            }

            dp[i][j]=max(dp[i][j],get(1,1,m,j,m)+pf[i][j]-pf[i][j-k]);

            id.push_back(j);

        }

	}

	int ans=0;

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

        ans=max(ans,dp[n][i]);

	}

	cout<<ans;

}


A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5
1 1 1 0 0
0 1 1 1 1
OutputCopy3
InputCopy3
0 0 0
0 0 0
OutputCopy-1
InputCopy4
1 1 1 1
1 1 1 1
OutputCopy-1
InputCopy9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
OutputCopy4
NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.

#include <bits/stdc++.h>

using namespace std;

int main()

{

    int n;

    cin>>n;

    int a[n],b[n];

    int count1=0,count2=0;

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

    {

        cin>>a[i];

    }

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

    {

        cin>>b[i];

    }

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

    {

        if(a[i]==1 && b[i]==0)

            count1++;

        else if(a[i]==0 && b[i]==1)

            count2++;

    }

    if(count1==0)

    {

        cout<<"-1"<<endl;

        return 0;

    }

    int p = count2/count1+1;

    cout<<p<<endl;

    return 0;

}


#include <bits/stdc++.h>
using namespace std;

#define Int register int
#define MAXN 400005

template <typename T> inline void read (T &t){t = 0;char c = getchar();int f = 1;while (c < '0' || c > '9'){if (c == '-') f = -f;c = getchar();}while (c >= '0' && c <= '9'){t = (t << 3) + (t << 1) + c - '0';c = getchar();} t *= f;}
template <typename T,typename ... Args> inline void read (T &t,Args&... args){read (t);read (args...);}
template <typename T> inline void write (T x){if (x < 0){x = -x;putchar ('-');}if (x > 9) write (x / 10);putchar (x % 10 + '0');}
template <typename T> inline void chkmax (T &a,T b){a = max (a,b);}
template <typename T> inline void chkmin (T &a,T b){a = min (a,b);}

int n,K,R;
vector <int> g[MAXN];

int fa[MAXN],dep[MAXN],dis[MAXN],par[MAXN][21];
void dfs1 (int u,int pat){
    par[u][0] = pat,dep[u] = dep[pat] + 1;
    for (Int i = 1;i <= 20;++ i) par[u][i] = par[par[u][i - 1]][i - 1];
    for (Int v : g[u]) if (v != pat) dfs1 (v,u);
}

int getlca (int u,int v){
    if (dep[u] < dep[v]) swap (u,v);
    for (Int i = 20,dis = dep[u] - dep[v];~i;-- i) if (dis >> i & 1) u = par[u][i];
    if (u == v) return u;
    else{
        for (Int i = 20;~i;-- i) if (par[u][i] ^ par[v][i]) u = par[u][i],v = par[v][i];
        return par[u][0];
    }
}

int findSet (int x){return fa[x] == x ? x : fa[x] = findSet (fa[x]);}
int getdist (int u,int v){
    return dep[u] + dep[v] - dep[getlca (u,v)] * 2;
}
int getclimb (int u,int t){
    for (Int i = 20;~i;-- i) if (t >> i & 1) u = par[u][i];
    return u;
}

signed main(){
    read (n,K,R);int now = n;
    for (Int x = 1;x <= 2 * n;++ x) fa[x] = x;
    for (Int i = 2,u,v;i <= n;++ i)
        read (u,v),++ now,g[u].push_back (now),g[v].push_back (now),g[now].push_back (u),g[now].push_back (v);
    queue <int> q;memset (dis,-1,sizeof (dis));
 	for (Int i = 1,x;i <= R;++ i) read (x),q.push (x),dis[x] = 0;
    while (!q.empty()){
        int u = q.front();q.pop ();
        if (dis[u] == K) break;
        for (Int v : g[u]){
            fa[findSet (v)] = findSet (u);
            if (dis[v] == -1) dis[v] = dis[u] + 1,q.push (v);
        }
    }
    dfs1 (1,0);
    int Q;read (Q);
    while (Q --> 0){
        int u,v;read (u,v);int len = getdist (u,v);
        if (len <= 2 * K){puts ("YES");continue;}
        int lca = getlca (u,v);
        int tu = (dep[u] - dep[lca] >= K) ? getclimb (u,K) : getclimb (v,len - K),
            tv = (dep[v] - dep[lca] >= K) ? getclimb (v,K) : getclimb (u,len - K);
        if (findSet (tu) == findSet (tv)) puts ("YES");
        else puts ("NO");
    }
    return 0;
}


B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2
1 0 1
1 1 1
OutputCopy4
InputCopy3 5 4
1 1 1
1 1 1 1 1
OutputCopy14
NoteIn first example matrix cc is:  There are 44 subrectangles of size 22 consisting of only ones in it:  In second example matrix cc is:

#include<iostream>
#include<cstring>
#include<vector>
#include<map>
#include<queue>
#include<unordered_map>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<set>
#include<cstdlib>
#include<stack>
#include<ctime>
#define forin(i,a,n) for(int i=a;i<=n;i++)
#define forni(i,n,a) for(int i=n;i>=a;i--)
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef double db;
typedef pair<int,int> PII;
const double eps=1e-7;
const int N=6e5+7 ,M=2*N , INF=0x3f3f3f3f,mod=1e9+7;
inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;}
void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);}

template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);}
template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);}

int T;
int n,m,k;
int a[N],b[N];
int la[N],lb[N];

void solve() {
    n=read(),m=read(),k=read();

    for(int i=1;i<=n;i++) a[i]=read();
    for(int i=1;i<=m;i++) b[i]=read();

    vector<int> vec;
    for(int i=1;i<=k/i;i++) {
        if(k%i==0) {
            vec.push_back(i);
            if(i!=k/i) vec.push_back(k/i);
        }
    }

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

    int last=0;
    for(int i=1;i<=n;i++) {
        if(a[i]==1) last++;
        else {
            int temp=last;
            for(int j=1;j<=temp;j++) la[j]+=last--;
            last=0;
        }
    }

    if(last!=0) {
        int temp=last;
        for(int j=1;j<=temp;j++) la[j]+=last--;
    }

    last=0;
    for(int i=1;i<=m;i++) {
        if(b[i]==1) last++;
        else {
            int temp=last;
            for(int j=1;j<=temp;j++) lb[j]+=last--;
            last=0;
        }
    }

    if(last!=0) {
        int temp=last;
        for(int j=1;j<=temp;j++) lb[j]+=last--;
    }

    ll ans=0;
    for(int i=0;i<vec.size();i++) {
        int l=vec[i],r=k/vec[i];
        if(l>=1&&l<=n&&r>=1&&r<=m) {
            ans+=(ll)la[l]*lb[r];
        }
    }

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

int main() {
    // init();
    // stin();

    // scanf("%d",&T);
    T=1;
    while(T--) solve();

    return 0;
}


C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
OutputCopy1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

using vi = vector<ll>;

using si = set<ll>;

int main() {

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

  ll t, n;

  cin >> t;

  while (t--) {

    cin >> n;

    si s;

    for (int i = 1; i <= 2*n; i++) s.insert(i);

    vi a(2*n), b(n), c(n), d(n+1);

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

      cin >> b[i];

      c[i] = b[i];

      s.erase(b[i]);

    }

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

    bool ok=1;

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

      if (c[i] > j) {

        ok=0;

        break;

      }

    }

    if (!ok) cout << "-1\n";

    else {

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

        a[2*i] = b[i];

        int next = *lower_bound(s.begin(), s.end(), b[i]);

        s.erase(next);

        a[2*i+1] = next;

      }

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

        cout << a[i] << " \n"[i==2*n-1];

    }

  }

}


F. Blocks and Sensorstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPolycarp plays a well-known computer game (we won't mention its name). Every object in this game consists of three-dimensional blocks — axis-aligned cubes of size 1×1×11×1×1. These blocks are unaffected by gravity, so they can float in the air without support. The blocks are placed in cells of size 1×1×11×1×1; each cell either contains exactly one block or is empty. Each cell is represented by its coordinates (x,y,z)(x,y,z) (the cell with these coordinates is a cube with opposite corners in (x,y,z)(x,y,z) and (x+1,y+1,z+1)(x+1,y+1,z+1)) and its contents ax,y,zax,y,z; if the cell is empty, then ax,y,z=0ax,y,z=0, otherwise ax,y,zax,y,z is equal to the type of the block placed in it (the types are integers from 11 to 2⋅1052⋅105).Polycarp has built a large structure consisting of blocks. This structure can be enclosed in an axis-aligned rectangular parallelepiped of size n×m×kn×m×k, containing all cells (x,y,z)(x,y,z) such that x∈[1,n]x∈[1,n], y∈[1,m]y∈[1,m], and z∈[1,k]z∈[1,k]. After that, Polycarp has installed 2nm+2nk+2mk2nm+2nk+2mk sensors around this parallelepiped. A sensor is a special block that sends a ray in some direction and shows the type of the first block that was hit by this ray (except for other sensors). The sensors installed by Polycarp are adjacent to the borders of the parallelepiped, and the rays sent by them are parallel to one of the coordinate axes and directed inside the parallelepiped. More formally, the sensors can be divided into 66 types:  there are mkmk sensors of the first type; each such sensor is installed in (0,y,z)(0,y,z), where y∈[1,m]y∈[1,m] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OxOx axis and has the same direction;  there are mkmk sensors of the second type; each such sensor is installed in (n+1,y,z)(n+1,y,z), where y∈[1,m]y∈[1,m] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OxOx axis and has the opposite direction;  there are nknk sensors of the third type; each such sensor is installed in (x,0,z)(x,0,z), where x∈[1,n]x∈[1,n] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OyOy axis and has the same direction;  there are nknk sensors of the fourth type; each such sensor is installed in (x,m+1,z)(x,m+1,z), where x∈[1,n]x∈[1,n] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OyOy axis and has the opposite direction;  there are nmnm sensors of the fifth type; each such sensor is installed in (x,y,0)(x,y,0), where x∈[1,n]x∈[1,n] and y∈[1,m]y∈[1,m], and it sends a ray that is parallel to the OzOz axis and has the same direction;  finally, there are nmnm sensors of the sixth type; each such sensor is installed in (x,y,k+1)(x,y,k+1), where x∈[1,n]x∈[1,n] and y∈[1,m]y∈[1,m], and it sends a ray that is parallel to the OzOz axis and has the opposite direction. Polycarp has invited his friend Monocarp to play with him. Of course, as soon as Monocarp saw a large parallelepiped bounded by sensor blocks, he began to wonder what was inside of it. Polycarp didn't want to tell Monocarp the exact shape of the figure, so he provided Monocarp with the data from all sensors and told him to try guessing the contents of the parallelepiped by himself.After some hours of thinking, Monocarp has no clue about what's inside the sensor-bounded space. But he does not want to give up, so he decided to ask for help. Can you write a program that will analyze the sensor data and construct any figure that is consistent with it?InputThe first line contains three integers nn, mm and kk (1≤n,m,k≤2⋅1051≤n,m,k≤2⋅105, nmk≤2⋅105nmk≤2⋅105) — the dimensions of the parallelepiped.Then the sensor data follows. For each sensor, its data is either 00, if the ray emitted from it reaches the opposite sensor (there are no blocks in between), or an integer from 11 to 2⋅1052⋅105 denoting the type of the first block hit by the ray. The data is divided into 66 sections (one for each type of sensors), each consecutive pair of sections is separated by a blank line, and the first section is separated by a blank line from the first line of the input.The first section consists of mm lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (0,i,j)(0,i,j).The second section consists of mm lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (n+1,i,j)(n+1,i,j).The third section consists of nn lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,0,j)(i,0,j).The fourth section consists of nn lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,m+1,j)(i,m+1,j).The fifth section consists of nn lines containing mm integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,j,0)(i,j,0).Finally, the sixth section consists of nn lines containing mm integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,j,k+1)(i,j,k+1).OutputIf the information from the input is inconsistent, print one integer −1−1.Otherwise, print the figure inside the parallelepiped as follows. The output should consist of nmknmk integers: a1,1,1a1,1,1, a1,1,2a1,1,2, ..., a1,1,ka1,1,k, a1,2,1a1,2,1, ..., a1,2,ka1,2,k, ..., a1,m,ka1,m,k, a2,1,1a2,1,1, ..., an,m,kan,m,k, where ai,j,kai,j,k is the type of the block in (i,j,k)(i,j,k), or 00 if there is no block there. If there are multiple figures consistent with sensor data, describe any of them.For your convenience, the sample output is formatted as follows: there are nn separate sections for blocks having x=1x=1, x=2x=2, ..., x=nx=n; each section consists of mm lines containing kk integers each. Note that this type of output is acceptable, but you may print the integers with any other formatting instead (even all integers on the same line), only their order matters.ExamplesInputCopy4 3 2

1 4
3 2
6 5

1 4
3 2
6 7

1 4
1 4
0 0
0 7

6 5
6 5
0 0
0 7

1 3 6
1 3 6
0 0 0
0 0 7

4 3 5
4 2 5
0 0 0
0 0 7
OutputCopy1 4
3 0
6 5

1 4
3 2
6 5

0 0
0 0
0 0

0 0
0 0
0 7
InputCopy1 1 1

0

0

0

0

0

0
OutputCopy0
InputCopy1 1 1

0

0

1337

0

0

0
OutputCopy-1
InputCopy1 1 1

1337

1337

1337

1337

1337

1337
OutputCopy1337

// LUOGU_RID: 100810478
#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
namespace IO {
const int SIZ = 1 << 14;

inline char getc() {
    static char bf[SIZ], *begin = bf, *end = bf;
    if (begin == end) begin = bf, end = bf + fread(bf, 1, SIZ, stdin);
    if (begin == end) return EOF;
    return *begin++;
}
char wbf[SIZ], *wend = wbf, *weoo = wbf + SIZ;
inline void putc(char c) {
    *wend = c, ++wend;
    if (wend == weoo) fwrite(wbf, 1, SIZ, stdout), wend = wbf;
}
inline void do_flush() { fwrite(wbf, 1, wend - wbf, stdout); }
template <typename T>
inline void uread(T &ans) {
    static char tmp;
    tmp = getc(), ans = 0;
    while (!isdigit(tmp)) tmp = getc();
    while (isdigit(tmp)) ans = (ans << 1) + (ans << 3) + (tmp ^ 48), tmp = getc();
}
template <typename T>
inline void read(T &ans) {
    static char tmp2;
    static bool flag;
    tmp2 = getc(), ans = 0, flag = 0;
    while (!isdigit(tmp2)) {
        if (tmp2 == '-') flag = 1;
        tmp2 = getc();
    }
    while (isdigit(tmp2)) ans = (ans << 1) + (ans << 3) + (tmp2 ^ 48), tmp2 = getc();
    if (flag) ans = -ans;
}
template <typename T>
inline void uwrite(T x) {
    if (x > 9) uwrite(x / 10);
    putc(x % 10 + '0');
}
template <typename T>
inline void write(T x) {
    if (x < 0)
        putc('-'), uwrite(-x);
    else
        uwrite(x);
}
inline void putstr(const char str[]) {
    for (int i = 0; str[i]; i++) putc(str[i]);
}
inline void readalpha(char &x) {
    for (x = getc(); !isalpha(x); x = getc())
        ;
}
};  // namespace IO
using IO::read, IO::write, IO::do_flush, IO::putc, IO::uread, IO::uwrite;
template <typename T>
struct Table2D {
    vector<vector<T>> vec;
    int __n, __m;
    inline void init(int n, int m) {
        vec.resize(n), __n = n, __m = m;
        for (int i = 0; i < n; i++) vec[i].resize(m);
    }

    inline void read(int n, int m) {
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++) ::read(vec[i][j]);
    }
    inline bool inrange(int x, int y) { return x >= 1 && x <= __n && y >= 1 && y <= __m; }
    inline T &at(int x, int y) { return vec[x - 1][y - 1]; }
};
template <typename T>
inline void fill(Table2D<T> &x, int k) {
    for (int i = 0; i < x.__n; i++)
        for (int j = 0; j < x.__m; j++)
            for (int l = 1; l <= k; l++) x.vec[i][j].insert(l);
}
int n, m, k;
// x:UD y:FB z:LR
Table2D<set<int>> vecD, vecB, vecL;
Table2D<set<int, greater<int>>> vecU, vecF, vecR;
Table2D<int> colU, colD, colF, colB, colL, colR;
Table2D<vector<bool>> used;
inline void make(int &a, int b) {
    if (a == -1)
        a = b;
    else if (a != b)
        a = 0;
}
inline int getcol(int x, int y, int z) {
    int col = -1;
    if (vecD.at(y, z).size() && *vecD.at(y, z).begin() == x) make(col, colD.at(y, z));  // cout << "readcolD" << colD.at(y, z) << endl ;
    if (vecU.at(y, z).size() && *vecU.at(y, z).begin() == x) make(col, colU.at(y, z));  // cout << "readcolU" << colU.at(y, z) << endl ;
    if (vecB.at(x, z).size() && *vecB.at(x, z).begin() == y) make(col, colB.at(x, z));  // cout << "readcolB" << colB.at(x, z) << endl ;
    if (vecF.at(x, z).size() && *vecF.at(x, z).begin() == y) make(col, colF.at(x, z));  // cout << "readcolF" << colF.at(x, z) << endl ;
    if (vecL.at(x, y).size() && *vecL.at(x, y).begin() == z) make(col, colL.at(x, y));  // cout << "readcolL" << colL.at(x, y) << endl ;
    if (vecR.at(x, y).size() && *vecR.at(x, y).begin() == z) make(col, colR.at(x, y));  // cout << "readcolR" << colR.at(x, y) << endl ;
    return col;
}
inline void check(int x, int y, int z) {
    if (x < 1 || x > n || y < 1 || y > m || z < 1 || z > k || !used.at(x, y)[z]) return;
    int p = getcol(x, y, z);
    if (!p) {
        // cout << "del:" << x << ' ' << y << ' ' << z << endl;
        used.at(x, y)[z] = 0;
        vecD.at(y, z).erase(x);
        vecU.at(y, z).erase(x);
        vecB.at(x, z).erase(y);
        vecF.at(x, z).erase(y);
        vecL.at(x, y).erase(z);
        vecR.at(x, y).erase(z);
        if (vecD.at(y, z).size() && *vecD.at(y, z).rbegin() > x) check(*vecD.at(y, z).upper_bound(x), y, z);
        if (vecU.at(y, z).size() && *vecU.at(y, z).rbegin() < x) check(*vecU.at(y, z).upper_bound(x), y, z);
        if (vecB.at(x, z).size() && *vecB.at(x, z).rbegin() > y) check(x, *vecB.at(x, z).upper_bound(y), z);
        if (vecF.at(x, z).size() && *vecF.at(x, z).rbegin() < y) check(x, *vecF.at(x, z).upper_bound(y), z);
        if (vecL.at(x, y).size() && *vecL.at(x, y).rbegin() > z) check(x, y, *vecL.at(x, y).upper_bound(z));
        if (vecR.at(x, y).size() && *vecR.at(x, y).rbegin() < z) check(x, y, *vecR.at(x, y).upper_bound(z));
    }
}
template <typename T>
inline bool cc(Table2D<T> &a, Table2D<int> &b) {
    for (int i = 1; i <= a.__n; i++)
        for (int j = 1; j <= a.__m; j++)
            if (b.at(i, j) && !a.at(i, j).size()) return 0;
    return 1;
}
int main() {
    cin >> n >> m >> k;
    vecU.init(m, k), vecD.init(m, k), vecF.init(n, k), vecB.init(n, k), vecL.init(n, m), vecR.init(n, m);
    fill(vecU, n), fill(vecD, n), fill(vecF, m), fill(vecB, m), fill(vecL, k), fill(vecR, k);
    colU.init(m, k), colD.init(m, k), colF.init(n, k), colB.init(n, k), colL.init(n, m), colR.init(n, m);
    colD.read(m, k), colU.read(m, k), colB.read(n, k), colF.read(n, k), colL.read(n, m), colR.read(n, m);
    used.init(n, m);
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++) {
            used.at(i, j).resize(k + 1);
            for (int l = 1; l <= k; l++) used.at(i, j)[l] = 1;
        }
    // cout << *vecR.at(1, 1).begin() << ' '<< *vecL<< endl;
    // cout << getcol(1, 1, 2) << endl;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            for (int l = 1; l <= k; l++) check(i, j, l);
    if (!cc(vecU, colU)) return puts("-1"), 0;
    if (!cc(vecD, colD)) return puts("-1"), 0;
    if (!cc(vecL, colL)) return puts("-1"), 0;
    if (!cc(vecR, colR)) return puts("-1"), 0;
    if (!cc(vecB, colB)) return puts("-1"), 0;
    if (!cc(vecF, colF)) return puts("-1"), 0;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            for (int l = 1; l <= k; l++) {
                int tmp;
                if (!used.at(i, j)[l])
                    printf("%d ", 0);
                else if ((tmp = getcol(i, j, l)) == -1)
                    printf("%d ", 0);
                else
                    printf("%d ", tmp);
            }
            puts("");
        }
        puts("");
    }
    return 0;
}


C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move:   'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y);  'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y);  'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1);  'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1

#include <bits/stdc++.h>

using namespace std;

int main() {

#ifdef _DEBUG

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

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

#endif

	int t;

	cin >> t;

	while (t--) {

		int n;

		string s;

		cin >> n >> s;

		int l = -1, r = n;

		map<pair<int, int>, int> vis;

		pair<int, int> cur = {0, 0};

		vis[cur] = 0;

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

			if (s[i] == 'L') --cur.first;

			if (s[i] == 'R') ++cur.first;

			if (s[i] == 'U') ++cur.second;

			if (s[i] == 'D') --cur.second;

			if (vis.count(cur)) {

				if (i - vis[cur] + 1 < r - l + 1) {

					l = vis[cur];

					r = i;

				}

			}

			vis[cur] = i + 1;

		}

		if (l == -1) {

			cout << -1 << endl;

		} else {

			cout << l + 1 << " " << r + 1 << endl;

		}

	}

	return 0;

}


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

#include<bits/stdc++.h>
using namespace std;
#include <iostream>
#include <cmath>
#include <algorithm>
#define ll long long
#define fi first
#define se second
#define sst string
#define pb push_back
#define maxco 100000+5
#define lld long double
#define cha ios_base::sync_with_stdio(false);
#define ffl cout.flush();
#define phi acos(-1)
#define mod 1000000007

ll a[200069];

int main(){
  ll n;
  cin>>n;
  ll m;
  cin>>m;
  for(ll i=1;i<=n;i++){
    cin>>a[i];
  }
  if(n>m){
    cout<<0<<endl;
  }
  else{
    sort(a+1,a+n+1);
    for(ll i=1;i<=n;i++){
      a[i]=(a[i]+m)%m;
    }
    ll ans=1;
    for(ll i=1;i<n;i++){
      for(ll j=i+1;j<=n;j++){
        ll val=(m+a[j]%m-a[i]%m)%m;
        // cout<<val<<" ";
        ans*=val;
        ans%=m;
      }
    }
    cout<<ans<<endl;
  }
}


B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3
tab
one
bat
OutputCopy6
tabbat
InputCopy4 2
oo
ox
xo
xx
OutputCopy6
oxxxxo
InputCopy3 5
hello
codef
orces
OutputCopy0

InputCopy9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
OutputCopy20
ababwxyzijjizyxwbaba
NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string.

#include <bits/stdc++.h>

using namespace std;

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

#define L(i, j, k) for(int i = (j); i <= (k); ++i)

#define R(i, j, k) for(int i = (j); i >= (k); --i)

#define endl '\n'

#define pb push_back

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

typedef long long ll;

const int N=2e5;

ll gcd (ll a, ll b) {

    if (b == 0)

        return a;

    else

        return gcd (b, a % b);

}

bool f(string s){

	for(int i=0;i<s.size()/2;i++){

		if(s[i]!=s[s.size()-i-1]) return false;

	}

	return true;

}

int main()

{

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    cout.tie(NULL);

    ll n,m;

    cin>>n>>m;

    bool t[n];

    string s[n];

    string x;

    bool tx=0;

    vector <string> ans;

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

    	cin>>s[i];

    	t[i]=0;

    	if(tx==false&&f(s[i])){

    		x=s[i];

    		tx=true;

		}

	}

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

		if(t[i]==0){

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

				if(i==j) continue;

				if(t[j]==1) continue;

				string a=s[j];

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

				if(s[i]==a){

					t[i]=1;

					t[j]=1;

					ans.pb(s[i]);

				}

			}

		}

	}

	cout<<ans.size()*2*m + ll(tx)*m<<"\n";

	for(int i=0;i<ans.size();i++) cout<<ans[i];

	if(tx==true) cout<<x;

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

		for(int j=ans[i].size()-1;j>=0;j--){

			cout<<ans[i][j];

		}

	}

}


E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23
16 17 14 20 20 11 22
OutputCopy3
NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good.

#include<bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

//---------------------------------------------------------------------------------

#define ll long long

#define fixed(n) cout << fixed << setprecision(n)

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

#define TC int t; cin >> t;   while(t--)

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

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

#define dl "\n"

#define Ceil(a, b) ((a / b) + (a % b ? 1 : 0))

#define pi 3.141592

#define OO 2'000'000'000

#define MOD 1'000'000'007

#define EPS 1e-10

using namespace std;

using namespace __gnu_pbds;

//---------------------------------------------------------------------------------

template <typename K, typename V, typename Comp = std::less<K>>

using ordered_map = tree<K, V, Comp, rb_tree_tag, tree_order_statistics_node_update>;

template <typename K, typename Comp = std::greater<K>>

using ordered_set = ordered_map<K, null_type, Comp>;

template <typename K, typename V, typename Comp = std::less_equal<K>>

using ordered_multimap = tree<K, V, Comp, rb_tree_tag, tree_order_statistics_node_update>;

template <typename K, typename Comp = std::less_equal<K>>

using ordered_multiset = ordered_multimap<K, null_type, Comp>;

// order_of_key(val)  count elements smaller than val

// *s.find_by_order(idx)  element with index idx

template<typename T = int > istream& operator >> (istream &in , vector < T > &v){

    for(auto &i : v) in >> i ;

    return in ;

}

template<typename T = int > ostream& operator << (ostream &out ,vector < T > &v){

    for(auto &i : v) out <<  i  << ' ' ;

    return out ;

}

//-----------------------------------------------------------------------------------------

void ZEDAN() {

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

    #ifndef ONLINE_JUDGE

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

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

    #endif

}

//-----------------------------------------(notes)-----------------------------------------

/*

*/

//-----------------------------------------(function)--------------------------------------

ll n , h , l , r ;

vector<ll>v ;

vector<vector<ll>>dp ;

bool valid(ll t){

    return t>=l &&t<=r ;

}

ll rec(ll i=0 , ll t=0){

    if(i>=n) return 0 ;

    ll &ret = dp[i][t] ;

    if(~ret) return ret ;

    return ret = max(valid((t+v[i])%h)+rec(i+1,(t+v[i])%h),valid((t+v[i]-1)%h)+rec(i+1,(t+v[i]-1)%h)) ;

}

//-----------------------------------------(code here)-------------------------------------

void solve(){

    ll n , h , l , r ;

    cin >> n >> h >> l >> r;

    vector<ll>v(n) ;

    vector<vector<ll>>dp(n+5,vector<ll>(h+5)) ;

    cin >> v ;

    auto valid=[&](ll t){

        return t>=l && t<=r ;

    };

    for(ll i=n-1 ; i>=0 ; i--){

        for(ll t=0 ; t<h ; t++){

            ll &ret = dp[i][t] ;

            ret = max(ret,valid((t+v[i])%h)+dp[i+1][(t+v[i])%h]) ;

            ret = max(ret,valid((t+v[i]-1)%h)+dp[i+1][(t+v[i]-1)%h]) ;

        }

    }

    cout << dp[0][0] ;

}

//-----------------------------------------------------------------------------------------

int main()

{

    ZEDAN() ;

    ll t = 1 ;

    // cin >> t ;

    while(t--){

        solve() ;

        if(t) cout << dl ;

    }

    return 0;

}


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

2 1 2

1 2

0

1OutputCopy

? C

? CH

? CCHO

! CCHH

InputCopy2
5

0

2 2 3

1
8

1 5

1 5

1 3

2 1 2

1OutputCopy

? O

? HHH

! CHHHH

? COO

? COOH

? HCCOO

? HH

! HHHCCOOH

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

// Problem: E. Rin and The Unknown Flower

// Contest: Codeforces - Codeforces Round #614 (Div. 1)

// URL: https://codeforces.com/problemset/problem/1292/E

// Memory Limit: 256 MB

// Time Limit: 2000 ms

//

// Powered by CP Editor (https://cpeditor.org)

//And in that light,I find deliverance.

#include<bits/stdc++.h>

// #pragma GCC optimize("Ofast")

// #pragma GCC optimize("unroll-loops")

// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")

using namespace std;

inline int read(){

   int s=0,w=1;

   char ch=getchar();

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

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

   return s*w;

}

#ifdef local

string rin;

double power_used;

vector<int> query(string s)

{

	int N=rin.size(),M=s.size();

	power_used+=1.0/(M*M);

	vector<int> res;

	for(int i=0; i+M<=N; ++i)

		if(rin.substr(i,M)==s) res.push_back(i);

	return res;

}

bool check(string s)

{

	cerr<<power_used<<endl;

	if(s!=rin)

	{

		cout<<"WA"<<endl;

		cout<<"Your output is \""<<s<<"\"."<<endl;

		cout<<"Answer is \""<<rin<<"\"."<<endl;

	}

	if(power_used>1.4)

	{

		cout<<"WA"<<endl;

		cout<<"You used "<<power_used<<" power."<<endl;

		cout<<"Answer is \""<<rin<<"\"."<<endl;

	}

	return 1;

}

#else

vector<int> query(string s)

{

	printf("? ");

	for(char i:s) putchar(i);

	puts("");

	vector<int> res;

	fflush(stdout);

	for(int T=read(); T--;) res.push_back(read()-1);

	return res;

}

bool check(string s)

{

	printf("! ");

	for(char i:s) putchar(i);

	puts("");

	fflush(stdout);

	return read();

}

#endif

bool query(string s,int pos)

{

	vector<int> v=query(s);

	for(auto i:v) if(i==pos) return 1;

	return 0;

}

signed main()

{

	for(int T=read();T--;)

	{

		int n=read();

#ifdef local

		power_used=0,cin>>rin;

#endif

		string ans(n,'A');

		if(n>4)

		{

			vector<int>

				vcc=query("CC"),

				vch=query("CH"),

				vco=query("CO"),

				voh=query("OH"),

				vho=query("HO");

			int z=233333;

			for(int i:vcc) ans[i]='C',ans[i+1]='C',z=min(z,i);

			for(int i:vch) ans[i]='C',ans[i+1]='H',z=min(z,i);

			for(int i:vco) ans[i]='C',ans[i+1]='O',z=min(z,i);

			for(int i:voh) ans[i]='O',ans[i+1]='H',z=min(z,i);

			for(int i:vho) ans[i]='H',ans[i+1]='O',z=min(z,i);

			if(z==233333)

			{

				string sc(n-1,'C'),sh(n-1,'H'),so(n-1,'O');

				vector<int> vh=query(sh);

				if(vh.empty()||vh[0]!=0) ans=so+"A";

				else ans=sh+"A";

				ans[n-1]='C';

				if(ans.substr(n-2,2)=="OH"||

				ans.substr(n-2,2)=="HO"||

				query(ans).empty())

				{

					ans[n-1]='H';

					if(ans.substr(n-2,2)=="OH"||

				ans.substr(n-2,2)=="HO"||query(ans).empty())

					ans[n-1]='O';

				}

			}

			else

			{

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

					if(ans[i]=='A') ans[i]=ans[i-1];

				if(z)

				{

					for(int i=0; i<z; ++i) ans[i]='H';

					if(!query(ans.substr(0,n-1),0))

						for(int i=0; i<z; ++i) ans[i]='O';

				}

				ans[n-1]='C';

				if(query(ans).empty())

				{

					ans[n-1]='H';

					if(query(ans).empty()) ans[n-1]='O';

				}

			}

		}

		else

		{

			vector<int>

				vcc=query("CC"),

				vch=query("CH"),

				vco=query("CO");

			for(int i:vcc) ans[i]='C',ans[i+1]='C';

			for(int i:vch) ans[i]='C',ans[i+1]='H';

			for(int i:vco) ans[i]='C',ans[i+1]='O';

			const int pos1[]={2,0,1};

			const int pos2[]={0,0,1};

			const int pos3[]={3,3,0};

			bool flg=0;

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

				if(ans[i]=='C')

				{

					if(ans[pos1[i]]=='A')

					{

						ans[pos1[i]]='C';

						if(!query(ans.substr(pos2[i],3),pos2[i]))

						{

							ans[pos1[i]]='H';

							if(!query(ans.substr(pos2[i],3),pos2[i]))

								ans[pos1[i]]='O';

						}

					}

					if(ans[pos3[i]]=='A')

					{

						ans[pos3[i]]='C';

						if(!query(ans,0))

						{

							ans[pos3[i]]='H';

							if(!query(ans,0))

								ans[pos3[i]]='O';

						}

					}

					flg=1;

					break;

				}

			if(!flg)

			{

				vector<int> t=query("OH");

				if(t.empty())

				{

					vector<int> tt=query("HH");

					ans="HOOC";

					for(int i:tt) ans[i]=ans[i+1]='H';

					if(ans[1]=='H')

					{

						ans[3]='C';

						if(!query(ans,0))

						{

							ans[3]='O';

							if(!query(ans,0)) ans[3]='H';

						}

					}

					else

					{

						assert(ans[2]=='O');

						vector<int> ttt=query("OOO");

						for(int i:ttt)

							ans[i*3]='O';

					}

				}

				else

				{

					ans[t[0]]='O',ans[t[0]+1]='H',ans[pos1[t[0]]]='O';

					if(!query(ans.substr(pos2[t[0]],3),pos2[t[0]]))

						ans[pos1[t[0]]]='H';

					ans[pos3[t[0]]]='C';

					if(!query(ans,0))

					{

						ans[pos3[t[0]]]='H';

						if(!query(ans,0)) ans[pos3[t[0]]]='O';

					}

				}

			}

		}

		if(!check(ans)) return 0;

	}

	return 0;

}


C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
OutputCopy1

#include <bits/stdc++.h>

typedef long long ll;

typedef long double ld;

using namespace std;

#include <ext/pb_ds/assoc_container.hpp>

using namespace __gnu_pbds;

typedef tree<int,null_type,less<int>,rb_tree_tag,

tree_order_statistics_node_update> indexed_set;

#define endl '\n'

#define ilihg ios_base::sync_with_stdio(false);cin.tie(NULL)

int c[1000001];

void build(int i,int l,int r,int a[],vector<ll> &t){

    if(l==r){

        t[i]=a[l];

    }

    else{

        int mid=(l+r)/2;

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

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

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

    }

}

void propagate(int i,int l,int r,vector<ll> &t,vector<ll> &p){

    t[i]+=p[i];

    if(l!=r){

        p[2*i+1]+=p[i];

        p[2*i+2]+=p[i];

    }

    p[i]=0;

}

void update(int i,int tl,int tr,int l,int r,ll val,vector<ll> &t,vector<ll> &p){

    propagate(i,tl,tr,t,p);

    if(tl>=l&&tr<=r){

        p[i]+=val;

    }

    else{

        int mid=(tl+tr)/2;

        if(mid>=l){

            update(2*i+1,tl,mid,l,r,val,t,p);

        }

        if(mid+1<=r){

            update(2*i+2,mid+1,tr,l,r,val,t,p);

        }

        propagate(2*i+1,tl,mid,t,p);

        propagate(2*i+2,mid+1,tr,t,p);

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

    }

}

ll query(int i,int tl,int tr,int l,int r,vector<ll> &t,vector<ll> &p){

    propagate(i,tl,tr,t,p);

    if(tl>=l&&tr<=r){

        return t[i];

    }

    else{

        int mid=(tl+tr)/2;

        ll k=-1e9;

        if(mid>=l){

            k=max(k,query(2*i+1,tl,mid,l,r,t,p));

        }

        if(mid+1<=r){

            k=max(k,query(2*i+2,mid+1,tr,l,r,t,p));

        }

        return k;

    }

}

int main(){

#ifndef ONLINE_JUDGE

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

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

#endif

	clock_t time_req=clock();

	ilihg;

	int t=1;

    // cin>>t;

    while(t--){

       	int n,m,q;

       	cin>>n>>m>>q;

       	pair<int,int> a[n],b[m];

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

       		cin>>a[i].first>>a[i].second;

       	}

       	sort(a,a+n);

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

       		cin>>b[i].first>>b[i].second;

       	}

       	sort(b,b+m);

       	int k=-2e9;

       	int j=m-1;

       	for(int i=1000000;i>=0;i--){

       		while(j>=0&&b[j].first>i){

       			k=max(k,-b[j].second);

       			j--;

       		}

       		c[i]=k;

       	}

       	vector<ll> t(4000001),p(4000001);

       	build(0,0,1000000,c,t);

       	vector<pair<pair<int,int>,int>> v(q);

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

       		cin>>v[i].first.first>>v[i].first.second>>v[i].second;

       	}

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

       	j=0;

       	ll ans=-2e9;

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

       		while(j<q&&v[j].first.first<a[i].first){

       			update(0,0,1000000,v[j].first.second,1000000000,v[j].second,t,p);

       			j++;

       		}

       		ans=max(ans,query(0,0,1000000,0,1000000,t,p)-a[i].second);

       	}

       	cout<<ans<<endl;

    }

#ifndef ONLINE_JUDGE

    cout<<"Time : "<<fixed<<setprecision(6)<<((double)(clock()-time_req))/CLOCKS_PER_SEC<<endl;

#endif

}


F. Harry The Pottertime limit per test9 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputTo defeat Lord Voldemort; Harry needs to destroy all horcruxes first. The last horcrux is an array aa of nn integers, which also needs to be destroyed. The array is considered destroyed if all its elements are zeroes. To destroy the array, Harry can perform two types of operations:  choose an index ii (1≤i≤n1≤i≤n), an integer xx, and subtract xx from aiai. choose two indices ii and jj (1≤i,j≤n;i≠j1≤i,j≤n;i≠j), an integer xx, and subtract xx from aiai and x+1x+1 from ajaj. Note that xx does not have to be positive.Harry is in a hurry, please help him to find the minimum number of operations required to destroy the array and exterminate Lord Voldemort.InputThe first line contains a single integer nn — the size of the array aa (1≤n≤201≤n≤20). The following line contains nn integers a1,a2,…,ana1,a2,…,an — array elements (−1015≤ai≤1015−1015≤ai≤1015).OutputOutput a single integer — the minimum number of operations required to destroy the array aa.ExamplesInputCopy3
1 10 100
OutputCopy3
InputCopy3
5 3 -2
OutputCopy2
InputCopy1
0
OutputCopy0
NoteIn the first example one can just apply the operation of the first kind three times.In the second example; one can apply the operation of the second kind two times: first; choose i=2,j=1,x=4i=2,j=1,x=4, it transforms the array into (0,−1,−2)(0,−1,−2), and then choose i=3,j=2,x=−2i=3,j=2,x=−2 to destroy the array.In the third example, there is nothing to be done, since the array is already destroyed.

#include<bits/stdc++.h>

#define mset(a,b) memset((a),(b),sizeof((a)))

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

#define dec(i,l,r) for(int i=(r);i>=(l);i--)

#define cmax(a,b) (((a)<(b))?(a=b):(a))

#define cmin(a,b) (((a)>(b))?(a=b):(a))

#define Next(k) for(int x=head[k];x;x=li[x].next)

#define vc vector

#define ar array

#define pi pair

#define fi first

#define se second

#define mp make_pair

#define pb push_back

#define N 21

#define M 2000100

using namespace std;

typedef double dd;

typedef long double ld;

typedef long long ll;

typedef unsigned int uint;

typedef unsigned long long ull;

#define int long long

typedef pair<int,int> P;

typedef vector<int> vi;

const int INF=0x3f3f3f3f;

const dd eps=1e-9;

template<typename T> inline void read(T &x) {

    x=0; int f=1;

    char c=getchar();

    for(;!isdigit(c);c=getchar()) if(c == '-') f=-f;

    for(;isdigit(c);c=getchar()) x=x*10+c-'0';

    x*=f;

}

int n,a[N],f[M],lg[M],b[N],bt,sum[M];

inline vi Get(int nl,int nr){

    vi v;v.clear();

    if(nl==nr){

        if(b[nl]>0){v.pb(-b[nl]);v.pb(b[nl]);}

        else{v.pb(b[nl]);v.pb(-b[nl]);}return v;

    }

    v=Get(nl+1,nr);

    vi v1,v2;v1.clear();v2.clear();

    rep(i,0,(int)v.size()-1) v1.pb(v[i]-b[nl]);

    rep(i,0,(int)v.size()-1) v2.pb(v[i]+b[nl]);

    vi now;now.clear();

    int l=0,r=0;

    while(l<(int)v1.size()&&r<(int)v2.size()){

        if(v1[l]<v2[r]) now.pb(v1[l]),l++;

        else now.pb(v2[r]),r++;

    }

    // printf("now.size()=%d l=%d r=%d\n",now.size(),l,r);

    while(l<(int)v1.size()) now.pb(v1[l]),l++;

    while(r<(int)v2.size()) now.pb(v2[r]),r++;

    // printf("v1.size()=%d v2.size()=%d\n",v1.size(),v2.size());

    // printf("now.size()=%d\n",now.size());

    return now;

}

inline bool Check(int S){

    if(__builtin_popcount(S)==1){

        if(sum[S]==0) return 1;return 0;

    }

    int siz=__builtin_popcount(S)-1;

    if((sum[S]-siz)&1) return 0;bt=0;

    rep(i,0,n-1) if((S>>i)&1) b[++bt]=a[i+1];int mid=(1+bt)>>1;

    vi L=Get(1,mid),R=Get(mid+1,bt);

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

    int l=R.size(),r=R.size()-1;

    // puts("L:");for(int x:L) printf("%d ",x);puts("");

    // puts("R:");for(int x:R) printf("%d ",x);puts("");

    int nd=1+(abs(sum[S])<=siz)*2;

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

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

        while(l&&L[i]+R[l-1]>=-siz) l--;

        while(r>=0&&L[i]+R[r]>siz) r--;

        // printf("l=%d r=%d\n",l,r);

        nd-=min(nd,r-l+1);

        // if(l<=r&&r!=R.size()) return 1;

        // if(r==-1) return 0;

    }

    return (nd==0);

}

signed main(){

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

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

    read(n);rep(i,1,n) read(a[i]),lg[1<<i]=i;

    rep(i,1,n) sum[1<<(i-1)]+=a[i];

    rep(i,0,n-1)rep(j,0,(1<<n)-1) if((j>>i)&1) sum[j]+=sum[j^(1<<i)];

    lg[1]=0;

    // printf("Check(7)=%d\n",Check(7));

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

        if(!f[T]&&Check(T)){

            // puts("Now");

            int t=T^((1<<n)-1);

            for(int S=t;;S=(S-1)&t){

                // printf("T|S=%d T=%d S=%d\n",T|S,T,S);

                cmax(f[T|S],f[S]+1);

                if(!S) break;

            }

        }

        // printf("f[%d]=%d\n",T,f[T]);

    }

    printf("%lld\n",n-f[(1<<n)-1]);

    return 0;

}


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

#include <bits/stdc++.h>

using namespace std;

int dp[401][401][401], n, m;

string s, t;

int solve(int i, int j, int k) {

    if (i == n) {

        if (k == m)

            return j;

        return -2;

    }

    int &res = dp[i][j][k];

    if (res != -1)

        return res;

    res = solve(i + 1, j, k);

    if (j < m && s[i] == t[j])

        res = max(res, solve(i + 1, j + 1, k));

    if (k < m && s[i] == t[k])

        res = max(res, solve(i + 1, j, k + 1));

    return res;

}

int main() {

    ios_base::sync_with_stdio(0);

    cin.tie(0);

    int tt;

    cin >> tt;

    while (tt--) {

        bool ok = false;

        cin >> s >> t;

        n = s.size();

        m = t.size();

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

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

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

                    dp[i][j][k] = -1;

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

            ok |= (solve(0, 0, i + 1) > i);

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

    }

}


D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4
OutputCopy2
3 1InputCopy1 3
OutputCopy3
1 1 1InputCopy8 5
OutputCopy-1InputCopy0 0
OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty.

#include <bits/stdc++.h>
using namespace std;
int main(){
long long n,m,x;
cin>>n>>m;
if(n>m||(n&1)!=(m&1)) cout<<-1;
else if(n==m){
if(n) cout<<"1\n"<<n<<endl;
else cout<<0;
}
else{
x=m-n>>1;
if(x&n) cout<<"3\n"<<x<<' '<<x<<' '<<n<<endl;
else cout<<"2\n"<<x<<' '<<x+n<<endl;
}
return 0;
}