#include <bits/stdc++.h>

const int P = 1000000007;

int n, m;

std::vector<bool> vis;

std::vector<int> Par, Dis, a, b, l, top, p, type, len;

std::vector<unsigned> v;

std::vector<std::vector<int> > f, dp;

std::vector<std::vector<std::pair<int, int> > > e;

std::map<int, int> id;

void Inc(int &a, int b) { a += b - P, a += a >> 31 & P; }

void Dfs(int u) {

    for (auto [v, i] : e[u]) {

        if (Par[v] == -1) Dis[v] = Dis[u] ^ l[i], vis[i] = true, top[v] = top[u], Par[v] = u, Dfs(v);

    }

}

int main() {

    std::ios::sync_with_stdio(false);

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

    v = {0};

    id[0] = 0;

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

        unsigned u = v[i];

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

            if (u >> j & 1) continue;

            unsigned s = u;

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

                if (u >> k & 1) s |= 1 << (k ^ j);

            }

            s |= 1 << j;

            if (id.count(s)) continue;

            id[s] = v.size(), v.push_back(s);

        }

    }

    int cnt = v.size();

    f.assign(cnt, std::vector<int>(cnt));

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

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

            if (v[i] & v[j] && (f[i][j] = -1)) continue;

            unsigned s = v[i] | v[j];

            for (int x = 1; x < 32; ++x) {

                if (v[j] >> x & 1) {

                    for (int y = 0; y < 32; ++y) {

                        if (v[i] >> y & 1) s |= 1 << (y ^ x);

                    }

                }

            }

            f[i][j] = id[s];

        }

    }

    std::cin >> n >> m;

    Par.assign(n, -1), a.resize(m), b.resize(m), l.resize(m), e.resize(n), top.resize(n);

    type.resize(n), p.assign(n, -1), vis.resize(m), len.resize(n), Dis.resize(n), Par[0] = 0;

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

        std::cin >> a[i] >> b[i] >> l[i], --a[i], --b[i];

        if (a[i] == 0) {

            Par[b[i]] = 0, Dis[b[i]] = l[i], vis[i] = true;

        } else if (b[i] == 0) {

            Par[a[i]] = 0, Dis[a[i]] = l[i], vis[i] = true;

        }

        e[a[i]].emplace_back(b[i], i);

        e[b[i]].emplace_back(a[i], i);

    }

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

        if (Par[i] == 0) top[i] = i, Dfs(i);

    }

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

        if (!vis[i]) {

            int u = a[i], v = b[i];

            if (top[u] != top[v]) {

                p[u] = v, p[v] = u, len[u] = len[v] = Dis[u] ^ Dis[v] ^ l[i];

                continue;

            }

            int t = top[u];

            if (type[t] == -1) continue;

            if ((Dis[u] ^ Dis[v] ^ l[i]) == 0 && (type[t] = -1)) continue;

            type[t] = f[type[t]][Dis[u] ^ Dis[v] ^ l[i]];

        }

    }

    dp.assign(2, std::vector<int>(cnt));

    int cur = 0;

    dp[cur][0] = 1;

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

        if (top[i] == i && p[i] < i) {

            cur ^= 1, dp[cur] = dp[cur ^ 1];

            if (p[i] == -1) {

                if (type[i] != -1) {

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

                        if (f[j][type[i]] != -1) Inc(dp[cur][f[j][type[i]]], dp[cur ^ 1][j]);

                    }

                }

            } else {

                int k = p[i];

                if (type[i] == -1 || type[k] == -1) continue;

                int ty = f[type[i]][type[k]];

                if (ty != -1) {

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

                        if (f[j][ty] != -1) {

                            Inc(dp[cur][f[j][ty]], dp[cur ^ 1][j]);

                            Inc(dp[cur][f[j][ty]], dp[cur ^ 1][j]);

                        }

                    }

                }

                if (len[i] != 0 && ty != -1) {

                    ty = f[ty][len[i]];

                    if (ty != -1) {

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

                            if (f[j][ty] != -1) Inc(dp[cur][f[j][ty]], dp[cur ^ 1][j]);

                        }

                    }

                }

            }

        }

    }

    std::cout << std::accumulate(dp[cur].begin(), dp[cur].end(), 0LL) % P << "\n";

    return 0;

}


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

