D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string ss starting from the ll-th character and ending with the rr-th character as s[l…r]s[l…r]. The characters of each string are numbered from 11.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string aa is considered reachable from binary string bb if there exists a sequence s1s1, s2s2, ..., sksk such that s1=as1=a, sk=bsk=b, and for every i∈[1,k−1]i∈[1,k−1], sisi can be transformed into si+1si+1 using exactly one operation. Note that kk can be equal to 11, i. e., every string is reachable from itself.You are given a string tt and qq queries to it. Each query consists of three integers l1l1, l2l2 and lenlen. To answer each query, you have to determine whether t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1].InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of string tt.The second line contains one string tt (|t|=n|t|=n). Each character of tt is either 0 or 1.The third line contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries.Then qq lines follow, each line represents a query. The ii-th line contains three integers l1l1, l2l2 and lenlen (1≤l1,l2≤|t|1≤l1,l2≤|t|, 1≤len≤|t|−max(l1,l2)+11≤len≤|t|−max(l1,l2)+1) for the ii-th query.OutputFor each query, print either YES if t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1], or NO otherwise. You may print each letter in any register.ExampleInputCopy5
11011
3
1 3 3
1 4 2
1 2 3
OutputCopyYes
Yes
No

#include<bits/stdc++.h>

typedef long long ll;

typedef unsigned long long ull;

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

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

#define Ede(i, u) for(int i = head[u]; i; i = e[i].nxt)

using namespace std;

const int P = 998244353, Q = 13331;

inline int plu(int x, int y) {return x + y >= P ? x + y - P : x + y;}

inline int del(int x, int y) {return x - y <  0 ? x - y + P : x - y;}

inline void add(int &x, int y) {x = plu(x, y);}

inline void sub(int &x, int y) {x = del(x, y);}

inline int qpow(int a, int b) {int s = 1; for(; b; b >>= 1, a = 1ll * a * a % P) if(b & 1) s = 1ll * s * a % P; return s;}

inline int read() {

	int x = 0, f = 1; char c = getchar();

	while(c < '0' || c > '9') f = (c == '-') ? - 1 : 1, c = getchar();

	while(c >= '0' && c <= '9') x = x * 10 + c - 48, c = getchar();

	return x * f;

}

const int N = 2e5 + 10;

int n, q, f[N][2], g[N], p[N];

char str[N];

int calc(int l, int r) {

	int o = l & 1;

	return del(f[r][o], 1ll * f[l - 1][o] * p[g[r] - g[l - 1]] % P);

}

int main() {

	n = read();

	scanf("%s", str + 1);

	q = read();

	p[0] = 1; rep(i, 1, n) p[i] = 1ll * p[i - 1] * Q % P;

	rep(i, 1, n)

		if(str[i] == '1') f[i][0] = f[i - 1][0], f[i][1] = f[i - 1][1], g[i] = g[i - 1];

		else

			f[i][0] = plu(1ll * f[i - 1][0] * Q % P, (i & 1) ? 2 : 3),

			f[i][1] = plu(1ll * f[i - 1][1] * Q % P, (i & 1) ? 3 : 2),

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

	while(q --) {

		int x = read(), y = read(), len = read();

		int vx = calc(x, x + len - 1);

		int vy = calc(y, y + len - 1);

		puts(vx == vy ? "Yes" : "No");

	}

	return 0;

}


A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4.

// Problem: A. Non-zero

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

// URL: https://codeforces.com/contest/1300/problem/A

// Memory Limit: 256 MB

// Time Limit: 1000 ms

//

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

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int maxn = 110;

int a[maxn];

int main(void)

{

	ios::sync_with_stdio(0);

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

	int t;

	cin >> t;

	while (t--) {

		int n;

		cin >> n;

		int sum = 0, cnt = 0;

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

			cin >> a[i];

			if (!a[i]) ++cnt;

			sum += a[i];

		}

		if (sum + cnt == 0) {

			cout << cnt + 1 << endl;

		} else {

			cout << cnt << endl;

		}

	}

	return 0;

}


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

// Problem: D. Pair of Topics

// Contest: Codeforces - Codeforces Round #627 (Div. 3)

// URL: https://codeforces.com/problemset/problem/1324/D

// Memory Limit: 256 MB

// Time Limit: 2000 ms

//

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

/*

* Coder -> ranadip_01 aKa RANADIP MUNDA

* DEPT. -> ECE"25

* COLLEGE -> JALPAIGURI GOVT. ENGINEERING COLLEGE

* Date -> 02/13/2023

*/

#include <bits/stdc++.h>

#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

using namespace std;

#define F ios_base::sync_with_stdio(false);

#define I cin.tie(NULL);

#define O cout.tie(NULL);

#define f first

#define s second

#define d  double

#define ll long long

#define l long int

#define i int

#define e "\n"

#define in cin>>

#define out cout<<

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

#define forll(a,c) for(ll a=0;a<c;a++)

#define frl(a,b,c) for(l a=b;a<=c;a++)

#define forl(a,c) for(l a=0;a<c;a++)

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

#define fori(a,c) for(i a=0;a<c;a++)

#define n(t) while(T--)

#define T tes_cases

#define vec vector

#define vs vector<string>

#define vc vector<char>

#define uset unordered_set

#define umap unordered_map

#define mm multimap

#define pr pair

#define stk stack

#define que queue

#define dqu deque

#define pub emplace_back

#define pob pop_back()

#define puf emplace_front

#define pof pop_front()

#define pr_q priority_queue

#define mod  1000000007

const ll inf = 1e18+5;

const i Num = 1e3 + 5;

i park[Num];

i dellRow[]={-1,0,1,0};

i dellCol[]={0,1,0,-1};

void precompute()

{

    park[0] = 0;

    park[1] = 1;

    park[2] = 2;

    for (int a = 3; a < Num; a++)

    {

        park[a] = park[a - 1] * a;

        park[a] %= mod;

    }

}

bool isPerfectSquare(ll num){

    if(ceil((double)sqrt(num))==floor((double)sqrt(num))){

        return true;

    }else{

        return false;

    }

}

bool isPalindrome(string s1, int left, int right) {

    if (left > right) return true;

    if (s1[left] != s1[right]) return false;

    else return isPalindrome( s1, left + 1, right - 1);

}

bool isPrime(ll val) { // O(sqrt(N)

    if (val <= 1) return false;

    if (val <= 3) return true;

    if (val % 2 == 0 || val % 3 == 0) return false;

    for (ll a = 5; a * a <= val; a = a + 6)

        if (val % a == 0 || val % (a + 2) == 0)

            return false;

    return true;

}

ll gcd(ll a,ll b){ return (b==0)? a:gcd(b,a%b);}//Euclidean Division (O(log(min(a,b)))

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

inline int normalize(int x, int y)

{

    x %= y;

    if (x < 0)

        x += y;

    return x;

}

i floor1(int n, int k)

{

    if (n % k == 0 || n >= 0)

        return n / k;

    return (n / k) - 1;

}

i ceil1(int n, int k){return floor1(n + k - 1, k);}

ll powm(ll a, ll b)// O(logN)

{

    ll res = 1;

    while (b)

    {

        if (b & 1)

            res = (res * a) % mod;

        a = (a * a) % mod;

        b >>= 1;

    }

    return res;

}

ll binpow(ll a, ll b, ll m) {// O(logN)

    a %= m;

    ll res = 1;

    while (b > 0) {

        if (b & 1)

            res = res * a % m;

        a = a * a % m;

        b >>= 1;

    }

    return res;

}

ll moduloInverse1(ll n1,ll modulo){//Fermats Little O(logN)

    // a^(m-1)=1 (Formula)

    // a^(m-2)=a^-1

    return binpow(n1,modulo-2,modulo);

}

int nPr(int n, int c)

{

    int num = park[n];

    num %= mod;

    num /= park[n - c];

    num %= mod;

    return num;

}

int all_0_To_1(int n)

{

    if (n == 1)

        return 1;

    if (!(n & (n - 1)))

        return all_0_To_1(n + 1);

    else

    {

        int p = ceil(log2(n));

        int ans = (1 << p);

        return (ans - 1);

    }

}

int stringToInt(string s)

{

    int num = 0;

    int n = s.length();

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

        num = num * 10 + ((int)(s[a]) - 48);

    return num;

}

int count_setBits(int n){

    if(n==0)return 0;

    return 1+count_setBits(n&(n-1));

}

int nearest_lowest_pow_of_2(int n)

