C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
OutputCopyYES
NO
YES
NO
NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way:  At 00-th minute, change the state to heating (the temperature is 0).  At 22-nd minute, change the state to off (the temperature is 2).  At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied).  At 66-th minute, change the state to off (the temperature is 3).  At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied).  At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

struct cust{

    ll t,l,h;

};

void solve(){

    ll n,m,lo,hi;

    cin>>n>>m;

    lo=hi=m;

    vector<cust> a(n);

    for(auto &x:a)cin>>x.t>>x.l>>x.h;

    for(int i=n-1;i>0;i--)a[i].t-=a[i-1].t;

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

        if(a[i].h<lo-a[i].t || a[i].l>hi+a[i].t){

            cout<<"NO\n";

            return;

        }

        lo=max(lo-a[i].t,a[i].l);

        hi=min(hi+a[i].t,a[i].h);

    }

    cout<<"YES\n";

    return;

}

int main() {

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

    int t=1;

    cin>>t;

    while(t--)solve();

    return 0;

}


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

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

#define fi(s) freopen(s".in","r",stdin)

#define fo(s) freopen(s".out","w",stdout)

#define file(s) fi(s),fo(s)

using namespace std;

namespace tomorinao {char arrs;

typedef long long ll;

const int mod = 998244353;

int MOD(int x) {return x>=mod?x-mod:x;}

int f[31][25][25][25][25][2][2],w[31],n,m,X[5],Y[5];

int fin(int x,int zx,int zy,int fx,int fy,int lzx,int lzy) {

	if(x==w[0]+1) return !zx&&!zy&&!fx&&!fy&&lzx&&lzy;

	int&r=f[x][zx][zy][fx][fy][lzx][lzy];if(~r) return r;r=0;

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

		int nzx=zx,nzy=zy,nfx=fx,nfy=fy;

		for(int i=0;i<n;i++) if(S>>i&1) {

			if(X[i]>0) nzx+=X[i];else nfx-=X[i];

			if(Y[i]>0) nzy+=Y[i];else nfy-=Y[i];

		}

		if((nzx&1)^(nfx&1)||(nzy&1)^(nfy&1)) continue;

		r=MOD(r+fin(x+1,nzx>>1,nzy>>1,nfx>>1,nfy>>1,(nzx&1)<w[x]?1:(nzx&1)==w[x]?lzx:0,(nzy&1)<w[x]?1:(nzy&1)==w[x]?lzy:0));

	}	return r;

}

char arre;void Main() {

	cerr<<fixed<<setprecision(1)<<(((&arre)-(&arrs))/1024./1024.)<<'\n';

	cin>>n>>m,memset(f,-1,sizeof(f));

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

	while(m) w[++w[0]]=m&1,m>>=1;

	cout<<MOD(fin(1,0,0,0,0,1,1)+mod-1)<<'\n';

}}signed main() {tomorinao::Main();return 0;}


A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length).  Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2
6 3
7 3
OutputCopyYES
NO
Note  The first test case of the example It can be shown that the answer for the second test case of the example is "NO".

#include <iostream>
using namespace std;

int main()
{
    long long t,n,m;
    cin >> t;
    while (t--) {
        cin >> n >> m;
        if (n % m == 0)
            cout << "YES"<<endl;
        else
            cout << "NO"<<endl;
    }
    return 0;
}


B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4
6 10
010010
5 3
10101
1 0
0
2 0
01
OutputCopy3
0
1
-1
NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

auto solve() {

  int n, x;

  cin >> n >> x;

  string s;

  cin >> s;

  int zero = 0, one = 0;

  map<int, int> mp;

  int mi = 0, mx = 0;

  for (auto i : s) {

    if (i == '0')

      zero++;

    else

      one++;

    mp[zero - one]++;

    mi = min(mi, zero - one);

    mx = max(mx, zero - one);

  }

  // cout << mi << " " << mx << " ";

  if (zero - one == 0) {

    if (mp[x] == 0 && x != 0) {

      cout << "0\n";

    } else {

      cout << "-1\n";

    }

  } else {

    int sum = 0;

    if (x == 0)

      sum++;

    if(x < mi && zero - one < 0){

      int dif = abs(mi - x);

      dif /= abs(zero - one);

      x += dif * abs(zero - one);

    }

    while (x < mi && zero - one < 0) {

      x -= zero - one;

    }

    if (x > mx && zero - one > 0) {

      int dif = abs(x - mx);

      dif /= abs(zero-one);

      x -= dif * abs(zero - one);

    }

    while (x > mx && zero - one > 0) {

      x -= zero - one;

    }

    while (x >= mi && x <= mx) {

      sum += mp[x];

      x -= zero - one;

    }

    cout << sum << "\n";

  }

}

auto main() -> int {

  ios::sync_with_stdio(false);

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

  int _ = 1;

  cin >> _;

  while (_--) {

    solve();

  }

}


D. Reality Showtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA popular reality show is recruiting a new cast for the third season! nn candidates numbered from 11 to nn have been interviewed. The candidate ii has aggressiveness level lili, and recruiting this candidate will cost the show sisi roubles.The show host reviewes applications of all candidates from i=1i=1 to i=ni=n by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate ii is strictly higher than that of any already accepted candidates, then the candidate ii will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit.The show makes revenue as follows. For each aggressiveness level vv a corresponding profitability value cvcv is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant ii enters the stage, events proceed as follows:  The show makes clicli roubles, where lili is initial aggressiveness level of the participant ii.  If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is:  the defeated participant is hospitalized and leaves the show.  aggressiveness level of the victorious participant is increased by one, and the show makes ctct roubles, where tt is the new aggressiveness level.  The fights continue until all participants on stage have distinct aggressiveness levels. It is allowed to select an empty set of participants (to choose neither of the candidates).The host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total sisi). Help the host to make the show as profitable as possible.InputThe first line contains two integers nn and mm (1≤n,m≤20001≤n,m≤2000) — the number of candidates and an upper bound for initial aggressiveness levels.The second line contains nn integers lili (1≤li≤m1≤li≤m) — initial aggressiveness levels of all candidates.The third line contains nn integers sisi (0≤si≤50000≤si≤5000) — the costs (in roubles) to recruit each of the candidates.The fourth line contains n+mn+m integers cici (|ci|≤5000|ci|≤5000) — profitability for each aggrressiveness level.It is guaranteed that aggressiveness level of any participant can never exceed n+mn+m under given conditions.OutputPrint a single integer — the largest profit of the show.ExamplesInputCopy5 4
4 3 1 2 1
1 2 1 2 1
1 2 3 4 5 6 7 8 9
OutputCopy6
InputCopy2 2
1 2
0 0
2 1 -100 -100
OutputCopy2
InputCopy5 4
4 3 2 1 1
0 2 6 7 4
12 12 12 6 -3 -5 3 10 -4
OutputCopy62
NoteIn the first sample case it is optimal to recruit candidates 1,2,3,51,2,3,5. Then the show will pay 1+2+1+1=51+2+1+1=5 roubles for recruitment. The events on stage will proceed as follows:  a participant with aggressiveness level 44 enters the stage, the show makes 44 roubles;  a participant with aggressiveness level 33 enters the stage, the show makes 33 roubles;  a participant with aggressiveness level 11 enters the stage, the show makes 11 rouble;  a participant with aggressiveness level 11 enters the stage, the show makes 11 roubles, a fight starts. One of the participants leaves, the other one increases his aggressiveness level to 22. The show will make extra 22 roubles for this. Total revenue of the show will be 4+3+1+1+2=114+3+1+1+2=11 roubles, and the profit is 11−5=611−5=6 roubles.In the second sample case it is impossible to recruit both candidates since the second one has higher aggressiveness, thus it is better to recruit the candidate 11.

// LUOGU_RID: 100118329
#include <cstdio>

#include <cstring>

#include <algorithm>

using std :: max;

namespace nagisa{

	const int maxn = 2005;

