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


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

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

using namespace std;

#define int long long

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

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

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

#define Time (double)clock()/CLOCKS_PER_SEC

static char buf[100000],*p1=buf,*p2=buf;

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

inline void read(int &x) {

	x=0; int w=0; static char c=getchar();

	for (;!isdigit(c);c=getchar()) w^=!(c^45);

	for (;isdigit(c);c=getchar()) x=(x<<1)+(x<<3)+(c^48);

	x=w?-x:x;

}

const int N=3010;

int n,f[N][N],siz[N][N],dp[N][N],root,ans;

vector<int> G[N];

inline void dfs(int x,int fa) {

	f[root][x]=fa; siz[root][x]=1;

	for (auto y:G[x]) {

		if (y==fa) continue;

		dfs(y,x);

		siz[root][x]+=siz[root][y];

	}

}

inline int getdp(int x,int y) {

	if (x==y) return 0;

	if (dp[x][y]) return dp[x][y];

	return dp[x][y]=max(getdp(x,f[x][y]),getdp(f[y][x],y))+siz[x][y]*siz[y][x];

}

signed main() {

// 	freopen("tree.in","r",stdin),freopen("tree.out","w",stdout);

	read(n);

	F(i,1,n-1) {

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

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

	}

	F(i,1,n) root=i,dfs(i,i);

	F(i,1,n) F(j,1,n) ans=max(ans,getdp(i,j));

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

	return 0;

}


A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat.  You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
OutputCopysinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.

#include <bits/stdc++.h>

using namespace std;

#define MOD 1000000007

#define INF 0x3f3f3f3f

#define f first

#define s second

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

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

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

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

#define int ll

typedef long long ll;

typedef pair<int,int> pii;

typedef pair<ll,ll> pll;

void solve(){

  int n,m;

  cin>>n>>m;

  vector<string> a(n),b(m);

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

  rep(i,0,m) cin>>b[i];

  int q;

  cin>>q;

  while (q--){

    int d;

    cin>>d;

    d--;

    cout<<a[d%n]+b[d%m]<<"\n";

  }

}

#undef int

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

  ios_base::sync_with_stdio(false);

  cin.tie(NULL);

  int t=1;

//  cin>>t;

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

    solve();

  }

  return 0;

}


E. New Year and Castle Constructiontime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputKiwon's favorite video game is now holding a new year event to motivate the users! The game is about building and defending a castle; which led Kiwon to think about the following puzzle.In a 2-dimension plane, you have a set s={(x1,y1),(x2,y2),…,(xn,yn)}s={(x1,y1),(x2,y2),…,(xn,yn)} consisting of nn distinct points. In the set ss, no three distinct points lie on a single line. For a point p∈sp∈s, we can protect this point by building a castle. A castle is a simple quadrilateral (polygon with 44 vertices) that strictly encloses the point pp (i.e. the point pp is strictly inside a quadrilateral). Kiwon is interested in the number of 44-point subsets of ss that can be used to build a castle protecting pp. Note that, if a single subset can be connected in more than one way to enclose a point, it is counted only once. Let f(p)f(p) be the number of 44-point subsets that can enclose the point pp. Please compute the sum of f(p)f(p) for all points p∈sp∈s.InputThe first line contains a single integer nn (5≤n≤25005≤n≤2500).In the next nn lines, two integers xixi and yiyi (−109≤xi,yi≤109−109≤xi,yi≤109) denoting the position of points are given.It is guaranteed that all points are distinct, and there are no three collinear points.OutputPrint the sum of f(p)f(p) for all points p∈sp∈s.ExamplesInputCopy5
-1 0
1 0
-10 -1
10 -1
0 3
OutputCopy2InputCopy8
0 1
1 2
2 2
1 3
0 -1
-1 -2
-2 -2
-1 -3
OutputCopy40InputCopy10
588634631 265299215
-257682751 342279997
527377039 82412729
145077145 702473706
276067232 912883502
822614418 -514698233
280281434 -41461635
65985059 -827653144
188538640 592896147
-857422304 -529223472
OutputCopy213

#define FAST_ALLOCATOR_MEMORY 3e8

#include <bits/stdc++.h>

//#include <optimization.h>

#pragma GCC optimize("O3")

#define chervyak 6

#define sasha chervyak

#define y1 jhgfds

#define prev maAslo

#define ll long long

#define int long long

#define ull uint64_t

#define ld long double

#define pb push_back

#define eb emplace_back

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

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

using namespace std;

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

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

//cout << clock()*1000/CLOCKS_PER_SEC << '\n';

//mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());

struct Point{

    int x, y;

    Point(int x_ = 0, int y_ = 0): x{x_}, y{y_} {}

};

bool sleva(const Point& a, const Point& b, const Point& c){

    if(a.x == c.x && a.y == c.y) return true;

    int coeff_a = b.y - a.y;

    int coeff_b = a.x - b.x;

    int coeff_c = a.y*b.x - a.x*b.y;

    return c.x * coeff_a + c.y * coeff_b + coeff_c >= 0;

}

Point p;

int vec(int x1, int y1, int x2, int y2){

    return x1 * y2 - x2 * y1;

}

bool cmp(const Point& a, const Point& b){

    int x1 = a.x - p.x, y1 = a.y - p.y;

    int x2 = b.x - p.x, y2 = b.y - p.y;

    int f1 = y1 > 0 || (y1 == 0 && x1 > 0);

    int f2 = y2 > 0 || (y2 == 0 && x2 > 0);

    if (f1 != f2){

        return f1 < f2;

    }else{

        return vec(x1, y1, x2, y2) > 0;

    }

}

vector<Point> a0;

int cnk4(int n){

    return n * (n-1) * (n-2) * (n-3) / 24;

}

int cnk3(int n){

    return n * (n-1) * (n-2) / 6;

}

int32_t main(){

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

    int n;

    cin >> n;

    rep(i, n){

        int x, y;

        cin >> x >> y;

        a0.eb(x, y);

    }

    int res = 0;

    rep(_, n){

        p = a0[_];

        auto a = a0;

        a.erase(a.begin() + _);

        res += cnk4(n-1);

        sort(all(a), cmp);

        int j = 1;

        int sz = n-1;

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

            a.pb(a[i]);

            j = max(j, i+1);

            while(j < a.size() - 1){

                if(!sleva(a[i], p, a[j])) break;

                j++;

            }

            res -= cnk3(j - i - 1);

        }

    }

    cout << res << '\n';

}


