F. Number of Componentstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix n×mn×m, initially filled with zeroes. We define ai,jai,j as the element in the ii-th row and the jj-th column of the matrix.Two cells of the matrix are connected if they share a side, and the elements in these cells are equal. Two cells of the matrix belong to the same connected component if there exists a sequence s1s1, s2s2, ..., sksk such that s1s1 is the first cell, sksk is the second cell, and for every i∈[1,k−1]i∈[1,k−1], sisi and si+1si+1 are connected.You are given qq queries of the form xixi yiyi cici (i∈[1,q]i∈[1,q]). For every such query, you have to do the following:  replace the element ax,yax,y with cc;  count the number of connected components in the matrix. There is one additional constraint: for every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.InputThe first line contains three integers nn, mm and qq (1≤n,m≤3001≤n,m≤300, 1≤q≤2⋅1061≤q≤2⋅106) — the number of rows, the number of columns and the number of queries, respectively.Then qq lines follow, each representing a query. The ii-th line contains three integers xixi, yiyi and cici (1≤xi≤n1≤xi≤n, 1≤yi≤m1≤yi≤m, 1≤ci≤max(1000,⌈2⋅106nm⌉)1≤ci≤max(1000,⌈2⋅106nm⌉)). For every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.OutputPrint qq integers, the ii-th of them should be equal to the number of components in the matrix after the first ii queries are performed.ExampleInputCopy3 2 10
2 1 1
1 2 1
2 2 1
1 1 2
3 1 2
1 2 2
2 2 2
2 1 2
3 2 4
2 1 5
OutputCopy2
4
3
3
4
4
4
2
2
4

#include<bits/stdc++.h>

using namespace std;

int const N=2000200,M=303,dx[]={-1,1,0,0},dy[]={0,0,-1,1};

struct node{int u,v,id;};vector<node> g1[N],g2[N];

int i,j,n,m,k,u,v,w,f[M*M],mp[M][M],Ans[N];

int read(){

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

	while (ch<'0'||ch>'9') ch=getchar();

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

	return x;

}

int idx(int x,int y){return (x-1)*m+y;}

int find(int x){return f[x]==x?x:f[x]=find(f[x]);}

int merg(int u,int v){

	u=find(u);v=find(v);

	if (u==v) return 0;

	f[u]=v;return 1;

}

void solve(int u,int v,int id,int type){

	if (mp[u][v]) return ;

	Ans[id]+=type;mp[u][v]=1;

	for (int U,V,k=0;k<4;k++)

		if (mp[U=u+dx[k]][V=v+dy[k]])

			Ans[id]-=type*merg(idx(u,v),idx(U,V));

}

void clear(){

	for (int i=1;i<=n*m;i++) f[i]=i;

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

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

			mp[i][j]=0;

}

int main(){

	n=read();m=read();k=read();

	for (i=1;i<=n;i++) for (j=1;j<=m;j++)

		g2[0].push_back({i,j,0});

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

		u=read();v=read();w=read();

		g1[mp[u][v]].push_back({u,v,i});

		g2[mp[u][v]=w].push_back({u,v,i});

	}

	for (i=1;i<=n;i++) for (j=1;j<=m;j++)

		g1[mp[i][j]].push_back({i,j,k+1}),mp[i][j]=0;

	for (i=0;i<=w;i++){ reverse(g1[i].begin(),g1[i].end());

		clear();for (j=0;j<g1[i].size();j++) solve(g1[i][j].u,g1[i][j].v,g1[i][j].id,-1);

		clear();for (j=0;j<g2[i].size();j++) solve(g2[i][j].u,g2[i][j].v,g2[i][j].id,1);

	}

	for (i=1;i<=k;i++) printf("%d\n",Ans[i]+=Ans[i-1]);

	return 0;

}


