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

#include<bits/stdc++.h>

#define deq deque<int

#define vec vector<int

#define pb push_back

#define pf push_front

#define sonic ios::sync_with_stdio(false); cin.tie(0);

using namespace std;

using ll = long long;

using ull = unsigned long long;

int main() {

	sonic;

	int t;

	cin >> t;

	while (t --) {

		int n;

		cin >> n;

		int a[n];

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

			cin >> a[i];

		}

		bool ok = false;

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

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

				if (i != j && abs(i-j) > 1) {

					if (a[i] == a[j]) {

						ok = true;

					}

				}

			}

		}

		if (ok) {

			cout << "YES\n";

		}

		else {

			cout << "NO\n";

		}

	}

}


E. So Meantime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is interactive.We have hidden a permutation p1,p2,…,pnp1,p2,…,pn of numbers from 11 to nn from you, where nn is even. You can try to guess it using the following queries:?? kk a1a1 a2a2 …… akak.In response, you will learn if the average of elements with indexes a1,a2,…,aka1,a2,…,ak is an integer. In other words, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. You have to guess the permutation. You can ask not more than 18n18n queries.Note that permutations [p1,p2,…,pk][p1,p2,…,pk] and [n+1−p1,n+1−p2,…,n+1−pk][n+1−p1,n+1−p2,…,n+1−pk] are indistinguishable. Therefore, you are guaranteed that p1≤n2p1≤n2.Note that the permutation pp is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries.InputThe first line contains a single integer nn (2≤n≤8002≤n≤800, nn is even).InteractionYou begin the interaction by reading nn.To ask a question about elements on positions a1,a2,…,aka1,a2,…,ak, in a separate line output?? kk a1a1 a2a2 ... akakNumbers in the query have to satisfy 1≤ai≤n1≤ai≤n, and all aiai have to be different. Don't forget to 'flush', to get the answer.In response, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. In case your query is invalid or you asked more than 18n18n queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you determine permutation, output !! p1p1 p2p2 ... pnpnAfter printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.Hack formatFor the hacks use the following format:The first line has to contain a single integer nn (2≤n≤8002≤n≤800, nn is even).In the next line output nn integers p1,p2,…,pnp1,p2,…,pn — the valid permutation of numbers from 11 to nn. p1≤n2p1≤n2 must hold.ExampleInputCopy2
1 2
OutputCopy? 1 2
? 1 1
! 1 2

#include<bits/stdc++.h>

#define Cn const

#define CI Cn int&

#define N 800

using namespace std;

int n,a[N+5],p[N+5],pp[N+5],o[N+5];vector<int> v;

int Q(vector<int> v)

{

	printf("? %d ",(int)v.size());for(auto x:v) printf("%d ",x);putchar('\n'),fflush(stdout);

	int t;return scanf("%d",&t),t;

}

int main()

{

	if(scanf("%d",&n),n==2) return puts("! 1 2"),0;

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

	{

		for(vector<int>().swap(v),j=1;j<=n;++j) j^i&&(v.push_back(j),0);

		if(Q(v)) if(!p[1]) p[a[i]=1]=i;else {p[a[i]=n]=i;break;}

	}

	for(o[p[1]]=i=1;i<=n;++i) !a[i]&&(o[i]=Q({p[1],i}));

	int P=2;for(int V=2;2*V<=n;++V)

	{

		for(i=1;i<=n;++i) if(!a[i]&&o[i]==V%P)

		{

			for(vector<int>().swap(v),j=1;j<=n;++j) !a[j]&&j^i&&(v.push_back(j),0);

			if(v.empty()||Q(v)) {p[a[i]=V]=i;break;}

		}

		for(i=1;i<=n;++i) if(!a[i]&&o[i]==(n-V+1)%P)

		{

			for(vector<int>().swap(v),j=1;j<=n;++j) (!a[j]||a[j]==V)&&j^i&&(v.push_back(j),0);

			if(v.empty()||Q(v)) {p[a[i]=n-V+1]=i;break;}

		}

		if(V==(P<<1)) for(P<<=1,i=1;i<=n;++i) if(!a[i])

		{

			for(vector<int>().swap(v),v.push_back(i),j=1;j<=P;++j) (j%P)^o[i]&&(v.push_back(p[j]),0);

			if(Q(v)) o[i]+=P>>1;

		}

	}

	if(a[1]>(n>>1)) for(i=1;i<=n;++i) a[i]=n-a[i]+1;for(printf("! "),i=1;i<=n;++i) printf("%d ",a[i]);return 0;

}


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

                                        //  ॐ

#include <bits/stdc++.h>

using namespace std;

#define PI 3.14159265358979323846

#define ll long long int

int main(){

    ios_base::sync_with_stdio(false);

    cin.tie(0);

    cout.tie(0);

   int test = 1;

   // cin>>test;

   while(test--){

                int n;

                cin>>n;

                int a[n+1];

                map<int,vector<pair<int,int>>> mp;

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

                     cin>>a[i];

                }

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

                     int curr=0;

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

                         curr+=a[j];

                         mp[curr].push_back({j,i});

                     }

                }

                int opt;

                int blocks=0;

                for(auto [sum,vec] : mp){

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

                       int st=0;

                       int mx=0;

                       for(auto [j,i] : vec){

                          if(i>st){

                              mx++;

                              st=j;

                          }

                       }

                       if(mx>blocks){

                           blocks=mx;

                           opt=sum;

                       }

                }

                cout<<blocks<<'\n';

                auto vec=mp[opt];

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

                int st=0;

                for(auto [j,i] : vec){

                       if(i>st){

                          cout<<i<<' '<<j<<'\n';

                          st=j;

                       }

                }

                // cout<<"\n";

   }

    return 0;

}


E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
OutputCopyYES
YES
NO
YES
NO
NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines).  Possible paths for the queries with "YES" answers are:   11-st query: 11 – 33 – 22  22-nd query: 11 – 22 – 33  44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33

#include <bits/stdc++.h>

// v.erase( unique(all(v)) , v.end() )    ----->   removes duplicates and resizes the vector as so

using namespace std;

#define ll long long

#define lld long double

const lld pi = 3.14159265358979323846;

#define pb push_back

#define pf push_front

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

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

#define getunique(v) {sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end());}

constexpr int mod = (int)(1e9+7);

#define log(x) (31^__builtin_clz(x)) // Easily calculate log2 on GNU G++ compilers