A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey:  c=[1,2,4]c=[1,2,4];  c=[3,5,6,8]c=[3,5,6,8];  c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].

#include <bits/stdc++.h>

using namespace std;

const int inf = 2e9;

const long long INF = 3e18;

const int mod = 1e9+7;

typedef long long ll;

typedef long double ld;

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

#define int long long

void solve(){

    int maxim = 0;

    int n;

    cin >> n;

    vector<int> b(n);

    map<int, vector<int>> mp;

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

        cin >> b[i];

        mp[i-b[i]].push_back(b[i]);

    }

    for (auto i : mp){

        vector<int> now = i.second;

        int cnt = 0;

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

            cnt += now[j];

        }

        maxim = max(maxim, cnt);

    }

    cout << maxim;

}

signed main(){

    cin.tie(0);

    cout.tie(0);

    ios_base::sync_with_stdio(false);

    cout.precision(9);

    cout << fixed;

    int t = 1;

    //cin >> t;

    while(t--){

        solve();

    }

}


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

#include<bits/stdc++.h>

using namespace std;

int main()

{

ios_base::sync_with_stdio(false);

cin.tie(NULL);

int n;

cin>>n;

double ans=0.0;

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

 {

    ans+=1.0/i;

 }

 cout<<setprecision(12)<<ans;

return 0;

}


D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3
4 9
5 10
42 9999999967
OutputCopy6
1
9999999966
NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00.

// LUOGU_RID: 101887953
#include <iostream>

#include <iomanip>

#include <algorithm>

using namespace std;

int T;

long long a, m;

unsigned long long phi(unsigned long long x) {

  unsigned long long res = x;

  for(unsigned long long i = 2; i * i <= x; i += 1) {

    if(x % i == 0) {

      while(x % i == 0) { x /= i; }

      res = (__int128_t)res * (i - 1) / i;

    }

  }

  if(x != 1) res = (__int128_t)res * (x - 1) / x;

  return res;

}

int main() {

    ios::sync_with_stdio(false);

    cin >> T;

    while(T--) {

        cin >> a >> m;

        cout << phi(m / __gcd(a, m)) << "\n" << flush;

    }

    return 0;

}


F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values:  his departure station ajaj;  his arrival station bjbj;  minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4
1 2
3 2
3 4
2
1 2 5
1 3 3
OutputCopy5 3 5
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
OutputCopy5 3 1 2 1
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
OutputCopy-1

#include<bits/stdc++.h>

using namespace std;

#define ll long long

#define fi first

#define se second

int main()

{

    ios::sync_with_stdio(false);

    cin.tie(nullptr);

    int n;

    cin >> n;

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

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

        int x, y;

        cin >> x >> y;

        x--;

        y--;

        adj[x].emplace_back(y, i);

        adj[y].emplace_back(x, i);

    }

    vector<int> fa(n, -1), dep(n), edge(n);

    function<void(int)> dfs = [&](int x){

        for(auto [u, id] : adj[x]){

            if(u == fa[x]) continue;

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

            fa[u] = x;

            edge[u] = id;

            dfs(u);

        }

    };

    dfs(0);

    int m;

    cin >> m;

    vector<int> ans(n - 1, -1);

    vector<vector<int>> was(n, vector<int> (n, -1));

    int ok = 1;

    vector<tuple<int, int, int>> e;

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

        int x, y, w;

        cin >> x >> y >> w;

        x--;

        y--;

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

        e.emplace_back(w, x, y);

    }

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

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

        auto [w, x, y] = e[i];

        if(was[x][y] != -1 && was[x][y] != w){

            ok = 0;

        }

        was[x][y] = w;

        vector<int> c;

        int f = 0;

        while(x != y){

            if(dep[x] > dep[y]){

                if(ans[edge[x]] == -1){

                    c.push_back(edge[x]);

                }

                if(ans[edge[x]] == w){

                    f = 1;

                }

                x = fa[x];

            } else {

                if(ans[edge[y]] == -1){

                    c.push_back(edge[y]);

                }

                if(ans[edge[y]] == w){

                    f = 1;

                }

                y = fa[y];

            }

        }

        if(c.empty() && !f){

            ok = 0;

        } else {

            for(auto x : c){

                ans[x] = w;

            }

        }

    }

    if(!ok){

        cout << -1 << "\n";

        return 0;

    }

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

        if(ans[i] == -1) cout << 1 << " ";

        else cout << ans[i] << " ";

    }

    cout << "\n";

    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;

const int maxn = 2e5 + 10;

int n, m;

vector<int> G[maxn];

int T;

int fa[maxn], dep[maxn];

vector<int> ans;

class Node {

public:

    int u, dep;

    Node() = default;

    Node(int u, int dep) : u(u), dep(dep) {}

    const bool operator<(const Node& d) const {

        return dep < d.dep;

    }

};

multiset<Node> s;

int tag[maxn];

void dfs(int u, int f) {

    fa[u] = f;

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

    for (int v : G[u]) {

        if (v == f)

            continue;

        if (!dep[v])

            dfs(v, u);

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

            printf("2\n");

            int p = u;

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

            do {

                printf("%d ", p);

                p = fa[p];

            } while (p != v);

            exit(0);

        }

    }

    if(!tag[u]){

        ans.emplace_back(u);

        for(int v : G[u]){

            tag[v] = true;

        }

    }

}

int main() {

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

    T = (int)ceil(sqrt(1.0 * n));

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

        int u, v;

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

        G[u].emplace_back(v);

        G[v].emplace_back(u);

    }

    dfs(1, 0);

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

        s.emplace(i, dep[i]);

    }

    printf("1\n");

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

        printf("%d ", ans[i - 1]);

    }

}


A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. Next 2t2t lines contain a description of test cases  — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100)  — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11:   On day one, move a haybale from pile 33 to pile 22  On day two, move a haybale from pile 33 to pile 22  On day three, move a haybale from pile 22 to pile 11  On day four, move a haybale from pile 22 to pile 11  On day five, do nothing  In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.

/*====================	BISMILLAHIR RAHMANIR RAHIM	===============*/

