F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.InputThe first line contains an integer nn (2≤n≤1052≤n≤105) — the number of elements in the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1051≤ai≤105) — the elements of the array aa.OutputPrint one integer, the maximum value of the least common multiple of two elements in the array aa.ExamplesInputCopy3
13 35 77
OutputCopy1001InputCopy6
1 2 4 8 16 32
OutputCopy32

#include<bits/stdc++.h>
using namespace std;
using ll=long long;
const ll maxN=2e5+10;
#define pb push_back
#define int ll
#define pli pair<ll,ll>
#define fi first
#define se second
#define task "danang"
#define plii pair<ll,pli>
ll ct[maxN];
bool check(ll x)
{
    ll s=x;
    for(int i=2;i*i<=x;i++)
    {
        ll cnt=0;
        while(x%i==0)
        {
            cnt++;
            x/=i;
        }
        if(cnt>0) ct[s]++;
        if(cnt>1) return false;
    }
    if(x>1) ct[s]++;
    return true;
}
vector<ll> d[maxN];
ll cnt[maxN];
void add(ll x)
{
    for(auto zz:d[x])
    {
        cnt[zz]++;
    }
}
void del(ll x)
{
    for(auto zz:d[x])
    {
        cnt[zz]--;
    }
}
ll cal(ll x)
{
    ll ans=0;
    for(auto zz:d[x])
    {
        if(ct[zz]%2==0) ans+=cnt[zz];
        else ans-=cnt[zz];
    }
    return ans;
}
ll n,a[maxN];
vector<ll> vec[maxN];
bool c[maxN];
void solve()
{
    cin >> n;
    for(int i=1;i<=n;i++)
    {
        cin >> a[i];
        vec[a[i]].pb(i);
    }
    for(int i=1;i<=1e5;i++)
    {
        c[i]=check(i);
    }
    for(int i=1;i<=1e5;i++)
    {
        if(c[i])
        {
            for(int j=i;j<=1e5;j+=i)
            {
                d[j].pb(i);
            }
        }
    }
    vector<ll> x;
    deque<ll> dq;
    ll ans=0;
    for(int i=1;i<=1e5;i++)
    {
        x.clear();
        for(int j=i;j<=1e5;j+=i)
        {
            for(int k=0;k<min(2ll,(int)vec[j].size());k++)
            {
                x.pb(j/i);
            }
        }
        dq.clear();
        for(int j=(int)x.size()-1;j>=0;j--)
        {
            if(cal(x[j])>=1)
            {
                ll cc=cal(x[j]);
                while(dq.size()>0)
                {
                    if(__gcd(x[j],dq.back())==1)
                    {
                        cc--;
                        if(cc==0) break;
                    }
                    del(dq.back());
                    dq.pop_back();
                }
                ans=max(ans,i*x[j]*dq.back());
            }
            dq.pb(x[j]);
            add(x[j]);
        }
        for(int j=0;j<x.size();j++)
        {
            for(auto zz:d[x[j]])
            {
                cnt[zz]=0;
            }
        }
    }
    cout << ans;
}
signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    //freopen(task".inp","r",stdin);
    //freopen(task".out","w",stdout);
    solve();
}


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

#include<iostream>

#include<stdio.h>

#include<list>

#include<set>

#include<map>

#include<string>

#include<functional>

#include <cmath>

#include <cstdio>

#include <vector>

#include <algorithm>

#include<bits/stdc++.h>

using namespace std;

#define ll long long

#define forn(i,k,n) for(int i=k;i<n;i++)

int main(){

    int t;cin>>t;

    while(t--){

        int n;cin>>n;int a[n];forn(i,0,n){cin>>a[i];}

        int k=0;

        int k1=0;

        // if(n==1){cout<<"YES"<<endl;continue;}

        forn(i,0,n){

            if(a[i]%2==0){k++;}

            if(a[i]%2!=0){k1++;}

        }

        if(k==n){cout<<"YES"<<endl;continue;}

        if(k1==n){cout<<"YES"<<endl;continue;}

        else{cout<<"NO"<<endl;}

    }

    return 0;

}


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

#include <bits/stdc++.h>

#define int long long

#define fi first

#define se second

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

using namespace std;

int32_t main()

{

        ios_base::sync_with_stdio(false);

        cin.tie(NULL);

        int n;

        cin >> n;

        priority_queue<int> pq;

        int ans = 0;

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

                int x;

                cin >> x;

                pq.push(x);

                pq.push(x);

                ans += pq.top() - x;

                pq.pop();

        }

        cout << ans << '\n';

        return 0;

}


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>

using namespace std;

#define mp make_pair

#define pb emplace_back

#define rep(i, s, e) for (int i = s; i <= e; ++i)

#define drep(i, s, e) for (int i = s; i >= e; --i)

#define file(a) freopen(#a".in", "r", stdin), freopen(#a".out", "w", stdout)

#define pv(a) cout << #a << " = " << a << endl

#define pa(a, l, r) cout << #a " : "; rep(_, l, r) cout << a[_] << ' '; cout << endl

using pii = pair <int, int>;

const int P = 1e9 + 7;

const int N = 1e5 + 10;

const int W = 32;

const int K = 400;

int read() {

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

  for (; c < '0' || c > '9'; c = getchar()) if (c == '-') f = -1;

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

  return x * f;

}

int inc(int a, int b) { return (a += b) >= P ? a - P : a; }

int dec(int a, int b) { return (a -= b) < 0 ? a + P : a; }

int mul(int a, int b) { return 1ll * a * b % P; }

int qpow(int a, int b) { int res = 1; for (; b; b >>= 1, a = mul(a, a)) if (b & 1) res = mul(res, a); return res; }

struct node {

  int dat[5];

  node() { rep(i, 0, 4) dat[i] = 0; }

  void clear() { rep(i, 0, 4) dat[i] = 0; }

  bool insert(int x) {

    drep(i, 4, 0) if (x >> i & 1) {

      if (!dat[i]) {

        dat[i] = x;

        rep(j, 0, i - 1) if (dat[j] && dat[i] >> j & 1) dat[i] ^= dat[j];

        rep(j, i + 1, 4) if (dat[j] && dat[j] >> i & 1) dat[j] ^= dat[i];

        return true;

      }

      else x ^= dat[i];

    }

    return false;

  }

  int val() {

    int res = 0;

    rep(i, 0, 4) res |= dat[i] << i * (i + 1) / 2;

    return res;

  }

} base[K], con;

int cnt, id[N], h[N], add[K][K];

void dfs(int i, node cur) {

  if (i == W) {

    if (!id[cur.val()]) id[cur.val()] = ++ cnt, base[cnt] = cur, h[cnt] = cur.val();

    return;

  }

  dfs(i + 1, cur);

  if (cur.insert(i)) dfs(i + 1, cur);

}

int join(int u, int v) {

  if (~add[u][v]) return add[u][v];

  node s = base[u], t = base[v];

  rep(i, 0, 4) if (t.dat[i]) {

    if (!s.insert(t.dat[i])) return add[u][v] = add[v][u] = 0;

  }

  return id[s.val()];

}

int n, m, d[N], f[K], g[K], ans, v1[N], v2[N];

vector <pii> e[N];

map <int, int> E[N];

bool tag[N];

int fa[N];

int get(int u) { return u == fa[u] ? u : fa[u] = get(fa[u]); }

void merge(int u, int v) { fa[get(v)] = get(u); }

