E. Cartesian Tree time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIldar is the algorithm teacher of William and Harris. Today; Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William.A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows: If the sequence is empty, return an empty tree; Let the position of the maximum element be xx; Remove element on the position xx from the sequence and break it into the left part and the right part (which might be empty) (not actually removing it, just taking it away temporarily); Build cartesian tree for each part; Create a new vertex for the element, that was on the position xx which will serve as the root of the new tree. Then, for the root of the left part and right part, if exists, will become the children for this vertex; Return the tree we have gotten.For example, this is the cartesian tree for the sequence 4,2,7,3,5,6,14,2,7,3,5,6,1:  After teaching what the cartesian tree is, Ildar has assigned homework. He starts with an empty sequence aa.In the ii-th round, he inserts an element with value ii somewhere in aa. Then, he asks a question: what is the sum of the sizes of the subtrees for every node in the cartesian tree for the current sequence aa?Node vv is in the node uu subtree if and only if v=uv=u or vv is in the subtree of one of the vertex uu children. The size of the subtree of node uu is the number of nodes vv such that vv is in the subtree of uu.Ildar will do nn rounds in total. The homework is the sequence of answers to the nn questions.The next day, Ildar told Harris that he has to complete the homework as well. Harris obtained the final state of the sequence aa from William. However, he has no idea how to find the answers to the nn questions. Help Harris!InputThe first line contains a single integer nn (1≤n≤1500001≤n≤150000).The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n). It is guarenteed that each integer from 11 to nn appears in the sequence exactly once.OutputPrint nn lines, ii-th line should contain a single integer  — the answer to the ii-th question.ExamplesInputCopy5
2 4 1 5 3
OutputCopy1
3
6
8
11
InputCopy6
1 2 4 5 6 3
OutputCopy1
3
6
8
12
17
NoteAfter the first round; the sequence is 11. The tree is  The answer is 11.After the second round, the sequence is 2,12,1. The tree is  The answer is 2+1=32+1=3.After the third round, the sequence is 2,1,32,1,3. The tree is  The answer is 2+1+3=62+1+3=6.After the fourth round, the sequence is 2,4,1,32,4,1,3. The tree is  The answer is 1+4+1+2=81+4+1+2=8.After the fifth round, the sequence is 2,4,1,5,32,4,1,5,3. The tree is  The answer is 1+3+1+5+1=111+3+1+5+1=11.

#include <bits/stdc++.h>

#define int long long

using namespace std;

const int maxn=150005,inf=1e18;

int n,a[maxn],pos[maxn];

struct vl

{int sum,mx,sc,cnt;

vl(){sum=0;mx=sc=-inf;cnt=0;}

};

inline vl merge(vl a,vl b)

{

    vl ret;

    ret.sum=a.sum+b.sum;

    ret.mx=max(a.mx,b.mx);

    ret.sc=-inf;

    ret.cnt=0;

    if(a.mx!=ret.mx)ret.sc=max(ret.sc,a.mx);

    else ret.cnt+=a.cnt;

    if(b.mx!=ret.mx)ret.sc=max(ret.sc,b.mx);

    else ret.cnt+=b.cnt;

    if(a.sc!=ret.mx)ret.sc=max(ret.sc,a.sc);

    if(b.sc!=ret.mx)ret.sc=max(ret.sc,b.sc);

    return ret;

}

vl val[maxn<<2];

int tag[maxn<<2],add[maxn<<2],len[maxn<<2];

inline void pushup(int i)

{

    val[i]=merge(val[i<<1],val[i<<1|1]);

    len[i]=len[i<<1]+len[i<<1|1];

}

inline void pushtgmin(int i,int v)

{

    if(v>=val[i].mx)return;

    val[i].sum-=(val[i].mx-v)*val[i].cnt;

    val[i].mx=v;

    tag[i]=min(tag[i],v);

    return;

}

inline void pushtgadd(int i,int v)

{

    add[i]+=v;

    val[i].sum+=len[i]*v;

    if(tag[i]!=inf)tag[i]+=v;

    if(val[i].mx!=-inf)val[i].mx+=v;

    if(val[i].sc!=-inf)val[i].sc+=v;

}

inline void pushdown(int i)

{

    pushtgadd(i<<1,add[i]);

    pushtgadd(i<<1|1,add[i]);

    add[i]=0;

    pushtgmin(i<<1,tag[i]);

    pushtgmin(i<<1|1,tag[i]);

    tag[i]=inf;

}

void update(int i,int l,int r,int L,int R,int v)

{

    if(L>R)return;

    if(L<=l&&r<=R){pushtgadd(i,v);return;}

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

    if(L<=mid)update(i<<1,l,mid,L,R,v);

    if(R>mid)update(i<<1|1,mid+1,r,L,R,v);

    pushup(i);

}

void calcmin(int i,int l,int r,int L,int R,int v)

{

    //if(i==1)printf("#%d %d %d\n",L,R,v);

    if(r<L||l>R||L>R)return;

    if(L<=L&&r<=R&&val[i].sc<v){pushtgmin(i,v);return;}

    if(l==r)return;

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

    calcmin(i<<1,l,mid,L,R,v);

    calcmin(i<<1|1,mid+1,r,L,R,v);

    pushup(i);

}

void build(int i,int l,int r)

{

    len[i]=0;

    val[i].cnt=val[i].sum=0;

    val[i].mx=val[i].sc=-inf;

    tag[i]=inf;add[i]=0;

    if(l==r)return;

    int mid=l+r>>1;

    build(i<<1,l,mid);

    build(i<<1|1,mid+1,r);

}

int query(int i,int l,int r,int p)

{

    if(l==r)return val[i].sum;

    int mid=l+r>>1;

    pushdown(i);

    if(p<=mid)return query(i<<1,l,mid,p);

    else return query(i<<1|1,mid+1,r,p);

}

void modify(int i,int l,int r,int p,int v)

{

    if(l==r)

    {

        val[i].cnt=1;

        val[i].mx=v;

        val[i].sc=-inf;

        val[i].sum=v;

        len[i]=1;

        return;

    }

    int mid=l+r>>1;

    pushdown(i);

    if(p<=mid)modify(i<<1,l,mid,p,v);

    else modify(i<<1|1,mid+1,r,p,v);

    pushup(i);

}

int c[maxn];

int num[maxn];

void uadd(int p,int v){while(p<=n){c[p]+=v;p+=p&-p;}}

int ask(int p){int ret=0;while(p){ret+=c[p];p-=p&-p;}return ret;}

int sum[maxn];

signed main()