a
aa
a

cb
b
c

cOutputCopy? 1 2

? 3 4

? 4 4

! aabc

#include <bits/stdc++.h>

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

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

#define max(a,b) ((a)>(b)?(a):(b))

#define min(a,b) ((a)<(b)?(a):(b))

using namespace std;

char an[105];

struct cx{

	int len,tn[26];

}sp[105];

int tn[105][26],tn1[26],tn2[26];

bool zqr(cx a1,cx a2)

{

	return a1.len<a2.len;

}

void solve(int l)

{

	if(l==1)

	{

		printf("? %d %d\n",1,1);fflush(stdout);

		string s;cin>>s;

		an[1]=s[0];

		return;

	}

	multiset<vector<int> >aa;

	printf("? %d %d\n",1,l);fflush(stdout);

	fo(i,1,l*(l+1)>>1)

	{

		vector<int> tn(26,0);

		string s;cin>>s;

		for(auto xx:s)tn[xx-'a']++;

		aa.insert(tn);

	}

	printf("? %d %d\n",1,l-1);fflush(stdout);

	fo(i,1,l*(l-1)>>1)

	{

		vector<int> tn(26,0);

		string s;cin>>s;

		for(auto xx:s)tn[xx-'a']++;

		aa.erase(aa.find(tn));

	}

	int tot=0;

	for(auto xx:aa)

	{

		tot++;

		fo(i,0,25)sp[tot].len+=xx[i],sp[tot].tn[i]=xx[i];

	}

	sort(sp+1,sp+tot+1,zqr);

	fo(i,1,tot)

	{

		fo(j,0,25)if(sp[i].tn[j]-sp[i-1].tn[j])an[tot-i+1]=j+'a';

	}

}

int main()

{

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

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

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

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

	if(n==1)

	{

		printf("? %d %d\n",1,1);fflush(stdout);

		string s;cin>>s;

		printf("! %c",s[0]);fflush(stdout);

		return 0;

	}

	solve(n>>1);

	printf("? %d %d\n",1,n);

	fo(i,1,n*(n+1)>>1)

	{

		string s;cin>>s;

		int len=s.size();

		for(auto xx:s)tn[len][xx-'a']++;

	}

	fo(i,1,n-(n>>1))

	{

		fo(j,0,25)tn1[j]=tn[i][j]-tn[i-1][j];

		fo(j,0,25)tn2[j]=tn[i+1][j]-tn[i][j];

		fo(j,0,25)if(tn1[j]-tn2[j])

		{

			if(tn1[j]-tn2[j]==2)an[n-i+1]=j+'a';

			else if(j+'a'!=an[i])an[n-i+1]=j+'a';

		}

	}

	printf("! ");fo(i,1,n)putchar(an[i]);

	return 0;

}


B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104)  — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
OutputCopy1 11
5 35
3 6
0 42
0 0
1 2
3 4
NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6].  |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0;  |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3;  |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3;  |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3;  |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33.

// CF template, version 3.0

#include <bits/stdc++.h>

using namespace std;

#define improvePerformance ios_base::sync_with_stdio(false); cin.tie(0)

#define getTest int t; cin >> t

#define eachTest for (int _var=0;_var<t;_var++)

#define get(name) int (name); cin >> (name)

#define out(o) cout << (o)

#define getList(cnt, name) vector<int> (name); for (int _=0;_<(cnt);_++) { get(a); (name).push_back(a); }

#define sortl(name) sort((name).begin(), (name).end())

#define rev(name) reverse((name).begin(), (name).end())

#define forto(name, var) for (int (var) = 0; (var) < (name); (var)++)

#define decision(b) if (b){out("YES");}else{out("NO");}

#define int long long int

int gcd(int a, int b) {

    if (a == b) return a;

    return gcd(max(a, b), max(a, b) % min(a, b));

}

