D. Around the Worldtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are planning 144144 trips around the world.You are given a simple weighted undirected connected graph with nn vertexes and mm edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 33 which passes through the vertex 11. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.But the trips with cost 00 aren't exciting. You may choose any subset of edges incident to the vertex 11 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 00 which passes through the vertex 11 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 109+7109+7.InputThe first line contains two integers nn and mm (1≤n,m≤1051≤n,m≤105) — the number of vertexes and edges in the graph. The ii-th of the next mm lines contains three integers aiai, bibi and wiwi (1≤ai,bi≤n,ai≠bi,0≤wi<321≤ai,bi≤n,ai≠bi,0≤wi<32) — the endpoints of the ii-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than 33 which passes through the vertex 11.OutputOutput the answer modulo 109+7109+7.ExamplesInputCopy6 8
1 2 0
2 3 1
2 4 3
2 6 2
3 4 8
3 5 4
5 4 5
5 6 6
OutputCopy2
InputCopy7 9
1 2 0
1 3 1
2 3 9
2 4 3
2 5 4
4 5 7
3 6 6
3 7 7
6 7 8
OutputCopy1
InputCopy4 4
1 2 27
1 3 1
1 4 1
3 4 0
OutputCopy6NoteThe pictures below represent the graphs from examples.  In the first example; there aren't any nontrivial cycles with cost 00, so we can either remove or keep the only edge incident to the vertex 11.  In the second example, if we don't remove the edge 1−21−2, then there is a cycle 1−2−4−5−2−11−2−4−5−2−1 with cost 00; also if we don't remove the edge 1−31−3, then there is a cycle 1−3−2−4−5−2−3−11−3−2−4−5−2−3−1 of cost 00. The only valid subset consists of both edges.  In the third example, all subsets are valid except for those two in which both edges 1−31−3 and 1−41−4 are kept.

#include<bits/stdc++.h>
using namespace std;
#define I inline int
#define V inline void
#define FOR(i,a,b) for(int i=a;i<=b;i++)
#define ROF(i,a,b) for(int i=a;i>=b;i--)
#define REP(u) for(int i=h[u],v;v=e[i].t,i;i=e[i].n)
const int N=1e5+1,M=400,mod=1e9+7,bit[]={1,3,7,15,31};
V check(int&x){x-=mod,x+=x>>31&mod;}
int n,m,tot,qwq,txt[N],dfn[N];
int h[N],fa[N],dep[N],dis[N],tag[N];
int to[M][M],dp[N][M],pre[N],id[1<<15];
struct edge{int t,n,w;}e[N<<1];
struct bas{
	int a[5],flag;
	I ins(int x){
		ROF(i,4,0)if(x>>i&1){
			if(a[i])x^=a[i];
			else return a[i]=x,1;
		}
		return flag=1,0;
	}
	I comp(){return a[0]|a[1]<<1|a[2]<<3|a[3]<<6|a[4]<<10;}
	V assign(int x){a[0]=x&1,a[1]=x>>1&3,a[2]=x>>3&7,a[3]=x>>6&15,a[4]=x>>10;}
	I hash(){
		FOR(i,0,4)if(a[i]&&!(a[i]>>i&1))return -1;
		FOR(i,0,4)FOR(j,i+1,4)if(a[j]>>i&1)a[j]^=a[i];
		return comp();
	}
}t[N][2],tmp;
I merge(int x,int y){
	static bas tx,ty;tx.assign(x),ty.assign(y);
	FOR(i,0,4)if(ty.a[i]&&!tx.ins(ty.a[i]))return 2;
	return tx.hash();
}
V add_edge(int x,int y,int w){
	if(y-1)e[++tot]=(edge){y,h[x],w},h[x]=tot;
	if(x-1)e[++tot]=(edge){x,h[y],w},h[y]=tot;
}
I find(int x){return fa[x]==x?x:fa[x]=find(fa[x]);}
V con(int x,int y){if(x-1&&y-1)fa[find(x)]=find(y);}
V input(){
	scanf("%d%d",&n,&m);
	FOR(i,1,n)fa[i]=i;int x,y,w;
	while(m--)scanf("%d%d%d",&x,&y,&w),con(x,y),add_edge(x,y,w);
}
queue<int>q;
V bfs(){
	for(q.push(1);!q.empty();q.pop()){
		int u=q.front(),p=dfn[find(u)];
		REP(u)
			if(!dep[v])
				dep[v]=dep[u]+1,pre[v]=u,dis[v]=dis[u]^e[i].w,q.push(v);
			else if(u>v&&pre[u]!=v){
				if(dep[u]==dep[v]&&dep[u]==1)tag[p]=dis[u]^dis[v]^e[i].w;
				else t[p][0].ins(dis[u]^dis[v]^e[i].w);
			}
	}
}
V init(){
	FOR(i,2,n)if(!dfn[find(i)])dfn[find(i)]=++qwq;
	tot=0,memset(tag,-1,sizeof(tag)),bfs(),dp[0][1]=1;
	int p,x=0;
	FOR(i,0,(1<<15)-1){
		tmp.assign(i),p=tmp.hash();
		if(~p&&!id[p])txt[id[p]=++tot]=p;
	}
	FOR(i,1,qwq)if(~tag[i])t[i][1]=t[i][0],t[i][1].ins(tag[i]);
	FOR(i,1,tot)FOR(j,1,tot)to[i][j]=id[merge(txt[i],txt[j])];
}
V work(){
	int p,ans=0;
	FOR(i,1,qwq){
		if(!t[i][0].flag){
			p=id[t[i][0].hash()];
			FOR(j,1,tot)check(dp[i][to[j][p]]+=(dp[i-1][j]<<!!~tag[i])%mod);
		}
		if(~tag[i]&&!t[i][1].flag){
			p=id[t[i][1].hash()];
			FOR(j,1,tot)check(dp[i][to[j][p]]+=dp[i-1][j]);
		}
		FOR(j,1,tot)check(dp[i][j]+=dp[i-1][j]);
	}
	FOR(i,1,tot)check(ans+=dp[qwq][i]);
	cout<<ans<<'\n';
}
int main(){
	input();
	init();
	work();
	return 0;
}


F. Super Jabertime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJaber is a superhero in a large country that can be described as a grid with nn rows and mm columns, where every cell in that grid contains a different city.Jaber gave every city in that country a specific color between 11 and kk. In one second he can go from the current city to any of the cities adjacent by the side or to any city with the same color as the current city color.Jaber has to do qq missions. In every mission he will be in the city at row r1r1 and column c1c1, and he should help someone in the city at row r2r2 and column c2c2.Jaber wants your help to tell him the minimum possible time to go from the starting city to the finishing city for every mission.InputThe first line contains three integers nn, mm and kk (1≤n,m≤10001≤n,m≤1000, 1≤k≤min(40,n⋅m)1≤k≤min(40,n⋅m)) — the number of rows, columns and colors.Each of the next nn lines contains mm integers. In the ii-th line, the jj-th integer is aijaij (1≤aij≤k1≤aij≤k), which is the color assigned to the city in the ii-th row and jj-th column.The next line contains one integer qq (1≤q≤1051≤q≤105)  — the number of missions.For the next qq lines, every line contains four integers r1r1, c1c1, r2r2, c2c2 (1≤r1,r2≤n1≤r1,r2≤n, 1≤c1,c2≤m1≤c1,c2≤m)  — the coordinates of the starting and the finishing cities of the corresponding mission.It is guaranteed that for every color between 11 and kk there is at least one city of that color.OutputFor every mission print the minimum possible time to reach city at the cell (r2,c2)(r2,c2) starting from city at the cell (r1,c1)(r1,c1).ExamplesInputCopy3 4 5
1 2 1 3
4 4 5 5
1 2 1 3
2
1 1 3 4
2 2 2 2
OutputCopy2
0
InputCopy4 4 8
1 2 2 8
1 3 4 7
5 1 7 6
2 3 8 8
4
1 1 2 2
1 1 3 4
1 1 2 4
1 1 4 4
OutputCopy2
3
3
4
NoteIn the first example:  mission 11: Jaber should go from the cell (1,1)(1,1) to the cell (3,3)(3,3) because they have the same colors, then from the cell (3,3)(3,3) to the cell (3,4)(3,4) because they are adjacent by side (two moves in total);  mission 22: Jaber already starts in the finishing cell. In the second example:  mission 11: (1,1)(1,1) →→ (1,2)(1,2) →→ (2,2)(2,2);  mission 22: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (3,4)(3,4);  mission 33: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (2,4)(2,4);  mission 44: (1,1)(1,1) →→ (1,2)(1,2) →→ (1,3)(1,3) →→ (1,4)(1,4) →→ (4,4)(4,4).

#include <bits/stdc++.h>

#pragma GCC optimize("Ofast")

#define debug(x) cerr << #x << " " << x << "\n"

#define debugs(x) cerr << #x << " " << x << " "

using namespace std;

typedef long long ll;

typedef pair <int, int> pii;

const ll NMAX = 1002;

const ll VMAX = 41;

const ll INF = (1LL << 59);

const ll MOD = 1000000009;

const ll BLOCK = 318;

const ll base = 31;

const ll nrbits = 21;

int dist[NMAX][NMAX][41];

int mat[NMAX][NMAX];

vector <pii> v[41];

bool viz[41];

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

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

int n, m;

bool OK(int i, int j) {

    if(i > 0 && i <= n && j > 0 && j <= m)

        return 1;

    return 0;

}

