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

#include <bits/stdc++.h>

using namespace std;

char buf[1<<23],*p1=buf,*p2=buf;

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

template <typename T>

inline void read(T &f)

{

    f=0;T fu=1;char c=getchar();

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

    while(c>='0'&&c<='9') {f=(f<<3)+(f<<1)+(c&15);c=getchar();}

    f*=fu;

}

template <typename T>

void print(T x,char c=0)

{

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

    if(x<10) putchar(x+48);

    else print(x/10),putchar(x%10+48);

    if(c) putchar(c);

}

inline void reads(string &f)

{

    string str="";char ch=getchar();

    while(ch<'!'||ch>'~') ch=getchar();

    while((ch>='!')&&(ch<= '~')) str+=ch,ch=getchar();

    f=str;

}

void prints(string s)

{

    for(int i=0;s[i];++i)

    putchar(s[i]);

}

typedef long long ll;

const int multicase=0,debug=0,maxn=4e5+50;

int n,a[maxn];

bitset<26> bs[maxn];

int val[maxn];

bool check(int pos)

{

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

    {

        bs[i]=a[i];

        for(int j=pos+1;j<=25;++j)

        bs[i][j]=0;

        val[i]=bs[i].to_ullong();

    }

    int l1=pow(2,pos),r1=pow(2,pos+1)-1;

    int l2=3*l1,r2=2*r1;

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

    int cnt=0;

    //[l1,r1]

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

    {

        int pos1=lower_bound(val+i+1,val+1+n,l1-val[i])-val;

        int pos2=upper_bound(val+i+1,val+1+n,r1-val[i])-val-1;

        cnt+=pos2-pos1+1;

    }

    //cout<<"cnt="<<cnt<<'\n';

    //[l2,r2]

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

    {

        int pos1=lower_bound(val+i+1,val+1+n,l2-val[i])-val;

        int pos2=upper_bound(val+i+1,val+1+n,r2-val[i])-val-1;

        cnt+=pos2-pos1+1;

    }

    //cout<<"cnt="<<cnt<<'\n';

    return cnt&1;

}

void solve()

{

    read(n);

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

    read(a[i]);

    int ans=0;

    /* check(0);

    check(1);

    return ; */

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

    {

        if(check(i))

        ans+=(1<<i);

    }

    print(ans);

}

int main()

{

    #ifdef AC

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

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

    #endif

    clock_t program_start_clock=clock();

    int _=1;

    if(multicase) read(_);

    while(_--) solve();

    fprintf(stderr,"\nTotal Time: %lf ms",double(clock()-program_start_clock)/1000);

    return 0;

}


E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be placed arbitrarily  — be inside each other, coincide and so on. Segments can degenerate into points, that is li=rili=ri is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:  if n=3n=3 and there are segments [3,6][3,6], [100,100][100,100], [5,8][5,8] then their union is 22 segments: [3,8][3,8] and [100,100][100,100];  if n=5n=5 and there are segments [1,2][1,2], [2,3][2,3], [4,5][4,5], [4,6][4,6], [6,6][6,6] then their union is 22 segments: [1,3][1,3] and [4,6][4,6]. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given nn so that the number of segments in the union of the rest n−1n−1 segments is maximum possible.For example, if n=4n=4 and there are segments [1,4][1,4], [2,3][2,3], [3,6][3,6], [5,7][5,7], then:  erasing the first segment will lead to [2,3][2,3], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union;  erasing the second segment will lead to [1,4][1,4], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union;  erasing the third segment will lead to [1,4][1,4], [2,3][2,3], [5,7][5,7] remaining, which have 22 segments in their union;  erasing the fourth segment will lead to [1,4][1,4], [2,3][2,3], [3,6][3,6] remaining, which have 11 segment in their union. Thus, you are required to erase the third segment to get answer 22.Write a program that will find the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n−1n−1 segments.InputThe first line contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first of each test case contains a single integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of segments in the given set. Then nn lines follow, each contains a description of a segment — a pair of integers lili, riri (−109≤li≤ri≤109−109≤li≤ri≤109), where lili and riri are the coordinates of the left and right borders of the ii-th segment, respectively.The segments are given in an arbitrary order.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.OutputPrint tt integers — the answers to the tt given test cases in the order of input. The answer is the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.ExampleInputCopy3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
OutputCopy2
1
5

#include <bits/stdc++.h>

using namespace std;
int i,j,k,n,m,t,it,res,f[200500],cnt[200500];
int main(){
cin>>t;
while(t--){
vector<pair<int,int> >v;vector<int> s;
for(i=1,cin>>n;i<=n;i++){cin>>j>>k;v.push_back({j,k});}
sort(v.begin(),v.end());
it=i=0;f[0]=-2e9;
for(auto [l,r]:v){i++;cnt[i]=cnt[i-1]+(f[i-1]<l);f[i]=max(f[i-1],r);}
reverse(v.begin(),v.end());res=cnt[n-1];i=n;
for(auto [l,r]:v){if(i==1){break;}while(!s.empty()&&s.back()+r>=0){s.pop_back();}s.push_back(-l);k=cnt[i-2]+lower_bound(s.begin(),s.end(),-f[i-2])-s.begin();res=max(res,k);i--;}
cout<<res<<'\n';
}
}


F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3
1 3 2
-100 2 3
OutputCopy3
InputCopy5
2 1 4 3 5
2 2 2 3 4
OutputCopy19
InputCopy2
2 1
-3 0
OutputCopy0

#define _USE_MATH_DEFINES

#pragma GCC optimize("Ofast")

#include <bits/stdc++.h>

using namespace std;

const  int  n1=1000000007;

#define miv map<int,vector<int>>

#define inf 5e18

#define mlv map<ll,vector<ll>>

#define mip map<int,pair<int,int>>

#define mii map<int,int>

#define mll map<ll,ll>

#define umip unordered_map<int,pair<int,int>>

#define umii unordered_map<int,int>

#define vi vector<int>

#define vll vector<ll>

#define vvll vector<vector<ll>>

#define vvi vector<vector<int>>

#define ll long long

#define pii pair<int,int>

#define pll pair<ll,ll>

#define vpii vector<pii>

#define vpll vector<pll>

#define pb push_back

#define f first

#define s second

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

#define pi = 3.1415926535897932384626

#define INF LLONG_MAX

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

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

#define input(a,x,n); for(int i=x;i<n;i++){cin>>a[i];}

#define output(b,x,n);  for(int i=x;i<n;i++){cout<<b[i]<<" ";}

#define umill unordered_map <int,ll>

#define  pvi pair<vector<int>,int>

#define  piv pair<int,vector<int>>

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

#define inl(i,x,n) for(ll i=x;i<n;i++)

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

#define del(i,x,n) for(ll i=n;i>=x;i--)

#define trav(it,m) for(auto it=m.begin();it!=m.end();it++)

#include <ext/pb_ds/assoc_container.hpp>

using namespace __gnu_pbds;

typedef tree<pll, null_type, less<pll>,

            rb_tree_tag, tree_order_statistics_node_update> ordered_set;

struct compare {

    inline bool operator()(const std::string& first,

            const std::string& second) const

    {

        return first.size() < second.size();

    }

};

vll factorial(ll n)

{

    vll fct(n+1);

    fct[0]=1;

    fct[1]=1;

    inl(i,2,n+1)

    {

        fct[i]=((fct[i-1%n1])*(i%n1))%n1;

    }

    return fct;

}

vll factorial(ll n,ll m)

{

    vll fct(n+1);

    fct[0]=1;

    fct[1]=1;

    inl(i,2,n+1)

    {

        fct[i]=((fct[i-1]%m)*(i%m))%m;

    }

    return fct;

}

 long long power(long long x,ll y)

{

    long long res = 1;

     ll p=n1;

    x = x % p;

    while (y > 0)

    {

        if (y & 1)

            res = ((res%p) * (x%p)) % p;

        y = y >> 1;

        x = ((x%p) * (x%p)) % p;

    }

    return res;

}

long long modInverse(long long n)

{

    return power(n, n1 - 2);

}

vector<bool> SieveOfEratosthenes(ll n){

vector<bool> prime(n + 1, 1); for (ll p = 2; p * p <= n; p++)

if (prime[p] == true) for (ll i = p * p; i <= n; i += p)

prime[i] = false; return prime;}

ll ncr(ll n,ll r,vll &fct,vll &rfct)

{

    return 1ll*(((((fct[n]%n1)*((rfct[r])%n1))%n1)*((rfct[n-r])%n1))%n1);

}

//   char a[400][400];

 ll cnt(int r1,int r2,int c1,int c2,vvll &pre)

 {

      ll cnt=0;

      if(r1>0&&c1>0)

      {

          cnt=pre[r2][c2]-pre[r2][c1-1]-pre[r1-1][c2]+pre[r1-1][c1-1];

      }

      else if(r1>0)

      {

          cnt=pre[r2][c2]-pre[r1-1][c2];

      }

      else if(c1>0)

      {

          cnt=pre[r2][c2]-pre[r2][c1-1];

      }

      else

      {

          cnt=pre[r2][c2];

      }

      return cnt;

 }

 //ll dp[500][500];

ll ans1;

void dfs1(vvll &adj,ll node,vll &vis,vll &lev)

{

    vis[node]=1;

    for(auto &u:adj[node])

    {

        if(vis[u]==0)

        {

            dfs1(adj,u,vis,lev);

            lev[node]=max(lev[node],lev[u]+1);

        }

    }

    if(lev[node]==-1)

    {

        lev[node]=1;

    }

}