	int n,m,l[maxn],c[maxn],p[maxn*2],dp[maxn*2][maxn];

	int main(){

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

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

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

		for(int i=1;i<=n+m;++i)scanf("%d",&p[i]);

		std :: reverse(l+1,l+n+1),std :: reverse(c+1,c+n+1);

		memset(dp,0xcf,sizeof(dp)),dp[0][0] = 0;

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

			for(int j=n-1;~j;--j)dp[l[i]][j+1] = max(dp[l[i]][j+1],dp[l[i]][j]-c[i]+p[l[i]]);

			for(int j=l[i],b=n;j<n+m;++j,b/=2)

				for(int k=0;k<=b;++k)dp[j+1][k/2] = max(dp[j+1][k/2],dp[j][k]+(k/2)*p[j+1]);

		}

		int ans = 0;for(int i=0;i<=n+m;++i)for(int j=0;j<=1;++j)ans = max(ans,dp[i][j]);printf("%d\n",ans);

		return 0;

	}

}

int main(){return nagisa::main();}


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;

long long count(int a,int b)

{

    if(b<10)

    {

        return 0;

    }

    else

        {

            return a+count(a,b/10);

        }

}

void solve()

{

    int a,b;

    cin >> a >> b;

    int dub=b;

    int k=0;

    int d=0;

    while(dub)

    {

        d++;

        if(dub%10==9)

            k++;

        dub=dub/10;

    }

    if(k==d)

        cout << count(a,b)+a;

    else

        cout << count(a,b);

    cout << endl;

}

int main()

{

    int t;

    cin >> t;

    while(t--)

        solve();

    return 0;

}


B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5
1 1
1 1
1 2
1 4
1 3
OutputCopy9
InputCopy3
4 2 0 2 0
6 9 9 8 8 7 7
1 6
OutputCopy7
InputCopy10
3 62 24 39
1 17
1 99
1 60
1 64
1 30
2 79 29
2 20 73
2 85 37
1 100
OutputCopy72
NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.

#include <bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
long long t,sum;
int n,a;
cin>>t;
sum=t*t;
vector<int> x;
vector<int> y;
for(int i=0;i<t;i++){
cin>>n;
int ma=INT_MIN,mi=INT_MAX,b=INT_MAX;
bool can=false;
for(int j=0;j<n;j++){
cin>>a;
if(a>b){
can=true;
}else
b=a;
ma=max(ma,a);
mi=min(mi,a);
}
if(!can){
x.push_back(mi);
y.push_back(ma);
}
}
sort(y.begin(),y.end());
for(int i=0;i<x.size();i++)
sum-=upper_bound(y.begin(),y.end(),x[i])-y.begin();
cout<<sum;
return 0;
}


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


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

#include <bits/stdc++.h>

#include <algorithm>

#include <iostream>

#include <numeric>

#include <cmath>

#include <conio.h>

#include <iomanip>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace std;

using namespace __gnu_pbds;

#define ll long long

#define ld long double

#define el '\n'

#define pi 3.14159265358979323846

#define NumOfDigit(w) (int)(log10(w) + 1)

#define fr(p_) for(auto &p__ : p_) cout<<p__<<" ";

#define debug(x) cout<<"[" << #x << " is:" << x << "]"<<el;

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

// decimal --> fixed << setprecision

#define orderedset template<class T> using ordered_set = tree<T, null_type, std::less<T>, rb_tree_tag, tree_order_statistics_node_update>;

#define tree typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> indexed_set;

//member functions :

//1. order_of_key(k) : number of elements strictly lesser than k

//2. find_by_order(k) : k-th element in the set

bool sortbyPair(const pair<int, int> &a, const pair<int, int> &b) {

    if (a.second != b.second)

        return (a.second < b.second);

    else

        return (a.first < b.first);

}

ll fast_power(ll base, ll exp) {

    if (!exp) return 1;

    ll ans = fast_power(base, exp / 2);

    ans = (ans % 1000000007 * ans % 1000000007) % 1000000007;

    if (exp & 1)

        ans = (ans % 1000000007 * base % 1000000007) % 1000000007;

    return ans;

}

ll convert_binary_to_decimal(long long n) {

    int dec = 0, i = 0, rem;

    while (n != 0) {

        rem = n % 10;

        n /= 10;

        dec += rem * pow(2, i);

        i++;

    }

    return dec;

}

bool is_prime(ll n) {

    if (n == 0 or n == 1)

        return 0;

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

        if (n % i == 0)

            return 0;

    }

    return 1;

}

ll gcd(ll a, ll b) {

    if (b == 0)

        return a;

    return gcd(b, a % b);

}

ll lcm(ll a, ll b) {

    return ((((a / gcd(a, b)) % 1000000009) * (b % 1000000009)) % 1000000009);

}

ll ncr2(ll n, ll r) {

    ll ans = 1, fact = 2;

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

        ans *= i;

        if (ans % fact == 0 and fact <= r)

            ans /= fact++;

    }

    return ans;

}

//ll factorial[1000006], inversefactorial[1000006];

//

//void calcFacAndInv(ll n) {

//    factorial[0] = inversefactorial[0] = 1;

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

//        factorial[i] = (i * factorial[i - 1]) % 1000000007;

//        inversefactorial[i] = fast_power(factorial[i], 1000000007 - 2);

//    }

//}

//

//ll ncr1(ll n, ll r) {

//    return ((factorial[n] % 1000000007 *

//             ((inversefactorial[n - r] % 1000000007 * inversefactorial[r] % 1000000007) % 1000000007) % 1000000007) %

//            1000000007);

//}

//

//

//ll npr(ll n, ll r) {

//    return ((factorial[n] % 1000000007 * inversefactorial[n - r] % 1000000007) % 1000000007);

//}

vector<bool> sieve(ll n) {

    vector<bool> isPrime(n + 1, 1);

    isPrime[0] = isPrime[1] = 0;

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

        if (isPrime[i])

            for (ll j = 2 * i; j <= n; j += i)

                isPrime[j] = 0;

    return isPrime;

}

//vector<pair<ll, ll>> factorize(ll n) {

//    vector<pair<ll, ll>> fact;

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

//        int cnt = 0;

//        while (n % i == 0) {

//            n /= i;

//            cnt++;

//        }

//        if (cnt) fact.push_back({i, cnt});

//    }

//    if (n > 1) fact.push_back({n, 1});

//    return fact;

//}

vector<int> getdivisors(ll n) {

    vector<int> divs;

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

        if (n % i == 0) {

            divs.push_back(i);

            if (i != n / i) divs.push_back(n / i);

        }

    }

    return divs;

}

// upper_bound -->(greater than only) -->return iterator

// lower_bound -->(greater than or equal) -->return iterator

//vector<ll> factorize(ll n) {

//    vector<ll> fact;

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

//        while (n % i == 0) {

//            n /= i;

//            fact.push_back(i);

//        }

//    }

//    if (n > 1) fact.push_back(n);

//    return fact;

//}

pair<int, int> arr[2005];

int main() {

    fast

    int t, n, x, y;

    cin >> t;

    while (t--) {

        cin >> n;

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

            cin >> x >> y;

            arr[i] = make_pair(x, y);

        }

        sort(arr, arr + n);

        int ok = 1;

        int last2 = 0;

        int last = 0;

        string res;

        bool flag = 0;

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

            if (arr[i].second < last) {

                cout << "NO" << el;

                flag = 1;

            }

            if (flag)break;

            int need_x = 0;

            need_x = arr[i].first - last2;

            while (need_x > 0) {

                res += 'R';

                need_x--;

            }

            last2 = arr[i].first;

            need_x = arr[i].second - last;

            while (need_x > 0) {

                res += 'U';

                need_x--;

            }

            last = max(last, arr[i].second);

        }

        if (flag)continue;

        cout << "YES" << el;

        cout << res << el;

    }

    return 0;

}


A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11

#include <bits/stdc++.h>

using namespace std;

typedef long long int ll;

