D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples:  for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array;  for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array;  for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3
0
1
2
2
0
0
10
OutputCopy1
2
3
3
4
4
7
InputCopy4 3
1
2
1
2
OutputCopy0
0
0
0
NoteIn the first example:  After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11.  After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22.  After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33.  After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations).  After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44.  After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44.  After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations:   a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5,  a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3,  a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3,  a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6,  a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7,  a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4.  The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77.

#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 <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 <unordered_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 <iomanip>

#include <assert.h>

#include <iostream>

#include <string>

#include <vector>

#include <algorithm>

#include <sstream>

using namespace std;

using ll = long long;

using vi = vector<int>;

using vii = vector< vector <int>>;

using vl = vector<ll>;

using vll = vector< vector <ll>>;

using vpi = vector <pair <int, int>>;

using vpl = vector <pair <ll, ll>>;

#define pb push_back

#define rsz resize

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

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

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

#define loop1(i,n) for(int i = 1;i<n;i++)

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

using pi = pair<int, int>;

using pl = pair<ll, ll>;

#define mp make_pair

#define ff first

#define ss second

#define endl "\n"

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

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

ll arr[400001];

ll tree[1600004];

ll build(int l, int r, int index) {

    if (l == r) {

        tree[index] = arr[l];

        return tree[index];

    }

    int mid = (l + r) / 2;

    tree[index] = min(build(l, mid, 2 * index + 1), build(mid + 1, r, 2 * index + 2));

    return tree[index];

}

void update(int k, int u, int l, int r, int index) {

    int mid = (l + r) / 2;

    if (l == r) {

        tree[index] += u;

        arr[k] += u;

        return;

    }

    if (k <= mid) update(k, u, l, mid, 2 * index + 1);

    else update(k, u, mid + 1, r, 2 * index + 2);

    tree[index] = min(tree[index * 2 + 1], tree[index * 2 + 2]);

}

ll query(int l, int r, int start, int end, int index) {

    if (l > end || start > r) return 999999999;

    if (start <= l && r <= end) return tree[index];

    int mid = (l + r) / 2;

    return min(query(l, mid, start, end, 2 * index + 1) , query(mid + 1, r, start, end, 2 * index + 2));

}

int main() {

#ifdef LOCAL

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

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

#endif

    ios::sync_with_stdio(0);

    cin.tie(0);

    int q, x;

    cin >> q >> x;

    loop(i, x) arr[i] = i;

    build(0, x - 1, 0);

    while (q--) {

        int k;

        cin >> k;

        k %= x;

        update(k, x, 0, x - 1, 0);

        cout << query(0, x - 1, 0, x - 1, 0) << endl;

    }

    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.

#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#include "bits/stdc++.h"
using namespace std;

#define ff first
#define ss second
#define mp make_pair
#define ll long long
#define ld long double
#define rep(i, n) for (ll i = 0; i < n; i++)
#define rev(i, n) for (ll i = n; i >= 0; i--)
#define rep_a(i, a, n) for (ll i = a; i < n; i++)
#define pb push_back
#define all(_obj) _obj.begin(), _obj.end()
#define pll pair<ll, ll>
#define vll vector<ll>
#define yes cout << "YES" << endl
#define no cout << "NO" << endl
const ll N = 1e5 + 11, mod = 1e9 + 7, inf = LONG_LONG_MAX;

void solve()
{
    string s;
    cin >> s;
    vll ans;
    ll i = 0, j = s.size() - 1;
    while (j > i)
    {
        if (s[j] == ')' && s[i] == '(')
        {
            ans.pb(i + 1);
            ans.pb(j + 1);
            i++;
            j--;
        }
        if (s[i] != '(')
            i++;
        if (s[j] != ')')
            j--;
    }
    if (ans.empty())
    {
        cout << 0 << endl;
        return;
    }
    sort(all(ans));
    cout << 1 << endl;
    cout << ans.size() << endl;
    for (auto &i : ans)
        cout << i << " ";
    cout << endl;
}

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

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

    return 0;
}


F. Coffee Varieties (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. You can find the hard version in the Div. 1 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will:   Tell you if acac is in SS;  Add acac at the back of SS;  If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 2n2k2n2k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 2n2k≤20 0002n2k≤20 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 2n2k2n2k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:  fflush(stdout) or cout.flush() in C++;  System.out.flush() in Java;  flush(output) in Pascal;  stdout.flush() in Python;  see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 2n2k≤20 0002n2k≤20 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2
N
N
Y
N
N
N
N
OutputCopy? 1
? 2
? 3
? 4
R
? 4
? 1
? 2
! 3
InputCopy8 8
N
N
N
N
Y
Y
OutputCopy? 2
? 6
? 4
? 5
? 2
? 5
! 6
NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5.

#include <bits/stdc++.h>

using namespace std;

bool ask(int x) {

    cout << '?' << ' ' << x + 1 << endl;

    char c; cin >> c;

    return c == 'Y' ? true : false;

}

void reset() {

    cout << 'R' << endl;

}

void tell(int x) {

    cout << '!' << ' ' << x << endl;

}

void solve_small(int n, int k) {

    set <int> ans;

    for(int i = 0; i < n; i++) ans.insert(i);

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

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

            reset();

            ask(i);

            if(ask(j)) ans.erase(j);

        }

    }

    tell(ans.size());

}

int main() {

    cin.tie(0)->sync_with_stdio(0);

    int n, k;

    cin >> n >> k;

    if(k == 1) {

        solve_small(n, k);

        return 0;

    }

    vector<vector<int>> v;

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

        reset();

        vector <int> unique;

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

            auto t = ask(i*k + j);

            if(!t) unique.push_back(i*k + j);

        }

        while((int)unique.size() < k) unique.push_back(unique.front());

        v.push_back(unique);

    }

    for(int sz = k; sz < n; sz *= 2) {

        vector<vector<int>> w;

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

            // merge v[i] and v[i + 1]!

            auto a = v[i];

            auto b = v[i + 1];

            map <int, bool> rema, remb;

            for(int j = 0; j < sz; j += k) {

                // starting block of a.

                for(int t = 0; t < sz; t += k) {

                    // starting block of b. Remove duplicates in (5K/2) queries.

                    reset();

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

                        ask(a[j + x]);

                    }

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

                        if(ask(b[t + x])) remb[t + x] = true;

                    }

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

                        if(ask(a[j + k/2 + x])) rema[j + k/2 + x] = true;

                    }

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

                        if(ask(b[t + k/2 + x])) remb[t + k/2 + x] = true;

                    }

                    reset();

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

                        ask(a[j + x]);

                    }

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

                        if(ask(b[t + k/2 + x])) remb[t + k/2 + x] = true;

                    }

                }

            }

            vector <int> temp;

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

                if(!rema[i]) temp.push_back(a[i]);

            }

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

                if(!remb[i]) temp.push_back(b[i]);

            }

            while((int)temp.size() < 2*sz) temp.push_back(temp.front());

            w.push_back(temp);

        }

        v = w;

    }

    set <int> s;

    for(auto i : v.front()) s.insert(i);

    tell((int)s.size());

    return 0;

}


