C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10
8 5
OutputCopy3InputCopy3 12
1 4 5
OutputCopy0InputCopy3 7
1 4 9
OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7.

// #pragma GCC optimize "fast-math"
// #pragma GCC optimize("O3,unroll-loops")
// #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#pragma GCC diagnostic ignored "-Wunused-variable"

#include "bits/stdc++.h"
#include "ext/pb_ds/assoc_container.hpp"

using namespace std;
using namespace __gnu_pbds;

#define endl "\n"
#define int long long
// #define ONLINE_JUDGE

#define MULTI  \
    int _T;    \
    cin >> _T; \
    while (_T--)

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

typedef tree<pair<int, int>, null_type,
             less<pair<int, int>>, rb_tree_tag,
             tree_order_statistics_node_update>
    ordered_set_pair;

//////////////////////////////////////-----/////////////////////////////////////////////

const int INF = 1e18;        // infinity
const int mod = 1e9 + 7;     // mod
const int base1 = 972663749; // base1
const int base2 = 998244353; // base2
const int mod1 = 1000000007; // mod1
const int mod2 = 1000000009; // mod2

const double pi = 4 * atan(1);

vector<int> dx = {-1, +1, +0, +0, +1, -1, +1, -1};
vector<int> dy = {+0, +0, +1, -1, +1, -1, -1, +1};

/////////////////////////////////////----////////////////////////////////////////////////

int modpower(int x, int n, int m)
{
    if (n == 0)
        return 1 % m;
    int u = modpower(x, n / 2, m);
    u = (u * u) % m;
    if (n % 2 == 1)
        u = (u * x) % m;
    return u;
}

int modinverse(int i, int MOD)
{
    if (i == 1)
        return 1;
    return (MOD - ((MOD / i) * modinverse(MOD % i, MOD)) % MOD + MOD) % MOD;
}

int lcm(int x1, int x2)
{
    return ((x1 * x2) / __gcd(x1, x2));
}

int bitCount(unsigned int u)
{
    unsigned int uCount;
    uCount = u - ((u >> 1) & 033333333333) - ((u >> 2) & 011111111111);
    return ((uCount + (uCount >> 3)) & 030707070707) % 63;
}

void printVector(vector<int> &array)
{
    int sz = array.size();
    if (sz == 0)
        return;
    for (int i = 0; i < sz - 1; i++)
    {
        cout << array[i] << " ";
    }
    cout << array[sz - 1] << endl;
}

void printArray(int array[], int sz)
{
    for (int i = 0; i < sz - 1; i++)
    {
        cout << array[i] << " ";
    }
    cout << array[sz - 1] << endl;
}

//////////////////////////////////////----main-function----///////////////////////////////////////////
//====================================================================================================
//====================================================================================================

int n, m;
int a[200005];

void solve_the_probelm(int test_case)
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        cin >> a[i];
    }

    if (n > m)
    {
        cout << 0 << endl;
        return;
    }
    int ans = 1;
    for (int i = 1; i <= n; i++)
    {
        for (int j = i + 1; j <= n; j++)
        {
            ans = (ans * abs(a[i] - a[j])) % m;
        }
    }
    cout << ans << endl;
}

///////////////////////////////////------------------------///////////////////////////////////////////
//====================================================================================================
//====================================================================================================
signed main()
{
    int test_cases = 1;
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif

    // cin >> test_cases; ////////////////////////////////////_test_cause___

    for (int test_case = 1; test_case <= test_cases; test_case++)
        solve_the_probelm(test_case);

#ifndef ONLINE_JUDGE
    cout << "\nExecution Time : " << 1.0 * clock() / CLOCKS_PER_SEC << "s ";
#endif

    return 0;
}


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

#include <bits/stdc++.h>

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

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

#include <ext/rope>

#define TIME 1.0*clock()/CLOCKS_PER_SEC

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

#define ull unsigned long long

#define pii pair < int , int >

#pragma GCC optimize("Ofast")

#define ld long double

#define pb push_back

#define ll long long

#define endl '\n'

#define S second

#define F first

#define sz size

#define int ll

using namespace std;

using namespace __gnu_pbds;

template <typename T>

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

mt19937 gen(chrono::system_clock::now().time_since_epoch().count());

int b[500000];

int n;

int get (int x, int y) {

    if (x > y) return 0;

    int kl = 0;

    int l = 1, r = 1;

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

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

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

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

    }

    return (kl / 2) ;

}

int32_t main() {

    #ifdef LOCAL

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

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

    #endif

    ios_base::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    cin >> n;

    int a[n + 2];

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

    int ans = 0;

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

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

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

        }

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

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

        if (cnt % 2) ans += (1 << i);

    }

    cout << ans;

return 0;

}


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

#include <cstdio>

#include <iostream>

#include <algorithm>

#include <cstring>

#include <vector>

#include <random>

#include <set>

using namespace std;

#define fi first

#define sc second

#define mkp make_pair

#define pii pair<int,int>

typedef long long ll;

const int N=1e5+5,oo=1e8,mod=1e9+9;

inline int read() {

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

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

    while('0'<=ch&&ch<='9') {x=(x<<3)+(x<<1)+ch-'0';ch=getchar();}

    return flag?-x:x;

}

inline int mx(int x,int y) {return x>y?x:y;}

inline int mn(int x,int y) {return x<y?x:y;}

inline void swp(int &x,int &y) {x^=y^=x^=y;}

inline int as(int x) {return x>0?x:-x;}

inline int ok(int x) {return x>0?1:-1;}

int n,m,a[N],t[N];

int main() {

#ifndef ONLINE_JUDGE

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

    freopen("1.out","w",stdout);

#endif

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

    int lim=0;

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

        lim+=(i-1)/2;

    if(lim<m) {

        printf("-1\n");

        return 0;

    }

    int p=1;

    for(p=1;p<=n;++p)

        if(m-(p-1)/2>=0) {

            m-=(p-1)/2;

            a[p]=p;

        } else break;

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

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

            ++t[i+j];

    for(int i=2*p;i>=1;--i)

        if(t[i]==m) {

            a[p]=i;

            break;

        }

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

        a[i]=oo-(n-i)*10000;

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

    return 0;

}

//yqmpo62327

//Ro5dPTkt


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

#include <bits/stdc++.h>

#define f first

#define s second

#define pb push_back

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

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

using namespace std;

using ll = long long;

using ld = long double;

using pii = pair<int, int>;

using vi = vector<int>;

using vp = vector <pii>;

using vl = vector<ll>;

const int inf = INT_MAX;

const ll linf = LLONG_MAX;

const int mod = 1e9+7;

int mex(vi v) {

    sort(all(v));

    v.resize(unique(all(v)) - v.begin());

    for(int i = 0; i < sz(v); i++)

        if(i != v[i]) return i;

    return sz(v);

}

using BLOCK = array<array<int, 3>, 5>;

