C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6
LRLRRLL
L
LLR
RRRR
LLLLLL
R
OutputCopy3
2
3
1
7
1
NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right.

/*  بسم الله الرحمن الرحيم  */
#include <bits/stdc++.h>
using namespace std;
#define Ma3rof ios_base::sync_with_stdio(false);cin.tie(NULL);
void solve() {
    string s;
    cin >> s;
    vector<int> v;
    v.push_back(0);
    for (int i = 0; i < s.size(); ++i) {
        if (s[i] == 'R') {
            v.push_back(i + 1);
        }
    }
    v.push_back(s.size() + 1);
    int ans = 0;
    for (int i = 0; i < v.size() - 1; ++i) {
        ans = max(ans, v[i + 1] - v[i]);
    }
    cout << ans << '\n';
}
signed main() {
    Ma3rof
    int t = 1;
    cin >> t;
    while (t--) {
        /*       وما تدري نفس ماذا تکسب غدا وما تدري نفس باي ارض تموت      */
        solve();
    }
    return 0;
}


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

#include<bits/stdc++.h>

using namespace std;

#define ll long long

#define N 101

#define bas (133)

#define yu (998244353)

ll n;

inline void ask(ll x,ll y){

	cout<<"? "<<x<<' '<<y<<'\n';

	cout.flush();

	return ;

}

string s1[N*N/2],s2[N*N/2];

char ans[N];

ll hs1[N*N/2],hs2[N*N/2];

bool vis[N*N/2];

ll p[N],len[N*N/2],cn=0;

inline bool cmp(ll x,ll y){return len[x]<len[y];}

int main()

{

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

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

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

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

	cin>>n;if(n==1){

		ask(1,1);

		cin>>s1[0];

		cout<<"! "<<s1[0]<<'\n';

		return 0;

	}

	ask(1,n);

	ll cnt[N];

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

		cin>>s1[i];memset(cnt,0,sizeof(cnt));

		for(int j=0;j<s1[i].size();j++)cnt[s1[i][j]-'a']++;

		for(int j=0;j<26;j++)hs1[i]=(hs1[i]*bas+cnt[j])%yu;

	}ask(1,n-1);

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

		cin>>s2[i];memset(cnt,0,sizeof(cnt));

		for(int j=0;j<s2[i].size();j++)cnt[s2[i][j]-'a']++;

		for(int j=0;j<26;j++)hs2[i]=(hs2[i]*bas+cnt[j])%yu;

	}

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

		for(int j=1;j<=n*(n+1)/2;j++){

			if(vis[j])continue;

			if(hs2[i]==hs1[j]){

				vis[j]=1;break;

			}

		}

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

		if(vis[i])continue;p[++cn]=i;len[i]=s1[i].length();

	}sort(p+1,p+cn+1,cmp);

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

		memset(cnt,0,sizeof(cnt));

		ll o=p[j];for(int g=0;g<s1[o].length();g++)cnt[s1[p[j]][g]-'a']++;

		if(j>1)for(int g=0;g<s1[p[j-1]].length();g++)cnt[s1[p[j-1]][g]-'a']--;

		for(int g=0;g<26;g++)if(cnt[g])ans[cn-j+1]=g+'a';

	}cout<<"! ";for(int i=1;i<=n;i++)cout<<ans[i];

	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

#pragma GCC target("arch=skylake")

#pragma GCC optimize("O3")

#include <bits/stdc++.h>

#include<ext/pb_ds/tree_policy.hpp>

#include<ext/pb_ds/assoc_container.hpp>

using namespace std;

using namespace __gnu_pbds;

typedef long long ll;

typedef double ld;

typedef tree< ll , null_type , less < ll > , rb_tree_tag , tree_order_statistics_node_update > ordered_set;

#define pii pair < int , int >

#define pll pair< ll , ll >

#define pb push_back

#define S second

#define F first

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

#define int ll

#define itn ll

const ll N = 5e5 + 123;

const ll mod = 998244353;

const ll INF = 1e18;

const ld eps = 5e-11;

vector< int > g[N];

int tin[N] , tout[N];

int up[N][30];

int t , h[N] , H;

void dfs( int v , int pr = 1 )

{

    cerr << v << '\n';

    H ++;

    h[v] = H;

	tin[v] = ++ t;

	up[v][0] = pr;

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

    {

//        cerr << i << '\n';

        up[v][i] = up[up[v][i - 1]][i - 1];

    }

//    cerr << v << '\n';

	for( auto to : g[v] )

    {

		if( to != pr )

        {

            dfs( to , v );

        }

	}

	tout[v] = ++ t;

	-- H;

}

bool upper( int a , int b )

{

	return tin[a] <= tin[b] && tout[a] >= tout[b];

}

int lca( int a , int b )

{

	if( upper( a , b ) )

    {

        return a;

    }

	if( upper( b , a ) )

    {

        return b;

    }

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

	{

	    if ( !upper( up[a][i] , b ) )

        {

            a = up[a][i];

        }

	}

	return up[a][0];

}

int len( int v , int u )

{

    int lc = lca( v , u );

//    cout << v << ' ' << u << ' ' << lc << '\n';

//

//    cout << h[v] << ' ' << h[u] << ' ' << h[lc] << "\n\n";

    return h[v] + h[u] - 2 * h[lc];

}

int32_t main()

{

    ios_base::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    #ifdef LOCAL

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

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

    #else

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

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

    #endif

    int n;

    cin >> n;

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

    {

        int v , u;

        cin >> v >> u;

        g[v].pb( u );

        g[u].pb( v );

    }

    dfs( 1 );

    int q;

    cin >> q;

    while( q -- )

    {

        int x , y , a , b , k;

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

        bool f = 0;

        int l1 = len( a , b );

        int l2 = len( a , x ) + 1 + len( b , y );

        int l3 = len( b , x ) + 1 + len( a , y );

//        cout << l1 << ' ' << l2 << ' ' << l3 << '\n';

        if( ( l1 <= k && l1 % 2 == k % 2 ) || ( l2 <= k && l2 % 2 == k % 2 )  || ( l3 <= k && l3 % 2 == k % 2 ) )

        {

            cout << "YES\n";

        }

        else

        {

            cout << "NO\n";

        }

    }

}


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

#include<bits/stdc++.h>

using namespace std;

typedef long long ll;

ll base = 1000000;

ll num[200001];

int main()

{

	ios::sync_with_stdio(0);

	cin.tie(0);

	cout.tie(0);

	ll T, n, len, ans, l, r, tmp;

	string s;

	cin>>T;

	while(T--)

	{//

		map<ll, ll>mp;

		cin>>n;

		cin>>s;

		len = s.length();

		ans = 1e9;

		//两个标准, x, y, 找两个标准都相同高度位置记录

		mp[0] = -1;

		for(ll i=0;i<=len-1;++i)

		{

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

			{

				num[i+1] = num[i] + base;

			}

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

			{

				num[i+1] = num[i] - base;

			}

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

			{

				num[i+1] = num[i] + 1;

			}

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

			{

				num[i+1] = num[i] - 1;

			}

			tmp = mp[num[i+1]];

			if(tmp==0)

			{

				mp[num[i+1]] = i+1;

			}

			else

			{

				if(tmp==-1)

				{

					tmp = 0;

				}

				if(ans>i+1-tmp)

				{

					ans = (i+1)-tmp;

					l = tmp+1;

					r = i+1;

				}

				mp[num[i+1]] = i+1;

			}

		}

		if(ans==1e9)

		{

			cout<<-1<<"\n";

		}

		else

		{

			cout<<l<<" "<<r<<"\n";

		}

	}

	return 0;

}


