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

#include<bits/stdc++.h>
using namespace std;
#define taskname ""
struct line{
int l,r;
bool operator < (const line &p)const{
return l<p.l;
}
};
struct suzy{
int id,pos;
};
line a[100009];
int vis[8];
int dp[200009][1<<8];
int dp2[200009][1<<8];
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    //freopen(taskname".INP","r",stdin);
    //freopen(taskname".OUT","w",stdout);
    int n,m,k;
    cin>>n>>m>>k;
    vector<int>pos;
    map<int,int>dm;
    pos.push_back(m);
    dm[m]=1;
    for (int i=1;i<=n;i++){
        cin>>a[i].l>>a[i].r;
        if (dm[a[i].l]==0){
            pos.push_back(a[i].l);
            dm[a[i].l]=1;
        }
        if (dm[a[i].r+1]==0){
            dm[a[i].r+1]=1;
            pos.push_back(a[i].r+1);
        }
    }
    if (dm[m+1]==0)pos.push_back(m+1);
    sort(pos.begin(),pos.end());
    sort(a+1,a+1+n);
    int p=0;
    int mask=0;
    vector<suzy>last;
    int ans=0;
    for (int i=0;i<(int)pos.size()-1;i++){
        for (int j=0;j<k;j++){
            vis[j]=0;
        }
        mask=0;
        for (auto v:last){
            if (a[v.id].r<pos[i])continue;
            vis[v.pos]=v.id;
            //cout<<i<<" "<<v.pos<<'\n';
            mask+=(1<<v.pos);
        }
        vector<int>newline;
        for (int j=p+1;j<=n;j++){
            if (a[j].l==pos[i]){
                p=j;
                newline.push_back(j);
            }
            else break;
        }
        //cout<<newline.size()<<'\n';
        last.clear();
        int newmask=0,nmask=0;;
        for (int j=0;j<k;j++){
            if (vis[j]==0){
                if (newline.empty())continue;
                vis[j]=newline.back();
                newline.pop_back();
                last.push_back({vis[j],j});
                if (a[vis[j]].r>=pos[i+1])newmask+=(1<<j);
                nmask|=(1<<j);
            }
            else {
                last.push_back({vis[j],j});
                if (a[vis[j]].r>=pos[i+1])newmask+=(1<<j);
                nmask|=(1<<j);
                //cout<<i<<" "<<j<<'\n';
            }
        }
        //cout<<pos[i]<<" "<<last.size()<<'\n';
        //cout<<pos[i]<<" "<<nmask<<'\n';
        for (int j=0;j<(1<<k);j++){
            //beforemask
            if ((j&nmask)!=j)continue;
            int huhu=(j&mask);
            int sum=0;
            if (i>0)sum=dp2[i-1][huhu];
            if (__builtin_popcount(j)%2==1){
                sum+=(pos[i+1]-pos[i]);
            }
            dp[i][j]=sum;
            ans=max(ans,sum);
            //cout<<pos[i]<<" "<<j<<" "<<sum<<'\n';
        }
        //cout<<mask<<" "<<pos[i]<<'\n';
        //cout<<pos[i]<<" "<<newmask<<'\n';
        for (int j=0;j<(1<<k);j++){
            dp2[i][(j&newmask)]=max(dp2[i][(j&newmask)],dp[i][j]);
        }
        //cout<<i<<" "<<last.size()<<'\n';
    }
    cout<<ans;

}


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

///******* In the name of ALLAH, Who is Most Gracious, Most Merciful *******///

///******* There is no God but ALLAH, MUHAMMAD(S.A.W) is the Messenger of ALLAH. *******///

///******* Every soul shall taste death.*******///

//  AL-HAMDULILLAH    //  AL-HAMDULILLAH     //  AL-HAMDULILLAH    //  AL-HAMDULILLAH

//  AL-HAMDULILLAH    //  AL-HAMDULILLAH     //  AL-HAMDULILLAH    //  AL-HAMDULILLAH

//  AL-HAMDULILLAH    //  AL-HAMDULILLAH     //  AL-HAMDULILLAH    //  AL-HAMDULILLAH

//  AL-HAMDULILLAH    //  AL-HAMDULILLAH     //  AL-HAMDULILLAH    //  AL-HAMDULILLAH

//  AL-HAMDULILLAH    //  AL-HAMDULILLAH     //  AL-HAMDULILLAH    //  AL-HAMDULILLAH

/**************************************************************************************

    ___  _          _   _  ___ ___  ________ _   _ _    _____ _     _      ___  _   _

   / _ \| |        | | | |/ _ \|  \/  |  _  | | | | |  |_   _| |   | |    / _ \| | | |

  / /_\ | |  ____  | |_| / /_\ | .  . | | | | | | | |    | | | |   | |   / /_\ | |_| |

  |  _  | | |____| |  _  |  _  | |\/| | | | | | | | |    | | | |   | |   |  _  |  _  |

  | | | | |____    | | | | | | | |  | | |/ /| |_| | |____| |_| |___| |___| | | | | | |

  \_| |_\_____/    \_| |_\_| |_\_|  |_|___/  \___/\_____\___/\_____\_____\_| |_\_| |_/

***************************************************************************************/

//  AL-HAMDULILLAH    //  AL-HAMDULILLAH     //  AL-HAMDULILLAH    //  AL-HAMDULILLAH

//  AL-HAMDULILLAH    //  AL-HAMDULILLAH     //  AL-HAMDULILLAH    //  AL-HAMDULILLAH

//  AL-HAMDULILLAH    //  AL-HAMDULILLAH     //  AL-HAMDULILLAH    //  AL-HAMDULILLAH

//#pragma GCC optimize("Ofast")

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

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

//#include <bits/stdc++.h>

#include<iostream>

#include<algorithm>

#include<vector>

#include<stdlib.h>

#include<string.h>

#include<math.h>

#define 	ll              long long

#define 	size1           1000001

#define 	bm              1000000007   //bigmod

#define		reset(arr,n,i)  fill(arr,arr+n,i)  //cbrt(n) means cube root

#define		rset(arr,x)  	memset(arr,x,sizeof(arr))

#define		_ceil(x,y)      ((x)/(y))+(((x)%(y))>0)

#define		INF             1e18 + 10

#define		mod             1e9 + 7//998244353;

#define 	endl            "\n"

#define		_cpy(c,a,n)     for(int i=0;i<n;i++) c.push_back(a[i]);

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

#define 	_lin(a,n)       ll a[n]; for(int i=0;i<n;i++) cin>>a[i]

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

#define 	_out(a,n)       for(int i=0;i<n;i++) cout<<a[i]<<" "; cout<<endl

#define		_celi(x,y)      (x+y-1)/(y)  //use this version of _ceil [note: ceil is risky]

#define     eps             0.0000000001

#define 	fopr()          freopen("input.txt", "r", stdin)

#define 	fopw()          freopen("output.txt", "w", stdout)

#define 	FastIO          ios_base::sync_with_stdio(false), cin.tie(0)

// Math :

void		mns(int *x, int *y)		{if(*x>=*y) *x-=*y, *y=0; else *y-=*x, *x=0;}

int			log_2(ll n)				{int cnt=0; while(n/2) cnt++, n/=2; return cnt;}

// Debuging :

#define		_dbg(_x,_y,_z)  cout<<_x<<" "<<_y<<" "<<_z<<endl

#define		_dbl			cout<<"_________________ "<<endl

#define		_db(_x,_y)      cout<<_x<<" "<<_y<<endl

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

using namespace std;

void solve()

{

	int n;

	cin>>n;

	string str;

	cin>>str;

	int cnt=0;

	vector<char>tr,vec;

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

		vec.push_back(str[i]);

		if(tr.empty() || tr.back()!=str[i])

			tr.push_back(str[i]);

	}

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

	for(int i=0;i<tr.size()-1;i++){

		vector<char>v;

		if(vec.empty()) break;

		for(int k=0;k<vec.size();){

			if(vec[k]==tr[i] && !v.empty() && v.back()==tr[i]-1) cnt++,k++;

			else if(vec[k]==tr[i]-1 && !v.empty() && v.back()==tr[i]) v.pop_back(),cnt++;

			else v.push_back(vec[k++]);

		}

		vec.clear();

		_cpy(vec,v,v.size());

	}

	cout<<cnt<<endl;

}

