E. Fedya the Potter Strikes Backtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFedya has a string SS, initially empty, and an array WW, also initially empty.There are nn queries to process, one at a time. Query ii consists of a lowercase English letter cici and a nonnegative integer wiwi. First, cici must be appended to SS, and wiwi must be appended to WW. The answer to the query is the sum of suspiciousnesses for all subsegments of WW [L, R][L, R], (1≤L≤R≤i)(1≤L≤R≤i).We define the suspiciousness of a subsegment as follows: if the substring of SS corresponding to this subsegment (that is, a string of consecutive characters from LL-th to RR-th, inclusive) matches the prefix of SS of the same length (that is, a substring corresponding to the subsegment [1, R−L+1][1, R−L+1]), then its suspiciousness is equal to the minimum in the array WW on the [L, R][L, R] subsegment. Otherwise, in case the substring does not match the corresponding prefix, the suspiciousness is 00.Help Fedya answer all the queries before the orderlies come for him!InputThe first line contains an integer nn (1≤n≤600000)(1≤n≤600000) — the number of queries.The ii-th of the following nn lines contains the query ii: a lowercase letter of the Latin alphabet cici and an integer wiwi (0≤wi≤230−1)(0≤wi≤230−1).All queries are given in an encrypted form. Let ansans be the answer to the previous query (for the first query we set this value equal to 00). Then, in order to get the real query, you need to do the following: perform a cyclic shift of cici in the alphabet forward by ansans, and set wiwi equal to wi⊕(ans & MASK)wi⊕(ans & MASK), where ⊕⊕ is the bitwise exclusive "or", && is the bitwise "and", and MASK=230−1MASK=230−1.OutputPrint nn lines, ii-th line should contain a single integer — the answer to the ii-th query.ExamplesInputCopy7
a 1
a 0
y 3
y 5
v 4
u 6
r 8
OutputCopy1
2
4
5
7
9
12
InputCopy4
a 2
y 2
z 0
y 2
OutputCopy2
2
2
2
InputCopy5
a 7
u 5
t 3
s 10
s 11
OutputCopy7
9
11
12
13
NoteFor convenience; we will call "suspicious" those subsegments for which the corresponding lines are prefixes of SS, that is, those whose suspiciousness may not be zero.As a result of decryption in the first example, after all requests, the string SS is equal to "abacaba", and all wi=1wi=1, that is, the suspiciousness of all suspicious sub-segments is simply equal to 11. Let's see how the answer is obtained after each request:1. SS = "a", the array WW has a single subsegment — [1, 1][1, 1], and the corresponding substring is "a", that is, the entire string SS, thus it is a prefix of SS, and the suspiciousness of the subsegment is 11.2. SS = "ab", suspicious subsegments: [1, 1][1, 1] and [1, 2][1, 2], total 22.3. SS = "aba", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3] and [3, 3][3, 3], total 44.4. SS = "abac", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] and [3, 3][3, 3], total 55.5. SS = "abaca", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [3, 3][3, 3] and [5, 5][5, 5], total 77.6. SS = "abacab", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [1, 6][1, 6], [3, 3][3, 3], [5, 5][5, 5] and [5, 6][5, 6], total 99.7. SS = "abacaba", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [1, 6][1, 6], [1, 7][1, 7], [3, 3][3, 3], [5, 5][5, 5], [5, 6][5, 6], [5, 7][5, 7] and [7, 7][7, 7], total 1212.In the second example, after all requests SS = "aaba", W=[2,0,2,0]W=[2,0,2,0].1. SS = "a", suspicious subsegments: [1, 1][1, 1] (suspiciousness 22), totaling 22.2. SS = "aa", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [2, 2][2, 2] ( 00), totaling 22.3. SS = "aab", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [1, 3][1, 3] ( 00), [2, 2][2, 2] (00), totaling 22.4. SS = "aaba", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [1, 3][1, 3] ( 00), [1, 4][1, 4] (00), [2, 2][2, 2] (00), [4, 4][4, 4] (00), totaling 22.In the third example, from the condition after all requests SS = "abcde", W=[7,2,10,1,7]W=[7,2,10,1,7].1. SS = "a", suspicious subsegments: [1, 1][1, 1] (77), totaling 77.2. SS = "ab", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), totaling 99.3. SS = "abc", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), totaling 1111.4. SS = "abcd", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), [1, 4][1, 4] (11), totaling 1212.5. SS = "abcde", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), [1, 4][1, 4] (11), [1, 5][1, 5] (11), totaling 1313.

// LUOGU_RID: 102268817
#include<bits/stdc++.h>
#define int __int128
#define N 600005
using namespace std;
int read(){
	int w=0,h=1;char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')h=-h;ch=getchar();}
	while(ch>='0'&&ch<='9'){w=w*10+ch-'0';ch=getchar();}
	return w*h;
}
void write(int x){if(x>9)write(x/10);putchar(x%10+'0');}
int n,w[N],nxt[N],fail[N],stk[N],top;
map<int,int>s;vector<int>del;
char S[N],ch[2];
signed main(){
	n=read();
	int ans=0,sum=0;
	for(int i=1,j=0;i<=n;i++){
		scanf("%s",ch+1);w[i]=read();
		S[i]=(ch[1]-'a'+ans)%26+'a';
		w[i]^=(ans&((1<<30)-1));
		while(j&&S[i]!=S[j+1])j=nxt[j];
		if(i>1&&S[i]==S[j+1])j++;nxt[i]=j;
		fail[i-1]=(S[i]==S[nxt[i-1]+1])?fail[nxt[i-1]]:nxt[i-1];
		for(int k=i-1,val;k;)
			if(S[i]==S[k+1])k=fail[k];
			else{
				sum-=(val=w[*lower_bound(stk+1,stk+top+1,i-k)]);
				if(--s[val]==0)s.erase(val);k=nxt[k];
			}
		while(top&&w[stk[top]]>=w[i])top--;stk[++top]=i;
		int cnt=0;del.clear();
		for(auto it=s.upper_bound(w[i]);it!=s.end();it++)
			cnt+=it->second,sum+=(w[i]-it->first)*it->second,del.push_back(it->first);
		for(auto u:del)s.erase(u);s[w[i]]+=cnt;
		if(i>1&&S[i]==S[1])sum+=w[i],s[w[i]]++;
		ans+=sum+w[stk[1]];
		write(ans);putchar('\n');
	}
	return 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 <bits/stdc++.h>
using namespace std;
int main() {
int n;cin>>n;
while(n--){
    int indx=0,sum=0, s=0,t = 0;
    cin>>t;
    string srt ;
    cin>>srt;
    for(int i =0;i<10000;i++){
      s=srt.find_last_of( "A")  ;
        if(s<srt.size()){
        sum=srt.size()-s-1;
        srt.erase(s,srt.size()-s );
        }
        if(sum>indx)
        indx=sum;
    }
    cout<<indx<<endl;
}

}


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

#include<bits/stdc++.h>

#define MOD 1000000007

#define eps 1e-9

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

#define endl '\n'

#define ll              long long

#define ull             unsigned long long

#define MAX 200010

#define pb push_back

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

#define pf push_front

#define fi first

#define se second

#define pii pair<int,int>

const int INF = INT_MAX;

using namespace std;

const int N=1e6+10;

#define int long long

/*----------------------------------------------------------------*/

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

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

/*----------------------------------------------------------------*/

void READ(){

#ifndef ONLINE_JUDGE

    freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);

#endif

}