bool dfs0(int u, int fa) {

  tag[u] = true;

  bool flag = true;

  for (auto [v, w] : e[u]) if (v != 1 && v != fa) {

    if (!tag[v]) d[v] = d[u] ^ w, flag &= dfs0(v, u);

    else if (u < v) flag &= con.insert(d[u] ^ d[v] ^ w);

  }

  return flag;

}

int main() {

  dfs(0, node());

  rep(i, 1, cnt) rep(j, 1, cnt) add[i][j] = -1;

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

  rep(i, 1, n) fa[i] = i;

  rep(i, 1, m) {

    int u = read(), v = read(), w = read();

    e[u].pb(mp(v, w)), e[v].pb(mp(u, w));

    E[u][v] = E[v][u] = w;

    if (u > 1 && v > 1) merge(u, v);

  }

  tag[1] = true, f[1] = 1;

  for (auto [r, w] : e[1]) {

    if (!v1[get(r)]) v1[get(r)] = r;

    else v2[get(r)] = r;

  }

  rep(r, 1, n) if (v1[r]) {

    if (!v2[r]) {

      int u = v1[r];

      if (dfs0(u, 1)) {

        int p = id[con.val()];

        fill(g, g + K, 0);

        rep(i, 1, cnt) {

          g[i] = inc(g[i], f[i]);

          if (join(i, p)) g[join(i, p)] = inc(g[join(i, p)], f[i]);

        }

        swap(f, g);

      }

      con.clear();

    }

    else {

      int u = v1[r], v = v2[r];

      fill(g, g + K, 0);

      rep(i, 1, cnt) g[i] = inc(g[i], f[i]);

      if (dfs0(u, 1)) {

        int p = id[con.val()];

        rep(i, 1, cnt) {

          if (join(i, p)) g[join(i, p)] = inc(g[join(i, p)], inc(f[i], f[i]));

        }

        if (con.insert(E[1][u] ^ E[1][v] ^ E[u][v])) {

          int p = id[con.val()];

          rep(i, 1, cnt) {

            if (join(i, p)) g[join(i, p)] = inc(g[join(i, p)], f[i]);

          }

        }

      }

      con.clear(), swap(f, g);

    }

  }

  rep(i, 1, cnt) ans = inc(ans, f[i]);

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

  return 0;

}


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

#include<bits/stdc++.h>

using namespace std;

int main(){

  int t;

  cin>>t;

  while(t--){

  int x;

  cin>>x;

  int a[x];

  int flag=0;

  int del=0;

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

    cin>>a[i];

    if(a[i]%2!=0)

    flag=1;

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

    del=1;

   }

  if(x%2!=0 && flag==1)

  cout<<"YES";

  else if(x%2==0 && del==1 && flag==1)

   cout<<"YES";

  else

  cout<<"NO";

   cout<<endl;

  }

}


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

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

#define ll long long
#define mod 1000000007ll

bool inPowerOfK(ll num, int k, bool vis[]){
    int bit = 0;
    while(num){
        if(num % k > 1) return false;
        if(num % k == 1) {
            if(!vis[bit]) vis[bit] = true;
            else return false;
        }
        num /= k;
        bit++;
    }
    return true;
}
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int t; cin >> t;
    while(t--){
        bool vis[60] = {false};
        int n, k; cin >> n >> k;
        ll arr[n];
        bool ans = true;
        for(int i = 0; i < n; i++) cin >> arr[i];
        for(int i = 0; i < n; i++){
            if(!inPowerOfK(arr[i], k, vis))
                {ans = false; break;}
        }
        if(ans) cout << "YES\n";
        else cout << "NO\n";
    }
}


E. Median Mountain Rangetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBerland — is a huge country with diverse geography. One of the most famous natural attractions of Berland is the "Median mountain range". This mountain range is nn mountain peaks, located on one straight line and numbered in order of 11 to nn. The height of the ii-th mountain top is aiai. "Median mountain range" is famous for the so called alignment of mountain peaks happening to it every day. At the moment of alignment simultaneously for each mountain from 22 to n−1n−1 its height becomes equal to the median height among it and two neighboring mountains. Formally, if before the alignment the heights were equal bibi, then after the alignment new heights aiai are as follows: a1=b1a1=b1, an=bnan=bn and for all ii from 22 to n−1n−1 ai=median(bi−1,bi,bi+1)ai=median(bi−1,bi,bi+1). The median of three integers is the second largest number among them. For example, median(5,1,2)=2median(5,1,2)=2, and median(4,2,4)=4median(4,2,4)=4.Recently, Berland scientists have proved that whatever are the current heights of the mountains, the alignment process will stabilize sooner or later, i.e. at some point the altitude of the mountains won't changing after the alignment any more. The government of Berland wants to understand how soon it will happen, i.e. to find the value of cc — how many alignments will occur, which will change the height of at least one mountain. Also, the government of Berland needs to determine the heights of the mountains after cc alignments, that is, find out what heights of the mountains stay forever. Help scientists solve this important problem!InputThe first line contains integers nn (1≤n≤5000001≤n≤500000) — the number of mountains.The second line contains integers a1,a2,a3,…,ana1,a2,a3,…,an (1≤ai≤1091≤ai≤109) — current heights of the mountains.OutputIn the first line print cc — the number of alignments, which change the height of at least one mountain.In the second line print nn integers — the final heights of the mountains after cc alignments.ExamplesInputCopy5
1 2 1 2 1
OutputCopy2
1 1 1 1 1
InputCopy6
1 3 2 5 4 6
OutputCopy1
1 2 3 4 5 6
InputCopy6
1 1 2 2 1 1
OutputCopy0
1 1 2 2 1 1
NoteIn the first example; the heights of the mountains at index 11 and 55 never change. Since the median of 11, 22, 11 is 11, the second and the fourth mountains will have height 1 after the first alignment, and since the median of 22, 11, 22 is 22, the third mountain will have height 2 after the first alignment. This way, after one alignment the heights are 11, 11, 22, 11, 11. After the second alignment the heights change into 11, 11, 11, 11, 11 and never change from now on, so there are only 22 alignments changing the mountain heights.In the third examples the alignment doesn't change any mountain height, so the number of alignments changing any height is 00.

#include <bits/stdc++.h>

#define int long long
using namespace std;
const int N = 5e5 + 5;
const int LOG = 20;
int n, type, res, a[N], b[N], lg[N], mn[LOG][N], mx[LOG][N];

pair<int, int> get(int l, int r) {
    int LG = lg[r - l];
    return {min(mn[LG][l], mn[LG][r - (1 << LG)]), max(mx[LG][l], mx[LG][r - (1 << LG)])};
}

void precalc() {
    for (int i = 2; i < N; i++) {
        lg[i] = lg[i / 2] + 1;
    }
    for (int i = 0; i <= n; i++) {
        mn[0][i] = max(a[i], a[i + 1]);
        mx[0][i] = min(a[i], a[i + 1]);
    }
    for (int i = 0; i < LOG - 1; i++) {
        for (int j = 0; j <= n - (1 << i); j++) {
            mn[i + 1][j] = min(mn[i][j], mn[i][j + (1 << i)]);
            mx[i + 1][j] = max(mx[i][j], mx[i][j + (1 << i)]);
        }
    }
}