#define fast                      \

    ios_base::sync_with_stdio(0); \

    cout.tie(nullptr);            \

    cin.tie(nullptr);

#define precision cout << fixed << setprecision(12);

#define done cout << "Successful\n";

#define input(gggg, n)             \

    for (int xd = 0; xd < n; xd++) \

        cin >> gggg[xd];

#define print(x) cout << #x << " = " << x << "\n";

#define nl "\n"

#define sp " "

void solve()

{

    ll n, c = 0;

    cin >> n;

    string a;

    if (n % 2 == 0)

    {

        ll d = n / 2;

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

        {

            cout << 1;

        }

    }

    else

    {

        cout << 7;

        ll d = (n - 3) / 2;

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

        {

            cout << 1;

        }

    }

    cout << nl;

}

int main()

{

    fast;

    int t;

    cin >> t;

    while (t--)

        solve();

    // solve();

    return 0;

}


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

#include <bits/stdc++.h>

#pragma GCC optimize(0)

using namespace std;

typedef long long ll;

typedef unsigned long long ull;

inline ll read()

{

    ll X = 0, w = 0; char ch = 0;

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

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

    return w ? -X : X;

}

inline void write(ll x)

{

    if (x < 0) putchar('-'), x = -x;

    if (x > 9) write(x / 10);

    putchar(x % 10 + '0');

}

#define pb push_back

#define mp make_pair

typedef pair<int, int> pii;

using namespace std;

void solve() {

    int n = read(), h = read(), l = read(), r = read();

    int dp[n + 1][h];

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

    dp[0][0] = 0;

    int pres[n + 1];

    pres[0] = 0;

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

        pres[i] = (pres[i - 1] + read()) % h;

    }

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

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

            if (dp[i][j] >= 0) {

                dp[i + 1][j] = max(dp[i + 1][j], dp[i][j] + (l <= (pres[i + 1] - j + h) % h && (pres[i + 1] - j + h) % h <= r));

                dp[i + 1][(j + 1) % h] = max(dp[i + 1][(j + 1) % h], dp[i][j] + (l <= (pres[i + 1] - j - 1 + h + h) % h && (pres[i + 1] - j - 1 + h + h) % h <= r));

            }

        }

    }

    int ans = 0;

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

        if (dp[n][j] > ans) ans = dp[n][j];

    }

    write(ans); putchar('\n');

}

int main() {

    int t = 1;

    while (t--) solve();

}


A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
OutputCopy56
6
442
1
45
80
NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window.

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		int a,b,x,y;
		scanf("%d%d%d%d",&a,&b,&x,&y);
		int p1=a-x-1,q1=b-y-1,p2=x-1+1,q2=y-1+1;
		int f1=p1*b,f2=q1*a,f3=p2*b,f4=q2*a;
		printf("%d\n",max(f1,max(f2,max(f3,f4))));
	}
	return 0;
}


F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by nn castles, the ii-th castle is defended by aiai soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.Each attack must target a castle with at least one alive defender in it. There are three types of attacks:  a mixed attack decreases the number of defenders in the targeted castle by xx (or sets it to 00 if there are already less than xx defenders);  an infantry attack decreases the number of defenders in the targeted castle by yy (or sets it to 00 if there are already less than yy defenders);  a cavalry attack decreases the number of defenders in the targeted castle by zz (or sets it to 00 if there are already less than zz defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.Then, the test cases follow. Each test case is represented by two lines. The first line contains four integers nn, xx, yy and zz (1≤n≤3⋅1051≤n≤3⋅105, 1≤x,y,z≤51≤x,y,z≤5). The second line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤10181≤ai≤1018).It is guaranteed that the sum of values of nn over all test cases in the input does not exceed 3⋅1053⋅105.OutputFor each test case, print the answer to it: the number of possible options for the first attack of the White King (or 00, if the Black King can launch the last attack no matter how the White King acts).ExamplesInputCopy3
2 1 3 4
7 6
1 1 2 3
1
1 1 2 2
3
OutputCopy2
3
0
InputCopy10
6 5 4 5
2 3 2 3 1 3
1 5 2 3
10
4 4 2 3
8 10 8 5
2 2 1 4
8 5
3 5 3 5
9 2 10
4 5 5 5
2 10 4 2
2 3 1 4
1 10
3 1 5 3
9 8 7
2 5 4 5
8 8
3 5 1 4
5 5 10
OutputCopy0
2
1
2
5
12
5
0
0
2

#line 1 "/home/maspy/compro/library/my_template.hpp"

#if defined(LOCAL)

#include <my_template_compiled.hpp>

#else

#pragma GCC optimize("Ofast")

#pragma GCC optimize("unroll-loops")

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

using pi = pair<ll, ll>;

using vi = vector<ll>;

using u32 = unsigned int;

using u64 = unsigned long long;

using i128 = __int128;

template <class T>

using vc = vector<T>;

template <class T>

using vvc = vector<vc<T>>;

template <class T>

using vvvc = vector<vvc<T>>;

template <class T>

using vvvvc = vector<vvvc<T>>;

template <class T>

using vvvvvc = vector<vvvvc<T>>;

template <class T>

using pq = priority_queue<T>;

template <class T>

using pqg = priority_queue<T, vector<T>, greater<T>>;

#define vec(type, name, ...) vector<type> name(__VA_ARGS__)

#define vv(type, name, h, ...) \

  vector<vector<type>> name(h, vector<type>(__VA_ARGS__))

#define vvv(type, name, h, w, ...)   \

  vector<vector<vector<type>>> name( \

      h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))

#define vvvv(type, name, a, b, c, ...)       \

  vector<vector<vector<vector<type>>>> name( \

      a, vector<vector<vector<type>>>(       \

             b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))

// https://trap.jp/post/1224/

#define FOR1(a) for (ll _ = 0; _ < ll(a); ++_)

#define FOR2(i, a) for (ll i = 0; i < ll(a); ++i)

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

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

#define FOR1_R(a) for (ll i = (a)-1; i >= ll(0); --i)

#define FOR2_R(i, a) for (ll i = (a)-1; i >= ll(0); --i)

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

#define FOR4_R(i, a, b, c) for (ll i = (b)-1; i >= ll(a); i -= (c))

#define overload4(a, b, c, d, e, ...) e

#define FOR(...) overload4(__VA_ARGS__, FOR4, FOR3, FOR2, FOR1)(__VA_ARGS__)

#define FOR_R(...) \

  overload4(__VA_ARGS__, FOR4_R, FOR3_R, FOR2_R, FOR1_R)(__VA_ARGS__)

#define FOR_subset(t, s) for (ll t = s; t >= 0; t = (t == 0 ? -1 : (t - 1) & s))

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

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

#define elif else if

#define eb emplace_back

#define mp make_pair

#define mt make_tuple

#define fi first

#define se second

#define stoi stoll

template <typename T, typename U>

T SUM(const vector<U> &A) {

  T sum = 0;

  for (auto &&a: A) sum += a;

  return sum;

}

#define MIN(v) *min_element(all(v))

#define MAX(v) *max_element(all(v))

#define LB(c, x) distance((c).begin(), lower_bound(all(c), (x)))

#define UB(c, x) distance((c).begin(), upper_bound(all(c), (x)))

#define UNIQUE(x) \

  sort(all(x)), x.erase(unique(all(x)), x.end()), x.shrink_to_fit()

int popcnt(int x) { return __builtin_popcount(x); }

int popcnt(u32 x) { return __builtin_popcount(x); }

int popcnt(ll x) { return __builtin_popcountll(x); }

int popcnt(u64 x) { return __builtin_popcountll(x); }

// (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2)

int topbit(int x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }

int topbit(u32 x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }

int topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }

int topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }

// (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2)

int lowbit(int x) { return (x == 0 ? -1 : __builtin_ctz(x)); }

int lowbit(u32 x) { return (x == 0 ? -1 : __builtin_ctz(x)); }

int lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }

int lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }

template <typename T>

T pick(deque<T> &que) {

  T a = que.front();

  que.pop_front();

  return a;

}