F. Blocks and Sensorstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPolycarp plays a well-known computer game (we won't mention its name). Every object in this game consists of three-dimensional blocks — axis-aligned cubes of size 1×1×11×1×1. These blocks are unaffected by gravity, so they can float in the air without support. The blocks are placed in cells of size 1×1×11×1×1; each cell either contains exactly one block or is empty. Each cell is represented by its coordinates (x,y,z)(x,y,z) (the cell with these coordinates is a cube with opposite corners in (x,y,z)(x,y,z) and (x+1,y+1,z+1)(x+1,y+1,z+1)) and its contents ax,y,zax,y,z; if the cell is empty, then ax,y,z=0ax,y,z=0, otherwise ax,y,zax,y,z is equal to the type of the block placed in it (the types are integers from 11 to 2⋅1052⋅105).Polycarp has built a large structure consisting of blocks. This structure can be enclosed in an axis-aligned rectangular parallelepiped of size n×m×kn×m×k, containing all cells (x,y,z)(x,y,z) such that x∈[1,n]x∈[1,n], y∈[1,m]y∈[1,m], and z∈[1,k]z∈[1,k]. After that, Polycarp has installed 2nm+2nk+2mk2nm+2nk+2mk sensors around this parallelepiped. A sensor is a special block that sends a ray in some direction and shows the type of the first block that was hit by this ray (except for other sensors). The sensors installed by Polycarp are adjacent to the borders of the parallelepiped, and the rays sent by them are parallel to one of the coordinate axes and directed inside the parallelepiped. More formally, the sensors can be divided into 66 types:  there are mkmk sensors of the first type; each such sensor is installed in (0,y,z)(0,y,z), where y∈[1,m]y∈[1,m] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OxOx axis and has the same direction;  there are mkmk sensors of the second type; each such sensor is installed in (n+1,y,z)(n+1,y,z), where y∈[1,m]y∈[1,m] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OxOx axis and has the opposite direction;  there are nknk sensors of the third type; each such sensor is installed in (x,0,z)(x,0,z), where x∈[1,n]x∈[1,n] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OyOy axis and has the same direction;  there are nknk sensors of the fourth type; each such sensor is installed in (x,m+1,z)(x,m+1,z), where x∈[1,n]x∈[1,n] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OyOy axis and has the opposite direction;  there are nmnm sensors of the fifth type; each such sensor is installed in (x,y,0)(x,y,0), where x∈[1,n]x∈[1,n] and y∈[1,m]y∈[1,m], and it sends a ray that is parallel to the OzOz axis and has the same direction;  finally, there are nmnm sensors of the sixth type; each such sensor is installed in (x,y,k+1)(x,y,k+1), where x∈[1,n]x∈[1,n] and y∈[1,m]y∈[1,m], and it sends a ray that is parallel to the OzOz axis and has the opposite direction. Polycarp has invited his friend Monocarp to play with him. Of course, as soon as Monocarp saw a large parallelepiped bounded by sensor blocks, he began to wonder what was inside of it. Polycarp didn't want to tell Monocarp the exact shape of the figure, so he provided Monocarp with the data from all sensors and told him to try guessing the contents of the parallelepiped by himself.After some hours of thinking, Monocarp has no clue about what's inside the sensor-bounded space. But he does not want to give up, so he decided to ask for help. Can you write a program that will analyze the sensor data and construct any figure that is consistent with it?InputThe first line contains three integers nn, mm and kk (1≤n,m,k≤2⋅1051≤n,m,k≤2⋅105, nmk≤2⋅105nmk≤2⋅105) — the dimensions of the parallelepiped.Then the sensor data follows. For each sensor, its data is either 00, if the ray emitted from it reaches the opposite sensor (there are no blocks in between), or an integer from 11 to 2⋅1052⋅105 denoting the type of the first block hit by the ray. The data is divided into 66 sections (one for each type of sensors), each consecutive pair of sections is separated by a blank line, and the first section is separated by a blank line from the first line of the input.The first section consists of mm lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (0,i,j)(0,i,j).The second section consists of mm lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (n+1,i,j)(n+1,i,j).The third section consists of nn lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,0,j)(i,0,j).The fourth section consists of nn lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,m+1,j)(i,m+1,j).The fifth section consists of nn lines containing mm integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,j,0)(i,j,0).Finally, the sixth section consists of nn lines containing mm integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,j,k+1)(i,j,k+1).OutputIf the information from the input is inconsistent, print one integer −1−1.Otherwise, print the figure inside the parallelepiped as follows. The output should consist of nmknmk integers: a1,1,1a1,1,1, a1,1,2a1,1,2, ..., a1,1,ka1,1,k, a1,2,1a1,2,1, ..., a1,2,ka1,2,k, ..., a1,m,ka1,m,k, a2,1,1a2,1,1, ..., an,m,kan,m,k, where ai,j,kai,j,k is the type of the block in (i,j,k)(i,j,k), or 00 if there is no block there. If there are multiple figures consistent with sensor data, describe any of them.For your convenience, the sample output is formatted as follows: there are nn separate sections for blocks having x=1x=1, x=2x=2, ..., x=nx=n; each section consists of mm lines containing kk integers each. Note that this type of output is acceptable, but you may print the integers with any other formatting instead (even all integers on the same line), only their order matters.ExamplesInputCopy4 3 2

1 4
3 2
6 5

1 4
3 2
6 7

1 4
1 4
0 0
0 7

6 5
6 5
0 0
0 7

1 3 6
1 3 6
0 0 0
0 0 7

4 3 5
4 2 5
0 0 0
0 0 7
OutputCopy1 4
3 0
6 5

1 4
3 2
6 5

0 0
0 0
0 0

0 0
0 0
0 7
InputCopy1 1 1

0

0

0

0

0

0
OutputCopy0
InputCopy1 1 1

0

0

1337

0

0

0
OutputCopy-1
InputCopy1 1 1

1337

1337

1337

1337

1337

1337
OutputCopy1337

#include<bits/stdc++.h>

using namespace std;
const int N=2e5+5;
const int dx[]={1,-1,0,0,0,0},dy[]={0,0,1,-1,0,0},dz[]={0,0,0,0,1,-1};
int n,m,k,col[N];vector<int>d[N];
inline int id(int x,int y,int z){return (x-1)*m*k+(y-1)*k+z;}
void ins(int x,int y,int z,int c,int tp)
{
if(x<1||x>n||y<1||y>m||z<1||z>k)
{
if(c)puts("-1"),exit(0);
return;
}
int now=id(x,y,z);
if(col[now]==-1||col[now]==c)
{
col[now]=c;d[now].push_back(tp);
if(!c)ins(x+dx[tp],y+dy[tp],z+dz[tp],c,tp);
return;
}
if(col[now]>0)
while(!d[now].empty())
{
int o=d[now].back();
d[now].pop_back();
ins(x+dx[o],y+dy[o],z+dz[o],col[now],o);
}
col[now]=0;
ins(x+dx[tp],y+dy[tp],z+dz[tp],c,tp);
}
int main()
{
memset(col,-1,sizeof col);
scanf("%d%d%d",&n,&m,&k);
for(int i=1,t;i<=m;++i)for(int j=1;j<=k;++j)scanf("%d",&t),ins(1,i,j,t,0);
for(int i=1,t;i<=m;++i)for(int j=1;j<=k;++j)scanf("%d",&t),ins(n,i,j,t,1);
for(int i=1,t;i<=n;++i)for(int j=1;j<=k;++j)scanf("%d",&t),ins(i,1,j,t,2);
for(int i=1,t;i<=n;++i)for(int j=1;j<=k;++j)scanf("%d",&t),ins(i,m,j,t,3);
for(int i=1,t;i<=n;++i)for(int j=1;j<=m;++j)scanf("%d",&t),ins(i,j,1,t,4);
for(int i=1,t;i<=n;++i)for(int j=1;j<=m;++j)scanf("%d",&t),ins(i,j,k,t,5);
for(int i=1;i<=n*m*k;++i)printf("%d ",col[i]<0?0:col[i]);
return 0;
}


E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3
3 1 2
7 1 4
OutputCopy4
InputCopy4
2 4 1 3
5 9 8 3
OutputCopy3
InputCopy6
3 5 1 6 2 4
9 1 9 9 1 9
OutputCopy2

// LUOGU_RID: 100021307
#include<iostream>

#include<cstdio>

using namespace std;

namespace fastio {

inline char get_char() {

	static char buf[1000001], *p1 = buf, *p2 = buf;

	return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1000000, stdin), p1 == p2) ? EOF : *p1++;

}

inline int read() {

	char ch;

	int x = 0, ff = 1;

	do {

		ch = get_char();

	} while ((ch < '0' || '9' < ch) && ch != '-');

	if (ch == '-')ff = -1, ch = get_char();

	while ('0' <= ch && ch <= '9') {

		x = 10 * x + ch - '0';

		ch = get_char();

	}

	return x * ff;

}

inline void read(int &x) {

	x = 0;

	char ch;

	int ff = 1;

	do {

		ch = get_char();

	} while ((ch < '0' || '9' < ch) && ch != '-');

	if (ch == '-')ff = -1, ch = get_char();

	while ('0' <= ch && ch <= '9') {

		x = 10 * x + ch - '0';

		ch = get_char();

	}

	x *= ff;

}

inline write(int x) {

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

	putchar(x % 10 + 48);

}

}

using namespace fastio;

namespace lyx {

const int N = 2e5 + 5;

int n;

int p[N], a[N];

struct tree {

	long long min, max, tag;

} t[N << 2];

void update(int p) {

	t[p].min = min(t[p << 1].min, t[p << 1 | 1].min);

	t[p].max = max(t[p << 1].max, t[p << 1 | 1].max);

}

void pushdown(int p) {

	if (!t[p].tag) return;

	t[p << 1].min += t[p].tag;

	t[p << 1].max += t[p].tag;

	t[p << 1].tag += t[p].tag;

	t[p << 1 | 1].min += t[p].tag;

	t[p << 1 | 1].max += t[p].tag;

	t[p << 1 | 1].tag += t[p].tag;

	t[p].tag = 0;

}

void change(int p, int l, int r, int x, int y, int k) {

	if (x <= l && r <= y) {

		t[p].tag += k, t[p].min += k, t[p].max += k;

		return;

	}

	pushdown(p);

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

	if (x <= mid) change(p << 1, l, mid, x, y, k);

	if (y > mid) change(p << 1 | 1, mid + 1, r, x, y, k);

	update(p);

}

int main() {

	ios::sync_with_stdio(false);

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

	cin >> n;

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

		cin >> p[i];

	}

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

		cin >> a[i];

		change(1, 0, n, p[i], n, a[i]);

	}

	long long ans = 9e18;

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

		change(1, 0, n, p[i], n, -a[i]);

		change(1, 0, n, 0, p[i] - 1, a[i]);

		ans = min(ans, t[1].min);

	}

	cout << ans << '\n';

	return 0;

}

}