A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO

#include<bits/stdc++.h>

using namespace std;

int main(){

	int t,n,a;

	bool o=0,e=0;

	cin>>t;

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

		cin>>n;

		if(n%2==0){

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

				cin>>a;

				if(a%2==0){

					e=1;

				}

				else{

					o=1;

				}

			}

			if(o && e){

				cout<<"YES"<<endl;

			}

			else{

				cout<<"NO"<<endl;

			}

			o=0;

			e=0;

		}

		else{

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

				cin>>a;

				if(a%2==1){

					o=1;

				}

			}

			if(o){

				cout<<"YES"<<endl;

			}

			else{

				cout<<"NO"<<endl;

			}

			o=0;

		}

	}

}


A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5
1 1 1 0 0
0 1 1 1 1
OutputCopy3
InputCopy3
0 0 0
0 0 0
OutputCopy-1
InputCopy4
1 1 1 1
1 1 1 1
OutputCopy-1
InputCopy9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
OutputCopy4
NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.

// Siddharth Ruria
//Linkedin: https://www.linkedin.com/in/ruria-siddharth/
//Codeforces: https://codeforces.com/profile/Sw00sh
//Codechef: https://www.codechef.com/users/airurdis

#include <iostream>
#include <bits/stdc++.h>
// #include <sys/resource.h>
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
using namespace std;
// using namespace chrono;
// using namespace __gnu_pbds;

// #define ruria 1

//Speed
#define fast ios_base::sync_with_stdio(false);
#define input cin.tie(NULL);
#define output cout.tie(NULL);

//Aliases
using ll= long long;
using lld= long double;
using ull= unsigned long long;

//Constants
const lld pi= 3.141592653589793238;
const ll INF= LONG_LONG_MAX;
const ll mod=1e9+7;

//TypeDef
typedef vector<int> vi;
typedef vector<pair<int, int>> vpi;
typedef pair<ll, ll> pll;
typedef vector<ll> vll;
typedef vector<pll> vpll;
typedef vector<string> vs;
typedef unordered_map<ll,ll> umll;
typedef map<ll,ll> mll;

// Macros
#define F first
#define S second
#define pb push_back
#define mp make_pair
#define fl(i, n) for(int i= 0; i< n; ++i)
#define rtl(i, m, n) for(int i= n;i>= m; --i)
#define yes cout<<"YES\n"
#define no cout<<"NO\n"
#define minus cout << "-1\n"
#define all(v) v.begin(),v.end()

//Debug
#ifdef ruria
#define debug(x) cerr << #x << " "; cerr << x << " "; cerr << endl;
#else
#define debug(x);
#endif

// Operator overloads
template<typename T1, typename T2> // cin >> pair<T1, T2>
istream& operator>>(istream &istream, pair<T1, T2> &p) { return (istream >> p.first >> p.second); }
template<typename T> // cin >> vector<T>
istream& operator>>(istream &istream, vector<T> &v){ for (auto &it: v)cin >> it; return istream; }
template<typename T1, typename T2> // cout << pair<T1, T2>
ostream& operator<<(ostream &ostream, const pair<T1, T2> &p) { return (ostream << p.F << " " << p.S); }
template<typename T> // cout << vector<T>
ostream& operator<<(ostream &ostream, const vector<T> &c) { for (auto &it: c) cout << it << " "; return ostream; }

// Utility functions
template <typename T>
void print(T &&t)  { cout << t << "\n"; }
void printarr(int arr[], int n){ fl(i, n) cout << arr[i] << " "; cout << "\n"; }
template<typename T>
void printvec(vector<T>v){ ll n= v.size(); fl(i, n) cout << v[i] << " "; cout << "\n"; }
template<typename T>
ll sumvec(vector<T>v){ ll n= v.size(); ll s= 0; fl(i, n) s+= v[i]; return s; }

// Mathematical functions
ll gcd(ll a, ll b){ if (b == 0) return a; return gcd(b, a % b); } //__gcd
ll lcm(ll a, ll b){ return (a/gcd(a,b)*b); }
ll moduloMultiplication(ll a,ll b,ll mod){ ll res = 0; a %= mod; while (b){ if(b & 1) res = (res + a) % mod; b >>= 1; } return res; }
ll powermod(ll x, ll y, ll p){ ll res = 1; x = x % p; if (x == 0) return 0; while (y > 0){ if(y & 1) res = (res*x) % p; y = y>>1; x = (x*x) % p; } return res; }

//Graph-dfs
// bool gone[MN];
// vector<int> adj[MN];
// void dfs(int loc){
//     gone[loc]=true;
//     for(auto x:adj[loc])if(!gone[x])dfs(x);
// }

//Sorting
bool sorta(const pair<int,int> &a,const pair<int,int> &b){return (a.second < b.second);}
bool sortd(const pair<int,int> &a,const pair<int,int> &b){return (a.second > b.second);}

//Bits
string decToBinary(int n){string s="";int i = 0;while (n > 0) {s =to_string(n % 2)+s;n = n / 2;i++;}return s;}
ll binaryToDecimal(string n){string num = n;ll dec_value = 0;int base = 1;int len = num.length();for(int i = len - 1; i >= 0; i--){if (num[i] == '1')dec_value += base;base = base * 2;}return dec_value;}