signed main() {
    cin >> n;
    type = 1;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }
    a[0] = a[1], a[n + 1] = a[n];
    precalc();
    for (int i = 1; i <= n; i++) {
        int l = 1, r = min(n + 1 - i, i), cnt = 0;
        int pff = 400;
        while (l <= r && pff--) {
            int m = (l + r) / 2;
            auto t = get(i - m, i + m);
            if (t.first <= t.second) {
                r = m - 1;
                cnt = m;
            }
            else {
                l = m + 1;
            }
        }
        if (!type)
            continue;
        if (cnt == 1) {
            b[i] = a[i];
        } else {
            auto got = get(i - cnt, i + cnt);
            if (a[i] > a[i - 1]) {
                if (cnt % 2 == 0) {
                    b[i] = got.second;
                } else {
                    b[i] = got.first;
                }
            } else {
                if (cnt % 2 == 1) {
                    b[i] = got.second;
                } else {
                    b[i] = got.first;
                }
            }
        }
        res = max(res, cnt - 1);
    }
    cout << res << '\n';
    if (type == 1) {
        for (int i = 1; i <= n; i++) {
            cout << b[i] << ' ';
        }
    }
    return 0;
}


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

#include<bits/stdc++.h>

using namespace std;
int n,a[150003],_[150003];
struct BIT{
int dat[150003];
void init(){
memset(dat,0,sizeof(dat));
}
int query(int x){
int ret=0;
while(x){
ret+=dat[x];
x^=(x&-x);
}return ret;
}
void add(int x,int y){
while(x<=n){
dat[x]+=y;
x+=(x&-x);
}
}
}tr1,tr2;
long long sum;
void add1(int x,int y){
tr1.add(x,y);
sum+=1ll*tr2.query(n+1-x)*y;
}
void add2(int x,int y){
sum+=1ll*tr1.query(x)*y;
tr2.add(n+1-x,y);
}
struct sgt{
int mn[524288],mc[524288],sn[524288],lzy[524288];
void init(){
sum=0;
memset(mn,31,sizeof(mn));
memset(mc,0,sizeof(mc));
memset(sn,31,sizeof(sn));
memset(lzy,-1,sizeof(lzy));
}
void pushtag(int k,int val,bool tp){
if(mn[k]>=val)
return;
if(tp){
add1(mn[k],-mc[k]);
add1(val,mc[k]);
}
mn[k]=val;
lzy[k]=val;
}
void pushdown(int k){
pushtag(k<<1,lzy[k],0);
pushtag(k<<1|1,lzy[k],0);
lzy[k]=0;
}
void pushup(int k){
if(mn[k<<1]<mn[k<<1|1]){
mn[k]=mn[k<<1];
mc[k]=mc[k<<1];
sn[k]=min(sn[k<<1],mn[k<<1|1]);
}
if(mn[k<<1]==mn[k<<1|1]){
mn[k]=mn[k<<1];
mc[k]=mc[k<<1]+mc[k<<1|1];
sn[k]=min(sn[k<<1],sn[k<<1|1]);
}
if(mn[k<<1]>mn[k<<1|1]){
mn[k]=mn[k<<1|1];
mc[k]=mc[k<<1|1];
sn[k]=min(mn[k<<1],sn[k<<1|1]);
}
}
void add(int k){
k+=262144;
int tk=k;vector<int>v;tk>>=1;
while(tk)v.push_back(tk),tk>>=1;
while(v.size())pushdown(v.back()),v.pop_back();
mn[k]=1;mc[k]=1;
add1(1,1);
k>>=1;
while(k){
pushup(k);
k>>=1;
}
}
void modify(int l,int r,int _l,int _r,int k,int val){
if(l>_r||r<_l||val<=mn[k])return;
if(_l<=l&&r<=_r&&val<sn[k]){
pushtag(k,val,1);
return;
}
pushdown(k);
modify(l,l+r>>1,_l,_r,k<<1,val);
modify(l+r+1>>1,r,_l,_r,k<<1|1,val);
pushup(k);
}
}TR;
long long ans[150003];
int main(){
cin>>n;
for(int i=0;i<n;i++)
cin>>_[i],a[_[i]-1]=i+1;
for(int i=0;i<2;i++){
tr1.init();tr2.init();TR.init();sum=0;
for(int j=0;j<n;j++){
if(a[j]!=n)
TR.modify(0,262143,a[j]+1,n,1,a[j]+1);
TR.add(a[j]);
add2(a[j],1);
ans[j]+=sum;
a[j]=n+1-a[j];
}
}
for(int i=0;i<n;i++)
cout<<ans[i]-1ll*(i+1)*(i+1)<<'\n';
}


F. Red-Blue Graphtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a bipartite graph: the first part of this graph contains n1n1 vertices, the second part contains n2n2 vertices, and there are mm edges. The graph can contain multiple edges.Initially, each edge is colorless. For each edge, you may either leave it uncolored (it is free), paint it red (it costs rr coins) or paint it blue (it costs bb coins). No edge can be painted red and blue simultaneously.There are three types of vertices in this graph — colorless, red and blue. Colored vertices impose additional constraints on edges' colours:  for each red vertex, the number of red edges indicent to it should be strictly greater than the number of blue edges incident to it;  for each blue vertex, the number of blue edges indicent to it should be strictly greater than the number of red edges incident to it. Colorless vertices impose no additional constraints.Your goal is to paint some (possibly none) edges so that all constraints are met, and among all ways to do so, you should choose the one with minimum total cost. InputThe first line contains five integers n1n1, n2n2, mm, rr and bb (1≤n1,n2,m,r,b≤2001≤n1,n2,m,r,b≤200) — the number of vertices in the first part, the number of vertices in the second part, the number of edges, the amount of coins you have to pay to paint an edge red, and the amount of coins you have to pay to paint an edge blue, respectively.The second line contains one string consisting of n1n1 characters. Each character is either U, R or B. If the ii-th character is U, then the ii-th vertex of the first part is uncolored; R corresponds to a red vertex, and B corresponds to a blue vertex.The third line contains one string consisting of n2n2 characters. Each character is either U, R or B. This string represents the colors of vertices of the second part in the same way.Then mm lines follow, the ii-th line contains two integers uiui and vivi (1≤ui≤n11≤ui≤n1, 1≤vi≤n21≤vi≤n2) denoting an edge connecting the vertex uiui from the first part and the vertex vivi from the second part.The graph may contain multiple edges.OutputIf there is no coloring that meets all the constraints, print one integer −1−1.Otherwise, print an integer cc denoting the total cost of coloring, and a string consisting of mm characters. The ii-th character should be U if the ii-th edge should be left uncolored, R if the ii-th edge should be painted red, or B if the ii-th edge should be painted blue. If there are multiple colorings with minimum possible cost, print any of them.ExamplesInputCopy3 2 6 10 15
RRB
UB
3 2
2 2
1 2
1 1
2 1
1 1
OutputCopy35
BUURRU
InputCopy3 1 3 4 5
RRR
B
2 1
1 1
3 1
OutputCopy-1
InputCopy3 1 3 4 5
URU
B
2 1
1 1
3 1
OutputCopy14
RBB

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

using namespace std;

const int INF=2147483647;

struct Edge

{

	int to;

	int nxt;

	int flow;

	int cost;

}e[10005];

int n1,n2,m,r,b,s,t,ss,tt,edgenum=1,head[505],dis[505],a[505],pre[505],d[505];

char s1[505],s2[505];

bool flag[1005];

queue<int>q;

void add(int u,int v,int f,int c)