const int N=1e5+7;

int n,d[N];vector<int> adj[N];int in[N],out[N],tick;pair<int,int> A[2*N];

pair<int,int> M[20][2*N];int par[N];

void dfss(int node,int p,int dist)// Call this then call build_sparse

{in[node]=(++tick);par[node]=p;d[node]=dist;

if(!dist)par[node]=node;

for(int i=0;i<adj[node].size();i++)if(adj[node][i]!=p)dfss(adj[node][i],node,dist+1);

out[node]=(++tick);

}

void build_sparse()

{for(int i=1;i<=n;i++)A[in[i]]=A[out[i]]={d[i],i};

for(int i=0 ; i<tick+1 ; i++) M[0][i] = A[i]; // base-case

   for(int j=1 ; 1<<j <= tick+1 ; j++) // while 2^j fits inside the array

      for(int i=0 ; i+(1<<j) <= tick+1 ; i++)

         M[j][i] = min(M[j-1][i], M[j-1][i+(1<<(j-1))]);

}

pair<int,int> inline get(int l, int r){

   int k = log(r-l+1);

   return min(M[k][l], M[k][r-(1<<k)+1]);

}

int get_LCA(int x,int y)

{if(out[x]>out[y])swap(x,y);

if(x==y)return x;

pair<int,int> p=get(out[x],out[y]-1);

return par[p.second];

}

int get_LCA(int x,int y,int z)

{return get_LCA(x,y)^get_LCA(x,z)^get_LCA(y,z);}

int main()

{ios_base::sync_with_stdio(0),cin.tie(0);

cin>>n;

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

  int a,b;cin>>a>>b;

  adj[a].pb(b);

  adj[b].pb(a);

}

dfss(1,0,0); build_sparse();

int q;cin>>q;

while(q--){

  int x,y,a,b,k;cin>>x>>y>>a>>b>>k;

  int path1=d[a]+d[b]-2*d[get_LCA(a,b)];

  int d1=d[a]+d[x]-2*d[get_LCA(a,x)]+d[y]+d[b]-2*d[get_LCA(y,b)]+1;

  int d2=d[a]+d[y]-2*d[get_LCA(a,y)]+d[x]+d[b]-2*d[get_LCA(x,b)]+1;

  int path2=min(d1,d2);

  int dist=2e9;

  if(path1%2!=k%2&&path2%2==k%2){

    dist=path2;

  }

  else if(path2%2!=k%2&&path1%2==k%2){

    dist=path1;

  }

  else if(path2%2==k%2&&path1%2==k%2){

    dist=min(path1,path2);

  }

  if(dist<=k)cout<<"YES\n";else cout<<"NO\n";

}

    return 0;

}

/*

*/


B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:

#include<bits/stdc++.h>

using namespace std;

typedef long long ll;

struct node

{

	int tx, ty;

};

bool cmp(node a, node b)

{

	if(a.ty==b.ty)

	{

		return a.tx<b.tx;

	}

	else return a.ty<b.ty;

}

int n, flag;

int main()

{

	ios::sync_with_stdio(0);

	cin.tie(0);

	cout.tie(0);

	int T, x, y, sz, nowx, nowy, nx, ny;

	string ans;

	cin>>T;

	while(T--)

	{

		vector<node>vtr;

		cin>>n;

		flag = 1;

		ans = "";

		nowx = nowy = 0;

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

		{

			cin>>x>>y;

			vtr.push_back({x, y});

		}

		sort(vtr.begin(), vtr.end(), cmp);

		sz = vtr.size();

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

		{

			nx = vtr[i].tx;

			ny = vtr[i].ty;

			if(nx>=nowx&&ny>=nowy)

			{

				for(int j=1;j<=nx-nowx;++j)

				{

					ans += 'R';

				}

				for(int j=1;j<=ny-nowy;++j)

				{

					ans += 'U';

				}

			}

			else

			{

				flag = 0;

				break;

			}

			nowx = nx;

			nowy = ny;

		}

		if(!flag)

		{

			cout<<"NO"<<"\n";

		}

		else

		{

			cout<<"YES"<<"\n";

			cout<<ans<<"\n";

		}

	}

	return 0;

}


C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2
OutputCopy1 2
InputCopy6
OutputCopy2 3
InputCopy4
OutputCopy1 4
InputCopy1
OutputCopy1 1

// Problem: C. Fadi and LCM

// Contest: Codeforces - Codeforces Round #613 (Div. 2)

// URL: https://codeforces.com/problemset/problem/1285/C

// Memory Limit: 256 MB

// Time Limit: 1000 ms

//

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

#include<bits/stdc++.h>

using namespace std;

typedef long long int       ll;

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

int main()

{

	//ios_base::sync_with_stdio(0);

	//cin.tie(0);

  	ll n;

	cin >> n;

	ll a=0,b=0;

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

		if(n%i==0){

			if(lcm(i , n/i) == n){

				a=i;

				b=n/i;

			}

		}

	}

    cout<< a << " " << b << '\n';

	return 0;

}


D. LCCtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn infinitely long Line Chillland Collider (LCC) was built in Chillland. There are nn pipes with coordinates xixi that are connected to LCC. When the experiment starts at time 0, ii-th proton flies from the ii-th pipe with speed vivi. It flies to the right with probability pipi and flies to the left with probability (1−pi)(1−pi). The duration of the experiment is determined as the time of the first collision of any two protons. In case there is no collision, the duration of the experiment is considered to be zero.Find the expected value of the duration of the experiment.Illustration for the first exampleInputThe first line of input contains one integer nn — the number of pipes (1≤n≤1051≤n≤105). Each of the following nn lines contains three integers xixi, vivi, pipi — the coordinate of the ii-th pipe, the speed of the ii-th proton and the probability that the ii-th proton flies to the right in percentage points (−109≤xi≤109,1≤v≤106,0≤pi≤100−109≤xi≤109,1≤v≤106,0≤pi≤100). It is guaranteed that all xixi are distinct and sorted in increasing order.OutputIt's possible to prove that the answer can always be represented as a fraction P/QP/Q, where PP is an integer and QQ is a natural number not divisible by 998244353998244353. In this case, print P⋅Q−1P⋅Q−1 modulo 998244353998244353.ExamplesInputCopy2
1 1 100
3 1 0
OutputCopy1
InputCopy3
7 10 0
9 4 86
14 5 100
OutputCopy0
InputCopy4
6 4 50
11 25 50
13 16 50
15 8 50
OutputCopy150902884