int main()

{

	FastIO;

	int n=1;

	while(n--)

	{

		solve();

	}

	return 0;

}

//written by MAMUN

/*  Cautions:

	1.array out of bound!!! [check array size and last accessed index]

	2.signed integer overflow!!! [int*int!=ll @typecast(ll) one of them or, multiply with 1LL]

	3.floating point numbers numbers are equal if the difference between them is less than 1e-9 [better way to compare floating point numbers]

	4.any square number when divided by 4 must have a remainder of either 0 or 1.

*/

/********************************************************************************************************************************************************

 _   _            _   _       _____          _     _   _       _                    _ _          ______                   _           _           _

| \ | |          | | | |     |  ___|        | |   | | | |     (_)                  (_) |         | ___ \                 | |         | |         | |

|  \| | ___  _ __| |_| |__   | |__  __ _ ___| |_  | | | |_ __  ___   _____ _ __ ___ _| |_ _   _  | |_/ / __ _ _ __   __ _| | __ _  __| | ___  ___| |__

| . ` |/ _ \| '__| __| '_ \  |  __|/ _` / __| __| | | | | '_ \| \ \ / / _ \ '__/ __| | __| | | | | ___ \/ _` | '_ \ / _` | |/ _` |/ _` |/ _ \/ __| '_ \

| |\  | (_) | |  | |_| | | | | |__| (_| \__ \ |_  | |_| | | | | |\ V /  __/ |  \__ \ | |_| |_| | | |_/ / (_| | | | | (_| | | (_| | (_| |  __/\__ \ | | |

\_| \_/\___/|_|   \__|_| |_| \____/\__,_|___/\__|  \___/|_| |_|_| \_/ \___|_|  |___/_|\__|\__, | \____/ \__,_|_| |_|\__, |_|\__,_|\__,_|\___||___/_| |_|

                                                                                __/ |                     __/ |

                                                                                |___/                     |___/

*********************************************************************************************************************************************************/


A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00:  You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2);  then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
OutputCopyYES
NO
YES
YES
NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

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

void yes() { cout<<"YES\n"; }

void no() { cout<<"NO\n"; }

#define yes yes();

#define no no();

#define endl '\n';

void solve()

{

	int n; cin>>n;

    set<int> st;

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

    {

        int temp; cin>>temp;

        st.insert(temp%2);

    }

    if (st.size()>1) no

    else yes;

}

int main()

{

	ios_base::sync_with_stdio(0);

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

	int t;

	cin >> t;

	while(t--)

	{

		solve();

	}

	return 0;

}


E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red; the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of nn rows and mm columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh qq options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 00.Warawreh couldn't find the best option himself so he asked you for help, can you help him?InputThe first line of input contains three integers nn, mm and qq (1≤n,m≤500,1≤q≤3⋅105)(1≤n,m≤500,1≤q≤3⋅105)  — the number of row, the number columns and the number of options.For the next nn lines, every line will contain mm characters. In the ii-th line the jj-th character will contain the color of the cell at the ii-th row and jj-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.For the next qq lines, the input will contain four integers r1r1, c1c1, r2r2 and c2c2 (1≤r1≤r2≤n,1≤c1≤c2≤m)(1≤r1≤r2≤n,1≤c1≤c2≤m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r1,c1)(r1,c1) and with the bottom-right corner in the cell (r2,c2)(r2,c2).OutputFor every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 00.ExamplesInputCopy5 5 5
RRGGB
RRGGY
YYBBG
YYBBR
RBBRG
1 1 5 5
2 2 5 5
2 2 3 3
1 1 3 5
4 4 5 5
OutputCopy16
4
4
4
0
InputCopy6 10 5
RRRGGGRRGG
RRRGGGRRGG
RRRGGGYYBB
YYYBBBYYBB
YYYBBBRGRG
YYYBBBYBYB
1 1 6 10
1 3 3 10
2 2 6 6
1 7 6 10
2 1 5 10
OutputCopy36
4
16
16
16
InputCopy8 8 8
RRRRGGGG
RRRRGGGG
RRRRGGGG
RRRRGGGG
YYYYBBBB
YYYYBBBB
YYYYBBBB
YYYYBBBB
1 1 8 8
5 2 5 7
3 1 8 6
2 3 5 8
1 2 6 8
2 1 5 5
2 1 7 7
6 5 7 5
OutputCopy64
0
16
4
16
4
36
0
NotePicture for the first test:The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black; the border of the sub-square with the maximal possible size; that can be cut is marked with gray.

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

#define int long long

using namespace std;

const int INF=505;

int n,m,q;

char a[INF][INF];

mt19937 rnd(chrono::system_clock().now().time_since_epoch().count());

int gen(int l,int r) {return rnd()%(r-l+1);}

int vis[INF],p[INF],b[INF][INF],ans[INF][INF];

int f[INF][INF][13][13];

int Get(int x,int y,int xx,int yy) {

//	cout<<x<<" "<<y<<" "<<xx<<" "<<yy<<" qweijqwej\n";

	return b[xx][yy]-b[x][yy]-b[xx][y]+b[x][y];

}

int solve2(int l,int r,int ll,int rr) {

	if (ll-l+1<2) return 0;

	if (rr-r+1<2) return 0;

	if (l<1 || r<1 || ll>n || rr>m) return 0;

	for (int i=0;i<=5;i++) vis[i]=0;

	int Mid1=(l+ll)>>1,Mid2=(r+rr)>>1;

	int kk=Get(l-1,r-1,Mid1,Mid2);

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

		if (kk%p[i]==0) {vis[i]++;break;}

	kk=Get(Mid1,r-1,ll,Mid2);

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

		if (kk%p[i]==0) {vis[i]++;break;}

	kk=Get(Mid1,Mid2,ll,rr);

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

		if (kk%p[i]==0) {vis[i]++;break;}

	kk=Get(l-1,Mid2,Mid1,rr);

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

		if (kk%p[i]==0) {vis[i]++;break;}

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

		if (vis[i]!=1) return 0;

	return 1;

}

int query(int l,int r,int ll,int rr) {

	if (l>ll || r>rr) return -1e9;

	int xx=__lg(ll-l+1),yy=__lg(rr-r+1);

	return max({f[l][r][xx][yy],f[ll-(1ll<<xx)+1][r][xx][yy],

			f[l][rr-(1ll<<yy)+1][xx][yy],f[ll-(1ll<<xx)+1][rr-(1ll<<yy)+1][xx][yy]});

}

signed main()

{

	ios::sync_with_stdio(false);

	cin>>n>>m>>q;

	for (int i=0;i<4;i++) p[i]=rnd();

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

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

			cin>>a[i][j];

			if (a[i][j]=='R') b[i][j]=p[0];

			else if (a[i][j]=='G') b[i][j]=p[1];

			else if (a[i][j]=='Y') b[i][j]=p[2];

			else b[i][j]=p[3];

		}

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

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

			b[i][j]+=b[i-1][j]+b[i][j-1]-b[i-1][j-1];

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

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

			int l=1,r=min(n,m),ans2=0;

			while (l<=r) {

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

				if (solve2(i-Mid+1,j-Mid+1,i+Mid,j+Mid)) l=(ans2=Mid)+1;

				else r=Mid-1;

			}

			ans[i][j]=ans2;

			f[i][j][0][0]=ans2;

		}

	}

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

		if ((1ll<<i)>n) break;

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

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

				f[j][k][i][0]=max(f[j][k][i-1][0],f[j+(1ll<<(i-1))][k][i-1][0]);

	}

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

		if ((1ll<<i)>m) break;

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

			for (int k=1;k+(1ll<<i)-1<=m;k++)

				f[j][k][0][i]=max(f[j][k][0][i-1],f[j][k+(1<<(i-1))][0][i-1]);

	}

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

		if ((1ll<<i)>n) break;

		for (int p=1;p<21;p++) {

			if ((1ll<<p)>m) break;

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

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

					f[j][k][i][p]=max({f[j][k][i-1][p-1],f[j+(1ll<<(i-1))][k][i-1][p-1],

									f[j][k+(1ll<<(p-1))][i-1][p-1],f[j+(1ll<<(i-1))][k+(1ll<<(p-1))][i-1][p-1]});

				}

			}

		}

	}

	for (int i=1;i<=q;i++) { //123123

		int x=0,y=0,xx=0,yy=0;

		cin>>x>>y>>xx>>yy;

		int l=1,r=min(yy-y+1,xx-x+1),ans2=-1;

		while (l<=r) {

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

			if (query(x+Mid-1,y+Mid-1,xx-Mid,yy-Mid)>=Mid) l=(ans2=Mid)+1;

			else r=Mid-1;

		}

		if (ans2==-1) cout<<"0\n";

		else cout<<ans2*ans2*4<<"\n";

	}

	return 0;

}