{

	e[++edgenum].cost=c;

	e[edgenum].flow=f;

	e[edgenum].to=v;

	e[edgenum].nxt=head[u];

	head[u]=edgenum;

}

bool SPFA()

{

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

	for(int i=1;i<=t;i++)dis[i]=INF,a[i]=0,flag[i]=0;

	q.push(s);

	dis[s]=0;

	a[s]=INF;

	flag[s]=1;

	while(!q.empty())

	{

		int node=q.front();

		q.pop();

		flag[node]=0;

		for(int hd=head[node];hd;hd=e[hd].nxt)

		{

			if(e[hd].flow==0)continue;

			int to=e[hd].to;

			if(dis[to]>dis[node]+e[hd].cost)

			{

				dis[to]=dis[node]+e[hd].cost;

				a[to]=min(a[node],e[hd].flow);

				pre[to]=hd;

				if(!flag[to])

				{

					q.push(to);

					flag[to]=1;

				}

			}

		}

	}

	return dis[t]<INF;

}

int EK1()

{

	int ans=0;

	while(SPFA())

	{

		ans+=dis[t]*a[t];

		int x=t;

		while(x!=s)

		{

			int hd=pre[x];

			e[hd].flow-=a[t];

			e[hd^1].flow+=a[t];

			x=e[hd^1].to;

		}

	}

	return ans;

}

int EK2()

{

	int ans=0;

	while(SPFA())

	{

		if(dis[t]>=0)break;

		ans+=dis[t]*a[t];

		int x=t;

		while(x!=s)

		{

			int hd=pre[x];

			e[hd].flow-=a[t];

			e[hd^1].flow+=a[t];

			x=e[hd^1].to;

		}

	}

	return ans;

}

int main()

{

	scanf("%d%d%d%d%d",&n1,&n2,&m,&r,&b);

	ss=n1+n2+1;

	tt=ss+1;

	s=tt+1;

	t=s+1;

	scanf("%s%s",s1+1,s2+1);

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

	{

		int u,v;

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

		d[u]++,d[v+n1]++;

		add(u,v+n1,1,-r);

		add(v+n1,u,0,r);

		add(u,v+n1,1,b);

		add(v+n1,u,0,-b);

	}

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

	{

		if(s1[i]=='U')

		{

			add(ss,i,2*d[i],0);

			add(i,ss,0,0);

		}

		if(s1[i]=='R')

		{

			add(ss,i,d[i]-1,0);

			add(i,ss,0,0);

		}

		if(s1[i]=='B')

		{

			add(ss,i,d[i]-1,0);

			add(i,ss,0,0);

			add(s,i,d[i]+1,0);

			add(i,s,0,0);

			add(ss,t,d[i]+1,0);

			add(t,ss,0,0);

		}

	}

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

	{

		if(s2[i]=='U')

		{

			add(i+n1,tt,2*d[i+n1],0);

			add(tt,i+n1,0,0);

		}

		if(s2[i]=='R')

		{

			add(i+n1,tt,d[i+n1]-1,0);

			add(tt,i+n1,0,0);

		}

		if(s2[i]=='B')

		{

			add(i+n1,tt,d[i+n1]-1,0);

			add(tt,i+n1,0,0);

			add(s,tt,d[i+n1]+1,0);

			add(tt,s,0,0);

			add(i+n1,t,d[i+n1]+1,0);

			add(t,i+n1,0,0);

		}

	}

	add(tt,ss,INF,0);

	add(ss,tt,0,0);

	int ans=r*m;

	for(int i=2;i<edgenum;i+=2)

	{

		if(e[i].cost<0&&e[i].flow)

		{

			add(s,e[i].to,e[i].flow,0);

			add(e[i].to,s,0,0);

			add(e[i^1].to,t,e[i].flow,0);

			add(t,e[i^1].to,0,0);

			ans+=e[i].cost*e[i].flow;

			e[i^1].flow=e[i].flow,e[i].flow=0;

		}

	}

	ans+=EK1();

	for(int hd=head[s];hd;hd=e[hd].nxt)

	{

		if(e[hd].flow)

		{

			printf("-1\n");

			return 0;

		}

	}

	for(int hd=head[s];hd;hd=e[hd].nxt)

	{

		e[hd].flow=e[hd^1].flow=0;

	}

	for(int hd=head[t];hd;hd=e[hd].nxt)

	{

		e[hd].flow=e[hd^1].flow=0;

	}

	ans+=EK2();

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

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

	{

		if(e[4*i-2].flow==1)putchar('R');

		else if(e[4*i].flow==1)putchar('U');

		else putchar('B');

	}

	return 0;

}


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

#include<bits/stdc++.h>

using namespace std;
enum{N=200001};
basic_string<int>G[N],a,b;
int n,m,u,v,ok[N],dep[N];
void dfs(int u){
a+=u,dep[u]=a.size();
for(int v:G[u])
if(!dep[v])dfs(v);
else if(dep[u]-dep[v]+1>=n){
cout<<"2\n"<<dep[u]-dep[v]+1<<'\n';
for(int i=dep[v]-1;i<dep[u];++i)cout<<a[i]<<' ';
exit(0);
}
if(!ok[u]){
b+=u;
for(int v:G[u])ok[v]=1;
}
a.pop_back();
}
main(){
cin>>n>>m,n=sqrt(n-1)+1;
while(m--)cin>>u>>v,G[u]+=v,G[v]+=u;
dfs(1);
puts("1");
for(m=0;m<n;++m)cout<<b[m]<<' ';
}


E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23
16 17 14 20 20 11 22
OutputCopy3
NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good.

#include <bits/stdc++.h>

using i64 = long long;

int main() {

	std::ios::sync_with_stdio(false);

	std::cin.tie(nullptr);

	int n, h, l, r;

	std::cin >> n >> h >> l >> r;

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

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

		std::cin >> a[i];

	}

	std::vector<int> dp(h + 1);

	std::vector<int> vis(h);

	vis[0] = true;

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

		std::vector<int> ndp(h), nvis(h);

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

			if (vis[j]) {

				int x = (j + a[i]) % h, y = (x - 1 + h) % h;

				ndp[x] = std::max(ndp[x], dp[j] + (x >= l && x <= r));

				ndp[y] = std::max(ndp[y], dp[j] + (y >= l && y <= r));

				nvis[x] = nvis[y] = true;

			}

		}

		std::swap(nvis, vis);

		std::swap(ndp, dp);

	}

	std::cout << *max_element(dp.begin(), dp.end()) << "\n";

	return 0;

}


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

a
aa
a

cb
b
c

cOutputCopy? 1 2

? 3 4

? 4 4

! aabc

#include<cstdio>

#include<cstring>

#include<cstdlib>

#include<utility>

#include<assert.h>

#include<vector>

struct edge

{

	int to;std::pair<int,int> s;

	edge(int to=0,std::pair<int,int> s=std::make_pair(0,0)){this->to=to,this->s=s;}

};

int n,f[105][30],p[105],q[105],ans[105];

char st[105];

std::vector<edge> a[105];

void print()

{

	printf("! ");

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

	puts("");

	fflush(stdout);

}

void add(int x,int y,std::pair<int,int> s){/*printf("%d %d (%c,%c)\n",x,y,s.first+96,s.second+96);*/a[x].push_back(edge(y,s));a[y].push_back(edge(x,s));}

void solve(int x,int y)