{

    scanf("%lld",&n);

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

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

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

    pos[a[i]]=i,num[a[i]]=ask(a[i]),uadd(a[i],1);

    build(1,1,n);

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

    {

        update(1,1,n,pos[i]+1,n,1);

        calcmin(1,1,n,1,pos[i]-1,num[i]);

        modify(1,1,n,pos[i],i);

        int S=0;

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

         //   if(a[j]<=i)

        //        printf("%d ",(x=query(1,1,n,j))),S+=x;

        // putchar('\n');

        //printf("%d\n",val[1].sum);

        sum[i]+=val[1].sum;

    }

    reverse(a+1,a+1+n);

    memset(c,0,sizeof c);

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

    pos[a[i]]=i,num[a[i]]=ask(a[i]),uadd(a[i],1);

    build(1,1,n);

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

    {

        update(1,1,n,pos[i]+1,n,1);

        calcmin(1,1,n,1,pos[i]-1,num[i]);

        modify(1,1,n,pos[i],i);

       // int S=0;

        // for(int j=n,x;j>=1;j--)

        //     if(a[j]<=i)

        //         printf("%d ",i-(x=query(1,1,n,j))+1),S+=x;

        // putchar('\n');

        //printf("%d\n",val[1].sum);

        sum[i]-=i*i-val[1].sum;

    }

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

        printf("%lld\n",sum[i]);

   // putchar('\n');

    return 0;

}


A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

#define ar array

#define vt vector

#define pq priority_queue

#define pu push

#define pub push_back

#define em emplace

#define emb emplace_back

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

#define allr(x) x.rbegin(), x.rend()

#define allp(x, l, r) x.begin() + l, x.begin() + r

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

using namespace std;

using namespace __gnu_pbds;

using ll = long long;

using ld = long double;

using ull = unsigned long long;

template <class T, size_t N>

void re(array <T, N>& x);

template <class T>

void re(vt <T>& x);

template <class T>

void re(T& x) {

    cin >> x;

}

template <class T, class... M>

void re(T& x, M&... args) {

    re(x); re(args...);

}

template <class T>

void re(vt <T>& x) {

    for(auto& it : x)

        re(it);

}

template <class T, size_t N>

void re(array <T, N>& x) {

    for(auto& it : x)

        re(it);

}

template <class T, size_t N>

void wr(array <T, N> x);

template <class T>

void wr(vt <T> x);

template <class T>

void wr(T x) {

    cout << x;

}

template <class T, class ...M>  void wr(T x, M... args) {

    wr(x), wr(args...);

}

template <class T>

void wr(vt <T> x) {

    for(auto it : x)

        wr(it, ' ');

}

template <class T, size_t N>

void wr(array <T, N> x) {

    for(auto it : x)

        wr(it, ' ');

}

inline void Open(const string Name) {

    #ifndef ONLINE_JUDGE

        (void)!freopen((Name + ".in").c_str(), "r", stdin);

        (void)!freopen((Name + ".out").c_str(), "w", stdout);

    #endif

}

void solve() {

    int n, s, k; re(n, s, k);

    vt <int> v(k); re(v);

    int res = (int)(1e9);

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

        if (find(all(v), i) == v.end()) {

            res = min(res, i - s);

            break;

        }

    }

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

        if (find(all(v), i) == v.end()) {

            res = min(res, s - i);

            break;

        }

    }

    wr(res, '\n');

}

int main() {

    ios_base::sync_with_stdio(false);

    cin.tie(nullptr);

    //Open("");

    int t; re(t);

    for(;t;t--) {

        solve();

    }

    return 0;

}


A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way:  Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x;  choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.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.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.


C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.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 nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5
64
32
97
2
12345
OutputCopyYES
2 4 8
NO
NO
NO
YES
3 5 823


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

#include<bits/stdc++.h>

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

using namespace std;

using ll = long long;

int n, k;

deque<int> cur;

void reset() {

	cout << "R" << endl;

	while(!cur.empty()) cur.pop_back();

}

bool add(int x) {

	cur.push_back(x);

	if(cur.size() > k) cur.pop_front();

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

	char c;

	cin >> c;

	return c == 'N';

}

int main() {

	cin.tie(0)->sync_with_stdio(0);

	cin >> n >> k;

	vector<vector<int>> lol;

	int Bs = k>1?k/2:1;

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

		if(lol.empty() || lol.back().size() == Bs) lol.push_back({});

		lol.back().push_back(i);

	}

	auto update = [&](int i) {

		vector<int> ni;

		for(auto x : lol[i]) if(add(x))

			ni.push_back(x);

		lol[i] = ni;

	};

	int m = lol.size();

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

		int g = __gcd(m, i);

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

			vector<int> v { j };

			do {

				v.push_back((v.back() + i)%m);

			} while(v.back() != j);

			v.pop_back();

			for(auto id : v) {

				update(id);

			}

			reset();

			if(v.size() > 2) {

				update(v.back());

				update(v[0]);

				reset();

			}

		}

	}

	int ans = 0;

	for(auto i : lol) ans += i.size();

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

	return 0;

}


A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — 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≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO

#include <bits/stdc++.h>

using namespace std;

int main() {

    int t;

    cin >> t;

    while (t--) {

        int n;

        cin >> n;

        int sum = 0;

        bool odd = false;

        bool even = false;

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

            int x;

            cin >> x;

            sum += x;

            odd |= x % 2 != 0;

            even |= x % 2 == 0;

        }

        if (sum % 2 != 0 || (odd && even))

            cout << "YES" << endl;

        else

            cout << "NO" << 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]

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

typedef pair <int,int> pii;

typedef pair <ll , ll> pll;

#define sp " "

#define nl "\n"

#define F first

#define S second

#define PB push_back

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

const int N = 3e5 + 5;

const int MOD = 1e9 + 7;

const ll INF = 1e18;

void freop(){

    if(fopen("FILE.INP", "r")){

        freopen("FILE.INP", "r", stdin);

        freopen("FILE.OUT", "w", stdout);

    }

}

int n, m;

int a[N], pre[N];

vector <int> seg[4 * N];

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

    if(l == r){

        seg[id].PB(pre[l]);

        return;

    }

    int mid = (l + r) / 2;

    build(id*2, l, mid);

    build(id*2+1, mid+1, r);

    merge(all(seg[id*2]), all(seg[id*2+1]), back_inserter(seg[id]));

}

int get(int id, int l, int r, int u, int v, int val){

    if(r < u || l > v) return 0;

    if(u <= l && r <= v) {

        int pos = lower_bound(all(seg[id]), val) - seg[id].begin();

        return pos;

    }

    int mid = (l + r) / 2;

    return get(id*2, l, mid, u, v, val) + get(id*2+1, mid+1, r, u, v, val);

}

int st[4*N];

void add(int node, int val){

    node += n; st[node] = val;

    for(node /= 2; node > 0; node /= 2)

        st[node] = st[node*2] + st[node*2+1];

}