A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way:  Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x;  choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.

#include<bits/stdc++.h>

using namespace std;

int main()

{

    int test;

    cin >> test;

    while(test--){

        int a, b;

        cin >> a >> b;

        if(a == b) cout << 0 << endl;

        else if(a<b){

            if(a%2 != 0 && b%2 == 0) cout << 1 << endl;

            else if(a%2 != 0 && b%2 != 0) cout << 2 << endl;

            else if(a%2 == 0 && b%2 != 0) cout << 1 << endl;

            else if(a%2 == 0 && b%2 == 0) cout << 2 << endl;

        }

        else{

            if(a%2 != 0 && b%2 == 0) cout << 2 << endl;

            else if(a%2 != 0 && b%2 != 0) cout << 1 << endl;

            else if(a%2 == 0 && b%2 != 0) cout << 2 << endl;

            else if(a%2 == 0 && b%2 == 0) cout << 1 << endl;

        }

    }

    return 0;

}


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.

#include <bits/stdc++.h>

using namespace std;

using llong = int64_t;

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

#define file_name "test"

#ifdef DAT

#include "debug.hpp"

#else

#define debug(x...) 12

#endif

namespace Task {

const int MAX_N = 150001;

const int MAX_LOG = 18;

const llong INF = 1e18;

vector<vector<int>> adj;

typedef class CentroidTree {

public:

  int size_tree;

  int root;

  vector<vector<int>> tree;

  vector<vector<int>> lev;

  vector<vector<int>> child;

  vector<bool> removed;

  vector<int> cnt_child;

  CentroidTree(){};

  CentroidTree(int init_size_tree) : size_tree(init_size_tree) {

    tree.resize(size_tree + 1, vector<int>());

    child.resize(size_tree + 1, vector<int>());

    lev.resize(MAX_LOG + 1, vector<int>());

    removed.resize(size_tree + 1, false);

    cnt_child.resize(size_tree + 1, 0);

  }

  void compute_size(int u, int par) {

    cnt_child[u] = 1;

    for (int v : adj[u]) {

      if (v != par and !removed[v]) {

        compute_size(v, u);

        cnt_child[u] += cnt_child[v];

      }

    }

  }

  int find_centroid(int u, int par, int cur_size) {

    while (true) {

      pair<int, int> best(-1, -1);

      for (int v : adj[u]) {

        if (v != par and !removed[v]) {

          if (cnt_child[v] > best.first) {

            best = {cnt_child[v], v};

          }

        }

      }

      if ((best.first << 1) <= cur_size) {

        return u;

      }

      par = u;

      u = best.second;

    }

  }

  void decompose(int u, int par, int cur_lev) {

    compute_size(u, -1);

    int cen_ver = find_centroid(u, -1, cnt_child[u]);

    removed[cen_ver] = true;

    if (par == -1) {

      root = cen_ver;

    }

    lev[cur_lev].emplace_back(cen_ver);

    child[cen_ver].emplace_back(cen_ver);

    if (par != -1) {

      tree[par].emplace_back(cen_ver);

    }

    for (int v : adj[cen_ver]) {

      if (!removed[v]) {

        decompose(v, cen_ver, cur_lev + 1);

      }

    }

    if (par != -1) {

      for (const int &v : child[cen_ver]) {

        child[par].emplace_back(v);

      }

    }

  }

  void decompose() { decompose(1, -1, 0); }

} td_centroid_tree;

typedef class Tree {

public:

  int size_tree;

  vector<vector<int>> jump;

  vector<int> euler_tour;

  vector<int> st;

  vector<llong> sum[2];

  vector<llong> sum_mult;

  vector<int> dep;

  vector<int> values;

  vector<int> dad;

  function<int(int, int)> comp = [&](const int &u, const int &v) {

    return (dep[u] <= dep[v] ? u : v);

  };

  Tree(){};

  Tree(int init_size_tree) : size_tree(init_size_tree) {

    jump.resize(MAX_LOG + 1, vector<int>(2 * size_tree + 1, 0));

    sum[0].resize(size_tree + 1, 0);

    sum[1].resize(size_tree + 1, 0);

    sum_mult.resize(size_tree + 1, 0);

    st.resize(size_tree + 1, 0);

    dep.resize(size_tree + 1, 1);

    dad.resize(size_tree + 1, 0);

    dep[0] = 0;

  }

  void add_edge(int u, int v) {

    adj[u].emplace_back(v);

    adj[v].emplace_back(u);

  }

  void dfs(int u, int par) {

    dad[u] = par;

    sum[0][u] = sum[0][par] + llong(values[u]);

    sum[1][u] = sum[1][par] + sum[0][u];

    sum_mult[u] = sum_mult[par] + llong(dep[u]) * llong(values[u]);

    st[u] = len(euler_tour);

    euler_tour.emplace_back(u);

    for (int v : adj[u]) {

      if (v != par) {

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

        dfs(v, u);

        euler_tour.emplace_back(u);

      }

    }

  }

  void build_lca() {

    for (int u = 0; u < len(euler_tour); ++u) {

      jump[0][u] = euler_tour[u];

    }

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

      for (int u = 0; u + (1 << j) - 1 < len(euler_tour); ++u) {

        jump[j][u] = comp(jump[j - 1][u], jump[j - 1][u + (1 << (j - 1))]);

      }

    }

  }

  int get_lca(int u, int v) const {

    int l, r;

    tie(l, r) = pair<int, int>{st[u], st[v]};

    if (l > r) {

      swap(l, r);

    }

    int x = int(log2(r - l + 1));

    return comp(jump[x][l], jump[x][r - (1 << x) + 1]);

  }

  int get_dist(int u, int v) const {

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

  }

  llong get_sum(int u, int v) const {

    int R = get_lca(u, v);

    return sum[0][u] + sum[0][v] - 2 * sum[0][R] + llong(values[R]);

  }

  llong sum_to_root(int u, int R) const {

    int p = (R == 1 ? 0 : dad[R]);

    return sum_mult[u] - sum_mult[p] - llong(dep[p]) * (sum[0][u] - sum[0][p]);

  }

  llong sum_from_root(int u, int R) const {

    int p = (R == 1 ? 0 : dad[R]);

    return sum[1][u] - sum[1][p] - llong(dep[u] - dep[p]) * sum[0][p];

  }

  llong prefix_sums(int u, int v) const {

    int R = get_lca(u, v);

    int p = (R == 1 ? 0 : dad[R]);

    if (u == R) {

      return sum_from_root(v, R);

    } else if (v == R) {

      return sum_to_root(u, R);

    } else {

      llong lhs = sum_to_root(u, R) +

                  llong(dep[v] - dep[p] - 1) * (sum[0][u] - sum[0][p]);

      llong rhs =

          sum_from_root(v, R) - llong(dep[v] - dep[p]) * llong(values[R]);

      return lhs + rhs;

    }

  }

} td_tree;

class Line {

public:

  llong m, b;

  Line() : m(0), b(-INF){};

  Line(llong init_m, llong init_b) : m(init_m), b(init_b){};

  llong operator()(const int &x) { return m * llong(x) + b; }

};

vector<Line> lichao_tree;

vector<bool> clean;

void insert_line(Line upd_line, int l, int r, int node = 1) {

  if (l == r) {

    clean[node] = false;

    if (lichao_tree[node](l) < upd_line(l)) {

      lichao_tree[node] = upd_line;

    }

    return;

  }

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

  if (lichao_tree[node].m > upd_line.m) {

    swap(lichao_tree[node], upd_line);

  }

  if (lichao_tree[node](mid) > upd_line(mid)) {

    insert_line(upd_line, mid + 1, r, node << 1 | 1);

  } else {

    swap(lichao_tree[node], upd_line);

    insert_line(upd_line, l, mid, node << 1);

  }

  clean[node] = clean[node << 1] & clean[node << 1 | 1];

}