C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4
7 5 5 7
OutputCopy5.666666667
5.666666667
5.666666667
7.000000000
InputCopy5
7 8 8 10 12
OutputCopy7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
InputCopy10
3 9 5 5 1 7 5 3 8 7
OutputCopy3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence.

#include <bits/stdc++.h>

using namespace std;

const int N = 1e6 + 5;

typedef long long ll;

inline int read() {

	register int s = 0, f = 1; register char ch = getchar();

	while (!isdigit(ch)) f = (ch == '-' ? -1 : 1), ch = getchar();

	while (isdigit(ch)) s = (s * 10) + (ch & 15), ch = getchar();

	return s * f;

}

inline int min_(int a, int b) {

	return a < b ? a : b;

}

inline int max_(int a, int b) {

	return a > b ? a : b;

}

struct node {

	int l, r;

	long long sum;

	inline node(int L, int R, long long S) : l(L), r(R), sum(S) { }

	inline node() { }

	inline void merge(const node& c) {

		l = min_(l, c.l);

		r = max_(r, c.r);

		sum += c.sum;

	}

	inline bool operator > (const node &c) {

		return 1.0 * sum / (r - l + 1) > 1.0 * c.sum / (c.r - c.l + 1);

	}

	inline bool operator < (const node &c) {

		return 1.0 * sum / (r - l + 1) < 1.0 * c.sum / (c.r - c.l + 1);

	}

} stk[N];

int n, a[N], top;

double b[N];

long long sum[N];

int main() {

	n = read();

	for (int i = 1; i <= n; ++i) a[i] = read(), sum[i] = sum[i - 1] + a[i];

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

		node tmp = node(i, i, a[i]);

		while (top && stk[top] > tmp) tmp.merge(stk[top--]);

		stk[++top] = tmp;

	}

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

		for (int j = stk[i].l; j <= stk[i].r; ++j)

			printf("%.9lf\n", 1.0 * (sum[stk[i].r] - sum[stk[i].l - 1]) / (stk[i].r - stk[i].l + 1));

	return 0;

}


C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation:   z=acacez=acace (if we choose subsequence aceace);  z=acbcdz=acbcd (if we choose subsequence bcdbcd);  z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3
aabce
ace
abacaba
aax
ty
yyt
OutputCopy1
-1
3

#include <bits/stdc++.h>

using namespace std;

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

typedef long long int ll;

const int N = 1e5+9;

void solve()

{

    string s1, s2;

    cin >> s1 >> s2;

    map<char, vector<int>> mp;

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

    {

        mp[s1[i]].push_back(i+1);

    }

    int cnt = 1, val = 1;

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

    {

        if(mp.find(s2[i]) == mp.end())

        {

            cout << -1 << "\n";

            return;

        }

        else

        {

            auto pos = lower_bound(mp[s2[i]].begin(), mp[s2[i]].end(), val);

            if(pos == mp[s2[i]].end())

            {

                cnt++;

                val = *lower_bound(mp[s2[i]].begin(), mp[s2[i]].end(), 0)+1;

            }

            else

            {

                val = *pos+1;

            }

            //cout << val << "\n";

        }

    }

    cout << cnt << "\n";

}

int main()

{

    FAST;

    int t = 1, cs = 1;

    cin >> t;

    while(t--)

    {

        //cout << "Case " << cs++ << ":\n";

        solve();

    }

    return 0;

}


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

//DEEPANSHU SONKAR

//2113092

#include<bits/stdc++.h>

#define turbo()                                                                \

    ios_base::sync_with_stdio(0);                                              \

    cin.tie(0);                                                                \

    cout.tie(0);

#define ll long long

const ll mod=1000000007;

const ll INF= 1e9+7;

#define pb push_back

#define pp pop_back

#define mp make_pair

#define pf push_front

#define vll vector<ll>

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

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

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

#define vsort(vec) sort(vec.begin(),vec.end());

#define rvsort(vec) sort(vec.begin(),vec.end(),greater<int>());

#define tc() long long int t;cin>>t;while(t--)

#define rep(var,start,to) for(ll var=start;var<to;var++)

#define rep1(a, b, c) for (ll a = b; a >= c; a--)

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

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

#define google cout<<"Case #"<<i+1<<": ";

using namespace std;

bool isprime(int n) {

  bool f = true;

  if (n == 0 || n == 1) {

    f = false;

  }

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

    if (n % i == 0) {

      f = false;

      break;

    }

  }

  return f;

}

void codingkarlo_BC(){

    string s;cin>>s;

    vector<int> x,x1;

    vector<int> ans;

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

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

            x.pb(i+1);

        }

        else{

            x1.pb(i+1);

        }

    }

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

    for(int i=0;i<min(x.size(),x1.size());i++){

        if(x[i]>x1[i]){

            break;

        }

        else{

            ans.pb(x[i]);

            ans.pb(x1[i]);

        }

    }

    if(ans.size()==0){

        cout<<0<<endl;

    }

    else{

        cout<<1<<endl;

        vsort(ans);

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

        print(ans,ans.size());

    }

  }

signed main()

{

    turbo()

    codingkarlo_BC();

   //tc(){ codingkarlo_BC(); /*google*/ }

    return 0;

}


/*

_/      _/       _/_/_/      _/      _/    _/           _/_/_/_/_/

 _/    _/      _/      _/     _/    _/     _/           _/

  _/  _/      _/               _/  _/      _/           _/

   _/_/       _/                 _/        _/           _/_/_/_/

  _/  _/      _/                 _/        _/           _/

 _/    _/      _/      _/        _/        _/           _/

_/      _/       _/_/_/          _/        _/_/_/_/_/   _/_/_/_/_/

*/

#include <bits/stdc++.h>

#define ll long long

#define lc(x) ((x) << 1)

#define rc(x) ((x) << 1 | 1)

#define ru(i, l, r) for (int i = (l); i <= (r); i++)

#define rd(i, r, l) for (int i = (r); i >= (l); i--)

#define mid ((l + r) >> 1)

#define pii pair<int, int>

#define mp make_pair

#define fi first

#define se second

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

#define maxn 1000005

using namespace std;

inline int read() {

	int x = 0, w = 0; char ch = getchar();

	while(!isdigit(ch)) {w |= ch == '-'; ch = getchar();}

	while(isdigit(ch)) {x = x * 10 + ch - '0'; ch = getchar();}

	return w ? -x : x;

}

int n; ll a[maxn]; int sta[maxn], top;

int chk(int x, int y, int z) {

	return (ll)(a[z] - a[y]) * (z - x) <= (ll)(a[z] - a[x]) * (z - y);

}

int main() {

	n = read();

	ru(i, 1, n) a[i] = read() + a[i - 1];

	ru(i, 1, n) {

		while(top > 0 && chk(sta[top - 1], sta[top], i)) top--;

		sta[++top] = i;

	}

//	ru(i, 1, top) printf("%d ", sta[i]); printf("\n");

	ru(i, 1, top) {

		ru(j, sta[i - 1] + 1, sta[i]) {

			printf("%.10f\n", (double)(a[sta[i]] - a[sta[i - 1]]) / (sta[i] - sta[i - 1]));

		}

	}

	return 0;

}


A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. Next 2t2t lines contain a description of test cases  — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100)  — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11:   On day one, move a haybale from pile 33 to pile 22  On day two, move a haybale from pile 33 to pile 22  On day three, move a haybale from pile 22 to pile 11  On day four, move a haybale from pile 22 to pile 11  On day five, do nothing  In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.

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

using namespace std;

int a[105];

int main()