int query(int lo, int hi){

    lo += n, hi += n;

    int ans = 0;

    while(lo <= hi){

        if(lo % 2 == 1) ans += st[lo++];

        if(hi % 2 == 0) ans += st[hi--];

        lo /= 2, hi /= 2;

    }

    return ans;

}

pii ans[N];

int main(){

    ios_base::sync_with_stdio(0);

    cin.tie(0);

    //freop();

    //srand(time(NULL));

    cin >> n >> m;

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

    map <int, int> pos;

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

        pre[i] = pos[a[i]];

        pos[a[i]] = i;

    }

    build(1, 1, m);

    pos.clear();

    for(int i = 1; i <= n; ++i) ans[i].F = ans[i].S = i;

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

        int val = a[i];

        if(pos[val] == 0){

            ans[val].S = max(ans[val].S, val + query(val + 1, n));

        }

        else{

            int pre = pos[val];

            ans[val].S = max(ans[val].S, 1 + get(1, 1, m, pre + 1, i - 1, pre + 1));

        }

        pos[val] = i;

        ans[val].F = 1;

        add(val, 1);

    }

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

        if(pos[i] == 0){

            ans[i].S = max(ans[i].S, i + query(i + 1, n));

        }

        else{

            int pre = pos[i];

            ans[i].S = max(ans[i].S, 1 + get(1, 1, m, pre + 1, m, pre + 1));

        }

    }

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

        cout << ans[i].F << sp << ans[i].S << nl;

    }

    return 0;

}


B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.

#include <iostream>

#include <iomanip>

#define ll long long

#include <set>

using namespace std;

int main() {

    int t=1;

    while(t--){

        int n; cin>>n;

        float a=0;

        for(float i=n;i>0;i--){

            a=a+(1/i);

        }

        cout<<a<<setprecision(13)<<endl;

    }return 0;}


F. Nora's Toy Boxestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSIHanatsuka - EMber SIHanatsuka - ATONEMENTBack in time; the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.One day, Nora's adoptive father, Phoenix Wyle, brought Nora nn boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO.She labelled all nn boxes with nn distinct integers a1,a2,…,ana1,a2,…,an and asked ROBO to do the following action several (possibly zero) times:  Pick three distinct indices ii, jj and kk, such that ai∣ajai∣aj and ai∣akai∣ak. In other words, aiai divides both ajaj and akak, that is ajmodai=0ajmodai=0, akmodai=0akmodai=0.  After choosing, Nora will give the kk-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty.  After doing so, the box kk becomes unavailable for any further actions. Being amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the largest amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes.Since ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them?As the number of such piles can be very large, you should print the answer modulo 109+7109+7.InputThe first line contains an integer nn (3≤n≤603≤n≤60), denoting the number of boxes.The second line contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤601≤ai≤60), where aiai is the label of the ii-th box.OutputPrint the number of distinct piles having the maximum number of boxes that ROBO_Head can have, modulo 109+7109+7.ExamplesInputCopy3
2 6 8
OutputCopy2
InputCopy5
2 3 4 9 12
OutputCopy4
InputCopy4
5 7 2 9
OutputCopy1
NoteLet's illustrate the box pile as a sequence bb; with the pile's bottommost box being at the leftmost position.In the first example, there are 22 distinct piles possible:   b=[6]b=[6] ([2,6,8]−→−−(1,3,2)[2,8][2,6,8]→(1,3,2)[2,8])  b=[8]b=[8] ([2,6,8]−→−−(1,2,3)[2,6][2,6,8]→(1,2,3)[2,6]) In the second example, there are 44 distinct piles possible:   b=[9,12]b=[9,12] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,3,4)[2,3,4][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,3,4)[2,3,4])  b=[4,12]b=[4,12] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,3,4)[2,3,9][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,3,4)[2,3,9])  b=[4,9]b=[4,9] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,4,3)[2,3,12][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,4,3)[2,3,12])  b=[9,4]b=[9,4] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,4,3)[2,3,12][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,4,3)[2,3,12]) In the third sequence, ROBO can do nothing at all. Therefore, there is only 11 valid pile, and that pile is empty.

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

typedef long long i64;
typedef vector<int> vi;
typedef pair<int,int> pii;

template<typename T>
inline T read(){
    T x=0,f=0;char ch=getchar();
    while(!isdigit(ch)) f|=(ch=='-'),ch=getchar();
    while(isdigit(ch)) x=x*10+(ch^48),ch=getchar();
    return f?-x:x;
}

#define rdi read<int>
#define rdi64 read<i64>
#define fi first
#define se second
#define pb push_back
#define mp make_pair

const int N=65,MOD=1e9+7;

int n,a[N];
vi e[N],_e[N];

i64 C[N][N];
void init(int n){
    for(int i=0;i<=n;i++){
        C[i][0]=1;
        for(int j=1;j<=i;j++)
            C[i][j]=(C[i-1][j-1]+C[i-1][j])%MOD;
    }
}

int id[N];
i64 f[(1<<(N/4))+1][N];
pair<int,i64> solve(const vi &nodes){
    if(nodes.size()==1) {return {0,1};}

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

    vi S,T;
    int cnt=0;
    for(auto x:nodes)
        if(_e[x].empty()) S.pb(x),id[x]=++cnt;
        else T.pb(x);

    static int s[N];
    for(auto x:T){
         s[x]=0;
         for(auto y:_e[x])
             if(id[y]) s[x]|=(1<<(id[y]-1));
    }

    f[0][0]=1;
    for(int i=0;i<(1<<cnt);i++){
        for(int j=0;j<=T.size();j++){
            i64 &v=(f[i][j]%=MOD);
            if(!v) continue;
            int c=0;
            for(auto x:T){
                if((s[x]&i)==s[x]) ++c;
                else if((s[x]&i)||!j) (f[s[x]|i][j+1]+=v)%=MOD;
            }
            if(j<c) f[i][j+1]+=v*(c-j)%MOD;
        }
    }
    pair<i64,int> ret={(int)(nodes.size()-S.size()-1),f[(1<<cnt)-1][T.size()]};
    for(int i=0;i<(1<<cnt);i++)
        for(int j=0;j<=T.size();j++) f[i][j]=0;
    return ret;
}

struct Dsu{
    int f[N];
    void init(int n) {iota(f+1,f+n+1,1);}
    int find(int x) {return x==f[x]?f[x]:f[x]=find(f[x]);}
    void merge(int x,int y) {f[find(x)]=find(y);}
}d;

void solve(){
    d.init(n);
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            if(i==j) continue;
            if(a[j]%a[i]==0)
                e[i].pb(j),_e[j].pb(i),d.merge(i,j);
        }
    }
    static vi buf[N];
    for(int i=1;i<=n;i++) buf[d.find(i)].pb(i);
    i64 ans=1;
    for(int i=1,sum=0;i<=n;i++)
        if(buf[i].size()){
            auto tmp=solve(buf[i]);
            ans=ans*tmp.se%MOD*C[sum+=tmp.fi][tmp.fi]%MOD;
        }
    cout<<ans<<endl;
}