void dfs(vvll &adj,ll node,ll p,vll &sum,vll &ans,vll &a,map<pll,ll>&mp,vll &v)

{

    sum[node]=sum[p]+mp[{p,node}];

    v.pb(node);

    ll l=0;

    ll r=v.size()-1;

    ll req=-1;

    while(l<=r)

    {

        ll mid=(l+r)/2;

        if(sum[node]-sum[v[mid]]<=a[node])

        {

            req=mid;

            r=mid-1;

        }

        else l=mid+1;

    }

    ans[p]++;

    if(req-1>=0)

    {

        ans[v[req-1]]--;

    }

   // cout<<node<<"g "<<v[req]<<endl;

    for(auto &u:adj[node])

    {

        if(u!=p)

        {

            dfs(adj,u,node,sum,ans,a,mp,v);

            ans[node]+=ans[u];

        }

    }

    v.pop_back();

}

void build(ll l,ll r,vll &a,vll &seg,ll idx)

{

    if(l==r)

    {

        seg[idx]=a[l];

        return;

    }

    ll mid=(l+r)/2;

    build(l,mid,a,seg,2*idx+1);

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

     seg[idx]=__gcd(seg[2*idx+1],seg[2*idx+2]);

     return ;

}

void build1(ll l,ll r,vll &a,vll &seg,ll idx)

{

    if(l==r)

    {

        seg[idx]=a[l];

        return;

    }

    ll mid=(l+r)/2;

    build1(l,mid,a,seg,2*idx+1);

     build1(mid+1,r,a,seg,2*idx+2);

     seg[idx]=max(seg[2*idx+1],seg[2*idx+2]);

     return ;

}

ll query1(ll l,ll r,ll low,ll high,ll idx,vll &seg)

{

    if(low>=l and high<=r)

    return seg[idx];

    if(low>r or high<l)

        return -1*inf;

    ll mid=(low+high)/2;

    ll x=query1(l,r,low,mid,2*idx+1,seg);

    ll y=query1(l,r,mid+1,high,2*idx+2,seg);

    return max(x,y);

}

ll query(ll l,ll r,ll low,ll high,ll idx,vll &seg)

{

    if(low>=l and high<=r)

    return seg[idx];

    if(low>r or high<l)

        return 0;

    ll mid=(low+high)/2;

    ll x=query(l,r,low,mid,2*idx+1,seg);

    ll y=query(l,r,mid+1,high,2*idx+2,seg);

    return __gcd(x,y);

}

void update(ll l,ll r,vll &seg, ll idx,ll val,ll index,mll &st)

{

    if(l==r)

    {

        ll x=seg[idx];

        if(l==0)

        {

            st[x]--;

            if(st[x]<=0)

                st.erase(x);

            seg[idx]-=val;

            st[seg[idx]]++;

        }

        else

        {

            seg[idx]-=val;

        }

        return;

    }

    ll mid=(l+r)/2;

    if(index>=l and index<=mid)

    {

        update(l,mid,seg,2*idx+1,val,index,st);

    }

    else

    {

        update(mid+1,r,seg,2*idx+2,val,index,st);

    }

    ll x=seg[idx];

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

    if(l==0)

    {

        st[x]--;

        if(st[x]<=0)

            st.erase(x);

        st[seg[idx]]++;

    }

    return;

}

 vll kmp(string str)

 {

     vll v(str.size());

     v[0]=0;

     in(i,1,str.size())

     {

         ll j=v[i-1];

         while(j>0 and str[i]!=str[j])

         {

             j=v[j-1];

         }

         if(str[i]==str[j])

         {

             j++;

         }

         v[i]=j;

     }

     return v;

 }

void fun(vector<int>&A)

{

    int n=A.size();

   int num1=1e9;

   int num2=1e9;

   int c1=0;

   int c2=0;

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

   {

       if(A[i]==num1)

       {

           c1++;

       }

       else if(A[i]==num2)

       {

           c2++;

       }

       else if(c1==0)

       {

           num1=A[i];

           c1++;

       }

       else if(c2==0)

       {

           num2=A[i];

           c2++;

       }

       else

       {

           c1--;

           c2--;

       }

   }

   c1=0;

   c2=0;

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

   {

       if(A[i]==num1)

       {

           c1++;

       }

       if(A[i]==num2)

       {

           c2++;

       }

   }

   cout<<num1<<" "<<num2<<endl;

   if(c1>(n/3))

   {

       cout<<num1;

   }

  else if(c2>(n/3))

   {

       cout<<num2;

   }

   else

   {

       cout<<-1;

   }

   cout<<endl;

}

/*ll spf[10000001];

void sieve()

{

    spf[1]=1;

    in(i,2,1e7+1)

    {

        spf[i]=i;

    }

    for(int i=4;i<=1e7+1;i+=2)

    {

        spf[i]=2;

    }

    for(int i=3;i*i<=1e7+1;i++)

    {

        if(spf[i]==i)

        {

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

            {

                if(spf[j]==j)

                {

                    spf[j]=i;

                }

            }

        }

    }

}

*/

ll lca(vvll &dp,ll n1,ll n2,vll &dep)

{

    if(dep[n1]<dep[n2])

        swap(n1,n2);

    de(i,0,21)

    {

        if(dep[n1]-(1ll<<i)>=dep[n2])

        {

            n1=dp[n1][i];

        }

    }

    if(n1==n2)

        return n1;

    de(i,0,21)

    {

        if(dp[n1][i]!=dp[n2][i])

        {

            n1=dp[n1][i];

            n2=dp[n2][i];

        }

    }

    return dp[n1][0];

}

void updatef(vll &bt,ll idx,ll val,ll n)

{

    while(idx<=n)

    {

        bt[idx]+=val;

        idx+=(idx&(-idx));

    }

}

ll sum(vll &bt,ll idx)

{

    ll ans=0;

    while(idx>0)

    {

        ans+=bt[idx];

        idx-=(idx&(-idx));

    }

    return ans;

}

int main()

{

ios_base::sync_with_stdio(false);

cin.tie(NULL);cout.tie(NULL);

int tt=1;

//cin>>tt;

 //cout<<primes.size()<<"LK"<<endl;

//output(primes,0,primes.size());

//cout<<endl;

//mlv fc;

while(tt--)

//in(x,1,tt+1)

{

    ll n;

    cin>>n;

    vpll v(n);

    in(i,0,n)

    {

        cin>>v[i].f;

    }

    in(i,0,n)

    {

        cin>>v[i].s;

    }

    sort(all(v));

    ll ans=0;

    ordered_set st;

    in(i,0,n)

    {

        ll val=st.order_of_key({v[i].s+1,-1}); // al  speeds <current one

        ans+=(val*v[i].f);

        st.insert({v[i].s,i});

    }

    st.clear();

     de(i,0,n-1)

    {

        ll val=(ll)st.size()-st.order_of_key({v[i].s,-1});

        ans-=(val*v[i].f);

        st.insert({v[i].s,i});

    }

    cout<<ans<<endl;

}

return 0;

}


A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2.

#include <bits/stdc++.h>

using namespace std;

#define int long long

int tt;

void solve();

void IO()

{

	ios_base::sync_with_stdio(false);

	cin.tie(NULL);

	cout.tie(NULL);

}

void testcase(int t)

{

	cin >> t;

	while (t--) solve();

}

typedef long long ll;

typedef long double lld;

#define ff first

#define ss second

#define pi pair<int, int>

#define vi vector<int>

#define vb vector<bool>

#define vs vector<string>

#define vc vector<char>

#define pv pair<vi, vi>

#define vpi vector<pi>

#define vvi vector<vi>

#define vvb vector<vb>

#define vvc vector<vc>

#define vvvi vector<vvi>

#define pb push_back

#define mp make_pair

#define arr(k) array<int, k>

#define var(k) vector<arr(k)>

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

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

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

#define each(nb, x) for (auto nb:x)

/*  ------------------------    BASIC INPUT -------------------------------  */

void read() {}

void read(int &a) {cin >> a;}

void read(string &s) {cin >> s;}

void read(double &a) {cin >> a;}

void read(lld &a) {cin >> a;}

template<typename x, typename y> void read(pair<x, y> &a) {read(a.first), read(a.second);}

template<typename x>void read(x &a) {for (auto  &i : a) read(i);}

template<typename x, typename... y> void read(x& a, y&... b) {read(a); read(b...);}

template<class T> void cmin(T&a, T b) {a = min(a, b);}

template<class T> void cmax(T&a, T b) {a = max(a, b);}

/*    ------------------------------------------------------------------   */

/* -------------------------------------  DEBUG STARTS ------------------------------- */

#ifndef ONLINE_JUDGE

#define dbg(x) cerr << #x << " = "; _print(x); cerr << endl;

#else

#define dbg(x)

#endif

void print(int t) {cout << t;}

void print(string t) {cout << t;}

void print(char t) {cout << t;}

void print(lld t) {cout << t;}

void print(double t) {cout << t;}

void print(bool t) {cout << t;}

void print(deque<int> t) {while (not t.empty()) {cout << t.front() << ' '; t.pop_front();}}

void print(queue<int> t) {while (not t.empty()) {cout << t.front() << ' '; t.pop();}}

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

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

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

void _print(lld t) {cerr << t;}

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

void _print(bool t) {cerr << t;}

void _print(deque<int> t) {while (not t.empty()) {cerr << t.front() << ' '; t.pop_front();}}

void _print(queue<int> t) {while (not t.empty()) {cerr << t.front() << ' '; t.pop();}}

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