vector <BLOCK> step[6][6][6];

vector <BLOCK> period[6][6][6];

void solve() {

    int n, x, y, z;

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

    vl a(n);

    auto sg = [&](ll v, int j) -> int {

        ll b = v / 5;

        int r = v % 5;

        if(b < sz(step[x][y][z])) {

            return step[x][y][z][b][r][j];

        }

        else {

            b -= sz(step[x][y][z]);

            b %= sz(period[x][y][z]);

            return period[x][y][z][b][r][j];

        }

    };

    ll tot = 0;

    for(auto &v : a) {

        scanf("%lld", &v);

        tot ^= sg(v, 0);

    }

    int ans = 0;

    array <int, 3> w = {x, y, z};

    for(auto &v : a) {

        ll cur = tot ^ sg(v, 0);

        for(int j : {0, 1, 2}) {

            if(cur == sg(max(0ll, v - w[j]), j))

                ans++;

        }

    }

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

}

int main() {

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

        for(int y = 1; y <= 5; y++) {

            for(int z = 1; z <= 5; z++) {

                set <BLOCK> S;

                vector <array<int, 3>> sg;

                vector <BLOCK> block_sg;

                array <int, 3> w = {x, y, z};

                for(int j = 0; ; j += 5) {

                    BLOCK block;

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

                        array <int, 3> nsg;

                        if(k == 0) nsg = {0, 0, 0};

                        else for(int i : {0, 1, 2}) {

                            vi v;

                            for(int j : {0, 1, 2}) {

                                if(!i || i != j) {

                                    v.pb(sg[max(0, k - w[j])][j]);

                                }

                            }

                            nsg[i] = mex(v);

                        }

                        block[k - j] = nsg;

                        sg.pb(nsg);

                    }

                    if(S.count(block)) {

                        bool f = false;

                        for(int q = 0; q < sz(block_sg); q++) {

                            if(!f && block_sg[q] == block)

                                f = true;

                            if(!f) {

                                step[x][y][z].pb(block_sg[q]);

                            }

                            else {

                                period[x][y][z].pb(block_sg[q]);

                            }

                        }

                        break;

                    }

                    block_sg.pb(block);

                    S.insert(block);

                }

            }

        }

    }

    int tc;

    scanf("%d", &tc);

    while(tc--) {

        solve();

    }

    return 0;

}


E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.The chemical structure of this flower can be represented as a string pp. From the unencrypted papers included, Rin already knows the length nn of that string, and she can also conclude that the string contains at most three distinct letters: "C" (as in Carbon), "H" (as in Hydrogen), and "O" (as in Oxygen).At each moment, Rin can input a string ss of an arbitrary length into the artifact's terminal, and it will return every starting position of ss as a substring of pp.However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific:  The artifact only contains 7575 units of energy.  For each time Rin inputs a string ss of length tt, the artifact consumes 1t21t2 units of energy.  If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?InteractionThe interaction starts with a single integer tt (1≤t≤5001≤t≤500), the number of test cases. The interaction for each testcase is described below:First, read an integer nn (4≤n≤504≤n≤50), the length of the string pp.Then you can make queries of type "? s" (1≤|s|≤n1≤|s|≤n) to find the occurrences of ss as a substring of pp.After the query, you need to read its result as a series of integers in a line: The first integer kk denotes the number of occurrences of ss as a substring of pp (−1≤k≤n−1≤k≤n). If k=−1k=−1, it means you have exceeded the energy limit or printed an invalid query, and you need to terminate immediately, to guarantee a "Wrong answer" verdict, otherwise you might get an arbitrary verdict because your solution will continue to read from a closed stream. The following kk integers a1,a2,…,aka1,a2,…,ak (1≤a1<a2<…<ak≤n1≤a1<a2<…<ak≤n) denote the starting positions of the substrings that match the string ss.When you find out the string pp, print "! pp" to finish a test case. This query doesn't consume any energy. The interactor will return an integer 11 or 00. If the interactor returns 11, you can proceed to the next test case, or terminate the program if it was the last testcase.If the interactor returns 00, it means that your guess is incorrect, and you should to terminate to guarantee a "Wrong answer" verdict.Note that in every test case the string pp is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might 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 the documentation for other languages.HacksFor hack, use the following format. Note that you can only hack with one test case:The first line should contain a single integer tt (t=1t=1).The second line should contain an integer nn (4≤n≤504≤n≤50) — the string's size.The third line should contain a string of size nn, consisting of characters "C", "H" and "O" only. This is the string contestants will have to find out.ExamplesInputCopy1
4

2 1 2

1 2

0

1OutputCopy

? C

? CH

? CCHO

! CCHH

InputCopy2
5

0

2 2 3

1
8

1 5

1 5

1 3

2 1 2

1OutputCopy

? O

? HHH

! CHHHH

? COO

? COOH

? HCCOO

? HH

! HHHCCOOH

NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.

// wygzgyw

#include <bits/stdc++.h>

using namespace std;

template <typename T> void read(T &t) {

	t=0; char ch=getchar(); int f=1;

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

	do { (t*=10)+=ch-'0'; ch=getchar(); } while ('0'<=ch&&ch<='9'); t*=f;

}

template <typename T> void write(T t) {

	if (t<0) { putchar('-'); write(-t); return; }

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

	putchar('0'+t%10);

}

template <typename T> void writeln(T t) { write(t); puts(""); }

#define MP make_pair

const int xyr=1;

int T,n;

string ans;

char t[60]; double all;

int query(string s) {

	int len=s.size(); all+=1.0/len/len;

	printf("? "); for (int i=0;i<len;i++) putchar(s[i]); puts(""); fflush(stdout);

	int x=0,y;

	if (xyr) {

		scanf("%d",&x);

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

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

			for (int j=y;j<y+len;j++) ans[j]=s[j-y];

		}

	} else {

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

			int flag=1; for (int j=i;j<i+len;j++) flag&=(t[j]==s[j-i]);

			if (flag) {

				x++;

				for (int j=i;j<i+len;j++) ans[j]=t[j];

			}

		}

	}

	return x;

}

int tmp;

vector<char> P[10];

void dfs(int x,string &s) {

	if (tmp<0) return;

	if (x==n) {

		tmp--; if (tmp==0) { ans=s; return; }

		if (query(s)) ans=s,tmp=-1;

		return;

	}

	if (s[x]>0) dfs(x+1,s);

	else {

		for (char &a : P[x]) s[x]=a,dfs(x+1,s); s[x]=0;

	}

}