{

    int val = log2(n);

    int ans = (1 << val);

    return ans;

}

int removeLast_SetBits(int n){

    return (n&(n-1));

}

int change_ithBit(int n,int a){

    return (n|(1<<a));

}

int clear_ithBit(int n,int a){

    return (a&(~(1<<a)));

}

int find_ithBit_from_Right(int n,int k,int a){

    return (n&(1<<(k-a)));

}

void swapp(int h,int k){

    h=(h^k);

    k=(k^h);

    h=(h^k);

}

bool sortBySec(const pair<ll,ll>&p1,const pair<ll,ll>&p2){

    return p1.s<p2.s;

}

const ll maxN=1e4;

vec<ll> factorials(maxN);

ll binomial(ll n1,ll k){

    if(n1<k) return 0;

    ll res=factorials[n1];

    res=(res*powm(factorials[k],mod-2))%mod;

    res=(res*powm(factorials[n1-k],mod-2))%mod;

    return res;

}

void factorial(){

    factorials[0]=factorials[1]=1;

    fri(a,2,1000000){

        factorials[a]=(factorials[a-1]*a)%mod;

    }

}

//Total prime - 31622

vec<i> primeSet;

bool prime[maxN];

bitset<31622> prm;

void madePrime(){

    for(i a=2;a<sqrt(1e9);++a){

        if(prm[a]==0) {

        primeSet.pub(a);

        for(i b=2*a;b<sqrt(1e9);b+=a) prm[b]=1;

        }

    }

}

void SieveOfEratosthenes() // O(NLog(LogN)

{

    memset(prime, true, sizeof(prime));

    prime[0]=prime[1]=false;

    for (ll p = 2; p*p < maxN; p++) {

        if (prime[p] == true) {

            for (ll a = p * p;a < maxN;a += p)

                prime[a] = false;

        }

    }

    for (ll p = 2; p <maxN; p++){

        if (prime[p]) primeSet.pub(p);

    }

}

// ll ans=0;

// vec<pair<ll,ll>>a1;

vec<ll>a1;umap<ll,ll> mp1,mp2;

void primeFact1(ll n1){// O(sqrt(N)

    for(ll a=2;a*a<=n1;++a){

        if(n1%a==0){

            ll cnt1=0;

            while(n1%a==0) ++cnt1,n1=n1/a;

            if(cnt1!=0) mp1[a]=1;

            // a1.push_back({cnt1,a});

            // out a<<"^"<<cnt1<<e;

        }

        // out n1<<"^1"<<e;

    }

    if(n1>1) mp1[n1]=1;

    // a1.push_back({1,n1});

}

vec<ll> sieve(maxN,0);

void primeFactofSieve(){// O(Nlog(logN)

    iota(sieve.begin()+1,sieve.end(),1);

    for(ll a=4;a<maxN;a+=2) sieve[a]=2;

    for(ll a=3;a*a<maxN;++a){

        if(sieve[a]==a){

            for(ll b=a*a;b<maxN;b+=a){

                if(sieve[b]==b) sieve[b]=a;

            }

        }

    }

}

umap<ll,ll> sve;

void getFactors(ll n1){ // O(logN)

    while(n1>1){

        // Sieve.push_back(sieve[n1]);

        sve[sieve[n1]]++;

        n1/=sieve[n1];

    }

    // return Sieve;

}

ll phi(ll n1){//Eulors Totient - O(sqrt(N)logN)

    ll res=n1;

    for(i a=2;a*a<=n1;++a){

        if(n1%a==0){

            while(n1%a==0) n1/=a;

            res-=res/a;

        }

    }

    if(n1>1) res-=res/n1;

    return res;

}

ll binaryToDecimal(string s1){

    ll dec_val=0;

    ll base=1;

    ll len=s1.length();

    for(ll a=len-1;a>=0;--a){

        if(s1[a]=='1') dec_val=(dec_val+base)%1000003;

        base*=2;

    }

    return dec_val;

}

string decimalToBinary(ll n1){

    string ans="";

    while(n1){

        if(n1&1) ans+='1';

        else ans+='0';

        n1>>=1;

    }

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

    return ans;

}

bool operator < (const string &a, const string &b)

{

    if (a.size() < b.size()) return true;

    if (b.size() < a.size()) return false;

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

    {

        if (a[c] < b[c]) return true;

        if (b[c] < a[c]) return false;

    }

    return true;

}

vec<ll> fib(82);

void fibonacii(){

    fib[0]=0;

    fib[1]=fib[2]=1;

    fri(a,3,81){

        fib[a]=fib[a-1]+fib[a-2];

    }

}

ll factorialss(ll n1)

{

    if (n1 == 0 || n1 == 1)

        return 1;

    return n1 * factorialss(n1 - 1);

}

vector<ll> graph[100001];//graph

string number="0123456789";

string abc = "abcdefghijklmnopqrstuvwxyz";

// ll dp[100001][1000000];

void go(){

    ll n1,h=0,j=10,k=2,cnt1=0,cnt2=0,cnt3=0;

    ll maxi=INT_MIN,mini=INT_MAX,f=0,d1,sum=0,flag=0,sum1=0,sum2=0,sum3=0;

    in n1;

    string s1,s2,s3="",s4="";

    // in s1;

    vec<ll> v1,v2,pre(n1);

    // vec<pair<ll,ll>> vp1,vp2;/

    umap<ll,ll> mp1,mp2;

    uset<ll> st1,st2,st3;

    // priority_queue<pair<i,string>> pq1,pq2;

    fori(a,n1) {

        in h;

        mp1[a]=h;

    }

    fori(a,n1) {

        in h;

        mp2[a]=h;

    }

    fori(a,n1){

    	h = mp1[a]-mp2[a];

    	if(h==0) ++cnt3;

    	else if(h>0) v1.pub(h);

    	// if(h<0) cnt1++,st1.insert(h);

    	// else if(h==0) cnt3++;

    	// else cnt2++,st2.insert(h);

    }

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

    // sort(v2.begin(),v2.end());

    // h = st2.size();k = st1.size();

    // sum+=cnt3*cnt2;

    // sum+=

    k = v1.size();

    fori(a,n1){

    	h = mp1[a]-mp2[a];

    	if(h>0) continue;

    	h = abs(h);

    	i up = upper_bound(v1.begin(),v1.end(),h) - v1.begin();

    	cnt1+=k-up;

    }

    out cnt1+(k*(k-1)/2);

    out e;

}

signed main() {

    F

    I

    O

    // fri(a,1,100000)

    // for(i b=a;b<=100000;b+=a) fac[b].push_back(a);

    // factorial();

    i T=1;

    // in T;

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

    precompute();

    // cout << fixed << setprecision(10);

    n(t) go();

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

// auto start = std::chrono::system_clock::now() ;

// auto end = std::chrono::system_clock::now();

//

// std::chrono::duration<double> elapsed_seconds = end-start;

// std::time_t end_time = std::chrono::system_clock::to_time_t(end);

//

// #ifndef ONLINE_JUDGE

// cout<<"RUN TIME : "<<elapsed_seconds.count()<<"s"<<endl;

// #endif

    return 0;

}


B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3
SET
ETS
TSE
OutputCopy1InputCopy3 4
SETE
ETSE
TSES
OutputCopy0InputCopy5 4
SETT
TEST
EEET
ESTE
STES
OutputCopy2NoteIn the third example test; these two triples of cards are sets:  "SETT"; "TEST"; "EEET"  "TEST"; "ESTE", "STES"

#include<bits/stdc++.h>

#define eps 1e-9

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

#define endl '\n'

#define ll              long long

#define ull             unsigned long long

#define MAX 200010

#define pb push_back

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

#define pf push_front

#define fi first

#define se second

#define pii pair<int,int>

const long long  INF = LLONG_MAX;

using namespace std;

const int N=3e5+10,M=10;

const int mod=998244353;

#define int long long

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

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

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

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

void READ(){

#ifndef ONLINE_JUDGE

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

#endif

}

void solve(){

    map<pair<char,char>,char>mp;

    map<string,int>frq;

    mp[{'S','T'}]=mp[{'T','S'}]='E';

    mp[{'E','S'}]=mp[{'S','E'}]='T';

    mp[{'E','T'}]=mp[{'T','E'}]='S';

    int n,m;

    cin>>n>>m;

    vector<string>v(n);

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

        cin>>v[i];

        frq[v[i]]++;

    }

    int ans=0;

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

        string s=v[i];

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

            string t=v[j];

            string x;

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

                if(s[k]==t[k]){

                    x+=s[k];

                }

                else{

                    x+=mp[{s[k],t[k]}];

                }

            }

            ans+=frq[x];

        }

    }

    cout<<ans/3<<endl;

}