llong get_max(int pos, int l, int r, int node = 1) {

  if (l > r or r < pos or l > pos) {

    return -INF;

  }

  if (l == r) {

    return lichao_tree[node](l);

  }

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

  if (pos <= mid) {

    return max(lichao_tree[node](pos), get_max(pos, l, mid, node << 1));

  } else {

    return max(lichao_tree[node](pos), get_max(pos, mid + 1, r, node << 1 | 1));

  }

}

void delete_lichao_tree(int l, int r, int node = 1) {

  if (l > r or clean[node]) {

    return;

  }

  clean[node] = true;

  lichao_tree[node] = Line();

  if (l < r) {

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

    delete_lichao_tree(l, mid, node << 1);

    delete_lichao_tree(mid + 1, r, node << 1 | 1);

  }

}

void solve() {

  int n;

  cin >> n;

  adj.resize(n + 1, vector<int>());

  lichao_tree.resize((MAX_N << 2) + 10, Line());

  clean.resize((MAX_N << 2) + 10, true);

  td_tree tree_gr(n);

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

    int u, v;

    cin >> u >> v;

    tree_gr.add_edge(u, v);

  }

  {

    vector<int> values(n + 1);

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

      cin >> values[u];

    }

    tree_gr.values = values;

  }

  tree_gr.dfs(1, 1);

  tree_gr.build_lca();

  td_centroid_tree cen_tree(n);

  cen_tree.decompose();

  llong ans = -INF;

  function<void(int, int)> dfs = [&](int u, int cen_root) -> void {

    vector<Line> lines;

    for (const int &v : cen_tree.child[u]) {

      int x = tree_gr.get_dist(v, cen_root);

      ans = max({ans,

                 get_max(x - 1, 0, MAX_N) + tree_gr.prefix_sums(cen_root, v) -

                     llong(x) * tree_gr.values[cen_root],

                 tree_gr.prefix_sums(cen_root, v),

                 tree_gr.prefix_sums(v, cen_root)});

      llong m = tree_gr.get_sum(v, cen_root);

      llong b = tree_gr.prefix_sums(v, cen_root);

      lines.emplace_back(Line(m, b));

    }

    for (const Line &line : lines) {

      insert_line(line, 0, n);

    }

  };

  auto go = [&](int u, auto it_st, auto it_en) {

    for (; it_st != it_en; ++it_st) {

      dfs(*it_st, u);

    }

  };

  for (int cur_lev = 0; cur_lev <= MAX_LOG; ++cur_lev) {

    for (const int &u : cen_tree.lev[cur_lev]) {

      go(u, ranges::rbegin(cen_tree.tree[u]), ranges::rend(cen_tree.tree[u]));

      delete_lichao_tree(0, MAX_N);

      go(u, ranges::begin(cen_tree.tree[u]), ranges::end(cen_tree.tree[u]));

      delete_lichao_tree(0, MAX_N);

    }

  }

  cout << ans << '\n';

  //// CLEAR

  auto clearData = [&]() -> void { adj.clear(); };

  clearData();

}

} // namespace Task

int main(int argc, char **argv) {

  ios_base::sync_with_stdio(false);

  cin.tie(0);

  int nTest = 1;

#ifdef DAT

  freopen(file_name ".inp", "r", stdin);

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

  freopen(".log", "w", stderr);

  nTest = (argc > 1 ? stoi(argv[1]) : 1);

  auto rand_range = [&](int l, int r) -> int { return l + rand(r - l + 1); };

  auto generate_tree = [&](int size_tree) {

    ofstream cout("test.inp");

    cout << size_tree << '\n';

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

      int p = rand_range(1, i - 1);

      cout << i << ' ' << p << '\n';

    }

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

      cout << rand_range(1, 1000000) << ' ';

    }

    cout.close();

  };

#endif

  // cin >> nTest;

  for (int _ = 1; _ <= nTest; ++_) {

#ifdef DAT

    cout << "Test #" << _ << ":\n";

    // generate_tree(150000);

#endif

    Task::solve();

  }

}


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


E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements:  The score of each problem should be a positive integer not exceeding 109109.  A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109.  The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3
OutputCopy4 5 9 13 18InputCopy8 0
OutputCopy10 11 12 13 14 15 16 17
InputCopy4 10
OutputCopy-1
NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution.   (1,2,3)(1,2,3)  (1,3,4)(1,3,4)  (2,4,5)(2,4,5)

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;

constexpr int N = int(4e2) + 5;
constexpr int inf = 0x7f7f7f7f;
constexpr int MOD = int(1e9) + 7;

void solve(){
    int n, m, k = 0, l;
    cin >> n >> m;

    vector<int> v;
    for(int i = 1; i <= n; i++){
        if(k + (i - 1 >> 1) <= m){
            k += i - 1 >> 1;
            v.push_back(i);
            l = v.back() + 1;
        }
        else if(k < m){
            v.push_back(2 * (i - m + k) - 1);
            k = m;
            l = v.back() + 1;
        }
        else v.push_back(int(1e9) - l * (n - i));
    }
    if(k != m) cout << -1;
    else for(auto& i : v) cout << i << ' ';
}
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

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


A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
OutputCopyNO
YES
YES
NO
NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb.

#include<bits/stdc++.h>

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

#define reverse(allv) reverse(v.begin(), v.end())

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

#define ll long long

#define pb push_back

#define pob pop_back

#define ff first

#define ss second

#define mk make_pair

using namespace std;

void d1zzaster1(){

	string a, b, c;

    cin >> a >> b >> c;

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

    	if(c[i] != a[i] && c[i] != b[i]){

    		cout << "NO\n";

    		return;

		}

	}

	cout << "YES\n";

	return;

}

int main()

{

	ios_base::sync_with_stdio(0);

	cin.tie(0);

    cout.tie(0);

    int q;

    cin >> q;

    while(q--){

    	d1zzaster1();

	}

}


A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied:   All scores are integers  0≤ai≤m0≤ai≤m  The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105)  — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m)  — scores of the students.OutputFor each testcase, output one integer  — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m.

#include "bits/stdc++.h"

using namespace std;

#define ll long long

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

  int t; cin >> t;
  while (t--) {

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

    int tot = 0;
    while (n--) {
      int x; cin >> x;
      tot += x;
    }

    cout << min(tot, m) << "\n";

  }

}

// ~ BucketPotato