template <class T> void print(vector <T> v);

template <class T, class V> void print(pair <T, V> p) {print(p.ff); cout << " "; print(p.ss);}

template <class T> void print(vector <T> v) {for (T i : v) {print(i); cout << " ";}}

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

template <class T> void _print(vector <T> v);

template <class T> void _print(set <T> v);

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

template <class T> void _print(multiset <T> v);

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

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

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

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

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

/* -------------------------------------  DEBUG ENDS --------------------------------- */

int n, m, l, r, odd, even;

// we can observe that if we at ith level and then even_to_fill + odd_to_fill = blank_pos till i

// so we'll use this fact to cut one dimension in iterative dp,

// define dp(i,j,k,par) -> min complexity till ith index and we have filled j odds and

// k evens till now and the current element we fill is of parity = par

// so we currently at index i, we know that we have filled j odds, so the rest blank pos

// = (0_till_i - j) have to be filled with evens

void solve()

{

	cin >> n;

    vi vis(n+1, 0), a(n+1), zero(n+1, 0);

    rep(i,1,n+1)

    {

        cin >> a[i];

        vis[a[i]] = 1;

        if (a[i] == 0) zero[i] = zero[i-1] + 1;

        else zero[i] = zero[i-1];

    }

    rep(i,1,n+1)

    {

        if (vis[i] == 0)

        {

            if (i&1) odd++;

            else even++;

        }

    }

    vvvi dp(n+5, vvi(n+5, vi(4, 1e18)));

    // base case

    dp[0][0][0] = dp[0][0][1] = 0;

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

    {

        for (int of=0; of<=odd; of++)

        {

            // we have filled "of" odds(those which were not present in a[]) till ith index

            // so the remaining blank pos till i must be filled with evens

            // evens_to_fill = zeros[i] - of

            int etf = zero[i] - of;

            if (a[i] == 0)

            {

                if (of > 0) dp[i][of][1] = min(dp[i-1][of-1][1], dp[i-1][of-1][0]+1);

                if (etf > 0 and etf <= even)

                    dp[i][of][0] = min(dp[i-1][of][0], dp[i-1][of][1]+1);

            }

            else

            {

                if (a[i]%2 == 1)

                    dp[i][of][1] = min(dp[i-1][of][1], dp[i-1][of][0]+1);

                else

                    dp[i][of][0] = min(dp[i-1][of][1]+1, dp[i-1][of][0]);

            }

        }

    }

    cout << min(dp[n][odd][0], dp[n][odd][1]);

}

signed main()

{

	IO();

	// testcase(tt);

	solve();

}


B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5
1 1
1 1
1 2
1 4
1 3
OutputCopy9
InputCopy3
4 2 0 2 0
6 9 9 8 8 7 7
1 6
OutputCopy7
InputCopy10
3 62 24 39
1 17
1 99
1 60
1 64
1 30
2 79 29
2 20 73
2 85 37
1 100
OutputCopy72
NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.

                 /**Bismillahir Rahmanir Rahim.**/

#include<bits/stdc++.h>

using namespace std;

typedef unsigned long long int   ull;

typedef long long int            ll;

typedef long double              ld;

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

#define pi          acos(-1)

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

#define dot(x)      fixed<<setprecision(x)

#define eps         0.000000001

#define dbug        cout <<"OK" <<endl;

#define mod         1000000007

#define MAX         100005

#define en          '\n'

#define ff          first

#define ss          second

inline void         yes(){cout<<"YES\n";}

inline void         no(){cout<<"NO\n";}

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

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

//ordered_set variable;

//In order to insert multiple copies of the same element in the ordered set..

using ordered_multiset = tree<ll, null_type ,  less_equal<ll> , rb_tree_tag , tree_order_statistics_node_update>;

//ordered_multiset variable;

using ordered_map = tree<pair<ll,ll>, null_type, less<pair<ll,ll> >,rb_tree_tag, tree_order_statistics_node_update>;

// ordered_map varibale

// order_of_key (k) : Number of items strictly smaller than k .

// find_by_order(k) : K-th element in a set (counting from zero).

// priority_queue<int> Q (greatar to smaller)

// priority_queue<int, vector<int>, greater<int> > Q;   (smaller to greater)

// p^e % m

ll bigMod(ll p, ll e, ll M) {ll ret = 1; for (; e > 0; e >>= 1) { if (e & 1) ret = (ret * p) % M; p = (p * p) % M;} return (ll)ret;}

ll modInverse(ll a, ll M) {return bigMod(a, M - 2, M);}

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

ll lcm(ll a, ll b) {a = abs(a); b = abs(b); return (a / gcd(a, b)) * b;}

int chessx[]={-1,-1,1, 1,-2,-2, 2,2}; //knight

int chessy[]={ 2,-2,2,-2, 1,-1,-1,1}; //knight

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

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

const double EPS = 1e-12;

///Bit-Masking.. pos is 0 based index and starts from left to right: [31 30 ... ... ... 3 2 1 0]

ll onbit(ll N, ll pos) {

    return N = N | (1 << pos);

}

ll offbit(ll N, ll pos) {

    return N = N & ~(1 << pos);

    //or return N = N & !(1<<pos);

}

ll flipbit(ll N, ll pos) {

    return N = N ^ (1 << pos);

}

bool checkbit(ll N, ll pos) {

    return (bool)(N & (1 << pos));

}

int main()

{

    int t1=1;

    Faster

    // test

    // {

    ll n,i,j,cnt=0,res=0;

    cin>>n;

    vector<ll> mn,mmx;

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

    {

        ll l;

        cin>>l;

        ll a[l+1];

        ll mi=INT_MAX,mx=0;

        for(j=1;j<=l;j++)

        {

            cin>>a[j];

            mi=min(mi,a[j]);

            mx=max(mx,a[j]);

        }

        ll flag=0;

        for(j=1;j<l;j++)

        {

            if(a[j]<a[j+1])

            {

                flag=1;

                break;

            }

        }

        if(flag==0)

        {

            mn.push_back(mi);

            mmx.push_back(mx);

        }

        else

            cnt++;

    }

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

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

    ll ans=0;

    for(i=0;i<mn.size();i++)

    {

        auto l1=upper_bound(mmx.begin(),mmx.end(),mn[i])-mmx.begin();

        ans+=(mmx.size()-l1);

    }

    //cout<<ans<<en;

    // for(i=0;i<mmx.size();i++)

    // {

    //     auto l1=lower_bound(mn.begin(),mn.end(),mmx[i])-mn.begin();

    //     if(l1>i)

    //         ans+=(l1-i);

    // }

    //

    //cout<<ans<<en;

    ans+=(((n-cnt)*2)*cnt)+cnt+(cnt*(cnt-1));

    cout<<ans<<en;

    //cout<<ans+ +cnt<<en;

    // }

}


D. Around the Worldtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are planning 144144 trips around the world.You are given a simple weighted undirected connected graph with nn vertexes and mm edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 33 which passes through the vertex 11. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.But the trips with cost 00 aren't exciting. You may choose any subset of edges incident to the vertex 11 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 00 which passes through the vertex 11 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 109+7109+7.InputThe first line contains two integers nn and mm (1≤n,m≤1051≤n,m≤105) — the number of vertexes and edges in the graph. The ii-th of the next mm lines contains three integers aiai, bibi and wiwi (1≤ai,bi≤n,ai≠bi,0≤wi<321≤ai,bi≤n,ai≠bi,0≤wi<32) — the endpoints of the ii-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than 33 which passes through the vertex 11.OutputOutput the answer modulo 109+7109+7.ExamplesInputCopy6 8
1 2 0
2 3 1
2 4 3
2 6 2
3 4 8
3 5 4
5 4 5
5 6 6
OutputCopy2
InputCopy7 9
1 2 0
1 3 1
2 3 9
2 4 3
2 5 4
4 5 7
3 6 6
3 7 7
6 7 8
OutputCopy1
InputCopy4 4
1 2 27
1 3 1
1 4 1
3 4 0
OutputCopy6NoteThe pictures below represent the graphs from examples.  In the first example; there aren't any nontrivial cycles with cost 00, so we can either remove or keep the only edge incident to the vertex 11.  In the second example, if we don't remove the edge 1−21−2, then there is a cycle 1−2−4−5−2−11−2−4−5−2−1 with cost 00; also if we don't remove the edge 1−31−3, then there is a cycle 1−3−2−4−5−2−3−11−3−2−4−5−2−3−1 of cost 00. The only valid subset consists of both edges.  In the third example, all subsets are valid except for those two in which both edges 1−31−3 and 1−41−4 are kept.