int main() {

	return lyx::main();

}


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

/*

Date:   16 February 2023

Problem Link:   https://codeforces.com/problemset/problem/1285/B

Author: Tareq Munawer Taj

CSE, Rajshahi University

*/

#include <bits/stdc++.h>

#define ll long long

#define ull unsigned long long

#define ld long double

#define pb push_back

#define mp make_pair

#define pii pair<int, int>

#define pll pair<ll, ll>

#define vii vector<int>

#define vll vector<ll>

#define vull vector<ull>

#define vss vector<string>

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

#define FORR(i, n, x) for (int i = n; i >= 0; i = i - x)

#define SORT(v) sort(v.begin(), v.end())

#define RSORT(v) sort(v.rbegin(), v.rend())

#define REVERSE(v) reverse(v.rbegin(), v.rend())

#define lowbound(name, val) lower_bound(name.begin(), name.end(), val) - name.begin()

#define uppbound(name, val) upper_bound(name.begin(), name.end(), val) - name.begin()

#define matrix(x) vector<vector<x>>

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

#define setdigit(n) fixed << setprecision(n)

#define MOD(a, b) (a % b + b) % b

#define lcm(a, b) ((a) * ((b) / __gcd(a, b)))

#define ff first

#define ss second

#define YES printf("YES\n")

#define NO printf("NO\n")

#define nl "\n"

#define PI (acos(-1.0))

#define mod 1000000007

#define INF (ll)1e17

#define N 100005

using namespace std;

ll maximum_sub_sum(int i, int j, vll &num)

{

    ll sub_sum = 0, max_sum = -INF;

    while (i < j)

    {

        if (sub_sum + num[i] <= 0)

            sub_sum = 0;

        else

            sub_sum += num[i];

        max_sum = max(max_sum, sub_sum);

        i++;

    }

    return max_sum;

}

void solve()

{

    int size;

    cin >> size;

    vll num(size);

    ll sum = 0;

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

    {

        cin >> num[i];

        sum += num[i];

    }

    ll max_sum = max(maximum_sub_sum(0, size - 1, num), maximum_sub_sum(1, size, num));

    if (sum > max_sum)

        cout

            << "YES" << nl;

    else

        cout << "NO" << nl;

}

int main()

{

    ios_base::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    int tc = 1;

    cin >> tc;

    while (tc--)

        solve();

    return 0;

}


D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters  — UU, DD, LL, RR or XX  — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote:   a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy).  or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103)  — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2
1 1 1 1
2 2 2 2
OutputCopyVALID
XL
RX
InputCopy3
-1 -1 -1 -1 -1 -1
-1 -1 2 2 -1 -1
-1 -1 -1 -1 -1 -1
OutputCopyVALID
RRD
UXD
ULLNoteFor the sample test 1 :The given grid in output is a valid one.   If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there.  If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1).  If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2).  If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below :   For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below :

#include <bits/stdc++.h>

using namespace std;

#define YES cout << "YES" << endl

#define NO cout << "NO" << endl

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

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

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

#define fs first

#define se second

#define Odd(_x) ((_x) & 1)

using i64 = long long;

using ll = long long;

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

const int inf = 1e9 + 10;

const ll mod = 1e9 + 7;

void solve() {

    int n;

    cin >> n;

    vector g(n, vector<array<int, 2>>(n));

    int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1};

    string DIR = "RDUL", invDIR = "LUDR";

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

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

            cin >> g[i][j][0] >> g[i][j][1];

        }

    }

    vector<string> ans(n, string(n, '#'));

    function<void(int, int)> dfs = [&](int x, int y) {

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

            int cx = x + dir[i][0], cy = y + dir[i][1];

            if (cx < 0 || cy < 0 || cx >= n | cy >= n) continue;

            if (ans[cx][cy] != '#' || g[cx][cy][0] != -1) continue;

            if (ans[x][y] == '#') {

                ans[x][y] = DIR[i];

            }

            ans[cx][cy] = invDIR[i];

            dfs(cx, cy);

        }

    };

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

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

            if (g[i][j][0] == -1 && ans[i][j] == '#') {

                dfs(i, j);

                if (ans[i][j] == '#') {

                    cout << "INVALID\n";

                    return ;

                }

            }

        }

    }

    function<void(int, int)> dfs2 = [&](int x, int y) {

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

            int cx = dir[i][0] + x, cy = dir[i][1] + y;

            if (cx < 0 || cy < 0 || cx >= n | cy >= n) continue;

            if (g[cx][cy] != g[x][y] || ans[cx][cy] != '#') continue;

            ans[cx][cy] = invDIR[i];

            dfs2(cx, cy);

        }

    };

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

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

            if (ans[i][j] == '#') {

                int x = g[i][j][0] - 1, y = g[i][j][1] - 1;

                if (g[x][y][0] != x + 1 || g[x][y][1] != y + 1 || ans[x][y] != '#') {

                    cout << "INVALID\n";

                    return ;

                }

                ans[x][y] = 'X';

                dfs2(x, y);

            }

        }

    }

    cout << "VALID\n";

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

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

    }

}

//#define MULTI_INPUT

int main() {

#ifndef ONLINE_JUDGE

    freopen(R"(D:\source files\source file2\input.txt)", "r", stdin);

    freopen(R"(D:\source files\source file2\output.txt)", "w", stdout);

#endif

    std::ios::sync_with_stdio(false);

    cin.tie(nullptr);

    cout << fixed << setprecision(20);

#ifdef MULTI_INPUT

    int T;

    cin >> T;

    while (T--) {

        solve();

    }

#else

    solve();

#endif

    return 0;

}


B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2
3
3 2 1
6
3 1 4 1 5 9
OutputCopy3
5
NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9].

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

int main()
{
    ll t;
    cin>>t;
    while(t--)
    {
        ll n;
        cin>>n;
        set<ll>st;
        for(ll i = 0; i < n; i++)
        {
            ll x;
            cin>>x;
            st.insert(x);
        }
        cout<<st.size()<<"\n";
    }

}


E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3
1 4 6
OutputCopy1InputCopy4
2 3 6 6
OutputCopy2InputCopy3
6 15 10
OutputCopy3InputCopy4
2 3 5 7
OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence.

#include <bits/stdc++.h>

using namespace std;

typedef pair<int,int> pi;

#define pb emplace_back

const int MN=8e4;

int N, at=170, ans = MN; bool pvis[1001], vis[MN]; pi dist[MN];

set<int> start; vector<int> prime, vals, adj[MN]; queue<pi> q;

unordered_map<int, int> ind; // (value, index it maps to)