int main() {

#ifdef HOME

    ifstream cin(".in");

    ofstream cout(".out");

#endif // HOME

    ios_base::sync_with_stdio(false);

    cin.tie(0);

    cout.tie(0);

    int k, i, j;

    cin >> n >> m >> k;

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

        for(j = 1; j <= m; j++) {

            cin >> mat[i][j];

            v[mat[i][j]].push_back({i, j});

        }

    }

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

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

            for(j = 1; j <= max(m, k); j++) {

                dist[i][j][col] = 32767;

            }

        }

        for(i = 1; i <= k; i++) viz[i] = 0;

        queue <pii> q;

        for(auto x : v[col]) {

            dist[x.first][x.second][col] = 0;

            q.push({x.first, x.second});

        }

        while(q.size()) {

            pii x = q.front();

            q.pop();

            for(int d = 0; d < 4; d++) {

                pii care = {x.first + dx[d], x.second + dy[d]};

                if(!OK(care.first, care.second)) continue;

                if(dist[care.first][care.second][col] == 32767) { /// Hmm...

                    dist[care.first][care.second][col] = dist[x.first][x.second][col] + 1;

                    q.push({care.first, care.second});

                }

            }

            if(!viz[mat[x.first][x.second]]) {

                viz[mat[x.first][x.second]] = 1;

                for(auto y : v[mat[x.first][x.second]]) {

                    pii care = y;

                    if(dist[care.first][care.second][col] == 32767) { /// Hmm...

                        dist[care.first][care.second][col] = dist[x.first][x.second][col] + 1;

                        q.push({care.first, care.second});

                    }

                }

            }

        }

    }

    int q;

    cin >> q;

    while(q--) {

        int a, b, c, d;

        cin >> a >> b >> c >> d;

        int minim = abs(c - a) + abs(d - b);

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

            minim = min(minim, (int)dist[a][b][col] + (int)dist[c][d][col] + 1);

        }

        cout << minim << "\n";

    }

    return 0;

}


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;

typedef unsigned long long ull;

using namespace std;

const ll mod = 998244353;

const int mm = 1e5 + 10;

vector<int>b;

ll dfs(int x,vector<int>v){

	if(v.size()==0||x<0)return 0;

	vector<int>l,r;

	for(auto i:v){

		if((1<<x)&i)l.push_back(i);

		else r.push_back(i);

	}

	if(l.size()==0)return dfs(x-1,r);

	else if(r.size()==0)return dfs(x-1,l);

	else return (1<<x)+min(dfs(x-1,l),dfs(x-1,r));

}

int main(){

	std::ios::sync_with_stdio(false);

	std::cin.tie(0);

	std::cout.tie(0);

	int n;

	cin>>n;

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

		ll x;

		cin>>x;

		b.push_back(x);

	}

	cout<<dfs(30,b);

}


C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33:  [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66.  [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32.

#include<stdio.h>
int main()
{
long long int n,m,ans=0;scanf("%lld%lld",&n,&m);
long long int store[n+2]; store[1] = 1;
for(int i=2;i<=n+1;i++)store[i]=(store[i-1]*i)%m;
for(int i=1;i<=n;i++)ans+=(n-i+1)*(store[i]*store[n-i+1]%m),ans%=m;
printf("%lld\n",ans);
}


D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10

#include <bits/stdc++.h>

#define int long long

using namespace std;

int32_t main()

{

        ios_base::sync_with_stdio(false);

        cin.tie(NULL);

        vector<vector<int>> a(26);

        vector<vector<int>> b(26);

        vector<int> qa;

        vector<int>qb;

        int n;

        string x, y;

        cin >> n >> x >> y;

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

                if (x[i] == '?') qa.push_back(i + 1);

                else a[x[i] - 'a'].push_back(i + 1);

                if (y[i] == '?') qb.push_back(i + 1);

                else b[y[i] - 'a'].push_back(i + 1);

        }

        vector<pair<int, int>> ans;

        vector<int> sa;

        vector<int> sb;

        int z;

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

                z = min((int)a[i].size(), (int)b[i].size());

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

                        ans.push_back({a[i].back(), b[i].back()});

                        a[i].pop_back();

                        b[i].pop_back();

                }

                for (auto z : a[i]) sa.push_back(z);

                for (auto z : b[i]) sb.push_back(z);

        }

        z = min((int)sa.size(), (int)qb.size());

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

                ans.push_back({sa.back(), qb.back()});

                sa.pop_back();

                qb.pop_back();

        }

        z = min((int)qa.size(), (int)sb.size());

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

                ans.push_back({qa.back(), sb.back()});

                qa.pop_back();

                sb.pop_back();

        }

        z = min((int)qa.size(), (int)qb.size());

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

                ans.push_back({qa.back(), qb.back()});

                qa.pop_back();

                qb.pop_back();

        }

        cout << ans.size() << '\n';

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

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

        }

}


F. Battalion Strengthtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn officers in the Army of Byteland. Each officer has some power associated with him. The power of the ii-th officer is denoted by pipi. As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these nn officers and calls this subset a battalion.(All 2n2n subsets of the nn officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be a1,a2,…,aka1,a2,…,ak, where a1≤a2≤⋯≤aka1≤a2≤⋯≤ak. The strength of this battalion is equal to a1a2+a2a3+⋯+ak−1aka1a2+a2a3+⋯+ak−1ak. (If the size of Battalion is ≤1≤1, then the strength of this battalion is 00).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be qq changes. Each one of the form ii xx indicating that pipi is changed to xx.You need to find the strength of the army initially and after each of these qq updates.Note that the changes are permanent.The strength should be found by modulo 109+7109+7. Formally, let M=109+7M=109+7. It can be shown that the answer can be expressed as an irreducible fraction p/qp/q, where pp and qq are integers and q≢0modMq≢0modM). Output the integer equal to p⋅q−1modMp⋅q−1modM. In other words, output such an integer xx that 0≤x<M0≤x<M and x⋅q≡pmodMx⋅q≡pmodM).InputThe first line of the input contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105)  — the number of officers in Byteland's Army.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤1091≤pi≤109).The third line contains a single integer qq (1≤q≤3⋅1051≤q≤3⋅105)  — the number of updates.Each of the next qq lines contains two integers ii and xx (1≤i≤n1≤i≤n, 1≤x≤1091≤x≤109), indicating that pipi is updated to xx .OutputIn the first line output the initial strength of the army.In ii-th of the next qq lines, output the strength of the army after ii-th update.ExamplesInputCopy2
1 2
2
1 2
2 1
OutputCopy500000004
1
500000004
InputCopy4
1 2 3 4
4
1 5
2 5
3 5
4 5
OutputCopy625000011
13
62500020
375000027
62500027
NoteIn first testcase; initially; there are four possible battalions   {} Strength = 00  {11} Strength = 00  {22} Strength = 00  {1,21,2} Strength = 22  So strength of army is 0+0+0+240+0+0+24 = 1212After changing p1p1 to 22, strength of battallion {1,21,2} changes to 44, so strength of army becomes 11.After changing p2p2 to 11, strength of battalion {1,21,2} again becomes 22, so strength of army becomes 1212.

#include<map>

#include<ctime>

#include<cmath>

#include<queue>

#include<bitset>

#include<cstdio>

#include<vector>

#include<random>

#include<cstdlib>

#include<cstring>

#include<iostream>

#include<algorithm>

#define ll long long

using namespace std;

#define I inline ll

#define her1 20090115

#define IV inline void

#define cht 1000000007

#define ld long double

#define Aestas16 392699

#define ull unsigned long long

#define mem(x,val)memset(x,val,sizeof x)

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

#define E(i,o)for(register int i=first[o];i;i=e[i].nxt)

#define F(i,j,n)for(register int i=j;i<=n;i++)

#define DL(i,j,n)for(register ll i=j;i>=n;i--)

#define EL(i,o)for(register ll i=first[o];i;i=e[i].nxt)

#define FL(i,j,n)for(register ll i=j;i<=n;i++)

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

//#define E(i,o)for(int i=first[o];i;i=e[i].nxt)

//#define F(i,j,n)for(int i=j;i<=n;i++)

//#define DL(i,j,n)for(ll i=j;i>=n;i--)

//#define EL(i,o)for(ll i=first[o];i;i=e[i].nxt)

//#define FL(i,j,n)for(ll i=j;i<=n;i++)

ll read(){

	ll ans=0,f=1;

	char c=getchar();

	while(c<'0'||c>'9'){

		if(c=='-')f=-1;

		c=getchar();

	}

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

	return ans*f;

}

#define ls (o<<1)

#define rs (o<<1|1)

mt19937 rnd(her1);

const int N = 6e5+5;

const int maxn = 1e6+5;

struct tree{ll l,r,tot,val,val1,val2;}t[N*4];

struct item{ll val,*s;}b[maxn];ll cnt,tot,pw[N],ip[N],n,q,a[N],p[N],x[N];

IV build(ll o,ll l,ll r){

	t[o].l=l;t[o].r=r;t[o].tot=t[o].val=t[o].val1=t[o].val2=0;

	if(l==r)return;ll mid=l+r>>1;build(ls,l,mid);build(rs,mid+1,r);

}

IV pushup(ll o){

	t[o].tot=t[ls].tot+t[rs].tot;

	t[o].val1=(t[ls].val1+t[rs].val1*pw[t[ls].tot])%cht;

	t[o].val2=(t[ls].val2+t[rs].val2*ip[t[ls].tot])%cht;

	t[o].val=(t[ls].val+t[rs].val+t[ls].val1*t[rs].val2%cht*ip[t[ls].tot])%cht;

}

IV upd(ll o,ll p,ll ty){

	if(t[o].l==t[o].r){

		if(~ty){

			t[o].tot=1;t[o].val1=b[p].val;

			t[o].val2=b[p].val*ip[1]%cht;t[o].val=0;

		}

		else t[o].tot=t[o].val1=t[o].val2=t[o].val=0;return;

	}

	ll mid=t[o].l+t[o].r>>1;

	p<=mid?upd(ls,p,ty):upd(rs,p,ty);pushup(o);

}

int main(){

	n=read();F(i,1,n)b[++cnt].val=a[i]=read(),b[cnt].s=a+i;

	q=read();F(i,1,q)p[i]=read(),b[++cnt].val=x[i]=read(),b[cnt].s=x+i;

	sort(b+1,b+1+cnt,[](item u,item v){return u.val<v.val;});F(i,1,cnt)(*b[i].s)=++tot;

	pw[0]=1;F(i,1,n)pw[i]=pw[i-1]*2%cht;ip[ip[0]=1]=(cht+1)>>1;F(i,2,n)ip[i]=ip[i-1]*ip[1]%cht;

	build(1,1,tot);F(i,1,n)upd(1,a[i],1);printf("%lld\n",t[1].val);

	F(i,1,q)upd(1,a[p[i]],-1),a[p[i]]=x[i],upd(1,a[p[i]],1),printf("%lld\n",t[1].val);return 0;

}