{

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

    int t,n,k;

    cin>>t;

    while(t--)

    {

        cin>>n>>k;

        int sum=0,ans=0;

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

        {

            cin>>a[i];

            if(i>1&&k>0)

            {

                sum=min(k/(i-1),a[i]);

                ans+=sum;

                k-=(i-1)*a[i];

            }

            if(i==1) ans+=a[i];

        }

        cout<<ans<<'\n';

    }

    return 0;

}


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

/*

ID: armaan48

LANG: C++

*/

#include <bits/stdc++.h>

using namespace std;

#define int long long

#define mod 1000000007

#define mod2 998244353

#define endl '\n'

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

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

#define print(x) {for(auto v: x) {cout << v<< ' ';} cout << endl;}

#define printp(x) {for(auto v: x) {cout << v.first << ':' << v.second << ' ';} cout << endl;}

signed main()

{

    ios_base::sync_with_stdio(false);

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

    int n; cin >> n;

    string s; cin >> s;

    int t = 2;

    int org = n;

    while (1){

        n = sz(s);

        int f = 1;

        for (int i=25;i>=0;i--){

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

                if ((s[j] - 'a')!=i)

                    continue;

                if ((j-1>=0 and (s[j-1]-'a')+1==i) or (j+1<n and (s[j+1]-'a')+1==i)){

                    f=0;

                    s = s.substr(0,j) + s.substr(j + 1);

                    break;

                }

            }

            if (!f){

                break;

            }

        }

        if (f){

            break;

        }

    }

    cout <<  org- sz(s) << endl;

    return 0;

}


D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai≤eaisai≤eai) and [sbi,ebi][sbi,ebi] (sbi≤ebisbi≤ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)≤min(y,v)max(x,u)≤min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1≤n≤1000001≤n≤100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1≤sai,eai,sbi,ebi≤1091≤sai,eai,sbi,ebi≤109, sai≤eai,sbi≤ebisai≤eai,sbi≤ebi).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2
1 2 3 6
3 4 7 8
OutputCopyYES
InputCopy3
1 3 2 4
4 5 6 7
3 4 5 5
OutputCopyNO
InputCopy6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
OutputCopyYES
NoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist.

#include<bits/stdc++.h>

typedef long long ll;

typedef unsigned long long ull;

using namespace std;

const ll mod = 1e11;

const int mm = 2e5 + 10;

struct node{

	ll p,id,k;

	node(){}

	node(ll p,ll id,ll k):p(p),id(id),k(k){}

	friend bool operator < (node a,node b){

		return a.p==b.p?a.k<b.k:a.p<b.p;

	}

}a1[mm],a2[mm];

ull s[mm],val[mm];

int main() {

	std::ios::sync_with_stdio(false);

	std::cin.tie(0);

	std::cout.tie(0);

	srand(time(NULL));

	int n;

	cin>>n;

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

		val[i]=(ull)(rand()<<31|rand());

		ll x,y,z,w;

		cin>>x>>y>>z>>w;

		a1[i*2-1]=node(x,i,0);

		a1[i*2]=node(y,i,1);

		a2[i*2-1]=node(z,i,0);

		a2[i*2]=node(w,i,1);

	}int N=n*2;

	sort(a1+1,a1+1+N);

	sort(a2+1,a2+1+N);

	ll Xor=0;

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

		if(a1[i].k)Xor^=val[a1[i].id];

		else s[a1[i].id]^=Xor;

	}Xor=0;

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

		if(!a1[i].k)Xor^=val[a1[i].id];

		else s[a1[i].id]^=Xor;

	}Xor=0;

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

		if(a2[i].k)Xor^=val[a2[i].id];

		else s[a2[i].id]^=Xor;

	}Xor=0;

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

		if(!a2[i].k)Xor^=val[a2[i].id];

		else s[a2[i].id]^=Xor;

	}

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

		if(s[i]>0){

			cout<<"NO";

			return 0;

		}

	}cout<<"YES";

}


E. Treeland and Virusestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are nn cities in Treeland connected with n−1n−1 bidirectional roads in such that a way that any city is reachable from any other; in other words, the graph of cities and roads is a tree. Treeland is preparing for a seasonal virus epidemic, and currently, they are trying to evaluate different infection scenarios.In each scenario, several cities are initially infected with different virus species. Suppose that there are kiki virus species in the ii-th scenario. Let us denote vjvj the initial city for the virus jj, and sjsj the propagation speed of the virus jj. The spread of the viruses happens in turns: first virus 11 spreads, followed by virus 22, and so on. After virus kiki spreads, the process starts again from virus 11.A spread turn of virus jj proceeds as follows. For each city xx not infected with any virus at the start of the turn, at the end of the turn it becomes infected with virus jj if and only if there is such a city yy that: city yy was infected with virus jj at the start of the turn; the path between cities xx and yy contains at most sjsj edges; all cities on the path between cities xx and yy (excluding yy) were uninfected with any virus at the start of the turn.Once a city is infected with a virus, it stays infected indefinitely and can not be infected with any other virus. The spread stops once all cities are infected.You need to process qq independent scenarios. Each scenario is described by kiki virus species and mimi important cities. For each important city determine which the virus it will be infected by in the end.InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Treeland.The following n−1n−1 lines describe the roads. The ii-th of these lines contains two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — indices of cities connecting by the ii-th road. It is guaranteed that the given graph of cities and roads is a tree.The next line contains a single integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of infection scenarios. qq scenario descriptions follow.The description of the ii-th scenario starts with a line containing two integers kiki and mimi (1≤ki,mi≤n1≤ki,mi≤n) — the number of virus species and the number of important cities in this scenario respectively. It is guaranteed that ∑qi=1ki∑i=1qki and ∑qi=1mi∑i=1qmi do not exceed 2⋅1052⋅105.The following kiki lines describe the virus species. The jj-th of these lines contains two integers vjvj and sjsj (1≤vj≤n1≤vj≤n, 1≤sj≤1061≤sj≤106) – the initial city and the propagation speed of the virus species jj. It is guaranteed that the initial cities of all virus species within a scenario are distinct.The following line contains mimi distinct integers u1,…,umiu1,…,umi (1≤uj≤n1≤uj≤n) — indices of important cities.OutputPrint qq lines. The ii-th line should contain mimi integers — indices of virus species that cities u1,…,umiu1,…,umi are infected with at the end of the ii-th scenario.ExampleInputCopy7
1 2
1 3
2 4
2 5
3 6
3 7
3
2 2
4 1
7 1
1 3
2 2
4 3
7 1
1 3
3 3
1 1
4 100
7 100
1 2 3
OutputCopy1 2
1 1
1 1 1

/**

 *    Author:  LZVSDY

**/

#include <bits/stdc++.h>

using namespace std;

#define FI first

#define SE second

#define MP make_pair

#define PB push_back

/*

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

*/

typedef long long LL;

typedef unsigned long long int ULL;

typedef pair<int, int> PII;

typedef vector<int> VI;

const int INF = 0x3f3f3f3f;

const LL LNF = 0x3f3f3f3f3f3f3f3f;

const int mod = 998244353;

const int N = 2500010;

const int M = 5e5 + 10;

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

int dep[N], dfn[N], f[N][19], sz[N], son[N], ti;

int st[N], s[N], tp;

bool vis[N], use[N];

PII dist[N];

int n, k, m;

struct V{

    int v, s, col;

}v[N];

void add(int a, int b) {

    e[idx] = b, ne[idx] = h[a], h[a] = idx ++;

}

void dfs1(int u, int fa) {

    sz[u] = 1;

    for (int i = h[u]; ~i; i = ne[i]) {

        int j = e[i];

        if (j == fa) continue;

        f[j][0] = u;

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

        dfs1(j, u);

        sz[u] += sz[j];

        if (sz[u] > sz[son[u]]) son[u] = j;

    }

}

