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.


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

}


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

#include<bits/stdc++.h>

#define deq deque<int

#define vec vector<int

#define pb push_back

#define pf push_front

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

using namespace std;

using ll = long long;

using ull = unsigned long long;

int main() {

	sonic;

	int t;

	cin >> t;

	while (t --) {

		int n;

		cin >> n;

		int a[n];

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

			cin >> a[i];

		}

		bool ok = false;

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

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

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

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

						ok = true;

					}

				}

			}

		}

		if (ok) {

			cout << "YES\n";

		}

		else {

			cout << "NO\n";

		}

	}

}


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

#include<bits/stdc++.h>

#define Cn const

#define CI Cn int&

#define N 800

using namespace std;

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

int Q(vector<int> v)

{

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

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

}

int main()

{

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

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

	{

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

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

	}

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

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

	{

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

		{

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

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

		}

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

		{

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

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

		}

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

		{

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

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

		}

	}

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

}


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

                                        //  ॐ

#include <bits/stdc++.h>

using namespace std;

#define PI 3.14159265358979323846

#define ll long long int

int main(){

    ios_base::sync_with_stdio(false);

    cin.tie(0);

    cout.tie(0);

   int test = 1;

   // cin>>test;

   while(test--){

                int n;

                cin>>n;

                int a[n+1];

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

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

                     cin>>a[i];

                }

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

                     int curr=0;

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

                         curr+=a[j];

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

                     }

                }

                int opt;

                int blocks=0;

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

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

                       int st=0;

                       int mx=0;

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

                          if(i>st){

                              mx++;

                              st=j;

                          }

                       }

                       if(mx>blocks){

                           blocks=mx;

                           opt=sum;

                       }

                }

                cout<<blocks<<'\n';

                auto vec=mp[opt];

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

                int st=0;

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

                       if(i>st){

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

                          st=j;

                       }

                }

                // cout<<"\n";

   }

    return 0;

}


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

#include <bits/stdc++.h>

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

using namespace std;

#define ll long long

#define lld long double

const lld pi = 3.14159265358979323846;

#define pb push_back

#define pf push_front

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

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

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

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

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

const int N=1e5+7;

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

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

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

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

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

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

out[node]=(++tick);

}

void build_sparse()

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

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

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

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

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

}

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

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

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

}

int get_LCA(int x,int y)

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

if(x==y)return x;

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

return par[p.second];

}

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

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

int main()

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

cin>>n;

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

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

  adj[a].pb(b);

  adj[b].pb(a);

}

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

int q;cin>>q;

while(q--){

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

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

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

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

  int path2=min(d1,d2);

  int dist=2e9;

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

    dist=path2;

  }

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

    dist=path1;

  }

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

    dist=min(path1,path2);

  }

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

}

    return 0;

}

/*

*/


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

#include<bits/stdc++.h>

using namespace std;

typedef long long ll;

struct node

{

	int tx, ty;

};

bool cmp(node a, node b)

{

	if(a.ty==b.ty)

	{

		return a.tx<b.tx;

	}

	else return a.ty<b.ty;

}

int n, flag;

int main()

{

	ios::sync_with_stdio(0);

	cin.tie(0);

	cout.tie(0);

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

	string ans;

	cin>>T;

	while(T--)

	{

		vector<node>vtr;

		cin>>n;

		flag = 1;

		ans = "";

		nowx = nowy = 0;

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

		{

			cin>>x>>y;

			vtr.push_back({x, y});

		}

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

		sz = vtr.size();

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

		{

			nx = vtr[i].tx;

			ny = vtr[i].ty;

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

			{

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

				{

					ans += 'R';

				}

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

				{

					ans += 'U';

				}

			}

			else

			{

				flag = 0;

				break;

			}

			nowx = nx;

			nowy = ny;

		}

		if(!flag)

		{

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

		}

		else

		{

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

			cout<<ans<<"\n";

		}

	}

	return 0;

}


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

// Problem: C. Fadi and LCM

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

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

// Memory Limit: 256 MB

// Time Limit: 1000 ms

//

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

#include<bits/stdc++.h>

using namespace std;

typedef long long int       ll;

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

int main()