int main() {

//	freopen("1.txt","r",stdin);

	scanf("%d",&T); while (T--) {

		all=0;

		scanf("%d",&n); if (!xyr) scanf("%s",t);

		ans.resize(n);

		for (int i=0;i<n;i++) ans[i]=0;

		if (n>4) {

			query("CC"),query("CH"),query("CO");

			query("HO"),query("OO");

			for (int i=1;i<n-1;i++) if (!ans[i]) ans[i]='H';

			// ans[1]=O,H

			// ans[n]=C,H

			if (!ans[0]&&!ans[n-1]) {

				ans[0]='O',ans[n-1]='H'; int flag=query(ans)>0;

				if (!flag) ans[0]='O',ans[n-1]='C',flag|=query(ans)>0;

				if (!flag) ans[0]='H',ans[n-1]='C',flag|=query(ans)>0;

				if (!flag) ans[0]='H',ans[n-1]='H';

			} else if (!ans[0]&&ans[n-1]) {

				ans[0]='O'; if (!query(ans)) ans[0]='H';

			} else if (!ans[n-1]&&ans[0]) {

				ans[n-1]='C'; if (!query(ans)) ans[n-1]='H';

			}

		} else {

			int cnt=query("CC")+query("CH")+query("CO");

			if (cnt||query("HO")) {

				for (int i=0;i<=2;i++) P[i]={'O','H'};

				P[3]={'O','H','C'}; tmp=1;

				for (int i=0;i<n;i++) if (!ans[i]) tmp*=(int)P[i].size();

				string ANS=ans; dfs(0,ANS);

			} else if (query("OO")) {

				if (!ans[n-1]&&ans[n-2]) { // OOO*

					ans[n-1]='C'; if (!query(ans)) ans[n-1]='H';

				} else if (!ans[n-1]&&!ans[n-2]) { // OO**

					ans[n-2]='H'; ans[n-1]='C'; if (!query(ans)) ans[n-1]='H';

				}

			} else {

				ans[1]=ans[2]='H';

				query("HHH");

				if (!ans[0]) ans[0]='O';

				if (!ans[3]) ans[3]='C';

			}

		}

		for (int i=0;i<n;i++) assert(ans[i]>0);

		printf("! "); for (int i=0;i<n;i++) putchar(ans[i]); puts(""); fflush(stdout);

		if (!xyr) {

			for (int i=0;i<n;i++) assert(ans[i]==t[i]);

			printf("all=%.5lf\n",all);

		} else scanf("%d",&n);

	}

	return 0;

}

/*

  0. Enough array size? Enough array size? Enough array size? Integer overflow?

  1. Think TWICE, Code ONCE!

  Are there any counterexamples to your algo?

  2. Be careful about the BOUNDARIES!

  N=1? P=1? Something about 0?

  3. Do not make STUPID MISTAKES!

  Time complexity? Memory usage? Precision error?

*/


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

#include <bits/stdc++.h>

#define ms(x, v) memset(x, v, sizeof(x))

#define il __attribute__((always_inline))

#define U(i,l,r) for(int i(l),END##i(r);i<=END##i;++i)

#define D(i,r,l) for(int i(r),END##i(l);i>=END##i;--i)

using namespace std;

typedef unsigned long long ull;

typedef long long ll;

template <typename T> using BS = basic_string<T>;

//const int SZ(1 << 23);

//unsigned char buf[SZ], *S, *Q;

//#define getchar() ((S==Q)&&(Q=buf+fread(S=buf,1,SZ,stdin)),S==Q?EOF:*S++)

template <typename T>

void rd(T& s) {

	int c = getchar();

	T f = 1; s = 0;

	while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); }

	while (isdigit(c)) { s = s * 10 + (c ^ 48); c = getchar(); }

	s *= f;

}

template <typename T, typename... Y>

void rd(T& x, Y&... y) { rd(x), rd(y...); }

template <typename T>

void pr(T s, bool f = 1) {

    if (s < 0) { printf("-"); s = -s; }

    if (!s) return void(f ? printf("0") : 0);

    pr(s / 10, 0);

    printf("%d", (signed)(s % 10));

}

#define meow(...) fprintf(stderr, __VA_ARGS__)

const int N = 2025;

const ll P = 998244353;

ll sub1(ll n) {

	// 求 \sum_1^n 分拆数

	ll f[N] {1}; // 划分数

	U (i, 1, n)

		U (j, i, n)

			(f[j] += f[j - i]) %= P;

	ll ans = 0;

	U (i, 1, n) (ans += f[i]) %= P;

	return ans;

}

ll sub2(ll n) {

	// 构造集合使得 i*t_i <= n，计数

    // 差分则不需要考虑 t_i 减的限制

    // 这样一个 c_i=t_i - t_{i-1}=1 对和的右移为 sum 1..i = i(i-1)/2

    ll f[N] {1};

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

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

            (f[j] += f[j - i * (i + 1) / 2]) %= P;

    ll ans = 0;

    U (i, 1, n) (ans += f[i]) %= P;

    return ans;

}

int n, k;

bool extend(int k, vector<int> v) {

    vector<int> g;

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

        int sum = 0;

        sort(v.rbegin(), v.rend());

        U (i, 0, v.size() - 1) sum += (i + 1) * v[i];

        if (sum > n) return 0;

        if (j + 3 < k && sum > 23) return 0;

        U (i, 0, v.size() - 1)

            U (j, 1, v[i])

                g.push_back(i + 1);

        v.swap(g);

        vector<int>().swap(g);

    }

    return 1;

}

vector<int> v;

ll ans = 0;

bool dfs(int lim) { // 随便嗯分

    if (!extend(k, v)) return 0;

    // clog << lim << ' ' << v.size() << endl;

    ++ans;

    // meow("x");

    // for (int x : v) meow("%d ", x);

    // meow("\n");

    for (int i = lim, flag; ; ++i) {

        v.push_back(i);

        flag = dfs(i);

        v.pop_back();

        if (!flag) return 1;

    }

    return 1;

}

ll sub3() {

    dfs(1);

    return ans - 1;

}

int main() {

    // Sol::main();

    // return 0;

	rd(n, k);

	if (k == 1) exit(printf("%lld", sub1(n)) & 0);

    if (k == 2) exit(printf("%lld", sub2(n)) & 0);

    printf("%lld", sub3());

}


D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5

#include<bits/stdc++.h>
using namespace std;
#define f(i,j,k) for(register int i=j;i<=k;++i)
#define g(i,j,k) for(register int i=j;i>=k;--i)
int n,m,s,l;
int f[303];
int a[303030][10];
int doing(int x){
int p=(1<<m)-1,q;
f(i,0,p)f[i]=0;
f(i,1,n){
q=0;
f(j,1,m)q=(q<<1)+(a[i][j]>=x);
f[q]=i;
}
f(i,0,p)f(j,0,p)if(f[i] && f[j] && (i|j)==p){
s=f[i];l=f[j];
return 1;
}
return 0;
}
int main(){
cin>>n>>m;
f(i,1,n)f(j,1,m)scanf("%d",&a[i][j]);
s=l=1;
int le=1,ri=1e9,mid;
while(le<=ri){
mid=(le+ri)>>1;
if(doing(mid))le=mid+1;
else ri=mid-1;
}
printf("%d %d\n",s,l);
return 0;
}