F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.InputThe first line contains an integer nn (2≤n≤1052≤n≤105) — the number of elements in the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1051≤ai≤105) — the elements of the array aa.OutputPrint one integer, the maximum value of the least common multiple of two elements in the array aa.ExamplesInputCopy3
13 35 77
OutputCopy1001InputCopy6
1 2 4 8 16 32
OutputCopy32

#include <bits/stdc++.h>

using namespace std;

#define ll long long

#define fi first

#define se second

#define Pii pair <int, int>

int n, a[100005], cnt[100005];

vector <int> fac[100005];

bool vis[100005];

int prime[100005], len = 0, mu[100005];

int suc[100005];

ll ans = 0;

void MySolve() {

    memset(vis, true, sizeof(vis));

    vis[1] = false, mu[1] = 1;

    for (int i = 2; i <= 1e5; ++i) {

        if (vis[i]) prime[ ++len ] = i, mu[i] = -1;

        for (int j = 1; j <= len && i * prime[j] <= 1e5; ++j) {

            vis[ i * prime[j] ] = false;

            if (i % prime[j] == 0) {

                mu[ i * prime[j] ] = 0;

                break;

            }

            mu[ i * prime[j] ] = -mu[i];

        }

    }

    cin >> n;

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

        cin >> a[i];

        ++cnt[ a[i] ];

    }

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

        if (cnt[i] >= 2) {

            ans = max(ans, 1ll * i);

        }

    }

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

        int V = 1e5 / i;

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

            fac[j].clear();

            suc[j] = 0;

        }

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

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

                fac[k].push_back(j);

            }

        }

        int p = 1;

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

            for (auto d : fac[j]) {

                suc[d] += mu[d] * cnt[ i * j ];

            }

        }

        for (int j = V; j; --j) if (cnt[ i * j ]) {

            auto calc = [&] () {

                int sum = 0;

                for (auto d : fac[j]) {

                    sum += suc[d];

                }

                return sum;

            };

            while (p <= j && calc()) {

                for (auto d : fac[p]) {

                    suc[d] -= mu[d] * cnt[ i * p ];

                }

                ++p;

            }

            if (p > j) break;

            ans = max(ans, 1ll * i * (p - 1) * j);

        }

    }

    cout << ans << '\n';

}

int main() {

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

    int t = 1;

    while (t--) {

        MySolve();

    }

    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:

#include<bits/stdc++.h>

#define ll long long

#define fir first

#define sec second

#define pii pair<int,int>

using namespace std;

const int maxn=6;

const int inf=0x3f3f3f3f;

const int mod=998244353;

struct mint {

	int val;

	mint():val(0) {}

	mint(ll tval) {

		if(-mod<=tval&&tval<2*mod) {

			if(tval>=mod) {

				tval-=mod;

			}

			if(tval<0) {

				tval+=mod;

			}

		} else {

			tval%=mod;

			if(tval<0) {

				tval+=mod;

			}

		}

		val=tval;

	}

	mint& operator += (const mint &b) {

		val=val+b.val>=mod?val+b.val-mod:val+b.val;

		return *this;

	}

	mint& operator -= (const mint &b) {

		val=val-b.val<0?val-b.val+mod:val-b.val;

		return *this;

	}

	mint& operator *= (const mint &b) {

		val=1ll*val*b.val>=mod?1ll*val*b.val%mod:val*b.val;

		return *this;

	}

	mint& operator /= (const mint &b) {

		*this*=b.inv();

		return *this;

	}

	friend mint operator + (const mint &a,const mint &b) {

		mint ans=a;

		ans+=b;

		return ans;

	}

	friend mint operator - (const mint &a,const mint &b) {

		mint ans=a;

		ans-=b;

		return ans;

	}

	friend mint operator * (const mint &a,const mint &b) {

		mint ans=a;

		ans*=b;

		return ans;

	}

	friend mint operator / (const mint &a,const mint &b) {

		mint ans=a;

		ans/=b;

		return ans;

	}

	friend bool operator < (const mint &a,const mint &b) {

		return a.val<b.val;

	}

	friend bool operator == (const mint &a,const mint &b) {

		return a.val==b.val;

	}

	friend bool operator != (const mint &a,const mint &b) {

		return a.val!=b.val;

	}

	friend istream& operator >> (istream &is,mint &x) {

		ll val;

		cin>>val;

		x.val=val%mod;

		return is;

	}

	friend ostream& operator << (ostream &os,const mint &x) {

		os<<x.val;

		return os;

	}

	mint qpow(ll y) const {

		mint x=*this,ans=1;

		while(y) {

			if(y&1) {

				ans*=x;

			}

			x*=x;

			y>>=1;

		}

		return ans;

	}

	mint inv() const {

		// mod must be a prime

		return qpow(mod-2);

	}

	mint sqrt() {

		mint a=*this;

		auto check=[&](mint x) {

			return x.qpow((mod-1)/2)==1;

		};

		static mt19937 rnd(73385);

		mint b=rnd()%mod;

		while(check(b*b-a)) {

			b=rnd()%mod;

		}

		static mint val=b*b-a;

		struct Complex {

			mint real,imag;

			Complex(mint treal=0,mint timag=0):real(treal),imag(timag) {}

			Complex operator * (const Complex &rhs) {

				return {real*rhs.real+imag*rhs.imag*val,real*rhs.imag+imag*rhs.real};

			}

			Complex& operator *= (const Complex &rhs) {

				return *this=*this*rhs;

			}

		};

		auto qpow=[&](Complex x,int y) {

			Complex ans={1};

			while(y) {

				if(y&1) {

					ans*=x;

				}

				x*=x;

				y>>=1;

			}

			return ans;

		};

		mint ans=qpow({b,1},(mod+1)/2).real;

		return min(ans,mod-ans);

	}

};

int n,m;

int dx[maxn];

int dy[maxn];

bool vis[35][25][25][25][25][2][2];

mint f[35][25][25][25][25][2][2];

#define state p][x][nx][y][ny][fx][fy

mint dfs(int p,int x,int nx,int y,int ny,bool fx,bool fy) {

	if(vis[state]) {

		return f[state];

	}

	if(p==30) {

		return !x&&!nx&&!y&&!ny&&fx&&fy;

	}

	auto ck=[&](bool f,int x,int m) {

		return x!=m?x<m:f;

	};

	mint ans=0;

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

		auto trans=[&](int v) {

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

				if((s>>(i-1))&1) {

					if(dx[i]>=0) {

						x+=dx[i]*v;

					} else {

						nx-=dx[i]*v;

					}

					if(dy[i]>=0) {

						y+=dy[i]*v;

					} else {

						ny-=dy[i]*v;

					}

				}

			}//

		};

		trans(1);

		if((x&1)==(nx&1)&&(y&1)==(ny&1)) {

			ans+=dfs(p+1,x>>1,nx>>1,y>>1,ny>>1,ck(fx,(x&1),(m>>p)&1),ck(fy,(y&1),(m>>p)&1));

		}

		trans(-1);

	}

//	cerr<<p<<" "<<x<<" "<<nx<<" "<<y<<" "<<ny<<" "<<fx<<" "<<fy<<": "<<ans<<"\n";

	vis[state]=true;

	return f[state]=ans;

}

signed main() {//asd

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

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

	ios::sync_with_stdio(false);

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

	cin>>n>>m;

	m++;

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

		cin>>dx[i]>>dy[i];

	}

	cout<<dfs(0,0,0,0,0,0,0)-1<<"\n";

}


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

#ifdef local

#define _GLIBCXX_DEBUG 1

#endif

#pragma GCC optimize("Ofast", "unroll-loops")

#include <bits/stdc++.h>

using namespace std;

#define int int64_t

#define double long double

using pii = pair<int, int>;

template <typename T> using Prior = std::priority_queue<T>;

template <typename T> using prior = std::priority_queue<T, vector<T>, greater<T>>;

// #define X first

// #define Y second

#define eb emplace_back

#define ef emplace_front

#define ee emplace

#define pb pop_back

#define pf pop_front

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

#define RALL(x) rbegin(x), rend(x)

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

template <size_t D, typename T> struct Vec : vector<Vec<D-1, T>> {

    static_assert(D >= 1, "Vector dimension must be greater than zero!");

    template <typename... Args> Vec(int n = 0, Args... args) : vector<Vec<D-1, T>>(n, Vec<D-1, T>(args...)) {}

};

template <typename T> struct Vec<1, T> : vector<T> {

    Vec(int n = 0, const T& val = T()) : vector<T>(n, val) {}

};

#ifdef local

#define fastIO() void()