signed main() {

    emailam

    //READ();

    int t=1;

    //cin>>t;

    while(t--){

        solve();

    }

}


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

#include<bits/stdc++.h>

using namespace std;

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

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

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

#define F first

#define S second

#define oo 1e18+5

#define MOD ll(1e9+7)

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

#define pb push_back

#define mpr make_pair

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

#define max3(a,b,c) max(a,max(b,c))

# define M_PI  3.14159265358979323846

#define int long long

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

#define num_ocur_insort(vec,x) equal_range(all(vec), x) /* return pair upper lower   auto r=num_ocur_insort(a,6);*/

typedef int ll;

typedef unsigned long long ull;

typedef vector<ll> vi;

typedef vector<vi> vii;

typedef pair<ll,ll> pi;

typedef vector<pi> vip;

typedef vector<string> vss;

typedef map<ll,ll> mapi;

typedef unordered_map<ll,ll> umapi;

typedef vector<vip> viip;

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

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

const int N=10000;

ll fun(vip &a) {

    ll sum = 1;

    ll mashgol = a[0].first;

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

        if (a[i].second > mashgol) {

            mashgol = a[i].first;

            sum++;

        }

    }

    return sum;

}

void solve(ll hh ) {

    ll n;

    cin >> n;

    vi a(n);

    vi pr(n);

    ll ans = 0, res;

    map<ll, vector<pi>> mp;

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

        cin >> a[i];

    }

    pr[0] = a[0];

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

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

    }

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

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

            ll lst = 0;

            if (i)lst = pr[i - 1];

            ll val = pr[j] - lst;

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

        }

    }

    for (auto it: mp) {

        auto vec = it.second;

        sort(all(vec));

        ll temp = fun(vec);

        if (temp > ans) {

            ans = temp;

            res = it.first;

        }

    }

    auto vec = mp[res];

    sort(all(vec));

    vip fin;

    ll mas = vec[0].first;

    fin.push_back({vec[0].second, vec[0].first});

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

        if (vec[i].second > mas) {

            mas = vec[i].first;

            fin.push_back({vec[i].second, vec[i].first});

        }

    }

    cout << ans << endl;

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

        cout << fin[i].first +1<< " " << fin[i].second+1 << endl;

    }

}

signed main() {

    ios_base::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    ll t = 1;

   // cin >> t;

    ll hh=t;

    while (t--) {

        solve(hh-t);

    }

}


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>

using namespace std;

using ll = long long;

#define endl "\n"

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

#define FOR1(i,s,e,d) for(long long i = s; i < e; i += d)

#define FOR2(i,s,e,d) for(long long i = s; i > e; i -= d)

#define FOR3(x,v) for (auto x : v)

#define pll pair<long long, long long>

#define vl vector<long long>

#define vll vector<pair<long long, long long>>

#define vvl vector<vector<long long>>

#define vs vector<string>

#define vc vector<char>

#define mll map<long long, long long>

#define mlc map<long long,char>

#define mls map<long long,string>

#define mlvl map<long long, vector<long long>>

#define pql priority_queue<long long>

#define over(ans) {cout<<ans<<endl;return;}

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

const ll INF = 1e18;

const ll mod = 998244353;

const ll mod1 = 1e9 + 7;

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

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

template<class c>

void display(c vect) {

    FOR3(x, vect) cout << x << ' ';

    cout << "\n";

}

void display(vll v) {

    FOR3(x, v) cout << "(" << x.first << ", " << x.second << ") ";

    cout << endl;

}

void display(vvl vect2d) {

    FOR3(x, vect2d) display(x);

}

void display(mll m) {

    FOR3(x, m) cout << x.first << ' ' << x.second << endl;

}

void display(mlvl  m) {

    FOR3(x, m) {

        cout << x.first << " : ";

        display(x.second);

    }

}

vl vin(int n) {

    vl v(n);

    FOR(i,n) cin >> v[i];

    return v;

}

int to_int(string s) {

    return stoi(s);

}

int to_int(char c) {

    string s = {c};

    return stoi(s);

}

char to_char(int i) {

    return char('0' + i);

}

int is_prime(ll n) {

    if (n == 1) return 0;

    if (n == 2 || n == 3) return 1;

    if ( n % 6 == 1 || n % 6 == 5) {

        for (ll k = 5; k*k <= n; k += 2) if (n % k == 0) return 0;

        return 1;

    }

    return 0;

}

ll gcd(ll a, ll b) {

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

}

ll inv(ll a, ll b){

    return 1<a ? b - inv(b%a,a)*b/a : 1;

}

template<class T>

T power(T a, ll b) {

    T res = 1;

    for(; b; b /= 2, a *= a) if (b%2) {res *= a;}

    return res;

}

template<class T>

T powermod(T a, ll b, ll P) {

    a %= P; ll res = 1;

    while (b > 0) {

        if (b & 1) res = res * a % P;

        a = a * a % P;

        b >>= 1;

    }

    return res;

}

vl factors(ll n) {

    vl factors;

    ll i = 1;

    while(i*i <= n) {

        if (n%i == 0) {

            factors.push_back(i);

            if (i*i != n) factors.push_back(n/i);

        }

        i++;

    }

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

    return factors;

}

ll lsb(ll a) {return (a & -a);}

template < typename T>

struct Fenwick {

    const ll n;

    vector<T> a;

    Fenwick(ll n) : n(n), a(n) {}

    void add(ll x, T v) {

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

            a[i-1] += v;

        }

    }

    T sum(ll x) {

        T ans = 0;

        for (ll i = x; i > 0; i -= i & -i) {

            ans += a[i-1];

        }

        return ans;

    }

    T rangeSum(ll l, ll r) {

        return sum(r) - sum(l);

    }

};

struct DSU {

    vl f, siz;

    DSU(ll n) : f(n), siz(n-1) { iota(f.begin(), f.end(), 0); }

    ll leader(ll x) {

        while (x != f[x]) x = f[x] = f[f[x]];

        return x;

    }

    bool same(ll x, ll y) { return leader(x) == leader(y); }

    bool merge(ll x, ll y) {

        x = leader(x);

        y = leader(y);

        if (x == y) return false;

        siz[x] += siz[y];

        f[y] = x;

        return true;

    }

    ll size(ll x) { return siz[leader(x)]; }

};

ll ncrmodP(ll n, ll r, ll P) {

    ll fac[n+1];

    fac[0] = 1;

    FOR1(i, 1, n+1, 1) {

        fac[i] = (fac[i-1] * i) % P;

    }

    return (fac[n] * inv(fac[r], P) % P * inv(fac[n-r], P) % P) % P;

}

// (condition ? value if yes : value if no)

// sort(v.begin(), v.end(), [](data_type x, data_type y) -> bool {

//     return condition;

// });

void init() {

}

void solve() {

    ll n; cin >> n;

    vl a = vin(n);

    sort(all(a), greater<ll>());

    display(a);

}

int main() {

    ios::sync_with_stdio(false), cin.tie(nullptr);

    init();

    ll t = 1;

    cin >> t;

    FOR(i,t) {

        // cout << "Case #" << i+1 << ": ";

        solve();

    }

}


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

#include <bits/stdc++.h>
using namespace std;

int t, n, m, a, sum;

int main()
{
    cin >> t;
    while (t--){
        cin >> n >> m;
        int sum = 0;
        for(int i=1; i<=n; ++i){
            cin >> a;
            sum += a;
        }
        cout << min(m,sum) << endl;
    }
}


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

#include <bits/stdc++.h>

using namespace std;

typedef long long int ll;

# define mod 998244353

int main()

