A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3
010011
0
1111000
OutputCopy2
0
0
NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).

#include <utility>

#include <bits/stdc++.h>

using namespace std;

#define si size

#define f first

#define s second

#define vec vector

#define pb push_back

typedef vec <int> vi;

void solve(){

    vi seq;

    pair <vi, vi> res;

    string s;

    int n, cnt = 0;

    cin >> s;

    n = s.length();

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

        seq.pb(int(s[i]) - 48);

    }

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

        if(i == 0){

            res.f.pb(seq[0]);

            res.s.pb(1);

        }

        else if(seq[i] != res.f[j]){

            res.f.pb(seq[i]);

            res.s.pb(1);

            j++;

        }

        else res.s[j] += 1;

    }

    if(res.f.si() == 1 && res.f[0] == 1)

        cout << "0\n";

    else if(res.f.si() == 2 && res.f[0] == 0 && res.f[1] == 1)

        cout << "0\n";

    else if(res.f.si() == 2 && res.f[0] == 1 && res.f[1] == 0)

        cout << "0\n";

    else if(res.f.si() == 3 && res.f[0] == 0 && res.f[1] == 1 && res.f[2] == 0)

        cout << "0\n";

    else{

        for(int i = 1; res.f.si() - 1 > i; i++){

            if(res.f[i] == 0) cnt += res.s[i];

            if(res.s[i] == 0) break;

        }

        cout << cnt << endl;

    }

}

int main(){

    int t; cin >> t;

    while(t--) solve();

}

// :D


A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8
))((())(
OutputCopy6
InputCopy3
(()
OutputCopy-1
NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds.

#include<bits/stdc++.h>

using namespace std;

#define int long long

const int N=1e6+10;

signed main()

{

    int n;cin>>n;

   string s;cin>>s;

   int a=0,b=0;

   int c=0;

   int res=0;

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

   {

       if(s[i]=='(') a++,c++;

       else

       {

           b++;if(c>0) c--;

       }

       if(a==b)

       {

           if(c)

           res+=2*a;

           a=b=c=0;

       }

   }

   if(a!=b) puts("-1");

   else cout<<res<<"\n";

}


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

#include <bits/stdc++.h>

using namespace std;

const int N = 805;

#define ha putchar(' ')

#define he putchar('\n')

inline int read() {

	int x = 0;

	char c = getchar();

	while (c < '0' || c > '9')

		c = getchar();

	while (c >= '0' && c <= '9')

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

	return x;

}

inline void write(int x) {

	if (x > 9)

		write(x / 10);

	putchar(x % 10 + 48);

}

int n, p[N], id[N], rd[N];

int ask(vector<int> v) {

	putchar('?'), ha, write(v.size());

	for (int x : v) ha, write(x);

	he;

	fflush(stdout);

	return read();

}

int qry(int x) {

	vector<int> v;

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

		if (i != x && !p[i]) v.push_back(i);

	return ask(v);

}

void get(int x, int a, int y, int b) {

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

		if (!p[i] && !id[x] && rd[i] == a) {

			if (qry(i)) id[x] = i;

		} else if (!p[i] && !id[y] && rd[i] == b) {

			if (qry(i)) id[y] = i;

		}

	}

	p[id[x]] = x, p[id[y]] = y;

}

signed main() {

	n = read();

	get(1, 0, n, 0);

	for (int t = 2, l = 2, r = n - 1; l <= r; t <<= 1) {

		for (int i = 1; i <= n; i++) if (!p[i]) {

			vector<int> v;

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

				if (j % t != rd[i]) v.push_back(id[j]);

			v.push_back(i);

			if (ask(v)) rd[i] += t >> 1;

		}

		while (l <= 2 * t && l <= r)

			get(l, l % t, r, r % t), l++, r--;

	}

	if (p[1] > n / 2) for (int i = 1; i <= n; i++)

		p[i] = n - p[i] + 1;

	putchar('!');

	for (int i = 1; i <= n; i++) ha, write(p[i]);

	he;

	fflush(stdout);

	return 0;

}


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

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

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

#include "bits/stdc++.h"

#define F first

#define S second

#define me "| Temirlan |"

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

#define OK  cout << "---------------------------OK-----------------------" << endl;

#define deb(x) cout << #x  << " = " << x << endl;

//#define endl '\n'

#define int long long

using namespace std ;

const int N =  6e5  + 7;

const int INF = 1e9 + 7 ;

const int mod = 1e9 + 7 ;

const double eps = 1e-9 ;

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

int n , m , k , x , a[N] , mx[N] , mn[N]  , p[N] , t[N];

void upd(int v ,int x){

	while(v < N){

		t[v] += x;

		v += v & -v ;

	}

}

int get(int v ){

	int s = 0 ;

	while(v ){

		s += t[v] ;

		v -= v & -v ;

	}

	return s;

}

void test(){

	cin >> n >> m ;

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

		mx[i] = i  ;

		mn[i] = i ;

		p[i] = i + m ;

		upd(p[i] , 1) ;

	}

	for(int i = m  ; i >= 1; i--){

		int x ;

		cin >> x ;

		mn[x] = 1 ;

		mx[x] = max(mx[x] , get(p[x]));

		upd(p[x] , -1 ) ;

		p[x] = i ;

		upd(p[x] , 1) ;

	//	deb(mx[x]) ;

	}

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

		mx[i] = max(mx[i] , get(p[i]) ) ;

	}

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

		cout << mn[i] << " " << mx[i] << endl;

	}

}

signed main(){

    ios_base::sync_with_stdio(false) ;

    cin.tie(0) ;

    cout.tie(0);

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

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

    int t = 1;

	//cin >> t ;

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

    	test() ;

    }

    return 0;

}


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

// LUOGU_RID: 98656651
//A tree without skin will surely die.
//A man without face will be alive
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define mid ((l+r)>>1)
#define sqr(x) ((x)*(x))
#define all(x) (x).begin(),(x).end()
#define Tim ((double)clock()/CLOCKS_PER_SEC)
#define lowbit(x) (x&-x)
int const N=3e5+10;
int a[N],pre,len,vis[6];
map< vector< vector<int> >,int >mp;vector< vector<int> >sg;
inline int mex(int a,int b,int c){
	memset(vis,0,sizeof(vis));vis[a]=vis[b]=vis[c]=1;
	for (int i=0;i<5;++i) if (!vis[i]) return i;
	return 0;
}
inline void add(int x,int y,int z){
	vector<int>tmp(3,0);int l=sg.size();
	tmp[0]=mex(sg[max(l-x,0ll)][0],sg[max(l-y,0ll)][1],sg[max(l-z,0ll)][2]);
	tmp[1]=mex(sg[max(l-x,0ll)][0],sg[max(l-z,0ll)][2],4);
	tmp[2]=mex(sg[max(l-x,0ll)][0],sg[max(l-y,0ll)][1],4);
	sg.push_back(tmp);
}
inline void go(int x,int y,int z){
	sg.clear(),mp.clear();
	sg.push_back({0,0,0});int cnt=0;
	for (int i=1;i<5;++i) add(x,y,z);
	while ("CCF is very good~"){
		vector< vector<int> > tmp(sg.end()-5,sg.end());
		if (mp[tmp]){pre=mp[tmp],len=sg.size()-5-pre;break;}
		mp[tmp]=sg.size()-5;add(x,y,z);
	}
}
inline int getsg(int x){return (x<=pre)?x:(x-pre)%len+pre;}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	int t;cin>>t;
	while (t--){
		int n,x,y,z;cin>>n>>x>>y>>z;
		for (int i=1;i<=n;++i) cin>>a[i];
		go(x,y,z);int sum=0,num[4]={0,0,0,0};
		for (int i=1;i<=n;++i){
			int la=sg[getsg(a[i])][0];
			int X=sg[getsg(max(0ll,a[i]-x))][0];
			int Y=sg[getsg(max(0ll,a[i]-y))][1];
			int Z=sg[getsg(max(0ll,a[i]-z))][2];
			sum^=la;++num[X^la],++num[Y^la],++num[Z^la];
		}
		cout<<num[sum]<<'\n';
	}
	return 0;
}


D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10

#include <bits/stdc++.h>

#include <ext/pb_ds/tree_policy.hpp>

#include <ext/pb_ds/assoc_container.hpp>

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

#define ll long long

#define ld long double

#define el "\n"

#define matrix vector<vector<int>>

#define pt complex<ld>

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

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

using namespace __gnu_pbds;

using namespace std;

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

const ld pi = acos(-1);

const ll mod = 1e9 + 7;

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

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

ll n, m, k, x, y;