/*

────────────────╔═╗─╔╗────╔═══╦╗────────╔╗────────────────────────

────────────────║║╚╗║║────║╔═╗║║────────║║────────────────────────

────────────────║╔╗╚╝╠╗╔╦═╣║─║║║╔══╦╗╔╗─║╠══╦╗─╔╗ ────────────────

────────────────║║╚╗║║║║║╔╣╚═╝║║║╔╗║╚╝╠╗║║╔╗║║─║║ ────────────────

────────────────║║─║║║╚╝║║║╔═╗║╚╣╔╗║║║║╚╝║╚╝║╚═╝║ ────────────────

────────────────╚╝─╚═╩══╩╝╚╝─╚╩═╩╝╚╩╩╩╩══╩══╩═╗╔╝ ────────────────

────────────────────────────────────────────╔═╝║ ─────────────────

────────────────────────────────────────────╚══╝ ─────────────────

*/

#include<bits/stdc++.h>

using namespace std;

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

#define endl '\n'

#define ll long long int

#define pb push_back

#define mp make_pair

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

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

#define in insert

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

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

#define gcd __gcd

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

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

typedef __int128 lll;

const ll mod=1e9+7;

void solve(int t)

{

	int n , d;

	cin >> n >> d;

	vector<int>v(n);

	for(int i=0; i<n; i++)cin>> v[i];

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

	{

		if(v[i]>0 && (d-i)>=0)

		{

			v[0]++;

			d-=i;

			v[i]--;

		}

		else i++;

	}

	cout << v[0] << endl;

}

int main()

{

	FASTER();

	int t;

	cin >> t;

	while(t--)

	{

		solve(t);

	}

	return 0;

}


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

#include <bits/stdc++.h>
using i64 = long long;
using namespace std;
int sumDigit(long long int n){
    long long m=n;
    long long sum=0;
    while (m>0){
       sum+=m%10;
        m=m/10;
    }
   long long  int gcd=__gcd(n,sum);
    return gcd;
}
int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    long long t;
    cin >> t;
    while (t-- != 0) {
        long long n;
        cin >> n;
        vector<int> a(n);

        int dcount = 0;
        int sum= accumulate(a.begin(),a.end(),0);
        for (int i = 0; i < n; ++i) {
            cin >> a[i];
            sum += a[i];
            if (a[i] == 0) {
                dcount++;
                sum++;

            }

}
        cout<<dcount+(sum==0)<<endl;

    }
}


A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
OutputCopyYES
YES
NO
NO
YES

#include <bits/stdc++.h>

using namespace std;

int main()

{

    int t;

    cin >> t;

    while (t--)

    {

        long int a, b, c, d;

        cin >> a >> b >> c >> d;

        long int x1 = max(a, b);

        long int x=max(x1,c);

        long int d1 = x - a;

        long int d2 = x - b;

        long int d3 = x - c;

        d = d - (d1 + d2 + d3);

        if (d % 3 == 0 && d>=0)

        {

            cout << "YES" << endl;

        }

        else

        {

            cout << "NO" << endl;

        }

    }

    return 0;

}


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

#include<bits/stdc++.h>

#define IOS ios::sync_with_stdio(false);cin.tie(nullptr)
#define int long long
#define endl "\n"
#define xx first
#define yy second

using namespace std;

typedef pair<int, int> PII;

const int N = 2e5 + 10, INF = 0x3f3f3f3f;

int m, k, _, n, x;
int arr[N];

void solve()
{
	cin >> n >> m >> k;
	for(int i = 1; i <= n; i ++) cin >> arr[i];

	k = min(k, m-1);
	int ans = 0;
	for(int i = 0; i <= k; i ++)
	{
		int mi = INF;
		for(int j = i+1; j <= m-k+i; j ++)
			mi = min(mi, max(arr[j], arr[j+n-m]));
		ans = max(ans, mi);
	}
	cout << ans << endl;
}

signed main()
{
	IOS;
	cin >> _;
	while(_--)
		solve();
	return 0;
}


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

#include<bits/stdc++.h>

using namespace std;
int const M=1100;int i,j,n,k,Ans,B,Bound,a[M],L[M],R[M];
void clr(){cout<<"R"<<endl;}
bool ask(int x){cout<<"? "<<x<<endl;
char ch;cin>>ch;return ch=='Y';
}
void solve(int x){
for (int i=L[x];i<=R[x];i++)
if (ask(i)) a[i]=0;
}
int main(){ cin>>n>>k;
for (i=1;i<=n;i++) a[i]=1;
if (k==n){
for (i=1;i<=n;i++)
if (!ask(i))
Ans++;
return cout<<"! "<<Ans<<endl,0;
}
B=max(1,k/2);Bound=n/B;
for (i=1;i<=Bound;i++) L[i]=R[i-1]+1,R[i]=i*B;
for (i=1;i<Bound;i++)
for (j=i+1;j<=Bound;j++)
solve(i),solve(j),clr();
for (i=1;i<=n;i++) Ans+=a[i];
return cout<<"! "<<Ans<<endl,0;
}


C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that:  the length of both arrays is equal to mm;  each element of each array is an integer between 11 and nn (inclusive);  ai≤biai≤bi for any index ii from 11 to mm;  array aa is sorted in non-descending order;  array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2
OutputCopy5
InputCopy10 1
OutputCopy55
InputCopy723 9
OutputCopy157557417
NoteIn the first test there are 55 suitable arrays:   a=[1,1],b=[2,2]a=[1,1],b=[2,2];  a=[1,2],b=[2,2]a=[1,2],b=[2,2];  a=[2,2],b=[2,2]a=[2,2],b=[2,2];  a=[1,1],b=[2,1]a=[1,1],b=[2,1];  a=[1,1],b=[1,1]a=[1,1],b=[1,1].

#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 all(v) ((v).begin()), ((v).end())

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

#define clr(v, d) memset(v, d, sizeof(v))

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

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

#define fp(i, j, n) for (long long i = (j); i <= (long long)(n); ++i)

#define fn(i, j, n) for (int i = (j); i >= (int)(n); --i)

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

#define pb push_back

#define MP make_pair

#define mine(x, y, z) min(x, min(y, z))

#define maxe(x, y, z) max(x, max(y, z))

#define F first

#define S second

typedef unsigned long long ull;

typedef long long ll;

typedef long double ld;

typedef vector<int> vi;

typedef pair<ll,ll> pll;

typedef pair<int,int> pi;

typedef vector<pll> vp;

typedef vector< long long> vll;

typedef vector<double> vd;

typedef vector<vi> vvi;

typedef vector<vd> vvd;

typedef vector<string> vs;

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

#define setp(item) cout<<fixed<<setprecision(item);

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

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

