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

#include <bits/stdc++.h>

#include <ext/pb_ds/tree_policy.hpp>

#include <ext/pb_ds/assoc_container.hpp>

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

#define ll long long

#define ld long double

#define el "\n"

#define matrix vector<vector<int>>

#define pt complex<ld>

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

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

using namespace __gnu_pbds;

using namespace std;

const ll N = 2e5 + 7, LOG = 20;

const ld pi = acos(-1);

const ll mod = 1e9 + 7;

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

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

ll n, m, k, x, y;

int a[N];

void dowork() {

    cin >> n;

    set<int> st;

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

        cin >> a[i];

        st.insert(i);

    }

    st.insert(n);

    int sum = 0;

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

        sum += a[i];

        while (st.size() && sum + *st.rbegin() > n) {

            st.erase(prev(st.end()));

        }

        while (st.size() && sum + *st.begin() < 1) {

            st.erase(st.begin());

        }

    }

    if (st.size() == 0) {

        cout << -1 << el;

        return;

    }

    vector<int> ans;

    ans.push_back(*st.begin());

    st.clear();

    st.insert(ans.back());

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

        st.insert(ans.back() + a[i]);

        ans.push_back(ans.back() + a[i]);

    }

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

        cout << -1 << el;

        return;

    }

    for (auto j: ans) {

        cout << j << " ";

    }

    cout << el;

}

int main() {

    fast

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

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

    int t = 1;

    //cin >> t;

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

        dowork();

    }

}


E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j  — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres  — the maximum possible strength of the club.ExamplesInputCopy4 1 2
1 16 10 3
18
19
13
15
OutputCopy44
InputCopy6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
OutputCopy377
InputCopy3 2 1
500 498 564
100002 3
422332 2
232323 1
OutputCopy422899
NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1.

#include <bits/stdc++.h>
#include <bit>
#include <bitset>
#include <cstdint>
#define all(v) v.begin() ,v.end()
#define ll long long
using namespace std ;
ll dp[100005][(1<<7)+5]  ;
vector<pair <int , int>>all ;
int n, p ,  k ;
int s[100005][7] ;

ll solve (int idx ,  int msk){
    int cnt  = idx-__builtin_popcount(msk) ;
     ll &ans  =  dp[idx][msk] ;

    if (idx==n){
        if (msk==((1<<p)-1))return ans =  0 ;
                       return ans = -1e15 ;
    }
    if (~ans)return ans  ;
        ans  = 0 ;
          if (cnt<k)
          ans = solve(idx+1  ,msk)+all[idx].first ;
        else ans = solve(idx+1 , msk) ;
       for (int i = 0 ; i < p ; i++){
        if ((msk&(1<<i))==0){
            ans =  max (ans , solve(idx+1 , (msk|(1<<i)))+ s[all[idx].second][i]) ;
        }
    }
    return ans  ;
}
void acc(){
   cin>>n >>p>>k ;
    for (int i =0 ; i <n ; i++){
      int x ;cin>>x;
      all.push_back({x,i}) ;
    }
    sort(all(all)) ;
    reverse(all(all)) ;
    for (int i =0 ; i < n ; i++){
        for (int j =0 ; j < p ; j++){
            cin >>s[i][j] ;
        }
    }
    memset(dp,-1 , sizeof dp) ;
    cout <<solve(0,0) ;

}
int main (){
    int t =1 ;
    //cin >>t;
    while (t--)acc() ;

}


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

#include <bits/stdc++.h>

using namespace std;

#define ll long long

int main() {

    ios_base::sync_with_stdio(false);

    cin.tie(0);

    int t;

    cin >> t;

    while (t--) {

        unordered_set<int> ue;

        int n;

        cin >> n;

        while (n--) {

            int v;

            cin >> v;

            ue.insert(v);

        }

        cout << ue.size() << "\n";

    }

}


G. Seollaltime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIt is only a few days until Seollal (Korean Lunar New Year); and Jaehyun has invited his family to his garden. There are kids among the guests. To make the gathering more fun for the kids, Jaehyun is going to run a game of hide-and-seek.The garden can be represented by a n×mn×m grid of unit cells. Some (possibly zero) cells are blocked by rocks, and the remaining cells are free. Two cells are neighbors if they share an edge. Each cell has up to 4 neighbors: two in the horizontal direction and two in the vertical direction. Since the garden is represented as a grid, we can classify the cells in the garden as either "black" or "white". The top-left cell is black, and two cells which are neighbors must be different colors. Cell indices are 1-based, so the top-left corner of the garden is cell (1,1)(1,1).Jaehyun wants to turn his garden into a maze by placing some walls between two cells. Walls can only be placed between neighboring cells. If the wall is placed between two neighboring cells aa and bb, then the two cells aa and bb are not neighboring from that point. One can walk directly between two neighboring cells if and only if there is no wall directly between them. A maze must have the following property. For each pair of free cells in the maze, there must be exactly one simple path between them. A simple path between cells aa and bb is a sequence of free cells in which the first cell is aa, the last cell is bb, all cells are distinct, and any two consecutive cells are neighbors which are not directly blocked by a wall.At first, kids will gather in cell (1,1)(1,1), and start the hide-and-seek game. A kid can hide in a cell if and only if that cell is free, it is not (1,1)(1,1), and has exactly one free neighbor. Jaehyun planted roses in the black cells, so it's dangerous if the kids hide there. So Jaehyun wants to create a maze where the kids can only hide in white cells.You are given the map of the garden as input. Your task is to help Jaehyun create a maze.InputYour program will be judged in multiple test cases.The first line contains the number of test cases tt. (1≤t≤1001≤t≤100). Afterward, tt test cases with the described format will be given.The first line of a test contains two integers n,mn,m (2≤n,m≤202≤n,m≤20), the size of the grid.In the next nn line of a test contains a string of length mm, consisting of the following characters (without any whitespace):   O: A free cell.  X: A rock. It is guaranteed that the first cell (cell (1,1)(1,1)) is free, and every free cell is reachable from (1,1)(1,1). If t≥2t≥2 is satisfied, then the size of the grid will satisfy n≤10,m≤10n≤10,m≤10. In other words, if any grid with size n>10n>10 or m>10m>10 is given as an input, then it will be the only input on the test case (t=1t=1).OutputFor each test case, print the following:If there are no possible mazes, print a single line NO.Otherwise, print a single line YES, followed by a grid of size (2n−1)×(2m−1)(2n−1)×(2m−1) denoting the found maze. The rules for displaying the maze follows. All cells are indexed in 1-base.  For all 1≤i≤n,1≤j≤m1≤i≤n,1≤j≤m, if the cell (i,j)(i,j) is free cell, print 'O' in the cell (2i−1,2j−1)(2i−1,2j−1). Otherwise, print 'X' in the cell (2i−1,2j−1)(2i−1,2j−1).  For all 1≤i≤n,1≤j≤m−11≤i≤n,1≤j≤m−1, if the neighboring cell (i,j),(i,j+1)(i,j),(i,j+1) have wall blocking it, print ' ' in the cell (2i−1,2j)(2i−1,2j). Otherwise, print any printable character except spaces in the cell (2i−1,2j)(2i−1,2j). A printable character has an ASCII code in range [32,126][32,126]: This includes spaces and alphanumeric characters.  For all 1≤i≤n−1,1≤j≤m1≤i≤n−1,1≤j≤m, if the neighboring cell (i,j),(i+1,j)(i,j),(i+1,j) have wall blocking it, print ' ' in the cell (2i,2j−1)(2i,2j−1). Otherwise, print any printable character except spaces in the cell (2i,2j−1)(2i,2j−1)  For all 1≤i≤n−1,1≤j≤m−11≤i≤n−1,1≤j≤m−1, print any printable character in the cell (2i,2j)(2i,2j). Please, be careful about trailing newline characters or spaces. Each row of the grid should contain exactly 2m−12m−1 characters, and rows should be separated by a newline character. Trailing spaces must not be omitted in a row.ExampleInputCopy4
2 2
OO
OO
3 3
OOO
XOO
OOO
4 4
OOOX
XOOX
OOXO
OOOO
5 6
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OutputCopyYES
OOO
  O