int main(){
#ifdef LOCAL
    freopen(".in","r",stdin);
    freopen(".out","w",stdout);
#endif
    n=rdi();init(n);
    for(int i=1;i<=n;i++) a[i]=rdi();
    solve();
    return 0;
}


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

// RADHASOAMI , WITH THE GRACE OF HUZUR I PROMISE TO FIGHT TILL THE LAST SECOND OF EVERY CONTEST AND CODE TO MY FULL POTENTIAL ......

#include <iostream>
#include <vector>
#include <unordered_map>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <set>
#include <map>
#include <queue>

#define ll long long int
#define mod 1000000007

using namespace std;

// ====================  FUNCTIONS FOR INPUT AND OUTPUT OF VECTORS =======================================================

void input(vector < ll > &arr)
{
   for(int i = 0;i < arr.size();i++)
      cin >> arr[i];
}

void output(vector < ll > &arr)
{
   for(int i = 0;i < arr.size();i++)
      cout << arr[i] << " ";

   cout << "\n";
}

// ==============================  FOR MATHEMATICAL FUNCTIONS =============================================================

ll gcd(ll a,ll b)
{
   if(b==0)
     return a;

   return gcd(b,a%b);
}

ll power(ll a,ll b)
{
    if(b==0)
      return 1;

    if(b==1)
      return a;

    ll smallans=power(a,b/2);
    ll myans=(smallans*smallans)%mod;

    if((b&1))
      myans=(myans*a)%mod;

    return myans;
}

ll multiply(ll a,ll b)
{
   ll ans=((a%mod)*(b%mod))%mod;

   return ans;
}

ll divide(ll a,ll b)
{
   return multiply(a,power(b,mod-2));
}

// ============================ SEGMENT TREE FOR DEFAULT MINIMUM QUERY ==================================================

void manageLazy(vector <ll> &tree,vector <ll> &lazy,ll idx)
{
   tree[2*idx + 1] += lazy[idx];
   lazy[2*idx + 1] += lazy[idx];

   tree[2*idx + 2] += lazy[idx];
   lazy[2*idx + 2] += lazy[idx];

   lazy[idx] = 0;
}

void build(vector <ll> &tree,vector <ll> &arr,ll left,ll right,ll idx)
{
    if(left == right)
    {
       tree[idx] = arr[left];
       return;
    }

    ll mid = (left + right) / 2;
    build(tree , arr , left , mid , 2*idx + 1);
    build(tree , arr , mid + 1 , right , 2*idx + 2);

    tree[idx] = min(tree[2*idx + 1],tree[2*idx + 2]);
}

void update(vector <ll> &tree,vector <ll> &lazy,ll tl,ll tr,ll l,ll r,ll idx,ll val)
{
   if(l > r)
     return;

   if(l == tl && tr == r)
   {
      tree[idx] += val;
      lazy[idx] += val;
      return;
   }

   manageLazy(tree,lazy,idx);
   ll mid = (tl + tr) / 2;

   update(tree,lazy,tl,mid,l,min(r,mid),2*idx + 1,val);
   update(tree,lazy,mid + 1,tr,max(l,mid + 1),r,2*idx + 2,val);

   tree[idx] = min(tree[2*idx + 1],tree[2*idx + 2]);

}

ll query(vector <ll> &tree,vector<ll> & lazy,ll tl,ll tr,ll l,ll r,ll idx)
{
   if(l > r)
     return 1e18;

   if(l <= tl && tr <= r)
     return tree[idx];

   manageLazy(tree,lazy,idx);
   ll mid = (tl + tr) / 2;

   ll a = query(tree,lazy,tl,mid,l,min(r,mid),2*idx + 1);
   ll b = query(tree,lazy,mid + 1,tr,max(l,mid + 1),r,2*idx + 2);

   return min(a,b);
}

// ==================================  SPARSE TABLE FOR DEFAULT MINIMUM QUERY ==================================================

void precompute_min(vector < vector < ll > > &sparsetable , vector < ll > &a)
{
   int n = sparsetable.size();
   int p = sparsetable[0].size();

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

   for(int j = 1;j < p;j++)
   {
      for(int i = 0;i + (1 << j) <= n;i++)
        sparsetable[i][j] = min(sparsetable[i][j - 1] , sparsetable[i + (1 << (j - 1))][j - 1]);
   }

}

ll minquery(vector < vector < ll > > &sparsetable , vector < ll > &log , ll l , ll r)
{
   ll range = r - l + 1;
   if(range == 0)  return sparsetable[l][0];
   ll j = log[range];
   return min(sparsetable[l][j] , sparsetable[r - (1 << j) + 1][j]);
}

//========================== BINARY INDEX TREE =========================================================================

void update(vector<ll> &tree,ll index,ll val)
{
   index++;
   while(index < tree.size())
   {
      tree[index]=(tree[index] + val) %mod;

      index+=index&(-index);
   }
}

ll calculate(vector<ll> &tree,ll index)
{
   ll sum=0;
   index++;
   while(index > 0)
   {
      sum=(sum + tree[index])%mod;

      index-=index&(-index);
   }

   return sum;
}

//=========================== FOR DISJOINT SET UNION ====================================================================

ll findpar(ll p,vector<ll> &parent)
{
    if(parent[p]==p)
     return p;

    parent[p]=findpar(parent[p],parent);

    return parent[p];
}

void merge(ll a, ll b,vector<ll> &parent,vector<ll> &size_)
{
    a = findpar(a,parent);
    b = findpar(b,parent);

    if (a != b)
    {
        if (size_[a] < size_[b])
             swap(a, b);

        parent[b] = a;
        size_[a] += size_[b];
    }
}

//   ====================================== FOR STORING AND COUNTING THE PRIMES USING SIEVE ============================

void sieve(vector<bool> &primes,vector<ll> &count)
{
   for(int i=2;i<primes.size();i++)
   {
      if(primes[i])
      {
         count.push_back(i);
         for(int j=i*i;j<primes.size();j+=i)
           primes[j]=false;
      }
   }
}

// =====================================================================================================================

void solve()
{
   ll n, m;
   cin >> n >> m;

   vector < ll > arr(n, 0);
   input(arr);

   ll poss = 0;
   for(int i = 1;i < arr.size();i++) poss += arr[i];
   poss = min(poss, m - arr[0]);

   cout << (arr[0] + poss) << "\n";

}

int main()
{
   ios_base::sync_with_stdio(false);
   cin.tie(NULL);
   cout.tie(NULL);
   #ifndef ONLINE_JUDGE
      freopen("input2.txt", "r", stdin);
      freopen("output.txt", "w", stdout);
   #endif

   int t;
   cin >> t;

   while(t--)
   {

      solve();

   }

   return 0;
}


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