void dfs2(int u, int fa) {

    dfn[u] = ++ ti;

    if (son[u]) {

        dfs2(son[u], u);

        for (int i = h[u]; ~i; i = ne[i]) {

            int j = e[i];

            if (j == fa || j == son[u]) continue;

            dfs2(j, u);

        }

    }

}

void init() {

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

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

            f[i][j] = f[f[i][j - 1]][j - 1];

}

int lca(int a, int b) {

    if (dep[a] < dep[b]) swap(a, b);

    for (int k = 18; k >= 0; k -- )

        if (dep[f[a][k]] >= dep[b])

            a = f[a][k];

    if (a == b) return a;

    for (int k = 18; k >= 0; k -- )

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

            a = f[a][k], b = f[b][k];

    return f[a][0];

}

bool cmp1(V &a, V &b) {

    return dfn[a.v] < dfn[b.v];

}

bool cmp2(V &a, V &b) {

    return a.col < b.col;

}

void ins(int x) {

    if (!tp) {

        st[++ tp] = x;

        return;

    }

    int anc = lca(st[tp], x);

    while (tp > 1 && dep[st[tp - 1]] > dep[anc]) {

        // cout << st[tp - 1] << ' ' << st[tp] << endl;

		add(st[tp - 1], st[tp]), add(st[tp], st[tp - 1]);

        tp --;

    }

    if (dep[st[tp]] > dep[anc]) {

        // cout << anc << ' ' << st[tp] << endl;

        add(anc, st[tp]), add(st[tp], anc);

        tp --;

    }

    if (!tp || st[tp] != anc) st[++ tp] = anc;

    st[++ tp] = x;

}

int query(int v, int u, int op) {

    int anc = lca(u, v);

    int len = dep[u] + dep[v] - 2 * dep[anc];

    return (len + s[op] - 1) / s[op];

}

struct Node{

    int rounds, col, fa, now;

    bool operator> (const Node& w) const {

        if (rounds != w.rounds) return rounds > w.rounds;

        else if (col != w.col) return col > w.col;

        else if (fa != w.fa) return fa > w.fa;

        else return now > w.now;

    }

};

void dij() {

    priority_queue<Node, vector<Node>, greater<Node>> q;

    sort(v + 1, v + k + m + 1, cmp2);

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

        dist[v[i].v] = {0, v[i].col};

        q.push({0, v[i].col, v[i].v, v[i].v});

    }

    while (!q.empty()) {

        auto t = q.top(); q.pop();

        if (vis[t.now]) continue;

        vis[t.now] = 1;

        for (int i = h[t.now]; ~i; i = ne[i]) {

            int j = e[i];

            int len = query(j, t.fa, t.col);

            if (dist[j].FI > len) {

                dist[j] = {len, dist[t.now].SE};

                // cout << "di" << t.now << ' ' << j << ' ' << dist[j].FI << ' ' << dist[j].SE << endl;

                q.push({len, dist[j].SE, t.fa, j});

            } else if (dist[j].FI == len && dist[j].SE > dist[t.now].SE) {

                dist[j].SE = dist[t.now].SE;

                // cout << "di" << t.now << ' ' << j << ' ' << dist[j].FI << ' ' << dist[j].SE << endl;

                q.push({len, dist[j].SE, t.fa, j});

            }

        }

    }

}

void build(int k, int m) {

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

        cin >> v[i].v >> v[i].s;

        s[i] = v[i].s;

        v[i].col = i;

    }

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

        cin >> v[i + k].v;

        v[i + k].col = i + k;

    }

    sort(v + 1, v + m + k + 1, cmp1);

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

    //     cout << v[i].v << endl;

    tp = 0;

    if (v[1].v != 1) st[++ tp] = 1;

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

        if (use[v[i].v]) continue;

        ins(v[i].v);

        // cout << v[i].v << endl;

        use[v[i].v] = 1;

    }

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

        use[v[i].v] = 0;

    while (-- tp) {

        // cout << st[tp] << ' ' << st[tp + 1] << endl;

        add(st[tp], st[tp + 1]), add(st[tp + 1], st[tp]);

    }

    dij();

}

void recover(int u, int fa) {

    // cout << u << ' ' << dist[u].FI << ' ' << dist[u].SE << endl;

    dist[u].FI = dist[u].SE = INF;

    vis[u] = 0;

    for (int i = h[u]; ~i; i = ne[i]) {

        int j = e[i];

        if (j == fa) continue;

        recover(j, u);

    }

    h[u] = -1;

}

int main() {

//	#ifdef lz

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

//    #endif

	ios::sync_with_stdio(false);

    cin.tie(nullptr);

    cin >> n;

    for (int i = 1; i <= n; i ++ ) dist[i].FI = dist[i].SE = INF;

    for (int i = 1; i <= n; i ++ ) h[i] = -1;

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

        int a, b;

        cin >> a >> b;

        add(a, b), add(b, a);

    }

    dep[1] = 1;

    dfs1(1, -1);

    dfs2(1, -1);

    init();

    for (int i = 1; i <= n; i ++ ) h[i] = -1;

    int q;

    cin >> q;

    while (q -- ) {

        cin >> k >> m;

        idx = 0;

        build(k, m);

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

            cout << dist[v[i].v].SE << ' ';

        cout << endl;

        recover(1, -1);

    }

	return 0;

}


/*........... বিসমিল্লাহির রাহমানির রাহীম .................

Author: jubs

Date: 25 Jan 2022

*/

#include <bits/stdc++.h>

using namespace std;

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

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

#define endl "\n"

#define pb push_back

//#define jubs

typedef long long ll;

const int mx = 1e5 + 5;

void solve(){

 int t;

 t = 1;

 while(t--){

  string s;

  cin>>s;

  vector<int> v;

  int l = 0;

  int r = s.length()-1;

  while(l < r){

  	if(s[l]=='(' and s[r]==')'){

  	 v.pb(l+1); v.pb(r+1);

  	 l++;r--;

  	}

  	if(s[l] == ')') l++;

  	if(s[r] == '(') r--;

  }

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

  if(v.size()) cout<<1<<endl;

  cout<<v.size()<<endl;

  for(auto i : v) cout<<i<<" ";

 }

}

int main(){

	BOOST;

	#ifdef jubs

        double start = clock();

    #endif

	solve();

       //cout<<"fsf"<<endl;

	#ifdef jubs

        double tim = (clock() - start)/CLOCKS_PER_SEC;

        cout<<"Running Time : "<<tim<<" \n";

    #endif

	return 0;

}


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

#include<bits/stdc++.h>

#define eps 1e-9

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

#define endl '\n'

#define ll              long long

#define ull             unsigned long long

#define MAX 200010

#define pb push_back

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

#define pf push_front

#define fi first

#define se second

#define pii pair<int,int>

const long long  INF = LLONG_MAX;

using namespace std;

const int N=1e7+3,M=10;

const int mod=998244353;

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

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

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

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

void READ(){

#ifndef ONLINE_JUDGE

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

#endif

}

void solve(){

    int n,a,b;

    cin>>n>>a>>b;

    int x=a+b;

    if(x>n){

        int y=n-x%(n+1);

        cout<<min(n,n-y+2)<<" "<<n<<endl;

    }

    else{

        cout<<1<<" "<<min(n,x-1)<<endl;

    }

}

signed main() {

    emailam

    //READ();

    int t=1;

    cin>>t;

    while(t--){

        solve();

    }

}


A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2.

#include <bits/stdc++.h>

using namespace std;

#define int long long

int tt;

void solve();

void IO()