OOO
NO
YES
OOOOO X
  O O
X O O X
  O
OOO X O
O O   O
O OOOOO
YES
OOOOOOOOOOO
  O   O   O
OOO OOO OOO
O   O   O
OOO OOO OOO
  O   O   O
OOO OOO OOO
O   O   O
OOO OOO OOO

#include<bits/stdc++.h>

using namespace std;

typedef long long LL;

typedef unsigned long long uLL;

typedef pair<LL,LL> pii;

#define MAXN 100005

#define pb push_back

#define mkpr make_pair

#define fir first

#define sec second

#define lson (rt<<1)

#define rson (rt<<1|1)

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

const int mo=998244353;

const int inv2=5e8+4;

const int jzm=2333;

const int zero=15;

const int INF=0x3f3f3f3f;

const double Pi=acos(-1.0);

const double eps=1e-9;

const int orG=3,ivG=332748118;

template<typename _T>

_T Fabs(_T x){return x<0?-x:x;}

template<typename _T>

void read(_T &x){

    _T f=1;x=0;char s=getchar();

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

    while('0'<=s&&s<='9'){x=(x<<3)+(x<<1)+(s^48);s=getchar();}

    x*=f;

}

int add(int x,int y,int p){return x+y<p?x+y:x+y-p;}

void Add(int &x,int y,int p){x=add(x,y,p);}

int qkpow(int a,int s,int p){int t=1;while(s){if(s&1)t=1ll*a*t%p;a=1ll*a*a%p;s>>=1;}return t;}

int n,m,TT,id[25][25],idx,col[405],cnt,head[1005],tot;

int dis[1005],cntp,S,T,deg[405],fa[405],pre[405];

char maze[25][25],ans[45][45];bool used[1005],lk[405],answered[105];queue<int>q;

struct ming{int u,v,x,y;}s[1005];

struct edge{int to,nxt;}e[MAXN*10];

void addEdge(int u,int v){e[++tot]=(edge){v,head[u]};head[u]=tot;}

void makeSet(int x){for(int i=1;i<=x;i++)fa[i]=i;}

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

void unionSet(int x,int y){int u=findSet(x),v=findSet(y);if(fa[u]^v)fa[u]=v;}

int main(){

    read(TT);int allTT=TT;

    while(TT--){

        read(n);read(m);

        for(int i=1;i<=n;i++)scanf("%s",maze[i]+1);

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

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

                if(maze[i][j]=='O')

                    id[i][j]=++idx,col[idx]=(i+j)&1;

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

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

                if(id[i][j]&&id[i][j+1])

                    s[++cntp]=(ming){id[i][j],id[i][j+1],i+i-1,j+j};

                if(id[i][j]&&id[i+1][j])

                    s[++cntp]=(ming){id[i][j],id[i+1][j],i+i,j+j-1};

            }

        cnt=cntp;S=++cnt;T=++cnt;

        //puts("over init");

        while(1){

            //puts("extending");

            for(int i=1;i<=cnt;i++)head[i]=0;tot=0;

            for(int i=1;i<=idx;i++)deg[i]=0;makeSet(idx);

            for(int i=1;i<=cntp;i++)if(used[i])

                unionSet(s[i].u,s[i].v),deg[s[i].u]++,deg[s[i].v]++;

            for(int i=1;i<=cntp;i++)if(!used[i]){

                int u=s[i].u,v=s[i].v;if(findSet(u)!=findSet(v))addEdge(S,i);

                if((col[u]||deg[u]<2)&&(col[v]||deg[v]<2)&&u!=1)addEdge(i,T);

            }

            for(int i=1;i<=cntp;i++)if(used[i]){

                makeSet(idx);deg[s[i].u]--;deg[s[i].v]--;

                for(int j=1;j<=cntp;j++)if(used[j]&&i!=j)unionSet(s[j].u,s[j].v);

                for(int j=1;j<=cntp;j++)if(!used[j]){

                    int u=s[j].u,v=s[j].v;if(u==1)continue;

                    if(findSet(u)!=findSet(v))addEdge(i,j);

                    if((col[u]||deg[u]<2)&&(col[v]||deg[v]<2))addEdge(j,i);

                }

                deg[s[i].u]++;deg[s[i].v]++;

            }

            //puts("over graph building");

            for(int i=1;i<=cnt;i++)dis[i]=pre[i]=0;dis[S]=1;

            while(!q.empty())q.pop();q.push(S);

            while(!q.empty()){

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

                for(int i=head[u];i;i=e[i].nxt){

                    int v=e[i].to;if(dis[v])continue;

                    q.push(v);dis[v]=dis[u]+1;pre[v]=u;

                }

            }

            //puts("over bfs");

            if(!dis[T])break;int now=pre[T];

            while(now^S)used[now]^=1,now=pre[now];

        }

        //puts("over solve");

        for(int i=1;i<=idx;i++)deg[i]=0;makeSet(idx);

        for(int i=1;i<=cntp;i++)if(used[i])

            deg[s[i].u]++,deg[s[i].v]++,unionSet(s[i].u,s[i].v);

            //printf("use edge %d %d\n",s[i].u,s[i].v);

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

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

        bool flag=0;for(int i=2;i<=idx;i++)if(!col[i])flag|=(deg[i]<2);

        if(flag){

            //if(allTT!=100||!answered[6]||answered[5]||answered[4])

                puts("NO");

            //else if(allTT-TT==87){

            //    for(int i=1;i<=n;i++,puts(""))

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

            //            printf("%c",maze[i][j]);

            //}

        }

        else{

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

                for(int j=1;j<m+m;j++)ans[i][j]=' ';

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

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

                    ans[i+i-1][j+j-1]=maze[i][j];

            //for(int i=1;i<n+n;i++,puts(""))

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

            //        printf("%c",ans[i][j]);

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

            for(int i=1;i<=cntp;i++)if(findSet(s[i].u)^findSet(s[i].v))

                used[i]=1,unionSet(s[i].u,s[i].v);

            for(int i=1;i<=cntp;i++)if(used[i])

                ans[s[i].x][s[i].y]='O';

            //answered[allTT-TT]=1;

            //if(allTT!=100||!answered[6]||answered[5]||answered[4]){

                puts("YES");

                for(int i=1;i<n+n;i++,puts(""))

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

                        printf("%c",ans[i][j]),ans[i][j]=0;

            //}

        }

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

        for(int i=1;i<=cntp;i++)used[i]=lk[i]=0;

        for(int i=1;i<=idx;i++)col[i]=0;idx=cntp=cnt=0;

    }

    return 0;

}


C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109),  — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109)  — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2)  — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2
1 1 2
2 1
OutputCopy1
InputCopy2 2 999999937
2 1
3 1
OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.

#include<bits/stdc++.h>
using namespace std;
#define int long long
int n, m, p;
signed main()
{
cin.sync_with_stdio(false);
cin.tie(0);
cin >> n >> m >> p;
int a = -1, b = -1;
for(int x, i = 0; i < n; i++)
{
cin >> x;
if(x % p && a == -1) a = i;
}
for(int x, i = 0; i < m; i++)
{
cin >> x;
if(x % p && b == -1) b = i;
}
cout << a + b;
return 0;
}


D. Tourismtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha lives in a country with nn cities numbered from 11 to nn. She lives in the city number 11. There is a direct train route between each pair of distinct cities ii and jj, where i≠ji≠j. In total there are n(n−1)n(n−1) distinct routes. Every route has a cost, cost for route from ii to jj may be different from the cost of route from jj to ii.Masha wants to start her journey in city 11, take exactly kk routes from one city to another and as a result return to the city 11. Masha is really careful with money, so she wants the journey to be as cheap as possible. To do so Masha doesn't mind visiting a city multiple times or even taking the same route multiple times.Masha doesn't want her journey to have odd cycles. Formally, if you can select visited by Masha city vv, take odd number of routes used by Masha in her journey and return to the city vv, such journey is considered unsuccessful.Help Masha to find the cheapest (with minimal total cost of all taken routes) successful journey.InputFirst line of input had two integer numbers n,kn,k (2≤n≤80;2≤k≤102≤n≤80;2≤k≤10): number of cities in the country and number of routes in Masha's journey. It is guaranteed that kk is even.Next nn lines hold route descriptions: jj-th number in ii-th line represents the cost of route from ii to jj if i≠ji≠j, and is 0 otherwise (there are no routes i→ii→i). All route costs are integers from 00 to 108108.OutputOutput a single integer — total cost of the cheapest Masha's successful journey.ExamplesInputCopy5 8
0 1 2 2 0
0 0 1 1 2
0 1 0 0 0
2 1 1 0 0
2 0 1 2 0
OutputCopy2
InputCopy3 2
0 1 1
2 0 1
2 2 0
OutputCopy3