/*

Segtree:

void build(vector<int> &tree, vector<int> &array, int i, int l, int r) {

    if (l == r) {

        tree[i] = array[l];

    } else {

        int middle = (l + r) / 2;

        build(tree, array, i * 2, l, middle);

        build(tree, array, i * 2 + 1, middle + 1, r);

        tree[i] = max(tree[i * 2], tree[i * 2 + 1]);

    }

}

void set_(vector<int> &tree, int v, int l, int r, int i, int x) {

    if (l == r) {

        tree[v] = x;

    } else {

        int middle = (l + r) / 2;

        if (i <= middle) {

            set_(tree, v * 2, l, middle, i, x);

        } else {

            set_(tree, v * 2 + 1, middle + 1, r, i, x);

        }

        tree[v] = max(tree[v * 2], tree[v * 2 + 1]);

    }

}

int query(vector<int> &tree, int v, int cl, int cr, int l, int r) {

    if (l == cl && r == cr) {

        return tree[v];

    }

    if (l > r) return 0;

    int middle = (cl + cr) / 2;

    return max(

        query(tree, v * 2, cl, middle, l, min(r, middle)),

        query(tree, v * 2 + 1, middle + 1, cr, max(l, middle + 1), r)

    );

}

vector<int> tree(4 * n);

build(tree, initial, 1, 0, n-1); // replace initial with name of array

set_(tree, 1, 0, n-1, a, b);

query(tree, 1, 0, n-1, a, b); // this returns an int

data structure can be changed

*/

signed main() {

    improvePerformance;

    getTest;

    eachTest {

        get(n);

        getList(n, nums);

        vector<int> adjs;

        int maxdiff = 0;

        forto(n, i) {

            int cur = nums[i];

            if (i != n - 1 && cur != -1 && nums[i + 1] != -1) maxdiff = max(maxdiff, abs(nums[i + 1] - cur));

            if (((i && nums[i - 1] == - 1) || (i != n - 1 && nums[i + 1] == -1)) && cur != -1) adjs.push_back(cur);

        }

        sortl(adjs);

        if (adjs.size() > 1) {

            int middle = (adjs[adjs.size() - 1] + adjs[0]) / 2;

            int ans = max(maxdiff, max(adjs[adjs.size() - 1] - middle, middle - adjs[0]));

            out(ans);

            out(" ");

            out(middle);

        } else if (adjs.size() == 0) {

            out(maxdiff);

            out(" ");

            out(0);

        } else {

            out(maxdiff);

            out(" ");

            out(adjs[0]);

        }

        out("\n");

    }

}


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

#include<bits/stdc++.h>

typedef long long ll;

typedef unsigned long long ull;

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

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

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

using namespace std;

const int N = 1050;

int n, k, len, blo; bool ans[N];

void clr() {cout << "R" << endl;}

bool ask(int x) {

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

	char rec; cin >> rec; return (rec == 'Y');

}

void calc(int x) {

	int l = (x - 1) * len + 1;

	int r = x * len;

	rep(i, l, r) if(ans[i] && ask(i)) ans[i] = false;

}

int main() {

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

	len = k;

	blo = n / k;

	rep(i, 1, n) ans[i] = true;

	rep(s, 1, blo) {

		if(s > 1) clr();

		for(int d = 0, i = 1; i <= blo; i ++) {

			int x = s + d;

			while(x <= 0) x += blo;

			while(x > blo) x -= blo;

			calc(x);

			if(d >= 0) d = - d - 1; else d = - d;

		}

	}

	int Ans = 0;

	rep(i, 1, n) Ans += ans[i];

	cout << "! " << Ans << endl;

	return 0;

}


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

#include <bits/stdc++.h>

using namespace std;

#define int long long

int32_t main() {

	int n; cin >> n;

	vector<int> q(n - 1);

	for (int &x : q)

		cin >> x;

	vector<int> answer(n, 0);

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

		answer[i + 1] = answer[i] + q[i];

	int mx = *max_element(begin(answer), end(answer));

	for (int &x : answer)

		x += n - mx;

	set<int> st;

	for (int x : answer)

		st.insert(x);

	if (*st.begin() < 1 || st.size() != n)

		cout << -1;

	else

		for (int x : answer)

			cout << x << ' ';

}


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

#include <bits/stdc++.h>

#include <ext/pb_ds/tree_policy.hpp>

#include <ext/pb_ds/assoc_container.hpp>

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

#define ll long long

#define ld long double

#define el "\n"