{

	ios_base::sync_with_stdio(false);

	cin.tie(NULL);

	cout.tie(NULL);

}

void testcase(int t)

{

	cin >> t;

	while (t--) solve();

}

typedef long long ll;

typedef long double lld;

#define ff first

#define ss second

#define pi pair<int, int>

#define vi vector<int>

#define vb vector<bool>

#define vs vector<string>

#define vc vector<char>

#define pv pair<vi, vi>

#define vpi vector<pi>

#define vvi vector<vi>

#define vvb vector<vb>

#define vvc vector<vc>

#define vvvi vector<vvi>

#define pb push_back

#define mp make_pair

#define arr(k) array<int, k>

#define var(k) vector<arr(k)>

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

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

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

#define each(nb, x) for (auto nb:x)

/*  ------------------------    BASIC INPUT -------------------------------  */

void read() {}

void read(int &a) {cin >> a;}

void read(string &s) {cin >> s;}

void read(double &a) {cin >> a;}

void read(lld &a) {cin >> a;}

template<typename x, typename y> void read(pair<x, y> &a) {read(a.first), read(a.second);}

template<typename x>void read(x &a) {for (auto  &i : a) read(i);}

template<typename x, typename... y> void read(x& a, y&... b) {read(a); read(b...);}

template<class T> void cmin(T&a, T b) {a = min(a, b);}

template<class T> void cmax(T&a, T b) {a = max(a, b);}

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

/* -------------------------------------  DEBUG STARTS ------------------------------- */

#ifndef ONLINE_JUDGE

#define dbg(x) cerr << #x << " = "; _print(x); cerr << endl;

#else

#define dbg(x)

#endif

void print(int t) {cout << t;}

void print(string t) {cout << t;}

void print(char t) {cout << t;}

void print(lld t) {cout << t;}

void print(double t) {cout << t;}

void print(bool t) {cout << t;}

void print(deque<int> t) {while (not t.empty()) {cout << t.front() << ' '; t.pop_front();}}

void print(queue<int> t) {while (not t.empty()) {cout << t.front() << ' '; t.pop();}}

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

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

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

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

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

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

void _print(deque<int> t) {while (not t.empty()) {cerr << t.front() << ' '; t.pop_front();}}

void _print(queue<int> t) {while (not t.empty()) {cerr << t.front() << ' '; t.pop();}}

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

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

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

template <class T> void print(vector <T> v) {for (T i : v) {print(i); cout << " ";}}

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

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

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

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

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

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

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

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

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

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

/* -------------------------------------  DEBUG ENDS --------------------------------- */

int n, m, l, r;

int dp[101][101][101][3];

vi a;

// we were getting WA due to -1 in parity

// rec(i) -> tot complexity in [i..n]

int rec(int i, int odd_left, int even_left, int prev_parity)

{

    if (i==n) return 0;

    if (dp[i][odd_left][even_left][prev_parity+1] != -1)

        return dp[i][odd_left][even_left][prev_parity+1];

    if (a[i] != 0)

    {

        return dp[i][odd_left][even_left][prev_parity+1] = (a[i]%2==prev_parity or i==0) ?

                rec(i+1, odd_left, even_left, a[i]%2) :1 + rec(i+1, odd_left, even_left, a[i]%2);

    }

    int op1 = 1e9, op2 = 1e9;

    // assign odd parity

    if (odd_left > 0)

    {

        op1 = (prev_parity==1 or i==0) ? rec(i+1, odd_left-1, even_left, 1) :

                                1+rec(i+1, odd_left-1, even_left,1);

    }

    // assign even parity

    if (even_left > 0)

    {

        op2 = (prev_parity==0 or i==0) ? rec(i+1, odd_left, even_left-1, 0) :

                                1+rec(i+1, odd_left, even_left-1,0);

    }

    return dp[i][odd_left][even_left][prev_parity+1] = min(op1, op2);

}

void solve()

{

	cin >> n; a.resize(n);

    vi vis(n+1, 0);

    int odd=0, even=0;

    rep(i,0,n)

    {

        cin >> a[i];

        vis[a[i]] = 1;

    }

    rep(i,1,n+1)

    {

        if (vis[i] == 0)

        {

            if (i&1) odd++;

            else even++;

        }

    }

    memset(dp, -1, sizeof dp);

    cout << rec(0,odd, even, -1);

}

signed main()

{

	IO();

	// testcase(tt);

	solve();

}


B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
OutputCopy7
1 5 1 3
2 4 6 1 3 5

// Jai shree ram

#include <bits/stdc++.h>

using namespace std;

int main()

{

    int t;

    cin >> t;

    while (t--)

    {

        int n;

        cin>>n;

        int a[n];

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

        {

            /* code */

            cin>>a[i];

        }

        sort(a,a+n,greater<int>());

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

        {

            /* code */

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

        }

        cout<<"\n";

    }

}


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;

typedef long long ll;

template<class t> using vc=vector<t>;

template<class t> using vvc=vc<vc<t>>;

using vi = vc<int>;

using vl = vc<ll>;

using vvi = vc<vi>;

using vvl = vc<vl>;

using pii = pair<int, int>;

using pll = pair<ll, ll>;

#define inf 0x3f3f3f3f

#define llinf 0x3f3f3f3f3f3f3f3f

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

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

#define rev(x) reverse(ALL(x))

#define srt(x) sort(ALL(x))

#define rsrt(x) sort(rALL(x))

#define rb(_, l, r) for(int _= l; _ <= r; ++_)

#define rep(_, l, r) for(int _ = l; _ < r; ++_)

#define br(_, r, l) for(int _ = r; _ >= l; _--)

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

template<class t,class u> bool chmax(t&a,u b){if(a<b){a=b;return true;}else return false;}

template<class t,class u> bool chmin(t&a,u b){if(b<a){a=b;return true;}else return false;}

template<typename T> void in(vector<T>&a) {for(auto& e: a) cin>> e;}

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

void p(int x) { if (x) cout << "YES" << '\n'; else cout << "NO" << '\n'; }

template<class t> void printv(t x, char delimiter = ',', bool needBrace = true) {

    needBrace && cout << "{";

    for(auto it = x.begin(); it != x.end(); ) {

        cout << *it;

        it = next(it);

        if (it != x.end()) {

            cout << delimiter;

        } else {

            needBrace && cout << "}";

        }

    }

    cout << "\n";

}

#define TEST

#ifdef TEST

    #define pr(...) printf(__VA_ARGS__);

    #define db(x, ...)      debug##x(__VA_ARGS__)

    #define ldb(parm...)    do {cout << "Line:" << __LINE__ << "  "; db(parm);} while(0)

    #define debugv(v...)    do {printv(v);} while(0)

    #define debug1(a)       cout << #a << " = " << a << ' ';

    #define debug2(a,b)     do {debug1(a); debug1(b); cout << '\n';} while(0)

    #define debug3(a,b,c)   do {debug1(a); debug2(b, c);} while(0)

    #define debug4(a,b,c,d) do {debug1(a); debug3(b, c, d);} while(0)

#else

    #define db(...) "Your attitude towards suffering is the melody of life.";

#endif

/*

str -> str.c_str()

db(v, a) -> printv()

db(1, x) -> print x

db(2, x, y) -> print x, y

*/

const char nl = '\n';

#define SINGLE

void solve() {

    int n;

    cin >> n;

    vi a(n);

    map<int, vc<pii>> mp;

    rep (i, 0, n) {

        cin >> a[i];

        int cur = 0;

        br (j, i, 0) {

            cur += a[j];

            mp[cur].push_back({j + 1, i + 1});

        }

    }

    vc<pii> ans;

    for (auto&[k, v]: mp) {

        vc<pii> t;

        int pre = -1;

        for (auto&[l, r] : v) {

            if (l > pre) {

                t.emplace_back(l, r); pre = r;

            }

        }

        if (sz(t) > sz(ans)) ans = t;

    }

    cout << sz(ans) << nl;

    for (auto&[l, r]: ans) {

        cout << l << ' ' << r << nl;

    }

}