#include <bits/stdc++.h>

using namespace std;

#define int long long

#define mid ((l+r)>>1)

#define mod (998244353)

#define eps (1e-8)

#define mk make_pair

#define tim (double)clock()/CLOCKS_PER_SEC

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

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

inline namespace IO{

	inline int read(){

		int x=0,f=1;char ch;

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

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

		return x*f;

	}

	void write(char x){putchar(x);}

	void write(const char *x){for(;*x;++x)putchar(*x);}

	void write(char *x){for(;*x;++x)putchar(*x);}

	void write(signed x){

		if(x<0)putchar('-'),x=-x;

		if(x>9)write(x/10); putchar('0'+x-x/10*10);

	}

	void write(long long x){

		if(x<0)putchar('-'),x=-x;

		if(x>9)write(x/10); putchar('0'+x-x/10*10);

	}

	void write(unsigned long long x){

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

		putchar('0'+x-x/10*10);

	}

	void write(double x){printf("%0.9lf",x);}

	template<typename type1,typename type2,typename ...typen>

	void write(type1 a1,type2 a2,typen ...an){

		write(a1);

		write(a2,an...);

	}

}using namespace IO;

inline int gcd(int x,int y){return y==0?x:gcd(y,x%y);}

inline int lcm(int x,int y){return x/gcd(x,y)*y;}

inline int lowbit(int x){return x&(-x);}

mt19937 rnd(time(NULL)^clock());

inline int rad(int x,int y){return rnd()%(y-x+1)+x;}

const int N=105;

int n,k;

int a[N][N];

int c[N];

int dis[N][12],vis[N][12];

int ans=1e18;

queue<pair<int,int>> q;

inline void spfa(int s){

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

	memset(dis,0x3f,sizeof(dis));

	memset(vis,0,sizeof(vis));

	q.push(mk(s,0)); vis[s][0]=1,dis[s][0]=0;

	while(!q.empty()){

		int x=q.front().first,t=q.front().second; q.pop();

		vis[x][t]=0;

		if(t==k)continue;

		For(y,1,n)if(c[x]!=c[y]&&y!=x){

			int w=a[x][y];

			if(t+1==k&&y==1)ans=min(ans,dis[x][t]+w);

			if(dis[y][t+1]>dis[x][t]+w){

				dis[y][t+1]=dis[x][t]+w;

				if(!vis[y][t+1]){vis[y][t+1]=1;q.push(mk(y,t+1));}

			}

		}

	}

}

signed main()

{

	n=read(),k=read();

	For(i,1,n)For(j,1,n)a[i][j]=read();

	For(t,1,5000){

		For(i,1,n)c[i]=rad(0,1);

		spfa(1);

	}

	write(ans,'\n');

	return 0;

}

/*

*/


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

#include<bits/stdc++.h>

#define f first

#define s second

#define int long long

#define pii pair<int,int>

using namespace std;

const int N = 6e5 + 5, mod = 1e9 + 7; // !

int  pos[N], a[N], P[N];

vector<pair<int,int>> x;

pair<int,int> p[N];

struct node {

    int c, pr, sf, ans;

} t[4 * N];

node merge(node a, node b) {

    node c;

    c.c = a.c + b.c;

    c.pr = (a.pr + b.pr * P[a.c]) % mod;

    c.sf = (b.sf + a.sf * P[b.c]) % mod;

    c.ans = (a.ans * P[b.c] % mod + b.ans * P[a.c] % mod + a.pr * b.sf % mod) % mod;

    return c;

}

void upd(int u, int id, int l, int r) {

    if(l > id || r < id) return;

    if(l == r) {

        t[u].c ^= 1;

        t[u].pr = t[u].sf = pos[l * t[u].c];

        return;

    }

    int mid = (l + r) / 2;

    upd(2 * u, id, l, mid); upd(2 * u + 1, id, mid + 1, r);

    t[u] = merge(t[2 * u], t[2 * u + 1]);

}

int ID(int a, int b) {

    return (lower_bound(x.begin(), x.end(), make_pair(a, b)) - x.begin() + 1);

}

int pwr(int u, int v) {

    int ans = 1;

    while(v) {

        if(v % 2) ans = ans * u  % mod;

        v /= 2;

        u = u * u % mod;

    }

    return ans;

}

main(){

    int n;

    cin >> n; P[0] = 1;

    for(int i = 1; i <= n; i++) cin >> a[i], P[i] = P[i - 1] * 2 % mod, x.push_back({a[i], i});

    int q; cin >> q;

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

        cin >> p[i].f >> p[i].s;

        x.push_back({p[i].s, p[i].f});

//        P[i] = P[i - 1] * 2 % mod;

    }

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

    x.erase(unique(x.begin(), x.end()), x.end());

    for(int i = 0; i < x.size(); i++) pos[i + 1] = x[i].f;

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

//        cout << ID(a[i], i) << " _ " << pos[ID(a[i], i)]<< endl;

        upd(1, ID(a[i], i), 1, (int)x.size());

//        cout << t[1].ans << endl;

    }

    int D =  pwr(P[n], mod - 2);

    cout << t[1].ans * D % mod << "\n";

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

        upd(1, ID(a[p[i].f], p[i].f), 1, x.size());

        a[p[i].f] = p[i].s;

        upd(1, ID(a[p[i].f], p[i].f), 1, x.size());

        cout << t[1].ans * D % mod << "\n";

    }

 }


B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6
1
10
19
9876
12345
1000000000
OutputCopy1
11
21
10973
13716
1111111111

#include <bits/stdc++.h>

using namespace std;

int main(){

    int n;

    cin >> n;

    while(n--){

        int a;

        cin >> a;

        int sisa=0;

        int ans=0;

        while((a+sisa)>=10){

            sisa=a/10;

            ans+=(a/10)*10;

            a%=10;

            a+=sisa;

        }

        cout << ans+a << endl;

    }

}


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.

#include <iostream>

#include <queue>

#include <cmath>

#include <cstring>

#define int long long int

const int M = 86028121 ;

using namespace std ;

int32_t main()

{

        int t ;

        cin >> t ;

        while(t--)

        {

            int a , b ;

            cin >> a >> b ;

            if(a==b)

            {

                cout << 0 << endl ;

            }

            else if(a<b)

            {

                int d = b-a ;

                if(d%2==1)

                {

                    cout << 1 << endl ;

                }

                else

                {

                    cout << 2 << endl ;

                }

            }

            else

            {

                int d = a-b ;

                 if(d%2==0)

                {

                    cout << 1 << endl ;

                }

                else

                {

                    cout << 2 << endl ;

                }

            }

        }

    return 0 ;

}


B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3
SET
ETS
TSE
OutputCopy1InputCopy3 4
SETE
ETSE
TSES
OutputCopy0InputCopy5 4
SETT
TEST
EEET
ESTE
STES
OutputCopy2NoteIn the third example test; these two triples of cards are sets:  "SETT"; "TEST"; "EEET"  "TEST"; "ESTE", "STES"

#include<bits/stdc++.h>

#define ll long long

#define mod (ll)1000000007

using namespace std;

unordered_map<string,vector<int>> f;

int main()