#define matrix vector<vector<int>>

#define pt complex<ld>

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

#define ordered_multiset tree<ll, null_type,less_equal<ll>, rb_tree_tag, tree_order_statistics_node_update>

using namespace __gnu_pbds;

using namespace std;

const ll N = 1500, LOG = 20;

const ld pi = acos(-1);

const ll mod = 1e9 + 7;

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

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

ll n, m, k, x, y;

int a[N];

int solve(vector<pair<int, int>> &v) {

    int cnt = 1;

    int idx;

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

    pair<int, int> p = {v[0].second, 1e9};

    for (auto j: v) {

        if (p.second > j.second) {

            p = j;

        }

    }

    p = {p.second + 1, 0};

    idx = upper_bound(v.begin(), v.end(), p) - v.begin();

    while (idx < v.size()) {

        p = v[idx];

        p = {p.second + 1, 0};

        idx = upper_bound(v.begin(), v.end(), p) - v.begin();

        cnt++;

    }

    return cnt;

}

void dowork() {

    map<int, vector<pair<int, int>>> mp;

    cin >> n;

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

        cin >> a[i];

    }

    int sum;

    vector<pair<int, int>> ans;

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

        sum = 0;

        for (int j = i; j > 0; j--) {

            sum += a[j];

            if (mp[sum].size() == 0 || mp[sum].back().second < j) {

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

            }

            if (mp[sum].size() > ans.size()) {

                ans = mp[sum];

            }

        }

    }

    cout << ans.size() << el;

    for (auto j: ans) {

        cout << j.first << " " << j.second << el;

    }

}

int main() {

    fast

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

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

    int t = 1;

    //cin >> t;

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

        dowork();

    }

}


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

#pragma GCC optimize("O2")

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

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace std;

using namespace __gnu_pbds;

#define ll     long long

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

#define ff     first

#define ss     second

#define pb     push_back

#define ppb    pop_back

#define pf     push_front

#define ppf    pop_front

template <typename T> using Ordered_Set_Tree =

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

template <typename T> using Ordered_Multiset_Tree =

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

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

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

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

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

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

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

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

///DEBUG

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

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

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

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

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

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

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

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

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

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

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

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

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

template <class T, class V> void _Print(map <T, V> &v);

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

template <class T, class V> void _Print(pair <T, V> &p) {cerr << "{"; _Print(p.ff); cerr << ","; _Print(p.ss); cerr << "}\n\n";}

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

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

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

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

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

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

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

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

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

vector<string> vec_splitter(string s)

{

    s += ',';

    vector<string> res;

    while(!s.empty())

    {

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

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

    }

    return res;

}

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

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

{

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

    stringstream ss; ss << H;

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

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

}

///DEBUG

int main()

{

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    test

    {

        string s, t;

        cin>>s>>t;

        vector<vector<int>> nextPos(s.size()+1, vector<int> (26, 1e9));

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

        {

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

                nextPos[i][s[j]-'a'] = min(nextPos[i][s[j]-'a'], j);

        }

        vector<vector<int>> dp(s.size()+2, vector<int> (s.size()+2));

        auto cal = [&](string a, string b)

        {

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

            {

                for(int j=0; j<=b.size(); j++)

                    dp[i][j] = 1e9;

            }

            dp[0][0] = 0;

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

            {

                for(int j=0; j<=b.size(); j++)

                {

                    if(dp[i][j] > s.size())             continue;

                    int lenS = dp[i][j];

                    if(i<a.size() && nextPos[lenS][a[i]-'a']<1e9)

                        dp[i+1][j] = min(dp[i+1][j], nextPos[lenS][a[i]-'a']+1);

                    if(j<b.size() && nextPos[lenS][b[j]-'a']<1e9)

                        dp[i][j+1] = min(dp[i][j+1], nextPos[lenS][b[j]-'a']+1);

                }

            }

            return (dp[a.size()][b.size()] <= s.size());

        };

        int poss = 0;

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

        {

            if(cal(t.substr(0, i), t.substr(i, t.size()-i)))

            {

                poss = 1;

                break;

            }

        }

        if(poss)            cout<<"YES\n";

        else                cout<<"NO\n";

    }

}


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';

}