void bfs(int r){ q.push({r,-1}); dist[r]={1,r};

	while(!q.empty()){ pi t = q.front(); int x=t.first, p=t.second; q.pop();

		for(int nx: adj[x]) if(nx!=p && nx>=r) if(adj[nx].size()>1) {

			if(dist[nx].second==dist[x].second) ans=min(ans,dist[x].first+dist[nx].first-1);

			else{ dist[nx]={dist[x].first + 1,r}; q.push({nx,x}); } } } }

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

    prime.reserve(170); prime.pb(0); prime.pb(1);

	for(int i=2;i<=1e3;i++) { if(pvis[i]) continue; prime.pb(i);

		for(int j=i*i;j<=1e3;j+=i) pvis[j]=1; }

	cin >> N; int x; for (int i=0; i<N; i++) { vals.clear(); cin >> x;

        for (int j=2; j<prime.size() && prime[j] * prime[j] <= x; j++) { int cnt = 0;

            while (x%prime[j] == 0) { x /= prime[j]; cnt++; }

            if (cnt%2 == 1) vals.pb(prime[j]); }

        if (vals.empty() && x == 1) { cout << 1 <<'\n'; return 0; }

        vals.pb(x); if (vals.size() == 1) vals.pb(1);

        for (int k: vals) if (ind.count(k) == 0)

			{ if (k > 1e3) ind[k] = at++;

			  else { int t=lower_bound(prime.begin(),prime.end(),k)-prime.begin();

				     ind[k]=t; start.insert(t); } }

		adj[ind[vals[0]]].pb(ind[vals[1]]);

        adj[ind[vals[1]]].pb(ind[vals[0]]);

    }

    for (int j: start) if(adj[j].size()>1) bfs(j);

    cout << (ans == MN ? -1 : ans) <<'\n';

}


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

import java.util.*;

public class Main

{

    public static void main(String[] args)

    {

        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();

        while(n-- > 0)

        {

            int no_of_stud = sc.nextInt();

            int highest_mar_poss = sc.nextInt();

            int[] arr = new int[no_of_stud];

            int sum = 0;

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

            {

                arr[i] = sc.nextInt();

                sum += arr[i];

            }

            if(sum >= highest_mar_poss)

            {

                System.out.println(highest_mar_poss);

            }

            else

            {

                System.out.println(sum);

            }

            //System.out.println(arr[no_of_stud - 1]);

        }

    }

}


A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000)  — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit).

import java.util.Scanner;

public class Main{

	private static Scanner in = new Scanner(System.in);

	public static void solve(){

		int n=in.nextInt();

		in.nextLine();

		String s=in.nextLine();

		int numOdd=0;

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

			if((s.charAt(i)-'0')%2==1)numOdd++;

		if(numOdd<=1)

			System.out.println(-1);

		else{

			int ii=0;

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

			if((s.charAt(i)-'0')%2==1){

				System.out.print(s.charAt(i));

				ii++;

				if(ii==2)break;

			}

			System.out.println();

		}

	}

	public static void main(String[] args){

		int t=in.nextInt();

		while(t>0){t--;solve();}

	}

}


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

 import java.util.*;

import java.io.*;

import java.io.DataInputStream;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.Scanner;

import java.util.StringTokenizer;

import java.math.BigInteger;

public final class Main{

    static class Reader {

        final private int BUFFER_SIZE = 1 << 16;

        private DataInputStream din;

        private byte[] buffer;

        private int bufferPointer, bytesRead;

        public Reader() {

            din = new DataInputStream(System.in);

            buffer = new byte[BUFFER_SIZE];

            bufferPointer = bytesRead = 0;

        }

        public Reader(String file_name) throws IOException {

            din = new DataInputStream(

                new FileInputStream(file_name));

            buffer = new byte[BUFFER_SIZE];

            bufferPointer = bytesRead = 0;

        }

        public String readLine() throws IOException {

            byte[] buf = new byte[64]; // line length

            int cnt = 0, c;

            while ((c = read()) != -1) {

                if (c == '\n') {

                    if (cnt != 0) {

                        break;

                    }

                    else {

                        continue;

                    }

                }

                buf[cnt++] = (byte)c;

            }

            return new String(buf, 0, cnt);

        }

        public int nextInt() throws IOException {

            int ret = 0;

            byte c = read();

            while (c <= ' ') {

                c = read();

            }

            boolean neg = (c == '-');

            if (neg)

                c = read();

            do {

                ret = ret * 10 + c - '0';

            } while ((c = read()) >= '0' && c <= '9');

            if (neg)

                return -ret;

            return ret;

        }

        public long nextLong() throws IOException {

            long ret = 0;

            byte c = read();

            while (c <= ' ')

                c = read();

            boolean neg = (c == '-');

            if (neg)

                c = read();

            do {

                ret = ret * 10 + c - '0';

            } while ((c = read()) >= '0' && c <= '9');

            if (neg)

                return -ret;

            return ret;

        }

        public double nextDouble() throws IOException {

            double ret = 0, div = 1;

            byte c = read();

            while (c <= ' ') c = read();

            boolean neg = (c == '-');

            if (neg) c = read();

            do {

                ret = ret * 10 + c - '0';

            } while ((c = read()) >= '0' && c <= '9');

            if (c == '.') {

                while ((c = read()) >= '0' && c <= '9') {

                    ret += (c - '0') / (div *= 10);

                }

            }

            if (neg) return -ret;

            return ret;

        }

        private void fillBuffer() throws IOException {

            bytesRead = din.read(buffer, bufferPointer = 0,

                                 BUFFER_SIZE);

            if (bytesRead == -1)

                buffer[0] = -1;

        }

        private byte read() throws IOException {

            if (bufferPointer == bytesRead)

                fillBuffer();

            return buffer[bufferPointer++];

        }

        public void close() throws IOException {

            if (din == null)

                return;

            din.close();

        }

    }

    static class Kattio extends PrintWriter {

        private BufferedReader r;

        private StringTokenizer st;

        // standard input

        public Kattio() { this(System.in, System.out); }

        public Kattio(InputStream i, OutputStream o) {

            super(o);

            r = new BufferedReader(new InputStreamReader(i));

        }

        // USACO-style file input

        public Kattio(String problemName) throws IOException {

            super(new FileWriter(problemName + ".out"));

            r = new BufferedReader(new FileReader(problemName + ".in"));

        }

        // returns null if no more input

        public String next() {

            try {

                while (st == null || !st.hasMoreTokens())

                    st = new StringTokenizer(r.readLine());

                return st.nextToken();

            } catch (Exception e) { }

            return null;

        }

        public int nextInt() { return Integer.parseInt(next()); }

        public double nextDouble() { return Double.parseDouble(next()); }

        public long nextLong() { return Long.parseLong(next()); }

    }

    static Kattio sc = new Kattio();

    static long  mod  = (long)1e9+7;

    static PrintWriter out =new PrintWriter(System.out);

    //Heapify function to maintain heap property.

    public static void swap(int i,int j,int arr[]) {

        int temp = arr[i];

        arr[i] = arr[j];

        arr[j] = temp;

    }

    static String endl = "\n" , gap = " ";

    public static int ans;

    public static void main(String[] args)throws IOException {

        int t = ri();

        while(t-->0) {

            solve();

        }

        out.close();

    }

    public static void solve()throws IOException {

        int a = ri() , b = ri() , p = ri();

        char s[] = rac();

        int n = s.length;

        int prev = s[n-2];

        int sum = 0;

        if(s[n-2] == 'A') {

            if(p < a) {

                System.out.println(n);

                return;

            }

        }

        if(s[n-2] == 'B') {

            if(p < b) {

              System.out.println(n);

              return;

            }

        }

        for(int i =n-3;i>=0;i--) {

            if(prev == s[i]) {

                continue;

            }

            else {

                sum += (prev == 'A'?a : b);

                // System.out.println("sum iis " + sum);

                prev  = s[i];

                if(prev == 'A') {

                    if(sum + a >p )  {

                        System.out.println(i + 2);

                        return;

                    }

                }

                if(prev == 'B') {

                    if(sum + b > p) {

                        System.out.println(i + 2);

                        return;

                    }

                }

            }

        }

        System.out.println(1);

    }