void dowork() {

    string a, b;

    cin >> n >> a >> b;

    set<int> sta[30], stb[30];

    n = a.size();

    vector<pair<int, int>> ans;

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

        if (a[i] == '?') {

            sta[26].insert(i + 1);

        } else {

            sta[a[i] - 'a'].insert(i + 1);

        }

    }

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

        if (b[i] == '?') {

            stb[26].insert(i + 1);

        } else {

            stb[b[i] - 'a'].insert(i + 1);

        }

    }

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

        if (sta[i].size() < stb[i].size()) {

            for (auto j: sta[i]) {

                ans.push_back({j, *stb[i].begin()});

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

            }

            sta[i].clear();

        } else {

            for (auto j: stb[i]) {

                ans.push_back({*sta[i].begin(), j});

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

            }

            stb[i].clear();

        }

    }

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

        if (sta[26].size() < stb[i].size()) {

            for (auto j: sta[26]) {

                ans.push_back({j, *stb[i].begin()});

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

            }

            sta[26].clear();

        } else {

            for (auto j: stb[i]) {

                ans.push_back({*sta[26].begin(), j});

                sta[26].erase(sta[26].begin());

            }

            stb[i].clear();

        }

    }

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

        if (sta[i].size() < stb[26].size()) {

            for (auto j: sta[i]) {

                ans.push_back({j, *stb[26].begin()});

                stb[26].erase(stb[26].begin());

            }

            sta[i].clear();

        } else {

            for (auto j: stb[26]) {

                ans.push_back({*sta[i].begin(), j});

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

            }

            stb[26].clear();

        }

    }

    if (sta[26].size() < stb[26].size()) {

        for (auto j: sta[26]) {

            ans.push_back({j, *stb[26].begin()});

            stb[26].erase(stb[26].begin());

        }

        sta[26].clear();

    } else {

        for (auto j: stb[26]) {

            ans.push_back({*sta[26].begin(), j});

            sta[26].erase(sta[26].begin());

        }

        stb[26].clear();

    }

    cout << ans.size() << el;

    for (auto j: ans) {

        cout << j.first << " " << j.second << el;

    }

}

int main() {

    fast

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

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

    int t = 1;

    //cin >> t;

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

        dowork();

    }

}


B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions:  If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss;  If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt;  For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e":  On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105)  — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa
3
1 1
2 4
5 5
OutputCopyYes
No
Yes
InputCopyaabbbbbbc
6
1 2
2 4
2 2
1 9
5 7
3 5
OutputCopyNo
Yes
Yes
Yes
No
No
NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram.

#pragma GCC optimize(2)

#pragma GCC optimize(3,"Ofast","inline")

#include <iostream>

#include <cstring>

#include <algorithm>

#include <string>

#include <cmath>

#include <iomanip>

#include <stdio.h>

#include <cstdio>

#include <ctime>

#include <set>

#include <queue>

#include <map>

#include <stack>

#include <random>

#include <cctype>

#include <unordered_map>

#include <unordered_set>

using namespace std;

#define lg log10

#define re register

#define db double

#define ld long double

#define ll long long

#define ull unsigned long long

#define nth nth_element

#define lb lower_bound

#define ub upper_bound

#define _div stable_partition

#define _merge inplace_merge

#define point(x) setiosflags(ios::fixed)<<setprecision(x)

#define writen(x) write(x),printf("\n")

#define writet(x) write(x),printf(" ")

//const ull MOD = 212370440130137957ll;

const ll MOD = 1e9 + 7;

int test = 1;

//读入输出优化

namespace Fio {

    inline string sread() {

        string s = " "; char e = getchar();

        while (e == ' ' || e == '\n') e = getchar();

        while (e != ' ' && e != '\n') s += e, e = getchar();

        return s;

    }

    inline ll read() {

        ll x = 0, y = 1; char c = getchar();

        while (!isdigit(c)) { if (c == '-') y = -1; c = getchar(); }

        while (isdigit(c)) { x = (x << 3) + (x << 1) + (c ^ 48); c = getchar(); }

        return x *= y;

    }

    inline void write(ll x) {

        if (x < 0)x = -x, putchar('-'); ll sta[35], top = 0;

        do sta[top++] = x % 10, x /= 10; while (x);

        while (top) putchar(sta[--top] + '0');

    }

} using namespace Fio;

const ll modd = 998244353;

const ll inv2 = 499122177;

const ll inv6 = 166374059;

const ld eps = 0.000001;

mt19937 rnd(time(0));

ll q, n, s[26][200005];

inline ll check(ll l, ll r) {

    ll res = 0;

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

        res += (s[i][r] - s[i][l - 1] > 0);

    return res >= 3;

}

inline void qfl_zzz() {

    string a = sread();

    ll n = a.size() - 1;

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

        for (ll j = 0; j < 26; ++j)

            s[j][i] = s[j][i - 1] + (a[i] - 'a' == j);

    q = read();

    while (q--) {

        ll l = read(), r = read();

        if (l == r || a[l] != a[r] || check(l, r)) printf("Yes\n");

        else printf("No\n");

    }

}

inline void pre_work() {

}

int main() {

    ios::sync_with_stdio(false);

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

    srand((unsigned)time(0));

    //test = read();

    //cin >> test;

    pre_work();

    while (test--) qfl_zzz();

    return 0;

}


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

#include<bits/stdc++.h>

using namespace std;

const int inf = 1e9 + 7;

int n, k, r;

vector<int> g[400005];

int anc[19][400005];

int h[400005];

void dfs(int v, int p = -1)

{

	for(int i = 0; i < g[v].size(); i++)

	{

		int to = g[v][i];

		if(to == p)

		{

			continue;

		}

		anc[0][to] = v;

		for(int k = 1; k < 19; k++)

		{

			anc[k][to] = anc[k - 1][anc[k - 1][to]];

		}

		h[to] = h[v] + 1;

		dfs(to, v);

	}

}

int la(int v, int len)

{

	for(int k = 19 - 1; k >= 0; k--)

	{

		if(len & (1 << k))

		{

			v = anc[k][v];

		}

	}

	return v;

}

int lca(int a, int b)

{

	if(h[a] < h[b])

	{

		swap(a, b);

	}

	a = la(a, h[a] - h[b]);

	if(a == b)

	{

		return a;

	}

	for(int k = 19 - 1; k >= 0; k--)

	{

		if(anc[k][a] != anc[k][b])

		{

			a = anc[k][a];

			b = anc[k][b];

		}

	}

	return anc[0][a];

}

int walk(int a, int b, int x)

{

	int c = lca(a, b);

	if(x <= h[a] - h[c])

	{

		return la(a, x);

	}

	int excess = x - (h[a] - h[c]);

	return la(b, h[b] - h[c] - excess);

}

int uf[400005];

int dist[400005];

int find(int a)

{

	while(a != uf[a])

	{

		a = uf[a] = uf[uf[a]];

	}

	return a;

}

bool query(int k)

{

	int a, b;

	cin >> a >> b;

	a--;

	b--;

	int c = lca(a, b);

	if(h[a] + h[b] - 2 * h[c] <= 2 * k)

	{

		return true;

	}

	else

	{

		return find(walk(a, b, k)) == find(walk(b, a, k));

	}

}

signed main()

{

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    cout.tie(NULL);

    cin >> n >> k >> r;

    int N = n;

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

    {

    	int x, y;

    	cin >> x >> y;

    	x--;

    	y--;

    	g[x].push_back(N);

    	g[y].push_back(N);

    	g[N].push_back(x);

    	g[N].push_back(y);

    	N++;

	}

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

	{

		uf[i] = i;

	}

	fill(dist, dist + N, inf);

	queue <int> fron;

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

	{

		int x;

		cin >> x;

		x--;

		dist[x] = 0;

		fron.push(x);

	}

	while(!fron.empty())

	{

		int x = fron.front();

		if(dist[x] > k - 1)

		{

			break;

		}

		fron.pop();

		for(int y = 0; y < g[x].size(); y++)

		{

			uf[find(g[x][y])] = find(x);

			if(dist[g[x][y]] == inf)

			{

				dist[g[x][y]] = dist[x] + 1;

				fron.push(g[x][y]);

			}

		}

	}

	dfs(0);

	int V;

	cin >> V;

	while(V--)

	{

		if(query(k))

		{

			cout << "YES\n";

		}

		else

		{

			cout << "NO\n";

		}

	}

    return 0;

}


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

#include<bits/stdc++.h>

#include<ext/pb_ds/assoc_container.hpp>

#include<ext/pb_ds/tree_policy.hpp>