int n,m;

int dp[20][1001];

const int mod=1e9+7;

int calc(int i,int j){

    if(i==m){

        return 1;

    }

    int &ret=dp[i][j];

    if(~ret){

        return ret;

    }

    ret=0;

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

        ret=(ret+calc(i+1,k))%mod;

    }

    return ret;

}

void solve(){

    cin>>n>>m;

    m*=2;

    memset(dp,-1,sizeof dp);

    cout<<calc(0,1)<<endl;

}

signed main() {

    emailam

    //READ();

    int t=1;

    //cin>>t;

    while(t--){

        solve();

    }

}


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.

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=5e3+1;
int n;
int f[N][N],s[N],p[N],c[N];
signed main()
{
scanf("%lld",&n);
for(int i=1;i<=n;i++)
{
int x;
scanf("%lld",&x);
c[x]++;
}
p[0]=1;
for(int i=1;i<=5000;i++)
{
p[i]=p[i-1];
for(int j=2,x=i;j<=i;j++)
{
f[i][j]=f[i-1][j];
if(x%j)continue;
while(x%j==0)f[i][j]++,x/=j;
p[i]=max(p[i],j);
}
}
int ans=0;
for(int i=1;i<=5000;i++)
for(int j=1;j<=i;j++)ans+=f[i][j]*c[i];
while(1)
{
memset(s,0,sizeof(s));
for(int i=1;i<=5000;i++)s[p[i]]+=c[i];
int mx=1;
for(int i=1;i<=5000;i++)if(s[i]>s[mx])mx=i;
if(mx==1||s[mx]*2<n)break;
ans=ans+n-s[mx]*2;
for(int i=1;i<=5000;i++)
{
if(p[i]!=mx)p[i]=1;
if(p[i]==1)continue;
f[i][p[i]]--;
while(p[i]>1&&!f[i][p[i]])p[i]--;
}
}
printf("%lld\n",ans);
return 0;
}


F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer.

// LUOGU_RID: 101682976

#include<cstdio>

#include<ctime>

#include<iostream>

#include<cmath>

#include<cstring>

#include<cctype>

#include<cstdlib>

#include<vector>

#include<algorithm>

#include<queue>

#include<cassert>

#include<random>

#include<numeric>

#include<functional>

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

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

#define tor(i,v,x) for(int i=head[x],v=to[i];i;i=nxt[i],v=to[i])

#define ls(x) ch[x][0]

#define rs(x) ch[x][1]

#define mpi(x,y) make_pair(x,y)

#define pi pair<int,int>

#define fi first

#define se second

//#define int ll

#define DEBUG printf("%s %d\n",__FUNCTION__,__LINE__)

using namespace std;

typedef long long ll;

typedef double db;

typedef long double ldb;

template<typename T>

void read(T &x){

	x=0;char ch=getchar();bool f=0;

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

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

		ch=getchar();

	}

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

	x=f?-x:x;

}

template<typename T,typename...Args>

void read(T &x,Args &...args){

	read(x);read(args...);

}

const int N=1e6+7;

int n,m,ans;

int dep[N];

vector<pi>mx[N];

vector<int>G[N];

vector<int>wt(3,0);

void upd(int x,int y,int z){

	wt[0]=x,wt[1]=y,wt[2]=z;

}

void df(int u,int fa){

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

	mx[u].push_back(mpi(0,u));

	mx[u].push_back(mpi(0,u));

	for(int v:G[u]){

		if(v^fa){

			df(v,u);

			mx[u].push_back(mpi(mx[v][0].fi+1,mx[v][0].se));

		}

	}

	sort(mx[u].begin(),mx[u].end(),[&](pi &lhs,pi &rhs){

		return lhs.fi>rhs.fi;

	});

}

void dfs(int u,int fa){

	sort(mx[u].begin(),mx[u].end(),[&](pi &lhs,pi &rhs){

		return lhs.fi>rhs.fi;

	});

	if(mx[u][0].fi+mx[u][1].fi+mx[u][2].fi>ans){

		ans=mx[u][0].fi+mx[u][1].fi+mx[u][2].fi;

		upd(mx[u][0].se,mx[u][1].se,mx[u][2].se);

	}

//	cout<<"////u:"<<u<<endl;

//	for(pi p:mx[u]){

//		cout<<p.se<<' '<<p.fi<<' '<<"| ";

//	}

//	cout<<endl;

	for(int v:G[u]){

		if(v^fa){

			if(mx[v][0].se==mx[u][0].se){

				mx[v].push_back(mpi(mx[u][1].fi+1,mx[u][1].se));

			}else{

				mx[v].push_back(mpi(mx[u][0].fi+1,mx[u][0].se));

			}

			dfs(v,u);

		}

	}

}

void solve(){

	read(n);//mx和cmx存的就是节点了

	//dfs下放的时候注意下放节点标号和最长长度

	fs(i,1,n-1){

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

	}

	df(1,0);dfs(1,0);

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

	if(wt[1]==wt[0]||wt[1]==wt[2]){

		fs(i,1,n){

			if(i!=wt[0]&&i!=wt[2]){

				wt[1]=i;break;

			}

		}

	}

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

	for(int nd:wt)printf("%d ",nd);

}

signed main(){

	int T=1;while(T--){

		solve();

	}

	return 0;

}


E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6
-100 -200 -300 125 77 -4
OutputCopy9
InputCopy1000000000000 5
-1 0 0 0 0
OutputCopy4999999999996
InputCopy10 4
-3 -6 5 4
OutputCopy-1

#include <bits/stdc++.h>

#define ll long long