{

/*

  for(int a=1;a<=100;a++)

  {

      for(int b=1;b<=1000;b++)

      {

          int now=a*b+a+b;

          int bb=b,cnt=1;

          while(bb)

          {

              cnt*=10;

              bb/=10;

          }

          ll c=a*cnt+b;

          //cout<<a<<" "<<b<<" "<<c<<endl;

          if(c==now)

          {

              cout<<a<<" "<<b<<endl;

          }

      }

  }

*/

int t;

cin>>t;

while(t--)

{

    ll a,b;

    cin>>a>>b;ll now=9ll;

    ll cnt=0;

    while(now<=b)

    {

        cnt++;

        now*=10ll;

        now+=9;

    }

    cout<<cnt*a<<endl;

}

    return 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.

#include <bits/stdc++.h>

using namespace std;

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

  int n;

  scanf("%d", &n);

  vector<pair<int, int>> vec(n);

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

    scanf("%d", &vec[i].first);

  }

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

    scanf("%d", &vec[i].second);

  }

  int score_a = 0, score_b = 0;

  for (const auto &[a, b] : vec) {

    score_a += a && !b;

    score_b += !a && b;

  }

  if (score_a == 0) {

    printf("-1\n");

    exit(0);

  }

  printf("%d\n", score_b / score_a + 1);

}


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

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

// #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")

#include <bits/stdc++.h>

#include <ext/rope>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/hash_policy.hpp>

#include <ext/pb_ds/tree_policy.hpp>

#include <ext/pb_ds/trie_policy.hpp>

#include <ext/pb_ds/priority_queue.hpp>

using namespace std;

using namespace __gnu_cxx;

using namespace __gnu_pbds;

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

using Trie = trie<string, null_type, trie_string_access_traits<>, pat_trie_tag, trie_prefix_search_node_update>;

// template <class T> using heapq = __gnu_pbds::priority_queue<T, greater<T>, pairing_heap_tag>;

template <class T> using heapq = std::priority_queue<T, vector<T>, greater<T>>;

#define ll long long

#define i128 ll

#define ld long double

#define ui unsigned int

#define ull unsigned long long

#define pii pair<int, int>

#define pll pair<ll, ll>

#define pdd pair<ld, ld>

#define vi vector<int>

#define vvi vector<vector<int>>

#define vll vector<ll>

#define vvll vector<vector<ll>>

#define vpii vector<pii>

#define vpll vector<pll>

#define lb lower_bound

#define ub upper_bound

#define pb push_back

#define pf push_front

#define eb emplace_back

#define fi first

#define se second

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

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

#define each(x, v) for(auto& x: v)

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

#define elif else if

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

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

#define mst(x, a) memset(x, a, sizeof(x))

#define lowbit(x) (x & (-x))

#define bitcnt(x) (__builtin_popcountll(x))

#define endl "\n"

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

#define Ran(a, b) rng() % ( (b) - (a) + 1 ) + (a)

struct custom_hash {

    static uint64_t splitmix64(uint64_t x) {

        // http://xorshift.di.unimi.it/splitmix64.c

        x += 0x9e3779b97f4a7c15;

        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;

        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;

        return x ^ (x >> 31);

    }

    size_t operator()(uint64_t x) const {

        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();

        return splitmix64(x + FIXED_RANDOM);

    }

    size_t operator()(pair<uint64_t,uint64_t> x) const {

        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();

        return splitmix64(x.first + FIXED_RANDOM) ^ (splitmix64(x.second + FIXED_RANDOM) >> 1);

    }

};

const i128 ONE = 1;

istream &operator>>(istream &in, i128 &x) {

    string s;

    in >> s;

    bool minus = false;

    if (s[0] == '-') {

        minus = true;

        s.erase(s.begin());

    }

    x = 0;

    for (auto i : s) {

        x *= 10;

        x += i - '0';

    }

    if (minus) x = -x;

    return in;

}

ostream &operator<<(ostream &out, i128 x) {

    string s;

    bool minus = false;

    if (x < 0) {

        minus = true;

        x = -x;

    }

    while (x) {

        s.push_back(x % 10 + '0');

        x /= 10;

    }

    if (s.empty()) s = "0";

    if (minus) out << '-';

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

    out << s;

    return out;

}

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

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

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

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