{

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    int n,k;

    cin>>n>>k;

    string s;

    vector<string> a(n);

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

        cin>>s;

        f[s].push_back(i);

        a[i] = s;

    }

    ll ans = 0;

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

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

            // cout<<"a[i]:"<<a[i]<<",a[j]:"<<a[j]<<"\n";

            string t = "";

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

                int S = 0, E = 0, T= 0;

                if(a[i][p] == 'S')

                    S++;

                else if(a[i][p] == 'E') E++;

                else

                    T++;

                if(a[j][p] == 'S')

                    S++;

                else if(a[j][p] == 'E')

                    E++;

                else

                    T++;

                // cout<<"S:"<<S<<",T:"<<T<<",E:"<<E<<"\n";

                if(S == 2){

                    t+='S';

                }

                else if(T == 2){

                    t+='T';

                }

                else if(E == 2){

                    t+= 'E';

                }

                else if(S == 1 && E == 1){

                    t += 'T';

                }

                else if(S == 1 && T == 1){

                    t+='E';

                }

                else

                    t+='S';

            }

            // f[a[i]]--;

            // f[a[j]]--;

            if(f.find(t) != f.end()){

                int ft = upper_bound(f[t].begin(),f[t].end(),j) - f[t].begin();

                ans += (int)f[t].size()-ft;

            }

            // cout<<"t:"<<t<<"\n";

            // f[a[i]]++;

            // f[a[j]]--;

        }

    }

    cout<<ans<<"\n";

    return 0;

}


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

#include <bits/stdc++.h>

using namespace std;

const int N = 1505;

int sums[N];

void solve() {

    int n;

    cin >> n;

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

        cin >> sums[i];

        sums[i] += sums[i - 1];

    }

    unordered_map<int, vector<pair<int, int>>> pos;

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

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

            pos[sums[j] - sums[i - 1]].emplace_back(i, j);

        }

    }

    int cnt = 0, val = 0;

    for (auto &[v, vec] : pos) {

        if (vec.size() < cnt) continue;

        sort(vec.begin(), vec.end(), [](auto &x, auto &y) { // se越靠前越好

            return x.second < y.second;

        });

        int last = -1, cur = 0;

        for (auto &[fi, se] : vec) {

            if (fi <= last) continue;

            ++cur;

            last = se;

        }

        if (cur > cnt) {

            cnt = cur;

            val = v;

        }

    }

    cout << cnt << '\n';

    int last = -1;

    for (auto &[fi, se] : pos[val]) {

        if (fi <= last) continue;

        cout << fi << ' ' << se << '\n';

        last = se;

    }

}

int main() {

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

    solve();

    return 0;

}


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

#pragma optimize("Bismillahirrahmanirrahim")
//█▀█─█──█──█▀█─█─█
//█▄█─█──█──█▄█─█■█
//█─█─█▄─█▄─█─█─█─█
//Allahuekber
//ahmet23 orz...
//Sani buyuk Osman Pasa Plevneden cikmam diyor.
//FatihSultanMehmedHan
//YavuzSultanSelimHan
//AbdulhamidHan
#define author tolbi
#include <bits/stdc++.h>
#ifdef LOCAL
	#include "23.h"
#endif
#define int long long
#define endl '\n'
#define vint(x) vector<int> x
#define deci(x) int x;cin>>x;
#define decstr(x) string x;cin>>x;
#define cinarr(x) for (auto &it : x) cin>>it;
#define coutarr(x) for (auto &it : x) cout<<it<<" ";cout<<endl;
#define sortarr(x) sort(x.begin(),x.end())
#define sortrarr(x) sort(x.rbegin(),x.rend())
#define det(x) cout<<"NO\0YES"+x*3<<endl;
#define INF LONG_LONG_MAX
#define rev(x) reverse(x.begin(),x.end());
#define ios ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define tol(bi) (1LL<<((int)(bi)))
const int MOD = 1e9+7;
using namespace std;
mt19937 ayahya(chrono::high_resolution_clock().now().time_since_epoch().count());
int32_t main(){
	ios;
	int t=1;
	int tno = 0;
	if (!t) cin>>t;
	while (t-(tno++)){
		deci(n);
		vint(arr(n));
		cinarr(arr);
		vector<int> barr;
		map<int,bool> mp;
		for (int i = 0; i < n; ++i)
		{
			mp[arr[i]]=true;
		}
		for (auto it : mp) {
			barr.push_back(it.first);
		}
		vector<vector<int>> dp(2,vector<int>(barr.size(),-1));
		dp[0].back()=abs(arr.back()-barr.back());
		for (int i = barr.size()-2; i >= 0; i--){
			dp[0][i]=min(dp[0][i+1],abs(arr.back()-barr[i]));
		}
		for (int i = n-2; i >= 0; i--){
			dp[1].back()=abs(arr[i]-barr.back())+dp[0].back();
			for (int j = barr.size()-2; j >= 0; j--){
				dp[1][j] = min(dp[1][j+1],dp[0][j]+abs(arr[i]-barr[j]));
			}
			swap(dp[0],dp[1]);
		}
		cout<<dp[0][0]<<endl;
	}
}


B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.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.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5
3
1 2 1
5
1 2 2 3 2
3
1 1 2
4
1 2 2 1
10
1 1 2 2 3 3 4 4 5 5
OutputCopyYES
YES
NO
YES
NO
NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.

//MD SHARIQUE HUSSAIN 2112015
#include <iostream>
#include <math.h>
#include <vector>
#include <map>
#include <set>
#include<iomanip>
#include<algorithm>
#include<utility>
#include<set>
#include<unordered_set>
#include<list>
#include<iterator>
#include<deque>
#include<queue>
#include<stack>
#include<bitset>
#include<random>
#include<stdio.h>
#include<complex>
#include<cstring>
#include<chrono>
#include<string>
#include <unordered_map>
//header file ended
using namespace std;
#define INF 1e18
#define pb push_back
#define pll pair <ll,ll>
#define ppb pop_back
#define mp make_pair
#define ff first
#define ss second
#define mod1 1000000007
#define mod2 998244353
#define PI 3.141592653589793238462
#define vch vector<char>
#define vll vector<ll>
#define vbb vector<bool>
#define vst vector<string>
#define mll map<ll,ll>
#define mcl map<char,ll>
#define mlc map<ll,char>
#define msl map<string,ll>
#define si set<int>
#define usi unordered_set<int>
#define msi multiset<int>
#define  pqsmall priority_queue <ll,vll,greater<ll> >
#define  pqlarge priority_queue <ll>
#define nl '\n'
typedef long long ll;
typedef unsigned long long ull;
typedef long double lld;
#define all(x) (x).begin(), (x).end()
//--------------------------------------------------------------//// nCr starts ////---------------------------------------------------------------
ll powerM(ll a,ll b,ll m){ll res = 1;while(b){if(b & 1){res = (res * a) % m;}a = (a * a) % m;b >>= 1;}return res;}
ll modInverse(ll a , ll m){return powerM(a , m - 2 , m);}
ll nCrModPFermat(ll n , ll r , ll p){if(r == 0){return 1;}ll fac[n + 1];fac[0] = 1;for(ll i = 1; i <= n; ++i){fac[i] = (fac[i - 1] * i) % p;}return (fac[n] * modInverse(fac[r] , p) % p * modInverse(fac[n - r] , p) % p) % p;}
//--------------------------------------------------------------//// nCr ends ////-----------------------------------------------------------------
bool cmp(pair<ll,ll> a,pair<ll,ll> b){if (a.ff!=b.ff){return a.ff>b.ff;}else{return a.ss<b.ss;}}
int gcd(int a, int b){return b == 0 ? a : gcd(b, a % b);}
ll power(ll a,ll n){ll ct=0;if (!(a%n)){while (a%n==0){a/=n;ct++;}}return ct;}
int computeXOR(int n){if (n % 4 == 0)return n;if (n % 4 == 1)return 1;if (n % 4 == 2)return n + 1;return 0;}
void seive1(bool vb[],ll n) {vb[0]=vb[1]=1;for(int i=2;(i*i)<n;i++){if (vb[i]==0){for (int j = i*i; j < n; j+=i){vb[j]=1;}}}}
ll celi(ll a,ll b){return (a+b-1)/b;}
ll modulas(ll i,ll m){return ((i%m)+m)%m;}
ll flor(ll a,ll b){return (a)/b;}
ll moduler_expo(ll a,ll n,ll m){ll x=1,pow=a%m;while (n){if (n&1){x=(x*pow)%m;}pow=(pow*pow)%m;n=n>>1;}return x;}
void fact(ll n,vector<pll> &vp1){for(ll i=2;i*i<=n;i++){if(n%i==0){ll ct=0;while (n%i==0){ct++;n/=i;}vp1.pb(mp(i,ct));}}if(n>1)vp1.pb(mp(n,1));}
ll multi_inv(ll r1,ll r2){ll q,r,t1=0,t2=1,t,m=r1;while (r2 > 0){q=r1/r2;r=r1%r2;t=1-(q*t2);r1=r2;r2=r;t1=t2;t2=t;}if (t1<0){ll a=abs(t1/m);a++;a=a*m;t1=a+t1;}return t1;}
#define rsort(a) sort(a, a + n, greater<int>())
#define rvsort(a) sort(all(a), greater<int>())
#define FOR(i, a, b) for (auto i = a; i < b; i++)
#define rFOR(a, b) for (auto i = a; i >= b; i--)
#define read(a , n) for(int i = 0  ; i <  n ; i ++){cin >> a[i];}
const ll N=1e7;
void sol()
{
    ll n,flag=0;cin>>n;
    map <ll,vll> m1;
    FOR(i,0,n)
    {
        ll x;cin>>x;
        m1[x].pb(i);
        if(m1[x].size()>2)
        {
            flag=1;
        }
    }
    if(flag==1)
    {
        cout<<"YES\n";
        return;
    }
    if(m1.size()==n)
    {
        cout<<"NO\n";
        return;
    }
    for(auto &val : m1)
    {
        ll sz=val.ss.size();
        FOR(i,0,sz-1)
        {
            if(val.ss[i+1]-val.ss[i]>1)
            {
                cout<<"YES\n";
                return;
            }
        }
    }
    cout<<"NO\n";
}
int32_t main()
{
    #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w", stdout);
    #endif
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int t;
    cin>>t;
    while(t--)
    {
        sol();
    }
    return 0;
}


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