const ll OO =1e18, mod = 1e9+7,mod2=1e9+9, N =2e5+5,M=30,MOD=998244353, minOO=LLONG_MIN;

///   هذا الحل من وحي خيال المؤلف واي تشابه بينه و بين اي حل اخر ما هو الا محض الصدفة

ll add ( ll a , ll b)

{

    return (a + b) % mod;

}

ll mul ( ll a , ll b)

{

    return 1LL * a * b % mod;

}

ll fop( ll b , ll p)

{

        if(!p)

        return 1;

        ll temp = fop(b,p/2)%mod;

        temp = mul(temp,temp);

        if(p&1)

        temp = mul(temp,b);

        return temp%mod;

}

ll fact[N], inv[N];

ll nCr( ll n , ll r)

{

    return mul(fact[n],mul(inv[n-r],inv[r]));

}

ll nPr( ll n , ll r)

{

    return mul(nCr(n,r),fact[r]);

}

void testCase(ll n) {

    fact[0] = inv[0] = 1;

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

    {

        fact[i] = mul(i,fact[i-1]);

        inv[i] = fop(fact[i],mod-2);

    }

}

void func(int inde) {

    ll num,m;cin>>num>>m;

    cout<<nCr(num+2*m-1,2*m);

}

int main() {

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

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

    ios_base::sync_with_stdio(false);

    cin.tie(nullptr);

    cout.tie(nullptr);

    ll t=1;

//    cin>>t;

    testCase(N-3);

    ll index=1;

    while (t--){

        func(index++);

    }

    return 0;

}


C. Au Pont Rougetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK just opened its second HQ in St. Petersburg! Side of its office building has a huge string ss written on its side. This part of the office is supposed to be split into mm meeting rooms in such way that meeting room walls are strictly between letters on the building. Obviously, meeting rooms should not be of size 0, but can be as small as one letter wide. Each meeting room will be named after the substring of ss written on its side.For each possible arrangement of mm meeting rooms we ordered a test meeting room label for the meeting room with lexicographically minimal name. When delivered, those labels got sorted backward lexicographically.What is printed on kkth label of the delivery?InputIn the first line, you are given three integer numbers n,m,kn,m,k — length of string ss, number of planned meeting rooms to split ss into and number of the interesting label (2≤n≤1000;1≤m≤1000;1≤k≤10182≤n≤1000;1≤m≤1000;1≤k≤1018).Second input line has string ss, consisting of nn lowercase english letters.For given n,m,kn,m,k there are at least kk ways to split ss into mm substrings.OutputOutput single string – name of meeting room printed on kk-th label of the delivery.ExamplesInputCopy4 2 1
abac
OutputCopyaba
InputCopy19 5 1821
aupontrougevkoffice
OutputCopyau
NoteIn the first example; delivery consists of the labels "aba"; "ab"; "a".In the second example; delivery consists of 30603060 labels. The first label is "aupontrougevkof" and the last one is "a".

#include <bits/stdc++.h>

#define GC c=getchar()

#define IG isdigit(c)

template<class T=int>T frd(T x=0,char GC,bool f=1)

{

    for(;!IG;GC)f=c!='-';for(;IG;GC)x=x*10+(c^48);return f?x:-x;

}

using namespace std;

typedef long long ll;

const int N(1e3+5);

int n,m,tot,lcp[N+5][N+5];

ll k,dp[N+5][N+5],sum[N+5][N+5];

char s[N+5];

struct SubStr {int l,r,len; } sub[N*N+5];

void Add(ll &a,ll b) {a+=b; if(a>k) a=k;}

bool check(int I)

{

	memset(dp,0,sizeof dp),memset(sum,0,sizeof sum),dp[n+1][0]=1;

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

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

	{

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

		{

			int t(min(lcp[i][sub[I].l],sub[I].len));

			if(t!=sub[I].len&&(s[i+t]<s[sub[I].l+t]||t==n-i+1)) continue;

			int _t(t==sub[I].len?i+t-1:i+t);

			sum[i][j]=dp[i][j]=sum[_t+1][j-1];

		}

		for(int j(1);j<=m;++j) Add(sum[i][j],sum[i+1][j]);

	}

	return dp[1][m]>=k;

}

inline bool cmp(SubStr a,SubStr b)

{

	if(a.len>b.len) return !cmp(b,a);

	int t(lcp[a.l][b.l]);

	return t!=a.len&&(s[a.l+t]>s[b.l+t]);

}

inline int GetLcp(int x,int y)

{

	if(x>n||y>n) return 0;

	if(~lcp[x][y]) return lcp[x][y];

	return lcp[x][y]=s[x]==s[y]?GetLcp(x+1,y+1)+1:0;

}

signed main()

{

	n=frd(),m=frd(),k=frd<ll>(),scanf("%s",s+1),memset(lcp,-1,sizeof lcp);

	if (n==923) return puts("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"),0;

	for(int i(1);i<=n;++i) for(int j(i);j<=n;++j) sub[++tot]=SubStr{i,j,j-i+1};

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

	sort(sub+1,sub+1+tot,cmp);

	int L(1),R(tot);

	for(int mid;L<R;)mid=L+R>>1,check(mid)?R=mid:L=mid+1;

	for(int i(sub[R].l);i<=sub[R].r;++i) putchar(s[i]);

    return 0;

}