B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
OutputCopy7
1 5 1 3
2 4 6 1 3 5

#include <iostream>

#include <algorithm>

using namespace std;

int a[110];

bool cmp(int a,int b){

    return a>b;

}

int main()

{

    int t;

    cin>>t;

    while(t--){

        int n;

        cin>>n;

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

            cin>>a[i];

        }

        sort(a+1,a+1+n,cmp);

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

            cout<<a[i]<<' ';

        }

        cout<<endl;

    }

    return 0;

}


A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb.  For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
OutputCopy2
-1
10
-1
1
NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

using vi = vector<ll>;

int main() {

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

  ll t, x, y, a, b;

  cin >> t;

  while (t--) {

    cin >> x >> y >> a >> b;

    if ((y-x) % (a+b)) cout << -1;

    else cout << (y-x)/(a+b);

    cout << '\n';

  }

}


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

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

  MK-1311

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

#include <bits/stdc++.h>

using namespace std;

#define fi first

#define se second

#define pb push_back

#define nl '\n'

#ifdef LOCAL

#include "debug.h"

#else

#define debug(...)

#endif

/*

*/

#define int long long

void solve() {

  int n, it;

  cin >> n >> it;

  vector<int> t(n + 1, 0), l(n + 1, 0), h(n + 1, 0);

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

    cin >> t[i] >> l[i] >> h[i];

  }

  int x = it, y = it;

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

    int time = t[i] - t[i - 1];

    x = max(l[i], x - time);

    y = min(h[i], y + time);

    debug(x, y);

    if(l[i] > y || h[i] < x) {

      cout << "NO" << endl;

      return;

    }

  }

  cout << "YES" << endl;

}

int32_t main() {

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

  int tt = 1;

  cin >> tt;

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

    solve();

  }

  cerr << "time taken : " << (float)clock() / CLOCKS_PER_SEC << " secs" << endl;

  return 0;

}


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

// time-limit: 3000
// problem-url: https://codeforces.com/problemset/problem/1288/E
// clang-format off
#include"bits/stdc++.h"
#include <numeric>
#define mod               1000000007
#define inf               1e18
#define pq                priority_queue
#define pqi               priority_queue<ll>
#define pqimn             priority_queue<ll,vi,greater<ll>>
#define pb                push_back
#define sz(v)             ((int)(v).size())
#define all(v)            (v).begin(),(v).end()
#define ss                second
#define ff                first

using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull = unsigned long long;
template<typename T>
using pair2 = pair<T, T>;
using pii = pair<int, int>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;
template<typename T>
ostream& operator <<(ostream& ostream, vector<T>& v) {for(auto& element : v) {cout << element << " ";}return ostream;}
template<typename T>
istream& operator >>(istream& istream, vector<T>& v) { for(auto& element : v) {cin >> element;}return istream;}
template <typename T> T abs(T x) { return x < 0? -x : x; }
template <typename T> bool chmin(T &x, const T& y) { if (x > y) { x = y; return true; } return false; }
template <typename T> bool chmax(T &x, const T& y) { if (x < y) { x = y; return true; } return false; }

void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>
void __print(const pair<T, V> &x);
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? ", " : ""), __print(i); cerr << "}";}
template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ", "; __print(x.second); cerr << '}';}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifdef DEBUG
#define dbg(x...) cerr << "\e[91m"<<__func__<<":"<<__LINE__<<" [" << #x << "] = ["; _print(x); cerr << "\e[39m" << endl;
#else
#define dbg(x...)
#endif
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;

template <typename T> using o_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <typename T, typename R> using o_map = tree<T, R, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

// find_by_order(0) -> k th element
// order_of_key(k) -> number of elements less than k

// clang-format on

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int n, m;
    cin >> n >> m;
    std::vector<int> a;
    std::vector<int> pos(n, -1);
    o_set<int> s;
    std::vector<int> lans(n), rans(n);
    for (int i = 0; i < n; i++) {
        pos[i] = 0;
        rans[i] = i;
        lans[i] = i;
    }
    for (int i = n - 1; i >= 0; i--) {
        s.order_of_key(n - i - 1);
        pos[i] = n - i - 1;
        s.insert(n - i - 1);
    }
    for (int i = 0; i < m; i++) {
        int k;
        cin >> k;
        k--, a.pb(k);
    }
    for (int i = 0; i < m; i++) {
        chmin(lans[a[i]], 0);
        int z = n - s.order_of_key(pos[a[i]]) - 1;
        s.erase(pos[a[i]]);
        chmax(rans[a[i]], z);
        pos[a[i]] = n + i;
        s.insert(n + i);
        dbg(pos);
    }
    for (int i = 0; i < n; i++) {
        int z = n - s.order_of_key(pos[i]) - 1;
        chmax(rans[i], z);
    }
    for (int i = 0; i < n; i++) {
        cout << lans[i] + 1 << ' ' << rans[i] + 1 << '\n';
    }
    return 0;
}


F. Cow and Vacationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is planning a vacation! In Cow-lifornia; there are nn cities, with n−1n−1 bidirectional roads connecting them. It is guaranteed that one can reach any city from any other city. Bessie is considering vv possible vacation plans, with the ii-th one consisting of a start city aiai and destination city bibi.It is known that only rr of the cities have rest stops. Bessie gets tired easily, and cannot travel across more than kk consecutive roads without resting. In fact, she is so desperate to rest that she may travel through the same city multiple times in order to do so.For each of the vacation plans, does there exist a way for Bessie to travel from the starting city to the destination city?InputThe first line contains three integers nn, kk, and rr (2≤n≤2⋅1052≤n≤2⋅105, 1≤k,r≤n1≤k,r≤n)  — the number of cities, the maximum number of roads Bessie is willing to travel through in a row without resting, and the number of rest stops.Each of the following n−1n−1 lines contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), meaning city xixi and city yiyi are connected by a road. The next line contains rr integers separated by spaces  — the cities with rest stops. Each city will appear at most once.The next line contains vv (1≤v≤2⋅1051≤v≤2⋅105)  — the number of vacation plans.Each of the following vv lines contain two integers aiai and bibi (1≤ai,bi≤n1≤ai,bi≤n, ai≠biai≠bi)  — the start and end city of the vacation plan. OutputIf Bessie can reach her destination without traveling across more than kk roads without resting for the ii-th vacation plan, print YES. Otherwise, print NO.ExamplesInputCopy6 2 1
1 2
2 3
2 4
4 5
5 6
2
3
1 3
3 5
3 6
OutputCopyYES
YES
NO
InputCopy8 3 3
1 2
2 3
3 4
4 5
4 6
6 7
7 8
2 5 8
2
7 1
8 1
OutputCopyYES
NO
NoteThe graph for the first example is shown below. The rest stop is denoted by red.For the first query; Bessie can visit these cities in order: 1,2,31,2,3.For the second query, Bessie can visit these cities in order: 3,2,4,53,2,4,5. For the third query, Bessie cannot travel to her destination. For example, if she attempts to travel this way: 3,2,4,5,63,2,4,5,6, she travels on more than 22 roads without resting.  The graph for the second example is shown below.