//Check
bool isPrime(ll n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(int i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
bool isPowerOfTwo(ll n){if(n==0)return false;return (ceil(log2(n)) == floor(log2(n)));}
bool isPerfectSquare(ll x){if (x >= 0) {ll sr = sqrt(x);return (sr * sr == x);}return false;}

//Code
void solve() {
    int n;
    cin >> n;
    vi v1(n);
    vi v2(n);
    cin >> v1 >> v2;
    int hisAlone= 0, myAlone= 0, common= 0;
    int myScore= 0, hisScore= 0;
    for(int i= 0; i< n; ++i) {
    	if(v1[i]== 1 and v2[i]== 0) myAlone++;
    	else if(v1[i]== 0 and v2[i]== 1) hisAlone++;
    	else if(v1[i]== 1 and v2[i]== 1) common++;
    }
    if(myAlone== 0) {
    	cout << -1;
    	return;
    }
    hisScore= hisAlone+common;
    myScore= common;
    int more= hisScore-myScore+1;
   	if(more<= myAlone) {
 	  	cout << 1;
 	  	return;
   	}
   	double one= double(more)/myAlone;
   	int two= more/myAlone;
   	if(one== two) cout << two;
   	else cout << two+1;
}

//Main
int main() {

	fast
	input
	output

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

    // Uncomment for Kickstart
    // fl(i,t) {
    //     cout<<"Case #"<<i+1<<": ";
    //     solve();
    //     cout<<"\n";
    // }
}

// End


D. Chaotic V.time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputÆsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years; it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1,2,3,…1,2,3,…). The node with a number xx (x>1x>1), is directly connected with a node with number xf(x)xf(x), with f(x)f(x) being the lowest prime divisor of xx.Vanessa's mind is divided into nn fragments. Due to more than 500 years of coma, the fragments have been scattered: the ii-th fragment is now located at the node with a number ki!ki! (a factorial of kiki).To maximize the chance of successful awakening, Ivy decides to place the samples in a node PP, so that the total length of paths from each fragment to PP is smallest possible. If there are multiple fragments located at the same node, the path from that node to PP needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node PP.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — number of fragments of Vanessa's mind.The second line contains nn integers: k1,k2,…,knk1,k2,…,kn (0≤ki≤50000≤ki≤5000), denoting the nodes where fragments of Vanessa's mind are located: the ii-th fragment is at the node with a number ki!ki!.OutputPrint a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node PP).As a reminder, if there are multiple fragments at the same node, the distance from that node to PP needs to be counted multiple times as well.ExamplesInputCopy3
2 1 4
OutputCopy5
InputCopy4
3 1 4 4
OutputCopy6
InputCopy4
3 1 4 1
OutputCopy6
InputCopy5
3 1 4 1 5
OutputCopy11
NoteConsidering the first 2424 nodes of the system; the node network will look as follows (the nodes 1!1!, 2!2!, 3!3!, 4!4! are drawn bold):For the first example, Ivy will place the emotion samples at the node 11. From here:  The distance from Vanessa's first fragment to the node 11 is 11.  The distance from Vanessa's second fragment to the node 11 is 00.  The distance from Vanessa's third fragment to the node 11 is 44. The total length is 55.For the second example, the assembly node will be 66. From here:  The distance from Vanessa's first fragment to the node 66 is 00.  The distance from Vanessa's second fragment to the node 66 is 22.  The distance from Vanessa's third fragment to the node 66 is 22.  The distance from Vanessa's fourth fragment to the node 66 is again 22. The total path length is 66.

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

#define N 5000

#define M 5000005

using namespace std;

int tot,n,pr[N+5],cnt,s[N+5][705],son[M],a[M],v[N+5],p[N+5][705];

long long asw,sum[M];

bool vi[N+5];

struct nood {

	int to,next,v;

} g[M];

inline void add(int x,int y,int z) {

	g[++cnt].v=z,g[cnt].to=y,g[cnt].next=a[x],a[x]=cnt;

}

inline void dfs(int u) {

	for(int j,i=a[u]; i; i=g[i].next) {

		dfs(j=g[i].to),son[u]+=son[j],sum[u]+=sum[j]+1ll*son[j]*g[i].v;

	}

}

inline void Dfs(int u) {

	for(int j,i=a[u]; i; i=g[i].next) {

		if(son[j=g[i].to]*2>son[0]) {

			asw-=1ll*g[i].v*(son[j]*2-son[0]);

			return Dfs(j);

		}

	}

}

int main() {

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

		if(!vi[i]) pr[++pr[0]]=i;

		for(int j=1; j<=pr[0]; j++) {

			if(i*pr[j]>N) break;

			vi[i*pr[j]]=1;

			if(i%pr[j]==0) break;

		}

	}

	scanf("%d",&n);

	for(int x,i=1; i<=n; i++) scanf("%d",&x),v[max(x,1)]++;

	son[0]=v[1];

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

		int op=0;

		for(int j=pr[0]; j; j--) {

			if(pr[j]>i) continue;

			int k=i;

			while(k) s[i][j]+=k/pr[j],k/=pr[j];

			if(op) add(p[i][j+1],p[i][j]=++tot,s[i][j]);

			else if(s[i-1][j]!=s[i][j]) {

				add(p[i-1][j],p[i][j]=++tot,s[i][j]-s[i-1][j]),op=1;

			} else p[i][j]=p[i-1][j];

		}

		son[tot]=v[i];

	}

	dfs(0),asw=sum[0],Dfs(0),printf("%lld",asw);

}


B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string:   Pick an integer kk, (1≤k≤n1≤k≤n).  For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through:   qwer (original string)  wqer (after reversing the first substring of length 22)  weqr (after reversing the second substring of length 22)  werq (after reversing the last substring of length 22)  Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds:   aa is a prefix of bb, but a≠ba≠b;  in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p
OutputCopyabab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1
NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows :   for k=1k=1 : abab  for k=2k=2 : baba  for k=3k=3 : abab  for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11.

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

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

int T;
int n,m,k;
string str;

void solve() {
    n=read();

    cin>>str;

    int id=1;
    string ans=str;
    for(int i=2;i<=n;i++) {
        if((n-i+1)%2==1) {
            string p=str.substr(0,i-1);
            reverse(p.begin(),p.end());
            string k=str.substr(i-1,n-i+1)+p;
            if(ans>k) {
                ans=k;
                id=i;
            }

        }else {
            string k=str.substr(i-1,n-i+1)+str.substr(0,i-1);
            if(ans>k) {
                ans=k;
                id=i;
            }
        }
    }

    cout<<ans<<'\n'<<id<<'\n';
}

int main() {

    scanf("%d",&T);

    // T=1;
    while(T--) solve();

    return 0;
}


C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3
2 4
1 1
1 1
1 2
2 1
2 2

3 4
1 1 1
1 1
1 2
2 2
2 3

4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
OutputCopy2
1
12
NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11.

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

#include<unordered_map>

#include<algorithm>

using namespace std;

#define ll long long

#define pii pair<ll,ll>

//struct Edge {

//	int from, to, nex;

//}edge[400010];

//int tot, head[200010];

//void add(int u, int v) {

//	edge[++tot] = { u,v,head[u] };

//	head[u] = tot;

//}

const ll mod = 998244353;

ll qpow(ll x, ll y) {

    ll res = 1;

    while (y) {

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

        x = x * x % mod;

        y >>= 1;

    }

    return res;

}

ll n,m;

ll gcd(ll a, ll b) {

    return b ? gcd(b, a % b) : a;

}

void solve()