    public static long get(long a) {

        long ans = 1;

        for(long i = (long)Math.sqrt(a);i>=1;i--) {

            if(i*(i+1l)/2l <= a) return i;

        }

        return ans;

    }

    public static long get2(long a) {

        long ans = 1;

        for(long i = (long)Math.sqrt(a);i>=1;i--) {

            if(i*(i+1)/2 < a ) return ans;

            ans = i;

        }

        return 1l;

    }

    public static long rl() {

        return sc.nextLong();

    }

    public static char[] rac() {

        return sc.next().toCharArray();

    }

    public static String rs() {

        return sc.next();

    }

    public static  int [] rai(int n) {

        int ans[] = new int[n];

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

            ans[i] = sc.nextInt();

        }

        return ans;

    }

    public static  long [] ral(int n) {

        long ans[] = new long[n];

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

            ans[i] = sc.nextLong();

        }

        return ans;

    }

    public static int ri() {

        return sc.nextInt();

    }

    public static int getValue(int num ) {

        int ans = 0;

        while(num > 0) {

            ans++;

            num = num&(num-1);

        }

        return ans;

    }

    public static boolean isValid(int x ,int y , int n,char arr[][],boolean visited[][][][])  {

        return x>=0 && x<n && y>=0 && y <n && !(arr[x][y] == '#');

    }

    // public static Pair join(Pair a , Pair b) {

    //     Pair res = new Pair(Math.min(a.min , b.min) , Math.max(a.max , b.max) , a.count + b.count);

    //     return res;

    // }

    // segment tree query over range

    // public static int query(int node,int l , int r,int a,int b ,Pair tree[] ) {

    //     if(tree[node].max < a || tree[node].min > b) return 0;

    //     if(l  > r) return 0;

    //     if(tree[node].min >= a && tree[node].max <= b) {

    //         return tree[node].count;

    //     }

    //     int mid = l + (r-l)/2;

    //     int ans = query(node*2 ,l , mid ,a , b , tree) + query(node*2 +1,mid + 1, r , a , b, tree);

    //     return ans;

    // }

    // // segment tree update over range

    // public static void update(int node, int i , int j ,int l , int r,long value, long arr[] ) {

    //     if(l >= i && j >= r) {

    //         arr[node]   += value;

    //         return;

    //     }

    //     if(j < l|| r < i) return;

    //     int mid = l + (r-l)/2;

    //     update(node*2 ,i ,j ,l,mid,value, arr);

    //     update(node*2 +1,i ,j ,mid + 1,r, value  , arr);

    // }

    public static long pow(long a , long b  , long mod) {

        if(b == 1) return a;

        if(b == 0) return 1;

        long ans = pow(a , b/2 , mod)%mod;

        if(b%2 == 0) {

            return (ans*ans)%mod;

        }

        else {

            return ((ans*ans)%mod*a)%mod;

        }

    }

    public static boolean isVowel(char ch) {

        if(ch == 'a' || ch == 'e'||ch == 'i' || ch == 'o' || ch == 'u') return true;

        return false;

    }

    public static int getFactor(int num) {

        if(num==1) return 1;

        int ans = 2;

        int k = num/2;

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

            if(num%i==0) ans++;

        }

        return Math.abs(ans);

    }

    public static int[] readarr()throws IOException {

        int n = sc.nextInt();

        int arr[] = new int[n];

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

            arr[i] =  sc.nextInt();

        }

        return arr;

    }

    public static boolean isPowerOfTwo (long x) {

        return x!=0 && ((x&(x-1)) == 0);

    }

    public static boolean isPrime(long num) {

        if(num==1) return false;

        if(num<=3) return true;

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

        for(long i =5;i*i<=num;i+=6) {

            if(num%i==0 || num%(i+2) == 0) return false;

        }

        return true;

    }

    public static boolean isPrime(int num) {

        if(num==1) return false;

        if(num<=3) return true;

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

        for(int i =5;i*i<=num;i+=6) {

            if(num%i==0) return false;

        }

        return true;

    }

    public static long gcd(long a , long b) {

        if (b == 0) return a;

        return gcd(b, a % b);

    }

    public static long get_gcd(long a , long b) {

        if (b == 0) return a;

        return gcd(b, a % b);

    }

    public static long fac(long num)  {

        long ans = 1;

        int mod = (int)1e9+7;

        for(long i = 2;i<=num;i++) {

            ans  =  (ans*i)%mod;

        }

        return ans;

    }

}


E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6
-100 -200 -300 125 77 -4
OutputCopy9
InputCopy1000000000000 5
-1 0 0 0 0
OutputCopy4999999999996
InputCopy10 4
-3 -6 5 4
OutputCopy-1

import java.io.*;

import java.util.*;

import java.lang.*;

import java.util.jar.JarEntry;

import static java.lang.Math.*;

// Sachin_2961 submission //

public class Codeforces {

    static void solve() {

        long H = fs.nLong();

        int n = fs.nInt();

        int[]ar = new int[n];

        long sum = 0;

        long mn = 0;

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

            ar[i] = fs.nInt();

            sum += ar[i];

            mn = min(mn,sum);

            if( H + sum <= 0 ){

                out.println(i+1);

                return;

            }

        }

        if(sum < 0){

            long ans = (long)floor((double)(H+mn)/(double)(-sum));

            H += sum*ans;

            ans *= n;

            int i = 0;

            while (H > 0 ){

                ans++;

                H += ar[i%n];

                i++;

            }

            out.println(ans);

            return;

        }

        out.println("-1");

    }

    static boolean multipleTestCase = false; static FastScanner fs; static PrintWriter out;

    public static void main(String[]args){

       try{

           fs = new FastScanner();

           out = new PrintWriter(System.out);

           int tc = (multipleTestCase)?fs.nInt():1;

           while (tc-->0)solve();

           out.flush();

           out.close();

       }catch (Exception e){

           e.printStackTrace();

       }

    }

    static class FastScanner {

        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

        StringTokenizer st=new StringTokenizer("");

        String n() {

            while (!st.hasMoreTokens())

                try {

                    st=new StringTokenizer(br.readLine());

                } catch (IOException e) {

                    e.printStackTrace();

                }

            return st.nextToken();

        }

        String Line()

        {

            String str = "";

            try

            {

                str = br.readLine();

            }catch (IOException e)

            {

                e.printStackTrace();

            }

            return str;

        }

        int nInt() {return Integer.parseInt(n()); }

        long nLong() {return Long.parseLong(n());}

        double nDouble(){return Double.parseDouble(n());}

        int[]aI(int n){

            int[]ar = new int[n];

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

                ar[i] = nInt();

            return ar;

        }

    }

}


B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3
5 1 1
8 10 10
1000000 1 1000000
OutputCopy5
8
499999500000
NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int T = sc.nextInt();

        for (int tc = 0; tc < T; ++tc) {

            int n = sc.nextInt();

            int g = sc.nextInt();

            int b = sc.nextInt();

            System.out.println(solve(n, g, b));

        }

        sc.close();

    }

    static long solve(int n, int g, int b) {

        int needed = (n + 1) / 2;

        long result;

        if (needed % g == 0) {

            result = (long) needed / g * (g + b) - b;

        } else {

            result = (long) needed / g * (g + b) + needed % g;

        }

        result = Math.max(result, n);

        return result;

    }

}