int main() {

    ios::sync_with_stdio(0);cin.tie(0);

#ifdef SINGLE

    solve();

#else

    int T; cin >> T; while (T--) solve();

#endif

    return 0;

}


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <queue>
#include <deque>
#include <bitset>
#include <iterator>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <numeric>
#include <utility>
#include <limits>
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <array>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <chrono>
#include <random>

#define ld long double
#define ll long long
using namespace std;

struct event{
    int t, type, id;
    event(int t, int type, int id) : t(t), type(type), id(id) {}
};

bool operator<(event a, event b){
    if(a.t==b.t){
        if(a.type==b.type){
            return a.id < b.id;
        }
        return a.type>b.type;
    }
    return a.t<b.t;
}

void solve(){
    int n;
    cin>>n;
    mt19937_64 gen(time(NULL));
    uniform_int_distribution<ll> distribution(1,1e9);
    vector<ll> hash(n);
    for(int i=0;i<n;i++){
        hash[i] = distribution(gen);
    }
    vector<event> a,b;
    for(int i=0;i<n;i++){
        int l1,r1, l2, r2;
        cin>>l1>>r1>>l2>>r2;
        a.emplace_back(l1,1,i);
        a.emplace_back(r1+1,2,i);
        b.emplace_back(l2,1,i);
        b.emplace_back(r2+1,2,i);
    }
    set<ll> founda,foundb;
    sort(a.begin(),a.end());
    sort(b.begin(),b.end());
    ll curr = 0;
    for(int i=0;i<a.size();i++){
        auto e = a[i];
        if(e.type==1){
            curr += hash[e.id];
        }
        else{
            curr -= hash[e.id];
            continue;
        }
        if(i!=a.size()-1 and a[i+1].type == 2){
            founda.insert(curr);
        }
    }
    // set<int> in;
    for(int i=0;i<b.size();i++){
        auto e = b[i];
        if(e.type==1){
            curr += hash[e.id];
        }
        else{
            curr -= hash[e.id];
            continue;
        }
        if(i!=b.size()-1 and b[i+1].type == 2){
            foundb.insert(curr);
        }
    }
    for(auto vala:founda){
        if(!foundb.count(vala)){
            cout<<"NO\n";
            return;
        }
    }
    for(auto valb:foundb){
        if(!founda.count(valb)){
            cout<<"NO\n";
            return;
        }
    }
    cout<<"YES\n";
}

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout<<setprecision(15)<<fixed;
    int t=1;
    // cin >> t;
    for (int c = 0; c < t; c++)
    {
        // cout<<"Case #"<<c+1<<": ";
        solve();
    }
}


#include <iostream>

#include <cstring>

#include <algorithm>

#include <unordered_map>

#define x first

#define y second

using namespace std;

typedef pair<int, int> pii;

const int N = 1510;

unordered_map<int, vector<pii>> mp;

int n, s[N];

int main()

{

    cin >> n;

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

    {

        int a;

        cin >> a;

        s[i] += s[i - 1] + a;

    }

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

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

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

    int k = 0;

    vector<pii> res;

    for (auto& t : mp)

    {

        vector<pii> path, tmp = t.y;

        sort(tmp.begin(), tmp.end(), [&](pii& a, pii& b){

            return a.y < b.y;

        });

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

        for (auto& range : tmp)

        {

            int l = range.x, r = range.y;

            if (ed < l) {

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

                st = l;

                ed = r;

                cnt ++;

            }

        }

        path.push_back({st, ed});

        if (k < cnt)    k = cnt, res = path;

    }

    cout << k << endl;

    for (auto& t : res)

        cout << t.x << ' ' << t.y << endl;

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


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

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

constexpr int N = 2e5 + 10;

void solve() {

	int n;

	cin >> n;

	vector<int> a(n + 1);

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

		cin >> a[i];

	int ans = 0;

	auto cal = [&](vector<int> &v, int b) {

		int cnt = 0;

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

			int l = lower_bound(v.begin() + i + 1, v.end(), (1 << b) - v[i]) - v.begin(), r = upper_bound(v.begin() + i + 1, v.end(), (1 << (b + 1)) - 1 - v[i]) - v.begin() - 1;

			cnt ^= (r - l + 1) % 2;

			//cout << i << ' ' << l << ' ' << r << '\n';

		}

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

			int l = lower_bound(v.begin() + i + 1, v.end(), (1 << b) + (1 << (b + 1)) - v[i]) - v.begin(), r = upper_bound(v.begin() + i + 1, v.end(), (1 << (b + 2)) - 1 - v[i]) - v.begin() - 1;

			cnt ^= (r - l + 1) % 2;

			//cout << i << ' ' << l << ' ' << r << '\n';

		}

		if(cnt & 1)

			return 1 << b;

		else

			return 0;

	};

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

		vector<int> b(n + 1);

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

			b[j] = a[j] % (1 << (i + 1));

		sort(b.begin() + 1, b.end());

		ans += cal(b, i);

	}

	cout << ans;

}

int main() {

	ios::sync_with_stdio(false);

	cin.tie(nullptr);

	int t = 1;

	while(t--) {

		solve();

	}

}


B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs:  buy one bus ticket to get from 11 to 33,  buy one tram ticket to get from 33 to 66,  buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
OutputCopy2
1
3
1
6

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

int binarySearch(vector<ll> main, int money) {

	int L = 0;

	int R = main.size() - 1;

	while (R >= L) {

		int mid = L + (R-L)/2;

		if (main[mid] <= money && main[mid-1] > money) return mid+1;

		if (main[mid] > money) L = mid + 1;

		else if (main[mid] <= money && main[mid-1] <= money) R = mid - 1;

	}

	return 1;

}

int main() {

	int t;

	cin >> t;

	while (t--) {

		int a, b, p; string s;

		cin >> a >> b >> p >> s;

		vector<ll> needed(s.length());

		needed[s.length() - 1] = 0;

		needed[s.length() - 2] = (s[s.length()-2] == 'A' ? a : b);

		for (int i = s.length()-3; i >= 0; i--) {

			if (s[i] == s[i+1]) needed[i] = needed[i+1];

			else if (s[i] == 'A') needed[i] = needed[i+1] + a;

			else if (s[i] == 'B') needed[i] = needed[i+1] + b;

		}

		cout << binarySearch(needed, p) << endl;

	}

}


C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following:  if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem);  otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
OutputCopyYES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO

#include <bits/stdc++.h>

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

#define xs(a) cout<<setiosflags(ios::fixed)<<setprecision(a);

#define lbit(a) (__builtin_ffsll(a))

#define ubit(a) (64-__builtin_clzll(a))

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

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

#define mem(a,b) memset(a,b,sizeof(a));

using namespace std;

#define ull unsigned long long

#define ll long long

#define endl '\n'

typedef pair<ll,ll> pll;

const int N=1e6+5;

const int mod=1e9+7;

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

void solve(){

	map<char,ll>mp;

	string s;cin>>s;

	string t;t+=s[0];mp[s[0]]=1;

	ll pos=0;

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

		if(!mp[s[i]]){

			if(!pos){

				t=s[i]+t;

			}else if(pos==t.size()-1)t+=s[i],pos++;

			else {

				cout<<"NO"<<endl;

				return ;

			}

			mp[s[i]]=1;

		}else {

			if(pos>0&&t[pos-1]==s[i])pos--;

			else if(pos<t.size()-1&&t[pos+1]==s[i])pos++;

			else {

				cout<<"NO"<<endl;

				return ;

			}

		}

	}

	for(char i='a';i<='z';i++){

		if(!mp[i])t+=i;

	}

	cout<<"YES"<<endl;

	cout<<t<<endl;

}