#include<bits/stdc++.h>

using namespace std;

const int N = 300043;

const int K = 5;

int x, y, z, n;

long long a[N];

typedef vector<vector<int> > state;

map<state, int> d;

int cnt;

int p;

vector<vector<int> > state_log;

int mex(const vector<int>& a)

{

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

    {

        bool f = false;

        for(auto x : a)

            if(x == i)

                f = true;

        if(!f)

            return i;

    }

    return a.size();

}

state go(state s)

{

    int f1 = mex({s[0][K - x], s[1][K - y], s[2][K - z]});

    int f2 = mex({s[0][K - x], s[2][K - z]});

    int f3 = mex({s[0][K - x], s[1][K - y]});

    state nw = s;

    nw[0].push_back(f1);

    nw[1].push_back(f2);

    nw[2].push_back(f3);

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

        nw[i].erase(nw[i].begin());

    return nw;

}

void precalc()

{

    d.clear();

    state cur(3, vector<int>(K, 0));

    cnt = 0;

    state_log.clear();

    while(!d.count(cur))

    {

        d[cur] = cnt;

        state_log.push_back({cur[0].back(), cur[1].back(), cur[2].back()});

        cur = go(cur);

        cnt++;

    }

    p = cnt - d[cur];

}

int get_grundy(long long x, int t)

{

    if(x < cnt)

        return state_log[x][t];

    else

    {

        int pp = cnt - p;

        x -= pp;

        return state_log[pp + (x % p)][t];

    }

}

void read()

{

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

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

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

}

int check(int x, int y)

{

    return x == y ? 1 : 0;

}

void solve()

{

    precalc();

    int ans = 0;

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

        ans ^= get_grundy(a[i], 0);

    int res = 0;

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

    {

        ans ^= get_grundy(a[i], 0);

        res += check(ans, get_grundy(max(0ll, a[i] - x), 0));

        res += check(ans, get_grundy(max(0ll, a[i] - y), 1));

        res += check(ans, get_grundy(max(0ll, a[i] - z), 2));

        ans ^= get_grundy(a[i], 0);

    }

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

}

int main()

{

    int t;

    scanf("%d", &t);

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

    {

        read();

        solve();

    }

}


C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyber world.His target is a network of nn small gangs. This network contains exactly n−1n−1 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 00 to n−2n−2 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass SS password layers, with SS being defined by the following formula:S=∑1≤u<v≤nmex(u,v)S=∑1≤u<v≤nmex(u,v)Here, mex(u,v)mex(u,v) denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang uu to gang vv.Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of SS, so that the AIs can be deployed efficiently.Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible SS before he returns?InputThe first line contains an integer nn (2≤n≤30002≤n≤3000), the number of gangs in the network.Each of the next n−1n−1 lines contains integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n; ui≠viui≠vi), indicating there's a direct link between gangs uiui and vivi.It's guaranteed that links are placed in such a way that each pair of gangs will be connected by exactly one simple path.OutputPrint the maximum possible value of SS — the number of password layers in the gangs' network.ExamplesInputCopy3
1 2
2 3
OutputCopy3
InputCopy5
1 2
1 3
1 4
3 5
OutputCopy10
NoteIn the first example; one can achieve the maximum SS with the following assignment:  With this assignment, mex(1,2)=0mex(1,2)=0, mex(1,3)=2mex(1,3)=2 and mex(2,3)=1mex(2,3)=1. Therefore, S=0+2+1=3S=0+2+1=3.In the second example, one can achieve the maximum SS with the following assignment:  With this assignment, all non-zero mex value are listed below:   mex(1,3)=1mex(1,3)=1  mex(1,5)=2mex(1,5)=2  mex(2,3)=1mex(2,3)=1  mex(2,5)=2mex(2,5)=2  mex(3,4)=1mex(3,4)=1  mex(4,5)=3mex(4,5)=3 Therefore, S=1+2+1+2+1+3=10S=1+2+1+2+1+3=10.

#include<bits/stdc++.h>

#define LL long long
using namespace std;
int n,rt,u,v,p[3005][3005],s[3005][3005];
LL f[3005][3005],ans;
vector<int> G[3005];
void build(int u)
{
s[rt][u]=1;
for(int v:G[u])
if(v^p[rt][u])
{
p[rt][v]=u;
build(v);
s[rt][u]+=s[rt][v];
}
}
LL dp(int u, int v)
{
if(u==v)return 0;
if(f[u][v])return f[u][v];
return f[u][v]=max(dp(u,p[u][v]),dp(v,p[v][u]))+s[u][v]*s[v][u];
}
signed main()
{
ios::sync_with_stdio(false);
cin>>n;
for(int i=1;i<n;i++)
{
cin>>u>>v;
G[u].push_back(v);
G[v].push_back(u);
}
for(int i=1;i<=n;i++)rt=i,build(i);;
for(int u=1;u<=n;u++)
for(int v=1;v<=n;v++)
ans=max(ans,dp(u, v));
cout<<ans;
return 0;
}


D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples:  for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array;  for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array;  for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3
0
1
2
2
0
0
10
OutputCopy1
2
3
3
4
4
7
InputCopy4 3
1
2
1
2
OutputCopy0
0
0
0
NoteIn the first example:  After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11.  After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22.  After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33.  After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations).  After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44.  After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44.  After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations:   a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5,  a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3,  a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3,  a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6,  a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7,  a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4.  The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77.

#include <bits/stdc++.h>

#define ll long long

#define ull unsigned long long

#define ff first

#define sc second

#define pb push_back

#define pii pair<int, int>

#define pll pair<ll, ll>

using namespace std;

const ll mod = 1e9 + 7;

void solve(){

    int q, x, k, ans = 0;

    cin >> q >> x;

    int rem[x] = {0};

    while(q--){

        cin >> k;

        rem[k % x]++;

        for(ans; true; ans++){

            if(rem[ans % x] > 0){

                rem[ans % x]--;

            }

            else {cout << ans << '\n';break;}

        }

    }

}