#include<bits/stdc++.h>

using namespace std;

typedef long long ll;

int h[200001];

int main()

{

	ios::sync_with_stdio(0);

	cin.tie(0);

	cout.tie(0);

	int n, a, b, k, ans;

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

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

	{

		cin>>h[i];

		h[i] %= (a+b);

		if(h[i]>=1&&h[i]<=a)

		{

			h[i] = 0;

		}

		else if(h[i]==0)

		{

			h[i] = a+b;

			h[i] = h[i]%a==0?(h[i]/a-1):(h[i]/a);

		}

		else

		{

			h[i] = h[i]%a==0?(h[i]/a-1):(h[i]/a);

		}

	}

	ans = 0;

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

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

	{

		if(h[i]==0)

		{

			++ans;

		}

		else

		{

			if(k>=h[i])

			{

				k -= h[i];

				++ans;

			}

			else break;

		}

	}

	cout<<ans<<"\n";

	return 0;

}


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

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

using pii = pair<int, int>;

#define out(x) cout << #x << '=' << x << endl;

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

int main(void) {

    ios::sync_with_stdio(false);

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

    int t = 1;

    //cin >> t;

    while (t--) {

    	ll h;

    	int n;

    	cin >> h >> n;

    	vector<ll> a(n);

    	ll sum = 0;

    	ll hh = h;

    	int ch = 0;

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

    		cin >> a[i];

    		sum += a[i];

    		hh += a[i];

    		if (hh <= 0) {

    			cout << i + 1 << endl;

    			ch = 1;

    			break;

			}

		}

		if (ch) continue;

		if (sum >= 0) {

			cout << -1 << endl;

		} else {

			ll left = 0;

			ll right = -(h - sum - 1) / sum;

			auto check = [&](ll rounds) -> ll {

				if (h + (__int128) rounds * sum <= 0) return rounds * n;

				ll health = h + rounds * sum;

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

					health += a[i - 1];

					//out()

					//out(health);

					if (health <= 0) {

						return rounds * n + i;

					}

				}

				return -1;

			};

			ll ans = -1;

			while (left <= right) {

				ll mid = left + (right - left) / 2;

				ll days = check(mid);

				if (days == -1) {

					left = mid + 1;

				} else {

					right = mid - 1;

					ans = days;

				}

			}

			cout << ans << endl;

		}

	}

}


A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
OutputCopyNO
YES
YES
NO
NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb.

#include<bits/stdc++.h>

using namespace std;

#define int long long

#define PII pair<int,int>

#define x first

#define y second

const int N=1e5+10;

string a,b,c;

void solve()

{

	cin>>a>>b>>c;

	bool f=0;

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

		if(a[i]!=c[i]&&b[i]!=c[i])

	{

		f=1;

		break;

	}

	if(f)

		cout<<"NO\n";

	else

		cout<<"YES\n";

	return;

}

signed main()

{

	ios::sync_with_stdio(false);

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

	int T=1;

	cin>>T;

	while(T--)

		solve();

	return 0;

}


F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33.

/*

     ॐ त्र्यम्बकं यजामहे सुगन्धिं पुष्टिवर्धनम् |

     उर्वारुकमिव बन्धनान्मृत्योर्मुक्षीय माऽमृतात् ||

*/

#include <bits/stdc++.h>

using namespace std;

#define int long long int

#define endl "\n"

const int N = 2e5 + 5;

const int inf = 1e18;

int mod = 1e9 + 7;

int power(int a, int b)

{

  int ans = 1;

  while (b > 0)

  {

    if (b & 1)

    {

      ans = (ans * a) % mod;

    }

    a = (a * a) % mod;

    b >>= 1;

  }

  return ans;

}

// vector<int> c(N), dp(N), ans(N), g[N];

int n;

vector<int> a;

vector<vector<int>> gr;

void dfs1(int u, int p)

{

  for (int v : gr[u])

  {

    if (v != p)

    {

      dfs1(v, u);

      a[u] += max(0ll, a[v]);

    }

  }

}

void dfs2(int u, int p)

{

  for (int v : gr[u])

  {

    if (v != p)

    {

      a[v] += max(0ll, a[u] - max(0ll, a[v]));

      dfs2(v, u);

    }

  }

}

void solve()

{

  cin >> n;

  a.resize(n);

  gr.resize(n);

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

  {

    cin >> a[i];

    if (a[i] == 0)

      a[i] = -1;

  }

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

  {

    int u, v;

    cin >> u >> v;

    u--, v--;

    gr[u].push_back(v);

    gr[v].push_back(u);

  }

  dfs1(0, -1);

  dfs2(0, -1);

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

    cout << a[i] << " \n"[i == n - 1];

}

int32_t main()

{

  ios_base::sync_with_stdio(false);

  cin.tie(NULL);

  cout.tie(NULL);

  // #ifndef ONLINE_JUDGE

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

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

  // #endif

  int t = 1;

  // cin >> t;

  while (t--)

    solve();

  return 0;

}


B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.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.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES

#include <bits/stdc++.h>
using namespace std;
const int N = 100;
int main(){
	int t;
	cin >> t;
	while (t--) {
		int n, p;
		int a[N], b[N];
		cin >> n >> p;
		for (int i = 0; i < n; i++) cin >> a[i];

		for (int i = 0; i < n; i++) b[i] = 0;
		for (int i = 0; i < p; i++) {
			int x;
			cin >> x;
			b[x-1] = 1;
		}

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n - i - 1; j++) {
				if (b[j] == 1 && a[j] > a[j + 1]) {
					swap(a[j], a[j + 1]);
				}
			}
		}

		bool x = true;
		for (int i = 0; i < n - 1; i++) {
			if (a[i] > a[i + 1]) {
				x = false;
				break;
			}
		}
		if (x == true) cout << "YES" << endl;
		else cout << "NO" << endl;

	}
	return 0;
}


E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3
5 7
10 19
10 18
OutputCopyYES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
NotePictures corresponding to the first and the second test cases of the example:

#include<bits/stdc++.h>

#define ll long long

#define pii pair<int,int>

#define fi first

#define se second

#define pb push_back

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

#define lb long double

#define db double

#define pll pair<ll,ll>

#define debug(a) cout<<"debug: "<<(#a)<<" = "<<a<<'\n'

#define cer(a) cerr<<#a<<'='<<(a)<<"@ line"<<__LINE__<<endl

#define cer2(a,b) cerr<<#a<<'='<<(a)<<','<<#b<<'='<<(b)<<"@ line"<<__LINE__<<endl