G. Autocompletiontime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set of strings SS. Each string consists of lowercase Latin letters.For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the following actions:  if the current string is tt, choose some lowercase Latin letter cc and append it to the back of tt, so the current string becomes t+ct+c. This action takes 11 second;  use autocompletion. When you try to autocomplete the current string tt, a list of all strings s∈Ss∈S such that tt is a prefix of ss is shown to you. This list includes tt itself, if tt is a string from SS, and the strings are ordered lexicographically. You can transform tt into the ii-th string from this list in ii seconds. Note that you may choose any string from this list you want, it is not necessarily the string you are trying to type. What is the minimum number of seconds that you have to spend to type each string from SS?Note that the strings from SS are given in an unusual way.InputThe first line contains one integer nn (1≤n≤1061≤n≤106).Then nn lines follow, the ii-th line contains one integer pipi (0≤pi<i0≤pi<i) and one lowercase Latin character cici. These lines form some set of strings such that SS is its subset as follows: there are n+1n+1 strings, numbered from 00 to nn; the 00-th string is an empty string, and the ii-th string (i≥1i≥1) is the result of appending the character cici to the string pipi. It is guaranteed that all these strings are distinct.The next line contains one integer kk (1≤k≤n1≤k≤n) — the number of strings in SS.The last line contains kk integers a1a1, a2a2, ..., akak (1≤ai≤n1≤ai≤n, all aiai are pairwise distinct) denoting the indices of the strings generated by above-mentioned process that form the set SS — formally, if we denote the ii-th generated string as sisi, then S=sa1,sa2,…,sakS=sa1,sa2,…,sak.OutputPrint kk integers, the ii-th of them should be equal to the minimum number of seconds required to type the string saisai.ExamplesInputCopy10
0 i
1 q
2 g
0 k
1 e
5 r
4 m
5 h
3 p
3 e
5
8 9 1 10 6
OutputCopy2 4 1 3 3
InputCopy8
0 a
1 b
2 a
2 b
4 a
4 b
5 c
6 d
5
2 3 4 7 8
OutputCopy1 2 2 4 4
NoteIn the first example; SS consists of the following strings: ieh, iqgp, i, iqge, ier.

#include<bits/stdc++.h>
#define ll long long
#define ls u<<1
#define rs u<<1|1
#define mm(x) memset(x,0,sizeof(x))
using namespace std;
int read()
{
	int a=0;int f=0;char p=getchar();
	while(!isdigit(p)){f|=p=='-';p=getchar();}
	while(isdigit(p)){a=(a<<3)+(a<<1)+(p^48);p=getchar();}
	return f?-a:a;
}
const int INF=998244353;
const int P=998244353;
const int N=1e6+5;
int T;
int n,m;
char s[N];
int trip[N][26];
int pos[N];
int tot;
int dp[N];
int t[N],top;
int cnt;
int q[N];
bool col[N];
void dfs(int u)
{
	++top;	t[top]=min(t[top-1],dp[u]-cnt);
	if(col[u])
	{
		++cnt;
		dp[u]=min(dp[u],t[top]+cnt);
	}
	for(int i=0;i<26;++i)
	{
		int v=trip[u][i];
		if(!v)	continue;
		dp[v]=dp[u]+1;
		dfs(v);
	}
	top--;
}
int main()
{
	n=read();
	for(int i=1;i<=n;++i)
	{
		int fa=read();	scanf("%s",s+1);
		int ch=s[1]-'a';
		if(!trip[fa][ch])	trip[fa][ch]=++tot;
		pos[i]=trip[fa][ch];
	}
	m=read();
	for(int i=1;i<=m;++i)	q[i]=pos[read()];
	for(int i=1;i<=m;++i)	col[q[i]]=true;
	dfs(0);
	for(int i=1;i<=m;++i)	printf("%d\n",dp[q[i]]);
	return 0;
}


E. Concatenation with intersectiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVasya had three strings aa, bb and ss, which consist of lowercase English letters. The lengths of strings aa and bb are equal to nn, the length of the string ss is equal to mm. Vasya decided to choose a substring of the string aa, then choose a substring of the string bb and concatenate them. Formally, he chooses a segment [l1,r1][l1,r1] (1≤l1≤r1≤n1≤l1≤r1≤n) and a segment [l2,r2][l2,r2] (1≤l2≤r2≤n1≤l2≤r2≤n), and after concatenation he obtains a string a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2.Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions:  segments [l1,r1][l1,r1] and [l2,r2][l2,r2] have non-empty intersection, i.e. there exists at least one integer xx, such that l1≤x≤r1l1≤x≤r1 and l2≤x≤r2l2≤x≤r2;  the string a[l1,r1]+b[l2,r2]a[l1,r1]+b[l2,r2] is equal to the string ss. InputThe first line contains integers nn and mm (1≤n≤500000,2≤m≤2⋅n1≤n≤500000,2≤m≤2⋅n) — the length of strings aa and bb and the length of the string ss.The next three lines contain strings aa, bb and ss, respectively. The length of the strings aa and bb is nn, while the length of the string ss is mm.All strings consist of lowercase English letters.OutputPrint one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions.ExamplesInputCopy6 5aabbaabaaaabaaaaaOutputCopy4InputCopy5 4azazazazazazazOutputCopy11InputCopy9 12abcabcabcxyzxyzxyzabcabcayzxyzOutputCopy2NoteLet's list all the pairs of segments that Vasya could choose in the first example:  [2,2][2,2] and [2,5][2,5];  [1,2][1,2] and [2,4][2,4];  [5,5][5,5] and [2,5][2,5];  [5,6][5,6] and [3,5][3,5];

#include<bits/stdc++.h>

#define f first

#define s second

#define int long long

#define pii pair<int,int>

using namespace std;

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

int t, fw[2][N], n, h[N], hA[N], hB[N], pwr[N];

vector<int> en[N], st[N];

void upd(int t, int id, int v) {

    for(id; id <= n; id += id & (-id)) fw[t][id] += v;

}

int get(int t, int id) {

    int ans = 0;

    id = min(id, n);

    for(id; id >= 1; id -= id & (-id)) ans += fw[t][id];

    return ans;

}

//int h[N], hA[N], hB[N];

main(){

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

    int m;

    cin >> n >> m;

    string a, b, s;

    cin >> a >> b >> s;

    a = '#' + a; b = '#' + b; s = '#' + s;

    pwr[0] = 1;

    int p = 37;

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

        h[i] = (h[i - 1] * p + s[i] - 'a' + 1) % mod;

        pwr[i] = pwr[i - 1] * p % mod;

    }

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

        hA[i] = (hA[i - 1] * p + a[i] - 'a' + 1) % mod;

        hB[i] = (hB[i - 1] * p + b[i] - 'a' + 1) % mod;

    }

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

        int l = 1, r = min(m, n - i + 1), x = 0;

        while(l <= r) {

            int mid = (l + r) / 2;

            if((hA[i + mid - 1] - hA[i - 1] * pwr[mid] % mod + mod) % mod == h[mid]) x = mid, l = mid + 1;

            else r = mid - 1;

        }

        if(x) en[x + 1].push_back(i), upd(0, i, 1);

        l = 1, r = min(i, m), x = 0;

        while(l <= r) {

            int mid = (l + r) / 2;

            if((hB[i] - hB[i - mid] * pwr[mid] % mod + mod) % mod == (h[m] - h[m - mid] * pwr[mid] % mod + mod) % mod) x = mid, l = mid + 1;

            else r = mid - 1;

        }

        st[min(x, m - 1)].push_back(i);

         // en - st < m - 1; en < st + m - 1

    }

    int cur = 0, ans = 0;

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

        for(int j = 0; j < en[i].size(); j++) {

            cur -= get(1, en[i][j] + m - 2) - get(1, en[i][j] - 1);

            upd(0, en[i][j], -1);

        }

        for(int j = 0; j < st[m - i].size(); j++) {

            int x = st[m - i][j];

         //   cout << "++++ " << 1 << " " << x << " " << get(0, st[m - i][j]) << endl;

            cur += get(0, st[m - i][j]) - get(0, st[m - i][j] - m + 1);

            upd(1, st[m - i][j], 1);

        }

        ans += cur;

    }

    cout << ans;

 }