G. Seollaltime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIt is only a few days until Seollal (Korean Lunar New Year); and Jaehyun has invited his family to his garden. There are kids among the guests. To make the gathering more fun for the kids, Jaehyun is going to run a game of hide-and-seek.The garden can be represented by a n×mn×m grid of unit cells. Some (possibly zero) cells are blocked by rocks, and the remaining cells are free. Two cells are neighbors if they share an edge. Each cell has up to 4 neighbors: two in the horizontal direction and two in the vertical direction. Since the garden is represented as a grid, we can classify the cells in the garden as either "black" or "white". The top-left cell is black, and two cells which are neighbors must be different colors. Cell indices are 1-based, so the top-left corner of the garden is cell (1,1)(1,1).Jaehyun wants to turn his garden into a maze by placing some walls between two cells. Walls can only be placed between neighboring cells. If the wall is placed between two neighboring cells aa and bb, then the two cells aa and bb are not neighboring from that point. One can walk directly between two neighboring cells if and only if there is no wall directly between them. A maze must have the following property. For each pair of free cells in the maze, there must be exactly one simple path between them. A simple path between cells aa and bb is a sequence of free cells in which the first cell is aa, the last cell is bb, all cells are distinct, and any two consecutive cells are neighbors which are not directly blocked by a wall.At first, kids will gather in cell (1,1)(1,1), and start the hide-and-seek game. A kid can hide in a cell if and only if that cell is free, it is not (1,1)(1,1), and has exactly one free neighbor. Jaehyun planted roses in the black cells, so it's dangerous if the kids hide there. So Jaehyun wants to create a maze where the kids can only hide in white cells.You are given the map of the garden as input. Your task is to help Jaehyun create a maze.InputYour program will be judged in multiple test cases.The first line contains the number of test cases tt. (1≤t≤1001≤t≤100). Afterward, tt test cases with the described format will be given.The first line of a test contains two integers n,mn,m (2≤n,m≤202≤n,m≤20), the size of the grid.In the next nn line of a test contains a string of length mm, consisting of the following characters (without any whitespace):   O: A free cell.  X: A rock. It is guaranteed that the first cell (cell (1,1)(1,1)) is free, and every free cell is reachable from (1,1)(1,1). If t≥2t≥2 is satisfied, then the size of the grid will satisfy n≤10,m≤10n≤10,m≤10. In other words, if any grid with size n>10n>10 or m>10m>10 is given as an input, then it will be the only input on the test case (t=1t=1).OutputFor each test case, print the following:If there are no possible mazes, print a single line NO.Otherwise, print a single line YES, followed by a grid of size (2n−1)×(2m−1)(2n−1)×(2m−1) denoting the found maze. The rules for displaying the maze follows. All cells are indexed in 1-base.  For all 1≤i≤n,1≤j≤m1≤i≤n,1≤j≤m, if the cell (i,j)(i,j) is free cell, print 'O' in the cell (2i−1,2j−1)(2i−1,2j−1). Otherwise, print 'X' in the cell (2i−1,2j−1)(2i−1,2j−1).  For all 1≤i≤n,1≤j≤m−11≤i≤n,1≤j≤m−1, if the neighboring cell (i,j),(i,j+1)(i,j),(i,j+1) have wall blocking it, print ' ' in the cell (2i−1,2j)(2i−1,2j). Otherwise, print any printable character except spaces in the cell (2i−1,2j)(2i−1,2j). A printable character has an ASCII code in range [32,126][32,126]: This includes spaces and alphanumeric characters.  For all 1≤i≤n−1,1≤j≤m1≤i≤n−1,1≤j≤m, if the neighboring cell (i,j),(i+1,j)(i,j),(i+1,j) have wall blocking it, print ' ' in the cell (2i,2j−1)(2i,2j−1). Otherwise, print any printable character except spaces in the cell (2i,2j−1)(2i,2j−1)  For all 1≤i≤n−1,1≤j≤m−11≤i≤n−1,1≤j≤m−1, print any printable character in the cell (2i,2j)(2i,2j). Please, be careful about trailing newline characters or spaces. Each row of the grid should contain exactly 2m−12m−1 characters, and rows should be separated by a newline character. Trailing spaces must not be omitted in a row.ExampleInputCopy4
2 2
OO
OO
3 3
OOO
XOO
OOO
4 4
OOOX
XOOX
OOXO
OOOO
5 6
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OutputCopyYES
OOO
  O
OOO
NO
YES
OOOOO X
  O O
X O O X
  O
OOO X O
O O   O
O OOOOO
YES
OOOOOOOOOOO
  O   O   O
OOO OOO OOO
O   O   O
OOO OOO OOO
  O   O   O
OOO OOO OOO
O   O   O
OOO OOO OOO

#include <bits/stdc++.h>

using namespace std;

const int NN = 2000;

struct T {

  bool rr;

  T *son[2], *pf, *fa;

} f1[NN], *ff = f1, *f[NN], *null;

void downdate(T *x) {

  if (x -> rr) {

    x -> son[0] -> rr = !x -> son[0] -> rr;

    x -> son[1] -> rr = !x -> son[1] -> rr;

    swap(x -> son[0], x -> son[1]);

    x -> rr = false;

  }

  // add stuff

}

void update(T *x) {

  // add stuff

}

void rotate(T *x, bool t) { /// start-hash

  T *y = x -> fa, *z = y -> fa;

  if (z != null)  z -> son[z -> son[1] == y] = x;

  x -> fa = z;

  y -> son[t] = x -> son[!t];

  x -> son[!t] -> fa = y;

  x -> son[!t] = y;

  y -> fa = x;

  update(y);

} /// end-hash

void xiao(T *x) {

  if (x -> fa != null)  xiao(x -> fa), x -> pf = x -> fa -> pf;

  downdate(x);

}

void splay(T *x) { /// start-hash

  xiao(x);

  T *y, *z;

  while (x -> fa != null) {

    y = x -> fa; z = y -> fa;

    bool t1 = (y -> son[1] == x), t2 = (z -> son[1] == y);

    if (z != null) {

      if (t1 == t2) rotate(y, t2), rotate(x, t1);

      else  rotate(x, t1), rotate(x, t2);

    }else rotate(x, t1);

  }

  update(x);

} /// end-hash

void access(T *x) {/// start-hash

  splay(x);

  x -> son[1] -> pf = x;

  x -> son[1] -> fa = null;

  x -> son[1] = null;

  update(x);

  while (x -> pf != null) {

    splay(x -> pf);

    x -> pf -> son[1] -> pf = x -> pf;

    x -> pf -> son[1] -> fa = null;

    x -> pf -> son[1] = x;

    x -> fa = x -> pf;

    splay(x);

  }

  x -> rr = true;

} /// end-hash

bool Cut(T *x, T *y) { /// start-hash

  access(x);

  access(y);

  downdate(y);

  downdate(x);

  if (y -> son[1] != x || x -> son[0] != null)

    return false;

  y -> son[1] = null;

  x -> fa = x -> pf = null;

  update(x);

  update(y);

  return true;

} /// end-hash

bool Connected(T *x, T *y) {

  access(x);

  access(y);

  return x == y || x -> fa != null;

}

bool Link(T *x, T *y) {

  if (Connected(x, y))

    return false;

  access(x);

  access(y);

  x -> pf = y;

  return true;

}

void solve(){

	int n, m;

	cin >> n >> m;

	vector<string> s(n);

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

	ff = f1;

	null = new T; null -> son[0] = null -> son[1] = null -> fa = null -> pf = null;

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

		f[i] = ++ff;

		f[i] -> son[0] = f[i] -> son[1] = f[i] -> fa = f[i] -> pf = null;

		f[i] -> rr = false;

	}

	vector<int> dx = {1, 0, -1, 0};

	vector<int> dy = {0, 1, 0, -1};

	vector<set<int> > used(n * m);

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

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

			if(i == 0 && j == 0) continue;

			if(s[i][j] == 'X') continue;

			if(((i + j) & 1) == 0){

				int a = m * i + j;

				for(int d = 0; d < 4; d++){

					if(used[a].size() == 2) continue;

					int ni = i + dx[d];

					int nj = j + dy[d];

					if(ni < 0 || nj < 0 || ni >= n || nj >= m || s[ni][nj] == 'X') continue;

					int b = m * ni + nj;

					while(true){

						if(!Connected(f[a], f[b])){

							used[a].insert(b);

							used[b].insert(a);

							Link(f[a], f[b]);

							break;

						}

						bool done = false;

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

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

								if(((v + w) & 1) != 0) continue;

								int c = m * v + w;

								if(!Connected(f[a], f[c])) continue;

								for(int d1 = 0; d1 < 4; d1++){

									int nv = v + dx[d1];

									int nw = w + dy[d1];

									if(nv < 0 || nw < 0 || nv >= n || nw >= m || s[nv][nw] == 'X') continue;

									int nc = nv * m + nw;

									if(Connected(f[a], f[nc])) continue;

									done = true;

									for(int bc : used[c]){

										assert(Cut(f[c], f[bc]));

										if(!Connected(f[a], f[c])){

											used[c].erase(bc);

											used[bc].erase(c);

											break;

										}

										Link(f[c], f[bc]);

									}

									used[c].insert(nc);

									used[nc].insert(c);

									Link(f[c], f[nc]);

									goto found;

								}

							}

						}

						found:;

						if(!done) break;

					}

				}

				if(used[a].size() < 2){

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

					return;

				}

			}

		}

	}

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

	vector<string> ans(2*n-1, string(2*m-1, ' '));

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

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

			ans[2*i][2*j] = s[i][j];

			if(s[i][j] == 'X') continue;

			if(((i + j) & 1) == 0){

				int a = m * i + j;

				for(int d = 0; d < 4; d++){

					int ni = i + dx[d];

					int nj = j + dy[d];

					if(ni < 0 || nj < 0 || ni >= n || nj >= m || s[ni][nj] == 'X') continue;

					int b = m * ni + nj;

					if(!Connected(f[a], f[b])){

						used[a].insert(b);

						used[b].insert(a);

						Link(f[a], f[b]);

					}

					if(used[a].count(b)){

						ans[2*i + dx[d]][2*j + dy[d]] = 'O';

					}

				}

			}

		}

	}

	for(string z : ans){

		cout << z << '\n';

	}

}