#include<bits/stdc++.h>

#define LL long long
#define mod 998244353
using namespace std;
int n,vec_t=0;
LL ans=0;
LL X[100002],v[100002];
LL p[100002][2];
struct aaa
{
int x;
bool o1,o2;
LL a,b;
}vec[200002];
inline bool cmp(aaa a,aaa b)
{
return a.a*b.b>b.a*a.b;
}
inline LL Pow(int a,int b)
{
if(!b)return 1;
LL c=Pow(a,b>>1);
c=(c*c)%mod;
if(b&1)c=(c*a)%mod;
return c;
}
struct Matrix
{
LL a[2][2];
}F[100002];
inline Matrix Mul(Matrix A,Matrix B)
{
Matrix C;
for(int i=0;i<2;++i)for(int j=0;j<2;C.a[i][j]%=mod,++j)for(int k=C.a[i][j]=0;k<2;++k)C.a[i][j]+=A.a[i][k]*B.a[k][j];
return C;
}
inline int lson(int x)
{
return (x<<1);
}
inline int rson(int x)
{
return ((x<<1)|1);
}
struct SegTree
{
Matrix a[400002];
inline void build(int k,int l,int r)
{
if(l==r)return (void)(a[k]=F[l]);
int mid=((l+r)>>1),ls=lson(k),rs=rson(k);
build(ls,l,mid),build(rs,mid+1,r),a[k]=Mul(a[ls],a[rs]);
}
inline void modify(int k,int l,int r,int x)
{
if(l==r)return (void)(a[k]=F[l]);
int mid=((l+r)>>1),ls=lson(k),rs=rson(k);
if(x<=mid)modify(ls,l,mid,x);
else modify(rs,mid+1,r,x);
a[k]=Mul(a[ls],a[rs]);
}
}S;
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;++i)scanf("%lld%lld%lld",&X[i],&v[i],&p[i][1]),F[i].a[0][0]=F[i].a[0][1]=p[i][0]=(1-(F[i].a[1][0]=F[i].a[1][1]=(p[i][1]*=Pow(100,mod-2))%=mod))%mod;
for(int i=1;i<n;++i)
{
vec[++vec_t]=(aaa){i,1,0,X[i+1]-X[i],v[i]+v[i+1]},F[i].a[1][0]=0;
if(v[i]<v[i+1])vec[++vec_t]=(aaa){i,0,0,X[i+1]-X[i],v[i+1]-v[i]},F[i].a[0][0]=0;
if(v[i]>v[i+1])vec[++vec_t]=(aaa){i,1,1,X[i+1]-X[i],v[i]-v[i+1]},F[i].a[1][1]=0;
}
F[n].a[0][1]=F[n].a[1][0]=0,S.build(1,1,n),sort(vec+1,vec+vec_t+1,cmp);
for(int i=1;i<=vec_t;++i)
{
F[0]=F[vec[i].x];
for(int j=0;j<2;++j)for(int k=0;k<2;++k)F[vec[i].x].a[j][k]=(j==vec[i].o1 && k==vec[i].o2? p[vec[i].x][j]:0);
S.modify(1,1,n,vec[i].x),(ans+=(((S.a[1].a[0][0]+S.a[1].a[0][1]+S.a[1].a[1][0]+S.a[1].a[1][1])*vec[i].a)%mod)*Pow(vec[i].b,mod-2))%=mod,F[vec[i].x]=F[0],F[vec[i].x].a[vec[i].o1][vec[i].o2]=p[vec[i].x][vec[i].o1],S.modify(1,1,n,vec[i].x);
}
return 0&printf("%lld",(ans+mod)%mod);
}


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

#include <bits/stdc++.h>

using namespace std;

#define pi (3.141592653589)

#define mod 1000000007

#define float double

#define pb push_back

#define mp make_pair

#define ff first

#define ss second

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

#define min3(a, b, c) min(c, min(a, b))

#define min4(a, b, c, d) min(d, min(c, min(a, b)))

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

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

#define fast ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);

#define ll long long

#define foi(n) for (ll i = 0; i < n; i++)

#define foj(n) for (ll j = 0; j < n; j++)

typedef vector<ll> vll;

typedef map<ll, ll> mll;

typedef vector<pair<ll, ll> > vpll;

bool isPrime(int n){

if(n==1) return false;

if(n==2) return true;

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

if(n%i==0)return false;

}

return true;

}

ll mod_mul(ll a, ll b){

a = a % mod;

b = b % mod;

return (((a * b) % mod) + mod) % mod;

}

ll mod_add(ll a, ll b){

a = a % mod;

b = b % mod;

return (((a + b) % mod) + mod) % mod;

}

int main(){

fast

int t=1;

cin>>t;

while(t!=0){

	ll n,m;

	cin>>n>>m;

	string s;

	cin>>s;

	vll v(m);

	map<ll,ll> p;

	foi(m)

	{

		cin>>v[i];

	}

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

	for(ll i=0;i<s.length();i++)

	{

		p[s[i]-97]++;

	}

	ll j=0,k=v.size();

	foi(v.size())

	{

		while((v[i])!=j)

		{

			p[s[j]-97]+=(k);

			j++;

		}

		if((i+1)!=v.size() && v[i]==v[i+1])

		{

			while((i+1)!=v.size() && v[i]==v[i+1])

			{

				i++;

				k--;

			}

		}

		k--;

	}

	foi(26)

	{

		if(p.find(i)==p.end())

		{

			cout<<0<<" ";

		}

		else

		{

			cout<<p[i]<<" ";

		}

	}

	cout<<endl;

t--;

}

return 0;

}


A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100)  — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2
2
14
OutputCopy1 1
6 4
NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.

#include <iostream>

#include <bits/stdc++.h>

using namespace std;

int t, x;

void Solve() {

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

        cin >> x;

        cout << 1 << ' ' << x - 1 << '\n';

    }

}

int main()