#define debug(...) \

    _color.eb("\u001b[31m"), \

    fprintf(stderr, "%sAt [%s], line %d: (%s) = ", _color.back().c_str(), __FUNCTION__, __LINE__, #__VA_ARGS__), \

    _do(__VA_ARGS__), _color.pop_back(), \

    fprintf(stderr, "%s", _color.back().c_str())

deque<string> _color{"\u001b[0m"};

template <typename T> concept is_string = is_same_v<T, string&> or is_same_v<T, const string&>;

template <typename T> concept is_iterable = requires (T _t) {begin(_t);};

template <typename T> inline void _print_err(T &&_t);

template <typename T> inline void _print_err(T &&_t) requires is_iterable<T> and (not is_string<T>);

template <size_t I = 0, typename ...U> inline typename enable_if<I == sizeof...(U), void>::type _print_err(const tuple<U...> &);

template <size_t I = 0, typename ...U> inline typename enable_if<I <  sizeof...(U), void>::type _print_err(const tuple<U...> &_t);

template <size_t I = 0, typename ...U> inline typename enable_if<I == sizeof...(U), void>::type _print_err(tuple<U...> &);

template <size_t I = 0, typename ...U> inline typename enable_if<I <  sizeof...(U), void>::type _print_err(tuple<U...> &_t);

template <typename T, typename U> ostream& operator << (ostream &os, const pair<T, U> &_tu);

inline void _do() {cerr << "\n";};

template <typename T> inline void _do(T &&_t) {_print_err(_t), cerr << "\n";}

template <typename T, typename ...U> inline void _do(T &&_t, U &&..._u) {_print_err(_t), cerr << ", ", _do(_u...);}

#else

#define fastIO() ios_base::sync_with_stdio(0), cin.tie(0)

#define debug(...) void()

#endif

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

inline int getRand(int L, int R) {

    if (L > R) swap(L, R);

    return (int)(rng() % ((uint64_t)R - L + 1) + L);

}

template <typename T, typename U> bool chmin(T &lhs, U rhs) {return lhs > rhs ? lhs = rhs, 1 : 0;}

template <typename T, typename U> bool chmax(T &lhs, U rhs) {return lhs < rhs ? lhs = rhs, 1 : 0;}

void solve() {

    int N, X, Y; cin >> N >> X >> Y;

    int min_place = min(max(X+Y-N, (int)0) + 1, N);

    int max_place = min({X-1, Y-1, N-X, N-Y}) + abs(X-Y) + min(X, Y);

    cout << min_place << " " << max_place << "\n";

}

int32_t main() {

    fastIO();

    int t = 1; cin >> t;

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

        // cout << "Case #" << _ << ": ";

        solve();

    }

    return 0;

}

/// below are Fast I/O and _print_err templates ///

/*

/// Fast I/O by FHVirus ///

/// https://fhvirus.github.io/blog/2020/fhvirus-io/ ///

#include <unistd.h>

const int S = 65536;

int OP = 0;

char OB[S];

inline char RC() {

    static char buf[S], *p = buf, *q = buf;

    return p == q and (q = (p = buf) + read(0, buf, S)) == buf ? -1 : *p++;

}

inline int RI() {

    static char c;

    int a;

    while (((c = RC()) < '0' or c > '9') and c != '-' and c != -1);

    if (c == '-') {

        a = 0;

        while ((c = RC()) >= '0' and c <= '9') a *= 10, a -= c ^ '0';

    }

    else {

        a = c ^ '0';

        while ((c = RC()) >= '0' and c <= '9') a *= 10, a += c ^ '0';

    }

    return a;

}

inline void WI(int n, char c = '\n') {

    static char buf[20], p;

    if (n == 0) OB[OP++] = '0';

    p = 0;

    if (n < 0) {

        OB[OP++] = '-';

        while (n) buf[p++] = '0' - (n % 10), n /= 10;

    }

    else {

        while (n) buf[p++] = '0' + (n % 10), n /= 10;

    }

    for (--p; p >= 0; --p) OB[OP++] = buf[p];

    OB[OP++] = c;

    if (OP > S-20) write(1, OB, OP), OP = 0;

}

/// Fast I/O by FHVirus ///

/// https://fhvirus.github.io/blog/2020/fhvirus-io/ ///

*/

#ifdef local

template <typename T> inline void _print_err(T &&_t) {cerr << _t;}

template <typename T> inline void _print_err(T &&_t) requires is_iterable<T> and (not is_string<T>) {

    string _tmp_color = _color.back();

    ++_tmp_color[3], _color.eb(_tmp_color);

    cerr << _color.back() << "[";

    for (bool _first = true; auto &_x : _t) {

        if (!_first) cerr << ", ";

        _print_err(_x), _first = false;

    }

    cerr << "]" << (_color.pb(), _color.back());

}

template <typename T, typename U> ostream& operator << (ostream &os, const pair<T, U> &_tu) {

    string _tmp_color = _color.back();

    ++_tmp_color[3], _color.eb(_tmp_color);

    cerr << _color.back() << "(";

    _print_err(_tu.first), cerr << ", ", _print_err(_tu.second);

    cerr << ")" << (_color.pb(), _color.back());

    return os;

}

template <size_t I = 0, typename ...U> inline typename enable_if<I == sizeof...(U), void>::type _print_err(const tuple<U...> &) {

    cerr << ")" << (_color.pb(), _color.back());

}

template <size_t I = 0, typename ...U> inline typename enable_if<I <  sizeof...(U), void>::type _print_err(const tuple<U...> &_t) {

    if (!I) {

        string _tmp_color = _color.back();

        ++_tmp_color[3], _color.eb(_tmp_color);

        cerr << _color.back();

    }

    cerr << (I ? ", " : "("), _print_err(get<I>(_t)), _print_err<I+1, U...>(_t);

}

template <size_t I = 0, typename ...U> inline typename enable_if<I == sizeof...(U), void>::type _print_err(tuple<U...> &) {

    cerr << ")" << (_color.pb(), _color.back());

}

template <size_t I = 0, typename ...U> inline typename enable_if<I <  sizeof...(U), void>::type _print_err(tuple<U...> &_t) {

    if (!I) {

        string _tmp_color = _color.back();

        ++_tmp_color[3], _color.eb(_tmp_color);

        cerr << _color.back();

    }

    cerr << (I ? ", " : "("), _print_err(get<I>(_t)), _print_err<I+1, U...>(_t);

}

#endif


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

// Judges with GCC >= 12 only needs Ofast

// #pragma GCC optimize("O3,no-stack-protector,fast-math,unroll-loops,tree-vectorize")

// MLE optimization

// #pragma GCC optimize("conserve-stack")

// Old judges

// #pragma GCC target("sse4.2,popcnt,lzcnt,abm,mmx,fma,bmi,bmi2")

// New judges. Test with assert(__builtin_cpu_supports("avx2"));

// #pragma GCC target("avx2,popcnt,lzcnt,abm,bmi,bmi2,fma,tune=native")

// Atcoder

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

#include<bits/stdc++.h>

using namespace std;

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

uniform_real_distribution<> pp(0.0,1.0);

#define ld long double

#define pii pair<int,int>

#define piii pair<int,pii>

#define fi first

#define se second

const int inf=1e9;

const int mod=998244353;

const int mod2=1e9+7;

const int maxn=55;

const int maxm=20005;

const int maxq=500005;

const int maxl=20;

const int maxa=1000005;

int power(int a,int n){

    int res=1;

    while(n){

        if(n&1) res=res*a%mod;

        a=a*a%mod;n>>=1;

    }

    return res;

}

struct node{

    int Max[3];

    node(){Max[0]=Max[1]=Max[2]=inf;}

    friend node operator+(node a,node b){

        node res;

        for(int i=0;i<3;i++) res.Max[i]=max(a.Max[i],b.Max[i]);

        return res;

    }

};

int n,m,k,a[maxn][maxm],pre[maxm],suf[maxm],dp[maxm],cur[maxm];

namespace Segtree{

    node tree[4*maxm];

    void build(int l,int r,int id){

        if(l==r){

            tree[id].Max[0]=dp[l];

            tree[id].Max[1]=dp[l]+suf[l+k];

            tree[id].Max[2]=dp[l]+pre[l-1];

            return;

        }

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

        build(l,mid,id<<1);build(mid+1,r,id<<1|1);

        tree[id]=tree[id<<1]+tree[id<<1|1];

    }

    int query(int l,int r,int id,int tl,int tr,int t){

        if(r<tl || tr<l) return -inf;

        if(tl<=l && r<=tr) return tree[id].Max[t];

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

        return max(query(l,mid,id<<1,tl,tr,t),query(mid+1,r,id<<1|1,tl,tr,t));

    }

}

void solve(){

    cin >> n >> m >> k;

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

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

    }

    for(int i=1;i<=k;i++) dp[1]+=a[1][i]+a[2][i];

    for(int i=2;i<=m-k+1;i++) dp[i]=dp[i-1]-a[1][i-1]-a[2][i-1]+a[1][i+k-1]+a[2][i+k-1];

    for(int i=1;i<=m;i++) cur[i]=cur[i-1]+a[2][i];

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

        for(int j=1;j<=m;j++){pre[j]=cur[j];cur[j]=cur[j-1]+a[i][j];}

        for(int j=m;j>=1;j--) suf[j]=suf[j+1]+a[i-1][j];

        Segtree::build(1,m-k+1,1);

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

            dp[j]=Segtree::query(1,m-k+1,1,max(1,j-k+1),j,1)-suf[j+k]+cur[j+k-1]-cur[j-1];

            //cout << dp[j] << ' ';

            dp[j]=max(dp[j],Segtree::query(1,m-k+1,1,j,min(j+k-1,m-k+1),2)-pre[j-1]+cur[j+k-1]-cur[j-1]);

            //cout << dp[j] << ' ';

            if(j>k) dp[j]=max(dp[j],Segtree::query(1,m-k+1,1,1,j-k,0)+pre[j+k-1]-pre[j-1]+cur[j+k-1]-cur[j-1]);

            //cout << dp[j] << ' ';

            if(j+k<=m-k+1) dp[j]=max(dp[j],Segtree::query(1,m-k+1,1,j+k,m-k+1,0)+pre[j+k-1]-pre[j-1]+cur[j+k-1]-cur[j-1]);

            //cout << dp[j] << ' ' << pre[j+k-1]-pre[j-1]+cur[j+k-1]-cur[j-1] << '\n';

        }

        //cout << '\n';

    }

    int ans=0;

    for(int i=1;i<=m-k+1;i++) ans=max(ans,dp[i]);

    cout << ans << '\n';

}

signed main(){

    ios_base::sync_with_stdio(false);

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

    int test=1;//cin >> test;

    while(test--) solve();

}


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

#include <bits/stdc++.h>

using namespace std;

int main()

{

    int t;

    cin>>t;

    while(t--){

        int n;

        cin>>n;

        cout<<1<<" "<<n-1<<endl;

    }

}


G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk.  The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2
1 4
4 3
3 5
3 6
5 2
OutputCopy2
1 2 1 1 2 InputCopy4 2
3 1
1 4
1 2
OutputCopy1
1 1 1 InputCopy10 2
10 3
1 2
1 3
1 4
2 5
2 6
2 7
3 8
3 9
OutputCopy3
1 1 2 3 2 3 1 3 1

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