{

    cin >> n >> m;

    vector<ll> a(n + 1);

    vector<set<int>> s(n + 1);

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

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

        int u, v;

        cin >> u >> v;

        s[v].insert(u);

    }

    map<set<int>, ll> mp;

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

      if(!s[i].empty())  mp[s[i]] += a[i];

    }

    ll ans = 0;

    for (auto i : mp) {

        if (ans) ans = gcd(ans, i.second);

        else ans = i.second;

    }

    cout << ans << '\n';

}

signed main()

{

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

    int tt = 1;

    cin >> tt;

    while (tt--) solve();

    return 0;

}

/*

*/


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

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int maxn = 2e5 + 10;

int a[maxn];

int main()

{

    ios::sync_with_stdio(0);

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

    int t;

    cin >> t;

    while (t--) {

        int n;

        string s;

        cin >> n >> s;

        int m = n;

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

            int len = 1;

            while (i < n - 1 && s[i] == '<') {

                ++i;

                ++len;

            }

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

                a[j] = m--;

            }

        }

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

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

        }

        cout << endl;

        m = 1;

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

            int len = 1;

            while (i < n - 1 && s[i] == '>') {

                ++i;

                ++len;

            }

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

                a[j] = m++;

            }

        }

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

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

        }

        cout << endl;

    }

    return 0;

}


E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.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 only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3
5 7
10 19
10 18
OutputCopyYES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
NotePictures corresponding to the first and the second test cases of the example:

#pragma GCC optimize("O2")

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

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace std;

using namespace __gnu_pbds;

#define ll     long long

#define test   int _TEST; cin>>_TEST; while(_TEST--)

#define ff     first

#define ss     second

#define pb     push_back

#define ppb    pop_back

#define pf     push_front

#define ppf    pop_front

template <typename T> using Ordered_Set_Tree =

        tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

template <typename T> using Ordered_Multiset_Tree =

        tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;

template <typename A, typename B> ostream& operator<<(ostream& s, const pair<A, B>& self) {s << self.first << ' ' << self.second << ' '; return s; }

template <typename T> ostream& operator<<(ostream& s, const vector<T>& self) { for (auto e : self) { s << e << '\n'; } return s; }

template <typename T> ostream& operator<<(ostream& s, tuple<T, T, T>& self) { s << get<0>(self) << ' ' << get<1>(self) << ' ' << get<2>(self); return s; }

template <typename A, typename B> istream& operator>>(istream& s, pair<A, B>& self) { s >> self.first >> self.second; return s; }

template <typename T> istream& operator>>(istream& s, tuple<T, T, T>& self) { s >> get<0>(self) >> get<1>(self) >> get<2>(self); return s; }

template <typename T> istream& operator>>(istream& s, tuple<T, T, T, T>& self) { s >> get<0>(self) >> get<1>(self) >> get<2>(self) >> get<3>(self); return s; }

template <typename T> istream& operator>>(istream& s, vector<T>& self) { for (size_t i = 0; i < self.size(); ++i) { s >> self[i]; } return s; }

///DEBUG

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

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

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

void _Print(long long t) {cerr << t;}

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

void _Print(unsigned long long t) {cerr << t;}

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

template <class T> void _Print(list <T> &v);

template <class T> void _Print(vector <T> &v);

template <class T> void _Print(deque <T> &v);

template <class T, class V> void _Print(T *v, V sz);

template <class T, class V, class P> void _Print(T *v, V sz, P sm);

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 << "}\n\n";}