using namespace std;

const ll mod = 1e9+7;

int main()

{

    ios::sync_with_stdio(false);

    cin.tie(NULL);

    cout.tie(NULL);

    ll H,n,najm=1e18,idx=-1;

    cin >> H >> n;

    vector<ll>a(n),p(n),x(n,1e18);

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

    {

        cin >> a[i];

        if(i) p[i]=p[i-1],x[i]=x[i-1];

        p[i]+=a[i];

        x[i]=min(x[i],p[i]);

    }

    if(p[n-1]>=0)

    {

        if(x[n-1]>-H)

        {

            cout << -1;

            return 0;

        }

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

        {

            if(p[i]>=-H&&p[i]<0)

            {

                cout << 1+i;

                return 0;

            }

        }

    }

    ll l=0,r=LLONG_MAX/abs(p[n-1]),o=-1;

    while(l<=r)

    {

        ll s=(l+r)/2;

        if(s*p[n-1]+x[n-1]<=-H)

        {

            o=s;

            r=s-1;

        }

        else l=s+1;

    }

  //  cout << o << endl;

    ll R=o*p[n-1],ans=n*o;

    l=0,r=n-1,o=-1;

    while(l<=r)

    {

        ll s=(l+r)/2;

        if(x[s]+R<=-H)

        {

            o=s;

            r=s-1;

        }

        else l=s+1;

    }

   // cout << ans << ' ' << o << endl;

    cout << ans+o+1;

    return 0;

}


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

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

// #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")

#include <bits/stdc++.h>

#include <ext/rope>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/hash_policy.hpp>

#include <ext/pb_ds/tree_policy.hpp>

#include <ext/pb_ds/trie_policy.hpp>

#include <ext/pb_ds/priority_queue.hpp>

using namespace std;

using namespace __gnu_cxx;

using namespace __gnu_pbds;

template <class T> using Tree = tree<T, null_type, less_equal<T>, rb_tree_tag,tree_order_statistics_node_update>;

using Trie = trie<string, null_type, trie_string_access_traits<>, pat_trie_tag, trie_prefix_search_node_update>;

// template <class T> using heapq = __gnu_pbds::priority_queue<T, greater<T>, pairing_heap_tag>;

template <class T> using heapq = std::priority_queue<T, vector<T>, greater<T>>;

#define ll long long

#define i128 __int128

#define ld long double

#define ui unsigned int

#define ull unsigned long long

#define pii pair<int, int>

#define pll pair<ll, ll>

#define pdd pair<ld, ld>

#define vi vector<int>

#define vvi vector<vector<int>>

#define vll vector<ll>

#define vvll vector<vector<ll>>

#define vpii vector<pii>

#define vpll vector<pll>

#define lb lower_bound

#define ub upper_bound

#define pb push_back

#define pf push_front

#define eb emplace_back

#define fi first

#define se second

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

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

#define each(x, v) for(auto& x: v)

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

#define elif else if

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

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

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

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

#define bitcnt(x) (__builtin_popcountll(x))

#define endl "\n"

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

#define Ran(a, b) rng() % ( (b) - (a) + 1 ) + (a)

struct custom_hash {

    static uint64_t splitmix64(uint64_t x) {

        // http://xorshift.di.unimi.it/splitmix64.c

        x += 0x9e3779b97f4a7c15;

        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;

        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;

        return x ^ (x >> 31);

    }

    size_t operator()(uint64_t x) const {

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

        return splitmix64(x + FIXED_RANDOM);

    }

    size_t operator()(pair<uint64_t,uint64_t> x) const {

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

        return splitmix64(x.first + FIXED_RANDOM) ^ (splitmix64(x.second + FIXED_RANDOM) >> 1);

    }

};

const i128 ONE = 1;

istream &operator>>(istream &in, i128 &x) {

    string s;

    in >> s;

    bool minus = false;

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

        minus = true;

        s.erase(s.begin());

    }

    x = 0;

    for (auto i : s) {

        x *= 10;

        x += i - '0';

    }

    if (minus) x = -x;

    return in;

}

ostream &operator<<(ostream &out, i128 x) {

    string s;

    bool minus = false;

    if (x < 0) {

        minus = true;

        x = -x;

    }

    while (x) {

        s.push_back(x % 10 + '0');

        x /= 10;

    }

    if (s.empty()) s = "0";

    if (minus) out << '-';

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

    out << s;

    return out;

}