{

	int len=(y-x+1),ss=len*(len+1)/2;

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

	assert(1<=x&&x<=y&&y<=n);

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

	fflush(stdout);

	for (int i=0;i<=len+1;i++) for (int ch=1;ch<=26;ch++) f[i][ch]=0;

	for (int i=0;i<=len+1;i++) p[i]=q[i]=0;

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

	{

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

		if (st[1]=='-') exit(0);

		int m=std::strlen(st+1);

		if (m>(len+1)/2) continue;

		for (int k=1;k<=m;k++) ++f[m][st[k]-96];

	}

	for (int s=(len+1)/2;s>=1;s--)

		for (int ch=1;ch<=26;ch++)

			f[s][ch]=f[s][ch]-f[s-1][ch];

	for (int s=1;s<=(len+1)/2;s++)

		for (int ch=1;ch<=26;ch++)

			f[s][ch]=f[s][ch]-f[s+1][ch];

//	for (int s=1;s<=(len+1)/2;s++)

//	{

//		for (int ch=1;ch<=26;ch++) printf("%d ",f[s][ch]);

//		puts("");

//	}

	for (int s=1;s<=(len+1)/1;s++)

		for (int ch=1;ch<=26;ch++)

		{

			if (!f[s][ch]) continue;

			if (f[s][ch]>1){p[s]=q[s]=ch;continue;}

//			printf("%d:%d\n",s,ch);

			if (p[s]) q[s]=ch;else p[s]=ch;

		}

	fflush(stdout);

}

void dfs(int v)

{

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

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

	{

		int u=a[v][i].to;

		std::pair<int,int> pp=a[v][i].s;

		if (ans[u]!=-1) continue;

		if (ans[v]==pp.first) ans[u]=pp.second;

		else ans[u]=pp.first;

		dfs(u);

	}

}

int main()

{

	scanf("%d",&n);

	if (n==1)

	{

		printf("? 1 1\n");

		fflush(stdout);

		char st[10];

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

		if (st[1]=='-') exit(0);

		printf("! %c\n",st[1]);

		fflush(stdout);

		return 0;

	}

	if (n==2)

	{

		printf("? 1 1\n");

		fflush(stdout);

		char st[10];

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

		if (st[1]=='-') exit(0);

		printf("? 2 2\n");

		fflush(stdout);

		scanf("%s",st+2);

		if (st[2]=='-') exit(0);

		printf("! %c%c\n",st[1],st[2]);

		fflush(stdout);

		return 0;

	}

	if (n==3)

	{

		printf("? 1 1\n");

		fflush(stdout);

		char st[10];

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

		if (st[1]=='-') exit(0);

		printf("? 2 2\n");

		fflush(stdout);

		scanf("%s",st+2);

		if (st[2]=='-') exit(0);

		printf("? 3 3\n");

		fflush(stdout);

		scanf("%s",st+3);

		if (st[2]=='-') exit(0);

		printf("! %c%c%c\n",st[1],st[2],st[3]);

		fflush(stdout);

		return 0;

	}

	int kk=n-n/3;

	if (n<=5) kk=n;

	if (n==6) kk=5;

	int l1=kk-(n-kk),r1=n;

//	printf("%d %d\n",l1,r1);

	int l2=l1-1,r2=n;

	int l3=1,r3=(n>2?2*(l2-2)+1:1);

	if (r3>n) r3=n;

	int pt=0;

	solve(l1,r1);

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

	for (int i=1;i<=(r1-l1)/2+1;i++)

	{

		int x=l1+i-1,y=r1-i+1;

		if (x!=y) add(x,y,std::make_pair(p[i],q[i]));

		else if (x==y) ans[x]=p[i],pt=x;

	}

	solve(l2,r2);

	for (int i=1;i<=(r2-l2)/2+1;i++)

	{

		int x=l2+i-1,y=r2-i+1;

		if (x!=y) add(x,y,std::make_pair(p[i],q[i]));

		else if (x==y) ans[x]=p[i];

	}

	solve(l3,r3);

	for (int i=1;i<=(r3-l3)/2+1;i++)

	{

		int x=l3+i-1,y=r3-i+1;

		if (x!=y) add(x,y,std::make_pair(p[i],q[i]));

		else if (x==y) ans[x]=p[i];

	}

//	printf("%d\n",pt);

	assert(pt);

	dfs(pt);

	print();

	return 0;

}


D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules:  He starts at the top-left cell in the grid;  In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to:   in the case 'U' to the cell (i−1,j)(i−1,j);  in the case 'D' to the cell (i+1,j)(i+1,j);  in the case 'L' to the cell (i,j−1)(i,j−1);  in the case 'R' to the cell (i,j+1)(i,j+1);   He wants to run exactly kk kilometers, so he wants to make exactly kk moves;  Bashar can finish in any cell of the grid;  He can't go out of the grid so at any moment of the time he should be on some cell;  Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4
OutputCopyYES
2
2 R
2 L
InputCopy3 3 1000000000
OutputCopyNO
InputCopy3 3 8
OutputCopyYES
3
2 R
2 D
1 LLRR
InputCopy4 4 9
OutputCopyYES
1
3 RLD
InputCopy3 4 16
OutputCopyYES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):

#include <algorithm>

#include <cassert>

#include <cstdio>

#include <cstring>

#include <iomanip>

#include <iostream>

#include <map>

#include <numeric>

#include <queue>

#include <ranges>

#include <set>

#include <string>

#include <vector>

using namespace std;

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

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

void __print(int x) { cerr << x; }

void __print(long x) { cerr << x; }

void __print(long long x) { cerr << x; }

void __print(unsigned x) { cerr << x; }

void __print(unsigned long x) { cerr << x; }

void __print(unsigned long long x) { cerr << x; }

void __print(float x) { cerr << x; }

void __print(double x) { cerr << x; }

void __print(long double x) { cerr << x; }

void __print(char x) { cerr << '\'' << x << '\''; }

void __print(const char *x) { cerr << '\"' << x << '\"'; }

void __print(const string &x) { cerr << '\"' << x << '\"'; }

void __print(bool x) { cerr << (x ? "true" : "false"); }

template <typename T, typename V>

void __print(const pair<T, V> &x) {

    cerr << '{';

    __print(x.first);

    cerr << ',';

    __print(x.second);

    cerr << '}';

}

template <typename T>

void __print(const T &x) {

    int f = 0;

    cerr << '{';

    for (auto &i : x) cerr << (f++ ? "," : ""), __print(i);

    cerr << "}";

}

void _print() { cerr << "]\n"; }

template <typename T, typename... V>

void _print(T t, V... v) {

    __print(t);

    if (sizeof...(v)) cerr << ", ";

    _print(v...);

}

#ifdef DUPA

#define debug(x...)               \

    cerr << "[" << #x << "] = ["; \

    _print(x)

#else

#define debug(x, ...)

#endif

typedef long long LL;

// HMMMM

#define int LL

typedef pair<int, int> PII;

typedef pair<int, PII> PIII;

const int INF = 1e18 + 1;

int n, m, k;