template <typename T>

T pick(pq<T> &que) {

  T a = que.top();

  que.pop();

  return a;

}

template <typename T>

T pick(pqg<T> &que) {

  assert(que.size());

  T a = que.top();

  que.pop();

  return a;

}

template <typename T>

T pick(vc<T> &que) {

  assert(que.size());

  T a = que.back();

  que.pop_back();

  return a;

}

template <typename T, typename U>

T ceil(T x, U y) {

  return (x > 0 ? (x + y - 1) / y : x / y);

}

template <typename T, typename U>

T floor(T x, U y) {

  return (x > 0 ? x / y : (x - y + 1) / y);

}

template <typename T, typename U>

pair<T, T> divmod(T x, U y) {

  T q = floor(x, y);

  return {q, x - q * y};

}

template <typename F>

ll binary_search(F check, ll ok, ll ng) {

  assert(check(ok));

  while (abs(ok - ng) > 1) {

    auto x = (ng + ok) / 2;

    tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x));

  }

  return ok;

}

template <typename F>

double binary_search_real(F check, double ok, double ng, int iter = 100) {

  FOR(iter) {

    double x = (ok + ng) / 2;

    tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x));

  }

  return (ok + ng) / 2;

}

template <class T, class S>

inline bool chmax(T &a, const S &b) {

  return (a < b ? a = b, 1 : 0);

}

template <class T, class S>

inline bool chmin(T &a, const S &b) {

  return (a > b ? a = b, 1 : 0);

}

vc<int> s_to_vi(const string &S, char first_char) {

  vc<int> A(S.size());

  FOR(i, S.size()) { A[i] = S[i] - first_char; }

  return A;

}

template <typename T, typename U>

vector<T> cumsum(vector<U> &A, int off = 1) {

  int N = A.size();

  vector<T> B(N + 1);

  FOR(i, N) { B[i + 1] = B[i] + A[i]; }

  if (off == 0) B.erase(B.begin());

  return B;

}

template <typename CNT, typename T>

vc<CNT> bincount(const vc<T> &A, int size) {

  vc<CNT> C(size);

  for (auto &&x: A) { ++C[x]; }

  return C;

}

// stable

template <typename T>

vector<int> argsort(const vector<T> &A) {

  vector<int> ids(A.size());

  iota(all(ids), 0);

  sort(all(ids),

       [&](int i, int j) { return A[i] < A[j] || (A[i] == A[j] && i < j); });

  return ids;

}

// A[I[0]], A[I[1]], ...

template <typename T>

vc<T> rearrange(const vc<T> &A, const vc<int> &I) {

  int n = len(I);

  vc<T> B(n);

  FOR(i, n) B[i] = A[I[i]];

  return B;

}

#endif

#line 1 "/home/maspy/compro/library/other/io.hpp"

// based on yosupo's fastio

#include <unistd.h>

namespace fastio {

// クラスが read(), print() を持っているかを判定するメタ関数

struct has_write_impl {

  template <class T>

  static auto check(T &&x) -> decltype(x.write(), std::true_type{});

  template <class T>

  static auto check(...) -> std::false_type;

};

template <class T>

class has_write : public decltype(has_write_impl::check<T>(std::declval<T>())) {

};

struct has_read_impl {

  template <class T>

  static auto check(T &&x) -> decltype(x.read(), std::true_type{});

  template <class T>

  static auto check(...) -> std::false_type;

};

template <class T>

class has_read : public decltype(has_read_impl::check<T>(std::declval<T>())) {};

struct Scanner {

  FILE *fp;

  char line[(1 << 15) + 1];

  size_t st = 0, ed = 0;

  void reread() {

    memmove(line, line + st, ed - st);

    ed -= st;

    st = 0;

    ed += fread(line + ed, 1, (1 << 15) - ed, fp);

    line[ed] = '\0';

  }

  bool succ() {

    while (true) {

      if (st == ed) {

        reread();

        if (st == ed) return false;

      }

      while (st != ed && isspace(line[st])) st++;

      if (st != ed) break;

    }

    if (ed - st <= 50) {

      bool sep = false;

      for (size_t i = st; i < ed; i++) {

        if (isspace(line[i])) {

          sep = true;

          break;

        }

      }

      if (!sep) reread();

    }

    return true;

  }

  template <class T, enable_if_t<is_same<T, string>::value, int> = 0>

  bool read_single(T &ref) {

    if (!succ()) return false;

    while (true) {

      size_t sz = 0;

      while (st + sz < ed && !isspace(line[st + sz])) sz++;

      ref.append(line + st, sz);

      st += sz;

      if (!sz || st != ed) break;

      reread();

    }

    return true;

  }

  template <class T, enable_if_t<is_integral<T>::value, int> = 0>

  bool read_single(T &ref) {

    if (!succ()) return false;

    bool neg = false;

    if (line[st] == '-') {

      neg = true;

      st++;

    }

    ref = T(0);

    while (isdigit(line[st])) { ref = 10 * ref + (line[st++] & 0xf); }

    if (neg) ref = -ref;

    return true;

  }

  template <typename T,

            typename enable_if<has_read<T>::value>::type * = nullptr>

  inline bool read_single(T &x) {

    x.read();

    return true;

  }

  bool read_single(double &ref) {

    string s;

    if (!read_single(s)) return false;

    ref = std::stod(s);

    return true;

  }

  bool read_single(char &ref) {

    string s;

    if (!read_single(s) || s.size() != 1) return false;

    ref = s[0];

    return true;

  }

  template <class T>

  bool read_single(vector<T> &ref) {

    for (auto &d: ref) {

      if (!read_single(d)) return false;

    }

    return true;

  }

  template <class T, class U>

  bool read_single(pair<T, U> &p) {

    return (read_single(p.first) && read_single(p.second));

  }

  template <size_t N = 0, typename T>

  void read_single_tuple(T &t) {

    if constexpr (N < std::tuple_size<T>::value) {

      auto &x = std::get<N>(t);

      read_single(x);

      read_single_tuple<N + 1>(t);

    }

  }

  template <class... T>

  bool read_single(tuple<T...> &tpl) {

    read_single_tuple(tpl);

    return true;

  }

  void read() {}

  template <class H, class... T>

  void read(H &h, T &... t) {

    bool f = read_single(h);

    assert(f);

    read(t...);

  }

  Scanner(FILE *fp) : fp(fp) {}

};

struct Printer {

  Printer(FILE *_fp) : fp(_fp) {}

  ~Printer() { flush(); }

  static constexpr size_t SIZE = 1 << 15;

  FILE *fp;

  char line[SIZE], small[50];

  size_t pos = 0;

  void flush() {

    fwrite(line, 1, pos, fp);

    pos = 0;

  }

  void write(const char val) {

    if (pos == SIZE) flush();

    line[pos++] = val;

  }

  template <class T, enable_if_t<is_integral<T>::value, int> = 0>

  void write(T val) {

    if (pos > (1 << 15) - 50) flush();

    if (val == 0) {

      write('0');

      return;

    }

    if (val < 0) {

      write('-');

      val = -val; // todo min

    }

    size_t len = 0;

    while (val) {

      small[len++] = char(0x30 | (val % 10));

      val /= 10;

    }

    for (size_t i = 0; i < len; i++) { line[pos + i] = small[len - 1 - i]; }

    pos += len;

  }

  void write(const string s) {

    for (char c: s) write(c);

  }

  void write(const char *s) {

    size_t len = strlen(s);

    for (size_t i = 0; i < len; i++) write(s[i]);

  }

  void write(const double x) {

    ostringstream oss;

    oss << fixed << setprecision(15) << x;

    string s = oss.str();

    write(s);

  }

  void write(const long double x) {

    ostringstream oss;

    oss << fixed << setprecision(15) << x;

    string s = oss.str();

    write(s);

  }

  template <typename T,

            typename enable_if<has_write<T>::value>::type * = nullptr>