signed main(){IOS

	ll T;T=1;

	cin>>T;

	while(T--){

		solve();

	}

	return 0;

}


F2. Animal Observation (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way:   On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days.  On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days.  If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤m1≤k≤m) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1:   Example 2:   Example 3:   Example 4:

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

#define int long long

#define mem(a,b) memset(a,b,sizeof(a))

#define fre(z) freopen(z".in","r",stdin),freopen(z".out","w",stdout)

using namespace std;

typedef long long ll;

typedef unsigned long long ull;

typedef pair<int,int> Pair;

const double eps=1e-8;

const int inf=2139062143;

#ifdef ONLINE_JUDGE

static char buf[1000000],*p1=buf,*p2=buf,obuf[1000000],*p3=obuf;

#define getchar() p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++

#endif

inline void qread(){}template<class T1,class ...T2>

inline void qread(T1 &a,T2&...b){

    register T1 x=0;register bool f=false;char ch=getchar();

    while(ch<'0') f|=(ch=='-'),ch=getchar();

    while(ch>='0') x=(x<<3)+(x<<1)+(ch^48),ch=getchar();

    x=(f?-x:x);a=x;qread(b...);

}

inline void dread(){}template<class T1,class ...T2>

inline void dread(T1 &a,T2&...b){

    register double w=0;register ll x=0,base=1;

    register bool f=false;char ch=getchar();

    while(!isdigit(ch)) f|=(ch=='-'),ch=getchar();

    while(isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=getchar();

    w=(f?-x:x);if(ch!='.') return a=w,dread(b...);x=0,ch=getchar();

    while(isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),base*=10,ch=getchar();

    register double tmp=(double)(x/(double)base);w=w+(double)(f?-tmp:tmp);a=w;dread(b...);

}

template<class T> T qmax(T x,T y){return x>y?x:y;}

template<class T,class ...Arg> T qmax(T x,T y,Arg ...arg){return qmax(x>y?x:y,arg...);}

template<class T> T qmin(T x,T y){return x<y?x:y;}

template<class T,class ...Arg> T qmin(T x,T y,Arg ...arg){return qmin(x<y?x:y,arg...);}

template<class T> T randint(T l,T r){static mt19937 eng(time(0));uniform_int_distribution<T>dis(l,r);return dis(eng);}

const int MAXN=57;

const int MAXM=2e4+7;

int n,m,k,b[MAXM],a[MAXN][MAXM],f[MAXN][MAXM];

struct Seg_tree{

    #define ls p<<1

    #define rs p<<1|1

    #define mid ((l+r)>>1)

    int tr[MAXM<<2],tag[MAXM<<2];

    inline void pup(int p){tr[p]=qmax(tr[ls],tr[rs]);}

    inline void f(int p,int l,int r,int k){tr[p]+=k;tag[p]+=k;}

    void pwn(int p,int l,int r){

        f(ls,l,mid,tag[p]);f(rs,mid+1,r,tag[p]);tag[p]=0;

    }void build(int a[],int p,int l,int r){

        tag[p]=0;if(l==r) tr[p]=a[l];

        else build(a,ls,l,mid),build(a,rs,mid+1,r),pup(p);

    }void upd(int p,int l,int r,int L,int R,int k){

        if(L<=l&&r<=R) f(p,l,r,k);

        else{

            pwn(p,l,r);if(L<=mid) upd(ls,l,mid,L,R,k);

            if(R>mid) upd(rs,mid+1,r,L,R,k);pup(p);

        }

    }int que(int p,int l,int r,int L,int R){

        if(L<=l&&r<=R) return tr[p];

        else{

            int res=0;pwn(p,l,r);

            if(L<=mid) res=que(ls,l,mid,L,R);

            if(R>mid) res=qmax(res,que(rs,mid+1,r,L,R));return res;

        }

    }

    #undef mid

}st[MAXN];int s[MAXN][MAXM],ans;

signed main(){

    qread(n,m,k);int i,j;for(i=1;i<=n;i++) for(j=1;j<=m;j++) qread(a[i][j]),s[i][j]=s[i][j-1]+a[i][j];

    for(j=1;j<=m-k+1;j++) f[1][j]=s[1][j+k-1]-s[1][j-1];

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

        for(j=1;j<=k;j++) b[j]=f[i-1][j]+s[i][j+k-1]-s[i][k];

        for(j=k+1;j<=m-k+1;j++) b[j]=f[i-1][j]+s[i][j+k-1]-s[i][j-1];

        st[i-1].build(b,1,1,m);f[i][1]=st[i-1].que(1,1,m,1,m-k+1)+s[i][k];

        // if(i==2){

        //     for(j=1;j<=m;j++) cout<<b[j]<<" ";cout<<endl;

        //     // cout<<b[j]<<" ";cout<<endl;

        //     cout<<st[i-1].que(1,1,m,1,m-k+1)<<" "<<s[i][k]<<endl;

        // }

        for(j=2;j<=m-k+1;j++){

            st[i-1].upd(1,1,m,qmax(1ll,j-k),j-1,a[i][j-1]);

            st[i-1].upd(1,1,m,j,j+k-1,-a[i][j+k-1]);

            f[i][j]=st[i-1].que(1,1,m,1,m-k+1)+s[i][j+k-1]-s[i][j-1];

        }

    }for(i=1;i<=m-k+1;i++) ans=qmax(ans,f[n][i]);printf("%lld\n",ans);

    // for(i=1;i<=n;i++){for(j=1;j<=m-k+1;j++) cout<<f[i][j]<<" ";cout<<endl;}

    #ifndef ONLINE_JUDGE

    cerr<<"Time: "<<clock()<<endl;

    system("pause > null");

    #endif

    return 0;

}


F. Red-Blue Graphtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a bipartite graph: the first part of this graph contains n1n1 vertices, the second part contains n2n2 vertices, and there are mm edges. The graph can contain multiple edges.Initially, each edge is colorless. For each edge, you may either leave it uncolored (it is free), paint it red (it costs rr coins) or paint it blue (it costs bb coins). No edge can be painted red and blue simultaneously.There are three types of vertices in this graph — colorless, red and blue. Colored vertices impose additional constraints on edges' colours:  for each red vertex, the number of red edges indicent to it should be strictly greater than the number of blue edges incident to it;  for each blue vertex, the number of blue edges indicent to it should be strictly greater than the number of red edges incident to it. Colorless vertices impose no additional constraints.Your goal is to paint some (possibly none) edges so that all constraints are met, and among all ways to do so, you should choose the one with minimum total cost. InputThe first line contains five integers n1n1, n2n2, mm, rr and bb (1≤n1,n2,m,r,b≤2001≤n1,n2,m,r,b≤200) — the number of vertices in the first part, the number of vertices in the second part, the number of edges, the amount of coins you have to pay to paint an edge red, and the amount of coins you have to pay to paint an edge blue, respectively.The second line contains one string consisting of n1n1 characters. Each character is either U, R or B. If the ii-th character is U, then the ii-th vertex of the first part is uncolored; R corresponds to a red vertex, and B corresponds to a blue vertex.The third line contains one string consisting of n2n2 characters. Each character is either U, R or B. This string represents the colors of vertices of the second part in the same way.Then mm lines follow, the ii-th line contains two integers uiui and vivi (1≤ui≤n11≤ui≤n1, 1≤vi≤n21≤vi≤n2) denoting an edge connecting the vertex uiui from the first part and the vertex vivi from the second part.The graph may contain multiple edges.OutputIf there is no coloring that meets all the constraints, print one integer −1−1.Otherwise, print an integer cc denoting the total cost of coloring, and a string consisting of mm characters. The ii-th character should be U if the ii-th edge should be left uncolored, R if the ii-th edge should be painted red, or B if the ii-th edge should be painted blue. If there are multiple colorings with minimum possible cost, print any of them.ExamplesInputCopy3 2 6 10 15
RRB
UB
3 2
2 2
1 2
1 1
2 1
1 1
OutputCopy35
BUURRU
InputCopy3 1 3 4 5
RRR
B
2 1
1 1
3 1
OutputCopy-1
InputCopy3 1 3 4 5
URU
B
2 1
1 1
3 1
OutputCopy14
RBB