template <class T> ostream &operator<<(ostream &os, const multiset<T> &v) {

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

template <class T> ostream &operator<<(ostream &os, const Tree<T> &v) {

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

template <class T, class S> ostream &operator<<(ostream &os, const pair<T, S> &p) {

    os << p.first << " " << p.second;

    return os;

}

ll gcd(ll x,ll y) {

    if(!x) return y;

    if(!y) return x;

    int t = __builtin_ctzll(x | y);

    x >>= __builtin_ctzll(x);

    do {

        y >>= __builtin_ctzll(y);

        if(x > y) swap(x, y);

        y -= x;

    } while(y);

    return x<<t;

}

ll lcm(ll x, ll y) { return x * y / gcd(x, y); }

ll exgcd(ll a, ll b, ll &x, ll &y) {

    if(!b) return x = 1, y = 0, a;

    ll d = exgcd(b, a % b, x, y);

    ll t = x;

    x = y;

    y = t - a / b * x;

    return d;

}

ll max(ll x, ll y) { return x > y ? x : y; }

ll min(ll x, ll y) { return x < y ? x : y; }

ll Mod(ll x, int mod) { return (x % mod + mod) % mod; }

ll pow(ll x, ll y, ll mod){

    ll res = 1, cur = x;

    while (y) {

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

        cur = ONE * cur * cur % mod;

        y >>= 1;

    }

    return res % mod;

}

ll probabilityMod(ll x, ll y, ll mod) {

    return x * pow(y, mod-2, mod) % mod;

}

vvi getGraph(int n, int m, bool directed = false) {

    vvi res(n);

    rep(_, 0, m) {

        int u, v;

        cin >> u >> v;

        u--, v--;

        res[u].emplace_back(v);

        if(!directed) res[v].emplace_back(u);

    }

    return res;

}

vector<vpii> getWeightedGraph(int n, int m, bool directed = false) {

    vector<vpii> res(n);

    rep(_, 0, m) {

        int u, v, w;

        cin >> u >> v >> w;

        u--, v--;

        res[u].emplace_back(v, w);

        if(!directed) res[v].emplace_back(u, w);

    }

    return res;

}

const ll LINF = 0x1fffffffffffffff;

const ll MINF = 0x7fffffffffff;

const int INF = 0x3fffffff;

const int MOD = 1000000007;

const int MODD = 998244353;

const int N = 1e6 + 10;

class SegmentTree {

public:

	struct STNode {

		STNode () : left(nullptr), right(nullptr), val(0), maxval(0), minval(0), lazy(0), mlazy(LINF) {}

		STNode* left;

		STNode* right;

		ll val;

		ll maxval;

		ll minval;

		ll lazy;

		ll mlazy;

	};

	STNode* root;

	SegmentTree() { root = new STNode(); }

	~SegmentTree() {}

	void assign(STNode* node, int l, int r, int start, int end, ll x) {

		if (l == start && r == end) {

			node->val = 0;

			node->maxval = 0;

			node->minval = 0;

			node->lazy = 0;

			node->mlazy = x;

			return;

		}

		pushdown(node);

		int mid = l+r>>1;

		if (end <= mid) {

			assign(node->left, l, mid, start, end, x);

		} elif (start > mid) {

			assign(node->right, mid+1, r, start, end, x);

		} else {

			assign(node->left, l, mid, start, mid , x);

			assign(node->right, mid+1, r, mid+1, end, x);

		}

		pushup(node, mid-l+1, r-mid);

	}

	void add(STNode* node, int l, int r, int start, int end, ll x){

		if (l == start && r == end) {

			node->lazy += x;

			return;

		}

		pushdown(node);

		int mid = l+r>>1;

		if (end <= mid) {

			add(node->left, l, mid, start, end, x);

		} elif (start > mid) {

			add(node->right, mid+1, r, start, end, x);

		} else {

			add(node->left, l, mid, start, mid , x);

			add(node->right, mid+1, r, mid+1, end, x);

		}

		pushup(node, mid-l+1, r-mid);

	}

	ll querySum(STNode* node, int l, int r, int start, int end) {

		if (l == start && r == end) {

			return node->val + node->lazy * (r-l+1) + \

				(node->mlazy == LINF ? 0 : node->mlazy * (r-l+1));

		}

		pushdown(node);

		int mid = l+r>>1;

		ll res;

		if (end <= mid) {

			res = querySum(node->left, l, mid, start, end);

		} elif (start > mid) {

			res = querySum(node->right, mid+1, r, start, end);

		} else {

			res = querySum(node->left, l, mid, start, mid) +

			querySum(node->right, mid+1, r, mid+1, end);

		}

		pushup(node, mid-l+1, r-mid);

		return res;

	}

	ll queryMax(STNode* node, int l, int r, int start, int end) {

		if (l == start && r == end) {

			return node->maxval + node->lazy + \

				(node->mlazy == LINF ? 0 : node->mlazy);

		}

		pushdown(node);

		int mid = l+r>>1;

		ll res;

		if (end <= mid) {

			res = queryMax(node->left, l, mid, start, end);

		} elif (start > mid) {

			res = queryMax(node->right, mid+1, r, start, end);

		} else {

			res = max(queryMax(node->left, l, mid, start, mid),

			queryMax(node->right, mid+1, r, mid+1, end));

		}

		pushup(node, mid-l+1, r-mid);

		return res;

	}

	ll queryMin(STNode* node, int l, int r, int start, int end) {

		if (l == start && r == end) {

			return node->minval + node->lazy + \

				(node->mlazy == LINF ? 0 : node->mlazy);

		}

		pushdown(node);

		int mid = l+r>>1;

		ll res;

		if (end <= mid) {

			res = queryMin(node->left, l, mid, start, end);

		} elif (start > mid) {

			res = queryMin(node->right, mid+1, r, start, end);

		} else {

			res = min(queryMin(node->left, l, mid, start, mid),

			queryMin(node->right, mid+1, r, mid+1, end));

		}

		pushup(node, mid-l+1, r-mid);

		return res;

	}

	void pushdown(STNode* node) {

		if (node->left == nullptr) {

			node->left = new STNode();

		}

		if (node->right == nullptr) {

			node->right = new STNode();

		}

		if (node->mlazy != LINF) {

			node->left->lazy = 0;

			node->left->val = 0;

			node->left->maxval = 0;

			node->left->minval = 0;

			node->right->lazy = 0;

			node->right->val = 0;

			node->right->maxval = 0;

			node->right->minval = 0;

			node->left->mlazy = node->mlazy;

			node->right->mlazy = node->mlazy;

			node->mlazy = LINF;

		}

		if (node->lazy) {

			node->left->lazy += node->lazy;

			node->right->lazy += node->lazy;

			node->lazy = 0;

		}

	}

	void pushup(STNode* node, int ln, int rn) {

		node->val = node->left->val + node->left->lazy * ln + \

					(node->left->mlazy == LINF ? 0 : node->left->mlazy * ln) + \

					node->right->val + node->right->lazy * rn + \

					(node->right->mlazy == LINF ? 0 : node->right->mlazy * rn);

		node->maxval = max(node->left->maxval + node->left->lazy + \

						(node->left->mlazy == LINF ? 0 : node->left->mlazy),

						node->right->maxval + node->right->lazy + \

						(node->right->mlazy == LINF ? 0 : node->right->mlazy));

		node->minval = min(node->left->minval + node->left->lazy + \

						(node->left->mlazy == LINF ? 0 : node->left->mlazy),

						node->right->minval + node->right->lazy + \

						(node->right->mlazy == LINF ? 0 : node->right->mlazy));

	}

};

void solve() {

    int n, m;

    cin >> n >> m;

    vi a(m);

    each(i, a) cin >> i;

    vi pos(n+1);

    vi mn(n+1);

    vi mx(n+1);

    rep(i, 1, n+1) mn[i] = mx[i] = i, pos[i] = i + m;

    SegmentTree st;

    rep(i, 1, n+1) st.add(st.root, -1, N, pos[i], pos[i], 1);

    int cur = m;

    each(i, a) {

        mn[i] = 1;

        mx[i] = max(mx[i], st.querySum(st.root, -1, N, 0, pos[i]));

        st.add(st.root, -1, N, pos[i], pos[i], -1);

        pos[i] = cur--;

        st.add(st.root, -1, N, pos[i], pos[i], 1);

    }

    rep(i, 1, n+1) {

        mx[i] = max(mx[i], st.querySum(st.root, -1, N, 0, pos[i]));

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

    }

}

signed main() {

    ios::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    int t = 1;

    // cin >> t;

    while (t--) {

        solve();

    }

    return 0;

}


B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.

//श्रमं विना न किमपि साध्यम्
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define all(a) (a).begin(),(a).end()
#define rev(p) reverse(p.begin(),p.end());
#define v vector
#define sortt(a) sort(all(a))
#define pll pair<ll,ll>
#define sz(c) (int)c.size()
#define fr first
#define sc second
#define pb push_back
#define pf push_front
#define eb emplace_back
#define mp make_pair
#define rep(i,a,n) for(int i=a ; i<n ; i++)
#define pi (2*acos(0.0))
#define F(a,b,i) for(int i=a;i<b;i++)
#define FN(a,b,i) for(int i=a-1;i>=b;i--)
#define endl "\n"
//*****DEBUG FUNCTIONS********//
#ifndef ONLINE_JUDGE
template<typename T>void __p(std::vector<T> v);
template<typename T>void __p(T a){cout<<a;}
template<typename T, typename F>void __p(pair<T, F> a){cout<<"{";__p(a.first);cout<<",";__p(a.second);cout<<"}";}
template<typename T>void __p(std::vector<T> a) {cout<<"{";for(auto it=a.begin(); it<a.end(); it++)__p(*it),cout<<",}"[it+1==a.end()];}
template<typename T>void __p(std::set<T> a){cout<<"{";for(auto it=a.begin(); it!=a.end();){__p(*it); cout<<",}"[++it==a.end()];}}
template<typename T>void __p(std::multiset<T> a){cout<<"{";for(auto it=a.begin(); it!=a.end();){__p(*it); cout<<",}"[++it==a.end()];}}
template<typename T, typename F>void __p(std::map<T,F> a){cout<<"{\n";for(auto it=a.begin(); it!=a.end();++it){__p(it->first);cout << ": ";__p(it->second);cout<<"\n";}cout << "}\n";}
template<typename T, typename ...Arg>void __p(T a1, Arg ...a){__p(a1);__p(a...);}
template<typename Arg1>void __f(const char *name, Arg1 &&arg1){cout<<name<<" : ";__p(arg1);cout<<endl;}
template<typename Arg1, typename ... Args>void __f(const char *names, Arg1 &&arg1, Args &&... args) {int bracket=0,i=0;for(;; i++)if(names[i]==','&&bracket==0)break;else if(names[i]=='(')bracket++;else if(names[i]==')')bracket--;const char *comma=names+i;cout.write(names,comma-names)<<" : ";__p(arg1);cout<<" | ";__f(comma+1,args...);}
#define trace(...) cout<<"Line:"<<__LINE__<<" ", __f(#__VA_ARGS__, __VA_ARGS__)
#else
#define trace(...)
#define error(...)
#endif
//*****DEBUG FUNCTIONS********//
ll inf =1e18;
ll mod1 = 1e9 + 7;
ll mod2=998244353;
ll log2n(ll n) // floor of(log2 n) , log2 (13)=3
{
  //FAILS FOR N=0
  if(n==0)return 0;
  return (63-__builtin_clzll(n));
}
bool is_prime( ll n)
{
  if(n==1)return false;
  ll i=2;
  for(i=2;i*i<=n;i++)
  {
    if(n%i==0)
    {
      return false;
    }
  }
  return true;
}
ll power(ll x, ll y, ll p)
{
    x = x % p;
    if(x==0)return 0;
    ll res = 1;
    while (y > 0)
    {
        if (y & 1)
            res = (res * x) % p;
        y = y >> 1;
        x = (x * x) % p;
    }
    return res;
}
ll pwr(ll x, ll y){if(x==0)return 0;ll res = 1;x = x ;while (y > 0){if (y & 1)res = (res * x);y = y >> 1;x = (x * x) ;}return res;}
ll modInverse(ll n, ll p){return power(n, p - 2, p);}
ll ncr(ll n, ll r , ll modd){if(r>n){return 0;}
    if(r>n-r){r = n-r;}ll ans = 1;
    for(ll i = 1; i<=r ; i++){
        ans *= (n-i+1);ans%= modd;ans *= modInverse(i, modd);ans %= modd;}
 return ans;}
ll _gcd(ll a, ll b){ if (b == 0) return a; return _gcd(b, a % b);}
//********CLOCK********
ll begtime = clock();
#define time() cerr << "\n\nTime elapsed: " << (clock() - begtime)*1000/CLOCKS_PER_SEC << " ms\n\n";
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
//********CLOCK********
ll testctr;
const int N=2e6+5;

void solve()
{

  ll i, j , t1 , t2 , t3 ,t4 , flag;
  //ARE YOU REALLY SURE()?
  //chckdstc?
  //MXMN?BSPZL
  //order_1e18?overflow!!!

  ll n; cin>>n;
  double ans=0;
  for(i=1;i<=n;i++)
  {
    ans+=(double)1/i;
  }
  cout<<ans<<endl;

}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);cout.tie(NULL);
#ifndef ONLINE_JUDGE
    freopen("input1.txt", "r", stdin);
    freopen("output1.txt", "w", stdout);
#endif
  cout<<fixed<<setprecision(20);
  ll TESTS;
  //cin>>TESTS;
  TESTS=1;
  for(int i=1;i<=TESTS;i++)
  {
    testctr=i;
    // cout<<"Case #"<<i<<":"<<" ";
    solve();
  }
  time();
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define int long long

#define For(i,a,n) for(int i = a; i < n; i++)

signed main(){

    ios_base::sync_with_stdio(0);

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

    int t;

    cin >> t;

    while (t--){

        int n;

        cin >> n;

        int sum = 0,cnt = 0;

        For(i,0,n){

            int temp;

            cin >> temp;

            if (temp == 0) cnt++;

            sum += temp;

        }

        if (sum + cnt == 0) cnt++;

        cout <<cnt<<"\n";

    }

    return 0;

}


B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
OutputCopyYES
NO
NO
NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.

#include<bits/stdc++.h>

typedef long long ll;

typedef unsigned long long ull;

using namespace std;

const ll mod = 998244353;

const int mm = 1e5 + 10;

ll a[mm];

void solve(){

	int n;

	cin>>n;

	ll sum=0;

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

		cin>>a[i],sum+=a[i];

	}

	ll mal=-mod*2,mar=-mod*2;

	ll bj=0;

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

		bj+=a[i];

		mal=max(mal,bj);

		if(bj<0)bj=0;

	}bj=0;

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

		bj+=a[j];

		mar=max(mar,bj);

		if(bj<0)bj=0;

	}

	if(sum>max(mal,mar))cout<<"YES";

	else cout<<"NO";

	cout<<"\n";

}