// LUOGU_RID: 90825835
#include<cstdio>

#include<vector>

#include<queue>

const int maxn=20;

struct dsu

{

	int n,fa[400005];

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

	void pre(int n){this->n=n;for (int i=1;i<=n;i++) fa[i]=i;}

	void merge(int x,int y){/*printf("Merge %d %d\n",x,y);*/fa[find(x)]=find(y);}

};

dsu ss;

int n,k,c,q,fa[400005][25],col[400005],dep[400005],d[400005],cnt;

std::vector<int> a[400005],p;

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

void dfs(int v,int x,int d)

{

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

	dep[v]=d;

	fa[v][0]=x;

	for (int i=1;i<=maxn;i++) fa[v][i]=fa[fa[v][i-1]][i-1];

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

	{

		int u=a[v][i];

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

		if (u==x) continue;

		dfs(u,v,d+1);

	}

}

void bfs(std::vector<int> s)

{

	std::queue<int> q;

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

	for (int i=0;i<(int)s.size();i++) col[s[i]]=i+1,q.push(s[i]);

	while (!q.empty())

	{

		int v=q.front();q.pop();

		if (d[v]==k) continue;

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

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

		{

			int u=a[v][i];

			if (col[u]) ss.merge(col[v],col[u]);

			else col[u]=col[v],d[u]=d[v]+1,q.push(u);

		}

	}

}

int getfa(int x,int k)

{

	for (int i=maxn;i>=0;i--) if (k&(1<<i)) x=fa[x][i];

	return x;

}

int lca(int x,int y)

{

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

	for (int i=maxn;i>=0;i--) if ((dep[x]-dep[y])&(1<<i)) x=fa[x][i];

	if (x==y) return x;

	for (int i=maxn;i>=0;i--) if (fa[x][i]!=fa[y][i]) x=fa[x][i],y=fa[y][i];

	return fa[x][0];

}

int getdis(int x,int y){return dep[x]+dep[y]-2*dep[lca(x,y)];}

void getstp(int &x,int y,int k)

{

	int d=lca(x,y);

	if (dep[x]-dep[d]>=k) x=getfa(x,k);

	else x=getfa(y,getdis(x,y)-k);

}

int solve(int x,int y)

{

	if (getdis(x,y)<=2*k||col[x]==col[y]&&col[x]&&col[y]) return 1;

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

	getstp(x,y,k),getstp(y,x,k);

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

	int px=col[x],py=col[y];

	return (px&&py&&px==py);

}

int main()

{

	scanf("%d%d%d",&n,&k,&c);cnt=n;

	for (int i=1;i<n;i++){int x,y,p=++cnt;scanf("%d%d",&x,&y);add(x,p),add(p,y);}

	ss.pre(n);

	n=cnt;

	for (int i=1;i<=c;i++){int x;scanf("%d",&x);p.push_back(x);}

	bfs(p);

	dfs(1,1,1);

	for (int i=1;i<=n;i++) col[i]=ss.find(col[i]);

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

	scanf("%d",&q);

	while (q--){int x,y;scanf("%d%d",&x,&y);solve(x,y)?puts("YES"):puts("NO");}

	return 0;

}


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 <iostream>

#include <iomanip>

#include <ostream>

#include <istream>

#include <set>

#include <unordered_set>

#include <map>

#include <unordered_map>

#include <bitset>

#include <vector>

#include <string>

#include <stack>

#include <queue>

#include <deque>

#include <array>

#include <algorithm>

#include <functional>

#include <cmath>

#include <time.h>

#include <random>

#include <chrono>

#include <cassert>

#include <cstring>

#include <limits>

#include <algorithm>

#include <iomanip>

#include <iostream>

#include <list>

#include <numeric>

#include <random>

#include <vector>

using namespace std;

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

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

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

#define F first

#define S second

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

#define time clock() / (double) CLOCKS_PER_SEC

using pii = pair<int, int>;

using ll = long long;

using ld = long double;

const ll infll = (ll)4e18 + 27;

const ll inf = (ll)1e9 + 27;

const ll mod = (ll)1e9 + 7;

#define dbg(x) cout << #x << " = " << (x) << endl

template <typename T, typename T2>

istream& operator>> (istream& in, pair<T, T2>& b) {

    in >> b.first >> b.second;

    return in;

}

template <typename T, typename T2>

ostream& operator<< (ostream& out, const pair<T, T2>& b) {

    out << "{" << b.first << ", " << b.second << "}";

    return out;

}

template <typename T>

istream& operator>> (istream& in, vector<T>& b) {

    for (auto& v : b)

        in >> v;

    return in;

}

template <typename T>

ostream& operator<< (ostream& out, vector<T>& b) {

    for (auto v : b)

        out << v << ' ';

    return out;

}

template <typename T>

void print(T x, string end = "\n") {

    cout << x << end;

}

template <typename T1, typename T2> bool chkmin(T1& x, const T2& y) { return x > y && (x = y, true); }

template <typename T1, typename T2> bool chkmax(T1& x, const T2& y) { return x < y && (x = y, true); }

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

const int N = 310;

int a[N][N];

const int K = 2e6 + 10;

vector<pii> del[K];

vector<pii> add[K];

int sub[K];

struct dsu {

    vector<int> d, p;

    int n = 1;

    void init(int k){

        n = k;

        d.assign(n, 1);

        p.assign(n, 0);

        iota(all(p), 0ll);

    }

    int find(int u){

        if(u == p[u])return u;

        return p[u] = find(p[u]);

    }

    void unite(int u, int v){

        u = find(u);

        v = find(v);

        if(u == v)return;

        if(d[u] < d[v])swap(u, v);

        d[u] += d[v];

        p[v] = u;

    }

};

dsu d;

int n, m;

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

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

void calculate(vector<pii> &event, int coefficient){

    for(auto [xy, index]: event){

        int current = 1;

        int x = xy / m, y = xy % m;

        a[x][y] = 1;

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

            int nx = x + dx[j], ny = y + dy[j];

            if(nx >= 0 && nx < n && ny >= 0 && ny < m && a[nx][ny] == 1 &&  d.find(nx * m + ny) != d.find(x * m + y)){

                current--;

                d.unite(nx * m + ny, x * m + y);

            }

        }

        sub[index] += current * coefficient;

    }

    for(auto [xy, index]: event){

        d.d[xy] = 1;

        d.p[xy] = xy;

        a[xy / m][xy % m] = 0;

    }

}