void solve() {

    cin >> n >> m >> k;

    vector<pair<char, int>> res;

    if (n == 1) {

        res.push_back({'R', m - 1});

        res.push_back({'L', m - 1});

    } else if (m == 1) {

        res.push_back({'D', n - 1});

        res.push_back({'U', n - 1});

    } else {

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

            res.push_back({'R', m - 1});

            res.push_back({'L', m - 1});

            res.push_back({'D', 1});

        }

        res.push_back({'R', m - 1});

        for (int j = m - 1; j > 0; j--) {

            res.push_back({'U', n - 1});

            res.push_back({'D', n - 1});

            res.push_back({'L', 1});

        }

        res.push_back({'U', n - 1});

    }

    int sum = 0;

    for (auto [_, x] : res) {

        sum += x;

    }

    assert(sum == 4 * n * m - 2 * n - 2 * m);

    if (k > sum) {

        cout << "NO " << endl;

        return;

    }

    while (sum != k) {

        res.back().second--;

        sum--;

        if (res.back().second == 0) res.pop_back();

    }

    assert(res.size() <= 3000);

    cout << "YES" << endl;

    cout << res.size() << endl;

    for (auto [y, x] : res) cout << x << " " << y << endl;

}

#undef int

int main() {

    ios::sync_with_stdio(false);

    cin.exceptions(cin.failbit);

    cin.tie(0);

    int t = 1;

#ifdef DUPA

    cin >> t;

#endif

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

}


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

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

#define IOS std::ios::sync_with_stdio(false);std::cin.tie(0);std::cout.tie(0);

#define endl '\n'

using ll = long long;

#define int long long

using pll = std::pair<int, int>;

using namespace std;

signed main()

{

//#ifdef LOCAL

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

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

//#endif

    IOS;///

    int n;

    cin >> n;

    vector<int>a(n + 7), b(n + 7);

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

    auto calc = [&](int L, int R) ->bool {

        if (L > R) return 0;

        ll ret = 0;

        for (int i = n, l = 1, r = 1; i; i--) {

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

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

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

        }

        return (ret >> 1) & 1;

    };

    int ans = 0;

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

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

            b[i] = a[i] & ((1 << (k + 1) ) - 1);

        }

        sort(&b[1], &b[1 + n]);

        int g = (calc(1 << k, (1 << (k + 1)) - 1) ^ calc(3 << k, (1 << (k + 2)) - 2));

        ans |= (g << k);

    }

    cout << ans << '\n';

    return 0;

}


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

#include <iostream>

#include <iomanip>

#include <cstdio>

#include <vector>

#include <math.h>

#include <algorithm>

#include <map>

using namespace std;

int main()

{

     cout.tie(nullptr);

    std::ios::sync_with_stdio(false);

int t; cin >> t;

while(t--){

int n,s,k;

cin >> n >> s >> k;

vector<int> v;

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

    int a; cin >> a;

    v.push_back(a);

}

int ans=0;

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

		if (s+i<=n) {

                if(find(v.begin(),v.end(),s+i)==v.end()){

                ans=i; break;

                }

        }

        if (s-i>=1){

            if(find(v.begin(),v.end(),s-i)==v.end()){

               ans=i; break;

        }

		}

	}

cout << ans << '\n';

}

 return 0;

}


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


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

#include<bits/stdc++.h>

using namespace std;

#define pb  push_back

#define ll  long long

#define vi  vector<int>

#define vvi vector<vi >

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

ll mod = 1e9 + 7;

vi tw, in;

struct pt {

    ll val, cnt, lva, rva;

    pt() {};

    pt(ll k, ll x) {

        cnt = k;

        val = (x * x % mod) * (k * in[1] % mod + mod - 1 + in[k]) % mod;

        lva = (tw[k] + mod - 1) * x % mod;

        rva = (1 + mod - in[k]) * x % mod;

    }

    pt(ll val, ll cnt, ll lva, ll rva) : val(val), cnt(cnt), lva(lva), rva(rva) {};

};

pt operator+(pt x, pt y) {

    return pt((x.val + y.val + (x.lva * y.rva % mod) * in[x.cnt]) % mod, x.cnt + y.cnt,

              (x.lva + y.lva * tw[x.cnt]) % mod, (x.rva + y.rva * in[x.cnt]) % mod);

}

ll n, m, q;

vi p, x, I, X;

vector<pt> t;

ll po(ll x, ll p) {

    ll res = 1;

    for (; p; p /= 2) {

        if (p % 2)

            res = (res * x) % mod;

        x = (x * x) % mod;

    }

    return res;

}

ll inv(ll x) { return po(x, mod - 2); }

void add(ll i, ll x) {

    ll k = t[i].cnt + 1;

    t[i] = pt(k, x);

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

        t[i] = (t[i + i] + t[i + i + 1]);

}

void del(ll i, ll x) {

    ll k = t[i].cnt - 1;

    t[i] = pt(k, x);

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

        t[i] = (t[i + i] + t[i + i + 1]);

}

int main() {

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

    cin >> n;

    ll inv2 = inv(2);

    tw.assign(n + 5, 1);

    in.assign(n + 5, 1);

    for (ll i = 1; i < in.size(); ++i) {

        in[i] = (in[i - 1] * inv2) % mod;

        tw[i] = (tw[i - 1] * 2) % mod;

    }

    p.resize(n);

    for (auto& el : p) {

        cin >> el; x.pb(el);

    }

    cin >> q;

    I = X = vi(q);

    for (ll e = 0; e < q; ++e) {

        cin >> I[e] >> X[e]; --I[e];

        x.pb(X[e]);

    }

    sort(all(x));

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

    m = 1;

    while (m < x.size())

        m *= 2;

    t.assign(2 * m, pt(0, 0, 0, 0));

    for (auto el : p) {

        ll e = lower_bound(all(x), el) - x.begin();

        add(e + m, el);

    }

    cout << t[1].val << "\n";

    for (ll o = 0; o < q; ++o) {

        ll i = I[o];

        ll to = X[o]; ll eto = lower_bound(all(x), to) - x.begin();

        ll fr = p[i]; ll efr = lower_bound(all(x), fr) - x.begin();

        p[i] = to;

        del(efr + m, fr);

        add(eto + m, to);

        cout << t[1].val << "\n";

    }

    return 0;

}


E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red; the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of nn rows and mm columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh qq options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 00.Warawreh couldn't find the best option himself so he asked you for help, can you help him?InputThe first line of input contains three integers nn, mm and qq (1≤n,m≤500,1≤q≤3⋅105)(1≤n,m≤500,1≤q≤3⋅105)  — the number of row, the number columns and the number of options.For the next nn lines, every line will contain mm characters. In the ii-th line the jj-th character will contain the color of the cell at the ii-th row and jj-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.For the next qq lines, the input will contain four integers r1r1, c1c1, r2r2 and c2c2 (1≤r1≤r2≤n,1≤c1≤c2≤m)(1≤r1≤r2≤n,1≤c1≤c2≤m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r1,c1)(r1,c1) and with the bottom-right corner in the cell (r2,c2)(r2,c2).OutputFor every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 00.ExamplesInputCopy5 5 5
RRGGB
RRGGY
YYBBG
YYBBR
RBBRG
1 1 5 5
2 2 5 5
2 2 3 3
1 1 3 5
4 4 5 5
OutputCopy16
4
4
4
0
InputCopy6 10 5
RRRGGGRRGG
RRRGGGRRGG
RRRGGGYYBB
YYYBBBYYBB
YYYBBBRGRG
YYYBBBYBYB
1 1 6 10
1 3 3 10
2 2 6 6
1 7 6 10
2 1 5 10
OutputCopy36
4
16
16
16
InputCopy8 8 8
RRRRGGGG
RRRRGGGG
RRRRGGGG
RRRRGGGG
YYYYBBBB
YYYYBBBB
YYYYBBBB
YYYYBBBB
1 1 8 8
5 2 5 7
3 1 8 6
2 3 5 8
1 2 6 8
2 1 5 5
2 1 7 7
6 5 7 5
OutputCopy64
0
16
4
16
4
36
0
NotePicture for the first test:The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black; the border of the sub-square with the maximal possible size; that can be cut is marked with gray.