template <class T> ostream &operator<<(ostream &os, const vector<T> &v) {

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

template <class T> ostream &operator<<(ostream &os, const set<T> &v) {

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

template <class T> ostream &operator<<(ostream &os, const multiset<T> &v) {

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

template <class T> ostream &operator<<(ostream &os, const Tree<T> &v) {

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

template <class T, class S> ostream &operator<<(ostream &os, const pair<T, S> &p) {

    os << p.first << " " << p.second;

    return os;

}

ll gcd(ll x,ll y) {

    if(!x) return y;

    if(!y) return x;

    int t = __builtin_ctzll(x | y);

    x >>= __builtin_ctzll(x);

    do {

        y >>= __builtin_ctzll(y);

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

        y -= x;

    } while(y);

    return x<<t;

}

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

ll exgcd(ll a, ll b, ll &x, ll &y) {

    if(!b) return x = 1, y = 0, a;

    ll d = exgcd(b, a % b, x, y);

    ll t = x;

    x = y;

    y = t - a / b * x;

    return d;

}

ll max(ll x, ll y) { return x > y ? x : y; }

ll min(ll x, ll y) { return x < y ? x : y; }

ll Mod(ll x, int mod) { return (x % mod + mod) % mod; }

ll pow(ll x, ll y, ll mod){

    ll res = 1, cur = x;

    while (y) {

        if (y & 1) res = res * cur % mod;

        cur = ONE * cur * cur % mod;

        y >>= 1;

    }

    return res % mod;

}

ll probabilityMod(ll x, ll y, ll mod) {

    return x * pow(y, mod-2, mod) % mod;

}

vvi getGraph(int n, int m, bool directed = false) {

    vvi res(n);

    rep(_, 0, m) {

        int u, v;

        cin >> u >> v;

        u--, v--;

        res[u].emplace_back(v);

        if(!directed) res[v].emplace_back(u);

    }

    return res;

}

vector<vpii> getWeightedGraph(int n, int m, bool directed = false) {

    vector<vpii> res(n);

    rep(_, 0, m) {

        int u, v, w;

        cin >> u >> v >> w;

        u--, v--;

        res[u].emplace_back(v, w);

        if(!directed) res[v].emplace_back(u, w);

    }

    return res;

}

const ll LINF = 0x1fffffffffffffff;

const ll MINF = 0x7fffffffffff;

const int INF = 0x3fffffff;

const int MOD = 1000000007;

const int MODD = 998244353;

const int N = 1e6 + 10;

void solve() {

    int n;

    cin >> n;

    vi a(n);

    each(i, a) cin >> i;

    auto calc = [&] (int bit) -> int {

        vi h;

        each(i, a) h.pb(i % (1 << bit + 1));

        sort(all(h));

        int res = 0;

        each(i, h) {

            res += ub(all(h), (1 << bit + 1) - 1 - i) - lb(all(h), (1 << bit) - i);

            if ((1 << bit) - i <= i && i <= (1 << bit + 1) - 1 - i)

                res -= 1;

            res += ub(all(h), (1 << bit + 2) - 2 - i) - lb(all(h), (0b11 << bit) - i);

            if ((0b11 << bit) - i <= i && i <= (1 << bit + 2) - 2 - i)

                res -= 1;

        }

        res /= 2;

        return res & 1;

    };

    int ans = 0;

    rep(bit, 0, 30) ans |= calc(bit) << bit;

    cout << ans << endl;

}

signed main() {

    ios::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    int t = 1;

    // cin >> t;

    while (t--) {

        solve();

    }

    return 0;

}


C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab.  During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab.  During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab.  During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba.  During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows.  During the first move, remove the third character s3=s3= d, ss becomes bca.  During the second move, remove the second character s2=s2= c, ss becomes ba.  And during the third move, remove the first character s1=s1= b, ss becomes a.

// @author manish926

//NEVER GIVE UP,struggle... ,struggle...,struggle....        success.

#include<bits/stdc++.h>

using namespace std;

#define ll                            long long int

#define ld                            long double

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

#define f3(j,n)                       for(int j=0;j<n;j++)

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

#define vi                            vector<long long>

#define pi                            pair<long long,long long>

#define vvi                           vector<vector<int,int>>

#define vll                           vector<ll>

#define mi                            map<long long,long long>

#define umi                           unordered_map<long long,long long>

#define si                            set<long long>

#define usi                           unordered_set<long long>

#define pb                            push_back

#define pp                            pop_back

#define sortv(v)                      sort(v.begin(),v.end())

#define e                             '\n'

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

#define mp                            make_pair

#ifndef ONLINE_JUDGE

#define debug(x) cerr << #x <<" "; _print(x); cerr << endl;

#else

#define debug(x)

#endif

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

void _print(ld t) {cerr << t;}

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

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

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

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

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

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

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

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

signed main(){

ios_base::sync_with_stdio(false);

cin.tie(NULL);

int n;cin>>n;

string s;cin>>s;

int ans =0;

for(char ch = 'z' ; ch>='b';){

   int t = 0;

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

        if(s[i] == ch){

             if(i > 0 && ((ch-'0')-1 == (s[i-1]-'0'))){

               s.erase(s.begin()+i);

               ans++;

               t++;

               break;

             }else if(i<n-1 && ((ch-'0')-1 == (s[i+1]-'0'))){

               s.erase(s.begin()+i);

               ans++;

               t++;

               break;

             }

        }

   }

   if(t==0)ch--;

}

cout<<ans<<e;

return 0;

}


E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can:  choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive;  take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously.  Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this:  In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3
3 2 1
1 2 3
4 5 6
OutputCopy6
InputCopy4 3
1 2 3
4 5 6
7 8 9
10 11 12
OutputCopy0
InputCopy3 4
1 6 3 4
5 10 7 8
9 2 11 12
OutputCopy2
NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.

#include<iostream>

#include <bits/stdc++.h>

using namespace std;

template<class container> void print(container v) { for (auto& it : v) cout << it << ' ' ;cout <<endl;}

using ll = long long;

using ull = unsigned long long;

using ld = long double;

#define nd "\n"

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

#define popcount(x)  __builtin_popcount(x)

const ll N = 2e5+50 , LOG = 22 , inf = 1e8 , SQ= 550 , mod = 1e9+7;

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

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

#define pp  cout <<"ppppppppppppppppp"<<nd;

#define lol cout <<"i am here"<<nd;

const  double PI = acos(-1.0);

const int MX = 1000+10;

void hi(){

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

    vector<vector<ll> > a(n , vector <ll>(m));

    for (auto &i : a) for (auto &j : i) cin >> j , --j;

    ll ans = 0;

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

        vector <int > cnt(n);// the number of cycles needed to put the element in its position

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

            if (a[i][j] % m != j || a[i][j] /m >= n) continue;

            cnt[(i - a[i][j]/m +n) % n]++;

        }

        int cur = n - cnt[0];

        for (int i = 1; i < n; ++i) cur = min(cur , n-cnt[i]+i);

        ans+=cur;

    }

    cout << ans <<nd;

}

int main(){

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

    int tt = 1 , tc = 0;

  // cin >> tt;

    while(tt--) hi();

    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>

using namespace std;

const int N = 1e5 + 1, M = 20;

vector<int> adj[N];

int dep[N], Par[N][M], path[N];

void dfs(int cur, int par)

{

    dep[cur] = dep[par] + 1;

    Par[cur][0] = par;

    for (int j = 1; j < M; j++) Par[cur][j] = Par[Par[cur][j - 1]][j - 1];

    for (auto x : adj[cur]) if (x != par)  dfs(x, cur);

}

int LCA(int u, int v)

{

    if (u == v) return u;

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

    int diff = dep[u] - dep[v];

    for (int j = M - 1; j >= 0; j--)

    {

        if ((diff >> j) & 1) u = Par[u][j];

    }

    for (int j = M - 1; j >= 0; j--)

    {

        if (Par[u][j] != Par[v][j]) {

            u = Par[u][j];

            v = Par[v][j];

        }

    }

    return (u != v ? Par[u][0] : u);

}

int distance(int a, int b)

{

    int c = LCA(a, b);

    return dep[a] + dep[b] - 2*dep[c];

}

int 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; cin >> n;

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

    {

        int x, y; cin >> x >> y;

        adj[x].push_back(y);

        adj[y].push_back(x);

    }

    dfs(1, 0);

    int q; cin >> q;

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

    {

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

        int path1 = distance(a, b);

        int path2 = distance(a, x) + distance(y, b) + 1;

        int path3 = distance(a, y) + distance(x, b) + 1;

        if(path1 <= k && path1%2 == k%2) cout << "YES\n";

        else if(path2 <= k && path2%2 == k%2) cout << "YES\n";

        else if(path3 <= k && path3%2 == k%2) cout << "YES\n";

        else cout << "NO\n";

    }

}


B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3
2 0
0 2
2 0
OutputCopyYES
1 2 1 InputCopy5
0 1
1 3
2 1
3 0
2 0
OutputCopyYES
2 3 2 1 2

#include "bits/stdc++.h"

using namespace std;

// #define MULTI_TESTS

// #define FLOAT_PRECISION 13

void solve() {

    int n;

    cin >> n;

    vector p(n + 1, 0), c(n + 1, 0);

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

        cin >> p[i] >> c[i];

    vector<vector<int>> adj(n + 1);

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

        adj[p[i]].push_back(i);

    int rt = -1;

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

        if (p[i] == 0)

            rt = i;

    vector<int> sz(n + 1);

    auto dfs = [&] (auto &f, int cur) -> int {

        int s = 1;

        for (auto &e : adj[cur]) {

            s += f(f, e);

        }

        return sz[cur] = s;

    };

    dfs(dfs, rt);

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

        if (c[i] >= sz[i]) {

            cout << "NO\n";

            return;

        }

    }

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

    auto dfs2 = [&] (auto &f, int cur, vector<int> &av) -> void {

        ans[cur] = av[c[cur]];

        int i = 0;

        for (auto &e : adj[cur]) {

            vector<int> cv;

            for (int j = 0; j < sz[e]; ++j) {

                if (i == c[cur])

                    i++;

                cv.push_back(av[i]);

                i++;

            }

            f(f, e, cv);

        }

    };

    vector<int> av(n);

    iota(begin(av), end(av), 1);

    dfs2(dfs2, rt, av);

    cout << "YES\n";

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

        cout << ans[i] << ' ';

    cout << '\n';

};