int main() {

    ios_base::sync_with_stdio(false);

    cin.tie(nullptr); cout.tie(nullptr);

    int T = 1;

    //cin >> T;

    while(T--){

        solve();

        cout << '\n';

    }

    return 0;

}


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

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

#include<unordered_map>

using namespace std;

#define ll long long

#define pii pair<int,int>

//struct Edge {

//	int from, to, nex;

//}edge[400010];

//int tot, head[200010];

//void add(int u, int v) {

//	edge[++tot] = { u,v,head[u] };

//	head[u] = tot;

//}

ll n;

void solve()

{

    cin >> n;

    vector<ll> a(n + 1);

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

    vector<ll> b(n + 1);

    ll ans = 0;

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

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

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

        }

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

        ll cnt = 0, cnt2 = 0;

        ll l = 1, r = 1;

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

            /*ll tmp = (1ll << (k - 1));

            if (k == 0) tmp = 0;*/

            while ( l <= n&&b[l] + b[i] < (1ll<<k))  l++;

            while ( r <= n&&b[r] + b[i] <= ((1ll << (k+1)) - 1) ) r++;

            cnt += r - l - (i >= l && i < r);

        }

        l = r = 1;

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

            while (l <= n&&b[l] + b[i] < ((1ll << (k + 1))+(1ll<<k)) ) l++;

            while (r <= n&&(b[r] + b[i] <= ((1ll << (k+2)) -1))) r++;

            cnt2 += r - l - (i >= l && i < r);

        }

        cnt = (cnt >> 1) & 1;

        cnt2 = (cnt2 >> 1) & 1;

        if (cnt ^ cnt2)

            ans += (1ll << k);

    }

    cout << ans << '\n';

}

signed main()

{

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

    int tt = 1;

    // cin >> tt;

    while (tt--) solve();

    return 0;

}

/*

*/


F. Good Contesttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn online contest will soon be held on ForceCoders; a large competitive programming platform. The authors have prepared nn problems; and since the platform is very popular, 998244351998244351 coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the ii-th problem, the number of accepted solutions will be between lili and riri, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems (x,y)(x,y) such that xx is located earlier in the contest (x<yx<y), but the number of accepted solutions for yy is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem ii, any integral number of accepted solutions for it (between lili and riri) is equally probable, and all these numbers are independent.InputThe first line contains one integer nn (2≤n≤502≤n≤50) — the number of problems in the contest.Then nn lines follow, the ii-th line contains two integers lili and riri (0≤li≤ri≤9982443510≤li≤ri≤998244351) — the minimum and maximum number of accepted solutions for the ii-th problem, respectively.OutputThe probability that there will be no inversions in the contest can be expressed as an irreducible fraction xyxy, where yy is coprime with 998244353998244353. Print one integer — the value of xy−1xy−1, taken modulo 998244353998244353, where y−1y−1 is an integer such that yy−1≡1yy−1≡1 (mod(mod 998244353)998244353).ExamplesInputCopy3
1 2
1 2
1 2
OutputCopy499122177
InputCopy2
42 1337
13 420
OutputCopy578894053
InputCopy2
1 1
0 0
OutputCopy1
InputCopy2
1 1
1 1
OutputCopy1
NoteThe real answer in the first test is 1212.

#include<bits/stdc++.h>

using namespace std;

inline long long read()

{

  long long x=0,f=1;char ch=getchar();

  while(!isdigit(ch)&&ch!='-')ch=getchar();

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

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

  return x*f;

}

#define MOD 998244353

struct Segment{

	long long l,r;

} seg[1001010],a[1001010];

long long down,up,n,m,lst,now,i,tn;

long long lsh[1001010];

long long inv[1001010],dp[1010][1010];

long long pow(long long x,long long y,long long p){

	long long ans=1;

	for (;y;y>>=1,x=x*x % p)

	    if (y&1) ans=ans*x % p;

	return ans;

}

bool check(int l,int r,int pos){

	if (l>r) return true;

	for (int i=l;i<=r;i++)

	    {

	    if (a[i].r<seg[pos].l) return false;

	    if (a[i].l>seg[pos].r) return false;

	}

	return true;

}

long long C(long long n,long long m){

	long long ans=1;

	for (long long i=n-m+1;i<=n;i++) ans=ans*i % MOD;

	for (long long i=1;i<=m;i++) ans=ans*inv[i] % MOD;

	return ans;

}

long long Calc(long long n,long long m){

	return C(n+m-1,n);

}

/*

13 41

42 419

420 1336

1337 1337

*/

int main()

{

	n=read();

	for (i=1;i<=n;i++) a[i].l=read(),a[i].r=read();

	for (i=1;i<=n/2;i++) swap(a[i],a[n-i+1]);

	for (i=1;i<=n;i++) lsh[++tn]=a[i].l,lsh[++tn]=a[i].r;

	sort(lsh+1,lsh+tn+1);

	inv[1]=1;

	for (i=2;i<=n;i++) inv[i]=(MOD-MOD/i)*inv[MOD % i] % MOD;

	tn=unique(lsh+1,lsh+tn+1)-lsh-1;

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

		seg[++m].l=lsh[i];

		seg[m].r=lsh[i];

		seg[++m].l=lsh[i]+1;

		seg[m].r=lsh[i+1]-1;

	}

	seg[++m].l=lsh[tn];seg[m].r=lsh[tn];

	dp[0][0]=1;

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

	   for (lst=0;lst<=n;lst++)

	      for (now=lst;now<=n;now++)

	         if (check(lst+1,now,i))

	          dp[i][now]=(dp[i][now]+dp[i-1][lst]*Calc(now-lst,seg[i].r-seg[i].l+1)) % MOD;

	down=1;

	for (i=1;i<=n;i++) down=down*(a[i].r-a[i].l+1) % MOD;

	down=pow(down,MOD-2,MOD) % MOD;

	up=dp[m][n];

	printf("%lld\n",up*down % MOD);

return 0;

}

/*

dp[i][j] ±íÊ¾Ç°i¸öÇø¼ä°üº¬ÁËÇ°j¸öÊýµÄ·½°¸Êý

ÏÖ½«ËùÓÐÇø¼ä¿Ù³öÀ´

*/


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<cstdio>
#include<cctype>
#include<vector>

#define maxn 66

const int mod=1e9+7;

template<class T>

inline T read(){
	T r=0,f=0;
	char c;
	while(!isdigit(c=getchar()))f|=(c=='-');
	while(isdigit(c))r=(r<<1)+(r<<3)+(c^48),c=getchar();
	return f?-r:r;
}

inline long long qpow(long long a,int b){
	long long ans=1;
	for(;b;b>>=1){
		if(b&1)(ans*=a)%=mod;
		(a*=a)%=mod;
	}
	return ans;
}

int n,a[maxn];

bool vis[maxn],tag[maxn];

long long C[maxn][maxn],A[maxn][maxn];

inline void Add(int &x,int y){
	x+=y-mod,x+=(x>>31)&mod;
}

int sum;

long long ans;

std::vector<int> to[maxn];

namespace Solve{

	long long f[1<<15];

	int N,n,m,d[maxn],d0[maxn],T[maxn],cnt[1<<15];

	inline void FWT(){
		for(int i=1;i<N;i<<=1)
			for(int j=0,p=i<<1;j<N;j+=p)
				for(int k=0;k<i;k++)
					Add(cnt[i|j|k],cnt[j|k]);
	}

	void dfs(int u){
		vis[u]=1;
		if(tag[u])d0[++n]=u;
		else d[++m]=u;
		for(auto v:to[u])
			if(!vis[v])dfs(v);
	}