typedef pair<int, int> pii;

typedef pair<ll, ll> pll;

typedef vector<int> vi;

#define fi first

#define se second

#define pp push_back

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

#define Ones(n) __builtin_popcount(n)

#define endl '\n'

#define fill(arrr,xx) memset(arrr,xx,sizeof arrr)

#define rep(aa, bb, cc) for(int aa = bb; aa < cc;aa++)

#define PI acos(-1)

//#define int long long

void Gamal() {

    ios_base::sync_with_stdio(false);

    cin.tie(nullptr);

    cout.tie(nullptr);

#ifdef Clion

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

#endif

}

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

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

const double EPS = 1e-9;

const ll N = 2e5 + 5, INF = INT_MAX, MOD = 1e9 + 7, OO = 0X3F3F3F3F3F3F3F3F, LOG = 25;

vector<pii>adj[N];

int deg[N],ans,color[N];

void dfs(int u,int par,int prv){

    int cur = 0;

    for(auto v:adj[u]){

        if(v.fi == par)continue;

        if(cur == prv){

            cur = (cur + 1)%ans;

        }

        color[v.se] = cur;

        dfs(v.fi,u,cur);

        cur = (cur + 1)%ans;

    }

}

void solve() {

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

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

        int u,v;cin >> u >> v;

        u--,v--;

        adj[u].emplace_back(v,i);

        adj[v].emplace_back(u,i);

        deg[u]++,deg[v]++;

    }

    sort(deg,deg + n);

    ans = deg[n - k - 1];

    dfs(0,0,-1);

    cout << ans << endl;

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

        cout << color[i] + 1<< ' ';

    }

}

signed main() {

    Gamal();

    int t = 1;

//    cin >> t;

    while (t--) {

        solve();

    }

}


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

// prod by mdolchik

#pragma GCC optimize("Ofast")

#include <bits/stdc++.h>

#include <ext/pb_ds/detail/standard_policies.hpp>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace std;

typedef long long ll;

typedef long double ld;

typedef unsigned long long ull;

typedef pair <ll, int> pli;

typedef pair <int, int> pii;

typedef pair <ll, ll> pll;

#define int ll

#define E '\n'

#define fi first

#define se second

#define ins insert

#define pb push_back

#define pob pop_back

#define pof pop_front

#define umap unordered_map

#define gp gp_hash_table

#define uset unordered_set

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

#define fbo find_by_order

#define ork order_of_key

mt19937 gen (time (0));

const int MAXI = INT_MAX / 2;

const ll LMAXI = LLONG_MAX / 2;

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

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

const ll MD = 1e9 + 7;

ll bp(ll a, int b) {

    ll st = 1;

    while(b > 0) {

        if (b & 1) {

            st *= a;

            st %= MD;

            --b;

        } else {

            a *= a;

            a %= MD;

            b >>= 1;

        }

    }

    return st;

}

using namespace __gnu_pbds;

template <typename T>

using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

const int N = 4e5 + 12;

int a[N], b[N];

int n;

int get(int L, int R) {

    if(L > R)

        return 0;

    int l = 1, r = 0;

    int kol = 0;

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

        while(l <= n && b[l] + b[i] < L)

            l++;

        while(r + 1 <= n && b[r+1] + b[i] <= R)

            r++;

        kol += r - l + 1 - (l <= i && i < r);

//        cout << i << ' ' << r << E;

    }

    return kol / 2;

}

int32_t main() {

    ios_base::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

#ifdef LOCAL

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

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

#else

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

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

#endif // LOCAL

    cin >> n;

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

        cin >> a[i];

    }

    int ans = 0;

    for(int st = 0; st <= 25; st++) {

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

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

//            cout << b[i] << ' ';

        }

        sort (b + 1, b + n + 1);

//        cout << E;

        int cnt = get((1 << st), (1 << (st + 1)) - 1);

        cnt += get((1 << (st + 1)) + (1 << st), (1 << (st + 2)) - 1);

        if(cnt % 2 == 1) {

//            cout << st << E;

            ans += (1 << st);

        }

    }

    cout << ans;

    return 0;

}


G. Cow and Exercisetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFarmer John is obsessed with making Bessie exercise more!Bessie is out grazing on the farm; which consists of nn fields connected by mm directed roads. Each road takes some time wiwi to cross. She is currently at field 11 and will return to her home at field nn at the end of the day.Farmer John has plans to increase the time it takes to cross certain roads. He can increase the time it takes to cross each road by a nonnegative amount, but the total increase cannot exceed xixi for the ii-th plan. Determine the maximum he can make the shortest path from 11 to nn for each of the qq independent plans.InputThe first line contains integers nn and mm (2≤n≤502≤n≤50, 1≤m≤n⋅(n−1)1≤m≤n⋅(n−1)) — the number of fields and number of roads, respectively.Each of the following mm lines contains 33 integers, uiui, vivi, and wiwi (1≤ui,vi≤n1≤ui,vi≤n, 1≤wi≤1061≤wi≤106), meaning there is an road from field uiui to field vivi that takes wiwi time to cross.It is guaranteed that there exists a way to get to field nn from field 11. It is guaranteed that the graph does not contain self-loops or parallel edges. It is possible to have a road from uu to vv and a road from vv to uu.The next line contains a single integer qq (1≤q≤1051≤q≤105), the number of plans.Each of the following qq lines contains a single integer xixi, the query (0≤xi≤1050≤xi≤105).OutputFor each query, output the maximum Farmer John can make the shortest path if the total increase does not exceed xixi.Your answer is considered correct if its absolute or relative error does not exceed 10−610−6.Formally, let your answer be aa, and the jury's answer be bb. Your answer is accepted if and only if |a−b|max(1,|b|)≤10−6|a−b|max(1,|b|)≤10−6.ExampleInputCopy3 3
1 2 2
2 3 2
1 3 3
5
0
1
2
3
4
OutputCopy3.0000000000
4.0000000000
4.5000000000
5.0000000000
5.5000000000

#include<bits/stdc++.h>
#define fi first
#define se second
using namespace std;
const int _=100,inf=1e9;
int S,T,n,m,Q,head[_],ne[_*_],to[_*_],w[_*_],c[_*_],tot=1,x;
int dis[_],vis[_],p[_];
vector<pair<int,int>>ans;
void add(int x,int y,int z,int a){
	ne[++tot]=head[x],head[x]=tot,to[tot]=y,w[tot]=z,c[tot]=a;
}
void ad(int x,int y,int z){
	add(x,y,1,z),add(y,x,0,-z);
}
bool bfs(){
	for(int i=1;i<=n;i++)dis[i]=inf,vis[i]=0;
	queue<int>q;q.push(S),vis[S]=1,dis[S]=0;
	while(q.size()){
		int u=q.front();q.pop(),vis[u]=0;
		for(int i=head[u];i;i=ne[i])
			if(w[i]&&dis[to[i]]>dis[u]+c[i]){
				dis[to[i]]=dis[u]+c[i],p[to[i]]=i;
				if(!vis[to[i]])vis[to[i]]=1,q.push(to[i]);
			}
	}
	return dis[T]!=inf;
}
void EK(){
	int flow=0,cost=0;
	while(bfs()){
		int f=inf;
		for(int i=T;i!=S;i=to[p[i]^1])f=min(f,w[p[i]]);
		flow+=f,cost+=dis[T]*f;
		for(int i=T;i!=S;i=to[p[i]^1])w[p[i]]-=f,w[p[i]^1]+=f;
		ans.push_back({flow,cost});
	}
}
int main(){
	scanf("%d%d",&n,&m);
	for(int i=1,y,z;i<=m;i++)
		scanf("%d%d%d",&x,&y,&z),ad(x,y,z);
	S=1,T=n;EK();
	scanf("%d",&Q);
	while(Q--){
		scanf("%d",&x);
		long double Min=inf;
		for(auto v:ans)Min=min(Min,(long double)(v.se+x)/v.fi);
		printf("%.10Lf\n",Min);
	}
	return 0;
}


C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold:  Every label is an integer between 00 and n−2n−2 inclusive.  All the written labels are distinct.  The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3
1 2
1 3
OutputCopy0
1
InputCopy6
1 2
1 3
2 4
2 5
5 6
OutputCopy0
3
2
4
1NoteThe tree from the second sample:

#include <bits/stdc++.h>

using namespace std;

const int N=1e5+10;

int a[N],b[N],d[N];

int main(){

    int n;

    cin>>n;

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

        cin>>a[i]>>b[i];

        d[a[i]]++;

        d[b[i]]++;

    }

    int x=0,y=3,m=0;

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

        if(d[i]>=3){

            m=i,y=d[i];

            break;

        }

    }

    if(!m) y=0;

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

        if(a[i]==m || b[i]==m) cout<<x++<<endl;

        else cout<<y++<<endl;

    }

    return 0;

}


E. Strange Functiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's define the function ff of multiset aa as the multiset of number of occurences of every number, that is present in aa.E.g., f({5,5,1,2,5,2,3,3,9,5})={1,1,2,2,4}f({5,5,1,2,5,2,3,3,9,5})={1,1,2,2,4}.Let's define fk(a)fk(a), as applying ff to array aa kk times: fk(a)=f(fk−1(a)),f0(a)=afk(a)=f(fk−1(a)),f0(a)=a. E.g., f2({5,5,1,2,5,2,3,3,9,5})={1,2,2}f2({5,5,1,2,5,2,3,3,9,5})={1,2,2}.You are given integers n,kn,k and you are asked how many different values the function fk(a)fk(a) can have, where aa is arbitrary non-empty array with numbers of size no more than nn. Print the answer modulo 998244353998244353.InputThe first and only line of input consists of two integers n,kn,k (1≤n,k≤20201≤n,k≤2020).OutputPrint one number — the number of different values of function fk(a)fk(a) on all possible non-empty arrays with no more than nn elements modulo 998244353998244353.ExamplesInputCopy3 1
OutputCopy6
InputCopy5 6
OutputCopy1
InputCopy10 1
OutputCopy138
InputCopy10 2
OutputCopy33

#include<bits/stdc++.h>

#define pb emplace_back