{

    ios_base::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    cin >> t;

    Solve();

    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>

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)

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

    if(l==r){

        t[i]=-1;

    }

    else{

        int mid=(l+r)/2;

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

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

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

    }

}

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

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

        t[i]=max(t[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);

        }

        t[i]=min(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){

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

        return t[i];

    }

    else{

        int mid=(tl+tr)/2;

        ll k=27;

        if(mid>=l){

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

        }

        if(mid+1<=r){

            k=min(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;

       	cin>>n;

       	string s;

       	cin>>s;

       	int a[n];

       	int k=0;

       	vector<ll> t(4*n),p(4*n);

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

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

       		int l=0;

       		int r=n-1;

       		while(l<r){

       			int m=(l+r)/2;

       			if(query(0,0,n-1,m,m,t,p)<=s[i]-97){

       				r=m;

       			}

       			else{

       				l=m+1;

       			}

       		}

       		k=max(k,l+1);

       		a[i]=l+1;

       		update(0,0,n-1,l,l,s[i]-97,t,p);

       	}

       	cout<<k<<endl;

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

       		cout<<a[i]<<" ";

       	}

       	cout<<endl;

    }

#ifndef ONLINE_JUDGE

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

#endif

}


D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0

/////////////////////////////////// By Pradeep ///////////////////////////////////////////////

#include <bits/stdc++.h>

using namespace std;

#define ll                    long long

#define PI                    3.141592653589793

#define MOD                     1000000007

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

#define fl(k,n)              for(ll i=k;i<n; i++)

#define py                   cout<<"YES"<<endl

#define pn                   cout<<"NO"<<endl

#include<ext/pb_ds/assoc_container.hpp>

#include<ext/pb_ds/tree_policy.hpp>

using namespace std;

using namespace __gnu_pbds;

typedef tree<pair<ll,ll>, null_type, less<>, rb_tree_tag, tree_order_statistics_node_update> pbds;

////////////////////////////// Code starts here ////////////////////////////////////////

void  solve(){

   ll n;

   cin>>n;

   vector<ll>v1(n), v2(n);

   pbds s;

   fl(0,n)

    cin>>v1[i];

   fl(0, n)

    cin>>v2[i];

    ll ans = 0;

    fl(0, n){

        ll diff = v1[i] - v2[i];

        ans +=  s.order_of_key({diff , -1});

        s.insert({-diff , i});

    }

    cout<<ans<<endl;

}

//////////////////////////////// Main functin /////////////////////////////////////////

int32_t main() {

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

   ll t=1;

	// cin>>t;

	while(t--){

      solve();

  }

}


B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19).

#include <bits/stdc++.h>

//#pragma GCC optimize ("Ofast")

//#pragma GCC target ("avx2")

using namespace std;

#define MOD 1000000007

#define MOD2 998244353

#define MAXN 20000001

#define INF 2e9

#define INF2 1e18

#define ll long long

#define nl '\n'

#define pb push_back

#define pf push_front

#define fi first

#define se second

typedef pair<int,int> pii;

typedef pair<ll,ll> pll;

int main() {

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    int t;cin >> t;

    ll a,b;

    while(cin >> a >> b){

        cout << a*(ll)(log10(b+1)) << nl;

    }

}


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<unordered_set>

#include<unordered_map>

#include<algorithm>

#include<iostream>

#include<map>

#include<set>

#include<string>

using namespace std;

#define int long long

const int N = 1e7 + 10;

int T, n = 0, m, k, l;

const int mod = 998244353;

#define ll long long

#define endl '\n'

bool flag = false;

int cnt = 0;

#define endl '\n'

int ans = 0, p;

int d;

int qp(int a, int b) {

    int res = 1;

    int q = a;

    while (b) {

        if (b & 1) {

            res *= q; res %= mod;

        }

        b >>= 1;

        q *= q;

        q %= mod;

    }

    return res;

}

void solve()

{

    int h, r;

    cin >> n >> h >> l >> r; vector<int>a(n);

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

    int t = 0;

    vector<vector<int>>dp(n + 1, vector<int>(n + 1));

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

        for (int j = 0; i - j >= 0; j++) {

            int time = t - j;

            int k = 0; time += a[i];

            if (time % h >= l && time % h <= r) {

                k=1;

            }

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

            time--;

            if (time % h >= l && time % h <= r) {

                k = 1;

            }

            else k = 0;

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

        }

        t+= a[i];

    }

    cout << *max_element(dp[n].begin(), dp[n].end()) << endl;

}

signed main()

{

    ios::sync_with_stdio(false);

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

    T = 1;

    //cin >> T;

    while (T--)solve();

}


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>

using namespace std;

const int mx = 6e5 + 5;

int n, m, ans[mx], A[mx], prv[mx], bit[mx];

void upd(int i, int val){
for (; i <= mx; i += i & (-i)) bit[i] += val;
}
int qry(int i){
int ret = 0;
for (; i > 0; i -= i & (-i)) ret += bit[i];
return ret;
}

int main(){
cin >> n >> m;
for (int i = 1, X; i <= n + m; i++){
if (i <= n) X = n - i + 1;
else cin >> X;

upd(i, 1);
if (prv[X]){
ans[X] = max(ans[X], qry(i) - qry(prv[X]));
upd(prv[X], -1);
}
prv[X] = i;
}
for (int i = 1; i <= n; i++)
cout<<(prv[i] <= n ? i : 1)<<" "<<max(ans[i], qry(n + m) - qry(prv[i] - 1))<<"\n";
}


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

#include <iostream>
#include<bits/stdc++.h>
#include<deque>
#include<algorithm>
#include<math.h>
#include<sstream>
#include<stdio.h>
#include<bitset>
#include<string>
#include<vector>
#include<unordered_map>
#include<queue>
#include<set>
#include<fstream>
#include<map>
#define int long long int
#define ld long double
#define pi 3.1415926535897932384626433832795028841971
#define MOD1 998244353
using namespace std;
random_device seed_gen;
mt19937_64 engine(seed_gen());
int inf = 1e18;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
template <typename T, typename U> void debug(std::vector<pair<T, U>> v) {for (int i = 0; i < v.size(); i++) cout << "[ " << v[i].first << " " << v[i].second << " ]\n"; cout << "\n";}
template <typename T> void debug(std::vector<T> v) {cout << "[ "; for (int i = 0; i < v.size(); i++) cout << v[i] << " "; cout << "]\n";}
template <typename T> void debug(std::set<T> v) {cout << "[ "; for (auto x : v) cout << x << " "; cout << "]\n";}
template <typename T> void debug(std::multiset<T> v) {cout << "[ "; for (auto x : v) cout << x << " "; cout << "]\n";}
template <typename T> void debug(vector<vector<T>> v) {int n = v.size(), m = v[0].size(); for (int i = 0; i < n; i++) {cout << "[ "; for (int j = 0; j < m; j++) cout << v[i][j] << " "; cout << "]\n";}}
template <typename T> void debug(T i) {cout << "[ " << i << " ]\n";}
template <typename T, typename U> void debug(T i, U j) {cout << "[ " << i << " " << j << " ]\n";}
template <typename T, typename U, typename V> void debug(T i, U j, V k) {cout << "[ " << i << " " << j << " " << k << " ]\n";}
template <typename T, typename U, typename V, typename X> void debug(T i, U j, V k, X l) {cout << "[ " << i << " " << j << " " << k << " " << l << " ]\n";}
template <typename T, typename U> void debug(pair<T, U> x) {cout << "[ " << x.first << " " << x.second << " ]\n";}