int main(){

	std::ios::sync_with_stdio(false);

	std::cin.tie(0);

	std::cout.tie(0);

	int t;

	cin>>t;

	while(t--){

		solve();

	}

}


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.

#include <bits/stdc++.h>

using namespace std;

int ans,n;

string f(string s,char c){

	int l=s.length();

	string tmp="";

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

		if(s[i]==c){

			int j=i+1;

			while(j<l&&s[j]==c) j++;

			if(i>0&&s[i-1]==c-1||j<l&&s[j]==c-1){

				ans+=j-i;

				i=j-1;

				continue;

			}

		}

		tmp+=s[i];

	}

	return tmp;

}

int main(){

	cin>>n;

	string s;

	cin>>s;

	for(char c='z';c>'a';c--)

		s=f(s,c);

	cout<<ans<<endl;

	return 0;

}


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

#include <bits/stdc++.h>

#define N 205

#define wr cout << "Continue debugging\n";

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

#define ll long long int

#define pii pair <int, int>

#define pb push_back

#define ff first

#define ss second

using namespace std;

int p[N];

pair<int,pii> dp[N][30][30];

int main ()

{

	ios::sync_with_stdio(false);

	cin.tie(0);

	int n;

	string s;

	cin >> n >> s;

	// char lst1 = 'a', lst2 = 'a';

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

	// 	if (s[i] >= lst1) lst1 = s[i];

	// 	else if (s[i] >= lst2){

	// 		lst2 = s[i];

	// 		p[i] = 1;

	// 	}else return cout << "NO", 0;

	// }

	// cout << "YES\n";

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

	// 	cout << p[i];

	// }

	s = '#'+s;

	dp[0][0][0].ff = 1;

	int a = -1, b = -1;

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

		int x = s[i]-'a';

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

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

				if (dp[i-1][j][k].ff){

					if (j <= x){

						dp[i][x][k].ff = 1;

						dp[i][x][k].ss.ff = j;

						dp[i][x][k].ss.ss = k;

						if (i == n){

							a = x;

							b = k;

						}

					}

					if (k <= x){

						dp[i][j][x].ff = 1;

						dp[i][j][x].ss.ff = j;

						dp[i][j][x].ss.ss = k;

						if (i == n){

							a = j;

							b = x;

						}

					}

				}

			}

		}

	}

	if (a == -1) return cout << "NO", 0;

	cout << "YES\n";

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

		if (s[i]-'a' == b) p[i] = 1;

		int olda = a, oldb = b;

		a = dp[i][olda][oldb].ss.ff;

		b = dp[i][olda][oldb].ss.ss;

	}

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

		cout << p[i];

	}

}


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

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace std;

using namespace __gnu_pbds;

using ll = long long;

using ull = unsigned long long;

#ifdef LOCAL

#include "algo/debug.h"

#define TASK "inp1"

#else

#define debug(...) 42

#define TASK "printer"

#define debugArr(...) 42

#endif

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

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

#define fi first

#define se second

const ll MOD = 1e9+7;

const ll maxn = 1e5+5;

const ll inf = 1e18;

const ll BASE = 31;

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

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

//random

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

int Rand(int a, int b)

{

    return uniform_int_distribution<int>(a, b)(rng);

}

void solve()

{

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

    string s; cin >> s;

    s = '$' + s;

    vector <int> v(k), ans(26);

    vector <vector <int>> cnt(n + 1, vector <int> (26));

    for(int &x : v) cin >> x;

    v.push_back(n);

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

    {

        int x = s[i] - 'a';

        for(int j = 0; j < 26; j++) cnt[i][j] = cnt[i - 1][j] + (x == j);

    }

    for(int x : v)

    {

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

        {

            ans[i] += cnt[x][i];

        }

    }

    for(int x : ans) cout << x << ' ';

    cout << '\n';

}

signed main()

{

    faster();

    if (fopen(TASK ".inp", "r")) freopen(TASK ".inp", "r", stdin);

    int t = 1;

    cin >> t;

    while(t--)

    {

        solve();

    }

}


C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
OutputCopy1

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

// #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")

#include <bits/stdc++.h>

#include <ext/rope>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/hash_policy.hpp>

#include <ext/pb_ds/tree_policy.hpp>

#include <ext/pb_ds/trie_policy.hpp>

#include <ext/pb_ds/priority_queue.hpp>

using namespace std;

using namespace __gnu_cxx;

using namespace __gnu_pbds;

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

using Trie = trie<string, null_type, trie_string_access_traits<>, pat_trie_tag, trie_prefix_search_node_update>;

// template <class T> using heapq = __gnu_pbds::priority_queue<T, greater<T>, pairing_heap_tag>;

template <class T> using heapq = std::priority_queue<T, vector<T>, greater<T>>;

#define ll long long

#define i128 __int128

#define ld long double

#define ui unsigned int

#define ull unsigned long long

#define pii pair<int, int>

#define pll pair<ll, ll>

#define pdd pair<ld, ld>

#define vi vector<int>

#define vvi vector<vector<int>>

#define vll vector<ll>

#define vvll vector<vector<ll>>

#define vpii vector<pii>

#define vpll vector<pll>

#define lb lower_bound

#define ub upper_bound

#define pb push_back

#define pf push_front

#define eb emplace_back

#define fi first

#define se second

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

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

#define each(x, v) for(auto& x: v)

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

#define elif else if

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

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

#define mst(x, a) memset(x, a, sizeof(x))

#define lowbit(x) (x & (-x))

#define bitcnt(x) (__builtin_popcountll(x))

#define endl "\n"

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

#define Ran(a, b) rng() % ( (b) - (a) + 1 ) + (a)

struct custom_hash {

    static uint64_t splitmix64(uint64_t x) {

        // http://xorshift.di.unimi.it/splitmix64.c

        x += 0x9e3779b97f4a7c15;

        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;

        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;

        return x ^ (x >> 31);

    }

    size_t operator()(uint64_t x) const {

        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();

        return splitmix64(x + FIXED_RANDOM);

    }

    size_t operator()(pair<uint64_t,uint64_t> x) const {

        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();

        return splitmix64(x.first + FIXED_RANDOM) ^ (splitmix64(x.second + FIXED_RANDOM) >> 1);

    }

};

const i128 ONE = 1;

istream &operator>>(istream &in, i128 &x) {

    string s;

    in >> s;

    bool minus = false;

    if (s[0] == '-') {

        minus = true;

        s.erase(s.begin());

    }

    x = 0;

    for (auto i : s) {

        x *= 10;

        x += i - '0';

    }

    if (minus) x = -x;

    return in;

}