using namespace std;

using namespace chrono;

using namespace __gnu_pbds;

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

#define MOD 1000000007

#define MOD1 998244353

#define INF 1e18

#define nline "\n"

#define pb push_back

#define ppb pop_back

#define mp make_pair

#define ff first

#define ss second

#define PI 3.141592653589793238462

#define set_bits __builtin_popcountll

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

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

#ifdef tushar23

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

#else

#define debug(x);

#endif

typedef long long ll;

typedef unsigned long long ull;

typedef long double lld;

typedef __int128 ell;

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

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

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

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

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

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

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

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

template <class T, class V> void _print(pair <T, V> p);

template <class T> void _print(vector <T> v);

template <class T> void _print(set <T> v);

template <class T, class V> void _print(map <T, V> v);

template <class T> void _print(multiset <T> v);

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 << "]";}

void _print(pbds v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}

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

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

ll gcd(ll a, ll b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);}

ll expo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;}

void extendgcd(ll a, ll b, ll*v) {if (b == 0) {v[0] = 1; v[1] = 0; v[2] = a; return ;} extendgcd(b, a % b, v); ll x = v[1]; v[1] = v[0] - v[1] * (a / b); v[0] = x; return;} //pass an arry of size1 3

ll mminv(ll a, ll b) {ll arr[3]; extendgcd(a, b, arr); return arr[0];} //for non prime b

ll mminvprime(ll a, ll b) {return expo(a, b - 2, b);}

bool revsort(ll a, ll b) {return a > b;}

ll combination(ll n, ll r, ll m, ll *fact, ll *ifact) {ll val1 = fact[n]; ll val2 = ifact[n - r]; ll val3 = ifact[r]; return (((val1 * val2) % m) * val3) % m;}

void google(int t) {cout << "Case #" << t << ": ";}

vector<ll> sieve(int n) {int*arr = new int[n + 1](); vector<ll> vect; for (int i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (int j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;}

ll mod_add(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;}

ll mod_mul(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;}

ll mod_sub(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;}

ll mod_div(ll a, ll b, ll m) {a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m;}  //only for prime m

ll phin(ll n) {ll number = n; if (n % 2 == 0) {number /= 2; while (n % 2 == 0) n /= 2;} for (ll i = 3; i <= sqrt(n); i += 2) {if (n % i == 0) {while (n % i == 0)n /= i; number = (number / i * (i - 1));}} if (n > 1)number = (number / n * (n - 1)) ; return number;} //O(sqrt(N))

ll getRandomNumber(ll l, ll r) {return uniform_int_distribution<ll>(l, r)(rng);}

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

void solve() {

    ll n;

    cin>>n;

    string s;

    cin>>s;

    ll pre = 0, tochange = 0, ind = 0, ans = 0;

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

      if(s[i] == '(')

        pre++;

      else

        pre--;

      if(pre < 0)

        tochange = 1;

      if(pre == 0){

        if(tochange == 1)

          ans += (i-ind+1);

        ind = i+1;

        tochange = 0;

      }

    }

    if(ind == n)

      cout<<ans<<endl;

    else

      cout<<-1<<endl;

}

int main() {

#ifdef tushar23

    freopen("Error.txt", "w", stderr);

#endif

    fastio();

    auto start1 = high_resolution_clock::now();

    int t = 1;

    while(t--){

        solve();

    }

    auto stop1 = high_resolution_clock::now();

    auto duration = duration_cast<microseconds>(stop1 - start1);

#ifdef tushar23

    cerr << "Time: " << duration . count() / 1000 << endl;

#endif

}


G. Sum of Prefix Sumstime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWe define the sum of prefix sums of an array [s1,s2,…,sk][s1,s2,…,sk] as s1+(s1+s2)+(s1+s2+s3)+⋯+(s1+s2+⋯+sk)s1+(s1+s2)+(s1+s2+s3)+⋯+(s1+s2+⋯+sk).You are given a tree consisting of nn vertices. Each vertex ii has an integer aiai written on it. We define the value of the simple path from vertex uu to vertex vv as follows: consider all vertices appearing on the path from uu to vv, write down all the numbers written on these vertices in the order they appear on the path, and compute the sum of prefix sums of the resulting sequence.Your task is to calculate the maximum value over all paths in the tree.InputThe first line contains one integer nn (2≤n≤1500002≤n≤150000) — the number of vertices in the tree.Then n−1n−1 lines follow, representing the edges of the tree. Each line contains two integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n, ui≠viui≠vi), denoting an edge between vertices uiui and vivi. It is guaranteed that these edges form a tree.The last line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤1061≤ai≤106).OutputPrint one integer — the maximum value over all paths in the tree.ExampleInputCopy4
4 2
3 2
4 1
1 3 3 7
OutputCopy36
NoteThe best path in the first example is from vertex 33 to vertex 11. It gives the sequence [3,3,7,1][3,3,7,1], and the sum of prefix sums is 3636.

// LUOGU_RID: 98578627
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> Pair;
const int N=2e5+5;
#define F first
#define S second
#define ls now<<1
#define rs now<<1|1
int vis[N<<2],tag[N<<2]; Pair tr[N<<2];
int dep[N],used[N],siz[N],a[N]; ll su[N],sd[N],val[N];
int n,tot,rt,mn,u,v,R; ll ans;
vector<int> G[N],vec[N];
inline void pushdown(int now){
if (tag[now]){
tag[ls]=tag[rs]=1;
vis[ls]=vis[rs]=0;
tag[now]=0;
}
}
void update(int now, int l, int r, Pair p){
if (!vis[now]) return tr[now]=p,vis[now]=1,void();
int mid=(l+r)>>1;
if (mid*tr[now].F+tr[now].S<mid*p.F+p.S) swap(tr[now],p);
if (l==r) return;
pushdown(now);
p.F<tr[now].F?update(ls,l,mid,p):update(rs,mid+1,r,p);
}
ll query(int now, int l, int r, int x){
if (!vis[now]) return 0;
ll ret=tr[now].F*x+tr[now].S;
if (l==r) return ret;
int mid=(l+r)>>1; pushdown(now);
return max(ret,mid>=x?query(ls,l,mid,x):query(rs,mid+1,r,x));
}
void Getrt(int u, int f){
siz[u]=1; int mx=0;
for (int v:G[u])
if (v!=f && !used[v]){
Getrt(v,u); siz[u]+=siz[v];
mx=max(mx,siz[v]);
}
mx=max(mx,tot-siz[u]);
if (mx<mn) mn=mx,rt=u;
}
void dfs(int u, int f){
vec[R].push_back(u),siz[u]=1;
dep[u]=dep[f]+1,val[u]=val[f]+a[u];
sd[u]=sd[f]+val[u];
su[u]=su[f]+1ll*dep[f]*a[u];
for (int v:G[u])
if (v!=f && !used[v]) dfs(v,u),siz[u]+=siz[v];
}
inline void Ins(int v, int u){
for (int x:vec[v]) ans=max(ans,max(su[x]+val[x],sd[x]+query(1,1,n,dep[x])));
for (int x:vec[v]) update(1,1,n,{val[x]-a[u],su[x]});
}
void solve(int u){
used[u]=1; dep[u]=1,su[u]=0,val[u]=sd[u]=a[u];
for (int v:G[u])
if (!used[v]){
vec[v].clear(),R=v;
dfs(v,u),Ins(v,u);
}
tag[1]=1,vis[1]=0;
for (int i=G[u].size()-1; ~i; i--)
if (!used[G[u][i]]) Ins(G[u][i],u);
tag[1]=1,vis[1]=0;
for (int v:G[u])
if (!used[v]) tot=siz[v],mn=1e9,Getrt(v,u),solve(rt);
}
int main(){
scanf("%d",&n); tag[1]=1;
for (int i=1; i<n; i++){
scanf("%d%d",&u,&v);
G[u].push_back(v),G[v].push_back(u);
}
for (int i=1; i<=n; i++) scanf("%d",&a[i]);
tot=n,mn=1e9,Getrt(1,0),solve(rt);
printf("%lld\n",ans);
}


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

/* | In The Name Of Allah | */

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace std;

using namespace __gnu_pbds;

template <typename key>

using ordered_set = tree<key, null_type, less<key>, rb_tree_tag, tree_order_statistics_node_update>; // less_equal

/////////////////////////////////////////////////////////////////////////////////////////////////////////

#define LL                              __int128

#define ll                              long long

#define int                             long long

#define ld                              long double

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

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

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

#define MP                              make_pair

#define ceil(n, m)                      (((n) / (m)) + ((n) % (m) ? 1 : 0))