int expo(int a, int b, int mod) {
    int res = 1;
    while (b > 0)
    {   if (b & 1)
            res = (res * a) % mod;
        a = (a * a) % mod;
        b = b >> 1;
    } return res;
}
int gcd(int a, int b) {
    if (b == 0) return a;
    return gcd(b, a % b);
}
int mminvprime(int a, int b) {
    return expo(a, b, b + 2);
}
const int N = 1e5 + 12;
int a[N], ind[N];
bool cmp(int x, int y)
{
    return a[x] > a[y];
}
int32_t main() {
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n, p, k;
    cin >> n >> p >> k;
    vector<vector<int>> s(n + 1, vector<int>(p, 0));
    for (int i = 1; i <= n; ++i)
    {
        cin >> a[i];
        ind[i] = i;
    }
    sort(ind + 1, ind + n + 1, cmp);
    for (int i = 1; i <= n; ++i)
    {
        for (int j = 0; j < p; j++)
        {
            int x;
            cin >> x;
            s[i][j] = x;
        }
    }
    int all = 1 << p;
    vector<vector<int>> dp(n + 1, vector<int>(all + 1, -1));
    dp[0][0] = 0;
    for (int mask = 0; mask < all; mask++)
    {
        for (int i = 1; i <= n; ++i)
        {
            int curind = ind[i];

            int cur = i - __builtin_popcount(mask);
            if (cur <= k)
            {
                if (dp[i - 1][mask] != -1)
                    dp[i][mask] = dp[i - 1][mask] + a[curind];
            }
            else
            {
                if (dp[i - 1][mask] != -1)
                    dp[i][mask] = dp[i - 1][mask];
            }
            for (int j = 0; j < p; j++)
            {
                if (!(mask & (1 << j))) continue;
                if (dp[i - 1][mask ^ (1 << j)] != -1)
                    dp[i][mask] = max(dp[i][mask], dp[i - 1][mask ^ (1 << j)] + s[curind][j]);
            }
        }
    }
    cout << dp[n][all - 1];
    return 0;
}


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

// LUOGU_RID: 93184384
#include <bits/stdc++.h>
#define cnt(x) __builtin_parity(x)
using namespace std;
constexpr int N = 1e5 + 9, S = 64;
int n, m, k, dp[S], bt[N];
vector<pair<int, int>> es;
signed main() {
cin.tie(nullptr)->sync_with_stdio(false);
cin >> n >> m >> k, es.reserve(n << 1), k = 1 << k;
for (int i = 1, l, r; i <= n; ++i) {
cin >> l >> r;
es.emplace_back(l, i);
es.emplace_back(r + 1, -i);
}
ranges::sort(es);
for (int q = 0, tot = 0; auto [p, id] : es) {
q += p -= q;
if (id > 0) {
int h = bt[id] = (tot + 1) & ~tot;
for (int i = 0; i < k; ++i)
if ((i & tot) == i) dp[i | h] = dp[i] += p * cnt(i);
tot ^= h;
} else {
int h = bt[-id];
tot ^= h;
for (int i = 0; i < k; ++i)
if ((i & tot) == i)
dp[i] = max(dp[i] + p * cnt(i), dp[i | h] + p * cnt(i | h));
}
}
return cout << dp[0] << endl, 0;
}


A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":   "A" corresponds to an angry student  "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1
4
PPAP
OutputCopy1
InputCopy3
12
APPAPPPAPPPP
3
AAP
3
PPA
OutputCopy4
1
0
NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is:   after 11 minute — AAPAAPPAAPPP  after 22 minutes — AAAAAAPAAAPP  after 33 minutes — AAAAAAAAAAAP  after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry.

#include <iostream>

//#include <deque>

#include <vector>

using namespace std;

//vector <string> vec_s;

int main() {

    int t; cin >> t;

//    bool f = true;

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

        int n; cin >> n;

        string s; cin >> s;

        int p = 0, ans = 0;

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

            if (s[j] == 'P') p++;

            else ans = max(ans, p), p = 0;

        }

        cout << ans << '\n';

    }

    return 0;

}


#include<bits/stdc++.h>

using namespace std;

int main(){

int t,n;

cin>>t;

int k[t];

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

cin>>k[i];

string s;

cin>>s;

int maxi=0;

int sum=0;

int flag=0;

for (int j = 0; j <k[i]; j++)

{

        if(s[j]=='A'){

            flag=1;

            if(sum>maxi){

                maxi=sum;

            }

                sum=0;

        }

       else  if(s[j]=='P' and flag==1){

            sum++;

        }

    }

    if(sum>maxi){

        maxi=sum;

        sum=0;

    }

    cout<<maxi<<endl;

}

return 0;

}

// }


A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3
1 1
4 5
5 11
OutputCopyYES
YES
NO
NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days.

#include <bits/stdc++.h>

using namespace std;

#define pb push_back

#define ub upper_bound

#define lb lower_bound

#define ll long long

#define ld long double

#define pii pair<ll, ll>

typedef __int128 lll;

typedef vector<ll> vi;

typedef vector<vi> vvi;

typedef vector<pii> vpi;

typedef set<ll> si;

typedef map<ll, ll> mii;

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

const int M = 1e9+7;

//..................................................................

void solve(){

	ll n,d;

	cin>>n>>d;

	if(d<=n)

	{

		cout<<"YES"<<endl;return;

	}

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

	{

		ll curr=i+d/(i+1);

		if(d%(i+1)!=0) curr++;

		if(curr<=n)

		{

			cout<<"YES"<<endl;

			return;

		}

	}

	cout<<"NO"<<endl;

}

int main()

{

	ios_base::sync_with_stdio(false);

	cin.tie(NULL);

#ifndef ONLINE_JUDGE

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

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

#endif

	ll t=1;

	cin>>t;

	while(t--)

	{

		solve();

	}

}


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