#include<bits/stdc++.h>
#define I inline
#define ll long long
#define db double
#define lb long db
#define N (100000+5)
#define M (500+5)
#define K (700+5)
#define mod 1000000007
#define Mod (mod-1)
#define eps (1e-5)
#define ui unsigned int
#define ull unsigned ll
#define Gc() getchar()
#define Me(x,y) memset(x,y,sizeof(x))
#define Mc(x,y) memcpy(x,y,sizeof(x))
#define d(x,y) ((k+1)*(x)+(y))
#define R(n) (rnd()%(n)+1)
#define Pc(x) putchar(x)
#define LB lower_bound
#define UB upper_bound
#define PB push_back
using namespace std;struct Edge{int to,w;};vector<Edge> S[N];
int n,m,W[M][M],H,x,y,z,Pf[N],vis[N],d[N];ui A[M],Q[N];ll ToT,f[M],g[M],T1,T2;map<ui,int> Is,Fl[50];
I ui Merge(ui x,ui y){if((x&y)>1||!x||!y) return 0;ui z=0;for(int i=0;i<=31;i++)if(x>>i&1) for(int j=0;j<=31;j++)y>>j&1&&(z|=1u<<(i^j));return z;}
I void dfs(int x,ui w){if(Fl[x].count(w)) return;Fl[x][w]=1;if(x==32){A[Is[w]=++H]=w;return;}dfs(x+1,w);!(w>>x&1)&&(dfs(x+1,Merge(w,1u<<x|1)),0);}
I void FC(int x,int La){vis[x]=1;for(Edge i:S[x]){if(vis[i.to])i.to^La&&i.to^1&&d[i.to]<d[x]&&(T1=(i.w^Q[x]^Q[i.to]?Merge(1u<<(i.w^Q[x]^Q[i.to])|1,T1):0));else Q[i.to]=Q[x]^i.w,d[i.to]=d[x]+1,FC(i.to,x);}}
int main(){
//	freopen("1.in","r",stdin);
	int i,j,h;dfs(1,1);scanf("%d%d",&n,&m);for(i=1;i<=m;i++) scanf("%d%d%d",&x,&y,&z),S[x].PB((Edge){y,z}),S[y].PB((Edge){x,z});
	Me(W,-1);for(i=1;i<=H;i++) for(j=1;j<=H;j++) W[i][j]=((A[i]&A[j])>1?-1:Is[Merge(A[i],A[j])]);
	f[Is[1]]=1;vis[1]=1;for(Edge i:S[1]) Pf[i.to]=1,Q[i.to]=i.w;for(i=2;i<=n;i++){
		if(!Pf[i]) continue;Mc(g,f);for(Edge j:S[i]){if(!Pf[j.to]) continue;
			T1=1;T2=j.w^Q[i]^Q[j.to];FC(i,1);Pf[i]=Pf[j.to]=0;if(!T1) break;x=Is[T1];for(h=1;h<=H;h++) ~W[h][x]&&(f[W[h][x]]=(f[W[h][x]]+f[h]*2)%mod);
			T1=(T2?Merge(T1,1u<<T2|1):0);x=Is[T1];for(h=1;h<=H;h++) ~W[h][x]&&(f[W[h][x]]=(f[W[h][x]]+g[h])%mod);
		}if(Pf[i]){Pf[i]=0;T1=1;FC(i,1);if(T1) for(x=Is[T1],j=1;j<=H;j++) f[W[j][x]]=(f[W[j][x]]+g[j])%mod;}
	}for(i=1;i<=H;i++) ToT+=f[i];printf("%lld\n",ToT%mod);
}


D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string ss starting from the ll-th character and ending with the rr-th character as s[l…r]s[l…r]. The characters of each string are numbered from 11.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string aa is considered reachable from binary string bb if there exists a sequence s1s1, s2s2, ..., sksk such that s1=as1=a, sk=bsk=b, and for every i∈[1,k−1]i∈[1,k−1], sisi can be transformed into si+1si+1 using exactly one operation. Note that kk can be equal to 11, i. e., every string is reachable from itself.You are given a string tt and qq queries to it. Each query consists of three integers l1l1, l2l2 and lenlen. To answer each query, you have to determine whether t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1].InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of string tt.The second line contains one string tt (|t|=n|t|=n). Each character of tt is either 0 or 1.The third line contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries.Then qq lines follow, each line represents a query. The ii-th line contains three integers l1l1, l2l2 and lenlen (1≤l1,l2≤|t|1≤l1,l2≤|t|, 1≤len≤|t|−max(l1,l2)+11≤len≤|t|−max(l1,l2)+1) for the ii-th query.OutputFor each query, print either YES if t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1], or NO otherwise. You may print each letter in any register.ExampleInputCopy5
11011
3
1 3 3
1 4 2
1 2 3
OutputCopyYes
Yes
No

#include<bits/stdc++.h>

typedef long long ll;

typedef unsigned long long ull;

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

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

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

using namespace std;

const int P = 998244353, Q = 13331;

inline int plu(int x, int y) {return x + y >= P ? x + y - P : x + y;}

inline int del(int x, int y) {return x - y <  0 ? x - y + P : x - y;}

inline void add(int &x, int y) {x = plu(x, y);}

inline void sub(int &x, int y) {x = del(x, y);}

inline int qpow(int a, int b) {int s = 1; for(; b; b >>= 1, a = 1ll * a * a % P) if(b & 1) s = 1ll * s * a % P; return s;}

inline int read() {

	int x = 0, f = 1; char c = getchar();

	while(c < '0' || c > '9') f = (c == '-') ? - 1 : 1, c = getchar();

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

	return x * f;

}

const int N = 2e5 + 10;

int n, q, f[N][2], g[N], p[N];

char str[N];

int calc(int l, int r) {

	int o = l & 1;

	return del(f[r][o], 1ll * f[l - 1][o] * p[g[r] - g[l - 1]] % P);

}

int main() {

	n = read();

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

	q = read();

	p[0] = 1; rep(i, 1, n) p[i] = 1ll * p[i - 1] * Q % P;

	rep(i, 1, n)

		if(str[i] == '1') f[i][0] = f[i - 1][0], f[i][1] = f[i - 1][1], g[i] = g[i - 1];

		else

			f[i][0] = plu(1ll * f[i - 1][0] * Q % P, (i & 1) ? 2 : 3),

			f[i][1] = plu(1ll * f[i - 1][1] * Q % P, (i & 1) ? 3 : 2),

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

	while(q --) {

		int x = read(), y = read(), len = read();

		int vx = calc(x, x + len - 1);

		int vy = calc(y, y + len - 1);

		puts(vx == vy ? "Yes" : "No");

	}

	return 0;

}


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

// Problem: A. Non-zero

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

// URL: https://codeforces.com/contest/1300/problem/A

// Memory Limit: 256 MB

// Time Limit: 1000 ms

//

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

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int maxn = 110;

int a[maxn];

int main(void)

{

	ios::sync_with_stdio(0);

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

	int t;

	cin >> t;

	while (t--) {

		int n;

		cin >> n;

		int sum = 0, cnt = 0;

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

			cin >> a[i];

			if (!a[i]) ++cnt;

			sum += a[i];

		}

		if (sum + cnt == 0) {

			cout << cnt + 1 << endl;

		} else {

			cout << cnt << endl;

		}

	}

	return 0;

}


D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0

// Problem: D. Pair of Topics

// Contest: Codeforces - Codeforces Round #627 (Div. 3)

// URL: https://codeforces.com/problemset/problem/1324/D

// Memory Limit: 256 MB

// Time Limit: 2000 ms

//

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

/*

* Coder -> ranadip_01 aKa RANADIP MUNDA

* DEPT. -> ECE"25

* COLLEGE -> JALPAIGURI GOVT. ENGINEERING COLLEGE

* Date -> 02/13/2023

*/

#include <bits/stdc++.h>

#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

using namespace std;

#define F ios_base::sync_with_stdio(false);

#define I cin.tie(NULL);

#define O cout.tie(NULL);

#define f first

#define s second

#define d  double

#define ll long long

#define l long int

#define i int

#define e "\n"

#define in cin>>

#define out cout<<

#define frll(a,b,c) for(ll a=b;a<=c;a++)

#define forll(a,c) for(ll a=0;a<c;a++)

#define frl(a,b,c) for(l a=b;a<=c;a++)

#define forl(a,c) for(l a=0;a<c;a++)

#define fri(a,b,c) for(i a=b;a<=c;a++)

#define fori(a,c) for(i a=0;a<c;a++)

#define n(t) while(T--)

#define T tes_cases

#define vec vector

#define vs vector<string>

#define vc vector<char>

#define uset unordered_set

#define umap unordered_map

#define mm multimap

#define pr pair

#define stk stack

#define que queue

#define dqu deque

#define pub emplace_back

#define pob pop_back()

#define puf emplace_front

#define pof pop_front()

#define pr_q priority_queue

#define mod  1000000007

const ll inf = 1e18+5;

const i Num = 1e3 + 5;

i park[Num];

i dellRow[]={-1,0,1,0};

i dellCol[]={0,1,0,-1};

void precompute()

{

    park[0] = 0;

    park[1] = 1;

    park[2] = 2;

    for (int a = 3; a < Num; a++)

    {

        park[a] = park[a - 1] * a;

        park[a] %= mod;

    }

}

bool isPerfectSquare(ll num){

    if(ceil((double)sqrt(num))==floor((double)sqrt(num))){

        return true;

    }else{

        return false;

    }

}

bool isPalindrome(string s1, int left, int right) {

    if (left > right) return true;

    if (s1[left] != s1[right]) return false;

    else return isPalindrome( s1, left + 1, right - 1);

}

bool isPrime(ll val) { // O(sqrt(N)

    if (val <= 1) return false;

    if (val <= 3) return true;

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

    for (ll a = 5; a * a <= val; a = a + 6)

        if (val % a == 0 || val % (a + 2) == 0)

            return false;

    return true;

}

ll gcd(ll a,ll b){ return (b==0)? a:gcd(b,a%b);}//Euclidean Division (O(log(min(a,b)))

inline ll lcm(ll a, ll b) { return a / gcd(a, b) * 1ll * b; }

inline int normalize(int x, int y)

{

    x %= y;

    if (x < 0)

        x += y;

    return x;

}

i floor1(int n, int k)

{

    if (n % k == 0 || n >= 0)

        return n / k;

    return (n / k) - 1;

}