void init() {

}

int main()

{

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    cin.exceptions(cin.failbit);

    #ifdef FLOAT_PRECISION

        cout << fixed;

        cout.precision(FLOAT_PRECISION);

    #endif

    init();

    int numTests = 1;

    #ifdef MULTI_TESTS

        cin >> numTests;

    #endif

    for (int testNo = 1; testNo <= numTests; testNo++) {

        solve();

    }

    return 0;

}


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

#include <bits/stdc++.h>

#define x first

#define y second

#define TLE ios::sync_with_stdio(0),cin.tie(0)

using namespace std;

typedef long long LL;

typedef pair<int, int> PII;

typedef pair<double, double> PDD;

typedef unsigned long long ULL;

const int N = 3e5 + 10, M = 2 * N, mod = 1e9 + 7;

const double eps = 1e-8;

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

int h[N], ne[M], e[M], w[M];

LL T, n, m, k;

int a[N], s[N];

int main()

{

    TLE;

    cin >> n;

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

    map<int, vector<PII>> hash;

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

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

            hash[s[i] - s[j - 1]].push_back({j, i});

    //for (auto& c : hash[3]) cout << c.x << " " << c.y << endl;

    int st = -2e9, ed = -2e9;

    vector<PII> ans;

    for (auto& v : hash){

        st = -2e9, ed = -2e9;

        vector<PII> tmp;

        for (auto& c : v.y){

            if (c.x > ed){

                if (ed != -2e9) tmp.push_back({st, ed});

                st = c.x, ed = c.y;

            }

        }

        tmp.push_back({st, ed});

        if (tmp.size() > ans.size()) ans = tmp;

    }

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

    for (auto& c : ans) cout << c.x << " " << c.y << "\n";

}


B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows:  However, the results of the Olympiad could also look like this:  In the first case Nikolay would have taken first place, and in the second — third place.

#include <iostream>
#include <algorithm>
using namespace std;
void solve(){
int n,x,y;
cin>>n>>x>>y;
cout<<max(min(x+y-n+1,n),1)<<' '<<min(x+y-1,n)<<endl;
}
int main(){
int t;
cin>>t;
while(t--)solve();
return 0;
}


C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.

#include<iostream>
#include<vector>
#include<stack>
#include<deque>
using namespace std;
typedef long long ll;
void solve() {
	int n;
	cin >> n;
	vector<ll> a(n + 1);
	vector<ll> presum(n + 1), sufsum(n + 1);
	for (int i = 1; i <= n; ++i) {
		cin >> a[i];
	}
	stack<ll> st;//栈里面存放的是下标
	vector<ll> l(n + 2), r(n + 2);
	for (int i = 1; i <= n; ++i) {
		while (!st.empty() && a[st.top()] >=
		        a[i]) {
			// 不同题目的符号不同，注意分辨
			st.pop();
		}
		l[i] = (st.size() == 0 ? 0 :
		        st.top());
		st.push(i);// 注意栈里面放进去的是下标
	}
	while (!st.empty())st.pop();
	for (int i = n; i >= 1; --i) {
		while (!st.empty() && a[st.top()] >=
		        a[i]) {
			// 不同题目的符号不同，注意分辨
			st.pop();
		}
		r[i] = (st.size() == 0 ? (n + 1) :
		        st.top());
		st.push(i);// 注意栈里面放进去的是下标
	}

	for (int i = 1; i <= n; i++) {
		presum[i] = presum[l[i]] + a[i] * (i - l[i]);
	}
	for (int i = n; i >= 1; --i) {
		sufsum[i] = sufsum[r[i]] + a[i] * (r[i] - i);
	}

	vector<ll> res(n + 1);
	int idx;
	ll ans = -1;
	for (int j = 1; j <= n; j++) {
		if (ans < presum[j] + sufsum[j] - a[j]) {
			ans = presum[j] + sufsum[j] - a[j];
			idx = j;
		}
	}
	ll pre = a[idx];
	for (int i = idx - 1; i >= 1; --i) {
		res[i] = min(pre, a[i]);
		pre = min(pre, a[i]);
	}
	res[idx] = a[idx];
	pre = a[idx];
	for (int i = idx + 1; i <= n; i++) {
		res[i] = min(pre, a[i]);
		pre = min(pre, a[i]);
	}
	for (int i = 1; i <= n; i++) {
		cout << res[i] << " ";
	}
}
int main() {
	ios::sync_with_stdio(false), cin.tie(0);
	solve();
}


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

#include <bits/stdc++.h>

using namespace std;

#define int long long

const int maxn=405;

bitset<maxn> dp[maxn][maxn];

int32_t main()