template <class T> void _Print(list <T> &v) {cerr << "[ "; for (T i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";}

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

template <class T> void _Print(deque <T> &v) {cerr << "[ "; for (T i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";}

template <class T, class V> void _Print(T *v, V sz) {cerr << "[ "; for(int i=0; i<sz; i++) {_Print(v[i]); cerr << " ";} cerr << "]\n\n";}

template <class T, class V, class P> void _Print(T *v, V sz, P sm) {cerr << "[\n"; for(int i=0; i<sz; i++) { for(int j=0; j<sm; j++) {_Print(v[i][j]); cerr << " ";} cerr << "\n";} cerr << "]\n\n";}

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

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

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

#define debug(...) debug_out(vec_splitter(#__VA_ARGS__), 0, __LINE__, __VA_ARGS__)

vector<string> vec_splitter(string s)

{

    s += ',';

    vector<string> res;

    while(!s.empty())

    {

        res.push_back(s.substr(0, s.find(',')));

        s = s.substr(s.find(',') + 1);

    }

    return res;

}

void debug_out(vector<string> __attribute__ ((unused)) args, __attribute__ ((unused)) int idx, __attribute__ ((unused)) int LINE_NUM) { cerr << endl; }

template <typename Head, typename... Tail> void debug_out(vector<string> args, int idx, int LINE_NUM, Head H, Tail... T)

{

    if(idx > 0) cerr << ", "; else cerr << "Line(" << LINE_NUM << ") ";

    stringstream ss; ss << H;

    cerr << args[idx] << " = " << ss.str();

    debug_out(args, idx + 1, LINE_NUM, T...);

}

///DEBUG

int main()

{

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    test

    {

        int n, d;

        cin>>n>>d;

        int mmax = (n*(n-1))/2;

        int mmin = 0;

        int x = n-1, dd=1, mul=2;

        while(x > mul)

        {

            mmin += mul * dd;

            dd++;

            x -= mul;

            mul *= 2;

        }

        mmin += x * dd;

        if(d>mmax || d<mmin)

        {

            cout<<"NO\n";

            continue;

        }

        ll int val = mmax;

        vector<int> par(n);

        vector<set<int>> canTake(n);

        vector<int> child(n, 0);

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

        {

            canTake[i].insert(i);

            par[i] = i-1;

            child[i] = 1;

        }

        child[n-1] = 0;

        for(int u=n-1; u>0 && val>d; u--)

        {

            int dig = u-1;

            while(dig && val>d && canTake[dig-1].size()>0)

            {

                val--;

                dig--;

            }

            child[par[u]]--;

            par[u] = *canTake[dig].begin();

            child[*canTake[dig].begin()]++;

            if(child[*canTake[dig].begin()] == 2)

                canTake[dig].erase(canTake[dig].begin());

            canTake[dig+1].insert(u);

        }

        cout<<"YES\n";

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

            cout<<par[i]+1<<" ";

        cout<<"\n";

    }

}


#include<bits/stdc++.h>

using namespace std;

#define int long long

#define PII pair<int,int>

#define x first

#define y second

const int N=1e5+10;

void solve()

{

	string s;

	int n;

	cin>>n>>s;

	int l=0,m=n;

	vector<int> res(n);

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

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

	{

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

			res[j]=m--;

		l=i+1;

	}

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

		cout<<res[i]<<' ';

	cout<<endl;

	l=0,m=1;

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

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

	{

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

			res[j]=m++;

		l=i+1;

	}

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

		cout<<res[i]<<' ';

	cout<<endl;

	return;

}

signed main()

{

	ios::sync_with_stdio(false);

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

	int T=1;

	cin>>T;

	while(T--)

		solve();

	return 0;

}


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

#pragma GCC optimize("Ofast")

#pragma GCC optimize ("unroll-loops")

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

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include "stdio.h"

using namespace std;

using namespace __gnu_pbds;

// #define int long long

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

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

#define ff first

#define ss second

#define sz(a) (a).size()

template<typename T> using indexed_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

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

typedef long double ld;

namespace io{

    template<typename F, typename S> ostream& operator << ( ostream &os, const pair<F, S> &p ) { return os << p.ff << " " << p.ss; }

    template<typename F, typename S> ostream& operator << ( ostream &os, const map<F, S> &mp ) { for( auto it : mp ) { os << it << endl;  } return os; }

    template<typename F> ostream& operator << ( ostream &os, const vector<F> &v ) { bool space = false; for( F x : v ) { if( space ) os << " "; space = true; os << x; } return os; }

    template<typename F> ostream& operator << ( ostream &os, const deque<F> &d ) { bool space = false; for( F x : d ) { if( space ) os << " "; space = true; os << x; } return os; }

    template<typename F> ostream& operator << ( ostream &os, const set<F> &st ) { bool space = false; for( F x : st ) { if( space ) os << " "; space = true; os << x; } return os; }

    template<typename F> ostream& operator << ( ostream &os, const multiset<F> &st ) { bool space = false; for( F x : st ) { if( space ) os << " "; space = true; os << x; } return os; }

    template<typename F, typename S> istream& operator >> ( istream &is, pair<F, S> &p ) { return is >> p.ff >> p.ss; }

    template<typename F> istream& operator >> ( istream &is, vector<F> &v ) { for( F &x : v ) { is >> x; } return is; }

    long long fastread(){ char c; long long d = 1, x = 0; do c = getchar(); while( c == ' ' || c == '\n' ); if( c == '-' ) c = getchar(), d = -1; while( isdigit( c ) ){ x = x * 10 + c - '0'; c = getchar(); } return d * x; }

    static bool sep = false;

    using std::to_string;

    string to_string( bool x ){ return ( x ? "true" : "false" ); }

    string to_string( const string & s ){ return "\"" + s + "\""; }

    string to_string( const char * s ){ return "\"" + string( s ) + "\""; }

    string to_string ( const char & c ) { string s; s += c; return "\'" + s + "\'"; }

    template<typename Type> string to_string( vector<Type> );

    template<typename F, typename S> string to_string( pair<F, S> );

    template<typename Collection> string to_string( Collection );

    template<typename F, typename S> string to_string( pair<F, S> p ){ return "{" + to_string( p.ff ) + ", " + to_string( p.ss ) + "}"; }

    template<typename Type> string to_string( vector<Type> v ) { bool sep = false; string s = "["; for( Type x: v ){ if( sep ) s += ", "; sep = true; s += to_string( x ); } s += "]"; return s; }

    template<typename Collection> string to_string( Collection collection ) { bool sep = false; string s = "{"; for( auto x: collection ){ if( sep ) s += ", "; sep = true; s += to_string( x ); } s += "}"; return s; }

    void print() { cout << endl; sep = false; }

    template <typename F, typename... Other> void print( F ff, Other... other ) { if( sep ) cout << " | "; sep = true; cout << to_string( ff ); print( other... ); }

} using namespace io;

namespace utils {

    template<typename F, typename S> inline void maxs ( F &a, S b ) { a = a > b ? a : b; }

    template<typename F, typename S> inline void mins ( F &a, S b ) { a = a < b ? a : b; }

    template<typename F, typename S> int max(F a, S b) { return a > b ? a : b; }

    template<typename F, typename S> int min(F a, S b) { return a < b ? a : b; }

    constexpr long long operator"" _E ( unsigned long long n ){ long long p = 1, a = 10; for( int i = 0; i < n; i++ ) p *= a; return p; }

    random_device rd; mt19937 mt( rd( ) );

    template<typename T> T rand ( T l, T r ) { uniform_int_distribution<T> dist( l, r ); return dist( mt ); };

} using namespace utils;

#ifdef sunnitov

#define print( ... ) cout << "[" << #__VA_ARGS__ << "]: "; io::print( __VA_ARGS__ );

#else

#define print( ... ) 42

#endif

int mod = 9_E + 7;

const double EPS = 1e-7;

long long LLINF = 18_E + 10;

int INF = 9_E + 10;

const char nl = '\n';

int month[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};

/*

*/

int n, m, tar;

vector<vector<int>> a;;

bool ok(int mid) {

    vector<bool> can(tar + 1);

    vector<int> bit(n + 1);

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

        int pw = 1;

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

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

                bit[i] += pw;

            }

            pw *= 2;

        }

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

            if ((j | bit[i]) == bit[i]) {

                can[j] = 1;

            }

        }

    }

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

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

            if (can[j] and (j | bit[i]) == tar) {

                return true;

            }

        }

    }

    return false;

}

void solution( istream &cin, ostream &cout, const int &test_case ){

    cin >> n >> m;

    tar = (1 << m) - 1;

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

    cin >> a;

    int l = 0, r = 1e9 + 100, ans = -1;

    while (l <= r) {

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

        if (ok(mid)) {

            ans = mid;

            l = mid + 1;

        } else {

            r = mid - 1;

        }

    }

    // cout << ans;

    vector<bool> can(tar + 1);

    vector<int> bit(n + 1);

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

        int pw = 1;

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

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

                bit[i] += pw;

            }

            pw *= 2;

        }

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

            if ((j | bit[i]) == bit[i]) {

                can[j] = 1;

            }

        }

    }

    int ia, ij;

    for (int x1 = 0; x1 <= tar; x1++) {

        for (int x2 = 0; x2 <= tar; x2++) {

            if (!can[x1] or !can[x2] or (x1 | x2) != tar) continue;

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

                if ((bit[i] | x1) == bit[i]) ia = i;

                if ((bit[i] | x2) == bit[i]) ij = i;

            }

        }

    }

    cout << ia + 1 << " " << ij + 1;

}

int32_t main(){

    clock_t startTime = clock();

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

    srand( time( 0 ) );

    std::istream& in( std::cin ) ;

    std::ostream& out( std::cout );

    int32_t queries = 1;

    #ifdef test_cases

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

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

    cin >> queries;

    #else

    // cin >> queries;

    #endif

    for( int32_t test_case = 1; test_case <= queries; test_case++ ){

    	print(test_case);

        solution( cin, cout, test_case );

        cout << nl;

    }

    #ifdef sunnitov

    cout << "Time: " << (int)((double) (clock() - startTime) / CLOCKS_PER_SEC * 1000) << " ms" << endl;

    #endif

    return EXIT_SUCCESS;

}


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