i ceil1(int n, int k){return floor1(n + k - 1, k);}

ll powm(ll a, ll b)// O(logN)

{

    ll res = 1;

    while (b)

    {

        if (b & 1)

            res = (res * a) % mod;

        a = (a * a) % mod;

        b >>= 1;

    }

    return res;

}

ll binpow(ll a, ll b, ll m) {// O(logN)

    a %= m;

    ll res = 1;

    while (b > 0) {

        if (b & 1)

            res = res * a % m;

        a = a * a % m;

        b >>= 1;

    }

    return res;

}

ll moduloInverse1(ll n1,ll modulo){//Fermats Little O(logN)

    // a^(m-1)=1 (Formula)

    // a^(m-2)=a^-1

    return binpow(n1,modulo-2,modulo);

}

int nPr(int n, int c)

{

    int num = park[n];

    num %= mod;

    num /= park[n - c];

    num %= mod;

    return num;

}

int all_0_To_1(int n)

{

    if (n == 1)

        return 1;

    if (!(n & (n - 1)))

        return all_0_To_1(n + 1);

    else

    {

        int p = ceil(log2(n));

        int ans = (1 << p);

        return (ans - 1);

    }

}

int stringToInt(string s)

{

    int num = 0;

    int n = s.length();

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

        num = num * 10 + ((int)(s[a]) - 48);

    return num;

}

int count_setBits(int n){

    if(n==0)return 0;

    return 1+count_setBits(n&(n-1));

}

int nearest_lowest_pow_of_2(int n)

{

    int val = log2(n);

    int ans = (1 << val);

    return ans;

}

int removeLast_SetBits(int n){

    return (n&(n-1));

}

int change_ithBit(int n,int a){

    return (n|(1<<a));

}

int clear_ithBit(int n,int a){

    return (a&(~(1<<a)));

}

int find_ithBit_from_Right(int n,int k,int a){

    return (n&(1<<(k-a)));

}

void swapp(int h,int k){

    h=(h^k);

    k=(k^h);

    h=(h^k);

}

bool sortBySec(const pair<ll,ll>&p1,const pair<ll,ll>&p2){

    return p1.s<p2.s;

}

const ll maxN=1e4;

vec<ll> factorials(maxN);

ll binomial(ll n1,ll k){

    if(n1<k) return 0;

    ll res=factorials[n1];

    res=(res*powm(factorials[k],mod-2))%mod;

    res=(res*powm(factorials[n1-k],mod-2))%mod;

    return res;

}

void factorial(){

    factorials[0]=factorials[1]=1;

    fri(a,2,1000000){

        factorials[a]=(factorials[a-1]*a)%mod;

    }

}

//Total prime - 31622

vec<i> primeSet;

bool prime[maxN];

bitset<31622> prm;

void madePrime(){

    for(i a=2;a<sqrt(1e9);++a){

        if(prm[a]==0) {

        primeSet.pub(a);

        for(i b=2*a;b<sqrt(1e9);b+=a) prm[b]=1;

        }

    }

}

void SieveOfEratosthenes() // O(NLog(LogN)

{

    memset(prime, true, sizeof(prime));

    prime[0]=prime[1]=false;

    for (ll p = 2; p*p < maxN; p++) {

        if (prime[p] == true) {

            for (ll a = p * p;a < maxN;a += p)

                prime[a] = false;

        }

    }

    for (ll p = 2; p <maxN; p++){

        if (prime[p]) primeSet.pub(p);

    }

}

// ll ans=0;

// vec<pair<ll,ll>>a1;

vec<ll>a1;umap<ll,ll> mp1,mp2;

void primeFact1(ll n1){// O(sqrt(N)

    for(ll a=2;a*a<=n1;++a){

        if(n1%a==0){

            ll cnt1=0;

            while(n1%a==0) ++cnt1,n1=n1/a;

            if(cnt1!=0) mp1[a]=1;

            // a1.push_back({cnt1,a});

            // out a<<"^"<<cnt1<<e;

        }

        // out n1<<"^1"<<e;

    }

    if(n1>1) mp1[n1]=1;

    // a1.push_back({1,n1});

}

vec<ll> sieve(maxN,0);

void primeFactofSieve(){// O(Nlog(logN)

    iota(sieve.begin()+1,sieve.end(),1);

    for(ll a=4;a<maxN;a+=2) sieve[a]=2;

    for(ll a=3;a*a<maxN;++a){

        if(sieve[a]==a){

            for(ll b=a*a;b<maxN;b+=a){

                if(sieve[b]==b) sieve[b]=a;

            }

        }

    }

}

umap<ll,ll> sve;

void getFactors(ll n1){ // O(logN)

    while(n1>1){

        // Sieve.push_back(sieve[n1]);

        sve[sieve[n1]]++;

        n1/=sieve[n1];

    }

    // return Sieve;

}

ll phi(ll n1){//Eulors Totient - O(sqrt(N)logN)

    ll res=n1;

    for(i a=2;a*a<=n1;++a){

        if(n1%a==0){

            while(n1%a==0) n1/=a;

            res-=res/a;

        }

    }

    if(n1>1) res-=res/n1;

    return res;

}

ll binaryToDecimal(string s1){

    ll dec_val=0;

    ll base=1;

    ll len=s1.length();

    for(ll a=len-1;a>=0;--a){

        if(s1[a]=='1') dec_val=(dec_val+base)%1000003;

        base*=2;

    }

    return dec_val;

}

string decimalToBinary(ll n1){

    string ans="";

    while(n1){

        if(n1&1) ans+='1';

        else ans+='0';

        n1>>=1;

    }

    reverse(ans.begin(),ans.end());

    return ans;

}

bool operator < (const string &a, const string &b)

{

    if (a.size() < b.size()) return true;

    if (b.size() < a.size()) return false;

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

    {

        if (a[c] < b[c]) return true;

        if (b[c] < a[c]) return false;

    }

    return true;

}

vec<ll> fib(82);

void fibonacii(){

    fib[0]=0;

    fib[1]=fib[2]=1;

    fri(a,3,81){

        fib[a]=fib[a-1]+fib[a-2];

    }

}

ll factorialss(ll n1)

{

    if (n1 == 0 || n1 == 1)

        return 1;

    return n1 * factorialss(n1 - 1);

}

vector<ll> graph[100001];//graph

string number="0123456789";

string abc = "abcdefghijklmnopqrstuvwxyz";

// ll dp[100001][1000000];

void go(){

    ll n1,h=0,j=10,k=2,cnt1=0,cnt2=0,cnt3=0;

    ll maxi=INT_MIN,mini=INT_MAX,f=0,d1,sum=0,flag=0,sum1=0,sum2=0,sum3=0;

    in n1;

    string s1,s2,s3="",s4="";

    // in s1;

    vec<ll> v1,v2,pre(n1);

    // vec<pair<ll,ll>> vp1,vp2;/

    umap<ll,ll> mp1,mp2;

    uset<ll> st1,st2,st3;

    // priority_queue<pair<i,string>> pq1,pq2;

    fori(a,n1) {

        in h;

        mp1[a]=h;

    }

    fori(a,n1) {

        in h;

        mp2[a]=h;

    }

    fori(a,n1){

    	h = mp1[a]-mp2[a];

    	if(h==0) ++cnt3;

    	else if(h>0) v1.pub(h);

    	// if(h<0) cnt1++,st1.insert(h);

    	// else if(h==0) cnt3++;

    	// else cnt2++,st2.insert(h);

    }

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

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

    // h = st2.size();k = st1.size();

    // sum+=cnt3*cnt2;

    // sum+=

    k = v1.size();

    fori(a,n1){

    	h = mp1[a]-mp2[a];

    	if(h>0) continue;

    	h = abs(h);

    	i up = upper_bound(v1.begin(),v1.end(),h) - v1.begin();

    	cnt1+=k-up;

    }

    out cnt1+(k*(k-1)/2);

    out e;

}

signed main() {

    F

    I

    O

    // fri(a,1,100000)

    // for(i b=a;b<=100000;b+=a) fac[b].push_back(a);

    // factorial();

    i T=1;

    // in T;

    // memset(dp,-1,sizeof(dp));

    precompute();

    // cout << fixed << setprecision(10);

    n(t) go();

////////////////////////////////////////////////

// auto start = std::chrono::system_clock::now() ;

// auto end = std::chrono::system_clock::now();

//

// std::chrono::duration<double> elapsed_seconds = end-start;

// std::time_t end_time = std::chrono::system_clock::to_time_t(end);

//

// #ifndef ONLINE_JUDGE

// cout<<"RUN TIME : "<<elapsed_seconds.count()<<"s"<<endl;

// #endif

    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 eps 1e-9

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

#define endl '\n'

#define ll              long long

#define ull             unsigned long long

#define MAX 200010

#define pb push_back

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

#define pf push_front

#define fi first

#define se second

#define pii pair<int,int>

const long long  INF = LLONG_MAX;

using namespace std;

const int N=3e5+10,M=10;

const int mod=998244353;

#define int long long

/*----------------------------------------------------------------*/

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

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

/*----------------------------------------------------------------*/

void READ(){

#ifndef ONLINE_JUDGE

    freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);

#endif

}