// LUOGU_RID: 93522213
/*
* @Author: ftt2333
* @Email: ftt2333@126.com
* @Last Modified time: 2022-11-10 21:50:51
*/

#include <bits/stdc++.h>
using namespace std;
#define int ll
#define off ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define fin(s) freopen(s, "r", stdin)
#define fout(s) freopen(s, "w", stdout)
#define fio(s) fin(s".in"), fout(s".out")
using ll = long long; using ull = uint64_t;
using lll = __int128; using ulll = __uint128_t;
using db = double; using ldb = long double;
using pii = pair<int, int>; using pll = pair<ll, ll>;
using vi = vector<int>; using vl = vector<ll>;
using uchar = unsigned char; using uint = unsigned int;
template<class T> using uid = uniform_int_distribution<T>;
template<class T> using urd = uniform_real_distribution<T>;
#define rep(i, a, b) for(auto i = (a); i <= (b); i++)
#define per(i, a, b) for(auto i = (a); i >= (b); i--)
#define go(i, h, e, x) for(int i = h[x]; i; i = e[i].nxt)
#define pb push_back
#define fi first
#define se second
#define all(a) (a).begin(), (a).end()
#define szof(a) ((int)(a).size())
#define mem(a, b) memset(a, b, sizeof(a))
#define mcpy(a, b) memcpy(a, b, sizeof(a))

mt19937 rnd(random_device{}());
const int mod = 998244353;
const int inf = 1e18;
const int N = 2e6 + 10;
const int M = 2e6 + 10;

struct mcmf {
  struct edge { int y, c, w, nxt; }ed[M];
  int head[N], cur[N], dis[N], tot = 1, s, t, mc, mf;
  int deg[N];
  bool vis[N];
  void init(){ tot = 1; mem(head, 0); }
  void add(int x, int y, int c, int w) { ed[++tot] = edge{ y, c, w, head[x] }; head[x] = tot; }
  void link(int x, int y, int l, int r, int w) {
    // cout << "LINK " << x << ' ' << y << ' ' << l << ' ' << r << ' ' << w << '\n';
    deg[x] -= l, deg[y] += l;
    add(x, y, r - l, w), add(y, x, 0, -w);
  }
  bool lable(){
    fill(dis, dis + N, inf); mem(vis, 0); mcpy(cur, head);
    deque<int> q; dis[s] = 0, vis[s] = 1; q.push_front(s);
    for(; !q.empty(); ) {
      int x = q.front(); vis[x] = 0; q.pop_front();
      go(i, head, ed, x) {
        int y = ed[i].y, c = ed[i].c, w = ed[i].w;
        if(!c || dis[y] <= dis[x] + w) continue; dis[y] = dis[x] + w;
        if(vis[y]) continue; vis[y] = 1;
        if(!q.empty() && dis[y] <= dis[q.front()]) q.push_front(y);
        else q.push_back(y);
      }
    }
    return dis[t] != inf;
  }
  int dfs(int x, int f){
    if(x == t)return f;
    vis[x] = 1; int r = f;
    go(i, head, ed, x) {
      cur[x] = i; if(!r) break;
      int y = ed[i].y, c = ed[i].c, w = ed[i].w;
      if(!c || dis[y] != dis[x] + w || vis[y]) continue;
      int k = dfs(y, min(r, c));
      if(k) r -= k, ed[i].c -= k, ed[i ^ 1].c += k, mc += w * k;
      else dis[y] = inf;
    } vis[x] = 0;
    return f - r;
  }
  void calc(int S, int T){ s=S, t=T; mc = mf = 0; for(; lable(); ) mf += dfs(s, inf); }
} g;
int n1, n2, m, r, b;
char s1[N], s2[N];

signed main() {
  cin >> n1 >> n2 >> m >> r >> b;
  int s = n1 + n2 + 1, t = s + 1, S = t + 1, T = S + 1;
  scanf("%s%s", s1 + 1, s2 + 1);
  rep(i, 1, m) {
    int x, y; cin >> x >> y;
    g.link(x, y + n1, 0, 1, r);
    g.link(y + n1, x, 0, 1, b);
  }
  // cout << "------------------\n";
  rep(i, 1, n1) {
    if(s1[i] == 'R') g.link(s, i, 1, inf, 0);
    if(s1[i] == 'B') g.link(i, t, 1, inf, 0);
    if(s1[i] == 'U') g.link(s, i, 0, inf, 0), g.link(i, t, 0, inf, 0);
  }
  // cout << "------------------\n";
  rep(i, 1, n2) {
    if(s2[i] == 'B') g.link(s, n1 + i, 1, inf, 0);
    if(s2[i] == 'R') g.link(n1 + i, t, 1, inf, 0);
    if(s2[i] == 'U') g.link(s, n1 + i, 0, inf, 0), g.link(n1 + i, t, 0, inf, 0);
  }
  // cout << "------------------\n";
  g.link(t, s, 0, inf, 0);
  int sum = 0;
  rep(i, 1, t) {
    if(g.deg[i] > 0) sum += g.deg[i], g.link(S, i, 0, g.deg[i], 0);
    if(g.deg[i] < 0) g.link(i, T, 0, -g.deg[i], 0);
  }
  g.calc(S, T);
  if(g.mf != sum) {
    cout << -1 << '\n';
    return 0;
  }
  cout << g.mc << '\n';
  rep(i, 1, m) {
    if(!g.ed[i * 4 - 2].c) cout << 'R';
    else if(!g.ed[i * 4].c) cout << 'B';
    else cout << 'U';
  }
}


#include<bits/stdc++.h>

using namespace std;

const int MAXN = 100;

int dp[MAXN][MAXN][MAXN][2], a[MAXN], n, oddCount = 0, evenCount = 0;

int f(int index, int odd, int even, int previousParity)

{

    if(index == n) return 0;

    if(dp[index][odd][even][previousParity] != -1) return dp[index][odd][even][previousParity];

    if(a[index]) return (index && previousParity != a[index] % 2) + f(index + 1, odd, even, a[index] % 2);

    int takeOdd = MAXN, takeEven = MAXN;

    if(odd) takeOdd = (index && !previousParity) + f(index + 1, odd - 1, even, 1);

    if(even) takeEven = (index && previousParity) + f(index + 1, odd, even - 1, 0);

    return dp[index][odd][even][previousParity] = min(takeOdd, takeEven);

}

int main()

{

    memset(dp, -1, sizeof(dp));

    cin >> n;

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

    {

        cin >> a[i];

        if(a[i] && a[i] % 2) oddCount++;

        if(a[i] && a[i] % 2 == 0) evenCount++;

    }

    cout << f(0, (n + 1) / 2 - oddCount, n / 2 - evenCount, 0) << "\n";

}