{

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

    int t;cin>>t;

    while(t--)

    {

        string s1,s2;cin>>s1>>s2;

        int m=s2.size();s2.push_back('$');

        bool ok=false;

        {

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

            for(int i=0;i<=m;++i) dp[0][i][i]=1;

            for(char c:s1)

            {

                for(int i=m;i>=0;--i)

                {

                    for(int j=m;j>=i;--j)

                    {

                        if(c==s2[i]) dp[i+1][j]|=dp[i][j];

                        if(c==s2[j]) dp[i][j+1]|=dp[i][j];

                    }

                }

            }

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

            if(dp[i][m][i])

            {

                ok=true;

                break;

            }}

        }

        puts(ok ? "YES" : "NO");

    }

    return 0;

}


A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11

#include <iostream>

#include <map>

using namespace std;

int main()

{

    map<int,int> m;

    m[1] = 2;

    m[2] = 5;

    m[3] = 5;

    m[4] = 4;

    m[5] = 5;

    m[6] = 6;

    m[7] = 3;

    m[8] = 7;

    m[9] = 6;

    m[0] = 6;

    int n,f;

    string s;

    cin>>n;

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

    {

        s = "";

        f = 0;

        int tmp;

        cin>>tmp;

        int res = tmp/2;

        if(tmp%2 == 1)

        {

            res -=1;

            f = 1;

        }

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

        {

            s += "1";

        }

        if(f)

            s = "7" + s;

        cout<<s<<endl;

    }

    return 0;

}


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

//Author: Frustrated_EH

//Complexity: O(?)

#include <bits/stdc++.h>

//#define int long long

using namespace std;

const int mod = 998244353;

namespace FastIO {

	template<typename T>inline T    read(){T x=0,w=1;char c=0;while(c<'0'||c>'9'){if(c=='-')w=-1;c=getchar();}while(c>='0'&&c<='9'){x=x*10+(c-'0');c=getchar();}return x*w;}

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

	inline int                      getInt(){return read<int>();}

	inline int                      putInt(int x,char c){write<int>(x),putchar(c);return 0;}

} namespace Number_Theory {

	int  pw(int a,int b,int p=mod){int res=1;while(b){if(b&1)res=res*a%p;a=a*a%p;b>>=1;}return res;}

	int  gcd(int x,int y){return!y?x:gcd(y,x%y);}

	void exgcd(int a,int b,int&x,int&y){if(!b){x=1,y=0;return;}exgcd(b,a%b,y,x);y-=(a/b*x);}

	int  inv(int x,int p=mod){exgcd(x,p,x,*new int);return(x%p+p)%p;}

	int  bsgs(int a,int b,int p){map<int,int>val;int A=1,t=sqrt(p)+1;for(int i=0;i<t;i++){val[A*b%p]=i;A=A*a%p;}for(int i=1,_a=A;i<=t;i++){if(val[_a]&&val[_a]!=-1){int ans=i*t-val[_a];for(int i=0,A=1;i<t;i++){val[A*b%p]=-1;A=A*a%p;}return ans;}_a=_a*A%p;}return-1;}

} using namespace FastIO; using namespace Number_Theory;

const int N = 85;

int e[N][N], f[N], t[N];

int Solve() {

	srand(time(0));

	int n = getInt(), k = getInt();

	int res = mod;

	for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) e[i][j] = getInt();

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

		for(int j = 2; j <= n; j++) f[j] = mod, t[j] = rand() & 1;

		for(int i = 1; i <= k; i++) for(int j = 1; j <= n; j++) if((i & 1) == t[j]) {

			f[j] = mod;

			for(int k = 1; k <= n; k++) if((i & 1) != t[k]) f[j] = min(f[j], f[k] + e[k][j]);

		}

		res = min(res, f[1]);

		f[1] = 0;

	}

	putInt(res, '\n');

	return 0;

}

signed main() {

	int T = 1;

//	T = getInt();

	while(T--) Solve();

	return 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.

#include <iostream>
#include <vector>

using namespace std;

int main()
{
   int n;
   vector<int> r;
   vector<int> b;
   int rw=0;
   int bw=0;
   int ans;
   cin>>n;
   for(int i = 0; i<n; i++){
       int r_i;
       cin>>r_i;
       r.push_back(r_i);
   }
    for(int i = 0; i<n; i++){
       int b_i;
       cin>>b_i;
       b.push_back(b_i);
   }
   for(int i = 0; i<n; i++){
       if(r[i]>b[i]){
           rw+=1;

       }
        if(b[i]>r[i]){
           bw+=1;

       }
    }

   bw+=1;
 if(rw==0){
      ans=-1;
   }
   else{
   if(bw%rw==0){
       ans=bw/rw;
    }
    else{
     ans=bw/rw+1;
     }
     }
     cout<<ans;

    return 0;
}


D. Reality Showtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA popular reality show is recruiting a new cast for the third season! nn candidates numbered from 11 to nn have been interviewed. The candidate ii has aggressiveness level lili, and recruiting this candidate will cost the show sisi roubles.The show host reviewes applications of all candidates from i=1i=1 to i=ni=n by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate ii is strictly higher than that of any already accepted candidates, then the candidate ii will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit.The show makes revenue as follows. For each aggressiveness level vv a corresponding profitability value cvcv is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant ii enters the stage, events proceed as follows:  The show makes clicli roubles, where lili is initial aggressiveness level of the participant ii.  If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is:  the defeated participant is hospitalized and leaves the show.  aggressiveness level of the victorious participant is increased by one, and the show makes ctct roubles, where tt is the new aggressiveness level.  The fights continue until all participants on stage have distinct aggressiveness levels. It is allowed to select an empty set of participants (to choose neither of the candidates).The host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total sisi). Help the host to make the show as profitable as possible.InputThe first line contains two integers nn and mm (1≤n,m≤20001≤n,m≤2000) — the number of candidates and an upper bound for initial aggressiveness levels.The second line contains nn integers lili (1≤li≤m1≤li≤m) — initial aggressiveness levels of all candidates.The third line contains nn integers sisi (0≤si≤50000≤si≤5000) — the costs (in roubles) to recruit each of the candidates.The fourth line contains n+mn+m integers cici (|ci|≤5000|ci|≤5000) — profitability for each aggrressiveness level.It is guaranteed that aggressiveness level of any participant can never exceed n+mn+m under given conditions.OutputPrint a single integer — the largest profit of the show.ExamplesInputCopy5 4
4 3 1 2 1
1 2 1 2 1
1 2 3 4 5 6 7 8 9
OutputCopy6
InputCopy2 2
1 2
0 0
2 1 -100 -100
OutputCopy2
InputCopy5 4
4 3 2 1 1
0 2 6 7 4
12 12 12 6 -3 -5 3 10 -4
OutputCopy62
NoteIn the first sample case it is optimal to recruit candidates 1,2,3,51,2,3,5. Then the show will pay 1+2+1+1=51+2+1+1=5 roubles for recruitment. The events on stage will proceed as follows:  a participant with aggressiveness level 44 enters the stage, the show makes 44 roubles;  a participant with aggressiveness level 33 enters the stage, the show makes 33 roubles;  a participant with aggressiveness level 11 enters the stage, the show makes 11 rouble;  a participant with aggressiveness level 11 enters the stage, the show makes 11 roubles, a fight starts. One of the participants leaves, the other one increases his aggressiveness level to 22. The show will make extra 22 roubles for this. Total revenue of the show will be 4+3+1+1+2=114+3+1+1+2=11 roubles, and the profit is 11−5=611−5=6 roubles.In the second sample case it is impossible to recruit both candidates since the second one has higher aggressiveness, thus it is better to recruit the candidate 11.