  inline void write(T x) {

    x.write();

  }

  template <class T>

  void write(const vector<T> val) {

    auto n = val.size();

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

      if (i) write(' ');

      write(val[i]);

    }

  }

  template <class T, class U>

  void write(const pair<T, U> val) {

    write(val.first);

    write(' ');

    write(val.second);

  }

  template <size_t N = 0, typename T>

  void write_tuple(const T t) {

    if constexpr (N < std::tuple_size<T>::value) {

      if constexpr (N > 0) { write(' '); }

      const auto x = std::get<N>(t);

      write(x);

      write_tuple<N + 1>(t);

    }

  }

  template <class... T>

  bool write(tuple<T...> tpl) {

    write_tuple(tpl);

    return true;

  }

  template <class T, size_t S>

  void write(const array<T, S> val) {

    auto n = val.size();

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

      if (i) write(' ');

      write(val[i]);

    }

  }

  void write(i128 val) {

    string s;

    bool negative = 0;

    if (val < 0) {

      negative = 1;

      val = -val;

    }

    while (val) {

      s += '0' + int(val % 10);

      val /= 10;

    }

    if (negative) s += "-";

    reverse(all(s));

    if (len(s) == 0) s = "0";

    write(s);

  }

};

Scanner scanner = Scanner(stdin);

Printer printer = Printer(stdout);

void flush() { printer.flush(); }

void print() { printer.write('\n'); }

template <class Head, class... Tail>

void print(Head &&head, Tail &&... tail) {

  printer.write(head);

  if (sizeof...(Tail)) printer.write(' ');

  print(forward<Tail>(tail)...);

}

void read() {}

template <class Head, class... Tail>

void read(Head &head, Tail &... tail) {

  scanner.read(head);

  read(tail...);

}

} // namespace fastio

using fastio::print;

using fastio::flush;

using fastio::read;

#define INT(...)   \

  int __VA_ARGS__; \

  read(__VA_ARGS__)

#define LL(...)   \

  ll __VA_ARGS__; \

  read(__VA_ARGS__)

#define STR(...)      \

  string __VA_ARGS__; \

  read(__VA_ARGS__)

#define CHAR(...)   \

  char __VA_ARGS__; \

  read(__VA_ARGS__)

#define DBL(...)      \

  double __VA_ARGS__; \

  read(__VA_ARGS__)

#define VEC(type, name, size) \

  vector<type> name(size);    \

  read(name)

#define VV(type, name, h, w)                     \

  vector<vector<type>> name(h, vector<type>(w)); \

  read(name)

void YES(bool t = 1) { print(t ? "YES" : "NO"); }

void NO(bool t = 1) { YES(!t); }

void Yes(bool t = 1) { print(t ? "Yes" : "No"); }

void No(bool t = 1) { Yes(!t); }

void yes(bool t = 1) { print(t ? "yes" : "no"); }

void no(bool t = 1) { yes(!t); }

#line 1 "/home/maspy/compro/library/string/zalgorithm.hpp"

template <typename STRING>  // string, vector どちらでも

vector<int> zalgorithm(const STRING& s) {

  int n = int(s.size());

  if (n == 0) return {};

  vector<int> z(n);

  z[0] = 0;

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

    int& k = z[i];

    k = (j + z[j] <= i) ? 0 : min(j + z[j] - i, z[i - j]);

    while (i + k < n && s[k] == s[i + k]) k++;

    if (j + z[j] < i + z[i]) j = i;

  }

  z[0] = n;

  return z;

}

#line 4 "main.cpp"

template <typename T>

struct Interpolate_Periodic_Sequence_Query {

  vc<T> dat;

  int p;

  Interpolate_Periodic_Sequence_Query(vc<T> A) : dat(A) {

    reverse(all(A));

    auto Z = zalgorithm(A);

    Z[0] = 0;

    p = max_element(all(Z)) - Z.begin();

    FOR(i, p) assert(A[i] == A[p + i]);

  }

  T operator[](ll n) {

    if (n < len(dat)) return dat[n];

    ll k = ceil(n - (len(dat) - 1), p);

    n -= k * p;

    return dat[n];

  }

};

void solve() {

  LL(N, X, Y, Z);

  ll LIM = 1000;

  vv(int, dp, 3, LIM);

  FOR(n, 1, LIM) {

    FOR(s, 3) {

      set<int> TO;

      TO.insert(dp[0][max<int>(0, n - X)]);

      if (s != 1) TO.insert(dp[1][max<int>(0, n - Y)]);

      if (s != 2) TO.insert(dp[2][max<int>(0, n - Z)]);

      int mex = 0;

      while (TO.count(mex)) ++mex;

      dp[s][n] = mex;

    }

  }

  vc<int> DP = dp[0];

  Interpolate_Periodic_Sequence_Query<int> XXX(DP);

  ll g = 0;

  VEC(ll, A, N);

  for (auto&& x: A) {

    if (x < LIM) continue;

    ll k = ceil(x - (LIM - 1), XXX.p);

    x -= k * XXX.p;

  }

  for (auto&& x: A) { g ^= DP[x]; }

  ll ANS = 0;

  for (auto&& n: A) {

    vc<int> TO;

    TO.eb(dp[0][max<int>(0, n - X)]);

    TO.eb(dp[1][max<int>(0, n - Y)]);

    TO.eb(dp[2][max<int>(0, n - Z)]);

    int now = dp[0][n];

    for (auto&& t: TO)

      if ((g ^ now ^ t) == 0) ++ANS;

  }

  print(ANS);

}

signed main() {

  INT(T);

  FOR(T) solve();

  return 0;

}


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

a
aa
a

cb
b
c

cOutputCopy? 1 2

? 3 4

? 4 4

! aabc

#include <bits/stdc++.h>

using namespace std;

#define int long long

#define fi first

#define se second

int t, n, m, k, a[1000005], mod = 1e9 + 7;

mt19937_64 rng;

map<vector<int>, int> mp;

vector<int> ans[100005];

int mul(int x, int y){

    if(y == 0) return 1;

    int ans = mul(x, y / 2);

    if(y % 2 == 0) return (ans * ans) % mod;

    else return (((ans * ans) % mod) * x) % mod;

}

void solve(){

    if(n == 1){

        cout << "? " << 1 <<" "<< n << endl;

        string s; cin >> s;

        cout << "! " << s << endl; return;

    }

    cout << "? " << 1 <<" "<< n << endl;

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

        string s; cin >> s;

        int sz = s.size();

        vector<int> v(26);

        for(int j = 0; j < sz; j++) v[s[j] - 97]++;

        mp[v]++;

    }

    cout << "? " << 2 <<" "<< n << endl;

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

        string s; cin >> s;

        int sz = s.size();

        vector<int> v(26);

        for(int j = 0; j < sz; j++) v[s[j] - 97]++;

        mp[v]--;

    }

    for(auto i: mp){

        if(i.se){

            int sum = 0;

            for(auto j: i.fi) sum += j;

            ans[sum] = i.fi;

        }

    }

    cout << "! ";

    ans[0].assign(26, 0);

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

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

            if(ans[i][j] > ans[i - 1][j]){

                cout << char(j + 97);

            }

        }

    }

    cout << endl;

}

signed main(){

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

    rng.seed((int)main ^ time(0));

    #ifdef Kawaii

        auto starttime = chrono::high_resolution_clock::now();

    #endif

    cin >> n;

    solve();

    #ifdef Kawaii

        auto endtime = chrono::high_resolution_clock::now();

        auto duration = chrono::duration_cast<chrono::milliseconds>(endtime - starttime).count();

        cout << "\n=====" << "\nUsed: " << duration << " ms\n";

    #endif

}