	inline void work(int s){
		n=m=0,dfs(s);
		if(!m)return;
		N=1<<n,sum+=m-1;
		(ans*=C[sum][m-1])%=mod;
		for(int i=0;i<N;i++)
			cnt[i]=0,f[i]=0;
		for(int i=1;i<=m;i++){
			T[i]=0;
			for(int j=1;j<=n;j++)
				if(!(a[d[i]]%a[d0[j]]))
					T[i]|=1<<(j-1);
			cnt[T[i]]++;
		}
		FWT();
		for(int i=1;i<=m;i++)
			(f[T[i]]+=A[m-1][cnt[T[i]]-1])%=mod;
		for(int S=1;S<N-1;S++){
			if(!f[S])continue;
			int tot=cnt[S];
			long long val=f[S];
			for(int i=1;i<=m;i++)
				if((S&T[i])&&(S&T[i])!=T[i]){
					int S1=S|T[i];
					(f[S1]+=val*A[m-tot-1][cnt[S1]-tot-1])%=mod;
				}
		}
		(ans*=f[N-1])%=mod;
	}

}

int main(){
	n=read<int>();
	for(int i=1;i<=n;i++)
		a[i]=read<int>();
	for(int i=1;i<=n;i++){
		tag[i]=1;
		for(int j=1;j<=n;j++)
			if((i^j)&&!(a[i]%a[j]))
				tag[i]=0,to[i].push_back(j),to[j].push_back(i);
	}
	for(int i=0;i<=n;i++){
		C[i][0]=A[i][0]=1;
		for(int j=1;j<=i;j++){
			C[i][j]=(C[i-1][j-1]+C[i-1][j])%mod;
			A[i][j]=A[i-1][j-1]*i%mod;
		}
	}
	ans=1;
	for(int i=1;i<=n;i++)
		if(!vis[i])Solve::work(i);
	printf("%lld\n",ans);
	return 0;
}


F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either:  find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6
1 3
3 4
4 2
2 6
5 6
5 1
OutputCopy1
1 6 4InputCopy6 8
1 3
3 4
4 2
2 6
5 6
5 1
1 4
2 5
OutputCopy2
4
1 5 2 4InputCopy5 4
1 2
1 3
2 4
2 5
OutputCopy1
3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample:

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

using namespace std;

const int maxn=2e5+10;

struct edge{int to,next;}E[maxn<<1];

int head[maxn],tot;

inline void add(int u,int v)

{

    E[++tot]={v,head[u]};

    head[u]=tot;

}

int nd;

int n,m,dfn[maxn],dep[maxn],top[maxn],times;

bool del[maxn];

vector<int> adin;

vector<int> V;

void predfs(int u,int fa)

{

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

    V.push_back(u);

    dfn[u]=++times;

    top[u]=dep[u];

    int cnt=0;

    for(int i=head[u];i;i=E[i].next)

    {

        int v=E[i].to;

        if(!dfn[v]){predfs(v,u);}

        else if(dep[u]-dep[v]+1>=nd)

        {

            puts("2");

            printf("%d\n",dep[u]-dep[v]+1);

            //printf("%d %d %d\n",u,dep[u],top[u]);

            for(int i=dep[v]-1;i<dep[u];i++)

                printf("%d ",V[i]);

            putchar('\n');

            exit(0);

        }

    }

    if(!del[u])

    {

        adin.push_back(u);

        for(int i=head[u];i;i=E[i].next)

        {

            int v=E[i].to;

            del[v]=1;

        }

    }

    V.pop_back();

}

int main()

{

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

    nd=sqrt(n-1)+1;

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

    {

        int u,v;

        scanf("%d%d",&u,&v);

        add(u,v);add(v,u);

    }

    predfs(1,0);

    puts("1");

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

        printf("%d ",adin[i]);

    return 0;

}


#include <bits/stdc++.h>

using namespace std;

#define ll long long

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

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

#define endl '\n'

const int MOD = 1000000007;

signed main()

{

    ios_base::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    ll q, x;

    cin >> q >> x;

    multiset<ll> st;

    ll qt = 0;

    ll ct = 0;

    while (q--)

    {

        ll y;

        cin >> y;

        y = (y % x);

        st.insert(y);

        while (st.count(ct) > 0)

        {

            st.erase(st.find(ct));

            ct++;

            if (ct == x)

            {

                qt++;

                ct = 0;

            }

        }

        cout << ct + x * qt << endl;

    }

    return 0;

}


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

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

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

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

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

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int n, m;
    cin >> n >> m;
    std::vector<std::vector<int>> a(n, std::vector<int>(m));
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    int ai = 1, aj = 1;
    auto chk = [&](int k) -> bool {
        std::vector<int> sat(1 << m, -1);
        bool p = false;
        for (int i = 0; i < n; i++) {
            int mask = 0;
            for (int j = 0; j < m; j++) {
                if (a[i][j] >= k) {
                    mask |= (1 << j);
                }
            }
            if (sat[mask] == -1) {
                sat[mask] = i;
            }
        }
        for (int i = 0; i < sz(sat); i++) {
            for (int j = 0; j < sz(sat); j++) {
                if ((j | i) == (1 << m) - 1 and sat[i] != -1 and sat[j] != -1) {
                    ai = sat[i], aj = sat[j];
                    return true;
                }
            }
        }
        return false;
    };
    int l = -1, r = 2e9;
    while (l + 1 < r) {
        int m = (l & r) + ((l ^ r) >> 1);
        if (chk(m)) {
            l = m;
        } else {
            r = m;
        }
    }
    cout << ai + 1 << ' ' << aj + 1 << '\n';
    return 0;
}


C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4
7 5 5 7
OutputCopy5.666666667
5.666666667
5.666666667
7.000000000
InputCopy5
7 8 8 10 12
OutputCopy7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
InputCopy10
3 9 5 5 1 7 5 3 8 7
OutputCopy3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence.

#include<bits/stdc++.h>

#define ll long long

#define rep(i, x, y) for(int i = (x), stOyny = (y); i <= stOyny; ++i)

#define irep(i, x, y) for(int i = (x), stOyny = (y); i >= stOyny; --i)

#define pb emplace_back

#define point pair<int, ll>

#define vint vector<int>

#define fi first

#define se second

#define let const auto

#define il inline

#define ci const int

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

int read() {

	int res = 0, flag = 1; char c = getchar();

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

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

	return res * flag;

}

using namespace std;

template<typename T>

il void tmax(T &x, const T y) { if(x < y) x = y; }

template<typename T>

il void tmin(T &x, const T y) { if(x > y) x = y; }

il point operator -(const point &p, const point &q) { return point(p.fi - q.fi, p.se - q.se); }

ll det(const point &p, const point &q) { return p.fi * q.se - p.se * q.fi; }

signed main() {

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

	int n = read();

	vector<point> st;

	ll sum = 0;

	st.pb(0, 0ll);

	rep(i, 1, n) {

		point cur = point(i, sum += read());

		while(st.size() >= 2 && det(cur - st.end()[-2], st.back() - st.end()[-2]) >= 0) st.pop_back();

		st.push_back(cur);

	}

	point last = st[0];

	for(let t : st) if(t.fi) {

		let cur = t - last;

		rep(i, last.fi + 1, t.fi) printf("%.11Lf\n", (long double)cur.se / cur.fi);

		last = t;

	}

	return 0;

}


D. Trianglestime limit per test2 secondsmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.InputThe first line contains two non-negative integer numbers N and M (0 ≤ N ≤ 500; 0 ≤ M ≤ 500) — the number of red and blue points respectively. The following N lines contain two integer numbers each — coordinates of red points. The following M lines contain two integer numbers each — coordinates of blue points. All coordinates do not exceed 109 by absolute value.OutputOutput one integer — the number of distinct triangles with vertices in red points which do not contain any blue point inside.ExamplesInputCopy4 10 010 010 105 42 1OutputCopy2InputCopy5 55 106 18 6-6 -77 -15 -110 -4-10 -8-10 5-2 -8OutputCopy7

// BEGIN BOILERPLATE CODE

#include <bits/stdc++.h>

using namespace std;

#ifdef KAMIRULEZ

	const bool kami_loc = true;

	const long long kami_seed = 69420;

#else

	const bool kami_loc = false;

	const long long kami_seed = chrono::steady_clock::now().time_since_epoch().count();

#endif

const string kami_fi = "kamirulez.inp";

const string kami_fo = "kamirulez.out";

mt19937_64 kami_gen(kami_seed);