#include <bits/stdc++.h>

using namespace std;

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

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

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

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

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

#define fs first

#define se second

#define Odd(_x) ((_x) & 1)

using i64 = long long;

using ll = long long;

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

const int inf = 1e9 + 10;

const ll mod = 1e9 + 7;

void solve() {

    int n, m;

    cin >> n >> m;

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

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

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

            cin >> a[i][j];

            a[i][j]--;

        }

    }

    int ans = 0;

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

        vector<int> cnt(n);

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

            if (a[j][i] % m == i && a[j][i] < n * m) {

                cnt[(j - a[j][i] / m + n) % n] += 1;

            }

        }

        int res = n;

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

            res = min(res, n - cnt[i] + i);

        }

        ans += res;

    }

    cout << ans << "\n";

}

//#define MULTI_INPUT

int main() {

#ifndef ONLINE_JUDGE

    freopen(R"(D:\source files\source file2\input.txt)", "r", stdin);

    freopen(R"(D:\source files\source file2\output.txt)", "w", stdout);

#endif

    std::ios::sync_with_stdio(false);

    cin.tie(nullptr);

    cout << fixed << setprecision(20);

#ifdef MULTI_INPUT

    int T;

    cin >> T;

    while (T--) {

        solve();

    }

#else

    solve();

#endif

    return 0;

}


E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3
1 4 6
OutputCopy1InputCopy4
2 3 6 6
OutputCopy2InputCopy3
6 15 10
OutputCopy3InputCopy4
2 3 5 7
OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence.

// Judges with GCC >= 12 only needs Ofast

// #pragma GCC optimize("O3,no-stack-protector,fast-math,unroll-loops,tree-vectorize")

// MLE optimization

// #pragma GCC optimize("conserve-stack")

// Old judges

// #pragma GCC target("sse4.2,popcnt,lzcnt,abm,mmx,fma,bmi,bmi2")

// New judges. Test with assert(__builtin_cpu_supports("avx2"));

// #pragma GCC target("avx2,popcnt,lzcnt,abm,bmi,bmi2,fma,tune=native")

// Atcoder

// #pragma GCC target("avx2,popcnt,lzcnt,abm,bmi,bmi2,fma")

#include<bits/stdc++.h>

using namespace std;

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

uniform_real_distribution<> pp(0.0,1.0);

#define ld long double

#define pii pair<int,int>

#define piii pair<int,pii>

#define fi first

#define se second

const int inf=1e9;

const int mod=998244353;

const int mod2=1e9+7;

const int maxn=100005;

const int maxm=200005;

const int maxq=500005;

const int maxl=20;

const int maxa=1000000;

int power(int a,int n){

    int res=1;

    while(n){

        if(n&1) res=res*a%mod;

        a=a*a%mod;n>>=1;

    }

    return res;

}

int n,num,a[maxn],prime[maxa+5],pos[maxa+5],cn[maxn],from[maxn],dist[maxn];

vector<pii> edge[maxn];

int query(int s){

    int res=inf;

    for(int i=1;i<=num;i++){dist[i]=-1;from[i]=-1;}

    queue<int> q;q.push(s);dist[s]=0;from[s]=0;

    while(!q.empty()){

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

        for(pii v:edge[u]){

            if(dist[v.fi]!=-1){

                if(from[u]!=v.se) res=min(res,dist[u]+dist[v.fi]+1);

                continue;

            }

            dist[v.fi]=dist[u]+1;from[v.fi]=v.se;

            q.push(v.fi);

        }

    }

    return res;

}

void solve(){

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

        if(prime[i]==0){

            prime[i]=i;pos[i]=++num;

            for(int j=min(i,maxa/i+1)*i;j<=maxa;j+=i) prime[j]=i;

        }

    }

    cin >> n;

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

        cin >> a[i];

        int d=a[i],p=1,q=1;

        while(d>1){

            int j=prime[d],cnt=0;

            while(d%j==0){d/=j;cnt^=1;}

            if(cnt){

                if(p==1) p=j;

                else q=j;

            }

        }

        if(p==1){

            cout << 1 << '\n';

            return;

        }

        else if(q==1) cn[pos[p]]++;

        else{

            edge[pos[p]].push_back({pos[q],i});

            edge[pos[q]].push_back({pos[p],i});

        }

    }

    queue<int> q;

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

        dist[i]=-1;

        if(cn[i]){

            q.push(i);

            dist[i]=1;from[i]=i;

        }

        if(cn[i]>=2){

            cout << 2 << '\n';

            return;

        }

    }

    while(!q.empty()){

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

        for(pii v:edge[u]){

            if(dist[v.fi]!=-1) continue;

            dist[v.fi]=dist[u]+1;from[v.fi]=from[u];

            q.push(v.fi);

        }

    }

    int res=inf;

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

        for(pii v:edge[i]){

            if(dist[i]!=-1 && dist[v.fi]!=-1 && from[i]!=from[v.fi]) res=min(res,dist[i]+dist[v.fi]+1);

        }

    }

    for(int i=1;i*i<=maxa;i++){

        if(pos[i]==0) continue;

        res=min(res,query(pos[i]));

    }

    cout << (res==inf?-1:res) << '\n';

}

signed main(){

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);cout.tie(NULL);

    int test=1;//cin >> test;

    while(test--) solve();

}


#include<bits/stdc++.h>