typedef long long LL;

typedef unsigned long long ULL;

typedef std::pair<int,int> PII;

using std::vector;

const int N=2030,mod=998244353;

inline int read()

{

	int x=0,y=1;char ch=getchar();

	while(ch<'0'||ch>'9') {if(ch=='-') y=-1;ch=getchar();}

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

	return x*y;

}

int n,K,ans;

inline int M(int A)

{

	return (A>=mod)?A-mod:A;

}

namespace sub1{

	// 不超过 n 的所有划分数方案。

	//  dp[i]：i 的划分方案数，需要钦定从小到大，放入一个数。

	//  dp[i]+=dp[i-k];

	//  dp[i]+=dp[i-k];

	int dp[N];

	signed main()

	{

		dp[0]=1;

		for(int i=1;i<=n;i++) for(int j=i;j<=n;j++) dp[j]=M(dp[j]+dp[j-i]);

		for(int i=1;i<=n;i++) ans=M(ans+dp[i]);

		printf("%d\n",ans);

		return 0;

	}

}

namespace sub2{

	// f(f(S))：c[i] 个 i, 和小等于 n，c单调不增，方案数。

	// 单调不增 -> c[i-1]-c[i]>=0 -> 差分

	// dp[i]=

	int dp[N];

	inline int S(int l,int r)

	{

		return (1ll*(l+r)*(r-l+1)/2)%mod;

	}

	signed main()

	{

		dp[0]=1;

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

		{

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

			{

				dp[j]=M(dp[j]+dp[j-ns]);

			}

		}

		for(int i=1;i<=n;i++) ans=M(ans+dp[i]);

		printf("%d\n",ans);

		return 0;

	}

}

namespace sub3{

	int cnt[N];

	inline bool check(int nn)

	{

		int nw,sum=0;

		vector<int> a,b;a.clear(),b.clear();

		for(int i=1;i<=nn;i++) a.pb(cnt[i]);

		for(int i=1,nw;i<K;i++)

		{

			b.clear();

			std::reverse(a.begin(),a.end()),nw=sum=0;

			for(int sz:a)

			{

				++nw;

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

				{

					b.pb(nw);

					sum+=nw;

				}

			}

			std::swap(a,b);

			if(sum>n) return 0;

		}

		return 1;

	}

	int dfs(int step,int pre,int ns)

	{

		if(step&&!check(step)) return 0;

		ans++;

		for(int i=pre;i<=n-ns;i++)

		{

			cnt[step+1]=i;

			if(!dfs(step+1,i,ns+i)) return 1;

		}

		return 1;

	}

	signed main()

	{

		dfs(0,1,0),printf("%d\n",ans-1);

		return 0;

	}

}

signed main()

{

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

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

	n=read(),K=read();

	if(K==1) sub1::main();

	else if(K==2) sub2::main();

	else sub3::main();

	return 0;

}


// prod by mdolchik

#pragma GCC optimize("Ofast")

#include <bits/stdc++.h>

#include <ext/pb_ds/detail/standard_policies.hpp>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace std;

typedef long long ll;

typedef long double ld;

typedef unsigned long long ull;

typedef pair <ll, int> pli;

typedef pair <int, int> pii;

typedef pair <ll, ll> pll;

#define int ll

#define E '\n'

#define fi first

#define se second

#define ins insert

#define pb push_back

#define pob pop_back

#define pof pop_front

#define umap unordered_map

#define gp gp_hash_table

#define uset unordered_set

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

#define fbo find_by_order

#define ork order_of_key

mt19937 gen (time (0));

const int MAXI = INT_MAX / 2;

const ll LMAXI = LLONG_MAX / 2;

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

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

const ll MD = 1e9 + 7;

ll bp(ll a, int b) {

    ll st = 1;

    while(b > 0) {

        if (b & 1) {

            st *= a;

            st %= MD;

            --b;

        } else {

            a *= a;

            a %= MD;

            b >>= 1;

        }

    }

    return st;

}

using namespace __gnu_pbds;

template <typename T>

using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

const int N = 4e5 + 12;

int a[N], b[N];

int n;

int get(int L, int R) {

    if(L > R)

        return 0;

    int l = 1, r = 1;

    int kol = 0;

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

        while(l <= n && b[l] + b[i] < L)

            l++;

        while(r <= n && b[r] + b[i] <= R)

            r++;

        kol += r - l - (l <= i && i < r);

//        cout << i << ' ' << r << E;

    }

    return kol / 2;

}

int32_t main() {

    ios_base::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

#ifdef LOCAL

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

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

#else

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

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

#endif // LOCAL

    cin >> n;

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

        cin >> a[i];

    }

    int ans = 0;

    for(int st = 0; st <= 25; st++) {

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

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

//            cout << b[i] << ' ';

        }

        sort (b + 1, b + n + 1);

//        cout << E;

        int cnt = get((1 << st), (1 << (st + 1)) - 1);

        cnt += get((1 << (st + 1)) + (1 << st), (1 << (st + 2)) - 1);

        if(cnt % 2 == 1) {

//            cout << st << E;

            ans += (1 << st);

        }

    }

    cout << ans;

    return 0;

}


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

#include<cstdio>

#include<vector>

#include<algorithm>

#include<cstdlib>

#include<utility>

#include<queue>

#include<stack>

#include<map>

struct edge{int x,y,d;edge(int x=0,int y=0,int d=0){this->x=x,this->y=y,this->d=d;}};

struct tree

{

	std::vector<int> a[200005];

	int n,rt,dep[200005],fa[200005],sz[200005],son[200005],top[200005],g[200005],cnt;

	static int id[200005];

	void add(int x,int y)

	{

//		printf("Edge %d %d\n",x,y);

		a[x].push_back(y);

		a[y].push_back(x);

	}

	void dfs1(int v,int d)

	{

		sz[v]=1;dep[v]=d;son[v]=0;

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

		{

			int u=a[v][i];

			if (u==fa[v]) continue;

			fa[u]=v;

			dfs1(u,d+1);

			sz[v]=sz[v]+sz[u];

			if (sz[son[v]]<sz[u]) son[v]=u;

		}

	}

	void dfs2(int v,int k)

	{

		id[v]=++cnt;top[v]=k;

		if (son[v]) dfs2(son[v],k);

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

		{

			int u=a[v][i];

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

			dfs2(u,u);

		}

	}

	void pre(int nn,int x=1)

	{

		rt=x;

		n=nn;cnt=0;

		fa[rt]=0;

		dfs1(rt,1);

		dfs2(rt,rt);

	}

	int lca(int x,int y)

	{

		while (top[x]!=top[y])

		{

			if (dep[top[x]]<dep[top[y]]) std::swap(x,y);

			x=fa[top[x]];

		}

		if (dep[x]<dep[y]) std::swap(x,y);

		return y;

	}

	static int cmp(int x,int y)

	{

		return id[x]<id[y];

	}

	std::vector<edge> solve(std::vector<int> s)

	{

#define rt 1

		std::sort(s.begin(),s.end(),cmp);

		std::vector<int> p;

		std::stack<int> st;

		std::vector<edge> e;

		st.push(rt);p.push_back(rt);

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

		{

			int x=s[i],d=lca(st.top(),x);

			if (x==rt) continue;

			if (st.top()==d){st.push(x),p.push_back(x),g[x]=d;continue;}

			while (!st.empty())

			{

				int k=st.top();st.pop();

				if (st.empty()){st.push(k);st.push(x);p.push_back(x);break;}

				if (dep[st.top()]<=dep[d])

				{

					if (st.top()==d){st.push(x),p.push_back(x),g[x]=d;break;}

					g[k]=d;

					g[d]=st.top(),st.push(d);p.push_back(d);

					g[x]=d,st.push(x),p.push_back(x);

					break;

				}

			}

		}

		for (int i=0;i<(int)p.size();i++) if (p[i]!=rt) e.push_back(edge(p[i],g[p[i]],dep[p[i]]-dep[g[p[i]]]));

		for (int i=0;i<(int)p.size();i++) g[p[i]]=0;

//		puts("qwq");

//		for (int i=1;i<=n;i++) printf("%d ",g[i]);puts("");

		return e;

#undef rt

	}

};

int tree::id[200005];

struct graph

{

	struct edge

	{

		int to,w;

		edge(int to=0,int w=0){this->to=to,this->w=w;}

	};

	struct node

	{

		int t,c,d,s;

		node(int t=0,int c=0,int d=0,int s=0){this->t=t,this->c=c,this->d=d,this->s=s;}

		int operator >(node x)

		{

			if (t!=x.t) return t>x.t;

			if (c!=x.c) return c>x.c;

			return s>x.s;

		}

		int operator <(node x)

		{

			if (t!=x.t) return t<x.t;

			if (c!=x.c) return c<x.c;

			return s<x.s;

		}

		node operator -()

		{

			node ret=*this;

			ret.t=-ret.t;

			return ret;

		}

		node operator +(int w)

		{

			node ret=*this;

			ret.d=ret.d+w;

			ret.t=(ret.d-1)/ret.s+1;

			return ret;

		}

	};

	int n,vis[200005];

	node dis[200005];

	std::vector<edge> a[200005];

	struct cmp

	{

		int operator()(std::pair<node,int> x,std::pair<node,int> y){return x.first>y.first;}

	};

	std::priority_queue< std::pair<node,int>,std::vector< std::pair<node,int> >,cmp > pq;

	void add(int x,int y,int s){a[x].push_back(edge(y,s));a[y].push_back(edge(x,s));}

	void make(int x,int c,int s){/*printf("qwq %d %d %d\n",x,c,s);*/dis[x]=node(0,c,0,s);pq.push(std::make_pair(dis[x],x));}

	void dijkstra()