int main(){

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

	int T;

	cin >> T;

	while(T--) solve();

}


A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840
OutputCopy7
InputCopy42 42
OutputCopy0
InputCopy48 72
OutputCopy-1
NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.

#include<bits/stdc++.h>

using ll = long long;

using namespace std;

ll del(ll n, ll m) {ll a=0;if(n%m>0)a++;a+=n/m;return a;}

#define endl '\n'

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

#define pb push_back

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

#define inf 1e9 + 1e5

#define watch(x) cout << (#x) << " => " << (x) << endl

void solve(){

ll n, m;

cin >> n >> m;

ll ans = 0;

if(m % n != 0)

{

    cout<<-1;

    return;

}

m/=n;

while(m % 2 == 0)

{

    ans++;

    m/=2;

}

while(m % 3 == 0)

{

    ans++;

    m/=3;

}

if(m != 1)

{

    cout<<ans / ans * -1;

    return;

}

cout<<ans;

}

int main()

{

IOS

//ll _; cin>>_; while(_--)

solve();

return 0;

}


B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.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 separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6
1
10
19
9876
12345
1000000000
OutputCopy1
11
21
10973
13716
1111111111


H. Kuroni the Private Tutortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs a professional private tutor; Kuroni has to gather statistics of an exam. Kuroni has appointed you to complete this important task. You must not disappoint him.The exam consists of nn questions, and mm students have taken the exam. Each question was worth 11 point. Question ii was solved by at least lili and at most riri students. Additionally, you know that the total score of all students is tt.Furthermore, you took a glance at the final ranklist of the quiz. The students were ranked from 11 to mm, where rank 11 has the highest score and rank mm has the lowest score. Ties were broken arbitrarily.You know that the student at rank pipi had a score of sisi for 1≤i≤q1≤i≤q.You wonder if there could have been a huge tie for first place. Help Kuroni determine the maximum number of students who could have gotten as many points as the student with rank 11, and the maximum possible score for rank 11 achieving this maximum number of students.InputThe first line of input contains two integers (1≤n,m≤1051≤n,m≤105), denoting the number of questions of the exam and the number of students respectively.The next nn lines contain two integers each, with the ii-th line containing lili and riri (0≤li≤ri≤m0≤li≤ri≤m).The next line contains a single integer qq (0≤q≤m0≤q≤m). The next qq lines contain two integers each, denoting pipi and sisi (1≤pi≤m1≤pi≤m, 0≤si≤n0≤si≤n). It is guaranteed that all pipi are distinct and if pi≤pjpi≤pj, then si≥sjsi≥sj.The last line contains a single integer tt (0≤t≤nm0≤t≤nm), denoting the total score of all students.OutputOutput two integers: the maximum number of students who could have gotten as many points as the student with rank 11, and the maximum possible score for rank 11 achieving this maximum number of students. If there is no valid arrangement that fits the given data, output −1−1 −1−1.ExamplesInputCopy5 4
2 4
2 3
1 1
0 1
0 0
1
4 1
7
OutputCopy3 2
InputCopy5 6
0 6
0 6
2 5
6 6
4 6
1
3 3
30
OutputCopy-1 -1
NoteFor the first sample; here is one possible arrangement that fits the data:Students 11 and 22 both solved problems 11 and 22.Student 33 solved problems 22 and 33.Student 44 solved problem 44.The total score of all students is T=7T=7. Note that the scores of the students are 22, 22, 22 and 11 respectively, which satisfies the condition that the student at rank 44 gets exactly 11 point. Finally, 33 students tied for first with a maximum score of 22, and it can be proven that we cannot do better with any other arrangement.

#include<bits/stdc++.h>

template <typename _Tp>void read(_Tp &x){
char ch(getchar());bool f(false);while(!isdigit(ch))f|=ch==45,ch=getchar();
x=ch&15,ch=getchar();while(isdigit(ch))x=x*10+(ch&15),ch=getchar();
if(f)x=-x;
}
template <typename _Tp,typename... Args>void read(_Tp &t,Args &...args){read(t);read(args...);}
const int N=100005;typedef long long ll;
int L[N],R[N],p[N],s[N],a[N],n,m,val[N],VAL[N];ll t,lim[N],b[N],suf[N];
ll calc1(int mid){ll tot=0;for(int i=1;i<=n;++i)tot+=std::min(R[i],std::max(L[i],mid));return tot;}
bool check(int mid){
int x=-1,y=-1;for(int i=1;i<=mid;++i)if(val[i]!=-1)(x==-1?x:y)=val[i];
if(x!=-1&&y!=-1&&x!=y)return 0;
if(x==-1&&y==-1){
ll tmp=1e18,tot=0;
for(int i=1;i<=m;++i)tot+=i>mid?VAL[i]:0,tmp=std::min(tmp,(lim[i]-tot)/std::min(i,mid));
for(int i=1;i<=m;++i)b[i]=i<=mid?tmp:VAL[i];
}
else for(int i=1;i<=m;++i)b[i]=i<=mid?x:VAL[i];
ll tot=0;for(int i=1;i<=m;++i){tot+=b[i],suf[i]=lim[i]-tot;if(tot>lim[i])return 0;}
suf[m+1]=1e18;for(int i=m;i>=1;--i)suf[i]=std::min(suf[i],suf[i+1]);
ll sum=0;for(int i=mid+1;i<=m;++i)if(val[i]==-1)b[i]=std::min(VAL[i]+suf[i]-sum,b[i-1]),sum+=b[i]-VAL[i];
for(int i=1;i<m;++i)if(b[i]<b[i+1])return 0;
return sum+tot==t;
}
int main(){
read(n,m);
for(int i=1;i<=n;++i)read(L[i],R[i]);
int q;read(q);
memset(val,-1,sizeof(val));
for(int i=1;i<=q;++i)read(p[i],s[i]),val[p[i]]=s[i],VAL[p[i]]=s[i];
for(int i=m;i>=1;--i)if(!VAL[i])VAL[i]=VAL[i+1];
read(t);int l=0,r=m,mid;
while(l<r)mid=(l+r+1)>>1,calc1(mid)<=t?l=mid:r=mid-1;
ll tot=0;for(int i=1;i<=n;++i)a[i]=std::min(R[i],std::max(L[i],l)),tot+=a[i];
for(int i=1;i<=n;++i)if(tot<t&&a[i]!=R[i]&&a[i]==l)++a[i],++tot;
std::sort(a+1,a+n+1);
for(int i=1,j=1;i<=m;++i){
while(j<=n&&a[j]<i)++j;
lim[i]=std::min(t,lim[i-1]+n-j+1);
}
l=1,r=m;while(l<r)mid=(l+r+1)>>1,check(mid)?l=mid:r=mid-1;
if(!check(l))return puts("-1 -1"),0;
printf("%d %lld\n",l,b[1]);
return 0;
}


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

/*                                                     لا اله الا الله محمد رسول الله                                              */

#include <bits/stdc++.h>

#ifndef ONLINE_JUDGE

#include "Debug.cpp"

#else

#define debug(...) 1

#define Time(i, x...) x

#endif

using namespace std;

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

#define el '\n'

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

#define LL  long long

#define int LL

#define ld long double

#define un unsigned

#define Test unsigned int TC; cin >> TC; while(TC--)

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

#define NO cout<<"NO";

#define YES cout<<"YES";

#define FILE freopen("Input.txt", "r", stdin);

set<int>ans;

void fun() {

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

        ans.insert(i*i*i);

    }

}

void Solve() {

    int n;

    cin >> n;

    string s;

    cin >> s;

    int c = 0;

    bool x = 1;

    while (x){

        bool y = 0;

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

        if (s[i] == 'A' && s[i+1] == 'P')

            s[i+1] = 'A', y = 1, i++;

    }

        if (!y)x = !x;

        c++;

    }

    cout << c-1;

}

signed main() {

    sad;

//    FILE

    Test

    Solve(), cout << el;

}


C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries:   ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled.  ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can 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. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4

a
aa
a

cb
b
c

cOutputCopy? 1 2

? 3 4

? 4 4

! aabc

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

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

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

#define max(a,b) ((a)>(b)?(a):(b))