#define cer3(a,b,c) cerr<<#a<<'='<<(a)<<','<<#b<<'='<<(b)<<','<<#c<<'='<<(c)<<','<<"@ line"<<__LINE__<<endl

#define pdd pair<db,db>

using namespace std;

const int maxn=2e5+100;

const int mode=1e9+7;

const ll inf=9223372036854775807;

const db eps=1e-6;

ll n,m,a[maxn];

ll sum,ans[maxn],d;

string str;

vector<int>vt;

int vis[maxn];

int par[maxn],ch[maxn];

int now,c,mx;

int get()

{

	int res=now;

	c++;

	if(c==mx)

	{

		now++;

		mx*=2;

		c=1;

	}

	return res;

}

void solve()

{

    cin>>n>>d;

    ll cnt=0;

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

    {

    	ans[i]=i;

    	ch[i]=0;

    	cnt+=i;

	}

	ch[0]=0;

	if(cnt<d)

	{

		cout<<"NO"<<'\n';

		return;

	}

	now=1;

	mx=2;

	c=1;

	ll pos=n-1;

	while(cnt>d)

	{

		int deg=get();

		ll res=cnt-d;

		if(deg>=pos)

		break;

		if(res>=(pos-deg))

		{

			ans[pos]=deg;

			cnt-=(pos-deg);

		}else{

			ans[pos]-=res;

			cnt=d;

			break;

		}

		pos--;

	}

	if(cnt>d)

	{

		cout<<"NO"<<'\n';

		return;

	}

	cout<<"YES"<<'\n';

	ans[0]=0;

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

	{

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

		{

			if(ans[j]==ans[i]-1&&ch[j]<2)

			{

				par[i]=j;

				ch[j]++;

				break;

			}

		}

	}

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

    {

    	cout<<par[i]+1<<" ";

	}

	cout<<'\n';

}

int main(){

	#ifndef ONLINE_JUDGE

		freopen("C:\\Users\\JIAJIEASHI\\Desktop\\in.cpp","r",stdin);

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

	#endif

   ios::sync_with_stdio(false);

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

	int t;

	t=1;

    cin>>t;

	while(t--)

    solve();

	return 0;

}


B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3
2 0
0 2
2 0
OutputCopyYES
1 2 1 InputCopy5
0 1
1 3
2 1
3 0
2 0
OutputCopyYES
2 3 2 1 2

#include<bits/stdc++.h>
using namespace std;
#define int long long
const int maxm=2e3+5;
vector<int>g[maxm];
int c[maxm];
int res[maxm];
int n;
vector<int> dfs(int now){
    vector<int>res;//存子节点
    for(int x:g[now]){
        vector<int>ch=dfs(x);
        for(int v:ch){
            res.push_back(v);
        }
    }
    if(c[now]>res.size()){//如果没法插入说明不可能
        cout<<"NO"<<endl;
        exit(0);
    }
    res.insert(res.begin()+c[now],now);//插到中间
    return res;
}
signed main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        int fa;
        cin>>fa;
        cin>>c[i];
        g[fa].push_back(i);
    }
    vector<int>ans=dfs(0);//0是虚根
    for(int i=0;i<(int)ans.size();i++){//节点赋值
        res[ans[i]]=i;
    }
    cout<<"YES"<<endl;
    for(int i=1;i<=n;i++){//输出答案
        cout<<res[i]<<' ';
    }
    cout<<endl;
    return 0;
}


C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can:   either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki;  or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
OutputCopyYES
YES
NO
NO
YES
NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2.

#include<bits/stdc++.h>

#define ll long long

#define endl "\n"

#define    rep(X,Y)     for(X=0;X<Y;X++)

#define    rep1(X,Y)    for(X=1;X<=Y;X++)

#define ml ll T,g; cin>>T; for(g=0;g<T;g++)

#define nml ll T = 1,g; for(g=0;g<T;g++)

#define pb push_back

#define pll pair<ll , ll>

using namespace std;

int main()

{

#ifndef ONLINE_JUDGE

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

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

#endif

  ll i, j;

  ml {

    ll n , k , x = 0;

    cin >> n >> k;

    map<ll, ll>mp;

    for(i= 0 ; i<=100;i++)

    {

      mp[i] = 0;

    }

    rep(i , n)

    {

      ll a;

      cin >> a;

      ll cnt = 0;

      while (a)

      {

        ll b = a % k;

        mp[cnt] += b;

        cnt++;

        a /= k;

      }

    }

    for (auto it : mp)

    {

      if (it.second > 1)

      {

        x = 1;

        break;

      }

    }

    if (x)cout << "NO" << endl;

    else cout << "YES" << endl;

  }

  return 0;

}


#include <bits/stdc++.h>

using namespace std;

using ll = long long;

using pii = pair<int, int>;

using pll = pair<ll, ll>;

using vi = vector<int>;

using vb = vector<bool>;

using vll = vector<ll>;

using vs = vector<string>;

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

#define SORT(v) sort(ALL(v))

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

#ifdef DLOCAL

#include <local.h>

#else

#define deb(...);

#endif

void solve() {

    int n; cin >> n;

    vi  vec(2);

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

        int v; cin >> v;

        vec[v % 2]++;

    }

    if (vec[1] % 2 || (vec[1] && vec[0])) {

        cout << "YES\n";

    }

    else {

        cout << "NO\n";

    }

}

int main() {

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

    //ifstream cin ("puzzle_name.in");

    //ofstream cout ("puzzle_name.out");

    int t; cin >> t;

    while (t--)

    {

        solve();

    }

    return 0;

}


A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.

// Problem: A. ConneR and the A.R.C. Markland-N

// Contest: Codeforces - Codeforces Round #614 (Div. 2)

// URL: https://codeforces.com/problemset/problem/1293/A

// Memory Limit: 256 MB

// Time Limit: 1000 ms

//

// Powered by CP Editor (https://cpeditor.org)

#include <bits/stdc++.h>

using namespace std;

#define pb push_back

#define endl "\n"

void solve(){

int n,s,k;

cin>>n>>s>>k;

int forw=0;

int back=0;

vector<int>v(k);

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

	cin>>v[i];

}

set<int>st;

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

	st.insert(v[i]);

}

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

// if(st.find(s)!=st.end()){

	// cout<<0<<endl;

	// return;

// }

bool flag1 =false;

bool flag2 =false;

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

	if(st.find(i)==st.end()){

		flag1 =true;

		break;

	}

	forw++;

}

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

	if(st.find(i)==st.end()){

		flag2 =true;

		break;

	}

	back++;

}

if(flag1 && flag2){

int ans = min(forw,back);

cout<<ans<<endl;

}

else if(!flag1 && flag2){

	cout<<back<<endl;

}

else{

cout<<forw<<endl;

}

}

int32_t main(){

    ios_base::sync_with_stdio(false);

    cin.tie(0);

    cout.tie(0);

    int t;

    cin>>t;

    while(t--){

        solve();

    }

    }


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