#include <bits/stdc++.h>

#include <iostream>

using namespace std;

void solve()

{

    int n;

    cin >> n;

    int a[n];

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

    {

        cin >> a[i];

    }

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

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

    {

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

    }

    cout<<endl;

    return ;

}

int main()

{

    int t;

    cin >> t;

    while (t--)

    {

        solve();

    }

    return 0;

}


B. Double Eliminationtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe biggest event of the year – Cota 2 world championship "The Innernational" is right around the corner. 2n2n teams will compete in a double-elimination format (please, carefully read problem statement even if you know what is it) to identify the champion. Teams are numbered from 11 to 2n2n and will play games one-on-one. All teams start in the upper bracket.All upper bracket matches will be held played between teams that haven't lost any games yet. Teams are split into games by team numbers. Game winner advances in the next round of upper bracket, losers drop into the lower bracket.Lower bracket starts with 2n−12n−1 teams that lost the first upper bracket game. Each lower bracket round consists of two games. In the first game of a round 2k2k teams play a game with each other (teams are split into games by team numbers). 2k−12k−1 loosing teams are eliminated from the championship, 2k−12k−1 winning teams are playing 2k−12k−1 teams that got eliminated in this round of upper bracket (again, teams are split into games by team numbers). As a result of each round both upper and lower bracket have 2k−12k−1 teams remaining. See example notes for better understanding.Single remaining team of upper bracket plays with single remaining team of lower bracket in grand-finals to identify championship winner.You are a fan of teams with numbers a1,a2,...,aka1,a2,...,ak. You want the championship to have as many games with your favourite teams as possible. Luckily, you can affect results of every championship game the way you want. What's maximal possible number of championship games that include teams you're fan of?InputFirst input line has two integers n,kn,k — 2n2n teams are competing in the championship. You are a fan of kk teams (2≤n≤17;0≤k≤2n2≤n≤17;0≤k≤2n).Second input line has kk distinct integers a1,…,aka1,…,ak — numbers of teams you're a fan of (1≤ai≤2n1≤ai≤2n).OutputOutput single integer — maximal possible number of championship games that include teams you're fan of.ExamplesInputCopy3 1
6
OutputCopy6
InputCopy3 3
1 7 8
OutputCopy11
InputCopy3 4
1 3 5 7
OutputCopy14
NoteOn the image; each game of the championship is denoted with an English letter (aa to nn). Winner of game ii is denoted as WiWi, loser is denoted as LiLi. Teams you're a fan of are highlighted with red background.In the first example, team 66 will play in 6 games if it looses the first upper bracket game (game cc) and wins all lower bracket games (games h,j,l,mh,j,l,m). In the second example, teams 77 and 88 have to play with each other in the first game of upper bracket (game dd). Team 88 can win all remaining games in upper bracket, when teams 11 and 77 will compete in the lower bracket. In the third example, your favourite teams can play in all games of the championship.

#include<iostream>

#include<cstring>
#include<algorithm>
using namespace std;
using LL = long long;
const int maxn = 1e6 + 5;

bool v[maxn];

int main(){

#ifdef LOCAL
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif

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

const int INF = 1e9;
int n, k;
cin >> n >> k;
if (k == 0){
cout << 0 << '\n';
return 0;
}
vector<array<int, 4> > dp(1 << n, {0, -INF, -INF, -INF});
for(int i = 1; i <= k; i++){
int x;
cin >> x;
int s = (1 << n - 1) + (x - 1) / 2;
if (dp[s][1] != -INF) dp[s][3] = 1;
else dp[s][1] = dp[s][2] = 1;
}
for(int i = (1 << n - 1) - 1; i >= 1; i--){
for(int j = 0; j < 4; j++){
for(int k = 0; k < 4; k++){
dp[i][j | k] = max(dp[i][j | k], dp[2 * i][j] + dp[2 * i + 1][k] + (j | k));
}
}
}
cout << max({dp[1][1], dp[1][2], dp[1][3]}) + 1 << '\n';

}


F. Making Shapestime limit per test5 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputYou are given nn pairwise non-collinear two-dimensional vectors. You can make shapes in the two-dimensional plane with these vectors in the following fashion: Start at the origin (0,0)(0,0). Choose a vector and add the segment of the vector to the current point. For example, if your current point is at (x,y)(x,y) and you choose the vector (u,v)(u,v), draw a segment from your current point to the point at (x+u,y+v)(x+u,y+v) and set your current point to (x+u,y+v)(x+u,y+v). Repeat step 2 until you reach the origin again.You can reuse a vector as many times as you want.Count the number of different, non-degenerate (with an area greater than 00) and convex shapes made from applying the steps, such that the shape can be contained within a m×mm×m square, and the vectors building the shape are in counter-clockwise fashion. Since this number can be too large, you should calculate it by modulo 998244353998244353.Two shapes are considered the same if there exists some parallel translation of the first shape to another.A shape can be contained within a m×mm×m square if there exists some parallel translation of this shape so that every point (u,v)(u,v) inside or on the border of the shape satisfies 0≤u,v≤m0≤u,v≤m.InputThe first line contains two integers nn and mm  — the number of vectors and the size of the square (1≤n≤51≤n≤5, 1≤m≤1091≤m≤109).Each of the next nn lines contains two integers xixi and yiyi  — the xx-coordinate and yy-coordinate of the ii-th vector (|xi|,|yi|≤4|xi|,|yi|≤4, (xi,yi)≠(0,0)(xi,yi)≠(0,0)).It is guaranteed, that no two vectors are parallel, so for any two indices ii and jj such that 1≤i<j≤n1≤i<j≤n, there is no real value kk such that xi⋅k=xjxi⋅k=xj and yi⋅k=yjyi⋅k=yj.OutputOutput a single integer  — the number of satisfiable shapes by modulo 998244353998244353.ExamplesInputCopy3 3
-1 0
1 1
0 -1
OutputCopy3
InputCopy3 3
-1 0
2 2
0 -1
OutputCopy1
InputCopy3 1776966
-1 0
3 3
0 -2
OutputCopy296161
InputCopy4 15
-4 -4
-1 1
-1 -4
4 3
OutputCopy1
InputCopy5 10
3 -4
4 -3
1 -3
2 -3
-3 -4
OutputCopy0
InputCopy5 1000000000
-2 4
2 -3
0 -4
2 4
-1 -3
OutputCopy9248783
NoteThe shapes for the first sample are:  The only shape for the second sample is:  The only shape for the fourth sample is:


E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times:  Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair).  Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5
4 3 2 2 3
OutputCopy2
InputCopy7
3 3 4 4 4 3 3
OutputCopy2
InputCopy3
1 3 5
OutputCopy3
InputCopy1
1000
OutputCopy1
NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all.