E. Fedya the Potter Strikes Backtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFedya has a string SS, initially empty, and an array WW, also initially empty.There are nn queries to process, one at a time. Query ii consists of a lowercase English letter cici and a nonnegative integer wiwi. First, cici must be appended to SS, and wiwi must be appended to WW. The answer to the query is the sum of suspiciousnesses for all subsegments of WW [L, R][L, R], (1≤L≤R≤i)(1≤L≤R≤i).We define the suspiciousness of a subsegment as follows: if the substring of SS corresponding to this subsegment (that is, a string of consecutive characters from LL-th to RR-th, inclusive) matches the prefix of SS of the same length (that is, a substring corresponding to the subsegment [1, R−L+1][1, R−L+1]), then its suspiciousness is equal to the minimum in the array WW on the [L, R][L, R] subsegment. Otherwise, in case the substring does not match the corresponding prefix, the suspiciousness is 00.Help Fedya answer all the queries before the orderlies come for him!InputThe first line contains an integer nn (1≤n≤600000)(1≤n≤600000) — the number of queries.The ii-th of the following nn lines contains the query ii: a lowercase letter of the Latin alphabet cici and an integer wiwi (0≤wi≤230−1)(0≤wi≤230−1).All queries are given in an encrypted form. Let ansans be the answer to the previous query (for the first query we set this value equal to 00). Then, in order to get the real query, you need to do the following: perform a cyclic shift of cici in the alphabet forward by ansans, and set wiwi equal to wi⊕(ans & MASK)wi⊕(ans & MASK), where ⊕⊕ is the bitwise exclusive "or", && is the bitwise "and", and MASK=230−1MASK=230−1.OutputPrint nn lines, ii-th line should contain a single integer — the answer to the ii-th query.ExamplesInputCopy7
a 1
a 0
y 3
y 5
v 4
u 6
r 8
OutputCopy1
2
4
5
7
9
12
InputCopy4
a 2
y 2
z 0
y 2
OutputCopy2
2
2
2
InputCopy5
a 7
u 5
t 3
s 10
s 11
OutputCopy7
9
11
12
13
NoteFor convenience; we will call "suspicious" those subsegments for which the corresponding lines are prefixes of SS, that is, those whose suspiciousness may not be zero.As a result of decryption in the first example, after all requests, the string SS is equal to "abacaba", and all wi=1wi=1, that is, the suspiciousness of all suspicious sub-segments is simply equal to 11. Let's see how the answer is obtained after each request:1. SS = "a", the array WW has a single subsegment — [1, 1][1, 1], and the corresponding substring is "a", that is, the entire string SS, thus it is a prefix of SS, and the suspiciousness of the subsegment is 11.2. SS = "ab", suspicious subsegments: [1, 1][1, 1] and [1, 2][1, 2], total 22.3. SS = "aba", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3] and [3, 3][3, 3], total 44.4. SS = "abac", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] and [3, 3][3, 3], total 55.5. SS = "abaca", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [3, 3][3, 3] and [5, 5][5, 5], total 77.6. SS = "abacab", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [1, 6][1, 6], [3, 3][3, 3], [5, 5][5, 5] and [5, 6][5, 6], total 99.7. SS = "abacaba", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [1, 6][1, 6], [1, 7][1, 7], [3, 3][3, 3], [5, 5][5, 5], [5, 6][5, 6], [5, 7][5, 7] and [7, 7][7, 7], total 1212.In the second example, after all requests SS = "aaba", W=[2,0,2,0]W=[2,0,2,0].1. SS = "a", suspicious subsegments: [1, 1][1, 1] (suspiciousness 22), totaling 22.2. SS = "aa", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [2, 2][2, 2] ( 00), totaling 22.3. SS = "aab", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [1, 3][1, 3] ( 00), [2, 2][2, 2] (00), totaling 22.4. SS = "aaba", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [1, 3][1, 3] ( 00), [1, 4][1, 4] (00), [2, 2][2, 2] (00), [4, 4][4, 4] (00), totaling 22.In the third example, from the condition after all requests SS = "abcde", W=[7,2,10,1,7]W=[7,2,10,1,7].1. SS = "a", suspicious subsegments: [1, 1][1, 1] (77), totaling 77.2. SS = "ab", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), totaling 99.3. SS = "abc", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), totaling 1111.4. SS = "abcd", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), [1, 4][1, 4] (11), totaling 1212.5. SS = "abcde", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), [1, 4][1, 4] (11), [1, 5][1, 5] (11), totaling 1313.

// S2OJ Submission #67679 @ 1675132874448
#include <bits/stdc++.h>

#define int long long

const int N = 1e6 + 10;

int n;

char s[N];

int w[N];

std::map<int, int> cnt;

int q[N], top;

int nxt[N], anc[N];

int ans1, ans2;

__int128_t ans;

int sum;

void write(__int128_t x) {

	if (!x) return ;

	write(x / 10);

	putchar(x % 10 + '0');

}

signed main() {

	scanf("%lld", &n);

	nxt[1] = 0;

	getchar();

	s[1] = getchar();

	scanf("%lld", &w[1]);

	ans = w[1];

	ans1 = w[1] % 26, ans2 = w[1];

	q[top = 1] = 1;

	if (ans == 0) {

		puts("0");

	}

	else {

		write(ans);

		puts("");

	}

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

		getchar();

		s[i] = getchar();

		scanf("%lld", &w[i]);

		s[i] = (s[i] - 'a' + ans1) % 26 + 'a';

		w[i] ^= ans2;

		while (j && s[j + 1] != s[i]) {

			j = nxt[j];

		}

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

		nxt[i] = j;

		if (s[nxt[i - 1] + 1] == s[i]) {

			anc[i - 1] = anc[nxt[i - 1]];

		}

		else {

			anc[i - 1] = nxt[i - 1];

		}

		for (int k = i - 1; k > 0;) {

			if (s[k + 1] == s[i]) {

				k = anc[k];

			}

			else {

				int v = w[*std::lower_bound(q + 1, q + top + 1, i - k)];

				--cnt[v];

				sum -= v;

				if (cnt[v] == 0) cnt.erase(v);

				k = nxt[k];

			}

		}

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

			++cnt[w[i]];

			sum += w[i];

		}

		while (top && w[i] <= w[q[top]]) {

			--top;

		}

		q[++top] = i;

		int num = 0;

		for (auto it = cnt.upper_bound(w[i]); it != cnt.end();) {

			sum -= 1ll * (it->first) * (it->second);

			num += it->second;

			auto jt = std::next(it);

			cnt.erase(it);

			it = jt;

		}

		cnt[w[i]] += num;

		sum += num * w[i];

		int res = w[q[1]] + sum;

		ans1 = (ans1 + res) % 26;

		ans2 = (ans2 + res) & ((1ll << 30) - 1);

		ans += res;

		if (ans == 0) {

			puts("0");

		}

		else {

			write(ans);

			puts("");

		}

	}

	return 0;

}


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

#include <bits/stdc++.h>

using namespace std;

#ifdef AISH_PC

    #include <debug.h>

#else

    #define debug(x...)

#endif

#define fastIO          {ios_base ::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);}

#define int             long long

#define mod             1000000007

#define PI              3.1415926535897932384626

#define endl            "\n"

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

#define YES             cout << "YES" << "\n"

#define NO              cout << "NO" << "\n"

#define ispowoftwo(n)   (!(n & (n-1)))

#define pb              push_back

#define ppb             pop_back

#define mine(a)    (*min_element((a).begin(), (a).end()))

#define maxe(a)    (*max_element((a).begin(), (a).end()))

#define mini(a)    ( min_element((a).begin(), (a).end()) - (a).begin())

#define maxi(a)    ( max_element((a).begin(), (a).end()) - (a).begin())

#define lowb(a, x) ( lower_bound((a).begin(), (a).end(), (x)) - (a).begin())

#define uppb(a, x) ( upper_bound((a).begin(), (a).end(), (x)) - (a).begin())

typedef pair<int,int> pii;

typedef vector<int> vi;

typedef vector<pii> vp;

typedef vector<vi> vvi;

vi prime;

int gcd(int a, int b)

{

    if (a == 0)

        return b;

    return gcd(b % a, a);

}

//Function for creating a vector of prime numbers

void primes(int n)