// https://codeforces.com/problemset/problem/1316/D

#include <iostream>
#include <vector>
#include <string>
#include <utility>

using Point = std::pair<int, int>;
constexpr Point Stop(-1, -1);

struct Test {
    struct Move {
        int dr, dc;
        char cmd, inv_cmd;

        Point apply(int r, int c) const {
            return {r + dr, c + dc};
        }
    };

    static constexpr Move movies[] = {
        {-1, 0, 'U', 'D'},
        {1, 0, 'D', 'U'},
        {0, -1, 'L', 'R'},
        {0, 1, 'R', 'L'},
    };

    int size;
    std::vector<std::vector<Point>> grid;
    std::vector<std::string> result;

    bool in_range(int r, int c) {
        return 0 <= r && r < size && 0 <= c && c < size;
    }

    void dfs(int r, int c, const Point& mark) {
        for (const auto& m: movies) {
            const auto [nr, nc] = m.apply(r, c);
            if (!in_range(nr, nc) || grid[nr][nc] != mark || result[nr][nc] != ' ') {
                continue;
            }
            result[nr][nc] = m.inv_cmd;
            dfs(nr, nc, mark);
        }
    }

public:
    Test(int size):
        size(size),
        grid(size, std::vector<Point>(size)),
        result(size, std::string(size, ' '))
    {}

    bool solve() {
        for (int r = 0; r < size; ++r) {
            for (int c = 0; c < size; c++) {
                if (grid[r][c] == Point(r, c)) {
                    result[r][c] = 'X';
                    dfs(r, c, grid[r][c]);
                }
            }
        }
        for (int r = 0; r < size; ++r) {
            for (int c = 0; c < size; c++) {
                if (result[r][c] != ' ' || grid[r][c] != Stop) {
                    continue;
                }
                for (const auto& m: movies) {
                    const auto [nr, nc] = m.apply(r, c);
                    if (!in_range(nr, nc)) {
                        continue;
                    }
                    if (grid[nr][nc] == Stop) {
                        result[r][c] = m.cmd;
                        if (result[nr][nc] == ' ') {
                            result[nr][nc] = m.inv_cmd;
                        }
                    }
                }
            }
        }
        for (const auto& row: result) {
            if (row.find(' ') != std::string::npos) {
                return false;
            }
        }
        return true;
    }
};

int main() {
    std::ios::sync_with_stdio(false);

    int size;
    std::cin >> size;
    Test test(size);
    for (auto& row: test.grid) {
        for (auto& p: row) {
            std::cin >> p.first >> p.second;
            if (p != Stop) {
                --p.first;
                --p.second;
            }
        }
    }

    if (test.solve()) {
        std::cout << "VALID\n";
        for (const auto& row: test.result) {
            std::cout << row << '\n';
        }
    } else {
        std::cout << "INVALID\n";
    }

    return 0;
}


C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following:  if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem);  otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
OutputCopyYES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO

#include<iostream>

#include<cstring>

#include<vector>

#include<map>

#include<queue>

#include<unordered_map>

#include<cmath>

#include<cstdio>

#include<algorithm>

#include<set>

#include<cstdlib>

#include<stack>

#include<ctime>

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

#define forni(i,n,a) for(int i=n;i>=a;i--)

#define fi first

#define se second

using namespace std;

typedef long long ll;

typedef double db;

typedef pair<int,int> PII;

const double eps=1e-7;

const int N=3e5+7 ,M=2*N , INF=0x3f3f3f3f,mod=1e9+7;

inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();}

while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;}

void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);}

template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);}

template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);}

int T;

int n,m,k;

char str[220];

pair<char,char> w[30];

bool sign;

char ans[30];

bool st[30];

bool path(char ch,char t) {

    int p=ch-'a';

    if(w[p].fi==t||w[p].se==t) return true;

    if(w[p].fi==0) {

        w[p].fi=t;

        return true;

    }else if(w[p].se==0) {

        w[p].se=t;

        return true;

    }else return false;

}

void dfs(int u) {

    if(u==3) {

        int res=0;

        if(w[ans[1]-'a'].fi!=0) res++;

        if(w[ans[1]-'a'].se!=0) res++;

        if(res==2) return ;

        if(res==1&&w[ans[1]-'a'].fi!=ans[2]) return ;

    }

    if(u>3&&u<=27) {

        char a=w[ans[u-2]-'a'].fi,b=w[ans[u-2]-'a'].se;

        if(a!=0&&b==0) {

            if(!(a==ans[u-3]||a==ans[u-1])) {

                return ;

            }

        }else if(a!=0&&b!=0) {

            if(!((a==ans[u-3]&&b==ans[u-1])||(a==ans[u-1]&&b==ans[u-3]))) {

                return ;

            }

        }

    }

    if(u>26) {

        if(w[ans[u-1]-'a'].se!=0) return ;

        if(w[ans[u-1]-'a'].fi!=0&&ans[u-2]!=w[ans[u-1]-'a'].fi) return ;

        sign=true;

        return ;

    }

    for(int i='a';i<='z';i++) {

        if(!st[i-'a']) {

            ans[u]=i;

            st[i-'a']=true;

            dfs(u+1);

            if(sign) return ;

            st[i-'a']=false;

        }

    }

}

void solve() {

    scanf("%s",str+1);

    n=strlen(str+1);

    if(n==1) {

        printf("YES\n");

        for(int i='a';i<='z';i++) printf("%c",i);

        printf("\n");

        return ;

    }

    memset(w,0,sizeof w);

    memset(st,false,sizeof st);

    memset(ans,0,sizeof ans);

    bool flag=true;

    sign=false;

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

        char a=str[i-1],b=str[i];

        if(!path(a,b)) {

            flag=false;

            break;

        }

        if(!path(b,a)) {

            flag=false;

            break;

        }

    }

    int x=0,y=0;

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

        if(w[i].se!=0) x++;

        if(w[i].fi!=0) y++;

    }

    if(y-x<2) flag=false;

    if(!flag) printf("NO\n");

    else {

        dfs(1);

        if(!sign) printf("NO\n");

        else {

            printf("YES\n");

            for(int i=1;i<=26;i++) printf("%c",ans[i]);

            printf("\n");

        }

    }

}

int main() {

    // init();

    // stin();

    scanf("%d",&T);

    // T=1;

    while(T--) solve();

    return 0;

}


A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1)  — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4
6 4 2
2 9 2 3 8 5
4 4 1
2 13 60 4
4 1 3
1 2 2 1
2 2 0
1 2
OutputCopy8
4
1
1
NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element.  the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8];  the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8];  if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element);  if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44.

#include "bits/stdc++.h"

using namespace std;

// #define ORD_SET

// #define ROPE