void solve(){

    map<pair<char,char>,char>mp;

    map<string,int>frq;

    mp[{'S','T'}]=mp[{'T','S'}]='E';

    mp[{'E','S'}]=mp[{'S','E'}]='T';

    mp[{'E','T'}]=mp[{'T','E'}]='S';

    int n,m;

    cin>>n>>m;

    vector<string>v(n);

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

        cin>>v[i];

        frq[v[i]]++;

    }

    int ans=0;

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

        string s=v[i];

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

            string t=v[j];

            string x;

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

                if(s[k]==t[k]){

                    x+=s[k];

                }

                else{

                    x+=mp[{s[k],t[k]}];

                }

            }

            ans+=frq[x];

        }

    }

    cout<<ans/3<<endl;

}

signed main() {

    emailam

    //READ();

    int t=1;

    //cin>>t;

    while(t--){

        solve();

    }

}


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

#include<bits/stdc++.h>

using namespace std;

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

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

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

#define F first

#define S second

#define oo 1e18+5

#define MOD ll(1e9+7)

#define fvec(i,vec) for(auto i:vec)

#define pb push_back

#define mpr make_pair

#define min3(a,b,c) min(a,min(b,c))

#define max3(a,b,c) max(a,max(b,c))

# define M_PI  3.14159265358979323846

#define int long long

#define foor(i,a,b) for (ll i = a; i < b; i++)

#define num_ocur_insort(vec,x) equal_range(all(vec), x) /* return pair upper lower   auto r=num_ocur_insort(a,6);*/

typedef int ll;

typedef unsigned long long ull;

typedef vector<ll> vi;

typedef vector<vi> vii;

typedef pair<ll,ll> pi;

typedef vector<pi> vip;

typedef vector<string> vss;

typedef map<ll,ll> mapi;

typedef unordered_map<ll,ll> umapi;

typedef vector<vip> viip;

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

ll gcd(ll a, ll b) { return ((b == 0) ? a : gcd(b, a % b)); }

const int N=10000;

ll fun(vip &a) {

    ll sum = 1;

    ll mashgol = a[0].first;

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

        if (a[i].second > mashgol) {

            mashgol = a[i].first;

            sum++;

        }

    }

    return sum;

}

void solve(ll hh ) {

    ll n;

    cin >> n;

    vi a(n);

    vi pr(n);

    ll ans = 0, res;

    map<ll, vector<pi>> mp;

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

        cin >> a[i];

    }

    pr[0] = a[0];

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

        pr[i] += pr[i - 1]+a[i];

    }

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

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

            ll lst = 0;

            if (i)lst = pr[i - 1];

            ll val = pr[j] - lst;

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

        }

    }

    for (auto it: mp) {

        auto vec = it.second;

        sort(all(vec));

        ll temp = fun(vec);

        if (temp > ans) {

            ans = temp;

            res = it.first;

        }

    }

    auto vec = mp[res];

    sort(all(vec));

    vip fin;

    ll mas = vec[0].first;

    fin.push_back({vec[0].second, vec[0].first});

    for (int i = 1; i < vec.size(); ++i) {

        if (vec[i].second > mas) {

            mas = vec[i].first;

            fin.push_back({vec[i].second, vec[i].first});

        }

    }

    cout << ans << endl;

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

        cout << fin[i].first +1<< " " << fin[i].second+1 << endl;

    }

}

signed main() {

    ios_base::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    ll t = 1;

   // cin >> t;

    ll hh=t;

    while (t--) {

        solve(hh-t);

    }

}


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

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

#define endl "\n"

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

#define FOR1(i,s,e,d) for(long long i = s; i < e; i += d)

#define FOR2(i,s,e,d) for(long long i = s; i > e; i -= d)

#define FOR3(x,v) for (auto x : v)

#define pll pair<long long, long long>

#define vl vector<long long>

#define vll vector<pair<long long, long long>>

#define vvl vector<vector<long long>>

#define vs vector<string>

#define vc vector<char>

#define mll map<long long, long long>

#define mlc map<long long,char>

#define mls map<long long,string>

#define mlvl map<long long, vector<long long>>

#define pql priority_queue<long long>

#define over(ans) {cout<<ans<<endl;return;}

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

const ll INF = 1e18;

const ll mod = 998244353;

const ll mod1 = 1e9 + 7;

template<class T, class T1> bool ckmin(T& a, const T1& b) { return b < a ? a = b, 1 : 0; }

template<class T, class T1> bool ckmax(T& a, const T1& b) { return a < b ? a = b, 1 : 0; }

template<class c>

void display(c vect) {

    FOR3(x, vect) cout << x << ' ';

    cout << "\n";

}

void display(vll v) {

    FOR3(x, v) cout << "(" << x.first << ", " << x.second << ") ";

    cout << endl;

}

void display(vvl vect2d) {

    FOR3(x, vect2d) display(x);

}

void display(mll m) {

    FOR3(x, m) cout << x.first << ' ' << x.second << endl;

}

void display(mlvl  m) {

    FOR3(x, m) {

        cout << x.first << " : ";

        display(x.second);

    }

}

vl vin(int n) {

    vl v(n);

    FOR(i,n) cin >> v[i];

    return v;

}

int to_int(string s) {

    return stoi(s);

}

int to_int(char c) {

    string s = {c};

    return stoi(s);

}

char to_char(int i) {

    return char('0' + i);

}

int is_prime(ll n) {

    if (n == 1) return 0;

    if (n == 2 || n == 3) return 1;

    if ( n % 6 == 1 || n % 6 == 5) {

        for (ll k = 5; k*k <= n; k += 2) if (n % k == 0) return 0;

        return 1;

    }

    return 0;

}

ll gcd(ll a, ll b) {

    return b == 0 ? a : gcd(b, a % b);

}

ll inv(ll a, ll b){

    return 1<a ? b - inv(b%a,a)*b/a : 1;

}

template<class T>

T power(T a, ll b) {

    T res = 1;

    for(; b; b /= 2, a *= a) if (b%2) {res *= a;}

    return res;

}

template<class T>

T powermod(T a, ll b, ll P) {

    a %= P; ll res = 1;

    while (b > 0) {

        if (b & 1) res = res * a % P;

        a = a * a % P;

        b >>= 1;

    }

    return res;

}

vl factors(ll n) {

    vl factors;

    ll i = 1;

    while(i*i <= n) {

        if (n%i == 0) {

            factors.push_back(i);

            if (i*i != n) factors.push_back(n/i);

        }

        i++;

    }

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

    return factors;

}

ll lsb(ll a) {return (a & -a);}

template < typename T>

struct Fenwick {

    const ll n;

    vector<T> a;

    Fenwick(ll n) : n(n), a(n) {}

    void add(ll x, T v) {

        for (ll i = x+1; i <= n; i += i & -i) {

            a[i-1] += v;

        }

    }

    T sum(ll x) {

        T ans = 0;

        for (ll i = x; i > 0; i -= i & -i) {

            ans += a[i-1];

        }

        return ans;

    }

    T rangeSum(ll l, ll r) {

        return sum(r) - sum(l);

    }

};

struct DSU {

    vl f, siz;

    DSU(ll n) : f(n), siz(n-1) { iota(f.begin(), f.end(), 0); }

    ll leader(ll x) {

        while (x != f[x]) x = f[x] = f[f[x]];

        return x;

    }

    bool same(ll x, ll y) { return leader(x) == leader(y); }

    bool merge(ll x, ll y) {

        x = leader(x);

        y = leader(y);

        if (x == y) return false;

        siz[x] += siz[y];

        f[y] = x;

        return true;

    }

    ll size(ll x) { return siz[leader(x)]; }

};

ll ncrmodP(ll n, ll r, ll P) {

    ll fac[n+1];

    fac[0] = 1;

    FOR1(i, 1, n+1, 1) {

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

    }

    return (fac[n] * inv(fac[r], P) % P * inv(fac[n-r], P) % P) % P;

}

// (condition ? value if yes : value if no)

// sort(v.begin(), v.end(), [](data_type x, data_type y) -> bool {

//     return condition;

// });

void init() {

}

void solve() {

    ll n; cin >> n;

    vl a = vin(n);

    sort(all(a), greater<ll>());

    display(a);

}

int main() {

    ios::sync_with_stdio(false), cin.tie(nullptr);

    init();

    ll t = 1;

    cin >> t;

    FOR(i,t) {

        // cout << "Case #" << i+1 << ": ";

        solve();

    }

}


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

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

int t, n, m, a, sum;

int main()
{
    cin >> t;
    while (t--){
        cin >> n >> m;
        int sum = 0;
        for(int i=1; i<=n; ++i){
            cin >> a;
            sum += a;
        }
        cout << min(m,sum) << endl;
    }
}


B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19).

#include <bits/stdc++.h>

using namespace std;

typedef long long int ll;

# define mod 998244353

int main()

{

/*

  for(int a=1;a<=100;a++)

  {

      for(int b=1;b<=1000;b++)

      {

          int now=a*b+a+b;

          int bb=b,cnt=1;

          while(bb)

          {

              cnt*=10;

              bb/=10;

          }

          ll c=a*cnt+b;

          //cout<<a<<" "<<b<<" "<<c<<endl;

          if(c==now)

          {

              cout<<a<<" "<<b<<endl;

          }

      }

  }

*/

int t;

cin>>t;

while(t--)

{

    ll a,b;

    cin>>a>>b;ll now=9ll;

    ll cnt=0;

    while(now<=b)

    {

        cnt++;

        now*=10ll;

        now+=9;

    }

    cout<<cnt*a<<endl;

}

    return 0;

}


A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5
1 1 1 0 0
0 1 1 1 1
OutputCopy3
InputCopy3
0 0 0
0 0 0
OutputCopy-1
InputCopy4
1 1 1 1
1 1 1 1
OutputCopy-1
InputCopy9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
OutputCopy4
NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.