{

	//ios_base::sync_with_stdio(0);

	//cin.tie(0);

  	ll n;

	cin >> n;

	ll a=0,b=0;

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

		if(n%i==0){

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

				a=i;

				b=n/i;

			}

		}

	}

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

	return 0;

}


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

#include<bits/stdc++.h>

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


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

#include <bits/stdc++.h>

using namespace std;

#define pi (3.141592653589)

#define mod 1000000007

#define float double

#define pb push_back

#define mp make_pair

#define ff first

#define ss second

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

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

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

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

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

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

#define ll long long

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

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

typedef vector<ll> vll;

typedef map<ll, ll> mll;

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

bool isPrime(int n){

if(n==1) return false;

if(n==2) return true;

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

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

}

return true;

}

ll mod_mul(ll a, ll b){

a = a % mod;

b = b % mod;

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

}

ll mod_add(ll a, ll b){

a = a % mod;

b = b % mod;

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

}

int main(){

fast

int t=1;

cin>>t;

while(t!=0){

	ll n,m;

	cin>>n>>m;

	string s;

	cin>>s;

	vll v(m);

	map<ll,ll> p;

	foi(m)

	{

		cin>>v[i];

	}

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

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

	{

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

	}

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

	foi(v.size())

	{

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

		{

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

			j++;

		}

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

		{

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

			{

				i++;

				k--;

			}

		}

		k--;

	}

	foi(26)

	{

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

		{

			cout<<0<<" ";

		}

		else

		{

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

		}

	}

	cout<<endl;

t--;

}

return 0;

}


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

#include <iostream>

#include <bits/stdc++.h>

using namespace std;

int t, x;

void Solve() {

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

        cin >> x;

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

    }

}

int main()

{

    ios_base::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    cin >> t;

    Solve();

    return 0;

}


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

#include <bits/stdc++.h>

typedef long long ll;

typedef long double ld;

using namespace std;

#include <ext/pb_ds/assoc_container.hpp>

using namespace __gnu_pbds;

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

tree_order_statistics_node_update> indexed_set;

#define endl '\n'

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

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

    if(l==r){

        t[i]=-1;

    }

    else{

        int mid=(l+r)/2;

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

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

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

    }

}

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

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

        t[i]=max(t[i],val);

    }

    else{

        int mid=(tl+tr)/2;

        if(mid>=l){

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

        }

        if(mid+1<=r){

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

        }

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

    }

}

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

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

        return t[i];

    }

    else{

        int mid=(tl+tr)/2;

        ll k=27;

        if(mid>=l){

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

        }

        if(mid+1<=r){

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

        }

        return k;

    }

}

int main(){

#ifndef ONLINE_JUDGE

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

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

#endif

	clock_t time_req=clock();

	ilihg;

	int t=1;

    // cin>>t;

    while(t--){

       	int n;

       	cin>>n;

       	string s;

       	cin>>s;

       	int a[n];

       	int k=0;

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

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

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

       		int l=0;

       		int r=n-1;

       		while(l<r){

       			int m=(l+r)/2;

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

       				r=m;

       			}

       			else{

       				l=m+1;

       			}

       		}

       		k=max(k,l+1);

       		a[i]=l+1;

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

       	}

       	cout<<k<<endl;

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

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

       	}

       	cout<<endl;

    }

#ifndef ONLINE_JUDGE

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

#endif

}


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

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

#include <bits/stdc++.h>

using namespace std;

#define ll                    long long

#define PI                    3.141592653589793

#define MOD                     1000000007

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

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

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

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

#include<ext/pb_ds/assoc_container.hpp>

#include<ext/pb_ds/tree_policy.hpp>

using namespace std;

using namespace __gnu_pbds;

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

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

void  solve(){

   ll n;

   cin>>n;

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

   pbds s;

   fl(0,n)

    cin>>v1[i];

   fl(0, n)

    cin>>v2[i];

    ll ans = 0;

    fl(0, n){

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

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

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

    }

    cout<<ans<<endl;

}

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

int32_t main() {

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

   ll t=1;

	// cin>>t;

	while(t--){

      solve();

  }

}


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

#include <bits/stdc++.h>

//#pragma GCC optimize ("Ofast")