D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that:  each array contains nn elements;  each element is an integer from 11 to mm;  for each array, there is exactly one pair of equal elements;  for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are:  [1,2,1][1,2,1];  [1,3,1][1,3,1];  [1,4,1][1,4,1];  [2,3,2][2,3,2];  [2,4,2][2,4,2];  [3,4,3][3,4,3].

import java.util.*;

public class countthearrays {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();

		int m = sc.nextInt();

		int k = 998244353;

		long pow = 1;

		long[] fac = new long[m + 1];

		fac[0] = 1;

		fac[1] = 1;

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

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

		}

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

			pow = pow * 2 % k;

		}

		long ncr = 0;

		ncr = fac[m] * modInverse(fac[n - 1], k) % k * modInverse(fac[m - n + 1], k) % k;

		long ans = ncr * (n - 2) % k;

		ans = ans * pow % k;

		System.out.println(ans);

	}

	static long power(long x, long y, int p) {

		long res = 1;

		x = x % p;

		while (y > 0) {

			if (y % 2 == 1) {

				res = (res * x) % p;

			}

			y = y >> 1;

			x = (x * x) % p;

		}

		return res;

	}

	static long modInverse(long n, int p) {

		return power(n, p - 2, p);

	}

}


A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat.  You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
OutputCopysinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.

import java.io.*;

import java.util.*;

public class A1 {

    static final Reader s = new Reader();

    static final PrintWriter out = new PrintWriter(System.out);

    public static void main(String[] args) throws IOException {

//        int t  = s.nextInt();

        int t=1;

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

//            out.print("Case #"+i+": ");

            new Solver();

        }

        out.close();

    }

    static class Solver {

        Solver() {

        	Scanner sc = new Scanner(System.in);

        	int n = sc.nextInt(),m = sc.nextInt();

      	    sc.nextLine();

        	String[] a = sc.nextLine().split(" ");

        	String[] b = sc.nextLine().split(" ");

        	int q = sc.nextInt();

	       	while(q-->0) {

	       		int q1 = sc.nextInt();

	       		int g = q1%n;

	       		int h = q1%m;

	       		if(g==0)g=n;

	       		if(h==0)h=m;

	       		String ans="";

	       		ans+=a[g-1]+b[h-1];

	     		System.out.println(ans);

	       	}

        }

    }

    static class Reader {

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        StringTokenizer st;

        String next() {

            while(st==null||!st.hasMoreTokens()) {

                try {

                    st=new StringTokenizer(in.readLine());

                } catch(Exception e) {}

            }

            return st.nextToken();

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        long nextLong() {

            return Long.parseLong(next());

        }

    }

}


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

import java.util.*;

import java.io.*;

public class Main {

  static StringBuilder sb;

  static dsu dsu;

  static long fact[];

  static int mod = (int) (1e9 + 7);

  static void solve() {

    int n = i();

    int x = i();

    String str = s();

    int cnt0 = 0;

    for(int i =0;i<str.length();i++){

        if(str.charAt(i)=='0') cnt0++;

    }

    int obal = 2*cnt0-n; // cnt0 - cnt1 , cnt0 - (n-cnt0)

    int cbal = 0;

    int ans = 0;

    for(int i =0;i<str.length();i++){

        if(obal==0&&cbal==x){

            System.out.println(-1);

            return;

        }

        if(obal!=0&&(Math.abs(x-cbal)%Math.abs(obal))==0){

            if((x-cbal)/obal>=0){

                ans++;

            }

        }

        if(str.charAt(i)=='0') cbal++;

        else cbal--;

    }

    System.out.println(ans);

  }

  public static void main(String[] args) {

    sb = new StringBuilder();

    int test = i();

    while (test-- > 0) {

      solve();

    }

    System.out.println(sb);

  }

  /*

   * fact=new long[(int)1e6+10]; fact[0]=fact[1]=1; for(int i=2;i<fact.length;i++)

   * { fact[i]=((long)(i%mod)1L(long)(fact[i-1]%mod))%mod; }

   */

//**************NCR%P******************

  static long ncr(int n, int r) {

    if (r > n)

      return (long) 0;

    long res = fact[n] % mod;

    // System.out.println(res);

    res = ((long) (res % mod) * (long) (p(fact[r], mod - 2) % mod)) % mod;

    res = ((long) (res % mod) * (long) (p(fact[n - r], mod - 2) % mod)) % mod;

    // System.out.println(res);

    return res;

  }

  static long p(long x, long y)// POWER FXN //

  {

    if (y == 0)

      return 1;

    long res = 1;

    while (y > 0) {

      if (y % 2 == 1) {

        res = (res * x) % mod;

        y--;

      }

      x = (x * x) % mod;

      y = y / 2;

    }

    return res;

  }

//**************END******************

  // *************Disjoint set

  // union*********//

  static class dsu {

    int parent[];

    dsu(int n) {

      parent = new int[n];

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

        parent[i] = -1;

    }

    int find(int a) {

      if (parent[a] < 0)

        return a;

      else {

        int x = find(parent[a]);

        parent[a] = x;

        return x;

      }

    }

    void merge(int a, int b) {

      a = find(a);

      b = find(b);

      if (a == b)

        return;

      parent[b] = a;

    }

  }

//**************PRIME FACTORIZE **********************************//

  static TreeMap<Integer, Integer> prime(long n) {

    TreeMap<Integer, Integer> h = new TreeMap<>();

    long num = n;

    for (int i = 2; i <= Math.sqrt(num); i++) {

      if (n % i == 0) {

        int nt = 0;

        while (n % i == 0) {

          n = n / i;

          nt++;

        }

        h.put(i, nt);

      }

    }

    if (n != 1)

      h.put((int) n, 1);

    return h;

  }

//****CLASS PAIR ************************************************

  static class Pair implements Comparable<Pair> {

    int x;

    long y;

    Pair(int x, long y) {

      this.x = x;

      this.y = y;

    }

    public int compareTo(Pair o) {

      return (int) (this.y - o.y);

    }

  }

//****CLASS PAIR **************************************************

  static class InputReader {

    private InputStream stream;

    private byte[] buf = new byte[1024];

    private int curChar;

    private int numChars;

    private SpaceCharFilter filter;

    public InputReader(InputStream stream) {

      this.stream = stream;

    }

    public int read() {

      if (numChars == -1)

        throw new InputMismatchException();

      if (curChar >= numChars) {

        curChar = 0;

        try {

          numChars = stream.read(buf);

        } catch (IOException e) {

          throw new InputMismatchException();

        }

        if (numChars <= 0)

          return -1;

      }

      return buf[curChar++];

    }

    public int Int() {

      int c = read();

      while (isSpaceChar(c))

        c = read();

      int sgn = 1;

      if (c == '-') {

        sgn = -1;

        c = read();

      }

      int res = 0;

      do {

        if (c < '0' || c > '9')

          throw new InputMismatchException();

        res *= 10;

        res += c - '0';

        c = read();

      } while (!isSpaceChar(c));

      return res * sgn;

    }

    public String String() {

      int c = read();

      while (isSpaceChar(c))

        c = read();

      StringBuilder res = new StringBuilder();

      do {

        res.appendCodePoint(c);

        c = read();

      } while (!isSpaceChar(c));

      return res.toString();

    }