#include<bits/stdc++.h>

using namespace std;

int main()

{

    #ifndef ONLINE_JUDGE

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

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

    #endif

    int n, m, k; cin >> n >> m >> k;

    if(4*n*m - 2*n - 2*m < k) cout << "NO\n";

    else

    {

        cout << "YES\n";

        vector<string>moves;

        vector<pair<int,string>>finalMoves;

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

        {

            if(i == 0)

            {

                for(int i = 0; i < m - 1; i++) moves.push_back("R");

                for(int i = 0; i < m - 1; i++) moves.push_back("L");

            }

            else

            {

                moves.push_back("D");

                for(int i = 0; i < m - 1; i++) moves.push_back("RUD");

                for(int i = 0; i < m - 1; i++) moves.push_back("L");

            }

        }

        for(int i = 0; i < n - 1; i++) moves.push_back("U");

        for(auto &i : moves)

        {

            if(k == 0) break;

            if(k >= i.size())

            {

                k -= i.size();

                if(finalMoves.size() && finalMoves.back().second == i)

                {

                    finalMoves[finalMoves.size() - 1].first++;

                }

                else

                {

                    finalMoves.push_back({1, i});

                }

            }

            else

            {

                finalMoves.push_back({1, string(i.begin(), i.begin() + k)});

                k = 0;

            }

        }

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

        for(auto &i : finalMoves) cout << i.first << " " << i.second << "\n";

    }

}


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

#include <iostream>

#include <string>

#include <vector>

#include <algorithm>

#include <sstream>

#include <queue>

#include <deque>

#include <bitset>

#include <iterator>

#include <list>

#include <stack>

#include <map>

#include <set>

#include <functional>

#include <numeric>

#include <utility>

#include <limits>

#include <time.h>

#include <math.h>

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include <assert.h>

#include <iostream>

#include <string>

#include <vector>

#include <algorithm>

#include <sstream>

#include <queue>

#include <deque>

#include <bitset>

#include <iterator>

#include <list>

#include <stack>

#include <map>

#include <set>

#include <unordered_set>

#include <functional>

#include <numeric>

#include <utility>

#include <limits>

#include <time.h>

#include <math.h>

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include <iomanip>

#include <assert.h>

#include <iostream>

#include <string>

#include <vector>

#include <algorithm>

#include <sstream>

using namespace std;

using ll = long long;

using vi = vector<int>;

using vii = vector< vector <int>>;

using vl = vector<ll>;

using vll = vector< vector <ll>>;

using vpi = vector <pair <int, int>>;

using vpl = vector <pair <ll, ll>>;

#define pb push_back

#define rsz resize

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

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

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

#define loop1(i,n) for(int i = 1;i<n;i++)

#define loopx(i, x, n) for(int i = x; i<n; i++);

using pi = pair<int, int>;

using pl = pair<ll, ll>;

#define mp make_pair

#define ff first

#define ss second

#define endl "\n"

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

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

ll arr[400001];

ll tree[1600004];

ll build(int l, int r, int index) {

    if (l == r) {

        tree[index] = arr[l];

        return tree[index];

    }

    int mid = (l + r) / 2;

    tree[index] = min(build(l, mid, 2 * index + 1), build(mid + 1, r, 2 * index + 2));

    return tree[index];

}

void update(int k, int u, int l, int r, int index) {

    int mid = (l + r) / 2;

    if (l == r) {

        tree[index] += u;

        arr[k] += u;

        return;

    }

    if (k <= mid) update(k, u, l, mid, 2 * index + 1);

    else update(k, u, mid + 1, r, 2 * index + 2);

    tree[index] = min(tree[index * 2 + 1], tree[index * 2 + 2]);

}

ll query(int l, int r, int start, int end, int index) {

    if (l > end || start > r) return 999999999;

    if (start <= l && r <= end) return tree[index];

    int mid = (l + r) / 2;

    return min(query(l, mid, start, end, 2 * index + 1) , query(mid + 1, r, start, end, 2 * index + 2));

}

int main() {

#ifdef LOCAL

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

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

#endif

    ios::sync_with_stdio(0);

    cin.tie(0);

    int q, x;

    cin >> q >> x;

    loop(i, x) arr[i] = i;

    build(0, x - 1, 0);

    while (q--) {

        int k;

        cin >> k;

        k %= x;

        update(k, x, 0, x - 1, 0);

        cout << query(0, x - 1, 0, x - 1, 0) << endl;

    }

    return 0;

}


B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk  — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm  — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am  — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()((
OutputCopy1
2
1 3
InputCopy)(
OutputCopy0
InputCopy(()())
OutputCopy1
4
1 2 5 6
NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations.

#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#include "bits/stdc++.h"
using namespace std;

#define ff first
#define ss second
#define mp make_pair
#define ll long long
#define ld long double
#define rep(i, n) for (ll i = 0; i < n; i++)
#define rev(i, n) for (ll i = n; i >= 0; i--)
#define rep_a(i, a, n) for (ll i = a; i < n; i++)
#define pb push_back
#define all(_obj) _obj.begin(), _obj.end()
#define pll pair<ll, ll>
#define vll vector<ll>
#define yes cout << "YES" << endl
#define no cout << "NO" << endl
const ll N = 1e5 + 11, mod = 1e9 + 7, inf = LONG_LONG_MAX;

void solve()
{
    string s;
    cin >> s;
    vll ans;
    ll i = 0, j = s.size() - 1;
    while (j > i)
    {
        if (s[j] == ')' && s[i] == '(')
        {
            ans.pb(i + 1);
            ans.pb(j + 1);
            i++;
            j--;
        }
        if (s[i] != '(')
            i++;
        if (s[j] != ')')
            j--;
    }
    if (ans.empty())
    {
        cout << 0 << endl;
        return;
    }
    sort(all(ans));
    cout << 1 << endl;
    cout << ans.size() << endl;
    for (auto &i : ans)
        cout << i << " ";
    cout << endl;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

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

    return 0;
}


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

#include <bits/stdc++.h>

using namespace std;

bool ask(int x) {

    cout << '?' << ' ' << x + 1 << endl;

    char c; cin >> c;

    return c == 'Y' ? true : false;

}

void reset() {

    cout << 'R' << endl;

}

void tell(int x) {

    cout << '!' << ' ' << x << endl;

}

void solve_small(int n, int k) {

    set <int> ans;

    for(int i = 0; i < n; i++) ans.insert(i);

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

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

            reset();

            ask(i);

            if(ask(j)) ans.erase(j);

        }

    }

    tell(ans.size());

}