{

    prime.assign(n+1,1);

    for (int p=2;p*p<=n;p++)

    {

        if(prime[p])

        {

            for (int i=p*p;i<=n;i+=p)

            {

                prime[i]=0;

            }

        }

    }

}

//Conditional sorting in vector of pairs

bool sortcon(const pair<int,int>&a,const pair<int,int>&b)

{

    if(a.first==b.first)

    {

        return(a.second>b.second);

    }

    return a.first<b.first;

}

void solve()

{

    int n;

    string s;

    cin>>n>>s;

    map<string,int>mp;

    int k=0;

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

    {

        string s1=s.substr(0,k);

        string s2=s.substr(k);

        if((n-k)%2!=0)

        {

            reverse(all(s1));

        }

        if(mp[s2+s1]==0)

        {

            mp[s2+s1]=k+1;

        }

        else

        {

            mp[s2+s1]=min(mp[s2+s1],k+1);

        }

        debug(s1, s2);

        k++;

    }

    auto it=mp.begin();

    cout<<it->first<<endl;

    cout<<it->second<<endl;

}

//<><><><><><><><><><><><>><><>><><><><><><><>

int32_t main()

{

    fastIO;

    auto start = std::chrono::high_resolution_clock::now();

    int t;

    t=1;

    cin>>t;

    while(t--)

    {

        solve();

    }

    return 0;

}


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

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

using namespace std;

#define pi pair<int,int>

#define mp make_pair

#define fi first

#define se second

#define pb push_back

#define ls (rt<<1)

#define rs (rt<<1|1)

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

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

const int maxn=1e4+5,M=2e5+5,mod=998244353;

inline int read(){

	char ch=getchar();bool f=0;int x=0;

	for(;!isdigit(ch);ch=getchar())if(ch=='-')f=1;

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

	if(f==1){x=-x;}return x;

}

void print(int x){

    static int a[55];int top=0;

    if(x<0) putchar('-'),x=-x;

    do{a[top++]=x%10,x/=10;}while(x);

    while(top) putchar(a[--top]+48);

}

int n,k,flag[maxn],x,ans=0;

int g[1055][1055];

char a[5];

void query(int x){

	cout<<"? "<<x<<endl;

	fflush(stdout);

	scanf("%s",a);

	if(a[0]=='Y')flag[x]=1;

}

void solve(int x,int y){

	cout<<"R \n";

	fflush(stdout);

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

		query(g[x][i]);

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

		query(g[y][i]);

}

signed main(){

	n=read(),k=read();

	if(n<=k){

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

			query(i);ans+=!flag[i];

		}

		cout<<"! "<<ans<<endl;

		fflush(stdout);

		exit(0);

	}

	if(k==1){

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

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

				cout<<"R \n";

				fflush(stdout);

				query(j),query(i);

				if(flag[i])break;

			}

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

		if(!flag[i])ans++;

		cout<<"! "<<ans<<endl;

		fflush(stdout);exit(0);

	}int z=0;

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

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

			g[z][j]=i+j;

	}

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

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

			solve(i,j);

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

		if(!flag[i])ans++;

	cout<<"! "<<ans<<endl;

	fflush(stdout);

 	return 0;

}


D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns.   You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster.  Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3
7 10 50 12 1 8
OutputCopy5
InputCopy1 1 100 99
100
OutputCopy1
InputCopy7 4 2 1
1 3 5 4 2 7 6
OutputCopy6

#include<bits/stdc++.h>

#define int long long

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

#define pb push_back

#define bp pop_back

#define mp make_pair

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

#define vi vector<int>

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

using namespace std;

void solve(){

    int n,a,b,k;

    cin>>n>>a>>b>>k;

    vector<int>v(n),temp;

    fa(i,0,n)cin>>v[i];

    fa(i,0,n){

        int kar = v[i]%(a+b);

        if(!kar)temp.pb(b);

        else if(kar>a)temp.pb(kar-a);

    }

    int ct=0;

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

    ct+=(n-temp.size());

    fa(i,0,temp.size()){

        int ans = temp[i]/a;

        if(temp[i]%a)ans++;

        if(ans>k)break;

        k-=ans;

        ct++;

    }

    cout<<ct<<endl;

    return;

}

signed main()

{

    Utaval;

    int t=1;

   // cin>>t;

    while(t--)

    solve();

}


D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3
1 2 3
OutputCopy2
InputCopy2
1 5
OutputCopy4
NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5.

#include<bits/stdc++.h>

typedef long long ll;

const int maxx=10010;

const int inf=0x3f3f3f3f;

using namespace std;

vector<int>a;

int n;

int solve(vector<int>v, int bit)

{

    if(bit<0 || v.size()==0)

        return 0;

    vector<int>z,o;

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

    {

        if((v[i]>>bit)&1)

            z.push_back(v[i]);

        else

            o.push_back(v[i]);

    }

    if(o.size()==0)

        return solve(z,bit-1);

    if(z.size()==0)

        return solve(o,bit-1);

    return (min(solve(o,bit-1),solve(z, bit-1))|1<<bit);

}

int main()

{

    cin>>n;

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

    {

        cin>>x;

        a.push_back(x);

    }

    cout<<solve(a,30)<<endl;

    return 0;

}


#include <cstdio>

#include <algorithm>

using namespace std;

const int maxn = 100000 + 10;

int n;

int trie[maxn*30][2], cnt;

void insert(int val)

{

    int x = 0;

    for (int i=(1<<29);i;i>>=1)

    {

        int a = (bool)(val & i);

        if (!trie[x][a]) trie[x][a] = ++cnt;

        x = trie[x][a];

    }

}

int find(int x, int k)

{

    if ((!trie[x][0] && !trie[x][1])) return 0;

    int ans = 0x3f3f3f3f;

    if (trie[x][0]) ans = min(ans, find(trie[x][0], k >> 1));

    if (trie[x][1]) ans = min(ans, find(trie[x][1], k >> 1));

    return trie[x][0] && trie[x][1] ? (k | ans) : ans;

}

int main()

{

    scanf("%d",&n);

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

    {

        int a;

        scanf("%d",&a);

        insert(a);

    }

    printf("%d\n",find(0, 1<<29));

    return 0;

}


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.

///Moba8ta gya mn el 2alb

#pragma GCC optimize("O3")

#pragma GCC optimize("unroll-loops")

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

#include "bits/stdc++.h"

using namespace std;

#define pb push_back

#define F first

#define S second

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

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

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

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

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

#define popCnt(x) (__builtin_popcountll(x))

#define int ll

using ll = long long;

using ull = unsigned long long;

using uint = uint32_t;

using ii = pair<int, int>;

const int N = 2e5 + 5, A = 12, LG = 18, MOD = 1e9 + 7;

const long double PI = acos(-1);

const long double EPS = 1e-9;

const int INF = 1e18;

void doWork()

{

    int n, m;

    cin >> n >> m;

    int sum = 0;

    f(i,0,n) {

        int x;

        cin >> x;

        sum += x;

    }

    cout << min(sum,m) << endl;

}

int32_t main()

{

#ifdef ONLINE_JUDGE

    ios_base::sync_with_stdio(0);

    cin.tie(0);

#endif // ONLINE_JUDGE

    int t = 1;

    cin >> t;

    while (t--)

    {

        doWork();

    }

    return 0;

}