#define rep(i, f, t)                    for (int i = f; i < t; i++)

#define lep(i, f, t)                    for (int i = f; i >= t; i--)

#define cin(vec)                        for (auto &i : vec) cin >> i

#define cin_2d(vec, n, m)               for(int i = 0; i < n; i++) for(int j = 0; j < m && cin >> vec[i][j]; j++);

#define cout(vec)                       for(auto& i : vec) cout << i << " "; cout << "\n";

#define cout_2d(vec, n, m)              for(int i = 0; i < n; i++, cout << "\n") for(int j = 0; j < m && cout << vec[i][j] << " "; j++);

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

#define count1(n)                       __builtin_popcount(n)  // count 1s in Binary number

#define count0(n)                       __builtin_ctz(n)      // trailing 0s in the begin from right

#define countb0(n)                      __builtin_clz(n)     // trailing 0s in the begin from left (LOL)

int setBit(int num, int idx, int val)   { return val ? (num | (1 << idx)) : (num & (~(1 << idx))); }

int getBit(int num, int idx)            { return (((1 << idx) & num) >= 1); }

int addt(int x, int y, int mod)         { return ((x % mod) + (y % mod)) % mod; }

int mult(int x, int y, int mod)         { return ((x % mod) * (y % mod)) % mod; }

int subt(int x, int y, int mod)         { return ((x % mod) - (y % mod) + mod) % mod; }

/////////////////////////////////////////////////////////////////////////////////////////////////////////

const int inf = (int)(1e18);

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

void Test_Case() {

    int n;

    cin >> n;

    string str;

    cin >> str;

    map<pair<int, int>, int> last;

    int ans = inf, l = -1, r = -1, ansl, ansr;

    last[MP(0, 0)] = 0;

    int s = 0, e = 0;

    for (int i = 0; i < str.length(); i++) {

        if (str[i] == 'L') {

            s--;

        } else if (str[i] == 'R') {

            s++;

        } else if (str[i] == 'U') {

            e++;

        } else {

            e--;

        }

        if (last.count(MP(s, e))) {

            l = last[MP(s, e)] + 1;

            r = i + 1;

            last[MP(s, e)] = i + 1;

            if ((r - l + 1) < ans) {

                ans = (r - l + 1);

                ansl = l;

                ansr = r;

            }

        } else {

            last[MP(s, e)] = i + 1;

        }

    }

    if (l == -1) {

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

    } else {

        cout << ansl << ' ' << ansr << '\n';

    }

}

int32_t main()

{

#ifndef ONLINE_JUDGE

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

#endif

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

    cout << fixed << setprecision(3);

    //////////////////////////////////////////////////////

    int tt = 1;

    cin >> tt;

    while (tt--) { Test_Case(); }

    return 0;

}


E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9
abacbecfd
OutputCopyYES
001010101
InputCopy8
aaabbcbb
OutputCopyYES
01011011
InputCopy7
abcdedc
OutputCopyNO
InputCopy5
abcde
OutputCopyYES
00000

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

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

#define pb push_back

#define int long long

#define pop pop_back

#define v_i vector <int>

#define f1 first

#define s2 second

#define vp vector<pair <int, int>>

using namespace std;

using namespace __gnu_pbds;

typedef long long lli;

typedef tree<int, null_type, less_equal<int>, rb_tree_tag,tree_order_statistics_node_update> ordered_set;

long long binpow(long long a, long long b)

{

    if(b==0) return 1;

    long long res = binpow(a, b/2);

    if(b%2==0) return res*res;

    else return res*res*a;

}

void solve()

{

    int n; cin>>n;

    string s; cin>>s;

    vector <int> v;

    for(int i=0;i<n;i++) v.pb(0);

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

        set <int> se;

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

            if(s[i]<s[j]){

                se.insert(v[j]);

            }

        }

        if(se.size()==1) {v[i]=!(*se.begin());}

        if(se.size()==2) {cout<<"NO"<<endl; return;}

    }

    cout<<"YES"<<endl;

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

    cout<<endl;

}

signed main () {

    ios::sync_with_stdio(0);

    cin.tie(0);

    int tt;

    tt=1;

    //cin>>tt;

    while(tt--)

    {

        solve();

    }

}


F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105)  — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012)  — the elements of the array.OutputPrint a single integer  — the minimum number of operations required to make the array good.ExamplesInputCopy3
6 2 4
OutputCopy0
InputCopy5
9 8 7 3 1
OutputCopy4
NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations:  Add 11 to the second element, making it equal to 99.  Subtract 11 from the third element, making it equal to 66.  Add 11 to the fifth element, making it equal to 22.  Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int N = 2e5 + 5;

const int M = 1e6 + 5;

int n, prime[M], tot;

ll a[N];

mt19937_64 rnd(19260817);

bool vis[M];

inline void Euler()

{

    for (int i = 2; i <= M - 5; i++)

    {

        if (!vis[i])

            prime[++tot] = i;

        for (int j = 1; j <= tot && 1ll * i * prime[j] <= M - 5; j++)

        {

            vis[i * prime[j]] = true;

            if (!(i % prime[j]))

                break;

        }

    }

}

set<ll> s;

inline void solve(ll x)

{

    for (int i = 1; i <= tot && x > 1; i++)

        if (!(x % prime[i]))

        {

            s.insert(prime[i]);

            while (!(x % prime[i]))

                x /= prime[i];

        }

    if (x > 1)

        s.insert(x);

}

int main()

{

    ios::sync_with_stdio(false);

    cin.tie(nullptr);

    Euler();

    cin >> n;

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

        cin >> a[i];

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

    {

        int x = rnd() % n + 1;

        if (a[x] > 2)

            solve(a[x] - 1);

        solve(a[x]), solve(a[x] + 1);

    }

    ll ans = n;

    for (ll x : s)

    {

        ll cur = 0;

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

            cur += a[i] < x ? x - a[i] : min(a[i] % x, x - a[i] % x);

        ans = min(ans, cur);

    }

    cout << ans;

    return 0;

}


B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)).  Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0).

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

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

int T;
int n,m,k;
int w[N];

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

    int maxn=1;
    bool flag=false;
    for(int i=1;i<=n;i++) {
        w[i]=read();maxn=max(maxn,w[i]);
        if(w[i]==m) flag=true;
    }

    int l=0,r=1e9;
    while(l<r) {
        int mid=l+r>>1;
        if((ll)mid*maxn>=m) r=mid;
        else l=mid+1;
    }

    if(flag) printf("1\n");
    else if(((ll)l*maxn==m)||((ll)l*maxn>m&&l!=1)) printf("%d\n",l);
    else printf("%d\n",l+1);
}

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

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

    return 0;
}


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

#include <bits/stdc++.h>

#define int ll

#define ff first

#define ss second

#define zort sort

#define endl '\n'

#define pb push_back

#define IMAX INT64_MAX

#define N 200005

#define MOD 1000000007

#define MOD2 998244353

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

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

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

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

#define cendl cout<<endl

#define rset srand(int(time(NULL)));

#define dpset memset(dp,-1,sizeof(dp))

#define isint(x) ceil(x)==floor(x)

#define acm(x) accumulate(all(v),0)

#define sumroot(i) double(1/2)*double((double)sqrt(8*i+1)-1)

#define ssum(x) x*(x+1)/2

#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);cout<<setprecision(10);

#define allset fast;rset;dpset

using namespace std;

typedef long long ll;

typedef long double ldouble;

typedef string str;

typedef pair<int,int> ii;

typedef pair<ii,int> iii;

typedef vector<int> vi;

typedef vector<char> vc;

typedef vector<pair<char,int>> vci;

typedef vector<ii> vii;

typedef vector<iii> viii;

typedef vector<vi> vvi;

typedef map<int,int> mii;

typedef map<char,int> mci;

typedef map<double,int> mdi;

typedef map<string,int> msi;

typedef map<int,str> mis;

/*

g++ -Wall -g C:\Users\teoat\OneDrive\Belgeler\temp.cpp -o C:\Users\teoat\OneDrive\Belgeler\a.exe

*/

int n,res;

priority_queue<int> pq;

main()

{

    cin >> n;

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

    {

        int x; cin >> x;

        if(!pq.empty() && pq.top() > x)

        {

            res += pq.top() - x;

            pq.pop();

            pq.push(x);

        }

        pq.push(x);

    }

    cout << res;

      return 0;

}


B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.

#include <bits/stdc++.h>

#define ll long long

using namespace std;