#define min(a,b) ((a)<(b)?(a):(b))

using namespace std;

char an[105];

struct cx{

	int len,tn[26];

}sp[105];

int tn[105][26],tn1[26],tn2[26];

bool zqr(cx a1,cx a2)

{

	return a1.len<a2.len;

}

void solve(int l)

{

	if(l==1)

	{

		printf("? %d %d\n",1,1);fflush(stdout);

		string s;cin>>s;

		an[1]=s[0];

		return;

	}

	multiset<vector<int> >aa;

	printf("? %d %d\n",1,l);fflush(stdout);

	fo(i,1,l*(l+1)>>1)

	{

		vector<int> tn(26,0);

		string s;cin>>s;

		for(auto xx:s)tn[xx-'a']++;

		aa.insert(tn);

	}

	printf("? %d %d\n",1,l-1);fflush(stdout);

	fo(i,1,l*(l-1)>>1)

	{

		vector<int> tn(26,0);

		string s;cin>>s;

		for(auto xx:s)tn[xx-'a']++;

		aa.erase(aa.find(tn));

	}

	int tot=0;

	for(auto xx:aa)

	{

		tot++;

		fo(i,0,25)sp[tot].len+=xx[i],sp[tot].tn[i]=xx[i];

	}

	sort(sp+1,sp+tot+1,zqr);

	fo(i,1,tot)

	{

		fo(j,0,25)if(sp[i].tn[j]-sp[i-1].tn[j])an[tot-i+1]=j+'a';

	}

}

int main()

{

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

	if(n==1)

	{

		printf("? %d %d\n",1,1);fflush(stdout);

		string s;cin>>s;

		printf("! %c",s[0]);fflush(stdout);

		return 0;

	}

	solve(n>>1);

	printf("? %d %d\n",1,n);

	fo(i,1,n*(n+1)>>1)

	{

		string s;cin>>s;

		int len=s.size();

		for(auto xx:s)tn[len][xx-'a']++;

	}

	fo(i,1,n-(n>>1))

	{

		fo(j,0,25)tn1[j]=tn[i][j]-tn[i-1][j];

		fo(j,0,25)tn2[j]=tn[i+1][j]-tn[i][j];

		fo(j,0,25)if(tn1[j]-tn2[j])

		{

			if(tn1[j]-tn2[j]==2)an[n-i+1]=j+'a';

			else if(j+'a'!=an[i])an[n-i+1]=j+'a';

		}

	}

	printf("! ");fo(i,1,n)putchar(an[i]);

	return 0;

}

//niceprob


D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that:  each array contains nn elements;  each element is an integer from 11 to mm;  for each array, there is exactly one pair of equal elements;  for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are:  [1,2,1][1,2,1];  [1,3,1][1,3,1];  [1,4,1][1,4,1];  [2,3,2][2,3,2];  [2,4,2][2,4,2];  [3,4,3][3,4,3].

#include<bits/stdc++.h>

using namespace std;

#define int long long

const int M=2e5+10;

const int MOD=998244353;

int fac[M],ifac[M],n,m;

int pw(int x,int y)

{

	if(y==0)

		return 1;

	int p=pw(x,y/2);

	if(y%2==1)

		return p*p %MOD *x %MOD;

	return p*p %MOD;

}

int modinv(int x)

{

	return pw(x,MOD-2);

}

int comb(int x,int y)

{

	return fac[x] * ifac[y] %MOD * ifac[x-y] %MOD;

}

void prec()

{

	fac[0]=1;

	ifac[0]=1;

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

	{

		fac[i]=fac[i-1]*i %MOD;

		ifac[i]=modinv(fac[i]);

	}

}

int32_t main()

{

	prec();

	cin>>n>>m;

	if(n==2)return cout<<0<<endl,0;

	cout<<comb(m,n-1) * (n-2) %MOD * pw(2,n-3) %MOD<<endl;

}


C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyber world.His target is a network of nn small gangs. This network contains exactly n−1n−1 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 00 to n−2n−2 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass SS password layers, with SS being defined by the following formula:S=∑1≤u<v≤nmex(u,v)S=∑1≤u<v≤nmex(u,v)Here, mex(u,v)mex(u,v) denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang uu to gang vv.Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of SS, so that the AIs can be deployed efficiently.Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible SS before he returns?InputThe first line contains an integer nn (2≤n≤30002≤n≤3000), the number of gangs in the network.Each of the next n−1n−1 lines contains integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n; ui≠viui≠vi), indicating there's a direct link between gangs uiui and vivi.It's guaranteed that links are placed in such a way that each pair of gangs will be connected by exactly one simple path.OutputPrint the maximum possible value of SS — the number of password layers in the gangs' network.ExamplesInputCopy3
1 2
2 3
OutputCopy3
InputCopy5
1 2
1 3
1 4
3 5
OutputCopy10
NoteIn the first example; one can achieve the maximum SS with the following assignment:  With this assignment, mex(1,2)=0mex(1,2)=0, mex(1,3)=2mex(1,3)=2 and mex(2,3)=1mex(2,3)=1. Therefore, S=0+2+1=3S=0+2+1=3.In the second example, one can achieve the maximum SS with the following assignment:  With this assignment, all non-zero mex value are listed below:   mex(1,3)=1mex(1,3)=1  mex(1,5)=2mex(1,5)=2  mex(2,3)=1mex(2,3)=1  mex(2,5)=2mex(2,5)=2  mex(3,4)=1mex(3,4)=1  mex(4,5)=3mex(4,5)=3 Therefore, S=1+2+1+2+1+3=10S=1+2+1+2+1+3=10.

#include <bits/stdc++.h>
#ifdef __LOCAL__
  #include <debug_local.h>
#endif
using namespace std;
const int mxN = 3005;
vector<int> ad[mxN];
int par[mxN][mxN], dist[mxN][mxN], sz[mxN][mxN];
long long dp[mxN][mxN];
void  dfs(int r, int u, int p) {
  par[r][u] = p;
  sz[r][u] = 1;
  for (int v : ad[u]) {
    if (v == p) continue;
    dist[r][v] = dist[r][u] + 1;
    dfs(r, v, u);
    sz[r][u] += sz[r][v];
  }
}
long long solve(int u, int v) {
  if (u == v) return 0LL;
  if (dp[u][v] != -1) return dp[u][v];
  long long &r = dp[u][v];
  int cur = dist[u][v];
  r = max(r, solve(u, par[u][v]) + 1LL * sz[u][v] * sz[v][u]);
  r = max(r, solve(par[v][u], v) + 1LL * sz[u][v] * sz[v][u]);
  return r;
}
void testCase() {
  int n;
  cin >> n;
  for (int i = 0; i < n - 1; i++) {
    int u, v;
    cin >> u >> v;
    ad[u].push_back(v);
    ad[v].push_back(u);
  }
  for (int i = 1; i <= n; i++) {
    dfs(i, i, i);
  }
  memset(dp, -1, sizeof dp);
  long long ans = 0;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
      ans = max(ans, solve(i, j));
    }
  }
  cout << ans << "\n";
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  testCase();
}


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

#include <bits/stdc++.h>

using namespace std;

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

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

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

#define ll long long

void file() {

    std::ios_base::sync_with_stdio(0);

    cin.tie(NULL);

    cout.tie(NULL);

}

int main() {

    file();

    int n;

    cin >> n;

    vector<int> v(n);

    for (auto &it: v)cin >> it;

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

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

        ll sum = 0;

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

            sum += v[l];

            mp[sum].emplace_back(l, r);

        }

    }

    vector<pair<int, int>> ans;

    for (auto it: mp) {

        int last = -1;

        vector<pair<int, int>> temp;

        for (auto it2: it.second) {

            if (it2.first > last) {

                temp.push_back(it2);

                last = it2.second;

            }

        }

        if (temp.size() > ans.size()) {

            ans = temp;

        }

    }

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

    for (auto it: ans)cout << it.first + 1 << " " << it.second + 1 << "\n";

}