using namespace std;
int main()
{
int n; string s;
cin>>n>>s;
for(int i='z';i>'a';i--)
for(int k=0;k<s.size();k++)
if(s[k]==i&&(s[k-1]==i-1||s[k+1]==i-1))
s.erase(k,1),k=-1;
cout<<n-s.size()<<endl;
return 0;
}


A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.


B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104)  — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
OutputCopy1 11
5 35
3 6
0 42
0 0
1 2
3 4
NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6].  |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0;  |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3;  |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3;  |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3;  |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33.

#include <bits/stdc++.h>

using namespace std;

#define oo 1000000010

#define mod 1000000007

const int N = 300010;

int n , arr[N] ;

void solve(){

    int mn = oo , mx = -oo;

	scanf("%d",&n);

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

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

	}

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

		if(i > 0 && arr[i] == -1 && arr[i - 1] != -1)

			mn = min(mn , arr[i - 1]) , mx = max(mx , arr[i - 1]);

		if(i < n - 1 && arr[i] == - 1 && arr[i + 1] != -1)

			mn = min(mn , arr[i + 1]) , mx = max(mx , arr[i + 1]);

	}

	int res = (mx + mn) / 2;

	int ans = 0;

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

		if(arr[i] == -1)

			arr[i] = res;

		if(i)

			ans = max(ans,abs(arr[i] - arr[i - 1]));

	}

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

}

int main(){

	int t;

	cin >> t;

	while(t--){

	    solve();

	}

	return 0;

}


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

#include<bits/stdc++.h>

typedef long long ll;

typedef unsigned long long ull;

using namespace std;

const ll mod = 1e9+7;

const int mm = 3e5 + 10;

ll a[mm][10];

ll n,m;

map<ll,pair<ll,ll>>anss;

bool check(ll x){

	map<ll,ll>mp;

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

		ll bj=0;

		int jj=1;

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

			if(a[i][j]>=x)bj+=(1ll<<(j-1));

			else jj=0;

		}

		mp[bj]=i;

		if(jj){

			anss[x].first=anss[x].second=i;

			return 1;

		}

	}

	ll xx=(1ll<<m)-1;

	for(auto [i,y]:mp){

		for(auto [z,w]:mp){

			if((i|z)==xx){

				anss[x].first=y;

				anss[x].second=w;

				return 1;

			}

		}

	}return 0;

}

int main(){

	std::ios::sync_with_stdio(false);

	std::cin.tie(0);

	std::cout.tie(0);

	cin>>n>>m;

	ll ma=0;

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

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

			cin>>a[i][j];

			ma=max(ma,a[i][j]);

		}

	}

	ll l=0,r=ma;

	ll ans=0;

	while(l<=r){

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

		if(check(m))l=m+1,ans=m;

		else r=m-1;

	}cout<<anss[ans].first<<' '<<anss[ans].second;

}


F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer.

// In His Name

#include <bits/stdc++.h>

using namespace std;

const int maxn = 2e5 +5;

int n , dis[maxn] , a , b , c , dadi[maxn];

vector<int> masir;

bool mark[maxn];

vector<int> adj[maxn];

queue<int> q;

void dfs(int u , int dad){

    mark[u] = true;

    dis[u] = dis[dad]+1;

    for (int i = 0; i < adj[u].size(); ++i) {

        int v = adj[u][i];

        if (!mark[v]){

            dadi[v] = u;

            dfs(v , u);

        }

    }

}

void bfs(){

   while(q.size()){

       int u = q.front();

       q.pop();

       for (auto v : adj[u]) {

           if (!mark[v]){

               q.push(v);

               mark[v] = true;

               dis[v] = dis[u] + 1;

           }

       }

   }

}

int main() {

    ios_base::sync_with_stdio(false);

    cin >> n;

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

        int u , v;

        cin >> u >> v;

        adj[v].push_back(u);

        adj[u].push_back(v);

    }

    dfs(1 , 0);

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

        dis[i]--;

    }

    int maxi = 0;

    int f = 0;

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

        if (dis[i] > maxi){

            maxi = dis[i];

            f = i;

        }

    }

    a = f;

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

        dis[i] = 0;

        mark[i] = false;

        dadi[i] = 0;

    }

    dfs(a , 0);

    maxi = 0;

    f = 0;

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

        if (dis[i] > maxi){

            maxi = dis[i];

            f = i;

        }

    }

    b = f;

    int B = b;

    masir.push_back(B);

    while(B != a){

        masir.push_back(dadi[B]);

        B = dadi[B];

    }

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

        mark[i] = false;

        dis[i] = 0;

    }

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

        mark[masir[i]] = true;

        q.push(masir[i]);

        dis[masir[i]] = 0;

    }

    bfs();

    maxi = -1;

    f = 0;

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

        if (maxi < dis[i] and i!= a and i!= b){

            maxi = dis[i];

            f = i;

        }

    }

    c = f;

    cout << masir.size() + maxi-1 << endl;

    cout << a << " " << b << " " << c;

}


E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai; then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions:   Set the power of the hole a to value b.  Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types:   0 a b  1 a  Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInputCopy8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2OutputCopy8 78 57 3

//#pragma GCC optomize ("Ofast")

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

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

#include <bits/stdc++.h>

#define F first

#define S second

#define ll long long

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

#define uint unsigned int

#define pb push_back

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

//#define int ll

using namespace std;

const int N = 1e5+9;

//const ll INF = 1e18 , inf = 1e9 , mod = 1e9+7;

int n,m;

int a[N];

int cnt[N];

int last[N];

int BLOCK=300;

void upd(int x){

	int l=x*BLOCK,r=min(l+BLOCK,n)-1;

	for(int i=r;i>=l;i--){

		if(i+a[i]>r){

			cnt[i]=1;

			last[i]=i;

		}

		else{

			cnt[i]=cnt[i+a[i]]+1;

			last[i]=last[i+a[i]];

		}

	}

}

signed main(){

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

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

    ios;

	int tt=1;

//	cin>>tt;

	while(tt--){

		cin>>n>>m;

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

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

		while(m--){

			int q;

			cin>>q;

			if(q==0){

				int ind,val;

				cin>>ind>>val;

				ind--;

				a[ind]=val;

				upd(ind/BLOCK);

			}

			else{

				int ind;

				cin>>ind;

				int ans=0;

				ind--;

				while(ind<n){

					ans+=cnt[ind];

					ind=last[ind];

					if(ind+a[ind]<n)ind+=a[ind];

					else break;

				}

				cout<<ind+1<<" "<<ans<<'\n';

			}

		}

	}

}