#ifdef ORD_SET

    #include <ext/pb_ds/assoc_container.hpp>

    #include <ext/pb_ds/tree_policy.hpp>

    using namespace __gnu_pbds;

    template<typename T>

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

#endif

#ifdef ROPE

    #include <ext/rope>

    using namespace __gnu_cxx;

#endif

// #pragma comment(linker, "/stack:200000000")

// #pragma GCC optimize("Ofast")

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

using ll = long long;

using ld = long double;

#define pb push_back

#define ff first

#define ss second

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

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

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

// #define ll int

void freopen(string s) { freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); }

void NotInteractive() { ios_base::sync_with_stdio(false); cin.tie(NULL); }

void pre(ll a) { cout<<fixed<<setprecision(a); }

ll bit(ll x) { return __builtin_popcountll(x); }

ll binpow(ll x, ll y, ll z) { ll pow = 1; while(y) { if(y&1) pow *= x, pow %= z; x *= x, x %= z; y >>= 1; } return pow; }

template<typename T> T gcd(T a, T b) { if(b==0) return a; return gcd(b, a%b); }

template<typename T> T lcm(T a, T b) { return a/gcd(a, b)*b; }

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

struct sn { ll l, r, x; }; // a.swap(b)

ll B = 316;

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

const ll inf = (ll)1e18+7;

const ll MX = LLONG_MAX;

const ll MN = LLONG_MIN;

const ld P = acos(-1.0);

const ll N = (ll)3e5+5;

ll a[N];

void kigash() {

    ll n, m, k;

    cin>>n>>m>>k;

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

    k = min(k, m-1);

    ll d = m-1-k, ans = MN;

    for(ll j=0; j<=k; j++) {

        ll mn = MX;

        for(ll i=0; i<=d; i++) mn = min(mn, max(a[j+i+1], a[j+i+1+n-m]));

        ans = max(ans, mn);

    }

    cout<<ans<<"\n";

    return;

}

signed main(/**/) {

    // freopen("");

    NotInteractive();

    // precalc();

    ll tt = 1;

    cin>>tt;

    for(ll i=1; i<=tt; i++) kigash();

    exit(0);

}


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

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

using namespace std;

int main()

{

	int t;

	cin>>t;

	while(t--)

	{

		int n;

		cin>>n;

		int sum=0,ans=0;

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

		{

			int x;

			cin>>x;

			sum+=x;

			if(x==0)

			{

				sum++,ans++;

			}

		}

		if(sum==0)

		{

			ans++;

		}

		cout<<ans<<endl;

	}

	return 0;

}


A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define MODY ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
signed main(){
  int t;
  cin >> t;
  while(t--){
    int n;
  cin >> n;
  int a[n];
  for (int i = 0; i<n ; i++) cin >> a[i];
  bool found = false;
  for (int i =0; i<n; i++){
    if (a[i]%2==0) {
      cout << 1 << '\n' << i+1;
      found = true;
      break;
    }
  }
  if (!found) {
    if (n==1) cout << -1;
    else cout << 2 << '\n' << 1 << ' ' << 2;
  }
    cout << '\n';

}
}


using namespace std;

#include <bits/stdc++.h>

#define int long long

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

#define mod 1000000007

void solve()

{

    int n;cin>>n;

    int a[n];repp(n)cin>>a[i];

    int sum=0,cnt=0;

    repp(n){

        sum+=a[i];

        if(a[i]==0)

            cnt++;

    }

    if(sum+cnt==0){

        cout<<cnt+1<<endl;

    }

    else{

        cout<<cnt<<endl;

    }

}

#define int int

int main()

{

    std::ios_base::sync_with_stdio(false);

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

    int t;cin>>t;while(t--)

    solve();

    return 0;

}


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

#include<iostream>

#include<algorithm>

#include<string.h>

#include<vector>

using namespace std;

// #define debug(x) cout<<"[debug]"#x<<"="<<x<<endl

typedef long long ll;

typedef long double ld;

typedef pair<int,int> pii;

const double eps=1e-8;

const int INF=0x3f3f3f3f,mod=998244353;

#ifndef ONLINE_JUDGE

#define debug(...)

#include<debug>

#else

#define debug(...)

#endif

const int N=100005;

int n;

int dcq(vector<int> ver,int w)

{

    vector<int> a;

    vector<int> b;

    for(auto x:ver)

    {

        if(x>>w&1) a.push_back(x);

        else b.push_back(x^(1<<w));

    }

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

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

    if(a.empty())

    {

        for(auto &x:b) x^=(1<<w);

        if(w==0) return b.back();

        return dcq(b,w-1);

    }

    else if(b.empty())

    {

        for(auto &x:a) x^=(1<<w);

        if(w==0) return a.back();

        return dcq(a,w-1);

    }

    else

    {

        if(w==0) return min(a.back(),b.back());

        return min(dcq(a,w-1),dcq(b,w-1));

    }

}

int main()

{

    scanf("%d",&n);

    vector<int> ver;

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

    {

        int x;

        scanf("%d",&x);

        ver.push_back(x);

    }

    int res=dcq(ver,30);

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

}


C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math; so he asks for your help.The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer — minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1

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

typedef long long int ll;

int main()
{
	ll n; cin >> n;

	priority_queue<ll> pq;

	ll ans = 0;

	for (ll i = 0; i < n; i++)
	{
		ll x; cin >> x;

		if (pq.empty())
		{
			pq.push(x);
		}
		else
		{
			if (pq.top() > x)
			{
				ans += pq.top() - x;

				pq.pop();

				pq.push(x);
			}

			pq.push(x);
		}
	}
	cout << ans << endl;
}


// CF template, version 3.0

#include <bits/stdc++.h>

using namespace std;

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

#define getTest int t; cin >> t

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

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

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

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

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

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

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

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

#define int long long int

int gcd(int a, int b) {

    if (a == b) return a;

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

}

/*

Segtree:

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

    if (l == r) {

        tree[i] = array[l];

    } else {

        int middle = (l + r) / 2;

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

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

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

    }

}

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

    if (l == r) {

        tree[v] = x;

    } else {

        int middle = (l + r) / 2;

        if (i <= middle) {

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

        } else {

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

        }

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

    }

}

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

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

        return tree[v];

    }

    if (l > r) return 0;

    int middle = (cl + cr) / 2;

    return max(

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

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

    );

}

vector<int> tree(4 * n);

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

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

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

data structure can be changed

*/

signed main() {

    improvePerformance;

    getTest;

    eachTest {

        get(n);

        getList(n, nums);

        int sum = 0;

        int zeroes = 0;

        for (int num: nums) {

            sum += num;

            if (!num) zeroes++;

        }

        int steps = zeroes;

        if (sum + zeroes == 0) steps++;

        out(steps);

        out("\n");

    }

}