#include<iostream>

#include<cstring>

#include<algorithm>

using namespace std;

int n;

const int N = 1100;

int a[N],s[N];

int f[N][N],g[N];

int main()

{

    cin>>n;

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

    {

        cin>>a[i];

        f[i][i]=a[i];

    }

    for(int len=2;len<=n;len++)

    {

        for(int l=1;l+len-1<=n;l++)

        {

            int r=l+len-1;

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

            {

                if(f[l][k]==f[k+1][r] && f[l][k]) f[l][r]=f[k+1][r]+1;

            }

        }

    }

    memset(g,0x3f,sizeof g);

    g[0]=0;

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

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

    if(f[j+1][i]) g[i]=min(g[i],g[j]+1);

    cout<<g[n];

}


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.

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace std;

using namespace __gnu_pbds;

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

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

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

#define rep(i, v) for (int i = 0; i < siz(v); ++i)

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

#define fp(i, j, n) for (long long i = (j); i <= (long long)(n); ++i)

#define fn(i, j, n) for (int i = (j); i >= (int)(n); --i)

#define fvec(i, vec) for (auto i : vec)

#define pb push_back

#define MP make_pair

#define mine(x, y, z) min(x, min(y, z))

#define maxe(x, y, z) max(x, max(y, z))

#define F first

#define S second

typedef unsigned long long ull;

typedef long long ll;

typedef long double ld;

typedef vector<int> vi;

typedef pair<ll,ll> pll;

typedef pair<int,int> pi;

typedef vector<pll> vp;

typedef vector< long long> vll;

typedef vector<double> vd;

typedef vector<vi> vvi;

typedef vector<vd> vvd;

typedef vector<string> vs;

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

#define setp(item) cout<<fixed<<setprecision(item);

ll gcd(ll a, ll b) { return ((b == 0) ? a : gcd(b, a % b)); }

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

const ll OO = 1e18, mod = 1e9+7,mod2=1e9+9, N =1e6+5,M=30,MOD=998244353;

///   هذا الحل من وحي خيال المؤلف واي تشابه بينه و بين اي حل اخر ما هو الا محض الصدفة

void solve(int inde) {

    ll num,k;cin>>num>>k;

    vll vec(num);

    fo(i,num)cin>>vec[i];

    fp(i,1,num-1){

        ll nu=k/i;

        ll nn=min(nu,vec[i]);

        vec[0]+=min(nu,vec[i]);

        k-=i*nn;

    }

    cout<<vec[0]<<'\n';

}

int main() {

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

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

    ios_base::sync_with_stdio(false);

    cin.tie(nullptr);

    cout.tie(nullptr);

    ll t=1;

    cin>>t;

    ll index=1;

    while (t--){

        solve(index++);

    }

    return 0;

}


B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2
1 0 1
1 1 1
OutputCopy4
InputCopy3 5 4
1 1 1
1 1 1 1 1
OutputCopy14
NoteIn first example matrix cc is:  There are 44 subrectangles of size 22 consisting of only ones in it:  In second example matrix cc is:

#include "bits/stdc++.h"

using namespace std;

#ifdef LOCAL

#include "debug.h"

#endif

// abbreviations

using chr = char;     using ll = long long;     using pll = pair<ll, ll>;

using str = string;   using ld = long double;   using pii = pair<int, int>;

template<class T> using MaxHeap = priority_queue<T, vector<T>,    less<T>>;

template<class T> using MinHeap = priority_queue<T, vector<T>, greater<T>>;

template<typename T, typename T1> T amax(T &a, T1 b) { if (b > a) a = b; return a; }

template<typename T, typename T1> T amin(T &a, T1 b) { if (b < a) a = b; return a; }

// definitons

#define fi first

#define se second

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

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

// constants

const int maxN = 1e6 + 2;

const int Mod = 1e9 + 7, Modd = 998244353;

const int inf = 0x3f3f3f3f;

const ll linf = 1e18;

void aine() {

    int n, m, k;

    cin >> n >> m >> k;

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

    vector<int> div;

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

        if (k % i == 0) {

            div.push_back(i);

        }

    }

    for (auto &i : a) cin >> i;

    for (auto &i : b) cin >> i;

    vector<int> suba, subb;

    vector<int> nums(n + 1), Nums(m + 1);

    a.push_back(0); b.push_back(0);

    int len = 0;

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

        if (a[i] == 0) {

            suba.push_back(len);

            len = 0;

        }

        else len++;

    }

    len = 0;

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

        if (b[i] == 0) {

            subb.push_back(len);

            len = 0;

        }

        else len++;

    }

    for (auto i : suba) {

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

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

        }

    }

    for (auto i : subb) {

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

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

        }

    }

    // debug(nums, Nums, div);

    ll ans = 0;

    for (auto i : div) {

        int p = i, q = k / i;

        if (p <= n && q <= m) ans += 1ll * nums[p] * Nums[q];

        if (p != q && p <= m && q <= n) ans += 1ll * nums[q] * Nums[p];

    }

    cout << ans << '\n';

}