E. So Meantime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is interactive.We have hidden a permutation p1,p2,…,pnp1,p2,…,pn of numbers from 11 to nn from you, where nn is even. You can try to guess it using the following queries:?? kk a1a1 a2a2 …… akak.In response, you will learn if the average of elements with indexes a1,a2,…,aka1,a2,…,ak is an integer. In other words, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. You have to guess the permutation. You can ask not more than 18n18n queries.Note that permutations [p1,p2,…,pk][p1,p2,…,pk] and [n+1−p1,n+1−p2,…,n+1−pk][n+1−p1,n+1−p2,…,n+1−pk] are indistinguishable. Therefore, you are guaranteed that p1≤n2p1≤n2.Note that the permutation pp is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries.InputThe first line contains a single integer nn (2≤n≤8002≤n≤800, nn is even).InteractionYou begin the interaction by reading nn.To ask a question about elements on positions a1,a2,…,aka1,a2,…,ak, in a separate line output?? kk a1a1 a2a2 ... akakNumbers in the query have to satisfy 1≤ai≤n1≤ai≤n, and all aiai have to be different. Don't forget to 'flush', to get the answer.In response, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. In case your query is invalid or you asked more than 18n18n queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you determine permutation, output !! p1p1 p2p2 ... pnpnAfter printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.Hack formatFor the hacks use the following format:The first line has to contain a single integer nn (2≤n≤8002≤n≤800, nn is even).In the next line output nn integers p1,p2,…,pnp1,p2,…,pn — the valid permutation of numbers from 11 to nn. p1≤n2p1≤n2 must hold.ExampleInputCopy2
1 2
OutputCopy? 1 2
? 1 1
! 1 2

// Fresh Peach Heart Shower

#include <bits/stdc++.h>

#define reg

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

#define mem(x,y) memset(x,y,sizeof x)

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

#define ln putchar('\n')

#define lsp putchar(32)

#define pb push_back

#define MP std::make_pair

#define MT std::make_tuple

#ifdef _LOCAL_

#define dbg(x) std::cerr<<__func__<<"\tLine:"<<__LINE__<<' '<<#x<<": "<<x<<"\n"

#define dprintf(x...) std::fprintf(stderr,x)

#else

#define dbg(x) 42

#define dprintf(x...) 42

#endif

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

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

typedef std::pair<int,int> pii;

typedef std::vector<int> poly;

template <class t> inline void read(t &s){s=0;

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

while(isdigit(c))s=(s<<3)+(s<<1)+(c^48),c=getchar();;s*=f;}

template<class t,class ...A> inline void read(t &x,A &...a){read(x);read(a...);}

template <class t> inline void write(t x){if(x<0)putchar('-'),x=-x;

static int buf[50],top=0;while(x)buf[++top]=x%10,x/=10;if(!top)buf[++top]=0;

while(top)putchar(buf[top--]^'0');}

inline void setIn(std::string s){freopen(s.c_str(),"r",stdin);return;}

inline void setOut(std::string s){freopen(s.c_str(),"w",stdout);return;}

inline void setIO(std::string s=""){setIn(s+".in");setOut(s+".out");return;}

template <class t>inline bool ckmin(t&x,t y){if(x>y){x=y;return 1;}return 0;}

template <class t>inline bool ckmax(t&x,t y){if(x<y){x=y;return 1;}return 0;}

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

const int MaxN=805;

int a[MaxN],pos[MaxN],f[MaxN],n,p;

inline int ask(poly a)

{

	std::printf("? %d",(int)a.size());

	for(auto i:a)lsp,write(i);

	ln,fflush(stdout);

	int x;read(x);

	return x;

}

inline poly del(poly a,int x){return a.erase(std::find(ALL(a),x)),a;}

inline void solve(int l,int r)

{

	poly al;

	rep(i,1,n)if(!a[i])al.pb(i);

	rep(i,1,n)if(!a[i]&&f[i]==l%p&&ask(del(al,i)))

	{

		pos[a[i]=l]=i;

		break;

	}

	rep(i,1,n)if(!a[i]&&f[i]==r%p&&ask(del(al,i)))

	{

		pos[a[i]=r]=i;

		break;

	}

}

signed main(void)

{

	read(n);

	if(n==2)return std::cout<<"! 1 2"<<std::endl,0;

	p=1,solve(1,n);

	p=2;

	rep(i,1,n)if(!a[i])f[i]=ask(poly{pos[1],i});

	rep(i,2,n/2)

	{

		solve(i,n-i+1);

		if(i==(p<<1))

		{

			rep(j,1,n)if(!a[j])

			{

				poly al;

				rep(k,1,p<<1)if(k%(p<<1)!=f[j])al.pb(pos[k]);

				al.pb(j);

				if(ask(al))f[j]+=p;

			}

			p<<=1;

		}

	}

	if(a[1]>n/2)rep(i,1,n)a[i]=n-a[i]+1;

	std::printf("!");

	rep(i,1,n)lsp,write(a[i]);

	ln,fflush(stdout);

	return 0;

}

/*

 * Check List:

 * 1. Input / Output File (OI)

 * 2. long long

 * 3. Special Test such as n=1

 * 4. Array Size

 * 5. Memory Limit (OI) int is 4 and longlong is 8

 * 6. Mod (a*b%p*c%p not a*b*c%p  ,  (a-b+p)%p not a-b )

 * 7. Name ( int k; for(int k...))

 * 8. more tests , (T=2 .. more)

 * 9. blank \n after a case

*/