F. Bad Cryptographytime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn modern cryptography much is tied to the algorithmic complexity of solving several problems. One of such problems is a discrete logarithm problem. It is formulated as follows:  Let's fix a finite field and two it's elements aa and bb. One need to fun such xx that ax=bax=b or detect there is no such x. It is most likely that modern mankind cannot solve the problem of discrete logarithm for a sufficiently large field size. For example, for a field of residues modulo prime number, primes of 1024 or 2048 bits are considered to be safe. However, calculations with such large numbers can place a significant load on servers that perform cryptographic operations. For this reason, instead of a simple module residue field, more complex fields are often used. For such field no fast algorithms that use a field structure are known, smaller fields can be used and operations can be properly optimized. Developer Nikolai does not trust the generally accepted methods, so he wants to invent his own. Recently, he read about a very strange field — nimbers, and thinks it's a great fit for the purpose. The field of nimbers is defined on a set of integers from 0 to 22k−122k−1 for some positive integer kk . Bitwise exclusive or (⊕⊕) operation is used as addition. One of ways to define multiplication operation (⊙⊙) is following properties:   0⊙a=a⊙0=00⊙a=a⊙0=0  1⊙a=a⊙1=a1⊙a=a⊙1=a  a⊙b=b⊙aa⊙b=b⊙a  a⊙(b⊙c)=(a⊙b)⊙ca⊙(b⊙c)=(a⊙b)⊙c  a⊙(b⊕c)=(a⊙b)⊕(a⊙c)a⊙(b⊕c)=(a⊙b)⊕(a⊙c)  If a=22na=22n for some integer n>0n>0, and b<ab<a, then a⊙b=a⋅ba⊙b=a⋅b.  If a=22na=22n for some integer n>0n>0, then a⊙a=32⋅aa⊙a=32⋅a. For example:   4⊙4=64⊙4=6  8⊙8=4⊙2⊙4⊙2=4⊙4⊙2⊙2=6⊙3=(4⊕2)⊙3=(4⊙3)⊕(2⊙(2⊕1))=(4⊙3)⊕(2⊙2)⊕(2⊙1)=12⊕3⊕2=13.8⊙8=4⊙2⊙4⊙2=4⊙4⊙2⊙2=6⊙3=(4⊕2)⊙3=(4⊙3)⊕(2⊙(2⊕1))=(4⊙3)⊕(2⊙2)⊕(2⊙1)=12⊕3⊕2=13.  32⊙64=(16⊙2)⊙(16⊙4)=(16⊙16)⊙(2⊙4)=24⊙8=(16⊕8)⊙8=(16⊙8)⊕(8⊙8)=128⊕13=14132⊙64=(16⊙2)⊙(16⊙4)=(16⊙16)⊙(2⊙4)=24⊙8=(16⊕8)⊙8=(16⊙8)⊕(8⊙8)=128⊕13=141  5⊙6=(4⊕1)⊙(4⊕2)=(4⊙4)⊕(4⊙2)⊕(4⊙1)⊕(1⊙2)=6⊕8⊕4⊕2=85⊙6=(4⊕1)⊙(4⊕2)=(4⊙4)⊕(4⊙2)⊕(4⊙1)⊕(1⊙2)=6⊕8⊕4⊕2=8 Formally, this algorithm can be described by following pseudo-code. multiply(a, b) {   ans = 0   for p1 in bits(a)       // numbers of bits of a equal to one       for p2 in bits(b)   // numbers of bits of b equal to one          ans = ans xor multiply_powers_of_2(1 << p1, 1 << p2)   return ans;}multiply_powers_of_2(a, b) {    if (a == 1 or b == 1) return a * b    n = maximal value, such 2^{2^{n}} <= max(a, b)    power = 2^{2^{n}};    if (a >= power and b >= power) {        return multiply(power * 3 / 2, multiply_powers_of_2(a / power, b / power))    } else if (a >= power) {        return multiply_powers_of_2(a / power, b) * power    } else {        return multiply_powers_of_2(a, b / power) * power    }}It can be shown, that this operations really forms a field. Moreover, than can make sense as game theory operations, but that's not related to problem much. With the help of appropriate caching and grouping of operations, it is possible to calculate the product quickly enough, which is important to improve speed of the cryptoalgorithm. More formal definitions as well as additional properties can be clarified in the wikipedia article at link. The authors of the task hope that the properties listed in the statement should be enough for the solution. Powering for such muliplication is defined in same way, formally a⊙k=a⊙a⊙⋯⊙ak timesa⊙k=a⊙a⊙⋯⊙a⏟k times.You need to analyze the proposed scheme strength. For pairs of numbers aa and bb you need to find such xx, that a⊙x=ba⊙x=b, or determine that it doesn't exist. InputIn the first line of input there is single integer tt (1≤t≤1001≤t≤100) — number of pairs, for which you need to find the discrete logarithm.In each of next tt line there is a pair of integers aa bb (1≤a,b<2641≤a,b<264). OutputFor each pair you should print one integer xx (0≤x<2640≤x<264), such that a⊙x=ba⊙x=b, or -1 if no such x exists. It can be shown, that if any such xx exists, there is one inside given bounds. If there are several good values, you can output any of them. ExampleInputCopy7
2 2
1 1
2 3
8 10
8 2
321321321321 2
123214213213 4356903202345442785
OutputCopy1
1
2
4
-1
6148914691236517205
68943624821423112

#include <bits/stdc++.h>

using namespace std;
typedef unsigned long long ull;
const ull l = 0xFFFFFFFFFFFFFFFF;
const int p[] = {3, 5, 17, 257, 641, 65537, 6700417}, m[] = {1, 2, 6, 16, 25, 256, 2588}, I[] = {2, 2, 1, 32, 590, 16384, 3883315};
ull F[65][65], T[65][257][257], a, b, ans; int t, r[7];
ull mul(ull, ull) ;
ull mul2(ull a, ull b) {
if (a == 1 || b == 1) return a * b;
if (a < b) swap(a, b);
int x = __builtin_ctzll(a), y = __builtin_ctzll(b), z = 1 << 63 - __builtin_clz(x);
if (y & z) return mul((1ull << z >> 1) * 3, mul2(a >> z, b >> z));
return mul2(a >> z, b) << z;
}
ull mul(ull a, ull b) {
ull x, y, c = 0;
for (ull i=a; i; i^=x) {
x = 1ull << __builtin_ctzll(i);
for (ull j=b; j; j^=y)
y = 1ull << __builtin_ctzll(j), c ^= mul2(x, y);
} return c;
}
ull prod(ull a, ull b) {
ull c = 0;
for (int i=0; i<8; i++)
for (int j=0; j<8; j++)
c ^= T[i<<3|j][a>>(i<<3)&255][b>>(j<<3)&255];
return c;
}
ull qpow(ull x, ull y) {
ull t = 1;
for (; y; y>>=1) {
if (y & 1) t = prod(t, x);
x = prod(x, x);
} return t;
}
int main() {
for (int x=0; x<64; x++)
for (int y=0; y<64; y++)
F[x][y] = mul2(1ull << x, 1ull << y);
for (int i=0; i<8; i++)
for (int j=0; j<8; j++) {
for (int x=0; x<8; x++)
for (int y=0; y<8; y++)
T[i<<3|j][1<<x][1<<y] = F[i<<3|x][j<<3|y];
for (int a=1; a<256; a++)
for (int b=1; b<256; b++)
if (a^a&-a) T[i<<3|j][a][b] = T[i<<3|j][a&-a][b] ^ T[i<<3|j][a^a&-a][b];
else if (b^b&-b) T[i<<3|j][a][b] = T[i<<3|j][a][b&-b] ^ T[i<<3|j][a][b^b&-b];
}
cin >> t;
while (t --) {
scanf ("%llu%llu", &a, &b), ans = 0;
for (int i=0; i<7; i++) {
ull A = qpow(a, l / p[i]), B = qpow(b, l / p[i]), Am = qpow(A, m[i]), P = 1; int res = -1;
unordered_map <ull, int> id;
for (int j=0; j<m[i]; j++)
id[B] = j, B = prod(B, A);
for (int j=0, u=(p[i]-1)/m[i]; j<=u; j++) {
if (id. find(P) != id. end()) {
res = (j * m[i] - id[P] + p[i]) % p[i];
break;
} P = prod(P, Am);
}
if (~ res) r[i] = res;
else { puts ("-1"); goto E; }
}
for (int i=0; i<7; i++)
ans = (ans + (__int128) I[i] * (l / p[i]) * r[i]) % l;
printf ("%llu\n", ans); E : ;
}
}