    public boolean isSpaceChar(int c) {

      if (filter != null)

        return filter.isSpaceChar(c);

      return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;

    }

    public String next() {

      return String();

    }

    public interface SpaceCharFilter {

      public boolean isSpaceChar(int ch);

    }

  }

  static class OutputWriter {

    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {

      writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));

    }

    public OutputWriter(Writer writer) {

      this.writer = new PrintWriter(writer);

    }

    public void print(Object... objects) {

      for (int i = 0; i < objects.length; i++) {

        if (i != 0)

          writer.print(' ');

        writer.print(objects[i]);

      }

    }

    public void printLine(Object... objects) {

      print(objects);

      writer.println();

    }

    public void close() {

      writer.close();

    }

    public void flush() {

      writer.flush();

    }

  }

  static InputReader in = new InputReader(System.in);

  static OutputWriter out = new OutputWriter(System.out);

  public static long[] sort(long[] a2) {

    int n = a2.length;

    ArrayList<Long> l = new ArrayList<>();

    for (long i : a2)

      l.add(i);

    Collections.sort(l);

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

      a2[i] = l.get(i);

    return a2;

  }

  public static char[] sort(char[] a2) {

    int n = a2.length;

    ArrayList<Character> l = new ArrayList<>();

    for (char i : a2)

      l.add(i);

    Collections.sort(l);

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

      a2[i] = l.get(i);

    return a2;

  }

  public static long pow(long x, long y) {

    long res = 1;

    while (y > 0) {

      if (y % 2 != 0) {

        res = (res * x);// % modulus;

        y--;

      }

      x = (x * x);// % modulus;

      y = y / 2;

    }

    return res;

  }

//GCD___+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

  public static long gcd(long x, long y) {

    if (x == 0)

      return y;

    else

      return gcd(y % x, x);

  }

  // ******LOWEST COMMON MULTIPLE

  // *********************************************

  public static long lcm(long x, long y) {

    return (x * (y / gcd(x, y)));

  }

//INPUT PATTERN********************************************************

  public static int i() {

    return in.Int();

  }

  public static long l() {

    String s = in.String();

    return Long.parseLong(s);

  }

  public static String s() {

    return in.String();

  }

  public static int[] readArrayi(int n) {

    int A[] = new int[n];

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

      A[i] = i();

    }

    return A;

  }

  public static long[] readArray(long n) {

    long A[] = new long[(int) n];

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

      A[i] = l();

    }

    return A;

  }

}


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

import java.io.*;

import java.util.*;

public class main{

	public static void main(String args[]){

		Scanner scn = new Scanner(System.in);

		int t = Integer.parseInt(scn.nextLine());

		while(t-->0){

		    int n =Integer.parseInt(scn.nextLine());

			String inputs[] = scn.nextLine().split(" ");

			int sum = 0;

			int ans = 0;

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

			    sum += Integer.parseInt(inputs[i]);

			    if(Integer.parseInt(inputs[i])==0){

			        ans+=1;

			        sum+=1;

			    }

			}

			if(sum==0)ans+=1;

			System.out.println(ans);

		}

	}

}


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

/*

        "Everything in the universe is balanced. Every disappointment

                you face in life will be balanced by something good for you!

                        Keep going, never give up."

                        Just have Patience + 1...

*/

import java.util.*;

import java.lang.*;

import java.io.*;

public class Solution {

    static class Segment {

        int start;

        int end;

        Segment(int start, int end) {

            this.start = start;

            this.end = end;

        }

    }

    public static void main(String[] args) throws java.lang.Exception {

        out = new PrintWriter(new BufferedOutputStream(System.out));

        sc = new FastReader();

        int test = 1;

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

            solve();

        }

        out.close();

    }

    private static void solve() {

        int n = sc.nextInt();

        int[] arr = new int[n];

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

            arr[i] = sc.nextInt();

        }

        // divide into max subarray-blocks, such that each have same sum.

        Map<Long, List<Segment>> segmentsWithParticularSum = new HashMap<>();

        // for each possible subarray-sum

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

            long blockSum = 0;

            for (int start = end; start >= 0; start--) {

                blockSum += arr[start];

                if (!segmentsWithParticularSum.containsKey(blockSum)) {

                    segmentsWithParticularSum.put(blockSum, new ArrayList<>());

                }

                segmentsWithParticularSum.get(blockSum).add(new Segment(start + 1, end + 1));

            }

        }

        List<Segment> bestSegmentsChosen = new ArrayList<>();

        int maxTotalBlocks = 0;

        for (long blockSum : segmentsWithParticularSum.keySet()) {

            List<Segment> blocksTaken = new ArrayList<>();

            int lastBlockEnd = -1, totalBlocks = 0;

            for (Segment segment : segmentsWithParticularSum.get(blockSum)) {

                if (segment.start > lastBlockEnd) {

                    totalBlocks++;

                    blocksTaken.add(segment);

                    lastBlockEnd = segment.end;

                }

            }

            if (totalBlocks > maxTotalBlocks) {

                maxTotalBlocks = totalBlocks;

                bestSegmentsChosen = new ArrayList<>(blocksTaken);

            }

        }

        out.println(maxTotalBlocks);

        for (Segment segment : bestSegmentsChosen) {

            out.println(segment.start + " " + segment.end);

        }

    }

    public static FastReader sc;

    public static PrintWriter out;

    static class FastReader

    {

        BufferedReader br;

        StringTokenizer str;

        public FastReader()

        {

            br = new BufferedReader(new

                    InputStreamReader(System.in));

        }

        String next()

        {

            while (str == null || !str.hasMoreElements())

            {

                try

                {

                    str = new StringTokenizer(br.readLine());

                }

                catch (IOException  lastMonthOfVacation)

                {

                    lastMonthOfVacation.printStackTrace();

                }

            }

            return str.nextToken();

        }

        int nextInt()

        {

            return Integer.parseInt(next());

        }

        long nextLong()

        {

            return Long.parseLong(next());

        }

        double nextDouble()

        {

            return Double.parseDouble(next());

        }

        String nextLine()

        {

            String str = "";

            try

            {

                str = br.readLine();

            }

            catch (IOException lastMonthOfVacation)

            {

                lastMonthOfVacation.printStackTrace();

            }

            return str;

        }

    }

}