int main() {

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

    int n, k;

    cin >> n >> k;

    if(k == 1) {

        solve_small(n, k);

        return 0;

    }

    vector<vector<int>> v;

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

        reset();

        vector <int> unique;

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

            auto t = ask(i*k + j);

            if(!t) unique.push_back(i*k + j);

        }

        while((int)unique.size() < k) unique.push_back(unique.front());

        v.push_back(unique);

    }

    for(int sz = k; sz < n; sz *= 2) {

        vector<vector<int>> w;

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

            // merge v[i] and v[i + 1]!

            auto a = v[i];

            auto b = v[i + 1];

            map <int, bool> rema, remb;

            for(int j = 0; j < sz; j += k) {

                // starting block of a.

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

                    // starting block of b. Remove duplicates in (5K/2) queries.

                    reset();

                    for(int x = 0; x < k/2; x++) {

                        ask(a[j + x]);

                    }

                    for(int x = 0; x < k/2; x++) {

                        if(ask(b[t + x])) remb[t + x] = true;

                    }

                    for(int x = 0; x < k/2; x++) {

                        if(ask(a[j + k/2 + x])) rema[j + k/2 + x] = true;

                    }

                    for(int x = 0; x < k/2; x++) {

                        if(ask(b[t + k/2 + x])) remb[t + k/2 + x] = true;

                    }

                    reset();

                    for(int x = 0; x < k/2; x++) {

                        ask(a[j + x]);

                    }

                    for(int x = 0; x < k/2; x++) {

                        if(ask(b[t + k/2 + x])) remb[t + k/2 + x] = true;

                    }

                }

            }

            vector <int> temp;

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

                if(!rema[i]) temp.push_back(a[i]);

            }

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

                if(!remb[i]) temp.push_back(b[i]);

            }

            while((int)temp.size() < 2*sz) temp.push_back(temp.front());

            w.push_back(temp);

        }

        v = w;

    }

    set <int> s;

    for(auto i : v.front()) s.insert(i);

    tell((int)s.size());

    return 0;

}


A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO

#include<bits/stdc++.h>

using namespace std;

int main(){

	int t,n,a;

	bool o=0,e=0;

	cin>>t;

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

		cin>>n;

		if(n%2==0){

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

				cin>>a;

				if(a%2==0){

					e=1;

				}

				else{

					o=1;

				}

			}

			if(o && e){

				cout<<"YES"<<endl;

			}

			else{

				cout<<"NO"<<endl;

			}

			o=0;

			e=0;

		}

		else{

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

				cin>>a;

				if(a%2==1){

					o=1;

				}

			}

			if(o){

				cout<<"YES"<<endl;

			}

			else{

				cout<<"NO"<<endl;

			}

			o=0;

		}

	}

}


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.

// Siddharth Ruria
//Linkedin: https://www.linkedin.com/in/ruria-siddharth/
//Codeforces: https://codeforces.com/profile/Sw00sh
//Codechef: https://www.codechef.com/users/airurdis

#include <iostream>
#include <bits/stdc++.h>
// #include <sys/resource.h>
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
using namespace std;
// using namespace chrono;
// using namespace __gnu_pbds;

// #define ruria 1

//Speed
#define fast ios_base::sync_with_stdio(false);
#define input cin.tie(NULL);
#define output cout.tie(NULL);

//Aliases
using ll= long long;
using lld= long double;
using ull= unsigned long long;

//Constants
const lld pi= 3.141592653589793238;
const ll INF= LONG_LONG_MAX;
const ll mod=1e9+7;

//TypeDef
typedef vector<int> vi;
typedef vector<pair<int, int>> vpi;
typedef pair<ll, ll> pll;
typedef vector<ll> vll;
typedef vector<pll> vpll;
typedef vector<string> vs;
typedef unordered_map<ll,ll> umll;
typedef map<ll,ll> mll;

// Macros
#define F first
#define S second
#define pb push_back
#define mp make_pair
#define fl(i, n) for(int i= 0; i< n; ++i)
#define rtl(i, m, n) for(int i= n;i>= m; --i)
#define yes cout<<"YES\n"
#define no cout<<"NO\n"
#define minus cout << "-1\n"
#define all(v) v.begin(),v.end()

//Debug
#ifdef ruria
#define debug(x) cerr << #x << " "; cerr << x << " "; cerr << endl;
#else
#define debug(x);
#endif

// Operator overloads
template<typename T1, typename T2> // cin >> pair<T1, T2>
istream& operator>>(istream &istream, pair<T1, T2> &p) { return (istream >> p.first >> p.second); }
template<typename T> // cin >> vector<T>
istream& operator>>(istream &istream, vector<T> &v){ for (auto &it: v)cin >> it; return istream; }
template<typename T1, typename T2> // cout << pair<T1, T2>
ostream& operator<<(ostream &ostream, const pair<T1, T2> &p) { return (ostream << p.F << " " << p.S); }
template<typename T> // cout << vector<T>
ostream& operator<<(ostream &ostream, const vector<T> &c) { for (auto &it: c) cout << it << " "; return ostream; }

// Utility functions
template <typename T>
void print(T &&t)  { cout << t << "\n"; }
void printarr(int arr[], int n){ fl(i, n) cout << arr[i] << " "; cout << "\n"; }
template<typename T>
void printvec(vector<T>v){ ll n= v.size(); fl(i, n) cout << v[i] << " "; cout << "\n"; }
template<typename T>
ll sumvec(vector<T>v){ ll n= v.size(); ll s= 0; fl(i, n) s+= v[i]; return s; }

// Mathematical functions
ll gcd(ll a, ll b){ if (b == 0) return a; return gcd(b, a % b); } //__gcd
ll lcm(ll a, ll b){ return (a/gcd(a,b)*b); }
ll moduloMultiplication(ll a,ll b,ll mod){ ll res = 0; a %= mod; while (b){ if(b & 1) res = (res + a) % mod; b >>= 1; } return res; }
ll powermod(ll x, ll y, ll p){ ll res = 1; x = x % p; if (x == 0) return 0; while (y > 0){ if(y & 1) res = (res*x) % p; y = y>>1; x = (x*x) % p; } return res; }