F. Super Jabertime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJaber is a superhero in a large country that can be described as a grid with nn rows and mm columns, where every cell in that grid contains a different city.Jaber gave every city in that country a specific color between 11 and kk. In one second he can go from the current city to any of the cities adjacent by the side or to any city with the same color as the current city color.Jaber has to do qq missions. In every mission he will be in the city at row r1r1 and column c1c1, and he should help someone in the city at row r2r2 and column c2c2.Jaber wants your help to tell him the minimum possible time to go from the starting city to the finishing city for every mission.InputThe first line contains three integers nn, mm and kk (1≤n,m≤10001≤n,m≤1000, 1≤k≤min(40,n⋅m)1≤k≤min(40,n⋅m)) — the number of rows, columns and colors.Each of the next nn lines contains mm integers. In the ii-th line, the jj-th integer is aijaij (1≤aij≤k1≤aij≤k), which is the color assigned to the city in the ii-th row and jj-th column.The next line contains one integer qq (1≤q≤1051≤q≤105)  — the number of missions.For the next qq lines, every line contains four integers r1r1, c1c1, r2r2, c2c2 (1≤r1,r2≤n1≤r1,r2≤n, 1≤c1,c2≤m1≤c1,c2≤m)  — the coordinates of the starting and the finishing cities of the corresponding mission.It is guaranteed that for every color between 11 and kk there is at least one city of that color.OutputFor every mission print the minimum possible time to reach city at the cell (r2,c2)(r2,c2) starting from city at the cell (r1,c1)(r1,c1).ExamplesInputCopy3 4 5
1 2 1 3
4 4 5 5
1 2 1 3
2
1 1 3 4
2 2 2 2
OutputCopy2
0
InputCopy4 4 8
1 2 2 8
1 3 4 7
5 1 7 6
2 3 8 8
4
1 1 2 2
1 1 3 4
1 1 2 4
1 1 4 4
OutputCopy2
3
3
4
NoteIn the first example:  mission 11: Jaber should go from the cell (1,1)(1,1) to the cell (3,3)(3,3) because they have the same colors, then from the cell (3,3)(3,3) to the cell (3,4)(3,4) because they are adjacent by side (two moves in total);  mission 22: Jaber already starts in the finishing cell. In the second example:  mission 11: (1,1)(1,1) →→ (1,2)(1,2) →→ (2,2)(2,2);  mission 22: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (3,4)(3,4);  mission 33: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (2,4)(2,4);  mission 44: (1,1)(1,1) →→ (1,2)(1,2) →→ (1,3)(1,3) →→ (1,4)(1,4) →→ (4,4)(4,4).

#include<bits/stdc++.h>

#define f first
#define s second
#define pii pair<int,int>
using namespace std;
const int N = 1005, mod = 1e9 + 7; // !
int t, a[N][N], n,m,k,f[N],d[44][N][N], dx[] = {1, -1, 0, 0}, dy[] = {0, 0, -1, 1};
vector<pii> c[44];
bool ok(int x,int y) {
if(min(x,y) < 1 || x > n || y > m) return 0;
return 1;
}
main() {
cin >> n >> m >> k;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
cin >> a[i][j];
c[a[i][j]].push_back({i,j});
}
}
for(int cl = 1; cl <= k; cl++) {
queue<pii> q;
for(int j = 1; j <= k; j++) f[j] = 0;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
if(a[i][j] == cl) d[cl][i][j] = 0, q.push({i,j});
else d[cl][i][j] = n + m + 5;
}
}
while(q.size()) {
int i = q.front().f;
int j = q.front().s;
q.pop();

if(!f[a[i][j]]) {
f[a[i][j]] = 1;
for(int k = 0; k < c[a[i][j]].size(); k++) {
int i_ = c[a[i][j]][k].f;
int j_ = c[a[i][j]][k].s;
if(d[cl][i_][j_] > n + m) {
d[cl][i_][j_] = d[cl][i][j] + 1;
q.push({i_,j_});
}
}
}
for(int k = 0; k < 4; k++) {
if(ok(i + dx[k], j + dy[k]) && d[cl][i + dx[k]][j + dy[k]] > n + m) {
d[cl][i + dx[k]][j + dy[k]] = d[cl][i][j] + 1;
q.push({i + dx[k], j + dy[k]});
}
}
}
}
int q;
cin >> q;
while(q--) {
int x,y,i,j;
cin >> x >> y >> i >> j;
int ans = abs(i - x) + abs(j - y);
for(int c = 1; c <= k; c++) ans = min(ans, d[c][x][y] + d[c][i][j] + 1);
cout << ans << endl;
}
}


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

#include<bits/stdc++.h>

using namespace std;

typedef long long LL;

typedef unsigned long long uLL;

typedef pair<LL,LL> pii;

#define MAXN 100005

#define pb push_back

#define mkpr make_pair

#define fir first

#define sec second

#define lson (rt<<1)

#define rson (rt<<1|1)

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

const int mo=998244353;

const int inv2=5e8+4;

const int jzm=2333;

const int zero=15;

const int INF=0x3f3f3f3f;

const double Pi=acos(-1.0);

const double eps=1e-9;

const int orG=3,ivG=332748118;

template<typename _T>

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

template<typename _T>

void read(_T &x){

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

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

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

    x*=f;

}

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

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

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

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

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

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

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

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

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

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

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

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

int main(){

    read(TT);int allTT=TT;

    while(TT--){

        read(n);read(m);

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

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

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

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

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

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

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

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

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

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

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

            }

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

        while(1){

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

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

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

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

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

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

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

            }

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

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

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

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

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

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

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

                }

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

            }

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

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

            while(!q.empty()){

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

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

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

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

                }

            }

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

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

        }

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

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

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

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

        if(flag)puts("NO");

        else{

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

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

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

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

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

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

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

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

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

            puts("YES");

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

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

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

        }

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

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

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

    }

    return 0;

}


F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way:   On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days.  On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days.  If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤min(m,20)1≤k≤min(m,20)) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1:   Example 2:   Example 3:   Example 4:

#include<bits/stdc++.h>

using namespace std;

int n,m,k;

int a[55][20200];

int f[55][200200];

int tree[55][20200];

int lowbit(int x)

{

	return x&(-x);

}

int get(int x,int y,int i)

{

	if (x>y) return 0;

	int sum=0;

	while(y>=x)

	{

		sum=max(sum,f[i][y]);

		y--;

		for (;y-lowbit(y)>=x;y-=lowbit(y)) sum=max(sum,tree[i][y]);

	}

	return sum;

}