D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
OutputCopy1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
  public static void main(String[] args) {
    InputStream inputStream = System.in;
    OutputStream outputStream = System.out;
    InputReader in = new InputReader(inputStream);
    OutputWriter out = new OutputWriter(outputStream);
    DThreeIntegers solver = new DThreeIntegers();
    int testCount = Integer.parseInt(in.next());
    for (int i = 1; i <= testCount; i++) {
      solver.solve(i, in, out);
    }
    out.close();
  }

  static class DThreeIntegers {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
      int a = in.nextInt();
      int b = in.nextInt();
      int c = in.nextInt();
      int max = 0;
      max = Math.max(max, a);
      max = Math.max(max, b);
      max = Math.max(max, c);
      int min = (int) 1e9;
      int[] res = new int[3];
      for (int i = 1; i <= max; i++) {
        for (int j = 1; i * j <= 2e4; j++) {
          for (int k = 1; i * j * k <= 2e4; k++) {
            int d = Math.abs(a - i) + Math.abs(i * j - b) + Math.abs(i * j * k - c);
            if (d < min) {
              min = d;
              res[0] = i;
              res[1] = i * j;
              res[2] = i * j * k;
            }
          }
        }
      }
      out.println(min);
      out.println(res);
    }

  }

  static class InputReader {
    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private InputReader.SpaceCharFilter filter;

    public InputReader(InputStream stream) {
      this.stream = stream;
    }

    public int read() {
      if (numChars == -1) {
        throw new InputMismatchException();
      }
      if (curChar >= numChars) {
        curChar = 0;
        try {
          numChars = stream.read(buf);
        } catch (IOException e) {
          throw new InputMismatchException();
        }
        if (numChars <= 0) {
          return -1;
        }
      }
      return buf[curChar++];
    }

    public int nextInt() {
      int c = read();
      while (isSpaceChar(c)) {
        c = read();
      }
      int sgn = 1;
      if (c == '-') {
        sgn = -1;
        c = read();
      }
      int res = 0;
      do {
        if (c < '0' || c > '9') {
          throw new InputMismatchException();
        }
        res *= 10;
        res += c - '0';
        c = read();
      } while (!isSpaceChar(c));
      return res * sgn;
    }

    public String nextString() {
      int c = read();
      while (isSpaceChar(c)) {
        c = read();
      }
      StringBuilder res = new StringBuilder();
      do {
        if (Character.isValidCodePoint(c)) {
          res.appendCodePoint(c);
        }
        c = read();
      } while (!isSpaceChar(c));
      return res.toString();
    }

    public boolean isSpaceChar(int c) {
      if (filter != null) {
        return filter.isSpaceChar(c);
      }
      return isWhitespace(c);
    }

    public static boolean isWhitespace(int c) {
      return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public String next() {
      return nextString();
    }

    public interface SpaceCharFilter {
      public boolean isSpaceChar(int ch);

    }

  }

  static class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
      writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
    }

    public OutputWriter(Writer writer) {
      this.writer = new PrintWriter(writer);
    }

    public void print(int[] array) {
      for (int i = 0; i < array.length; i++) {
        if (i != 0) {
          writer.print(' ');
        }
        writer.print(array[i]);
      }
    }

    public void println(int[] array) {
      print(array);
      writer.println();
    }

    public void close() {
      writer.close();
    }

    public void println(int i) {
      writer.println(i);
    }

  }
}


E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times:   choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|;  erase the chosen subsequence from ss (ss can become empty);  concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4
ababcd
abcba
a
b
defi
fed
xyz
x
OutputCopyYES
NO
NO
YES

import java.io.IOException;

import java.io.InputStream;

import java.io.PrintWriter;

import java.math.BigDecimal;

import java.math.BigInteger;

import java.math.RoundingMode;

import java.util.*;

public class Main {

	static final long MOD1=1000000007;

	static final long MOD=998244353;

	static final int NTT_MOD1 = 998244353;

	static final int NTT_MOD2 = 1053818881;

	static final int NTT_MOD3 = 1004535809;

	static long MAX = 1000000000000000000l;

	public static void main(String[] args){

		PrintWriter out = new PrintWriter(System.out);

		InputReader sc=new InputReader(System.in);

		int t = sc.nextInt();

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

			char[] S = sc.next().toCharArray();

			char[] T = sc.next().toCharArray();

			out.println(solve(S, T));

		}

		out.flush();

   	}

	static String solve(char[] S, char[] T) {

		int s_len = S.length;

		int t_len = T.length;

		for (int i = 0; i < T.length; i++) {

			int len1 = i + 1;

			int[][] dp = new int[s_len + 1][len1 + 1];

			for (int j = 0; j < dp.length; j++) {

				Arrays.fill(dp[j], -1);

			}

			dp[0][0] = 0;

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

				for (int j2 = 0; j2 <= len1; j2++) {

					if(dp[j][j2] == -1) continue;

					dp[j + 1][j2] = Math.max(dp[j + 1][j2], dp[j][j2]);

					if(j2 + 1 <= len1 && S[j] == T[j2]) dp[j + 1][j2 + 1] = Math.max(dp[j + 1][j2 + 1], dp[j][j2]);

					if(dp[j][j2] + 1 + len1 <= t_len && S[j] == T[dp[j][j2] + len1]) dp[j + 1][j2] = Math.max(dp[j + 1][j2], dp[j][j2] + 1);

				}

			}

			if (dp[s_len][len1] + len1 == t_len) {

				return "YES";

			}

		}

		return "NO";

	}

	static class InputReader {

		private InputStream in;

		private byte[] buffer = new byte[1024];

		private int curbuf;

		private int lenbuf;

		public InputReader(InputStream in) {

			this.in = in;

			this.curbuf = this.lenbuf = 0;

		}

		public boolean hasNextByte() {

			if (curbuf >= lenbuf) {

				curbuf = 0;

				try {

					lenbuf = in.read(buffer);

				} catch (IOException e) {

					throw new InputMismatchException();

				}

				if (lenbuf <= 0)

					return false;

			}

			return true;

		}

		private int readByte() {

			if (hasNextByte())

				return buffer[curbuf++];

			else

				return -1;

		}

		private boolean isSpaceChar(int c) {

			return !(c >= 33 && c <= 126);

		}

		private void skip() {

			while (hasNextByte() && isSpaceChar(buffer[curbuf]))

				curbuf++;

		}

		public boolean hasNext() {

			skip();

			return hasNextByte();

		}

		public String next() {

			if (!hasNext())

				throw new NoSuchElementException();

			StringBuilder sb = new StringBuilder();

			int b = readByte();

			while (!isSpaceChar(b)) {

				sb.appendCodePoint(b);

				b = readByte();

			}

			return sb.toString();

		}

		public int nextInt() {

			if (!hasNext())

				throw new NoSuchElementException();

			int c = readByte();

			while (isSpaceChar(c))

				c = readByte();

			boolean minus = false;

			if (c == '-') {

				minus = true;

				c = readByte();

			}

			int res = 0;

			do {

				if (c < '0' || c > '9')

					throw new InputMismatchException();

				res = res * 10 + c - '0';

				c = readByte();

			} while (!isSpaceChar(c));

			return (minus) ? -res : res;

		}

		public long nextLong() {

			if (!hasNext())

				throw new NoSuchElementException();

			int c = readByte();

			while (isSpaceChar(c))

				c = readByte();

			boolean minus = false;

			if (c == '-') {

				minus = true;

				c = readByte();

			}

			long res = 0;

			do {

				if (c < '0' || c > '9')

					throw new InputMismatchException();

				res = res * 10 + c - '0';

				c = readByte();

			} while (!isSpaceChar(c));

			return (minus) ? -res : res;

		}

		public double nextDouble() {

			return Double.parseDouble(next());

		}

		public int[] nextIntArray(int n) {

			int[] a = new int[n];

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

				a[i] = nextInt();

			return a;

		}

		public double[] nextDoubleArray(int n) {

			double[] a = new double[n];

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

				a[i] = nextDouble();

			return a;

		}

		public long[] nextLongArray(int n) {

			long[] a = new long[n];

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

				a[i] = nextLong();

			return a;

		}

		public char[][] nextCharMap(int n, int m) {

			char[][] map = new char[n][m];

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

				map[i] = next().toCharArray();

			return map;

		}

	}

}