#include <bits/stdc++.h>

using namespace std;

template<class A, class B> bool maximize(A& x, B y) {if (x < y) return x = y, true; else return false;}

template<class A, class B> bool minimize(A& x, B y) {if (x >= y) return x = y, true; else return false;}

void __print(int x) {cerr << x;}

void __print(long x) {cerr << x;}

void __print(long long x) {cerr << x;}

void __print(unsigned x) {cerr << x;}

void __print(unsigned long x) {cerr << x;}

void __print(unsigned long long x) {cerr << x;}

void __print(float x) {cerr << x;}

void __print(double x) {cerr << x;}

void __print(long double x) {cerr << x;}

void __print(char x) {cerr << '\'' << x << '\'';}

void __print(const char *x) {cerr << '\"' << x << '\"';}

void __print(const string &x) {cerr << '\"' << x << '\"';}

void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>

void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ", "; __print(x.second); cerr << '}';}

template<typename T>

void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? ", " : ""), __print(i); cerr << "}";}

void _print() {cerr << " ]\n";}

template <typename T, typename... V>

void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}

#define     deb(x...)             cerr << "[ in " <<__func__<< "() : line " <<__LINE__<< " ] : [ " << #x << " ] = [ "; _print(x); cerr << '\n';

typedef     long long             ll;

typedef     unsigned long long    ull;

typedef     double                db;

typedef     long double           ld;

typedef     pair<db, db>          pdb;

typedef     pair<ld, ld>          pld;

typedef     pair<int, int>        pii;

typedef     pair<ll, ll>          pll;

typedef     pair<ll, int>         plli;

typedef     pair<int, ll>         pill;

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

#define     pb(a)                 push_back(a)

#define     pf(a)                 push_front(a)

#define     fi                    first

#define     se                    second

// #define     int                   long long

const int MAX_N = 500 + 5;

int n, m, q;

string a[MAX_N];

int prefSum[4][MAX_N][MAX_N];

int b[MAX_N][MAX_N];

int rmq[10][MAX_N][10][MAX_N];

int convert(const char& h) {

	if (h == 'R') return 0;

	if (h == 'G') return 1;

	if (h == 'Y') return 2;

	return 3;

}

bool inside(const int& x, const int& y) {

	return x > 0 && x <= n && y > 0 && y <= m;

}

int get(int t, int x, int y, int u, int v) {

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

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

	return prefSum[t][u][v] - prefSum[t][u][y - 1] - prefSum[t][x - 1][v] + prefSum[t][x - 1][y - 1];

}

int getMax(int x, int y, int u, int v) {

	int k1 = __lg(u - x + 1);

	int k2 = __lg(v - y + 1);

	int mx1 = max(rmq[k1][x][k2][y], rmq[k1][x][k2][v - (1 << k2) + 1]);

	int mx2 = max(rmq[k1][u - (1 << k1) + 1][k2][y], rmq[k1][u - (1 << k1) + 1][k2][v - (1 << k2) + 1]);

	return max(mx1, mx2);

}

signed main() {

	ios_base::sync_with_stdio(false);

	cin.tie(nullptr);

	cin >> n >> m >> q;

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

		cin >> a[i];

		a[i] = ' ' + a[i];

	}

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

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

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

				prefSum[t][i][j] = prefSum[t][i - 1][j] + prefSum[t][i][j - 1] - prefSum[t][i - 1][j - 1];

			}

			prefSum[convert(a[i][j])][i][j]++;

		}

	}

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

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

			if (a[i][j] == 'R' && a[i][j + 1] == 'G' && a[i + 1][j] == 'Y' && a[i + 1][j + 1] == 'B') {

				int low = 1, high = min(n, m);

				while (low <= high) {

					int mid = (low + high) >> 1;

					if (inside(i - mid + 1, j - mid + 1) && inside(i - mid + 1, j + mid) && inside(i + mid, j - mid + 1) && inside(i + mid, j + mid) && get(0, i - mid + 1, j - mid + 1, i, j) == mid * mid && get(1, i, j + 1, i - mid + 1, j + mid) == mid * mid && get(2, i + 1, j, i + mid, j - mid + 1) == mid * mid && get(3, i + 1, j + 1, i + mid, j + mid) == mid * mid) {

						b[i][j] = mid;

						low = mid + 1;

					}

					else {

						high = mid - 1;

					}

				}

			}

		}

	}

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

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

			rmq[0][ir][0][ic] = b[ir][ic];

		}

		for (int jc = 1; jc < 10; jc++) {

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

				if (ic + (1 << jc) > m) break;

				rmq[0][ir][jc][ic] = max(rmq[0][ir][jc - 1][ic], rmq[0][ir][jc - 1][ic + (1 << (jc - 1))]);

			}

		}

	}

	for (int jc = 0; jc < 10; jc++) {

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

			if (ic + (1 << jc) > m) break;

			for (int jr = 1; jr < 10; jr++) {

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

					if (ir + (1 << jr) > n) break;

					rmq[jr][ir][jc][ic] = max(rmq[jr - 1][ir][jc][ic], rmq[jr - 1][ir + (1 << (jr - 1))][jc][ic]);

				}

			}

		}

	}

	while (q--) {

		int x1, y1, x2, y2;

		cin >> x1 >> y1 >> x2 >> y2;

		int low = 1, high = min(n, m);

		int ans = 0;

		while (low <= high) {

			int mid = (low + high) >> 1;

			int u1 = x1 + mid - 1;

			int v1 = y1 + mid - 1;

			int u2 = x2 - mid;

			int v2 = y2 - mid;

			if (u1 <= u2 && v1 <= v2 && getMax(u1, v1, u2, v2) >= mid) {

				ans = mid;

				low = mid + 1;

			}

			else {

				high = mid - 1;

			}

		}

		cout << 4 * ans * ans << '\n';

	}

	return 0;

}

/*

*/


C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33:  [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66.  [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32.

#include <iostream>
using namespace std;

const int MAXN = 2.5e5+100;
long long fact[MAXN];

int main(){
	int n,m;
	cin >> n >> m;
	fact[0] = 1;
	for(int i = 1;i <= n;i++){
		fact[i] = fact[i-1]*i;
		fact[i]%=m;
	}
	long long ans = 0;
	long long tp = 0;
	long long tp1 = 0;
	long long tp3 = 0;
	for (int len = 1;len<=n;len++){
		tp = fact[n-len]*(n-len+1);
		tp1 = fact[len]*(n-len+1);
		tp%=m;
		tp1%=m;

		// ans+=fact[n-len]*fact[len]*(n-len+1)*(n-len+1);
		tp3 = tp*tp1;
		tp3%=m;
		ans+=tp3;
		ans%=m;
	}
	cout << ans << endl;

}


C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1≤pi<n1≤pi<n) (i.e. you will press first pipi buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1m+1-th try you press all buttons right and finally perform the combo.I.e. if s=s="abca", m=2m=2 and p=[1,3]p=[1,3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow.The first line of each test case contains two integers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤2⋅1051≤m≤2⋅105) — the length of ss and the number of tries correspondingly.The second line of each test case contains the string ss consisting of nn lowercase Latin letters.The third line of each test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n) — the number of characters pressed right during the ii-th try.It is guaranteed that the sum of nn and the sum of mm both does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105, ∑m≤2⋅105∑m≤2⋅105).It is guaranteed that the answer for each letter does not exceed 2⋅1092⋅109.OutputFor each test case, print the answer — 2626 integers: the number of times you press the button 'a', the number of times you press the button 'b', ……, the number of times you press the button 'z'.ExampleInputCopy3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4
OutputCopy4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0
2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2
NoteThe first test case is described in the problem statement. Wrong tries are "a"; "abc" and the final try is "abca". The number of times you press 'a' is 44, 'b' is 22 and 'c' is 22.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 99, 'd' is 44, 'e' is 55, 'f' is 33, 'o' is 99, 'r' is 33 and 's' is 11.