ostream &operator<<(ostream &out, i128 x) {

    string s;

    bool minus = false;

    if (x < 0) {

        minus = true;

        x = -x;

    }

    while (x) {

        s.push_back(x % 10 + '0');

        x /= 10;

    }

    if (s.empty()) s = "0";

    if (minus) out << '-';

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

    out << s;

    return out;

}

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

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

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

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

template <class T> ostream &operator<<(ostream &os, const multiset<T> &v) {

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

template <class T> ostream &operator<<(ostream &os, const Tree<T> &v) {

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

template <class T, class S> ostream &operator<<(ostream &os, const pair<T, S> &p) {

    os << p.first << " " << p.second;

    return os;

}

ll gcd(ll x,ll y) {

    if(!x) return y;

    if(!y) return x;

    int t = __builtin_ctzll(x | y);

    x >>= __builtin_ctzll(x);

    do {

        y >>= __builtin_ctzll(y);

        if(x > y) swap(x, y);

        y -= x;

    } while(y);

    return x<<t;

}

ll lcm(ll x, ll y) { return x * y / gcd(x, y); }

ll exgcd(ll a, ll b, ll &x, ll &y) {

    if(!b) return x = 1, y = 0, a;

    ll d = exgcd(b, a % b, x, y);

    ll t = x;

    x = y;

    y = t - a / b * x;

    return d;

}

ll max(ll x, ll y) { return x > y ? x : y; }

ll min(ll x, ll y) { return x < y ? x : y; }

ll Mod(ll x, int mod) { return (x % mod + mod) % mod; }

ll pow(ll x, ll y, ll mod){

    ll res = 1, cur = x;

    while (y) {

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

        cur = ONE * cur * cur % mod;

        y >>= 1;

    }

    return res % mod;

}

ll probabilityMod(ll x, ll y, ll mod) {

    return x * pow(y, mod-2, mod) % mod;

}

vvi getGraph(int n, int m, bool directed = false) {

    vvi res(n);

    rep(_, 0, m) {

        int u, v;

        cin >> u >> v;

        u--, v--;

        res[u].emplace_back(v);

        if(!directed) res[v].emplace_back(u);

    }

    return res;

}

vector<vpii> getWeightedGraph(int n, int m, bool directed = false) {

    vector<vpii> res(n);

    rep(_, 0, m) {

        int u, v, w;

        cin >> u >> v >> w;

        u--, v--;

        res[u].emplace_back(v, w);

        if(!directed) res[v].emplace_back(u, w);

    }

    return res;

}

const ll LINF = 0x1fffffffffffffff;

const ll MINF = 0x7fffffffffff;

const int INF = 0x3fffffff;

const int MOD = 1000000007;

const int MODD = 998244353;

const int N = 1e6 + 10;

class SegmentTree {

public:

	struct STNode {

		STNode () : left(nullptr), right(nullptr), val(0), maxval(0), minval(0), lazy(0), mlazy(LINF) {}

		STNode* left;

		STNode* right;

		ll val;

		ll maxval;

		ll minval;

		ll lazy;

		ll mlazy;

	};

	STNode* root;

	SegmentTree() { root = new STNode(); }

	~SegmentTree() {}

	void assign(STNode* node, int l, int r, int start, int end, ll x) {

		if (l == start && r == end) {

			node->val = 0;

			node->maxval = 0;

			node->minval = 0;

			node->lazy = 0;

			node->mlazy = x;

			return;

		}

		pushdown(node);

		int mid = l+r>>1;

		if (end <= mid) {

			assign(node->left, l, mid, start, end, x);

		} elif (start > mid) {

			assign(node->right, mid+1, r, start, end, x);

		} else {

			assign(node->left, l, mid, start, mid , x);

			assign(node->right, mid+1, r, mid+1, end, x);

		}

		pushup(node, mid-l+1, r-mid);

	}

	void add(STNode* node, int l, int r, int start, int end, ll x){

		if (l == start && r == end) {

			node->lazy += x;

			return;

		}

		pushdown(node);

		int mid = l+r>>1;

		if (end <= mid) {

			add(node->left, l, mid, start, end, x);

		} elif (start > mid) {

			add(node->right, mid+1, r, start, end, x);

		} else {

			add(node->left, l, mid, start, mid , x);

			add(node->right, mid+1, r, mid+1, end, x);

		}

		pushup(node, mid-l+1, r-mid);

	}

	ll querySum(STNode* node, int l, int r, int start, int end) {

		if (l == start && r == end) {

			return node->val + node->lazy * (r-l+1) + \

				(node->mlazy == LINF ? 0 : node->mlazy * (r-l+1));

		}

		pushdown(node);

		int mid = l+r>>1;

		ll res;

		if (end <= mid) {

			res = querySum(node->left, l, mid, start, end);

		} elif (start > mid) {

			res = querySum(node->right, mid+1, r, start, end);

		} else {

			res = querySum(node->left, l, mid, start, mid) +

			querySum(node->right, mid+1, r, mid+1, end);

		}

		pushup(node, mid-l+1, r-mid);

		return res;

	}

	ll queryMax(STNode* node, int l, int r, int start, int end) {

		if (l == start && r == end) {

			return node->maxval + node->lazy + \

				(node->mlazy == LINF ? 0 : node->mlazy);

		}

		pushdown(node);

		int mid = l+r>>1;

		ll res;

		if (end <= mid) {

			res = queryMax(node->left, l, mid, start, end);

		} elif (start > mid) {

			res = queryMax(node->right, mid+1, r, start, end);

		} else {

			res = max(queryMax(node->left, l, mid, start, mid),

			queryMax(node->right, mid+1, r, mid+1, end));

		}

		pushup(node, mid-l+1, r-mid);

		return res;

	}

	ll queryMin(STNode* node, int l, int r, int start, int end) {

		if (l == start && r == end) {

			return node->minval + node->lazy + \

				(node->mlazy == LINF ? 0 : node->mlazy);

		}

		pushdown(node);

		int mid = l+r>>1;

		ll res;

		if (end <= mid) {

			res = queryMin(node->left, l, mid, start, end);

		} elif (start > mid) {

			res = queryMin(node->right, mid+1, r, start, end);

		} else {

			res = min(queryMin(node->left, l, mid, start, mid),

			queryMin(node->right, mid+1, r, mid+1, end));

		}

		pushup(node, mid-l+1, r-mid);

		return res;

	}

	void pushdown(STNode* node) {

		if (node->left == nullptr) {

			node->left = new STNode();

		}

		if (node->right == nullptr) {

			node->right = new STNode();

		}

		if (node->mlazy != LINF) {

			node->left->lazy = 0;

			node->left->val = 0;

			node->left->maxval = 0;

			node->left->minval = 0;

			node->right->lazy = 0;

			node->right->val = 0;

			node->right->maxval = 0;

			node->right->minval = 0;

			node->left->mlazy = node->mlazy;

			node->right->mlazy = node->mlazy;

			node->mlazy = LINF;

		}

		if (node->lazy) {

			node->left->lazy += node->lazy;

			node->right->lazy += node->lazy;

			node->lazy = 0;

		}

	}

	void pushup(STNode* node, int ln, int rn) {

		node->val = node->left->val + node->left->lazy * ln + \

					(node->left->mlazy == LINF ? 0 : node->left->mlazy * ln) + \

					node->right->val + node->right->lazy * rn + \

					(node->right->mlazy == LINF ? 0 : node->right->mlazy * rn);

		node->maxval = max(node->left->maxval + node->left->lazy + \

						(node->left->mlazy == LINF ? 0 : node->left->mlazy),

						node->right->maxval + node->right->lazy + \

						(node->right->mlazy == LINF ? 0 : node->right->mlazy));

		node->minval = min(node->left->minval + node->left->lazy + \

						(node->left->mlazy == LINF ? 0 : node->left->mlazy),

						node->right->minval + node->right->lazy + \

						(node->right->mlazy == LINF ? 0 : node->right->mlazy));

	}

};

void solve() {

    int n, m, p;

    cin >> n >> m >> p;

    vpii a(n), b(m);

    vector<array<int, 3>> monster(p);

    rep(i, 0, n) cin >> a[i].fi >> a[i].se;

    rep(i, 0, m) cin >> b[i].fi >> b[i].se;

    rep(i, 0, p) cin >> monster[i][0] >> monster[i][1] >> monster[i][2];

    sort(all(a)), sort(all(b)), sort(all(monster));

    SegmentTree st;

    st.assign(st.root, 0, N, 0, N, -LINF);

    rep(i, 0, m) {

        ll t = st.queryMax(st.root, 0, N, b[i].fi, b[i].fi);

        st.assign(st.root, 0, N, b[i].fi, b[i].fi, max(t, -b[i].se));

    }

    ll ans = -LINF;

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

        for ( ; j < p && monster[j][0] < a[i].fi; j++) {

            auto [x, y, z] = monster[j];

            st.add(st.root, 0, N, y + 1, N, z);

        }

        ans = max(ans, st.queryMax(st.root, 0, N, 0, N) - a[i].se);

    }

    cout << ans << endl;

}

signed main() {

    ios::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    int t = 1;

    // cin >> t;

    while (t--) {

        solve();

    }

    return 0;

}


C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3
-2 1
OutputCopy3 1 2 InputCopy5
1 1 1 1
OutputCopy1 2 3 4 5 InputCopy4
-1 2 2
OutputCopy-1

#include <bits/stdc++.h>

using namespace std;

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

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

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

#define ll long long

void file() {

    std::ios_base::sync_with_stdio(0);

    cin.tie(NULL);

    cout.tie(NULL);

}

int main() {

    file();

    int n;

    cin >> n;

    vector<int> v(n - 1);

    ll sum = 0;

    int pos = 0;

    bool ok = true;

    for (auto &it: v) {

        cin >> it;

        sum += it;

        if (sum > 0)

            pos++;

    }

    vector<int> ans = {n - pos};

    vector<bool> vis(n + 1);

    vis[n - pos] = true;

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

        ans.push_back(v[i - 1] + ans.back());

        if (ans.back() > n || ans.back() <= 0 || vis[ans.back()]) {

            cout << "-1";

            return 0;

        }

        vis[ans.back()] = true;

    }

    for (auto it: ans)cout << it << " ";

}