#include <bits/stdc++.h>

using namespace std;

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

  int n;

  scanf("%d", &n);

  vector<pair<int, int>> vec(n);

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

    scanf("%d", &vec[i].first);

  }

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

    scanf("%d", &vec[i].second);

  }

  int score_a = 0, score_b = 0;

  for (const auto &[a, b] : vec) {

    score_a += a && !b;

    score_b += !a && b;

  }

  if (score_a == 0) {

    printf("-1\n");

    exit(0);

  }

  printf("%d\n", score_b / score_a + 1);

}


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

// #pragma GCC optimize("O3,unroll-loops")

// #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")

#include <bits/stdc++.h>

#include <ext/rope>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/hash_policy.hpp>

#include <ext/pb_ds/tree_policy.hpp>

#include <ext/pb_ds/trie_policy.hpp>

#include <ext/pb_ds/priority_queue.hpp>

using namespace std;

using namespace __gnu_cxx;

using namespace __gnu_pbds;

template <class T> using Tree = tree<T, null_type, less_equal<T>, rb_tree_tag,tree_order_statistics_node_update>;

using Trie = trie<string, null_type, trie_string_access_traits<>, pat_trie_tag, trie_prefix_search_node_update>;

// template <class T> using heapq = __gnu_pbds::priority_queue<T, greater<T>, pairing_heap_tag>;

template <class T> using heapq = std::priority_queue<T, vector<T>, greater<T>>;

#define ll long long

#define i128 ll

#define ld long double

#define ui unsigned int

#define ull unsigned long long

#define pii pair<int, int>

#define pll pair<ll, ll>

#define pdd pair<ld, ld>

#define vi vector<int>

#define vvi vector<vector<int>>

#define vll vector<ll>

#define vvll vector<vector<ll>>

#define vpii vector<pii>

#define vpll vector<pll>

#define lb lower_bound

#define ub upper_bound

#define pb push_back

#define pf push_front

#define eb emplace_back

#define fi first

#define se second

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

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

#define each(x, v) for(auto& x: v)

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

#define elif else if

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

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

#define mst(x, a) memset(x, a, sizeof(x))

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

#define bitcnt(x) (__builtin_popcountll(x))

#define endl "\n"

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

#define Ran(a, b) rng() % ( (b) - (a) + 1 ) + (a)

struct custom_hash {

    static uint64_t splitmix64(uint64_t x) {

        // http://xorshift.di.unimi.it/splitmix64.c

        x += 0x9e3779b97f4a7c15;

        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;

        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;

        return x ^ (x >> 31);

    }

    size_t operator()(uint64_t x) const {

        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();

        return splitmix64(x + FIXED_RANDOM);

    }

    size_t operator()(pair<uint64_t,uint64_t> x) const {

        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();

        return splitmix64(x.first + FIXED_RANDOM) ^ (splitmix64(x.second + FIXED_RANDOM) >> 1);

    }

};

const i128 ONE = 1;

istream &operator>>(istream &in, i128 &x) {

    string s;

    in >> s;

    bool minus = false;

    if (s[0] == '-') {

        minus = true;

        s.erase(s.begin());

    }

    x = 0;

    for (auto i : s) {

        x *= 10;

        x += i - '0';

    }

    if (minus) x = -x;

    return in;

}

ostream &operator<<(ostream &out, i128 x) {

    string s;

    bool minus = false;

    if (x < 0) {

        minus = true;

        x = -x;

    }

    while (x) {

        s.push_back(x % 10 + '0');

        x /= 10;

    }

    if (s.empty()) s = "0";

    if (minus) out << '-';

    reverse(s.begin(), s.end());

    out << s;

    return out;

}