void solve() {

    cin >> n >> m;

    d.init(K);

    int q;

    cin >> q;

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

        int x, y, c;

        cin >> x >> y >> c;

        x--;y--;

        if(a[x][y] == c)continue;

        add[c].push_back({x * m + y, i});

        del[a[x][y]].push_back({x * m + y, i});

        a[x][y] = c;

    }

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

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

            del[a[i][j]].push_back({i * m + j, q});

    for(int i = 0;i < n;i++) for(int j = 0;j < m;j++) a[i][j] = 0;

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

        reverse(all(del[i]));

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

        calculate(add[i], 1);

    }

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

        calculate(del[i], -1);

    }

    int ans = 1;

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

        ans += sub[i];

        cout << ans << "\n";

    }

}

signed main() {

    ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cout << fixed << setprecision(15);

    int test = 1;

    //cin >> test;

    while (test--)

        solve();

#ifdef home

    cout << "_________________________________" << endl;

    cout << "finished in " << time << " s";

#endif

    return 0;

}

/*

6 9 3

1 9 1

3 8 1

6 9 1

 */


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.

// #pragma GCC optimize "fast-math"
// #pragma GCC optimize("O3,unroll-loops")
// #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#pragma GCC diagnostic ignored "-Wunused-variable"

#include "bits/stdc++.h"
#include "ext/pb_ds/assoc_container.hpp"

using namespace std;
using namespace __gnu_pbds;

#define endl "\n"
#define int long long
// #define ONLINE_JUDGE

#define MULTI  \
    int _T;    \
    cin >> _T; \
    while (_T--)

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

typedef tree<pair<int, int>, null_type,
             less<pair<int, int>>, rb_tree_tag,
             tree_order_statistics_node_update>
    ordered_set_pair;

//////////////////////////////////////-----/////////////////////////////////////////////

const int INF = 1e18;        // infinity
const int mod = 1e9 + 7;     // mod
const int base1 = 972663749; // base1
const int base2 = 998244353; // base2
const int mod1 = 1000000007; // mod1
const int mod2 = 1000000009; // mod2

const double pi = 4 * atan(1);

vector<int> dx = {-1, +1, +0, +0, +1, -1, +1, -1};
vector<int> dy = {+0, +0, +1, -1, +1, -1, -1, +1};

/////////////////////////////////////----////////////////////////////////////////////////

int modpower(int x, int n, int m)
{
    if (n == 0)
        return 1 % m;
    int u = modpower(x, n / 2, m);
    u = (u * u) % m;
    if (n % 2 == 1)
        u = (u * x) % m;
    return u;
}

int modinverse(int i, int MOD)
{
    if (i == 1)
        return 1;
    return (MOD - ((MOD / i) * modinverse(MOD % i, MOD)) % MOD + MOD) % MOD;
}

int lcm(int x1, int x2)
{
    return ((x1 * x2) / __gcd(x1, x2));
}

int bitCount(unsigned int u)
{
    unsigned int uCount;
    uCount = u - ((u >> 1) & 033333333333) - ((u >> 2) & 011111111111);
    return ((uCount + (uCount >> 3)) & 030707070707) % 63;
}

void printVector(vector<int> &array)
{
    int sz = array.size();
    if (sz == 0)
        return;
    for (int i = 0; i < sz - 1; i++)
    {
        cout << array[i] << " ";
    }
    cout << array[sz - 1] << endl;
}

void printArray(int array[], int sz)
{
    for (int i = 0; i < sz - 1; i++)
    {
        cout << array[i] << " ";
    }
    cout << array[sz - 1] << endl;
}

//////////////////////////////////////----main-function----///////////////////////////////////////////
//====================================================================================================
//====================================================================================================

int n, k, mx = INTMAX_MIN, mn = INTMAX_MAX, a[100005], b[100005];

int check(int curr)
{
    for (int i = 1; i <= n; i++)
    {
        if (a[i] == -1)
        {
            b[i] = curr;
        }
        else
        {
            b[i] = a[i];
        }
    }

    int mxdiffernce = 0;

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

        mxdiffernce = max(mxdiffernce, abs(b[i] - b[i + 1]));
    }

    return mxdiffernce;
}

void solve_the_probelm(int test_case)
{

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

        cin >> a[i];
        if (a[i] == -1)
            continue;
        mx = max(mx, a[i]);
        mn = min(mn, a[i]);
    }

    int high = mx, low = mn, mid, ans = 0;
    if (low == INT_MAX && high == INT_MIN)
    {
        cout << "0 0" << endl;
        return;
    }
    while (low <= high)
    {
        mid = low + (high - low) / 2;
        if (check(mid - 1) >= check(mid) && check(mid) <= check(mid + 1))
        {
            ans = mid;
            break;
        }
        else if (check(mid - 1) > check(mid) && check(mid) > check(mid + 1))
            low = mid + 1;
        else if (check(mid - 1) < check(mid) && check(mid) < check(mid + 1))
            high = mid - 1;
    }

    cout << check(ans) << " " << ans << endl;
}
///////////////////////////////////------------------------///////////////////////////////////////////
//====================================================================================================
//====================================================================================================
signed main()
{
    int test_cases = 1;
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif

    cin >> test_cases; ////////////////////////////////////_test_cause___

    for (int test_case = 1; test_case <= test_cases; test_case++)
        solve_the_probelm(test_case);

#ifndef ONLINE_JUDGE
    cout << "\nExecution Time : " << 1.0 * clock() / CLOCKS_PER_SEC << "s ";
#endif

    return 0;
}


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<iostream>

#include <bits/stdc++.h>

#include <ext/numeric>

using namespace std;

//using L = __int128;

#include<ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

using ll = long long;

using ull = unsigned long long;

using ld = long double;

#define nd "\n"

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

#define lol cout <<"i am here"<<nd;

#define py cout <<"YES"<<nd;

#define pp  cout <<"ppppppppppppppppp"<<nd;

#define pn cout <<"NO"<<nd;

#define popcount(x)  __builtin_popcount(x)

#define clz(n) __builtin_clz(n)//31 -x

const  double PI = acos(-1.0);

double EPS = 1e-9;

#define print2(x , y) cout <<x<<' '<<y<<nd;

#define print3(x , y , z) cout <<x<<' '<<y<<' '<<z<<nd;

#define watch(x) cout << (#x) << " = " << x << nd;

const ll N = 4e5+500 , LOG = 22 , inf = 1e8 , SQ= 550 , mod= 1e9+7;//998244353;

template<class container> void print(container v) { for (auto& it : v) cout << it << ' ' ;cout <<endl;}

//template <class Type1 , class Type2>

ll fp(ll a , ll p){ if(!p) return 1; ll v = fp(a , p/2); v*=v;return p & 1 ? v*a : v;  }

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

ll mul (ll a, ll b){

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

}