D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
OutputCopy2
-1
0

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<cmath>
#include<queue>
#include<string>
#include<stack>
using namespace std;
const int maxn = 1e6 + 10;
typedef long long ll;
#define tbl ios::sync_with_stdio(false), cin.tie(0),cout.tie(0);
int main() {
	int t;
	cin >> t;
	while (t--) {
		vector<int>q(64, 0);
		ll m,n,sum=0,cnt=0;
		cin >> m >> n;
		for (int i = 0; i < n; i++) {
			int h;
			cin >> h;
			sum += h;
			q[log2(h)]++;
		}
		if (sum < m) {
			cout << "-1" << endl;
			continue;
		}
		for (int i = 0; i < 63&&m; i++) {
			if (m % 2 == 1) {
				int j = i;
				while (q[j] == 0) {
					j++;
					cnt++;
				}
				while (j != i) {
					q[j--]--;
					q[j] += 2;
				}
				q[i]--;
			}
			m /= 2;
			q[i + 1] += q[i] / 2;
		}
		cout << cnt << endl;
	}
}


F. Nora's Toy Boxestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSIHanatsuka - EMber SIHanatsuka - ATONEMENTBack in time; the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.One day, Nora's adoptive father, Phoenix Wyle, brought Nora nn boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO.She labelled all nn boxes with nn distinct integers a1,a2,…,ana1,a2,…,an and asked ROBO to do the following action several (possibly zero) times:  Pick three distinct indices ii, jj and kk, such that ai∣ajai∣aj and ai∣akai∣ak. In other words, aiai divides both ajaj and akak, that is ajmodai=0ajmodai=0, akmodai=0akmodai=0.  After choosing, Nora will give the kk-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty.  After doing so, the box kk becomes unavailable for any further actions. Being amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the largest amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes.Since ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them?As the number of such piles can be very large, you should print the answer modulo 109+7109+7.InputThe first line contains an integer nn (3≤n≤603≤n≤60), denoting the number of boxes.The second line contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤601≤ai≤60), where aiai is the label of the ii-th box.OutputPrint the number of distinct piles having the maximum number of boxes that ROBO_Head can have, modulo 109+7109+7.ExamplesInputCopy3
2 6 8
OutputCopy2
InputCopy5
2 3 4 9 12
OutputCopy4
InputCopy4
5 7 2 9
OutputCopy1
NoteLet's illustrate the box pile as a sequence bb; with the pile's bottommost box being at the leftmost position.In the first example, there are 22 distinct piles possible:   b=[6]b=[6] ([2,6,8]−→−−(1,3,2)[2,8][2,6,8]→(1,3,2)[2,8])  b=[8]b=[8] ([2,6,8]−→−−(1,2,3)[2,6][2,6,8]→(1,2,3)[2,6]) In the second example, there are 44 distinct piles possible:   b=[9,12]b=[9,12] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,3,4)[2,3,4][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,3,4)[2,3,4])  b=[4,12]b=[4,12] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,3,4)[2,3,9][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,3,4)[2,3,9])  b=[4,9]b=[4,9] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,4,3)[2,3,12][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,4,3)[2,3,12])  b=[9,4]b=[9,4] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,4,3)[2,3,12][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,4,3)[2,3,12]) In the third sequence, ROBO can do nothing at all. Therefore, there is only 11 valid pile, and that pile is empty.

#include<cstdio>
#include<cctype>
#include<vector>

#define maxn 66

const int mod=1e9+7;

template<class T>

inline T read(){
	T r=0,f=0;
	char c;
	while(!isdigit(c=getchar()))f|=(c=='-');
	while(isdigit(c))r=(r<<1)+(r<<3)+(c^48),c=getchar();
	return f?-r:r;
}

inline long long qpow(long long a,int b){
	long long ans=1;
	for(;b;b>>=1){
		if(b&1)(ans*=a)%=mod;
		(a*=a)%=mod;
	}
	return ans;
}

int n,a[maxn];

bool vis[maxn],tag[maxn];

long long C[maxn][maxn],A[maxn][maxn];

inline void Add(int &x,int y){
	x+=y-mod,x+=(x>>31)&mod;
}

int sum;

long long ans;

std::vector<int> to[maxn];

namespace Solve{

	long long f[1<<15];

	int N,n,m,d[maxn],d0[maxn],T[maxn],cnt[1<<15];

	inline void FWT(){
		for(int i=1;i<N;i<<=1)
			for(int j=0,p=i<<1;j<N;j+=p)
				for(int k=0;k<i;k++)
					Add(cnt[i|j|k],cnt[j|k]);
	}

	void dfs(int u){
		vis[u]=1;
		if(tag[u])d0[++n]=u;
		else d[++m]=u;
		for(auto v:to[u])
			if(!vis[v])dfs(v);
	}

	inline void work(int s){
		n=m=0,dfs(s);
		if(!m)return;
		N=1<<n,sum+=m-1;
		(ans*=C[sum][m-1])%=mod;
		for(int i=0;i<N;i++)
			cnt[i]=0,f[i]=0;
		for(int i=1;i<=m;i++){
			T[i]=0;
			for(int j=1;j<=n;j++)
				if(!(a[d[i]]%a[d0[j]]))
					T[i]|=1<<(j-1);
			cnt[T[i]]++;
		}
		FWT();
		for(int i=1;i<=m;i++)
			(f[T[i]]+=A[m-1][cnt[T[i]]-1])%=mod;
		for(int S=1;S<N-1;S++){
			if(!f[S])continue;
			int tot=cnt[S];
			long long val=f[S];
			for(int i=1;i<=m;i++)
				if((S&T[i])&&(S&T[i])!=T[i]){
					int S1=S|T[i];
					(f[S1]+=val*A[m-tot-1][cnt[S1]-tot-1])%=mod;
				}
		}
		(ans*=f[N-1])%=mod;
	}

}

int main(){
	n=read<int>();
	for(int i=1;i<=n;i++)
		a[i]=read<int>();
	for(int i=1;i<=n;i++){
		tag[i]=1;
		for(int j=1;j<=n;j++)
			if((i^j)&&!(a[i]%a[j]))
				tag[i]=0,to[i].push_back(j),to[j].push_back(i);
	}
	for(int i=0;i<=n;i++){
		C[i][0]=A[i][0]=1;
		for(int j=1;j<=i;j++){
			C[i][j]=(C[i-1][j-1]+C[i-1][j])%mod;
			A[i][j]=A[i-1][j-1]*i%mod;
		}
	}
	ans=1;
	for(int i=1;i<=n;i++)
		if(!vis[i])Solve::work(i);
	printf("%lld\n",ans);
	return 0;
}//