	{

//		puts("Start Point Distance");

//		for (int i=1;i<=n;i++) printf("%d(%d)[%d] ",dis[i].t,dis[i].c,dis[i].d);puts("");

		while (!pq.empty())

		{

			int v=pq.top().second;pq.pop();

			if (vis[v]) continue;vis[v]=1;

//			printf("v = %d\n",v);

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

			{

				int u=a[v][i].to,w=a[v][i].w;

//				printf("%d -> %d(w %d)[%d]\n",v,u,w,dis[v].t);

				if (dis[v]+w<dis[u]) dis[u]=dis[v]+w,pq.push(std::make_pair(dis[u],u));

			}

		}

		while (!pq.empty()) pq.pop();

//		puts("Distance");

//		for (int i=1;i<=n;i++) printf("%d(%d)[%d] ",dis[i].t,dis[i].c,dis[i].d);puts("");

	}

	void clear(int s)

	{

//		printf("Clear %d\n",s);

		dis[s]=node(1000000000,-1,-1,-1);

		vis[s]=0;

		a[s].clear();

	}

	void pre(int n)

	{

		this->n=n;

		for (int i=1;i<=n;i++) dis[i]=node(1000000000,-1,-1,-1);

	}

};

//graph::node;

graph g;

tree t;

int n,q,pt[200005],p[200005],d[200005];

std::map<int,int> mp;

int main()

{

	scanf("%d",&n);

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

	{

		int x,y;

		scanf("%d%d",&x,&y);

		t.add(x,y);

	}

	t.pre(n);

	g.pre(n);

	scanf("%d",&q);

	while (q--)

	{

		std::vector<int> vec,used;

		int m,s;

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

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

		{

			scanf("%d%d",&p[i],&d[i]);

			if (!mp[p[i]]) mp[p[i]]=1,vec.push_back(p[i]);

		}

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

		{

			scanf("%d",&pt[i]);

			if (!mp[pt[i]]) mp[pt[i]]=1,vec.push_back(pt[i]);

		}

		std::vector<edge> e=t.solve(vec);

		used.push_back(1);

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

		{

			int x=e[i].x,y=e[i].y,d=e[i].d;

//			printf("Edge %d %d %d\n",x,y,d);

			used.push_back(x);

			used.push_back(y);

			g.add(x,y,d);

		}

//		printf("pt %d\n",used.size());

//		for (int i=0;i<(int)used.size();i++) printf("%d ",used[i]);puts("");

		for (int i=1;i<=m;i++) g.make(p[i],i,d[i]);

		g.dijkstra();

//		puts("Success!");

//		printf("output:                         ");

		for (int i=1;i<=s;i++) printf("%d ",g.dis[pt[i]].c);puts("");

		for (int i=0;i<(int)used.size();i++) g.clear(used[i]);

		for (int i=1;i<=m;i++) p[i]=d[i]=0;

		for (int i=1;i<=s;i++) pt[i]=0;

		mp.clear();

	}

	return 0;

}


E. Cow and Treatstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful year of milk production; Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of nn units of grass, each with a sweetness sisi. Farmer John has mm cows, each with a favorite sweetness fifi and a hunger value hihi. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner:   The cows from the left and right side will take turns feeding in an order decided by Farmer John.  When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats hihi units.  The moment a cow eats hihi units, it will fall asleep there, preventing further cows from passing it from both directions.  If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset. Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them. Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo 109+7109+7)? The order in which FJ sends the cows does not matter as long as no cows get upset. InputThe first line contains two integers nn and mm (1≤n≤50001≤n≤5000, 1≤m≤50001≤m≤5000)  — the number of units of grass and the number of cows. The second line contains nn integers s1,s2,…,sns1,s2,…,sn (1≤si≤n1≤si≤n)  — the sweetness values of the grass.The ii-th of the following mm lines contains two integers fifi and hihi (1≤fi,hi≤n1≤fi,hi≤n)  — the favorite sweetness and hunger value of the ii-th cow. No two cows have the same hunger and favorite sweetness simultaneously.OutputOutput two integers  — the maximum number of sleeping cows that can result and the number of ways modulo 109+7109+7. ExamplesInputCopy5 2
1 1 1 1 1
1 2
1 3
OutputCopy2 2
InputCopy5 2
1 1 1 1 1
1 2
1 4
OutputCopy1 4
InputCopy3 2
2 3 2
3 1
2 1
OutputCopy2 4
InputCopy5 1
1 1 1 1 1
2 5
OutputCopy0 1
NoteIn the first example; FJ can line up the cows as follows to achieve 22 sleeping cows:   Cow 11 is lined up on the left side and cow 22 is lined up on the right side.  Cow 22 is lined up on the left side and cow 11 is lined up on the right side. In the second example, FJ can line up the cows as follows to achieve 11 sleeping cow:   Cow 11 is lined up on the left side.  Cow 22 is lined up on the left side.  Cow 11 is lined up on the right side.  Cow 22 is lined up on the right side. In the third example, FJ can line up the cows as follows to achieve 22 sleeping cows:   Cow 11 and 22 are lined up on the left side.  Cow 11 and 22 are lined up on the right side.  Cow 11 is lined up on the left side and cow 22 is lined up on the right side.  Cow 11 is lined up on the right side and cow 22 is lined up on the left side. In the fourth example, FJ cannot end up with any sleeping cows, so there will be no cows lined up on either side.

#pragma GCC optimaze(3)

#pragma GCC optimaze(2)

#pragma GCC optimaze("Ofast")

#pragma GCC optimaze("inline")

#pragma GCC optimaze("unroll-loops")

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

#include<bits/stdc++.h>

#define int long long

#define ll long long

#define N 5010

using namespace std;

const ll md=1e9+7;

int ss[N][N],s1[N],s2[N],a[N];

int n,m;

ll r1=1,r2=0;

inline void add(ll &x,ll y)

{

	x+=y;

	if (x>=md) x-=md;

}

signed main()

{

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

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

	{

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

		s2[a[i]]++;

	}

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

	{

		scanf("%lld%lld",&x,&y);

		ss[x][y]++;

	}

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

	{

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

		{

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

		}

	}

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

	{

		if (i)

		{

			s1[a[i]]++;

			s2[a[i]]--;

		}

		ll sum=1,num=0;

		int t1,t2;

		if (i)

		{

			t1=s1[a[i]],t2=s2[a[i]];

			t2=ss[a[i]][t2]-(t2>=t1);

			t1=ss[a[i]][t1]-ss[a[i]][t1-1];

			if (!t1) continue;

			if (t2)

			{

				sum=sum*t1*t2%md;

				num+=2;

			}

			else

			{

				sum=sum*t1%md;

				num++;

			}

		}

//		cout<<r1<<"   "<<r2<<endl;

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

		{

			if (j==a[i]) continue;

			t1=s1[j],t2=s2[j];

			t1=ss[j][t1],t2=ss[j][t2];

//			cout<<t1<<"   "<<t2<<endl;

			if (!t1&&!t2)

				continue;

			if (!t1||!t2)

			{

				sum=sum*(t1+t2)%md;

				num++;

			}

			else if (t1==1&&t2==1)

			{

				sum=sum*2%md;

				num++;

			}

			else

			{

				sum=sum*(t1*t2-min(t1,t2))%md;

				num+=2;

			}

		}

//		cout<<i<<"   "<<num<<"   "<<sum<<endl;

		if (num>r2)

			r2=num,r1=sum;

		else if (num==r2)

			add(r1,sum);

//		cout<<i<<"   "<<r1<<"   "<<r2<<endl;

	}

	if (!r2) r1=1;

	printf("%lld %lld",r2,r1);

	return 0;

}


B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold:  Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments.  The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees.  The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES

#include <bits/stdc++.h>

using namespace std;

using point_t=long long;  //全局数据类型，可修改为 long long 等

constexpr point_t eps=0;

constexpr long double PI=3.1415926535897932384l;

// 点与向量

template<typename T> struct point

{

    T x,y;

    // int id=-1;

    bool operator==(const point &a) const {return (abs(x-a.x)<=eps && abs(y-a.y)<=eps);}

    bool operator<(const point &a) const {if (abs(x-a.x)<=eps) return y<a.y-eps; return x<a.x-eps;}

    bool operator>(const point &a) const {return !(*this<a || *this==a);}

    point operator+(const point &a) const {return {x+a.x,y+a.y};}

    point operator-(const point &a) const {return {x-a.x,y-a.y};}

    point operator-() const {return {-x,-y};}

    point operator*(const T k) const {return {k*x,k*y};}

    point operator/(const T k) const {return {x/k,y/k};}

    T operator*(const point &a) const {return x*a.x+y*a.y;}  // 点积

    T operator^(const point &a) const {return x*a.y-y*a.x;}  // 叉积，注意优先级

    int toleft(const point &a) const {const auto t=(*this)^a; return (t>eps)-(t<-eps);}  // to-left 测试

    T len2() const {return (*this)*(*this);}  // 向量长度的平方

    T dis2(const point &a) const {return (a-(*this)).len2();}  // 两点距离的平方

    // 涉及浮点数

    long double len() const {return sqrtl(len2());}  // 向量长度

    long double dis(const point &a) const {return sqrtl(dis2(a));}  // 两点距离

    long double ang(const point &a) const {return acosl(max(-1.0l,min(1.0l,((*this)*a)/(len()*a.len()))));}  // 向量夹角

    point rot(const long double rad) const {return {x*cos(rad)-y*sin(rad),x*sin(rad)+y*cos(rad)};}  // 逆时针旋转（给定角度）

    point rot(const long double cosr,const long double sinr) const {return {x*cosr-y*sinr,x*sinr+y*cosr};}  // 逆时针旋转（给定角度的正弦与余弦）

};

using Point=point<point_t>;

// 极角排序

struct argcmp

{

    bool operator()(const Point &a,const Point &b) const

    {

        const auto quad=[](const Point &a)

        {

            if (a.y<-eps) return 1;

            if (a.y>eps) return 4;

            if (a.x<-eps) return 5;

            if (a.x>eps) return 3;

            return 2;

        };

        const int qa=quad(a),qb=quad(b);

        if (qa!=qb) return qa<qb;

        const auto t=a^b;

        // if (abs(t)<=eps) return a*a<b*b-eps;  // 不同长度的向量需要分开

        return t>eps;

    }

};

// 直线

template<typename T> struct line