//Graph-dfs
// bool gone[MN];
// vector<int> adj[MN];
// void dfs(int loc){
//     gone[loc]=true;
//     for(auto x:adj[loc])if(!gone[x])dfs(x);
// }

//Sorting
bool sorta(const pair<int,int> &a,const pair<int,int> &b){return (a.second < b.second);}
bool sortd(const pair<int,int> &a,const pair<int,int> &b){return (a.second > b.second);}

//Bits
string decToBinary(int n){string s="";int i = 0;while (n > 0) {s =to_string(n % 2)+s;n = n / 2;i++;}return s;}
ll binaryToDecimal(string n){string num = n;ll dec_value = 0;int base = 1;int len = num.length();for(int i = len - 1; i >= 0; i--){if (num[i] == '1')dec_value += base;base = base * 2;}return dec_value;}

//Check
bool isPrime(ll n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(int i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
bool isPowerOfTwo(ll n){if(n==0)return false;return (ceil(log2(n)) == floor(log2(n)));}
bool isPerfectSquare(ll x){if (x >= 0) {ll sr = sqrt(x);return (sr * sr == x);}return false;}

//Code
void solve() {
    int n;
    cin >> n;
    vi v1(n);
    vi v2(n);
    cin >> v1 >> v2;
    int hisAlone= 0, myAlone= 0, common= 0;
    int myScore= 0, hisScore= 0;
    for(int i= 0; i< n; ++i) {
    	if(v1[i]== 1 and v2[i]== 0) myAlone++;
    	else if(v1[i]== 0 and v2[i]== 1) hisAlone++;
    	else if(v1[i]== 1 and v2[i]== 1) common++;
    }
    if(myAlone== 0) {
    	cout << -1;
    	return;
    }
    hisScore= hisAlone+common;
    myScore= common;
    int more= hisScore-myScore+1;
   	if(more<= myAlone) {
 	  	cout << 1;
 	  	return;
   	}
   	double one= double(more)/myAlone;
   	int two= more/myAlone;
   	if(one== two) cout << two;
   	else cout << two+1;
}

//Main
int main() {

	fast
	input
	output

	int tt= 1;
	// cin >> tt;
	while(tt--) {
		solve();
	}

    // Uncomment for Kickstart
    // fl(i,t) {
    //     cout<<"Case #"<<i+1<<": ";
    //     solve();
    //     cout<<"\n";
    // }
}

// End


D. Chaotic V.time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputÆsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years; it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1,2,3,…1,2,3,…). The node with a number xx (x>1x>1), is directly connected with a node with number xf(x)xf(x), with f(x)f(x) being the lowest prime divisor of xx.Vanessa's mind is divided into nn fragments. Due to more than 500 years of coma, the fragments have been scattered: the ii-th fragment is now located at the node with a number ki!ki! (a factorial of kiki).To maximize the chance of successful awakening, Ivy decides to place the samples in a node PP, so that the total length of paths from each fragment to PP is smallest possible. If there are multiple fragments located at the same node, the path from that node to PP needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node PP.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — number of fragments of Vanessa's mind.The second line contains nn integers: k1,k2,…,knk1,k2,…,kn (0≤ki≤50000≤ki≤5000), denoting the nodes where fragments of Vanessa's mind are located: the ii-th fragment is at the node with a number ki!ki!.OutputPrint a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node PP).As a reminder, if there are multiple fragments at the same node, the distance from that node to PP needs to be counted multiple times as well.ExamplesInputCopy3
2 1 4
OutputCopy5
InputCopy4
3 1 4 4
OutputCopy6
InputCopy4
3 1 4 1
OutputCopy6
InputCopy5
3 1 4 1 5
OutputCopy11
NoteConsidering the first 2424 nodes of the system; the node network will look as follows (the nodes 1!1!, 2!2!, 3!3!, 4!4! are drawn bold):For the first example, Ivy will place the emotion samples at the node 11. From here:  The distance from Vanessa's first fragment to the node 11 is 11.  The distance from Vanessa's second fragment to the node 11 is 00.  The distance from Vanessa's third fragment to the node 11 is 44. The total length is 55.For the second example, the assembly node will be 66. From here:  The distance from Vanessa's first fragment to the node 66 is 00.  The distance from Vanessa's second fragment to the node 66 is 22.  The distance from Vanessa's third fragment to the node 66 is 22.  The distance from Vanessa's fourth fragment to the node 66 is again 22. The total path length is 66.

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

#define N 5000

#define M 5000005

using namespace std;

int tot,n,pr[N+5],cnt,s[N+5][705],son[M],a[M],v[N+5],p[N+5][705];

long long asw,sum[M];

bool vi[N+5];

struct nood {

	int to,next,v;

} g[M];

inline void add(int x,int y,int z) {

	g[++cnt].v=z,g[cnt].to=y,g[cnt].next=a[x],a[x]=cnt;

}

inline void dfs(int u) {

	for(int j,i=a[u]; i; i=g[i].next) {

		dfs(j=g[i].to),son[u]+=son[j],sum[u]+=sum[j]+1ll*son[j]*g[i].v;

	}

}

inline void Dfs(int u) {

	for(int j,i=a[u]; i; i=g[i].next) {

		if(son[j=g[i].to]*2>son[0]) {

			asw-=1ll*g[i].v*(son[j]*2-son[0]);

			return Dfs(j);

		}

	}

}

int main() {

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

		if(!vi[i]) pr[++pr[0]]=i;

		for(int j=1; j<=pr[0]; j++) {

			if(i*pr[j]>N) break;

			vi[i*pr[j]]=1;

			if(i%pr[j]==0) break;

		}

	}

	scanf("%d",&n);

	for(int x,i=1; i<=n; i++) scanf("%d",&x),v[max(x,1)]++;

	son[0]=v[1];

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

		int op=0;

		for(int j=pr[0]; j; j--) {

			if(pr[j]>i) continue;

			int k=i;

			while(k) s[i][j]+=k/pr[j],k/=pr[j];

			if(op) add(p[i][j+1],p[i][j]=++tot,s[i][j]);

			else if(s[i-1][j]!=s[i][j]) {

				add(p[i-1][j],p[i][j]=++tot,s[i][j]-s[i-1][j]),op=1;

			} else p[i][j]=p[i-1][j];

		}

		son[tot]=v[i];

	}

	dfs(0),asw=sum[0],Dfs(0),printf("%lld",asw);

}