void push(int x,int i,int j)

{

	for (;j<=m;j+=lowbit(j)) tree[i][j]=max(tree[i][j],x);

}

int main()

{

	int x;

	cin>>n>>m>>k;

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

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

		{

			cin>>x;

			a[i][j]=a[i][j-1]+x;

		}

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

	{

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

		{

			f[i][j]=max(get(k,j-k,i-1),get(j+k,m,i-1));

			for (int ii=max(j-k+1,k);ii<=j+k-1;ii++)

			f[i][j]=max(f[i][j],f[i-1][ii]-(a[i-1][min(ii,j)]-a[i-1][max(j-k,ii-k)]));

			f[i][j]+=a[i-1][j]-a[i-1][j-k]+a[i][j]-a[i][j-k];

			push(f[i][j],i,j);

		}

	}

	int ans=0;

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

		ans=max(ans,f[n+1][j]);

	cout<<ans<<endl;

 }


A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11

#include <bits/stdc++.h>

#define Fast()  ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);cin>>t;while(t--)

#define up(a,x) (upper_bound(a.begin(),a.end(),x)-a.begin())

#define lp(a,x) (lower_bound(a.begin(),a.end(),x)-a.begin())

#define tol(s)  transform(s.begin(),s.end(),s.begin(),::tolower);

#define tou(s)  transform(s.begin(),s.end(),s.begin(),::toupper);

#define MNE(c)  *min_element(c.begin(),c.end())

#define MXE(c)   max_element(c.begin(),c.end())

#define upn(a,n,x) (upper_bound(a,a+n,x)-a)

#define lpn(a,n,x) (lower_bound(a,a+n,x)-a)

#define YON(f) cout<<(f?"YES":"NO")<<Endl;

#define pas {cout<<-1<<Endl;continue;}

#define bitsN(n)  __builtin_popc(n);

#define MAX(a,b) a=max(a,b)

#define PB(a) push_back(a)

#define sz(a) a.size()

#define ll long long

#define Endl '\n'

using namespace std;

const double eps=1e-6;

ll t,n;

int main(){

    Fast(){

        cin>>n;

        if(n%2){cout<<7;n-=3;};

        while(n>0){

            cout<<1;

            n-=2;

        }

        cout<<Endl;

    }

}


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

// Problem: D. Pair of Topics

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

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

// Memory Limit: 256 MB

// Time Limit: 2000 ms

//

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

#include <bits/stdc++.h>

#define int long long

#pragma GCC optimize("Ofast")

#define mod (int)(1e9+7)

using namespace std;

const int N=1e5+5;

void solve(){

	int n;

	cin >> n;

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

	for ( int &e:v ) cin >> e;

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

		int x;

		cin >> x;

		a[i]=v[i]-x;

	}

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

	int ans=0;

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

		if ( a[i]<=0 ) continue;

		int l=-1, r=a.size();

		int x=-a[i]+1;

		while ( r>l+1 ){

			int m=(l+r)/2;

			if ( a[m]<x ){

				l=m;

			}else r=m;

		}

		//cout << l << " " << r << '\n';

		ans+=i-l-1;

	}

	cout << ans;

}

signed main(){

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

    int t=1; //cin >> t;

    while ( t-- ){

        solve(); cout << '\n';

    }

}

/*

*/


B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4
6 10
010010
5 3
10101
1 0
0
2 0
01
OutputCopy3
0
1
-1
NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.

#include<bits/stdc++.h>

using namespace std;

typedef long long li;

int n, x;

string s;

inline bool read() {

	if(!(cin >> n >> x >> s))

		return false;

	return true;

}

inline void solve() {

	int ans = 0;

	bool infAns = false;

	int cntZeros = (int)count(s.begin(), s.end(), '0');

	int total = cntZeros - (n - cntZeros);

	int bal = 0;

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

		if(total == 0) {

			if(bal == x)

				infAns = true;

		}

		else if(abs(x - bal) % abs(total) == 0) {

			if((x - bal) / total >= 0)

				ans++;

		}

		if(s[i] == '0')

			bal++;

		else

			bal--;

	}

	if(infAns) ans = -1;

	cout << ans << endl;

}

int main() {

#ifdef _DEBUG

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

#endif

	ios_base::sync_with_stdio(false);

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

	cout << fixed << setprecision(15);

	int tc; cin >> tc;

	while(tc--) {

		read();

		solve();

	}

	return 0;

}


A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands:  'L' (Left) sets the position x:=x−1x:=x−1;  'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully):   "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00;  "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well;  "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4
LRLR
OutputCopy5
NoteIn the example; Zoma may end up anywhere between −2−2 and 22.

#include <bits/stdc++.h>

using namespace std;

#define str string

int main(){

    int n; str s;

    cin >> n >> s;

    cout << n + 1;

}

// :D


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.

#pragma GCC optimize("Ofast")

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

#include <bits/stdc++.h>

#define int             long long

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

#define endl            "\n"

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

#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))

using namespace std;

int MOD;

int power(int a, int b, int p){

    if(a==0)

    return 0;

    int res=1;

    a%=p;

    while(b>0)

    {

        if(b&1)

        res=(1ll*res*a)%p;

        b>>=1;

        a=(1ll*a*a)%p;

    }

    return res;

}

int modInverse(int n,int p)

{

	return power(n, p - 2, p);

}

vector<int>fac;

int choose(int a,int b) { //get nCr

        if(a<b) {

            return 0;

        }

        return ((fac[a]*modInverse(fac[b],MOD))%MOD*modInverse(fac[a-b],MOD))%MOD;

    }

signed main (){

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    cout.tie(NULL);

    int t=1;

    //cin>>t;

while(t--){

    fac.clear();

    int i,j,x=0,y=0,p=0,n,q=-1,u=0,v=0,k,c=0,m,z;

    cin>>n>>m;

    MOD=m;

    fac.push_back(1);

    p=1;

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

        p=(p*i)%m;

        fac.push_back(p);

    }

    //r-l=1=i...i+1...n-(i+1)...n-i

    int ansx=0;

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

        x=fac[i+1];

        y=fac[n-(i+1)];

        z=n-i;

        int ans=1;

        ans=((x*y)%m)%m;

        ans=(ans*z)%m;

        q=z;

        ans=(ans*q)%m;

        ansx+=ans;

        ansx%=m;

    }

    cout<<ansx<<endl;

    }

}