ll add (ll a , ll b) {

    return (a + b + mod) % mod;

}

template< typename  T > using min_heap = priority_queue <T , vector <T >  , greater < T > > ;

void hi(int tc) {

    map <ll,set<pair<int , int > > > mp;

    ll n; cin >> n;

    vector <ll>a(n);

    for (ll &i : a) cin >> i;

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

        ll c = 0;

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

           c+=a[j];

           mp[c].emplace(i , j);

       }

    }

    vector <pair <int , int > > f;

    for (auto &i : mp){// sum  , vec

        vector <pair <int , int > > ans;

        auto &st= i.second;

        auto it = st.end(); it = prev(it); ans.emplace_back(*it);

        it = prev(it);

        while (it != st.begin()){

           ll L = next(it)->first;

           if (it->second >= L) it = st.erase(it);

           else ans.emplace_back(*it);

           it = prev(it);

        }

        if (it->second < ans.back().first) ans.emplace_back(*it);

        if ((int)ans.size() > (int)f.size())

            f.swap(ans);

    }

    cout << (int) f.size() <<nd;

    for (auto &i : f){

        cout << i.first+1 <<" "<<i.second+1 <<nd;

    }

}

int main(){

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

    int tt = 1 , tc = 0;

  //cin >> tt;

    while(tt--) hi(++tc);

    return 0;

}


C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2
OutputCopy1 2
InputCopy6
OutputCopy2 3
InputCopy4
OutputCopy1 4
InputCopy1
OutputCopy1 1

#include <bits/stdc++.h>

using namespace std;

#define ll long long int

#define mod 1000000007

ll binpow(ll a, ll n)

{

    ll res = 1;

    while (n)

    {

        if (n % 2 == 1)

        {

            n--;

            res = res * a;

        }

        else

        {

            n /= 2;

            a = a * a;

        }

    }

    return res;

}

void solve()

{

    ll n;

    cin >> n;

    ll temp = n;

    map<ll, ll> m;

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

    {

        while (n % i == 0)

        {

            m[i]++;

            n /= i;

        }

    }

    if (n >= 2)

        m[n]++;

    n = temp;

    ll mn = n;

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

    {

        ll res = 1;

        if (n % i == 0)

        {

            for (auto it : m)

            {

                ll x = binpow(it.first, it.second);

                if (i % x == 0)

                {

                    res = res * x;

                }

            }

            mn = min(mn, max(res, n / res));

        }

    }

    cout << mn << " " << n / mn << endl;

}

int main()

{

    ios_base::sync_with_stdio(false);

    solve();

    return 0;

}


A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00:  You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2);  then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.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 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
OutputCopyYES
NO
YES
YES
NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.

/*  بسم الله الرحمن الرحيم  */
#include <bits/stdc++.h>
using namespace std;
#define Ma3rof ios_base::sync_with_stdio(false);cin.tie(NULL);
void solve() {
    int n;
    cin >> n;
    bool odd = false, even = false;
    while (n--) {
        int x;
        cin >> x;
        if(x&1)
            odd = true;
        else
            even = true;
    }
    if (even && odd)
        cout << "NO\n";
    else
        cout << "YES\n";
}
signed main() {
    Ma3rof
    int t = 1;
    cin >> t;
    while (t--) {
        /*       وما تدري نفس ماذا تکسب غدا وما تدري نفس باي ارض تموت      */
        solve();
    }
    return 0;
}


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.

#include<bits/stdc++.h>

using namespace std;

typedef  long long int          ll ;

typedef  long double            ld;

typedef  vector<ll>             vll;

typedef  vector<string>         vs;

typedef  vector<pair<int,int> >  vpi;

typedef  set<ll>                s;

typedef  map<ll,ll>             mll;

typedef  pair<int,int>          pint;

double   pi = 3.14159265359;

#define  FOR(n,v)              for(ll i=1;i<=n;i++) cin>>v[i];

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

#define  pb                    push_back

#define  ttimes(T)             while(T--)

#define  fastIO                ios_base::sync_with_stdio(false);

#define  nl                    "\n";

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

#define  sort_a(v)             sort(all(v));

#define  sort_d(v)             sort(all(v),greater<ll>() );

#define  py                    printf("YES\n");

#define  pn                    printf("NO\n");

#define  pmone                 printf("-1\n");

void solve()

{

    int n,m;

    cin>>n>>m;

    vector<string> v(n+3),v1(m+3);

    FOR(n,v)

    FOR(m,v1)

    int q;

    cin>>q;

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

    {

        int a;

        cin>>a;

        int x,y;

        x = a%n;

        y = (a)%m;

        if(x == 0) x = n;

        if(y == 0) y = m;

        //cout<<"case : "<<i<<" ";

        cout<<v[x]<<v1[y]<<nl;

    }

}

int main()

{

    int t;

   // cin>>t;

    //while(t--)

    solve();

    return 0;

}


C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3
2 4
1 1
1 1
1 2
2 1
2 2

3 4
1 1 1
1 1
1 2
2 2
2 3

4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
OutputCopy2
1
12
NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11.

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

#define int long long

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

#define fre(z) freopen(z".in","r",stdin),freopen(z".out","w",stdout)

using namespace std;

typedef long long ll;

typedef unsigned long long ull;

typedef pair<int,int> Pair;

const double eps=1e-8;

const int inf=2139062143;

#ifdef ONLINE_JUDGE

static char buf[1000000],*p1=buf,*p2=buf,obuf[1000000],*p3=obuf;

#define getchar() p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++

#endif

inline void qread(){}template<class T1,class ...T2>

inline void qread(T1 &a,T2&...b){

    register T1 x=0;register bool f=false;char ch=getchar();

    while(ch<'0') f|=(ch=='-'),ch=getchar();

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

    x=(f?-x:x);a=x;qread(b...);

}inline void dread(){}template<class T1,class ...T2>

inline void dread(T1 &a,T2&...b){

    register double w=0;register ll x=0,base=1;

    register bool f=false;char ch=getchar();

    while(!isdigit(ch)) f|=(ch=='-'),ch=getchar();

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

    w=(f?-x:x);if(ch!='.') return a=w,dread(b...);x=0,ch=getchar();

    while(isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),base*=10,ch=getchar();

    register double tmp=(double)(x/(double)base);w=w+(double)(f?-tmp:tmp);a=w;dread(b...);

}template<class T>void cmax(T &x,T y){if(x<y) x=y;}template<class T>void cmin(T &x,T y){if(x>y) x=y;}

template<class T> T qmax(T x,T y){return x>y?x:y;}

template<class T,class ...Arg> T qmax(T x,T y,Arg ...arg){return qmax(x>y?x:y,arg...);}

template<class T> T qmin(T x,T y){return x<y?x:y;}

template<class T,class ...Arg> T qmin(T x,T y,Arg ...arg){return qmin(x<y?x:y,arg...);}