G. Kuroni and Antihypetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni isn't good at economics. So he decided to found a new financial pyramid called Antihype. It has the following rules:  You can join the pyramid for free and get 00 coins.  If you are already a member of Antihype, you can invite your friend who is currently not a member of Antihype, and get a number of coins equal to your age (for each friend you invite). nn people have heard about Antihype recently, the ii-th person's age is aiai. Some of them are friends, but friendship is a weird thing now: the ii-th person is a friend of the jj-th person if and only if ai AND aj=0ai AND aj=0, where ANDAND denotes the bitwise AND operation.Nobody among the nn people is a member of Antihype at the moment. They want to cooperate to join and invite each other to Antihype in a way that maximizes their combined gainings. Could you help them? InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105)  — the number of people.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤2⋅1050≤ai≤2⋅105)  — the ages of the people.OutputOutput exactly one integer  — the maximum possible combined gainings of all nn people.ExampleInputCopy3
1 2 3
OutputCopy2NoteOnly the first and second persons are friends. The second can join Antihype and invite the first one; getting 22 for it.

#include <bits/stdc++.h>

#include <ext/random>

using namespace std;

//#define labeltc

#define endl "\n"

#define MAXN 262143

#define ll long long

#define MOD 1000000007

//#define MOD 998244353 //853?

#define INFLL 1000000000001000000LL

#define INFI 1001000000

#define pii pair<int,int>

#define pll pair<ll,ll>

#define fi first

#define sc second

#define m_p make_pair

#define p_b push_back

#define l_b lower_bound

#define u_b upper_bound

#define vi vector<int>

#define vll vector<ll>

#define sp(x) x << " "

#define rand_num(x,y) uniform_int_distribution<ll>((ll)x,(ll)y)(rng)

#define lsb(x) (x&(-x))

#define dgt(x) (x-'0')

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

#define pans(x) ((x)? "YES " : "NO ")

template<typename T> bool ckmin(T& a, const T& b) {return (a>b)? a = b, 1 : 0;}

template<typename T> bool ckmax(T& a, const T& b) {return (a<b)? a = b, 1 : 0;}

__gnu_cxx::sfmt19937 rng(std::chrono::steady_clock::now().time_since_epoch().count());

ll power(ll x, ll e, ll m = LONG_LONG_MAX){

    //e %= phi[m];

    ll r = 1;

    while(e>0){

        if(e%2) r = (r*x)%m;

        x = (x*x)%m;

        e >>= 1;

    }

    return r;

}

template <typename T, typename U>

ostream& operator<<(ostream& os, const pair<T,U>& v){

    os << sp(v.fi) << v.sc;

    return os;

}

template <typename T>

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

    for (int i = 0; i < v.size(); ++i) {os << sp(v[i]);}

    return os;

}

template <typename T>

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

    for (auto it : v) {os << sp(it);}

    return os;

}

template <typename T, typename U>

ostream& operator<<(ostream& os, const map<T,U>& v){

    for (auto it : v) {os << it << "\n";}

    return os;

}

void setIO(string s) {

    freopen((s+".in").c_str(),"r",stdin);

    freopen((s+".out").c_str(),"w",stdout);

}

int e[MAXN+1],ans,n;

ll cnt[MAXN+1];

void init(int x) {for (int i=0; i<=x; i++) e[i]=-1;}

int get(int x) { return e[x] < 0 ? x : e[x] = get(e[x]); }

bool same_set(int a, int b) { return get(a) == get(b); }

int size(int x) { return -e[get(x)]; }

bool unite(int x, int y) {

    x = get(x), y = get(y);

       if(x==y) return false;

    if (e[x] > e[y]) swap(x, y);

       e[x] += e[y]; e[y] = x;

       return true;

}

void precomp(){

    return;

}

void solve(int tc){

    #ifdef labeltc

    cout << "Test case " << tc << ": ";

    #endif

    init(MAXN);

    cin >> n;

    ll ans = 0;

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

        int a; cin >> a;

        ans -= a;

        cnt[a]++;

    }

    cnt[0]++;

    for (int i=MAXN; ~i; i--){

        for (int j=i; 1; j=(j-1)&i){

            if(cnt[j]*cnt[i^j]){

                if(unite(j,i^j)){

                    ans += (cnt[j]+cnt[i^j]-1)*i;

                    cnt[j] = 1;

                    cnt[i^j] = 1;

                }

            }

            if(!j) break;

        }

    }

    cout << ans << endl;

    return;

}

int main(){

    //setIO();

    ios_base::sync_with_stdio(0);

    cin.tie(NULL);

    precomp();

    int t=1;

    //cin >> t;

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

    return 0;

}


B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold:  Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments.  The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees.  The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES


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.

#include<bits/stdc++.h>

using namespace std;

//#define int long long

string s;

vector <vector <int> > tree;

bool flag = true;

void build(int v, int l, int r)

{

	if(l == r)

	{

		tree[v][s[l] - 'a'] = 1;

	}

	else

	{

		build(v * 2, l, (r + l) / 2);

		build(v * 2 + 1, (r + l) / 2 + 1, r);

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

		{

			tree[v][i] = tree[v * 2][i] + tree[v * 2 + 1][i];

		}

	}

}

vector <int> ans(int v, int l, int r, int al, int ar)

{

	if(l >= al && r <= ar)

	{

		return tree[v];

	}

	else if(ar <= (r + l) / 2)

	{

		return ans(v * 2, l, (r + l) / 2, al, ar);

	}

	else if(al > (r + l) / 2)

	{

		return ans(v * 2 + 1, (r + l) / 2 + 1, r, al, ar);

	}

	else

	{

		vector <int> v1 = ans(v * 2, l, (r + l) / 2, al, ar);

		vector <int>  v2 = ans(v * 2 + 1, (r + l) / 2 + 1, r, al, ar);

		vector <int> v(26);

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

		{

			v[i] = v1[i] + v2[i];

		}

		return v;

	}

}

main () {

	ios_base::sync_with_stdio(false);

	cin.tie(NULL);

	cout.tie(NULL);

	cin >> s;

	int n = s.size();

	tree.resize(n * 4, vector <int> (26));

	build(1, 0, n - 1);

	int q;

	cin >> q;

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

	{

		int l, r;

		cin >> l >> r;

		if(l == r)

		{

			cout << "Yes\n";

			continue;

		}

		vector <int>  v = ans(1, 0, n - 1, l - 1, r - 1);

		int cnt = 0;

		int cnt1 = 0;

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

		{

			if(v[j] != 0)

			{

				cnt++;

			}

			if(v[j] >= 2)

			{

				cnt1++;

			}

		}

		if(cnt  >= 3)

		{

			cout << "Yes\n";

		}

		else if(cnt == 1)

		{

			cout << "No\n";

		}

		else if(cnt == 2)

		{

			if(s[l - 1] == s[r -1 ])

			{

				cout << "No\n";

			}

			else

			{

				cout << "Yes\n";

			}

		}

	}

    return 0;

}


C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105)  — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5
3 1
3 2
3 3
4 0
5 2
OutputCopy4
5
6
0
12
NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement.


#include <bits/stdc++.h>

#define ll long long

#define ld long double

using namespace std;

int main(){

    ll t = 1;

    cin >> t;

    while (t--) {

            bool flag = true;

        string a, b, c;

        cin >> a >> b >> c;

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

            if (c[i] == a[i] or c[i] == b[i]) {

                continue;

            }

            else {

                flag = false;

                break;

            }

        }

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

    }

    return 0;

}


D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3
3 <<
7 >><>><
5 >>><
OutputCopy1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.

#include <bits/stdc++.h>

using namespace std;

#define ll long long

#define mod 1e9 + 7

void solve(){

    int n;

    string s;

    cin >> n >> s;

    vector<int> res(n);

    int unused = n, start = 0;

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

        if(i == n - 1 || s[i] == '>'){

            for(int j=i; j>=start; --j){

                res[j] = unused;

                unused--;

            }

            start = i + 1;

        }

    }

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

        cout << res[i] << (i == n - 1? "\n": " ");

    }

    unused = 1, start = 0;

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

        if(i == n - 1 || s[i] == '<'){

            for(int j=i; j>=start; --j){

                res[j] = unused;

                unused++;

            }

            start = i + 1;

        }

    }

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

        cout << res[i] << (i == n - 1? "\n": " ");

    }

}

int main(){

    ios_base::sync_with_stdio(false);

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

//#ifndef ONLINE_JUDGE

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

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

//#endif

    ll t = 1;

    cin >> t;

    while(t--){

        solve();

    }

    return 0;

}