{

    point<T> p,v;  // p 为直线上一点，v 为方向向量

    bool operator==(const line &a) const {return v.toleft(a.v)==0 && v.toleft(p-a.p)==0;}

    int toleft(const point<T> &a) const {return v.toleft(a-p);}  // to-left 测试

    bool operator<(const line &a) const  // 半平面交算法定义的排序

    {

        if (abs(v^a.v)<=eps && v*a.v>=-eps) return toleft(a.p)==-1;

        return argcmp()(v,a.v);

    }

    // 涉及浮点数

    point<T> inter(const line &a) const {return p+v*((a.v^(p-a.p))/(v^a.v));}  // 直线交点

    long double dis(const point<T> &a) const {return abs(v^(a-p))/v.len();}  // 点到直线距离

    point<T> proj(const point<T> &a) const {return p+v*((v*(a-p))/(v*v));}  // 点在直线上的投影

};

using Line=line<point_t>;

//线段

template<typename T> struct segment

{

    point<T> a,b;

    bool operator<(const segment &s) const {return make_pair(a,b)<make_pair(s.a,s.b);}

    // 判定性函数建议在整数域使用

    // 判断点是否在线段上

    // -1 点在线段端点 | 0 点不在线段上 | 1 点严格在线段上

    int is_on(const point<T> &p) const

    {

        if (p==a || p==b) return -1;

        return (p-a).toleft(p-b)==0 && (p-a)*(p-b)<-eps;

    }

    // 判断线段直线是否相交

    // -1 直线经过线段端点 | 0 线段和直线不相交 | 1 线段和直线严格相交

    int is_inter(const line<T> &l) const

    {

        if (l.toleft(a)==0 || l.toleft(b)==0) return -1;

        return l.toleft(a)!=l.toleft(b);

    }

    // 判断两线段是否相交

    // -1 在某一线段端点处相交 | 0 两线段不相交 | 1 两线段严格相交

    int is_inter(const segment<T> &s) const

    {

        if (is_on(s.a) || is_on(s.b) || s.is_on(a) || s.is_on(b)) return -1;

        const line<T> l{a,b-a},ls{s.a,s.b-s.a};

        return l.toleft(s.a)*l.toleft(s.b)==-1 && ls.toleft(a)*ls.toleft(b)==-1;

    }

    // 点到线段距离

    long double dis(const point<T> &p) const

    {

        if ((p-a)*(b-a)<-eps || (p-b)*(a-b)<-eps) return min(p.dis(a),p.dis(b));

        const line<T> l{a,b-a};

        return l.dis(p);

    }

    // 两线段间距离

    long double dis(const segment<T> &s) const

    {

        if (is_inter(s)) return 0;

        return min({dis(s.a),dis(s.b),s.dis(a),s.dis(b)});

    }

};

using Segment=segment<point_t>;

bool check(vector<Segment> &vec)

{

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

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

    if(vec[i].is_inter(vec[j])==0)return 1;

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

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

    if(i!=j)

    if((vec[i].a.y-vec[i].b.y)*(vec[j].a.x-vec[j].b.x)

    ==(vec[j].a.y-vec[j].b.y)*(vec[i].a.x-vec[i].b.x))

    return 1;

        if((vec[1].is_on(vec[0].a))

        &&vec[2].is_on(vec[0].b))

        {

            swap(vec[0],vec[2]);

            return 0;

        }

        if((vec[1].is_on(vec[0].b))

        &&vec[2].is_on(vec[0].a))

        {

            swap(vec[0],vec[2]);

            return 0;

        }

        if((vec[0].is_on(vec[1].a))

        &&vec[2].is_on(vec[1].b))

        {

        swap(vec[1],vec[2]);

        return 0;

        }

        if((vec[0].is_on(vec[1].b))

        &&vec[2].is_on(vec[1].a))

        {

        swap(vec[1],vec[2]);

        return 0;

        }

        if((vec[1].is_on(vec[2].a))

        &&vec[0].is_on(vec[2].b))

        return 0;

        if((vec[1].is_on(vec[2].b))

        &&vec[0].is_on(vec[2].a))return 0;

    return 1;

}

vector<Point> dot;

void print(Segment a)

{

    cout<<"Seg-->"<<a.a.x<<" "<<a.a.y<<" "<<a.b.x<<" "<<a.b.y<<endl;

}

bool check_vec(vector<Line> vec)

{

    if(vec[0].v.toleft(vec[1].v)==0)return true;

    if(vec[0].v.toleft(vec[2].v)==0)return true;

    if(vec[1].v.toleft(vec[2].v)==0)return true;

    return false;

}

bool check2(vector<Segment> vec)

{

    if(vec[0].a==vec[1].a)

    {

        dot.push_back(vec[0].a);dot.push_back(vec[0].b);

        dot.push_back(vec[1].a);dot.push_back(vec[1].b);

        return 0;

    }

    if(vec[0].b==vec[1].b)

    {

        dot.push_back(vec[0].b);dot.push_back(vec[0].a);

        dot.push_back(vec[1].b);dot.push_back(vec[1].a);

        return 0;

    }

    if(vec[1].b==vec[0].a)

    {dot.push_back(vec[1].b);dot.push_back(vec[1].a);

    dot.push_back(vec[0].a);dot.push_back(vec[0].b);

    return 0;}

    if(vec[0].b==vec[1].a)

    {dot.push_back(vec[1].a);dot.push_back(vec[1].b);

    dot.push_back(vec[0].b);dot.push_back(vec[0].a);

    return 0;}

    return 1;

}

bool ccheck(vector<Point> vec)

{

    Segment s1={vec[0],vec[1]};

    if(s1.is_on(vec[4])==0)swap(vec[4],vec[5]);

    point_t l1=vec[0].dis2(vec[4]),l2=vec[2].dis2(vec[5]),

    l3=vec[1].dis2(vec[4]),l4=vec[0].dis2(vec[4]),

    l6=vec[2].dis2(vec[5]),l7=vec[3].dis2(vec[5]),

    l5=vec[4].dis2(vec[5]);

    if(l1+l2-l5<0)return false;

    if(max(l4,l3)>(__int128)min(l4,l3)*16)return false;

    if(max(l6,l7)>(__int128)min(l6,l7)*16)return false;

    return true;

}

bool is_right_triangle(vector<Point> &vec)

{

    point_t a=vec[0].dis2(vec[1]),b=vec[2].dis2(vec[3]),

    c=vec[4].dis2(vec[5]);

    if(a+b==c||a+c==b||b+c==a)return true;

    return false;

}

void solve()

{

    dot.clear();

    vector<Point> vec(6);

    for(point_t i=0,x,y;i<6;++i)

    {

        scanf("%lld%lld",&x,&y);

        vec[i]={x,y};

    }

        vector<Line>vecl(3);

    vector<Segment>vecs(3);

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

    vecs[i]={vec[i*2],vec[(i*2)^1]};

    // for(int i=0;i<3;++i)

    if(check(vecs)){printf("NO\n");return ;}

    if(check2(vecs)){printf("NO\n");return ;}

       if(is_right_triangle(vec)) {printf("NO\n");return ;}

        dot.push_back(vecs[2].a);

            dot.push_back(vecs[2].b);

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

    vec[i*2]=vecs[i].a,vec[(i*2)^1]=vecs[i].b;

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

    {

        vecl[i]={vec[i*2],vec[(i*2)^1]-vec[i*2]};

    }

    // if(check_vec(vecl)){printf("NO\n");return ;}

    if(ccheck(dot)) {printf("YES\n");return ;}

    printf("NO\n");

}

int main()

{

    int T;scanf("%d",&T);

    while(T--)solve();

}


E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements:  The score of each problem should be a positive integer not exceeding 109109.  A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109.  The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3
OutputCopy4 5 9 13 18InputCopy8 0
OutputCopy10 11 12 13 14 15 16 17
InputCopy4 10
OutputCopy-1
NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution.   (1,2,3)(1,2,3)  (1,3,4)(1,3,4)  (2,4,5)(2,4,5)

#include <bits/stdc++.h>

using namespace std;

#ifdef LOCAL
#include "debug.h"
#else
#define dout(...) 0
#endif

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int n, m;
  cin >> n >> m;
  vector<int> a(n);
  int i = 0;
  while (m > 0) {
    if (i == n) {
      cout << -1 << '\n';
      return 0;
    }
    if (m > i / 2) {
      a[i] = i + 1;
      m -= i / 2;
    } else {
      a[i] = i + 1;
      int extra = i / 2 - m;
      a[i] += extra * 2;
      m = 0;
    }
    i += 1;
  }
  while (i < n) {
    a[i] = 1e9 - 5005 * (n - 1 - i);
    i += 1;
  }
  for (int i = 0; i < n; i++) {
    cout << a[i] << " \n"[i + 1 == n];
  }
  return 0;
}


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

    #include<bits/stdc++.h>

    using namespace std;

    int main()

    {

   	  long long int t;

   	  cin>>t;

   	  while(t--){

        	long long int n,m,a,b,i,mx=0,xd=0,yd=0,dl=0;

        	cin>>n;

        	long long int arrx[2001][2],arra[2001],arr[n],k;

        	string str;

        	memset(arra,0,sizeof arra);

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

        		cin>>a>>b;

        		m=a+b;

        		arr[i]=m;

        		arrx[m][0]=a;

        		arrx[m][1]=b;

        		arra[m]++;

        		if(arra[m]==2){

        			dl=1;

        		}

        	}

        	if(dl==1){

        		cout<<"NO"<<endl;

        	}

        	else{

        		dl=0;

        		sort(arr,arr+n);

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

        			m=arr[i];

        			a=arrx[m][0]-xd;

        			b=arrx[m][1]-yd;

        			if(a<0 || b<0){

        				dl=1;

        			}

        			for(k=0;k<a;k++){

        				str +='R';

        			}

        			for(k=0;k<b;k++){

        				str +='U';

        			}

        			xd=arrx[m][0];

        			yd=arrx[m][1];

        		}

        		if(dl==0){

        			cout<<"YES"<<endl;

        			cout<<str<<endl;

        		}

        		else{

        			cout<<"NO"<<endl;

        		}

        	}

        }

        return 0;

    }