//#pragma GCC target ("avx2")

using namespace std;

#define MOD 1000000007

#define MOD2 998244353

#define MAXN 20000001

#define INF 2e9

#define INF2 1e18

#define ll long long

#define nl '\n'

#define pb push_back

#define pf push_front

#define fi first

#define se second

typedef pair<int,int> pii;

typedef pair<ll,ll> pll;

int main() {

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    int t;cin >> t;

    ll a,b;

    while(cin >> a >> b){

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

    }

}


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

#include <bits/stdc++.h>

#include<unordered_set>

#include<unordered_map>

#include<algorithm>

#include<iostream>

#include<map>

#include<set>

#include<string>

using namespace std;

#define int long long

const int N = 1e7 + 10;

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

const int mod = 998244353;

#define ll long long

#define endl '\n'

bool flag = false;

int cnt = 0;

#define endl '\n'

int ans = 0, p;

int d;

int qp(int a, int b) {

    int res = 1;

    int q = a;

    while (b) {

        if (b & 1) {

            res *= q; res %= mod;

        }

        b >>= 1;

        q *= q;

        q %= mod;

    }

    return res;

}

void solve()

{

    int h, r;

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

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

    int t = 0;

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

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

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

            int time = t - j;

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

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

                k=1;

            }

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

            time--;

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

                k = 1;

            }

            else k = 0;

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

        }

        t+= a[i];

    }

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

}

signed main()

{

    ios::sync_with_stdio(false);

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

    T = 1;

    //cin >> T;

    while (T--)solve();

}


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

#include <bits/stdc++.h>

using namespace std;

const int mx = 6e5 + 5;

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

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

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

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


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

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

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

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


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

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


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

#include <iostream>

//#include <deque>

#include <vector>

using namespace std;

//vector <string> vec_s;

int main() {

    int t; cin >> t;

//    bool f = true;

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

        int n; cin >> n;

        string s; cin >> s;

        int p = 0, ans = 0;

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

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

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

        }

        cout << ans << '\n';

    }

    return 0;

}


#include<bits/stdc++.h>

using namespace std;

int main(){

int t,n;

cin>>t;

int k[t];

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

cin>>k[i];

string s;

cin>>s;

int maxi=0;

int sum=0;

int flag=0;

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

{

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

            flag=1;

            if(sum>maxi){

                maxi=sum;

            }

                sum=0;

        }

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

            sum++;

        }

    }

    if(sum>maxi){

        maxi=sum;

        sum=0;

    }

    cout<<maxi<<endl;

}

return 0;

}

// }


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

#include <bits/stdc++.h>

using namespace std;

#define pb push_back

#define ub upper_bound

#define lb lower_bound

#define ll long long

#define ld long double

#define pii pair<ll, ll>

typedef __int128 lll;

typedef vector<ll> vi;

typedef vector<vi> vvi;

typedef vector<pii> vpi;

typedef set<ll> si;

typedef map<ll, ll> mii;

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

const int M = 1e9+7;

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

void solve(){

	ll n,d;

	cin>>n>>d;

	if(d<=n)

	{

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

	}

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

	{

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

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

		if(curr<=n)

		{

			cout<<"YES"<<endl;

			return;

		}

	}

	cout<<"NO"<<endl;

}

int main()

{

	ios_base::sync_with_stdio(false);

	cin.tie(NULL);

#ifndef ONLINE_JUDGE

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

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

#endif

	ll t=1;

	cin>>t;

	while(t--)

	{

		solve();

	}

}


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

#include<bits/stdc++.h>

using namespace std;

int main()

{

    #ifndef ONLINE_JUDGE

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

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

    #endif

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

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

    else

    {

        cout << "YES\n";

        vector<string>moves;

        vector<pair<int,string>>finalMoves;

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

        {

            if(i == 0)

            {

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

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

            }

            else

            {

                moves.push_back("D");

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

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

            }

        }

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

        for(auto &i : moves)

        {

            if(k == 0) break;

            if(k >= i.size())

            {

                k -= i.size();

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

                {

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

                }

                else

                {

                    finalMoves.push_back({1, i});

                }

            }

            else

            {

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

                k = 0;

            }

        }

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

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

    }

}