template<class T> T randint(T l,T r){static mt19937 eng(time(0));uniform_int_distribution<T>dis(l,r);return dis(eng);}

const int MAXN=5e5+7;

int T,n,a[MAXN],m;set<int>s[MAXN];map<set<int>,int>mp;

signed main(){

    qread(T);int i,j;

    while(T--){

        qread(n,m);for(i=1;i<=n;i++) qread(a[i]),s[i].clear();mp.clear();

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

            int u,v;qread(u,v);

            s[v].emplace(u);

        }for(i=1;i<=n;i++) if(!s[i].empty()) mp[s[i]]+=a[i];int ans=0;

        for(auto i:mp){

            if(!ans) ans=i.second;else ans=__gcd(ans,i.second);

        }printf("%lld\n",ans);

    }

    #ifndef ONLINE_JUDGE

    cerr<<"Time: "<<clock()<<endl;

    system("pause > null");

    #endif

    return 0;

}


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

//In The Name of ALLAH

#include <bits/stdc++.h>

using namespace std;

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

#define ll long long

void solve()

{

    ll n,m;cin>>n>>m;

    if(n%m==0) cout<<"YES\n";

    else cout<<"NO\n";

}

int main()

{

    sahadat();

    ll t;cin>>t;

    while(t--){

        solve();

    }

   return 0;

}


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

#pragma GCC optimize("Ofast")

#pragma GCC optimize ("unroll-loops")

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

#include <bits/stdc++.h>

using namespace std;

void solve() {

    int N = 1e5 + 2;

    vector<vector<int>> v(N);

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

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

            if (i % j == 0) {

                v[i].push_back(j);

                v[i].push_back(i / j);

            }

        }

    }

    cout << '\n';

    int q;

    cin >> q;

    while (q--) {

        int a, b, c;

        cin >> a >> b >> c;

        int ans = 1e9;

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

            int d = abs(b - i);

            if (i > c) {

                d += i - c;

            } else {

                d += min(c % i, i - c % i);

            }

            if (i < a) {

                d += a - i;

            } else {

                int mn = 1e9;

                for (int j : v[i]) {

                    mn = min(mn, abs(a - j));

                }

                d += mn;

            }

            ans = min(ans, d);

        }

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

            int d = abs(b - i);

            if (i > c) {

                d += i - c;

            } else {

                d += min(c % i, i - c % i);

            }

            if (i < a) {

                d += a - i;

            } else {

                int mn = 1e9;

                for (int j : v[i]) {

                    mn = min(mn, abs(a - j));

                }

                d += mn;

            }

            if (ans == d) {

                cout << d << '\n';

                if (i < a) {

                    a = i;

                } else {

                    int x = 1e9;

                    for (int j : v[i]) {

                        if (abs(a - x) > abs(a - j)) {

                            x = j;

                        }

                    }

                    a = x;

                }

                cout << a << " " << i << " ";

                if (i > c) {

                    c = i;

                } else {

                    if (c % i < i - c % i) {

                        c -= c % i;

                    } else {

                        c += i - c % i;

                    }

                }

                cout << c;

                break;

            }

        }

        cout << '\n';

    }

}

int main() {

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

    int q = 1;

    // cin >> q;

    while (q--) {

        solve();

        cout << '\n';

    }

}


F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer.

// LUOGU_RID: 101696200
// LUOGU_RID: 101682976

#include<cstdio>

#include<ctime>

#include<iostream>

#include<cmath>

#include<cstring>

#include<cctype>

#include<cstdlib>

#include<vector>

#include<algorithm>

#include<queue>

#include<cassert>

#include<random>

#include<numeric>

#include<functional>

#define fs(i,x,y) for(int i=(x),_=(y);i<=_;++i)

#define fn(i,x,y) for(int i=(x),_=(y);i>=_;--i)

#define tor(i,v,x) for(int i=head[x],v=to[i];i;i=nxt[i],v=to[i])

#define ls(x) ch[x][0]

#define rs(x) ch[x][1]

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

#define pi pair<int,int>

#define fi first

#define se second

//#define int ll

#define DEBUG printf("%s %d\n",__FUNCTION__,__LINE__)

using namespace std;

typedef long long ll;

typedef double db;

typedef long double ldb;

template<typename T>

void read(T &x){

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

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

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

		ch=getchar();

	}

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

	x=f?-x:x;

}

template<typename T,typename...Args>

void read(T &x,Args &...args){

	read(x);read(args...);

}

const int N=1e6+7;

int n,m,ans;

int dep[N];

vector<pi>mx[N];

vector<int>G[N];

vector<int>wt(3,0);

void upd(int x,int y,int z){

	wt[0]=x,wt[1]=y,wt[2]=z;

}

void df(int u,int fa){

	dep[u]=dep[fa]+1;

	mx[u].push_back(mpi(0,u));

	mx[u].push_back(mpi(0,u));

	for(int v:G[u]){

		if(v^fa){

			df(v,u);

			mx[u].push_back(mpi(mx[v][0].fi+1,mx[v][0].se));

		}

	}

	sort(mx[u].begin(),mx[u].end(),[&](pi &lhs,pi &rhs){

		return lhs.fi>rhs.fi;

	});

}

void dfs(int u,int fa){

	sort(mx[u].begin(),mx[u].end(),[&](pi &lhs,pi &rhs){

		return lhs.fi>rhs.fi;

	});

	if(mx[u][0].fi+mx[u][1].fi+mx[u][2].fi>ans){

		ans=mx[u][0].fi+mx[u][1].fi+mx[u][2].fi;

		upd(mx[u][0].se,mx[u][1].se,mx[u][2].se);

	}

//	cout<<"////u:"<<u<<endl;

//	for(pi p:mx[u]){

//		cout<<p.se<<' '<<p.fi<<' '<<"| ";

//	}

//	cout<<endl;

	for(int v:G[u]){

		if(v^fa){

			if(mx[v][0].se==mx[u][0].se){

				mx[v].push_back(mpi(mx[u][1].fi+1,mx[u][1].se));

			}else{

				mx[v].push_back(mpi(mx[u][0].fi+1,mx[u][0].se));

			}

			dfs(v,u);

		}

	}

}

void solve(){

	read(n);//mx和cmx存的就是节点了

	//dfs下放的时候注意下放节点标号和最长长度

	fs(i,1,n-1){

		int x,y;read(x,y);G[x].push_back(y);G[y].push_back(x);

	}

	df(1,0);dfs(1,0);

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

	if(wt[1]==wt[0]||wt[1]==wt[2]){

		fs(i,1,n){

			if(i!=wt[0]&&i!=wt[2]){

				wt[1]=i;break;

			}

		}

	}

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

	for(int nd:wt)printf("%d ",nd);

}

signed main(){

	int T=1;while(T--){

		solve();

	}

	return 0;

}