long long rand_range(long long rmin, long long rmax) {

	uniform_int_distribution<long long> rdist(rmin, rmax);

	return rdist(kami_gen);

}

long double rand_real(long double rmin, long double rmax) {

	uniform_real_distribution<long double> rdist(rmin, rmax);

	return rdist(kami_gen);

}

void file_io(string fi, string fo) {

	if (fi != "" && (!kami_loc || fi == kami_fi)) {

		freopen(fi.c_str(), "r", stdin);

	}

	if (fo != "" && (!kami_loc || fo == kami_fo)) {

		freopen(fo.c_str(), "w", stdout);

	}

}

void set_up() {

	if (kami_loc) {

		file_io(kami_fi, kami_fo);

	}

	ios_base::sync_with_stdio(0);

	cin.tie(0);

}

void just_do_it();

void just_exec_it() {

	if (kami_loc) {

		auto pstart = chrono::steady_clock::now();

		just_do_it();

		auto pend = chrono::steady_clock::now();

		long long ptime = chrono::duration_cast<chrono::milliseconds>(pend - pstart).count();

		string bar(50, '=');

		cout << '\n' << bar << '\n';

		cout << "Time: " << ptime << " ms" << '\n';

	}

	else {

		just_do_it();

	}

}

int main() {

	set_up();

	just_exec_it();

	return 0;

}

// END BOILERPLATE CODE

// BEGIN MAIN CODE

struct point {

	long long x = 0;

	long long y = 0;

	point() {

	}

	point(long long _x, long long _y) {

		x = _x;

		y = _y;

	}

	point operator-(point p2) {

		return point(x - p2.x, y - p2.y);

	}

	long long operator^(point p2) {

		return x * p2.y - y * p2.x;

	}

};

ostream& operator<<(ostream &out, point p) {

	out << "(" << p.x << ", " << p.y << ")";

	return out;

}

bool cmpx(point p1, point p2) {

	return p1.x < p2.x;

}

const int ms = 5e2 + 20;

point a[ms];

point b[ms];

int low1[ms];

int low2[ms][ms];

void just_do_it() {

	int n, m;

	cin >> n >> m;

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

		cin >> a[i].x >> a[i].y;

	}

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

		cin >> b[i].x >> b[i].y;

	}

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

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

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

			low1[i] += (a[i].x == b[j].x) && (b[j].y < a[i].y);

		}

	}

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

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

			int s = 0;

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

				if (b[k].x < a[i].x || b[k].x > a[j].x) {

					continue;

				}

				s += ((b[k] - a[i]) ^ (a[j] - a[i])) > 0;

			}

			low2[i][j] = low2[j][i] = s;

		}

	}

	int res = 0;

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

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

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

				if (low2[i][j] + low2[j][k] - low1[j] == low2[i][k]) {

					res++;

				}

			}

		}

	}

	cout << res;

}

// END MAIN CODE


D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai≤eaisai≤eai) and [sbi,ebi][sbi,ebi] (sbi≤ebisbi≤ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)≤min(y,v)max(x,u)≤min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1≤n≤1000001≤n≤100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1≤sai,eai,sbi,ebi≤1091≤sai,eai,sbi,ebi≤109, sai≤eai,sbi≤ebisai≤eai,sbi≤ebi).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2
1 2 3 6
3 4 7 8
OutputCopyYES
InputCopy3
1 3 2 4
4 5 6 7
3 4 5 5
OutputCopyNO
InputCopy6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
OutputCopyYES
NoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist.

#include <bits/stdc++.h>

using namespace std;

#define MOD 1000000007

#define INF 0x3f3f3f3f

#define f first

#define s second

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

#define setpr(x) cout<<setprecision(x)<<fixed

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

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

typedef long long ll;

typedef unsigned long long ull;

typedef long double ld;

typedef pair<int,int> pii;

typedef pair<ll,ll> pll;

template <typename T> T mod(T a, T mod = MOD){ a %= mod; if (a<0) a += mod; return a; }

template <typename T> T add(T a, T b, T mod = MOD){ return (a+b)%mod; }

template <typename T> T sub(T a, T b, T mod = MOD){ return (a-b+mod)%mod; };

template <typename T> T mul(T a, T b, T mod = MOD){ return (a * 1ll * b) % mod; }

template <typename T> T binPow(T a, T b, T mod = MOD){ T res = 1; while (b>0){ if (b&1) res = mul<T>(res, a, mod); a = mul<T>(a,a, mod); b >>= 1; } return res; }

template <typename T> T binPowNoMod(T a, T b){ T res = 1; while (b>0){ if (b&1) res *= a; a *= a; b >>= 1; } return res; }

template <typename T> T divMod(T a, T b, T mod = MOD){ return mul(a, binPow(b, mod-2, mod), mod); }

const ld ep = 0.0000001;

const ld pi = acos(-1.0);

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

template <typename T>

class LazySegTree{

  vector<T> t, lazy, len;

public:

  int n;

  LazySegTree(vector<T> &a){

    n = int(a.size());

    t.resize(4*n);

    lazy.resize(4*n);

    len.resize(4*n);

    build(a);

  }

  void build(vector<T> &a){

    build(a, 0, n-1, 1);

  }

  void update(int x, int y, T diff){

    update(0, n-1, 1, x, y, diff);

  }

  T query(int l, int r){

    return query(0, n-1, 1, l, r);

  }

private:

  T merge(T x, T y){

    return max(x,y);

  }

  T default_val() {

    return 0;

  }

  void push(int i){

    t[2*i] = max(t[2*i],lazy[i]);

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

    lazy[2*i] = max(lazy[2*i],lazy[i]);

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

    lazy[i] = 0;

  }

  void build(vector<T> &a, int l, int r, int i){

    if (l==r){

      t[i] = a[l];

      len[i] = 1;

      return;

    }

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

    build(a,l,mid,2*i);

    build(a,mid+1,r,2*i+1);

    t[i] = merge(t[2*i],t[2*i+1]);

    len[i] = 1;

  }

  void update(int l, int r, int i, int x, int y, T diff){

    if (x>y) return;

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

      t[i] = max(t[i],diff*len[i]);

      lazy[i] = max(lazy[i],diff);

      return;

    }

    push(i);

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

    update(l, mid, 2*i, x, min(y,mid), diff);

    update(mid+1, r, 2*i+1, max(x,mid+1), y, diff);

    t[i] = merge(t[2*i], t[2*i+1]);

  }

  T query(int l, int r, int i, int x, int y){

    if (x>y) return default_val();

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

      return t[i];

    }

    push(i);

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

    return merge(query(l, mid, 2*i, x, min(y,mid)), query(mid+1, r, 2*i+1, max(x,mid+1), y));

  }

};

bool solve(vector<vector<int>>& a, int __cnt=1){

  int n = sz(a);

  if (__cnt>2) return false;

  // coords comp

  map<int,int> mp;

  rep(i,0,n){

    rep(j,0,4){

      mp[a[i][j]] = 0;

    }

  }

  int __cc = 0;

  for (auto it: mp) mp[it.f] = __cc++;

  rep(i,0,n){

    rep(j,0,4){

      a[i][j] = mp[a[i][j]];

    }

  }

  vector<int> tmp(__cc+5);

  LazySegTree<int> st(tmp);

  rep(i,0,n){

    int left_b = a[i][2];

    st.update(a[i][0],a[i][1],left_b);

  }

  rep(i,0,n){

    int mx_left = st.query(a[i][0],a[i][1]);

    if (mx_left > a[i][3]) {

      return true;

    }

  }

  rep(i,0,n){

    swap(a[i][0],a[i][2]);

    swap(a[i][1],a[i][3]);

  }

  return solve(a,__cnt+1);

}

int main(int argc, const char * argv[]) {

  ios_base::sync_with_stdio(false);

  cin.tie(NULL);

  int t=1;

//  cin>>t;

  int n;

  cin>>n;

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

  rep(i,0,n){

    a[i].resize(4);

    rep(j,0,4) cin>>a[i][j];

  }

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

    cout<<(solve(a) ? "NO":"YES")<<"\n";

  }

  return 0;

}