int main(){

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

    int tt = 1;

    //cin >> tt;

    while(tt--){

        int n;

        cin >> n;

        vector<int> a(n);

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

            cin >> a[i];

        }

        int mx = 0;

        int current_length = 0;

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

            if(a[i % n] == 0){

                mx = max(mx, current_length);

                current_length = 0;

            }else{

                current_length++;

            }

        }

        cout << mx << '\n';

    }

    return 0;

}


C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33:  [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66.  [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32.

// LUOGU_RID: 102244174
#include<bits/stdc++.h>
using namespace std;
const int N=3e5;
int n,p,fac[N],ans;
int main()
{
    scanf("%d%d",&n,&p);
    fac[0]=1;
    for(int i=1;i<=n;i++)fac[i]=1ll*fac[i-1]*i%p;
    for(int i=1;i<=n;i++)ans=(ans+1ll*fac[i]%p*fac[n-i+1]%p*(n-i+1)%p)%p;
    printf("%d",ans);
}


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

#include <iostream>

using namespace std;

int maxx(int a , int b)

{

     if (a>=b)

     return a ;

    else

    return b ;

}

int main()

{

   int t ,a , b , c , n , max;

   long long x ;

   cin >> t ;

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

   {

       cin >> a >>b >> c >> n ;

       max=maxx(c, maxx(a, b));

       x= (max-a) + (max-b) + (max-c) ;

       if (n>=x && (n-x)%3==0)

       cout << "YES" ;

       else

       cout << "NO" ;

       cout << endl ;

   }

    return 0;

}


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

#include <bits/stdc++.h>

#define mod 998244353

#define int long long

using namespace std;

int ksm(int x,int y)

{

	int rtn=1;

	while(y)

	{

		if(y&1) rtn=rtn*x%mod;

		x=x*x%mod,y>>=1;

	}

	return rtn;

}

int inv(int x)

{

	return ksm(x,mod-2);

}

int l[55],r[55];

//int dp[55][100005];

int X[55][55];

const int inf=mod-1;

struct poly

{

	vector<int> v;

	void qzh()

	{

		vector<int> rtn;

		rtn.resize(v.size()+1);

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

		{

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

				rtn[j]=(rtn[j]+v[i]*X[i][j])%mod;

		}

		swap(v,rtn);

	}

	int cal(int x)

	{

		int rtn=0;

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

			rtn=(rtn*x+v[i])%mod;

		return rtn;

	}

};

struct qujian

{

	int l,r;

	poly f;

};

vector<qujian> dp[55];

void print(vector<qujian> x)

{

	for(auto t:x)

	{

		cout << t.l << "," << t.r << ":\n";

		int c=0;

		for(auto x:t.f.v) cout << x << "x^" << (c++) << "+";

		cout << "\n";

	}

	cout << "\n\n";

}

signed main()

{

	ios::sync_with_stdio(false);

	cin.tie(0);

	int n;

	cin >> n;

	int tot=1;

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

	{

		cin >> l[i] >> r[i];

		++l[i],++r[i];

		tot=(tot*(r[i]-l[i]+1))%mod;

	}

	l[n+1]=0,r[n+1]=inf;

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

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

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

	{

		int x[60]={},y[60]={};

		for(int i=0;i<=k+2;i++)

			x[i]=i+1,y[i]=((i?y[i-1]:0)+ksm(x[i],k))%mod;

		int b[60][60]={};

		for(int i=0;i<=k+2;i++)

		{

			for(int j=0;j<=k+2;j++) b[i][j]=ksm(x[i],j);

			b[i][k+3]=y[i];

		}

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

		{

			int X=inv(b[x][x]);

			for(int y=0;y<=k+3;y++) b[x][y]=(b[x][y]*X)%mod;

			for(int y=0;y<=k+2;y++)

			{

				if(x==y) continue;

				int t=b[y][x];

				for(int z=0;z<=k+3;z++) b[y][z]=(b[y][z]-b[x][z]*t)%mod;

			}

		}

		for(int x=0;x<=k+2;x++) X[k][x]=(b[x][k+3]%mod+mod)%mod;

	}

/*	dp[0][0]=1;

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

	{

		for(int j=0;j<=r[i];j++) dp[i][j]=dp[i-1][j];

		for(int j=0;j<=r[i];j++) dp[i][j]=(dp[i][j]+dp[i][j-1])%mod;

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

	}*/

	dp[0].push_back({0,0,{{1}}});

	dp[0].push_back({1,inf,{{0}}});

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

	{

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

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

		{

			dp[i][j].f.qzh();

			int lst=0;

			if(j) lst=dp[i][j-1].f.cal(dp[i][j].l-1);

			int nw=dp[i][j].f.cal(dp[i][j].l-1);

			dp[i][j].f.v[0]+=lst-nw;

		}

		while(dp[i].back().l>r[i]) dp[i].pop_back();

		dp[i].back().r=r[i];

		if(r[i]!=inf) dp[i].push_back({r[i]+1,inf,{{0}}});

		while(dp[i][0].r<l[i]) dp[i].erase(dp[i].begin());

		dp[i][0].l=l[i];

		if(l[i]>0) dp[i].insert(dp[i].begin(),{0,l[i]-1,{{0}}});

	}

/*	print(dp[0]);

	print(dp[1]);

	print(dp[2]);

	print(dp[3]);

	print(dp[4]);*/

//	int ans=0;

//	cout << dp[n+1][inf]*inv(tot)%mod;

	cout << (dp[n+1].back().f.cal(inf)*inv(tot)%mod+mod)%mod;

	return 0;

}


#line 1 "library/my_template.hpp"

#if defined(LOCAL)

#include <my_template_compiled.hpp>

#else

#pragma GCC optimize("Ofast")

#pragma GCC optimize("unroll-loops")

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

using pi = pair<ll, ll>;

using vi = vector<ll>;

using u32 = unsigned int;

using u64 = unsigned long long;

using i128 = __int128;

template <class T>

using vc = vector<T>;

template <class T>

using vvc = vector<vc<T>>;

template <class T>

using vvvc = vector<vvc<T>>;

template <class T>

using vvvvc = vector<vvvc<T>>;

template <class T>

using vvvvvc = vector<vvvvc<T>>;

template <class T>

using pq = priority_queue<T>;

template <class T>

using pqg = priority_queue<T, vector<T>, greater<T>>;

#define vec(type, name, ...) vector<type> name(__VA_ARGS__)

#define vv(type, name, h, ...) \

  vector<vector<type>> name(h, vector<type>(__VA_ARGS__))

#define vvv(type, name, h, w, ...)   \

  vector<vector<vector<type>>> name( \

      h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))

#define vvvv(type, name, a, b, c, ...)       \

  vector<vector<vector<vector<type>>>> name( \

      a, vector<vector<vector<type>>>(       \

             b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))

// https://trap.jp/post/1224/

#define FOR1(a) for (ll _ = 0; _ < ll(a); ++_)

#define FOR2(i, a) for (ll i = 0; i < ll(a); ++i)

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

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

#define FOR1_R(a) for (ll i = (a)-1; i >= ll(0); --i)

#define FOR2_R(i, a) for (ll i = (a)-1; i >= ll(0); --i)

#define FOR3_R(i, a, b) for (ll i = (b)-1; i >= ll(a); --i)

#define FOR4_R(i, a, b, c) for (ll i = (b)-1; i >= ll(a); i -= (c))

#define overload4(a, b, c, d, e, ...) e

#define FOR(...) overload4(__VA_ARGS__, FOR4, FOR3, FOR2, FOR1)(__VA_ARGS__)

#define FOR_R(...) \

  overload4(__VA_ARGS__, FOR4_R, FOR3_R, FOR2_R, FOR1_R)(__VA_ARGS__)

#define FOR_subset(t, s) for (ll t = s; t >= 0; t = (t == 0 ? -1 : (t - 1) & s))

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

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

#define elif else if

#define eb emplace_back

#define mp make_pair

#define mt make_tuple

#define fi first

#define se second

#define stoi stoll

template <typename T, typename U>

T SUM(const vector<U> &A) {

  T sum = 0;

  for (auto &&a: A) sum += a;

  return sum;

}

#define MIN(v) *min_element(all(v))

#define MAX(v) *max_element(all(v))

#define LB(c, x) distance((c).begin(), lower_bound(all(c), (x)))

#define UB(c, x) distance((c).begin(), upper_bound(all(c), (x)))

#define UNIQUE(x) \

  sort(all(x)), x.erase(unique(all(x)), x.end()), x.shrink_to_fit()

int popcnt(int x) { return __builtin_popcount(x); }

int popcnt(u32 x) { return __builtin_popcount(x); }

int popcnt(ll x) { return __builtin_popcountll(x); }

int popcnt(u64 x) { return __builtin_popcountll(x); }

// (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2)

int topbit(int x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }

int topbit(u32 x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }

int topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }

int topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }

// (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2)

int lowbit(int x) { return (x == 0 ? -1 : __builtin_ctz(x)); }

int lowbit(u32 x) { return (x == 0 ? -1 : __builtin_ctz(x)); }

int lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }

int lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }

template <typename T>

T pick(deque<T> &que) {

  T a = que.front();

  que.pop_front();

  return a;

}

template <typename T>

T pick(pq<T> &que) {

  T a = que.top();

  que.pop();

  return a;

}

template <typename T>

T pick(pqg<T> &que) {

  assert(que.size());

  T a = que.top();

  que.pop();

  return a;

}

template <typename T>

T pick(vc<T> &que) {

  assert(que.size());

  T a = que.back();

  que.pop_back();

  return a;

}

template <typename T, typename U>

T ceil(T x, U y) {

  return (x > 0 ? (x + y - 1) / y : x / y);

}

template <typename T, typename U>

T floor(T x, U y) {

  return (x > 0 ? x / y : (x - y + 1) / y);

}

template <typename T, typename U>

pair<T, T> divmod(T x, U y) {

  T q = floor(x, y);

  return {q, x - q * y};

}

template <typename F>

ll binary_search(F check, ll ok, ll ng) {

  assert(check(ok));

  while (abs(ok - ng) > 1) {

    auto x = (ng + ok) / 2;

    tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x));

  }

  return ok;

}

template <typename F>

double binary_search_real(F check, double ok, double ng, int iter = 100) {

  FOR(iter) {

    double x = (ok + ng) / 2;

    tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x));

  }

  return (ok + ng) / 2;

}

template <class T, class S>

inline bool chmax(T &a, const S &b) {

  return (a < b ? a = b, 1 : 0);

}

template <class T, class S>

inline bool chmin(T &a, const S &b) {

  return (a > b ? a = b, 1 : 0);

}

vc<int> s_to_vi(const string &S, char first_char) {

  vc<int> A(S.size());

  FOR(i, S.size()) { A[i] = S[i] - first_char; }

  return A;

}

template <typename T, typename U>

vector<T> cumsum(vector<U> &A, int off = 1) {

  int N = A.size();

  vector<T> B(N + 1);

  FOR(i, N) { B[i + 1] = B[i] + A[i]; }

  if (off == 0) B.erase(B.begin());

  return B;

}

template <typename CNT, typename T>

vc<CNT> bincount(const vc<T> &A, int size) {

  vc<CNT> C(size);

  for (auto &&x: A) { ++C[x]; }

  return C;

}

// stable

template <typename T>

vector<int> argsort(const vector<T> &A) {

  vector<int> ids(A.size());

  iota(all(ids), 0);

  sort(all(ids),

       [&](int i, int j) { return A[i] < A[j] || (A[i] == A[j] && i < j); });

  return ids;

}

// A[I[0]], A[I[1]], ...

template <typename T>

vc<T> rearrange(const vc<T> &A, const vc<int> &I) {

  int n = len(I);

  vc<T> B(n);

  FOR(i, n) B[i] = A[I[i]];

  return B;

}

#endif

#line 1 "library/other/io.hpp"

// based on yosupo's fastio

#include <unistd.h>

namespace fastio {

// クラスが read(), print() を持っているかを判定するメタ関数

struct has_write_impl {

  template <class T>

  static auto check(T &&x) -> decltype(x.write(), std::true_type{});

  template <class T>

  static auto check(...) -> std::false_type;

};

template <class T>

class has_write : public decltype(has_write_impl::check<T>(std::declval<T>())) {

};

struct has_read_impl {

  template <class T>

  static auto check(T &&x) -> decltype(x.read(), std::true_type{});

  template <class T>

  static auto check(...) -> std::false_type;

};

template <class T>

class has_read : public decltype(has_read_impl::check<T>(std::declval<T>())) {};

struct Scanner {

  FILE *fp;

  char line[(1 << 15) + 1];

  size_t st = 0, ed = 0;

  void reread() {

    memmove(line, line + st, ed - st);

    ed -= st;

    st = 0;

    ed += fread(line + ed, 1, (1 << 15) - ed, fp);

    line[ed] = '\0';

  }

  bool succ() {

    while (true) {

      if (st == ed) {

        reread();

        if (st == ed) return false;

      }

      while (st != ed && isspace(line[st])) st++;

      if (st != ed) break;

    }

    if (ed - st <= 50) {

      bool sep = false;

      for (size_t i = st; i < ed; i++) {

        if (isspace(line[i])) {

          sep = true;

          break;

        }

      }

      if (!sep) reread();

    }

    return true;

  }

  template <class T, enable_if_t<is_same<T, string>::value, int> = 0>

  bool read_single(T &ref) {

    if (!succ()) return false;

    while (true) {

      size_t sz = 0;

      while (st + sz < ed && !isspace(line[st + sz])) sz++;

      ref.append(line + st, sz);

      st += sz;

      if (!sz || st != ed) break;

      reread();

    }

    return true;

  }

  template <class T, enable_if_t<is_integral<T>::value, int> = 0>

  bool read_single(T &ref) {

    if (!succ()) return false;

    bool neg = false;

    if (line[st] == '-') {

      neg = true;

      st++;

    }

    ref = T(0);

    while (isdigit(line[st])) { ref = 10 * ref + (line[st++] & 0xf); }

    if (neg) ref = -ref;

    return true;

  }

  template <typename T,

            typename enable_if<has_read<T>::value>::type * = nullptr>

  inline bool read_single(T &x) {

    x.read();

    return true;

  }

  bool read_single(double &ref) {

    string s;

    if (!read_single(s)) return false;

    ref = std::stod(s);

    return true;

  }

  bool read_single(char &ref) {

    string s;

    if (!read_single(s) || s.size() != 1) return false;

    ref = s[0];

    return true;

  }

  template <class T>

  bool read_single(vector<T> &ref) {

    for (auto &d: ref) {

      if (!read_single(d)) return false;

    }

    return true;

  }

  template <class T, class U>

  bool read_single(pair<T, U> &p) {

    return (read_single(p.first) && read_single(p.second));

  }

  template <size_t N = 0, typename T>

  void read_single_tuple(T &t) {

    if constexpr (N < std::tuple_size<T>::value) {

      auto &x = std::get<N>(t);

      read_single(x);

      read_single_tuple<N + 1>(t);

    }

  }

  template <class... T>

  bool read_single(tuple<T...> &tpl) {

    read_single_tuple(tpl);

    return true;

  }

  void read() {}

  template <class H, class... T>

  void read(H &h, T &... t) {

    bool f = read_single(h);

    assert(f);

    read(t...);

  }

  Scanner(FILE *fp) : fp(fp) {}

};

struct Printer {

  Printer(FILE *_fp) : fp(_fp) {}

  ~Printer() { flush(); }

  static constexpr size_t SIZE = 1 << 15;

  FILE *fp;

  char line[SIZE], small[50];

  size_t pos = 0;

  void flush() {

    fwrite(line, 1, pos, fp);

    pos = 0;

  }

  void write(const char val) {

    if (pos == SIZE) flush();

    line[pos++] = val;

  }

  template <class T, enable_if_t<is_integral<T>::value, int> = 0>

  void write(T val) {

    if (pos > (1 << 15) - 50) flush();

    if (val == 0) {

      write('0');

      return;

    }

    if (val < 0) {

      write('-');

      val = -val; // todo min

    }

    size_t len = 0;

    while (val) {

      small[len++] = char(0x30 | (val % 10));

      val /= 10;

    }

    for (size_t i = 0; i < len; i++) { line[pos + i] = small[len - 1 - i]; }

    pos += len;

  }

  void write(const string s) {

    for (char c: s) write(c);

  }

  void write(const char *s) {

    size_t len = strlen(s);

    for (size_t i = 0; i < len; i++) write(s[i]);

  }

  void write(const double x) {

    ostringstream oss;

    oss << fixed << setprecision(15) << x;

    string s = oss.str();

    write(s);

  }

  void write(const long double x) {

    ostringstream oss;

    oss << fixed << setprecision(15) << x;

    string s = oss.str();

    write(s);

  }

  template <typename T,

            typename enable_if<has_write<T>::value>::type * = nullptr>

  inline void write(T x) {

    x.write();

  }

  template <class T>

  void write(const vector<T> val) {

    auto n = val.size();

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

      if (i) write(' ');

      write(val[i]);

    }

  }