signed main() {

    cin.tie(0)->sync_with_stdio(false);

    int t = 1;

    // cin >> t;

    while (t--) { aine(); } cout << '\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.

/* Author: izhang
 * Time: 02-06-2023 22:48:21
**/
#include <bits/stdc++.h>

using namespace std;

#if defined LOCAL || defined DEBUG
#include <debug.h>
#else
struct dbg {
    template<class c>
    dbg &operator<<(const c &) { return *this; }
};
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "
#endif

//#define DEBUG
void setIO(const string &name) {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cin.exceptions(istream::failbit);
#ifdef LOCAL
    freopen(("in" + name + ".txt").c_str(), "r", stdin);
    freopen("out.txt", "w", stdout);
    freopen("out.txt", "w", stderr);
#endif
}
const int inf = 0x3f3f3f3f, mod = 1e9 + 7; //998244353;
const long long INFL = 0x3f3f3f3f3f3f3f3f;

void test_case() {
    int n;
    cin >> n;
    string s;
    cin >> s;
    int sol = 0;
    bool found = true;
    while (found) {
        found = false;
        pair<char, int> mx;
        for (int i = 0; i < n; ++i) {
            if ((i > 0 && s[i - 1] + 1 == s[i]) || (i < n && s[i + 1] + 1 == s[i])) {
                mx = max(mx, {s[i], i});
                found = true;
            }
        }
        if (found) {
            string tmp;
            for (int i = 0; i < n; ++i) {
                if (i != mx.second) {
                    tmp += s[i];
                }
            }
            swap(s, tmp);
            ++sol;
        }
    }
    cout << sol << "\n";
}

int main() {
    setIO("1");

    int test_case_number = 1;
    while (test_case_number--) {
        test_case();
    }
    return 0;
}


F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3
1 3 2
-100 2 3
OutputCopy3
InputCopy5
2 1 4 3 5
2 2 2 3 4
OutputCopy19
InputCopy2
2 1
-3 0
OutputCopy0

#include <iostream>

#include <vector>

#include <algorithm>

#include <map>

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

#define LEFT(n) (2*n)

#define RIGHT(n) (2*n + 1)

using namespace std;

struct Point

{

    long long distance, velocity;

    Point(){};

    Point(long long D, long long V)

    {

        distance = D;

        velocity = V;

    }

};

int sort_by_distance(const Point &P, const Point &Q)

{

    return (P.distance < Q.distance);

}

const int MAX_N = 2e5 + 5;

pair <long long, int> sum_tree[3*MAX_N];

void update(int n, int left, int right, int position, long long value)

{

    if(position < left || right < position)

    {

        return;

    }

    if(left == right)

    {

        sum_tree[n].first += value;

        sum_tree[n].second++;

        //cout << "Sum Tree " << n << " = " << sum_tree[n].first << "," << sum_tree[n].second << "\n";

        return;

    }

    int mid = (left + right)/2;

    update(LEFT(n), left, mid, position, value);

    update(RIGHT(n), mid + 1, right, position, value);

    sum_tree[n].second = sum_tree[LEFT(n)].second + sum_tree[RIGHT(n)].second;

    sum_tree[n].first = sum_tree[LEFT(n)].first + sum_tree[RIGHT(n)].first;

    //cout << "Sum Tree " << n << " = " << sum_tree[n].first << "," << sum_tree[n].second << "\n";

}

pair <long long, int> get(int n, int left, int right, int query_left, int query_right)

{

    if(query_right < left || right < query_left || query_right < query_left)

    {

        return make_pair(0, 0);

    }

    if(query_left <= left && right <= query_right)

    {

        return sum_tree[n];

    }

    int mid = (left + right)/2;

    pair <long long, int> left_answer = get(LEFT(n), left, mid, query_left, query_right);

    pair <long long, int> right_answer = get(RIGHT(n), mid + 1, right, query_left, query_right);

    pair <long long, int> answer;

    answer.second = left_answer.second + right_answer.second;

    answer.first = left_answer.first + right_answer.first;

    return answer;

}

int main()

{

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    int no_of_points;

    cin >> no_of_points;

    vector <Point> P(no_of_points);

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

    {

        cin >> P[i].distance;

    }

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

    {

        cin >> P[i].velocity;

    }

    sort(all(P), sort_by_distance);

    vector <int> velocities;

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

    {

        velocities.push_back(P[i].velocity);

    }

    sort(all(velocities));

    map <long long, int> effective_index;

    effective_index[velocities[0]] = 1;

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

    {

        if(velocities[i] == velocities[i - 1])

        {

            continue;

        }

        effective_index[velocities[i]] = effective_index[velocities[i - 1]] + 1;

    }

    for(int i = 0; i < 3*MAX_N; i++)

    {

        sum_tree[i] = make_pair(0, 0);

    }

    long long answer = 0;

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

    {

        pair <long long, int> Q = get(1, 1, no_of_points, 1, effective_index[P[i].velocity]);

        long long total = Q.first;

        int no_of_points_here = Q.second;

        //cout << "At x = " << P[i].distance << " V = " << P[i].velocity << "\n";

        //cout << "No of Points = " << no_of_points_here << " Total = " << total << "\n";

        //cout << "Range = [1, " << effective_index[P[i].velocity] - 1 << "]\n";

        answer += ( (no_of_points_here)*P[i].distance - total);

        //cout << "Answer = " << answer << "\n";

        update(1, 1, no_of_points, effective_index[P[i].velocity], P[i].distance);

    }

    cout << answer << "\n";

    return 0;

}


D. Coffee Varieties (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. You can find the easy version in the Div. 2 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will:   Tell you if acac is in SS;  Add acac at the back of SS;  If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 3n22k3n22k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 3n22k≤15 0003n22k≤15 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 3n22k3n22k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:  fflush(stdout) or cout.flush() in C++;  System.out.flush() in Java;  flush(output) in Pascal;  stdout.flush() in Python;  see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 3n22k≤15 0003n22k≤15 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2
N
N
Y
N
N
N
N
OutputCopy? 1
? 2
? 3
? 4
R
? 4
? 1
? 2
! 3
InputCopy8 8
N
N
N
N
Y
Y
OutputCopy? 2
? 6
? 4
? 5
? 2
? 5
! 6
NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5.

#include<bits/stdc++.h>

using namespace std;

#pragma GCC optimize ("Ofast")

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

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

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

#define wall cout<<"--------------------------------------\n";

typedef long long int ll;

typedef pair<ll , ll> pll;

typedef pair<int , int> pii;

typedef double db;

typedef pair<pll , ll> plll;

typedef pair<int , pii> piii;

typedef pair<pll , pll> pllll;

const ll maxn = 1e6 + 17 , md = 1e9 + 7 , inf = 2e16;

char c;

bool a[maxn];

vector<ll> v[maxn];

int main(){

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

	ll n , k;

	cin>>n>>k;

	if(k > 1) k >>= 1;

	ll m = n / k , x = 0;

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

		v[x].push_back(i);

		x += (i % k == 0);

	}

	for(ll t = 1 ; t < m ; t++){

		for(ll s = 0 ; s < t ; s++){

			if(s + t >= m) break;

			for(ll i = s ; i < m ; i += t){

				for(auto j : v[i]){

					cout<<"? "<<j<<endl;

					cin>>c;

					a[j] |= (c == 'Y');

				}

			}

			cout<<"R"<<endl;

		}

	}

	ll cnt = 0;

	for(ll i = 1 ; i <= n ; i++) cnt += !a[i];

	cout<<"! "<<cnt<<endl;

	return 0;

}


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

#include<bits/stdc++.h>

using namespace std;

typedef long long ll;

int maxdp[26], ans[200001];

int main()

{

	ios::sync_with_stdio(0);

	cin.tie(0);

	cout.tie(0);

	int n, len, maxn;

	string s;

	cin>>n;

	cin>>s;

	len = s.length();

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

	{

		ans[i] = 1;

		for(int j=25;j>(s[i]-'a');--j)

		{

			ans[i] = max(ans[i], maxdp[j]+1);

		}

		maxdp[s[i]-'a'] = ans[i];

		maxn = max(maxn, maxdp[s[i]-'a']);

	}

	cout<<maxn<<"\n";

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

	{

		cout<<ans[i]<<" ";

	}

	return 0;

}