#include <bits/stdc++.h>

using namespace std;

int main()

{

    int t; cin >> t;

    while(t--){

        int n, m;

        cin >> n >> m;

        string s;

        cin >> s;

        vector<int> freq(n, 0);

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

            int x; cin >> x;

            freq[0]++;

            freq[x]--;

        }

        freq[0]++;

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

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

        }

        vector<int> c(26, 0);

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

            c[(s[i]-'a')]+= freq[i];

        }

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

            cout << c[i] << " ";

        }

        cout << endl;

    }

}


E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times:   choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|;  erase the chosen subsequence from ss (ss can become empty);  concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4
ababcd
abcba
a
b
defi
fed
xyz
x
OutputCopyYES
NO
NO
YES

#pragma GCC optimize("O2")

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

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace std;

using namespace __gnu_pbds;

#define ll     long long

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

#define ff     first

#define ss     second

#define pb     push_back

#define ppb    pop_back

#define pf     push_front

#define ppf    pop_front

template <typename T> using Ordered_Set_Tree =

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

template <typename T> using Ordered_Multiset_Tree =

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

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

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

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

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

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

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

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

///DEBUG

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

vector<string> vec_splitter(string s)

{

    s += ',';

    vector<string> res;

    while(!s.empty())

    {

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

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

    }

    return res;

}

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

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

{

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

    stringstream ss; ss << H;

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

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

}

///DEBUG

int main()

{

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    test

    {

        string s, t;

        cin>>s>>t;

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

        for(int i=s.size()-1; i>=0; i--)

        {

            nextPos[i] = nextPos[i+1];

            nextPos[i][s[i]-'a'] =i;

        }

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

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

        {

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

            {

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

                    dp[i][j] = 1e9;

            }

            dp[0][0] = 0;

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

            {

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

                {

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

                    int lenS = dp[i][j];

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

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

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

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

                }

            }

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

        };

        int poss = 0;

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

        {

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

            {

                poss = 1;

                break;

            }

        }

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

        else                cout<<"NO\n";

    }

}


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

//#pragma GCC optimize("Ofast")

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp> // Common file

#include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update

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

using namespace std;

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

struct custom_hash{

    static uint64_t splitmix64(uint64_t x){

        x += 0x9e3779b97f4a7c15;

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

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

        return x ^ (x >> 31);

    }

    size_t operator()(uint64_t a) const {

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

        return splitmix64(a + FIXED_RANDOM);

    }

    template<class T> size_t operator()(T a) const {

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

        hash<T> x;

        return splitmix64(x(a) + FIXED_RANDOM);

    }

    template<class T, class H> size_t operator()(pair<T, H> a) const {

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

        hash<T> x;

        hash<H> y;

        return splitmix64(x(a.f) * 37 + y(a.s) + FIXED_RANDOM);

    }

};

template<class T, class H>using umap=unordered_map<T,H,custom_hash>;

const int MAXN = 2e5 + 10;

const int MOD = 998244353;

#define int long long

using namespace __gnu_pbds;

int bm(int b, int p) { // bigmod

    if(p==0) return 1;

    int r = bm(b, p/2);

    if(p&1) return (((r*r) % MOD) * b) % MOD;

    return (r*r) % MOD;

}

int inv(int b) { // modinv

    return bm(b, MOD-2);

}

int f[MAXN];

int nCr(int n, int r) { // nCr main function, requires precomputation function

    int ans = f[n]; ans *= inv(f[r]); ans %= MOD;

    ans *= inv(f[n-r]); ans %= MOD; return ans;

}

int dsu[MAXN]; // disjoint set union

int set_of(int u) {

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

    return dsu[u] = set_of(dsu[u]);

}

void union_(int u, int v) {

    dsu[set_of(u)] = set_of(v);

}

void precomp() { // factorials for nCr

    f[0] = 1;

    for(int i=1; i<MAXN; i++) f[i] = (f[i-1] * i) % MOD;

}

int rnd(int x, int y) { // random number generator

    int u= uniform_int_distribution<int>(x, y)(rng); return u;

}

int sd(int n) { // sum of digits

    int sum = 0;

    while(n) {

        sum += n%10;

        n /= 10;

    }

    return sum;

}

string binAdd(string a, string b) { //O(max(n,m)) time binary addition

    string result = ""; int s = 0;

    int i = a.size()-1, j = b.size()-1;

    while(i >= 0 || j >= 0 || s == 1) {

        s += ((i>=0 ? a[i] - '0':0));

        s += ((j>=0 ? b[j] - '0':0));

        result += char(s%2 + '0');

        s /= 2;

        i--, j--;

    }

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

    return result;

}

string binSub(string a, string b) { // O(max(n,m)) time binary subtraction, a ≥ b required

    string result = ""; int s = 0;

    int i = a.size()-1, j = b.size()-1;

    while(i >= 0 || j >= 0 || s != 0) {

        s += ((i>=0 ? a[i] - '0':0));

        s -= ((j>=0 ? b[j] - '0':0));

        result += char(abs(s)%2 + '0');

        if(s >= 0) s /= 2;

        else s = (s-1) / 2;

        i--, j--;

    }

    while(result.size() > 1 && result[result.size() - 1] == '0') {

        result.erase(result.size() - 1, 1);

    }

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

    return result;

}

int fastlog(int x) {

    int k = 32 - __builtin_clz(x) - 1;

    return k;

}

void stress(int tc) {

}

void solve(int tc) {

    int n, m;

    cin >> n >> m;

    int a[n+1];

    if(n == 1 || n == 2) {

        if(m == 0) {

            cout << "2022 "; //!!!

            if(n == 2) cout << "2023\n";

            return;

        }

        else {

            cout << "-1\n";

            return;

        }

    }

    a[0] = 1;

    a[1] = 1, a[2] = 2;

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

        int wow = (i+1) / 2 - 1;

        if(m >= wow) {

            m -= wow;

            a[i] = i;

        }

        else {

            int st = i+1;

            if(m > 0) a[i] = a[i-1] + a[i-m*2];

            else st = i;

            m = 0;

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

                a[j] = 1000000000 - n * (4*n) + j * (4*n);

            }

            break;

        }

    }

    if(!m) {

        for(int i=1; i<=n; i++) cout << a[i] << " ";

        cout << "\n";

    }

    else {

        cout << "-1\n";

    }

}

signed main(){

    precomp();        //Comment when not needed

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

    int t = 1;

//    cin >> t;

    int cnt = 0;

    while(t--){

        stress(++cnt);

        solve(++cnt);

    }

}