  template <class T, class U>

  void write(const pair<T, U> val) {

    write(val.first);

    write(' ');

    write(val.second);

  }

  template <size_t N = 0, typename T>

  void write_tuple(const T t) {

    if constexpr (N < std::tuple_size<T>::value) {

      if constexpr (N > 0) { write(' '); }

      const auto x = std::get<N>(t);

      write(x);

      write_tuple<N + 1>(t);

    }

  }

  template <class... T>

  bool write(tuple<T...> tpl) {

    write_tuple(tpl);

    return true;

  }

  template <class T, size_t S>

  void write(const array<T, S> val) {

    auto n = val.size();

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

      if (i) write(' ');

      write(val[i]);

    }

  }

  void write(i128 val) {

    string s;

    bool negative = 0;

    if (val < 0) {

      negative = 1;

      val = -val;

    }

    while (val) {

      s += '0' + int(val % 10);

      val /= 10;

    }

    if (negative) s += "-";

    reverse(all(s));

    if (len(s) == 0) s = "0";

    write(s);

  }

};

Scanner scanner = Scanner(stdin);

Printer printer = Printer(stdout);

void flush() { printer.flush(); }

void print() { printer.write('\n'); }

template <class Head, class... Tail>

void print(Head &&head, Tail &&... tail) {

  printer.write(head);

  if (sizeof...(Tail)) printer.write(' ');

  print(forward<Tail>(tail)...);

}

void read() {}

template <class Head, class... Tail>

void read(Head &head, Tail &... tail) {

  scanner.read(head);

  read(tail...);

}

} // namespace fastio

using fastio::print;

using fastio::flush;

using fastio::read;

#define INT(...)   \

  int __VA_ARGS__; \

  read(__VA_ARGS__)

#define LL(...)   \

  ll __VA_ARGS__; \

  read(__VA_ARGS__)

#define STR(...)      \

  string __VA_ARGS__; \

  read(__VA_ARGS__)

#define CHAR(...)   \

  char __VA_ARGS__; \

  read(__VA_ARGS__)

#define DBL(...)      \

  double __VA_ARGS__; \

  read(__VA_ARGS__)

#define VEC(type, name, size) \

  vector<type> name(size);    \

  read(name)

#define VV(type, name, h, w)                     \

  vector<vector<type>> name(h, vector<type>(w)); \

  read(name)

void YES(bool t = 1) { print(t ? "YES" : "NO"); }

void NO(bool t = 1) { YES(!t); }

void Yes(bool t = 1) { print(t ? "Yes" : "No"); }

void No(bool t = 1) { Yes(!t); }

void yes(bool t = 1) { print(t ? "yes" : "no"); }

void no(bool t = 1) { yes(!t); }

#line 2 "library/graph/base.hpp"

template <typename T>

struct Edge {

  int frm, to;

  T cost;

  int id;

};

template <typename T = int, bool directed = false>

struct Graph {

  int N, M;

  using cost_type = T;

  using edge_type = Edge<T>;

  vector<edge_type> edges;

  vector<int> indptr;

  vector<edge_type> csr_edges;

  vc<int> vc_deg, vc_indeg, vc_outdeg;

  bool prepared;

  class OutgoingEdges {

  public:

    OutgoingEdges(const Graph* G, int l, int r) : G(G), l(l), r(r) {}

    const edge_type* begin() const {

      if (l == r) { return 0; }

      return &G->csr_edges[l];

    }

    const edge_type* end() const {

      if (l == r) { return 0; }

      return &G->csr_edges[r];

    }

  private:

    const Graph* G;

    int l, r;

  };

  bool is_prepared() { return prepared; }

  constexpr bool is_directed() { return directed; }

  Graph() : N(0), M(0), prepared(0) {}

  Graph(int N) : N(N), M(0), prepared(0) {}

  void resize(int n) { N = n; }

  void add(int frm, int to, T cost = 1, int i = -1) {

    assert(!prepared);

    assert(0 <= frm && 0 <= to && to < N);

    if (i == -1) i = M;

    auto e = edge_type({frm, to, cost, i});

    edges.eb(e);

    ++M;

  }

  // wt, off

  void read_tree(bool wt = false, int off = 1) { read_graph(N - 1, wt, off); }

  void read_graph(int M, bool wt = false, int off = 1) {

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

      INT(a, b);

      a -= off, b -= off;

      if (!wt) {

        add(a, b);

      } else {

        T c;

        read(c);

        add(a, b, c);

      }

    }

    build();

  }

  void read_parent(int off = 1) {

    for (int v = 1; v < N; ++v) {

      INT(p);

      p -= off;

      add(p, v);

    }

    build();

  }

  void build() {

    assert(!prepared);

    prepared = true;

    indptr.assign(N + 1, 0);

    for (auto&& e: edges) {

      indptr[e.frm + 1]++;

      if (!directed) indptr[e.to + 1]++;

    }

    for (int v = 0; v < N; ++v) { indptr[v + 1] += indptr[v]; }

    auto counter = indptr;

    csr_edges.resize(indptr.back() + 1);

    for (auto&& e: edges) {

      csr_edges[counter[e.frm]++] = e;

      if (!directed)

        csr_edges[counter[e.to]++] = edge_type({e.to, e.frm, e.cost, e.id});

    }

  }

  OutgoingEdges operator[](int v) const {

    assert(prepared);

    return {this, indptr[v], indptr[v + 1]};

  }

  vc<int> deg_array() {

    if (vc_deg.empty()) calc_deg();

    return vc_deg;

  }

  pair<vc<int>, vc<int>> deg_array_inout() {

    if (vc_indeg.empty()) calc_deg_inout();

    return {vc_indeg, vc_outdeg};

  }

  int deg(int v) {

    if (vc_deg.empty()) calc_deg();

    return vc_deg[v];

  }

  int in_deg(int v) {

    if (vc_indeg.empty()) calc_deg_inout();

    return vc_indeg[v];

  }

  int out_deg(int v) {

    if (vc_outdeg.empty()) calc_deg_inout();

    return vc_outdeg[v];

  }

  void debug() {

    print("Graph");

    if (!prepared) {

      print("frm to cost id");

      for (auto&& e: edges) print(e.frm, e.to, e.cost, e.id);

    } else {

      print("indptr", indptr);

      print("frm to cost id");

      FOR(v, N) for (auto&& e: (*this)[v]) print(e.frm, e.to, e.cost, e.id);

    }

  }

private:

  void calc_deg() {

    assert(vc_deg.empty());

    vc_deg.resize(N);

    for (auto&& e: edges) vc_deg[e.frm]++, vc_deg[e.to]++;

  }

  void calc_deg_inout() {

    assert(vc_indeg.empty());

    vc_indeg.resize(N);

    vc_outdeg.resize(N);

    for (auto&& e: edges) { vc_indeg[e.to]++, vc_outdeg[e.frm]++; }

  }

};

#line 2 "library/graph/centroid.hpp"

template <typename GT>

vc<int> find_centroids(GT& G) {

  int N = G.N;

  vc<int> par(N, -1);

  vc<int> V(N);

  vc<int> sz(N);

  int l = 0, r = 0;

  V[r++] = 0;

  while (l < r) {

    int v = V[l++];

    for (auto&& e: G[v])

      if (e.to != par[v]) {

        par[e.to] = v;

        V[r++] = e.to;

      }

  }

  FOR_R(i, N) {

    int v = V[i];

    sz[v] += 1;

    int p = par[v];

    if (p != -1) sz[p] += sz[v];

  }

  int M = N / 2;

  auto check = [&](int v) -> bool {

    if (N - sz[v] > M) return false;

    for (auto&& e: G[v]) {

      if (e.to != par[v] && sz[e.to] > M) return false;

    }

    return true;

  };

  vc<int> ANS;

  FOR(v, N) if (check(v)) ANS.eb(v);

  return ANS;

}

template <typename GT>

struct Centroid_Decomposition {

  using edge_type = typename GT::edge_type;

  GT& G;

  int N;

  vc<int> sz;

  vc<int> par;

  vector<int> cdep; // depth in centroid tree

  bool calculated;

  Centroid_Decomposition(GT& G)

      : G(G), N(G.N), sz(G.N), par(G.N), cdep(G.N, -1) {

    calculated = 0;

    build();

  }

private:

  int find(int v) {

    vc<int> V = {v};

    par[v] = -1;

    int p = 0;

    while (p < len(V)) {

      int v = V[p++];

      sz[v] = 0;

      for (auto&& e: G[v]) {

        if (e.to == par[v] || cdep[e.to] != -1) continue;

        par[e.to] = v;

        V.eb(e.to);

      }

    }

    while (len(V)) {

      int v = V.back();

      V.pop_back();

      sz[v] += 1;

      if (p - sz[v] <= p / 2) return v;

      sz[par[v]] += sz[v];

    }

    return -1;

  }

  void build() {

    assert(G.is_prepared());

    assert(!G.is_directed());

    assert(!calculated);

    calculated = 1;

    vc<pair<int, int>> st;

    st.eb(0, 0);

    while (!st.empty()) {

      auto [lv, v] = st.back();

      st.pop_back();

      auto c = find(v);

      cdep[c] = lv;

      for (auto&& e: G[c]) {

        if (cdep[e.to] == -1) { st.eb(lv + 1, e.to); }

      }

    }

  }

public:

  /*

  root を重心とする木において、(v, path data v) の vector

  を、方向ごとに集めて返す ・0 番目：root からのパスすべて（root を含む）

  ・i番目：i 番目の方向

  f: E x edge -> E

  */

  template <typename E, typename F>

  vc<vc<pair<int, E>>> collect(int root, E root_val, F f) {

    vc<vc<pair<int, E>>> res = {{{root, root_val}}};

    for (auto&& e: G[root]) {

      int nxt = e.to;

      if (cdep[nxt] < cdep[root]) continue;

      vc<pair<int, E>> dat;

      int p = 0;

      dat.eb(nxt, f(root_val, e));

      par[nxt] = root;

      while (p < len(dat)) {

        auto [v, val] = dat[p++];

        for (auto&& e: G[v]) {

          if (e.to == par[v]) continue;

          if (cdep[e.to] < cdep[root]) continue;

          par[e.to] = v;

          dat.eb(e.to, f(val, e));

        }

      }

      res.eb(dat);

      res[0].insert(res[0].end(), all(dat));

    }

    return res;

  }

  vc<vc<pair<int, int>>> collect_dist(int root) {

    auto f = [&](int x, auto e) -> int { return x + 1; };

    return collect(root, 0, f);

  }

  // (V, H), V[i] は、H における頂点 i の G における番号

  // 頂点は EulerTour 順に並ぶ

  pair<vc<int>, Graph<typename GT::cost_type, true>> get_subgraph(int root) {

    static vc<int> conv;

    while (len(conv) < N) conv.eb(-1);

    vc<int> V;

    using cost_type = typename GT::cost_type;

    vc<tuple<int, int, cost_type>> edges;

    auto dfs = [&](auto& dfs, int v, int p) -> void {

      conv[v] = len(V);

      V.eb(v);

      for (auto&& e: G[v]) {

        int to = e.to;

        if (to == p) continue;

        if (cdep[to] < cdep[root]) continue;

        dfs(dfs, to, v);

        edges.eb(conv[v], conv[to], e.cost);

      }

    };

    dfs(dfs, root, -1);

    int n = len(V);

    Graph<typename GT::cost_type, true> H(n);

    for (auto&& [a, b, c]: edges) H.add(a, b, c);

    H.build();

    for (auto&& v: V) conv[v] = -1;

    return {V, H};

  }

};

#line 2 "library/convex/lichao.hpp"

template <typename T>

struct LiChaoTree {

  struct Line {

    T a, b;

    Line(T a, T b) : a(a), b(b) {}

    inline T eval(T x) const { return a * x + b; }

    inline bool over(const Line &other, const T &x) const {

      return eval(x) < other.eval(x);

    }

  };

  vector<T> xs;

  vector<Line> seg;

  int size;

  const T INF;

  // コンストラクタ。クエリの来る x 全体を渡す。ソート不要。

  LiChaoTree(const vector<T> &_xs, T INF = numeric_limits<T>::max() / 2)

      : xs(_xs), INF(INF) {

    if (len(xs) == 0) xs.eb(0);

    UNIQUE(xs);

    size = 1;

    while (size < len(xs)) size *= 2;

    while (len(xs) < size) xs.eb(xs.back());

    seg.assign(2 * size, Line(0, INF));

  }

  // y = ax + bなる直線を追加

  void add(T a, T b) { inner_update(a, b, 0, size, 1); }

  // [lx, rx) に線分 y = ax + b を追加

  void add(T lx, T rx, T a, T b) {

    int l = LB(xs, lx) + size;

    int r = LB(xs, rx) + size;

    while (l < r) {

      if (l & 1) inner_update(a, b, l++);

      if (r & 1) inner_update(a, b, --r);

      l >>= 1, r >>= 1;

    }

  }

  T get_min(T x) {

    int i = LB(xs, x);

    assert(xs[i] == x);

    return inner_query(x, i + size);

  }

  T get_min_by_idx(int i) { return inner_query(xs[i], i + size); }

  void debug() {

    print("xs", xs);

    print("seg");

    FOR(i, len(seg)) print(i, seg[i].a, seg[i].b);

  }

private:

  void inner_update(T a, T b, int l, int r, int idx) {

    Line line(a, b);

    while (1) {

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

      bool l_over = line.over(seg[idx], xs[l]);

      bool r_over = line.over(seg[idx], xs[r - 1]);

      if (l_over == r_over) {

        if (l_over) swap(seg[idx], line);

        return;

      }

      bool m_over = line.over(seg[idx], xs[m]);

      if (m_over) swap(seg[idx], line);

      if (l_over != m_over)

        idx = (idx << 1) | 0, r = m;

      else

        idx = (idx << 1) | 1, l = m;

    }

  }

  void inner_update(T a, T b, int seg_idx) {

    int left, right;

    int upper_bit = 31 - __builtin_clz(seg_idx);

    left = (size >> upper_bit) * (seg_idx - (1 << upper_bit));

    right = left + (size >> upper_bit);

    inner_update(a, b, left, right, seg_idx);

  }

  T inner_query(T x, int idx) {

    T ret = INF;

    while (idx >= 1) {

      chmin(ret, seg[idx].eval(x));

      idx >>= 1;

    }

    return ret;

  }

};

#line 5 "main.cpp"

void solve() {

  LL(N);

  Graph<bool, 0> G(N);

  G.read_tree();

  VEC(ll, A, N);

  Centroid_Decomposition<decltype(G)> X(G);

  ll ANS = 0;

  auto solve = [&](Graph<bool, 1> G, vi A) -> void {

    /*

    各頂点について、根を含むものについて

    ・根からの距離 D[v]

    ・A[v] の和

    ・A[v]D[v] の和

    */

    const int N = len(A);

    vi D(N), dp(N), dp1(N);

    {

      auto dfs = [&](auto& dfs, int d, int v, int p) -> void {

        D[v] = d;

        dp[v] = (v == 0 ? 0 : dp[p]) + A[v];

        dp1[v] = (v == 0 ? 0 : dp1[p]) + A[v] * D[v];

        for (auto&& e: G[v]) dfs(dfs, d + 1, e.to, v);

      };

      dfs(dfs, 0, 0, -1);

    }

    // 根を含むパスに対する答の計算

    FOR(v, N) {

      // 根から

      chmax(ANS, dp1[v] + dp[v]);

      // 根に向かって

      chmax(ANS, (D[v] + 1) * dp[v] - dp1[v]);

    }

    // 方向ごとに頂点を集める

    vvc<int> vs;

    for (auto&& e: G[0]) {

      vc<int> V;

      auto dfs = [&](auto& dfs, int v) -> void {

        V.eb(v);

        for (auto&& e: G[v]) dfs(dfs, e.to);

      };

      dfs(dfs, e.to);

      vs.eb(V);

    }

    // (D[u]+1)dp[u] - dp1[u] - (D[u]+1)A[0] + (D[u]+1)dp[v] + dp1[v]

    // u を固定すると、a[u] dp[v] + b[u] + dp1[v] の形

    FOR(2) {

      reverse(all(vs));

      LiChaoTree<ll> seg(dp);

      for (auto&& V: vs) {

        // 計算

        for (auto&& v: V) {

          ll y = -seg.get_min(dp[v]) + dp1[v];

          chmax(ANS, y);

        }

        // 直線追加

        for (auto&& u: V) {

          ll a = D[u] + 1;

          ll b = (D[u] + 1) * dp[u] - dp1[u] - (D[u] + 1) * A[0];

          seg.add(-a, -b);

        }

      }

    }

  };

  FOR(v, N) {

    auto [V, H] = X.get_subgraph(v);

    vi B(len(V));

    FOR(i, len(V)) B[i] = A[V[i]];

    solve(H, B);

  }

  print(ANS);

}

signed main() {

  solve();

  return 0;

}