template <class T> ostream &operator<<(ostream &os, const vector<T> &v) {

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

template <class T> ostream &operator<<(ostream &os, const set<T> &v) {

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

template <class T> ostream &operator<<(ostream &os, const multiset<T> &v) {

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

template <class T> ostream &operator<<(ostream &os, const Tree<T> &v) {

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

template <class T, class S> ostream &operator<<(ostream &os, const pair<T, S> &p) {

    os << p.first << " " << p.second;

    return os;

}

ll gcd(ll x,ll y) {

    if(!x) return y;

    if(!y) return x;

    int t = __builtin_ctzll(x | y);

    x >>= __builtin_ctzll(x);

    do {

        y >>= __builtin_ctzll(y);

        if(x > y) swap(x, y);

        y -= x;

    } while(y);

    return x<<t;

}

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

ll exgcd(ll a, ll b, ll &x, ll &y) {

    if(!b) return x = 1, y = 0, a;

    ll d = exgcd(b, a % b, x, y);

    ll t = x;

    x = y;

    y = t - a / b * x;

    return d;

}

ll max(ll x, ll y) { return x > y ? x : y; }

ll min(ll x, ll y) { return x < y ? x : y; }

ll Mod(ll x, int mod) { return (x % mod + mod) % mod; }

ll pow(ll x, ll y, ll mod){

    ll res = 1, cur = x;

    while (y) {

        if (y & 1) res = res * cur % mod;

        cur = ONE * cur * cur % mod;

        y >>= 1;

    }

    return res % mod;

}

ll probabilityMod(ll x, ll y, ll mod) {

    return x * pow(y, mod-2, mod) % mod;

}

vvi getGraph(int n, int m, bool directed = false) {

    vvi res(n);

    rep(_, 0, m) {

        int u, v;

        cin >> u >> v;

        u--, v--;

        res[u].emplace_back(v);

        if(!directed) res[v].emplace_back(u);

    }

    return res;

}

vector<vpii> getWeightedGraph(int n, int m, bool directed = false) {

    vector<vpii> res(n);

    rep(_, 0, m) {

        int u, v, w;

        cin >> u >> v >> w;

        u--, v--;

        res[u].emplace_back(v, w);

        if(!directed) res[v].emplace_back(u, w);

    }

    return res;

}

const ll LINF = 0x1fffffffffffffff;

const ll MINF = 0x7fffffffffff;

const int INF = 0x3fffffff;

const int MOD = 1000000007;

const int MODD = 998244353;

const int N = 1e6 + 10;

class SegmentTree {

public:

	struct STNode {

		STNode () : left(nullptr), right(nullptr), val(0), maxval(0), minval(0), lazy(0), mlazy(LINF) {}

		STNode* left;

		STNode* right;

		ll val;

		ll maxval;

		ll minval;

		ll lazy;

		ll mlazy;

	};

	STNode* root;

	SegmentTree() { root = new STNode(); }

	~SegmentTree() {}

	void assign(STNode* node, int l, int r, int start, int end, ll x) {

		if (l == start && r == end) {

			node->val = 0;

			node->maxval = 0;

			node->minval = 0;

			node->lazy = 0;

			node->mlazy = x;

			return;

		}

		pushdown(node);

		int mid = l+r>>1;

		if (end <= mid) {

			assign(node->left, l, mid, start, end, x);

		} elif (start > mid) {

			assign(node->right, mid+1, r, start, end, x);

		} else {

			assign(node->left, l, mid, start, mid , x);

			assign(node->right, mid+1, r, mid+1, end, x);

		}

		pushup(node, mid-l+1, r-mid);

	}

	void add(STNode* node, int l, int r, int start, int end, ll x){

		if (l == start && r == end) {

			node->lazy += x;

			return;

		}

		pushdown(node);

		int mid = l+r>>1;

		if (end <= mid) {

			add(node->left, l, mid, start, end, x);

		} elif (start > mid) {

			add(node->right, mid+1, r, start, end, x);

		} else {

			add(node->left, l, mid, start, mid , x);

			add(node->right, mid+1, r, mid+1, end, x);

		}

		pushup(node, mid-l+1, r-mid);

	}

	ll querySum(STNode* node, int l, int r, int start, int end) {

		if (l == start && r == end) {

			return node->val + node->lazy * (r-l+1) + \

				(node->mlazy == LINF ? 0 : node->mlazy * (r-l+1));

		}

		pushdown(node);

		int mid = l+r>>1;

		ll res;

		if (end <= mid) {

			res = querySum(node->left, l, mid, start, end);

		} elif (start > mid) {

			res = querySum(node->right, mid+1, r, start, end);

		} else {

			res = querySum(node->left, l, mid, start, mid) +

			querySum(node->right, mid+1, r, mid+1, end);

		}

		pushup(node, mid-l+1, r-mid);

		return res;

	}

	ll queryMax(STNode* node, int l, int r, int start, int end) {

		if (l == start && r == end) {

			return node->maxval + node->lazy + \

				(node->mlazy == LINF ? 0 : node->mlazy);

		}

		pushdown(node);

		int mid = l+r>>1;

		ll res;

		if (end <= mid) {

			res = queryMax(node->left, l, mid, start, end);

		} elif (start > mid) {

			res = queryMax(node->right, mid+1, r, start, end);

		} else {

			res = max(queryMax(node->left, l, mid, start, mid),

			queryMax(node->right, mid+1, r, mid+1, end));

		}

		pushup(node, mid-l+1, r-mid);

		return res;

	}

	ll queryMin(STNode* node, int l, int r, int start, int end) {

		if (l == start && r == end) {

			return node->minval + node->lazy + \

				(node->mlazy == LINF ? 0 : node->mlazy);

		}

		pushdown(node);

		int mid = l+r>>1;

		ll res;

		if (end <= mid) {

			res = queryMin(node->left, l, mid, start, end);

		} elif (start > mid) {

			res = queryMin(node->right, mid+1, r, start, end);

		} else {

			res = min(queryMin(node->left, l, mid, start, mid),

			queryMin(node->right, mid+1, r, mid+1, end));

		}

		pushup(node, mid-l+1, r-mid);

		return res;

	}

	void pushdown(STNode* node) {

		if (node->left == nullptr) {

			node->left = new STNode();

		}

		if (node->right == nullptr) {

			node->right = new STNode();

		}

		if (node->mlazy != LINF) {

			node->left->lazy = 0;

			node->left->val = 0;

			node->left->maxval = 0;

			node->left->minval = 0;

			node->right->lazy = 0;

			node->right->val = 0;

			node->right->maxval = 0;

			node->right->minval = 0;

			node->left->mlazy = node->mlazy;

			node->right->mlazy = node->mlazy;

			node->mlazy = LINF;

		}

		if (node->lazy) {

			node->left->lazy += node->lazy;

			node->right->lazy += node->lazy;

			node->lazy = 0;

		}

	}

	void pushup(STNode* node, int ln, int rn) {

		node->val = node->left->val + node->left->lazy * ln + \

					(node->left->mlazy == LINF ? 0 : node->left->mlazy * ln) + \

					node->right->val + node->right->lazy * rn + \

					(node->right->mlazy == LINF ? 0 : node->right->mlazy * rn);

		node->maxval = max(node->left->maxval + node->left->lazy + \

						(node->left->mlazy == LINF ? 0 : node->left->mlazy),

						node->right->maxval + node->right->lazy + \

						(node->right->mlazy == LINF ? 0 : node->right->mlazy));

		node->minval = min(node->left->minval + node->left->lazy + \

						(node->left->mlazy == LINF ? 0 : node->left->mlazy),

						node->right->minval + node->right->lazy + \

						(node->right->mlazy == LINF ? 0 : node->right->mlazy));

	}

};

void solve() {

    int n, m;

    cin >> n >> m;

    vi a(m);

    each(i, a) cin >> i;

    vi pos(n+1);

    vi mn(n+1);

    vi mx(n+1);

    rep(i, 1, n+1) mn[i] = mx[i] = i, pos[i] = i + m;

    SegmentTree st;

    rep(i, 1, n+1) st.add(st.root, -1, N, pos[i], pos[i], 1);

    int cur = m;

    each(i, a) {

        mn[i] = 1;

        mx[i] = max(mx[i], st.querySum(st.root, -1, N, 0, pos[i]));

        st.add(st.root, -1, N, pos[i], pos[i], -1);

        pos[i] = cur--;

        st.add(st.root, -1, N, pos[i], pos[i], 1);

    }

    rep(i, 1, n+1) {

        mx[i] = max(mx[i], st.querySum(st.root, -1, N, 0, pos[i]));

        cout << mn[i] << " " << mx[i] << endl;

    }

}

signed main() {

    ios::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    int t = 1;

    // cin >> t;

    while (t--) {

        solve();

    }

    return 0;

}


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

//श्रमं विना न किमपि साध्यम्
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define all(a) (a).begin(),(a).end()
#define rev(p) reverse(p.begin(),p.end());
#define v vector
#define sortt(a) sort(all(a))
#define pll pair<ll,ll>
#define sz(c) (int)c.size()
#define fr first
#define sc second
#define pb push_back
#define pf push_front
#define eb emplace_back
#define mp make_pair
#define rep(i,a,n) for(int i=a ; i<n ; i++)
#define pi (2*acos(0.0))
#define F(a,b,i) for(int i=a;i<b;i++)
#define FN(a,b,i) for(int i=a-1;i>=b;i--)
#define endl "\n"
//*****DEBUG FUNCTIONS********//
#ifndef ONLINE_JUDGE
template<typename T>void __p(std::vector<T> v);
template<typename T>void __p(T a){cout<<a;}
template<typename T, typename F>void __p(pair<T, F> a){cout<<"{";__p(a.first);cout<<",";__p(a.second);cout<<"}";}
template<typename T>void __p(std::vector<T> a) {cout<<"{";for(auto it=a.begin(); it<a.end(); it++)__p(*it),cout<<",}"[it+1==a.end()];}
template<typename T>void __p(std::set<T> a){cout<<"{";for(auto it=a.begin(); it!=a.end();){__p(*it); cout<<",}"[++it==a.end()];}}
template<typename T>void __p(std::multiset<T> a){cout<<"{";for(auto it=a.begin(); it!=a.end();){__p(*it); cout<<",}"[++it==a.end()];}}
template<typename T, typename F>void __p(std::map<T,F> a){cout<<"{\n";for(auto it=a.begin(); it!=a.end();++it){__p(it->first);cout << ": ";__p(it->second);cout<<"\n";}cout << "}\n";}
template<typename T, typename ...Arg>void __p(T a1, Arg ...a){__p(a1);__p(a...);}
template<typename Arg1>void __f(const char *name, Arg1 &&arg1){cout<<name<<" : ";__p(arg1);cout<<endl;}
template<typename Arg1, typename ... Args>void __f(const char *names, Arg1 &&arg1, Args &&... args) {int bracket=0,i=0;for(;; i++)if(names[i]==','&&bracket==0)break;else if(names[i]=='(')bracket++;else if(names[i]==')')bracket--;const char *comma=names+i;cout.write(names,comma-names)<<" : ";__p(arg1);cout<<" | ";__f(comma+1,args...);}
#define trace(...) cout<<"Line:"<<__LINE__<<" ", __f(#__VA_ARGS__, __VA_ARGS__)
#else
#define trace(...)
#define error(...)
#endif
//*****DEBUG FUNCTIONS********//
ll inf =1e18;
ll mod1 = 1e9 + 7;
ll mod2=998244353;
ll log2n(ll n) // floor of(log2 n) , log2 (13)=3
{
  //FAILS FOR N=0
  if(n==0)return 0;
  return (63-__builtin_clzll(n));
}
bool is_prime( ll n)
{
  if(n==1)return false;
  ll i=2;
  for(i=2;i*i<=n;i++)
  {
    if(n%i==0)
    {
      return false;
    }
  }
  return true;
}
ll power(ll x, ll y, ll p)
{
    x = x % p;
    if(x==0)return 0;
    ll res = 1;
    while (y > 0)
    {
        if (y & 1)
            res = (res * x) % p;
        y = y >> 1;
        x = (x * x) % p;
    }
    return res;
}
ll pwr(ll x, ll y){if(x==0)return 0;ll res = 1;x = x ;while (y > 0){if (y & 1)res = (res * x);y = y >> 1;x = (x * x) ;}return res;}
ll modInverse(ll n, ll p){return power(n, p - 2, p);}
ll ncr(ll n, ll r , ll modd){if(r>n){return 0;}
    if(r>n-r){r = n-r;}ll ans = 1;
    for(ll i = 1; i<=r ; i++){
        ans *= (n-i+1);ans%= modd;ans *= modInverse(i, modd);ans %= modd;}
 return ans;}
ll _gcd(ll a, ll b){ if (b == 0) return a; return _gcd(b, a % b);}
//********CLOCK********
ll begtime = clock();
#define time() cerr << "\n\nTime elapsed: " << (clock() - begtime)*1000/CLOCKS_PER_SEC << " ms\n\n";
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
//********CLOCK********
ll testctr;
const int N=2e6+5;

void solve()
{

  ll i, j , t1 , t2 , t3 ,t4 , flag;
  //ARE YOU REALLY SURE()?
  //chckdstc?
  //MXMN?BSPZL
  //order_1e18?overflow!!!

  ll n; cin>>n;
  double ans=0;
  for(i=1;i<=n;i++)
  {
    ans+=(double)1/i;
  }
  cout<<ans<<endl;

}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);cout.tie(NULL);
#ifndef ONLINE_JUDGE
    freopen("input1.txt", "r", stdin);
    freopen("output1.txt", "w", stdout);
#endif
  cout<<fixed<<setprecision(20);
  ll TESTS;
  //cin>>TESTS;
  TESTS=1;
  for(int i=1;i<=TESTS;i++)
  {
    testctr=i;
    // cout<<"Case #"<<i<<":"<<" ";
    solve();
  }
  time();
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define int long long

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

signed main(){

    ios_base::sync_with_stdio(0);

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

    int t;

    cin >> t;

    while (t--){

        int n;

        cin >> n;

        int sum = 0,cnt = 0;

        For(i,0,n){

            int temp;

            cin >> temp;

            if (temp == 0) cnt++;

            sum += temp;

        }

        if (sum + cnt == 0) cnt++;

        cout <<cnt<<"\n";

    }

    return 0;

}


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

#include<bits/stdc++.h>

typedef long long ll;

typedef unsigned long long ull;

using namespace std;

const ll mod = 998244353;

const int mm = 1e5 + 10;

ll a[mm];

void solve(){

	int n;

	cin>>n;

	ll sum=0;

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

		cin>>a[i],sum+=a[i];

	}

	ll mal=-mod*2,mar=-mod*2;

	ll bj=0;

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

		bj+=a[i];

		mal=max(mal,bj);

		if(bj<0)bj=0;

	}bj=0;

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

		bj+=a[j];

		mar=max(mar,bj);

		if(bj<0)bj=0;

	}

	if(sum>max(mal,mar))cout<<"YES";

	else cout<<"NO";

	cout<<"\n";

}

int main(){

	std::ios::sync_with_stdio(false);

	std::cin.tie(0);

	std::cout.tie(0);

	int t;

	cin>>t;

	while(t--){

		solve();

	}

}