B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string:   Pick an integer kk, (1≤k≤n1≤k≤n).  For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through:   qwer (original string)  wqer (after reversing the first substring of length 22)  weqr (after reversing the second substring of length 22)  werq (after reversing the last substring of length 22)  Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds:   aa is a prefix of bb, but a≠ba≠b;  in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p
OutputCopyabab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1
NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows :   for k=1k=1 : abab  for k=2k=2 : baba  for k=3k=3 : abab  for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11.

#include<iostream>
#include<cstring>
#include<vector>
#include<map>
#include<queue>
#include<unordered_map>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<set>
#include<cstdlib>
#include<stack>
#include<ctime>
#define forin(i,a,n) for(int i=a;i<=n;i++)
#define forni(i,n,a) for(int i=n;i>=a;i--)
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef double db;
typedef pair<int,int> PII;
const double eps=1e-7;
const int N=6e5+7 ,M=2*N , INF=0x3f3f3f3f,mod=1e9+7;
inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;}
void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);}

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

int T;
int n,m,k;
string str;

void solve() {
    n=read();

    cin>>str;

    int id=1;
    string ans=str;
    for(int i=2;i<=n;i++) {
        if((n-i+1)%2==1) {
            string p=str.substr(0,i-1);
            reverse(p.begin(),p.end());
            string k=str.substr(i-1,n-i+1)+p;
            if(ans>k) {
                ans=k;
                id=i;
            }

        }else {
            string k=str.substr(i-1,n-i+1)+str.substr(0,i-1);
            if(ans>k) {
                ans=k;
                id=i;
            }
        }
    }

    cout<<ans<<'\n'<<id<<'\n';
}

int main() {

    scanf("%d",&T);

    // T=1;
    while(T--) solve();

    return 0;
}


C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3
2 4
1 1
1 1
1 2
2 1
2 2

3 4
1 1 1
1 1
1 2
2 2
2 3

4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
OutputCopy2
1
12
NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11.

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

#include<unordered_map>

#include<algorithm>

using namespace std;

#define ll long long

#define pii pair<ll,ll>

//struct Edge {

//	int from, to, nex;

//}edge[400010];

//int tot, head[200010];

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

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

//	head[u] = tot;

//}

const ll mod = 998244353;

ll qpow(ll x, ll y) {

    ll res = 1;

    while (y) {

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

        x = x * x % mod;

        y >>= 1;

    }

    return res;

}

ll n,m;

ll gcd(ll a, ll b) {

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

}

void solve()

{

    cin >> n >> m;

    vector<ll> a(n + 1);

    vector<set<int>> s(n + 1);

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

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

        int u, v;

        cin >> u >> v;

        s[v].insert(u);

    }

    map<set<int>, ll> mp;

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

      if(!s[i].empty())  mp[s[i]] += a[i];

    }

    ll ans = 0;

    for (auto i : mp) {

        if (ans) ans = gcd(ans, i.second);

        else ans = i.second;

    }

    cout << ans << '\n';

}

signed main()

{

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

    int tt = 1;

    cin >> tt;

    while (tt--) solve();

    return 0;

}

/*

*/


D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3
3 <<
7 >><>><
5 >>><
OutputCopy1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int maxn = 2e5 + 10;

int a[maxn];

int main()

{

    ios::sync_with_stdio(0);

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

    int t;

    cin >> t;

    while (t--) {

        int n;

        string s;

        cin >> n >> s;

        int m = n;

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

            int len = 1;

            while (i < n - 1 && s[i] == '<') {

                ++i;

                ++len;

            }

            for (int j = i; j >= i - len + 1; --j) {

                a[j] = m--;

            }

        }

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

            cout << a[i] << " ";

        }

        cout << endl;

        m = 1;

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

            int len = 1;

            while (i < n - 1 && s[i] == '>') {

                ++i;

                ++len;

            }

            for (int j = i; j >= i - len + 1; --j) {

                a[j] = m++;

            }

        }

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

            cout << a[i] << " ";

        }

        cout << endl;

    }

    return 0;

}


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

#pragma GCC optimize("O2")

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

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace std;

using namespace __gnu_pbds;

#define ll     long long

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

#define ff     first

#define ss     second

#define pb     push_back

#define ppb    pop_back

#define pf     push_front

#define ppf    pop_front

template <typename T> using Ordered_Set_Tree =

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

template <typename T> using Ordered_Multiset_Tree =

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

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

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

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

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

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

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

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

///DEBUG

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

vector<string> vec_splitter(string s)

{

    s += ',';

    vector<string> res;

    while(!s.empty())

    {

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

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

    }

    return res;

}

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

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

{

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

    stringstream ss; ss << H;

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

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

}

///DEBUG

int main()

{

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    test

    {

        int n, d;

        cin>>n>>d;

        int mmax = (n*(n-1))/2;

        int mmin = 0;

        int x = n-1, dd=1, mul=2;

        while(x > mul)

        {

            mmin += mul * dd;

            dd++;

            x -= mul;

            mul *= 2;

        }

        mmin += x * dd;

        if(d>mmax || d<mmin)

        {

            cout<<"NO\n";

            continue;

        }

        ll int val = mmax;

        vector<int> par(n);

        vector<set<int>> canTake(n);

        vector<int> child(n, 0);

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

        {

            canTake[i].insert(i);

            par[i] = i-1;

            child[i] = 1;

        }

        child[n-1] = 0;

        for(int u=n-1; u>0 && val>d; u--)

        {

            int dig = u-1;

            while(dig && val>d && canTake[dig-1].size()>0)

            {

                val--;

                dig--;

            }

            child[par[u]]--;

            par[u] = *canTake[dig].begin();

            child[*canTake[dig].begin()]++;

            if(child[*canTake[dig].begin()] == 2)

                canTake[dig].erase(canTake[dig].begin());

            canTake[dig+1].insert(u);

        }

        cout<<"YES\n";

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

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

        cout<<"\n";

    }

}


#include<bits/stdc++.h>

using namespace std;

#define int long long

#define PII pair<int,int>

#define x first

#define y second

const int N=1e5+10;

void solve()

{

	string s;

	int n;

	cin>>n>>s;

	int l=0,m=n;

	vector<int> res(n);

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

		if(i==n-1||s[i]=='>')

	{

		for(int j=i;j>=l;j--)

			res[j]=m--;

		l=i+1;

	}

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

		cout<<res[i]<<' ';

	cout<<endl;

	l=0,m=1;

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

		if(i==n-1||s[i]=='<')

	{

		for(int j=i;j>=l;j--)

			res[j]=m++;

		l=i+1;

	}

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

		cout<<res[i]<<' ';

	cout<<endl;

	return;

}

signed main()

{

	ios::sync_with_stdio(false);

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

	int T=1;

	cin>>T;

	while(T--)

		solve();

	return 0;

}


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

#pragma GCC optimize("Ofast")

#pragma GCC optimize ("unroll-loops")

#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx")

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include "stdio.h"

using namespace std;

using namespace __gnu_pbds;

// #define int long long

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

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

#define ff first

#define ss second

#define sz(a) (a).size()

template<typename T> using indexed_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

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

typedef long double ld;

namespace io{

    template<typename F, typename S> ostream& operator << ( ostream &os, const pair<F, S> &p ) { return os << p.ff << " " << p.ss; }

    template<typename F, typename S> ostream& operator << ( ostream &os, const map<F, S> &mp ) { for( auto it : mp ) { os << it << endl;  } return os; }

    template<typename F> ostream& operator << ( ostream &os, const vector<F> &v ) { bool space = false; for( F x : v ) { if( space ) os << " "; space = true; os << x; } return os; }

    template<typename F> ostream& operator << ( ostream &os, const deque<F> &d ) { bool space = false; for( F x : d ) { if( space ) os << " "; space = true; os << x; } return os; }

    template<typename F> ostream& operator << ( ostream &os, const set<F> &st ) { bool space = false; for( F x : st ) { if( space ) os << " "; space = true; os << x; } return os; }

    template<typename F> ostream& operator << ( ostream &os, const multiset<F> &st ) { bool space = false; for( F x : st ) { if( space ) os << " "; space = true; os << x; } return os; }

    template<typename F, typename S> istream& operator >> ( istream &is, pair<F, S> &p ) { return is >> p.ff >> p.ss; }

    template<typename F> istream& operator >> ( istream &is, vector<F> &v ) { for( F &x : v ) { is >> x; } return is; }

    long long fastread(){ char c; long long d = 1, x = 0; do c = getchar(); while( c == ' ' || c == '\n' ); if( c == '-' ) c = getchar(), d = -1; while( isdigit( c ) ){ x = x * 10 + c - '0'; c = getchar(); } return d * x; }

    static bool sep = false;

    using std::to_string;

    string to_string( bool x ){ return ( x ? "true" : "false" ); }

    string to_string( const string & s ){ return "\"" + s + "\""; }

    string to_string( const char * s ){ return "\"" + string( s ) + "\""; }

    string to_string ( const char & c ) { string s; s += c; return "\'" + s + "\'"; }

    template<typename Type> string to_string( vector<Type> );

    template<typename F, typename S> string to_string( pair<F, S> );

    template<typename Collection> string to_string( Collection );

    template<typename F, typename S> string to_string( pair<F, S> p ){ return "{" + to_string( p.ff ) + ", " + to_string( p.ss ) + "}"; }

    template<typename Type> string to_string( vector<Type> v ) { bool sep = false; string s = "["; for( Type x: v ){ if( sep ) s += ", "; sep = true; s += to_string( x ); } s += "]"; return s; }

    template<typename Collection> string to_string( Collection collection ) { bool sep = false; string s = "{"; for( auto x: collection ){ if( sep ) s += ", "; sep = true; s += to_string( x ); } s += "}"; return s; }

    void print() { cout << endl; sep = false; }

    template <typename F, typename... Other> void print( F ff, Other... other ) { if( sep ) cout << " | "; sep = true; cout << to_string( ff ); print( other... ); }

} using namespace io;

namespace utils {

    template<typename F, typename S> inline void maxs ( F &a, S b ) { a = a > b ? a : b; }

    template<typename F, typename S> inline void mins ( F &a, S b ) { a = a < b ? a : b; }

    template<typename F, typename S> int max(F a, S b) { return a > b ? a : b; }

    template<typename F, typename S> int min(F a, S b) { return a < b ? a : b; }

    constexpr long long operator"" _E ( unsigned long long n ){ long long p = 1, a = 10; for( int i = 0; i < n; i++ ) p *= a; return p; }

    random_device rd; mt19937 mt( rd( ) );

    template<typename T> T rand ( T l, T r ) { uniform_int_distribution<T> dist( l, r ); return dist( mt ); };

} using namespace utils;

#ifdef sunnitov

#define print( ... ) cout << "[" << #__VA_ARGS__ << "]: "; io::print( __VA_ARGS__ );

#else

#define print( ... ) 42

#endif

int mod = 9_E + 7;

const double EPS = 1e-7;

long long LLINF = 18_E + 10;

int INF = 9_E + 10;

const char nl = '\n';

int month[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};

/*

*/

int n, m, tar;

vector<vector<int>> a;;

bool ok(int mid) {

    vector<bool> can(tar + 1);

    vector<int> bit(n + 1);

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

        int pw = 1;

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

            if (a[i][j] >= mid) {

                bit[i] += pw;

            }

            pw *= 2;

        }

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

            if ((j | bit[i]) == bit[i]) {

                can[j] = 1;

            }

        }

    }

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

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

            if (can[j] and (j | bit[i]) == tar) {

                return true;

            }

        }

    }

    return false;

}

void solution( istream &cin, ostream &cout, const int &test_case ){

    cin >> n >> m;

    tar = (1 << m) - 1;

    a.assign(n, vector<int>(m));

    cin >> a;

    int l = 0, r = 1e9 + 100, ans = -1;

    while (l <= r) {

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

        if (ok(mid)) {

            ans = mid;

            l = mid + 1;

        } else {

            r = mid - 1;

        }

    }

    // cout << ans;

    vector<bool> can(tar + 1);

    vector<int> bit(n + 1);

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

        int pw = 1;

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

            if (a[i][j] >= ans) {

                bit[i] += pw;

            }

            pw *= 2;

        }

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

            if ((j | bit[i]) == bit[i]) {

                can[j] = 1;

            }

        }

    }

    int ia, ij;

    for (int x1 = 0; x1 <= tar; x1++) {

        for (int x2 = 0; x2 <= tar; x2++) {

            if (!can[x1] or !can[x2] or (x1 | x2) != tar) continue;

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

                if ((bit[i] | x1) == bit[i]) ia = i;

                if ((bit[i] | x2) == bit[i]) ij = i;

            }

        }

    }

    cout << ia + 1 << " " << ij + 1;

}

int32_t main(){

    clock_t startTime = clock();

    ios_base::sync_with_stdio( false ); cin.tie( nullptr ); cout.tie( nullptr );

    srand( time( 0 ) );

    std::istream& in( std::cin ) ;

    std::ostream& out( std::cout );

    int32_t queries = 1;

    #ifdef test_cases

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

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

    cin >> queries;

    #else

    // cin >> queries;

    #endif

    for( int32_t test_case = 1; test_case <= queries; test_case++ ){

    	print(test_case);

        solution( cin, cout, test_case );

        cout << nl;

    }

    #ifdef sunnitov

    cout << "Time: " << (int)((double) (clock() - startTime) / CLOCKS_PER_SEC * 1000) << " ms" << endl;

    #endif

    return EXIT_SUCCESS;

}


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

#include <bits/stdc++.h>

#include <iostream>

using namespace std;

void solve()

{

    int n;

    cin >> n;

    int a[n];

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

    {

        cin >> a[i];

    }

    sort(a, a + n, greater<int>());

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

    {

        cout<<a[i]<<" ";

    }

    cout<<endl;

    return ;

}

int main()

{

    int t;

    cin >> t;

    while (t--)

    {

        solve();

    }

    return 0;

}


B. Double Eliminationtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe biggest event of the year – Cota 2 world championship "The Innernational" is right around the corner. 2n2n teams will compete in a double-elimination format (please, carefully read problem statement even if you know what is it) to identify the champion. Teams are numbered from 11 to 2n2n and will play games one-on-one. All teams start in the upper bracket.All upper bracket matches will be held played between teams that haven't lost any games yet. Teams are split into games by team numbers. Game winner advances in the next round of upper bracket, losers drop into the lower bracket.Lower bracket starts with 2n−12n−1 teams that lost the first upper bracket game. Each lower bracket round consists of two games. In the first game of a round 2k2k teams play a game with each other (teams are split into games by team numbers). 2k−12k−1 loosing teams are eliminated from the championship, 2k−12k−1 winning teams are playing 2k−12k−1 teams that got eliminated in this round of upper bracket (again, teams are split into games by team numbers). As a result of each round both upper and lower bracket have 2k−12k−1 teams remaining. See example notes for better understanding.Single remaining team of upper bracket plays with single remaining team of lower bracket in grand-finals to identify championship winner.You are a fan of teams with numbers a1,a2,...,aka1,a2,...,ak. You want the championship to have as many games with your favourite teams as possible. Luckily, you can affect results of every championship game the way you want. What's maximal possible number of championship games that include teams you're fan of?InputFirst input line has two integers n,kn,k — 2n2n teams are competing in the championship. You are a fan of kk teams (2≤n≤17;0≤k≤2n2≤n≤17;0≤k≤2n).Second input line has kk distinct integers a1,…,aka1,…,ak — numbers of teams you're a fan of (1≤ai≤2n1≤ai≤2n).OutputOutput single integer — maximal possible number of championship games that include teams you're fan of.ExamplesInputCopy3 1
6
OutputCopy6
InputCopy3 3
1 7 8
OutputCopy11
InputCopy3 4
1 3 5 7
OutputCopy14
NoteOn the image; each game of the championship is denoted with an English letter (aa to nn). Winner of game ii is denoted as WiWi, loser is denoted as LiLi. Teams you're a fan of are highlighted with red background.In the first example, team 66 will play in 6 games if it looses the first upper bracket game (game cc) and wins all lower bracket games (games h,j,l,mh,j,l,m). In the second example, teams 77 and 88 have to play with each other in the first game of upper bracket (game dd). Team 88 can win all remaining games in upper bracket, when teams 11 and 77 will compete in the lower bracket. In the third example, your favourite teams can play in all games of the championship.

#include<iostream>

#include<cstring>
#include<algorithm>
using namespace std;
using LL = long long;
const int maxn = 1e6 + 5;

bool v[maxn];

int main(){

#ifdef LOCAL
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif

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

const int INF = 1e9;
int n, k;
cin >> n >> k;
if (k == 0){
cout << 0 << '\n';
return 0;
}
vector<array<int, 4> > dp(1 << n, {0, -INF, -INF, -INF});
for(int i = 1; i <= k; i++){
int x;
cin >> x;
int s = (1 << n - 1) + (x - 1) / 2;
if (dp[s][1] != -INF) dp[s][3] = 1;
else dp[s][1] = dp[s][2] = 1;
}
for(int i = (1 << n - 1) - 1; i >= 1; i--){
for(int j = 0; j < 4; j++){
for(int k = 0; k < 4; k++){
dp[i][j | k] = max(dp[i][j | k], dp[2 * i][j] + dp[2 * i + 1][k] + (j | k));
}
}
}
cout << max({dp[1][1], dp[1][2], dp[1][3]}) + 1 << '\n';

}


F. Making Shapestime limit per test5 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputYou are given nn pairwise non-collinear two-dimensional vectors. You can make shapes in the two-dimensional plane with these vectors in the following fashion: Start at the origin (0,0)(0,0). Choose a vector and add the segment of the vector to the current point. For example, if your current point is at (x,y)(x,y) and you choose the vector (u,v)(u,v), draw a segment from your current point to the point at (x+u,y+v)(x+u,y+v) and set your current point to (x+u,y+v)(x+u,y+v). Repeat step 2 until you reach the origin again.You can reuse a vector as many times as you want.Count the number of different, non-degenerate (with an area greater than 00) and convex shapes made from applying the steps, such that the shape can be contained within a m×mm×m square, and the vectors building the shape are in counter-clockwise fashion. Since this number can be too large, you should calculate it by modulo 998244353998244353.Two shapes are considered the same if there exists some parallel translation of the first shape to another.A shape can be contained within a m×mm×m square if there exists some parallel translation of this shape so that every point (u,v)(u,v) inside or on the border of the shape satisfies 0≤u,v≤m0≤u,v≤m.InputThe first line contains two integers nn and mm  — the number of vectors and the size of the square (1≤n≤51≤n≤5, 1≤m≤1091≤m≤109).Each of the next nn lines contains two integers xixi and yiyi  — the xx-coordinate and yy-coordinate of the ii-th vector (|xi|,|yi|≤4|xi|,|yi|≤4, (xi,yi)≠(0,0)(xi,yi)≠(0,0)).It is guaranteed, that no two vectors are parallel, so for any two indices ii and jj such that 1≤i<j≤n1≤i<j≤n, there is no real value kk such that xi⋅k=xjxi⋅k=xj and yi⋅k=yjyi⋅k=yj.OutputOutput a single integer  — the number of satisfiable shapes by modulo 998244353998244353.ExamplesInputCopy3 3
-1 0
1 1
0 -1
OutputCopy3
InputCopy3 3
-1 0
2 2
0 -1
OutputCopy1
InputCopy3 1776966
-1 0
3 3
0 -2
OutputCopy296161
InputCopy4 15
-4 -4
-1 1
-1 -4
4 3
OutputCopy1
InputCopy5 10
3 -4
4 -3
1 -3
2 -3
-3 -4
OutputCopy0
InputCopy5 1000000000
-2 4
2 -3
0 -4
2 4
-1 -3
OutputCopy9248783
NoteThe shapes for the first sample are:  The only shape for the second sample is:  The only shape for the fourth sample is:


E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times:  Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair).  Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5
4 3 2 2 3
OutputCopy2
InputCopy7
3 3 4 4 4 3 3
OutputCopy2
InputCopy3
1 3 5
OutputCopy3
InputCopy1
1000
OutputCopy1
NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all.

#include<iostream>

#include<cstring>

#include<algorithm>

using namespace std;

int n;

const int N = 1100;

int a[N],s[N];

int f[N][N],g[N];

int main()

{

    cin>>n;

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

    {

        cin>>a[i];

        f[i][i]=a[i];

    }

    for(int len=2;len<=n;len++)

    {

        for(int l=1;l+len-1<=n;l++)

        {

            int r=l+len-1;

            for(int k=1;k<r;k++)

            {

                if(f[l][k]==f[k+1][r] && f[l][k]) f[l][r]=f[k+1][r]+1;

            }

        }

    }

    memset(g,0x3f,sizeof g);

    g[0]=0;

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

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

    if(f[j+1][i]) g[i]=min(g[i],g[j]+1);

    cout<<g[n];

}


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.

#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< ll, null_type, less<ll>, 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 =1e6+5,M=30,MOD=998244353;

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

void solve(int inde) {

    ll num,k;cin>>num>>k;

    vll vec(num);

    fo(i,num)cin>>vec[i];

    fp(i,1,num-1){

        ll nu=k/i;

        ll nn=min(nu,vec[i]);

        vec[0]+=min(nu,vec[i]);

        k-=i*nn;

    }

    cout<<vec[0]<<'\n';

}

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;

    ll index=1;

    while (t--){

        solve(index++);

    }

    return 0;

}


B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2
1 0 1
1 1 1
OutputCopy4
InputCopy3 5 4
1 1 1
1 1 1 1 1
OutputCopy14
NoteIn first example matrix cc is:  There are 44 subrectangles of size 22 consisting of only ones in it:  In second example matrix cc is:

#include "bits/stdc++.h"

using namespace std;

#ifdef LOCAL

#include "debug.h"

#endif

// abbreviations

using chr = char;     using ll = long long;     using pll = pair<ll, ll>;

using str = string;   using ld = long double;   using pii = pair<int, int>;

template<class T> using MaxHeap = priority_queue<T, vector<T>,    less<T>>;

template<class T> using MinHeap = priority_queue<T, vector<T>, greater<T>>;

template<typename T, typename T1> T amax(T &a, T1 b) { if (b > a) a = b; return a; }

template<typename T, typename T1> T amin(T &a, T1 b) { if (b < a) a = b; return a; }

// definitons

#define fi first

#define se second

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

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

// constants

const int maxN = 1e6 + 2;

const int Mod = 1e9 + 7, Modd = 998244353;

const int inf = 0x3f3f3f3f;

const ll linf = 1e18;

void aine() {

    int n, m, k;

    cin >> n >> m >> k;

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

    vector<int> div;

    for (int i = 1; i <= sqrt(k); ++i) {

        if (k % i == 0) {

            div.push_back(i);

        }

    }

    for (auto &i : a) cin >> i;

    for (auto &i : b) cin >> i;

    vector<int> suba, subb;

    vector<int> nums(n + 1), Nums(m + 1);

    a.push_back(0); b.push_back(0);

    int len = 0;

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

        if (a[i] == 0) {

            suba.push_back(len);

            len = 0;

        }

        else len++;

    }

    len = 0;

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

        if (b[i] == 0) {

            subb.push_back(len);

            len = 0;

        }

        else len++;

    }

    for (auto i : suba) {

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

            nums[j] += i - j + 1;

        }

    }

    for (auto i : subb) {

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

            Nums[j] += i - j + 1;

        }

    }

    // debug(nums, Nums, div);

    ll ans = 0;

    for (auto i : div) {

        int p = i, q = k / i;

        if (p <= n && q <= m) ans += 1ll * nums[p] * Nums[q];

        if (p != q && p <= m && q <= n) ans += 1ll * nums[q] * Nums[p];

    }

    cout << ans << '\n';

}

signed main() {

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

    int t = 1;

    // cin >> t;

    while (t--) { aine(); } cout << '\n';

    return 0;

}


C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab.  During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab.  During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab.  During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba.  During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows.  During the first move, remove the third character s3=s3= d, ss becomes bca.  During the second move, remove the second character s2=s2= c, ss becomes ba.  And during the third move, remove the first character s1=s1= b, ss becomes a.

/* Author: izhang
 * Time: 02-06-2023 22:48:21
**/
#include <bits/stdc++.h>

using namespace std;

#if defined LOCAL || defined DEBUG
#include <debug.h>
#else
struct dbg {
    template<class c>
    dbg &operator<<(const c &) { return *this; }
};
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "
#endif

//#define DEBUG
void setIO(const string &name) {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cin.exceptions(istream::failbit);
#ifdef LOCAL
    freopen(("in" + name + ".txt").c_str(), "r", stdin);
    freopen("out.txt", "w", stdout);
    freopen("out.txt", "w", stderr);
#endif
}
const int inf = 0x3f3f3f3f, mod = 1e9 + 7; //998244353;
const long long INFL = 0x3f3f3f3f3f3f3f3f;

void test_case() {
    int n;
    cin >> n;
    string s;
    cin >> s;
    int sol = 0;
    bool found = true;
    while (found) {
        found = false;
        pair<char, int> mx;
        for (int i = 0; i < n; ++i) {
            if ((i > 0 && s[i - 1] + 1 == s[i]) || (i < n && s[i + 1] + 1 == s[i])) {
                mx = max(mx, {s[i], i});
                found = true;
            }
        }
        if (found) {
            string tmp;
            for (int i = 0; i < n; ++i) {
                if (i != mx.second) {
                    tmp += s[i];
                }
            }
            swap(s, tmp);
            ++sol;
        }
    }
    cout << sol << "\n";
}

int main() {
    setIO("1");

    int test_case_number = 1;
    while (test_case_number--) {
        test_case();
    }
    return 0;
}


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

#include <iostream>

#include <vector>

#include <algorithm>

#include <map>

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

#define LEFT(n) (2*n)

#define RIGHT(n) (2*n + 1)

using namespace std;

struct Point

{

    long long distance, velocity;

    Point(){};

    Point(long long D, long long V)

    {

        distance = D;

        velocity = V;

    }

};

int sort_by_distance(const Point &P, const Point &Q)

{

    return (P.distance < Q.distance);

}

const int MAX_N = 2e5 + 5;

pair <long long, int> sum_tree[3*MAX_N];

void update(int n, int left, int right, int position, long long value)

{

    if(position < left || right < position)

    {

        return;

    }

    if(left == right)

    {

        sum_tree[n].first += value;

        sum_tree[n].second++;

        //cout << "Sum Tree " << n << " = " << sum_tree[n].first << "," << sum_tree[n].second << "\n";

        return;

    }

    int mid = (left + right)/2;

    update(LEFT(n), left, mid, position, value);

    update(RIGHT(n), mid + 1, right, position, value);

    sum_tree[n].second = sum_tree[LEFT(n)].second + sum_tree[RIGHT(n)].second;

    sum_tree[n].first = sum_tree[LEFT(n)].first + sum_tree[RIGHT(n)].first;

    //cout << "Sum Tree " << n << " = " << sum_tree[n].first << "," << sum_tree[n].second << "\n";

}

pair <long long, int> get(int n, int left, int right, int query_left, int query_right)

{

    if(query_right < left || right < query_left || query_right < query_left)

    {

        return make_pair(0, 0);

    }

    if(query_left <= left && right <= query_right)

    {

        return sum_tree[n];

    }

    int mid = (left + right)/2;

    pair <long long, int> left_answer = get(LEFT(n), left, mid, query_left, query_right);

    pair <long long, int> right_answer = get(RIGHT(n), mid + 1, right, query_left, query_right);

    pair <long long, int> answer;

    answer.second = left_answer.second + right_answer.second;

    answer.first = left_answer.first + right_answer.first;

    return answer;

}

int main()

{

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    int no_of_points;

    cin >> no_of_points;

    vector <Point> P(no_of_points);

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

    {

        cin >> P[i].distance;

    }

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

    {

        cin >> P[i].velocity;

    }

    sort(all(P), sort_by_distance);

    vector <int> velocities;

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

    {

        velocities.push_back(P[i].velocity);

    }

    sort(all(velocities));

    map <long long, int> effective_index;

    effective_index[velocities[0]] = 1;

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

    {

        if(velocities[i] == velocities[i - 1])

        {

            continue;

        }

        effective_index[velocities[i]] = effective_index[velocities[i - 1]] + 1;

    }

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

    {

        sum_tree[i] = make_pair(0, 0);

    }

    long long answer = 0;

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

    {

        pair <long long, int> Q = get(1, 1, no_of_points, 1, effective_index[P[i].velocity]);

        long long total = Q.first;

        int no_of_points_here = Q.second;

        //cout << "At x = " << P[i].distance << " V = " << P[i].velocity << "\n";

        //cout << "No of Points = " << no_of_points_here << " Total = " << total << "\n";

        //cout << "Range = [1, " << effective_index[P[i].velocity] - 1 << "]\n";

        answer += ( (no_of_points_here)*P[i].distance - total);

        //cout << "Answer = " << answer << "\n";

        update(1, 1, no_of_points, effective_index[P[i].velocity], P[i].distance);

    }

    cout << answer << "\n";

    return 0;

}


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

#include<bits/stdc++.h>

using namespace std;

#pragma GCC optimize ("Ofast")

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

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

#define mp(x , y) make_pair(x , y)

#define wall cout<<"--------------------------------------\n";

typedef long long int ll;

typedef pair<ll , ll> pll;

typedef pair<int , int> pii;

typedef double db;

typedef pair<pll , ll> plll;

typedef pair<int , pii> piii;

typedef pair<pll , pll> pllll;

const ll maxn = 1e6 + 17 , md = 1e9 + 7 , inf = 2e16;

char c;

bool a[maxn];

vector<ll> v[maxn];

int main(){

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

	ll n , k;

	cin>>n>>k;

	if(k > 1) k >>= 1;

	ll m = n / k , x = 0;

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

		v[x].push_back(i);

		x += (i % k == 0);

	}

	for(ll t = 1 ; t < m ; t++){

		for(ll s = 0 ; s < t ; s++){

			if(s + t >= m) break;

			for(ll i = s ; i < m ; i += t){

				for(auto j : v[i]){

					cout<<"? "<<j<<endl;

					cin>>c;

					a[j] |= (c == 'Y');

				}

			}

			cout<<"R"<<endl;

		}

	}

	ll cnt = 0;

	for(ll i = 1 ; i <= n ; i++) cnt += !a[i];

	cout<<"! "<<cnt<<endl;

	return 0;

}


E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9
abacbecfd
OutputCopy2
1 1 2 1 2 1 2 1 2
InputCopy8
aaabbcbb
OutputCopy2
1 2 1 2 1 2 1 1
InputCopy7
abcdedc
OutputCopy3
1 1 1 1 1 2 3
InputCopy5
abcde
OutputCopy1
1 1 1 1 1

#include<bits/stdc++.h>

using namespace std;

typedef long long ll;

int maxdp[26], ans[200001];

int main()

{

	ios::sync_with_stdio(0);

	cin.tie(0);

	cout.tie(0);

	int n, len, maxn;

	string s;

	cin>>n;

	cin>>s;

	len = s.length();

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

	{

		ans[i] = 1;

		for(int j=25;j>(s[i]-'a');--j)

		{

			ans[i] = max(ans[i], maxdp[j]+1);

		}

		maxdp[s[i]-'a'] = ans[i];

		maxn = max(maxn, maxdp[s[i]-'a']);

	}

	cout<<maxn<<"\n";

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

	{

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

	}

	return 0;

}


A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules:  every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes);  each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk;  all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors.

// CF template, version 3.0

#include <bits/stdc++.h>

using namespace std;

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

#define getTest int t; cin >> t

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

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

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

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

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

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

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

#define int long long int

int gcd(int a, int b) {

    if (a == b) return a;

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

}

/*

Segtree:

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

    if (l == r) {

        tree[i] = array[l];

    } else {

        int middle = (l + r) / 2;

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

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

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

    }

}

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

    if (l == r) {

        tree[v] = x;

    } else {

        int middle = (l + r) / 2;

        if (i <= middle) {

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

        } else {

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

        }

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

    }

}

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

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

        return tree[v];

    }

    if (l > r) return 0;

    int middle = (cl + cr) / 2;

    return max(

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

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

    );

}

vector<int> tree(4 * n);

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

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

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

data structure can be changed

*/

signed main() {

    improvePerformance;

    getTest;

    vector<vector<vector<int>>> arrs = {{{0, 0, 1}}, {{0, 1, 1}, {0, 0, 1}}, {{0, 1, 1}}, {{0, 1, 0}, {0, 0, 1}}, {{0, 1, 0}}, {{0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{0, 1, 0}, {0, 1, 1}}, {{1, 1, 1}, {0, 0, 1}}, {{1, 1, 1}}, {{1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 1, 1}, {0, 1, 1}}, {{1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 1, 1}, {0, 1, 0}}, {{1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 1, 0}, {0, 0, 1}}, {{1, 1, 0}}, {{1, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 1, 0}, {0, 1, 1}}, {{1, 1, 0}, {0, 1, 0}, {0, 0, 1}}, {{1, 1, 0}, {0, 1, 0}}, {{1, 1, 0}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 1, 0}, {0, 1, 0}, {0, 1, 1}}, {{1, 1, 0}, {1, 1, 1}, {0, 0, 1}}, {{1, 1, 0}, {1, 1, 1}}, {{1, 1, 0}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 1, 0}, {1, 1, 1}, {0, 1, 1}}, {{1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 1, 0}, {1, 1, 1}, {0, 1, 0}}, {{1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 1}, {0, 0, 1}}, {{1, 0, 1}}, {{1, 0, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {0, 1, 1}}, {{1, 0, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 1}, {0, 1, 0}}, {{1, 0, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 1}, {1, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 1}}, {{1, 0, 1}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 1}, {0, 1, 1}}, {{1, 0, 1}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 1}, {0, 1, 0}}, {{1, 0, 1}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 1}, {1, 1, 0}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}}, {{1, 0, 1}, {1, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {0, 1, 1}}, {{1, 0, 1}, {1, 1, 0}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {0, 1, 0}}, {{1, 0, 1}, {1, 1, 0}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {0, 0, 1}}, {{1, 0, 0}}, {{1, 0, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {0, 1, 1}}, {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {0, 1, 0}}, {{1, 0, 0}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 1}}, {{1, 0, 0}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 1}, {0, 1, 1}}, {{1, 0, 0}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 1}, {0, 1, 0}}, {{1, 0, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}}, {{1, 0, 0}, {1, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 1, 0}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {0, 1, 0}}, {{1, 0, 0}, {1, 1, 0}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {0, 1, 0}}, {{1, 0, 0}, {1, 0, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 1, 0}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 1, 0}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}};

    eachTest {

        get(a);

        get(b);

        get(c);

        int maxi = 0;

        for (vector<vector<int>> cur: arrs) {

            int A=a;

            int B=b;

            int C=c;

            bool can = true;

            for (vector<int> arr: cur) {

                A-=arr[0];

                B-=arr[1];

                C-=arr[2];

                if (A<0||B<0||C<0) {

                    can = false;

                    break;

                }

            }

            if (can && cur.size() > maxi) maxi = cur.size();

        }

        out(maxi);

        out("\n");

    }

}


B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk  — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm  — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am  — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()((
OutputCopy1
2
1 3
InputCopy)(
OutputCopy0
InputCopy(()())
OutputCopy1
4
1 2 5 6
NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations.

#include<bits/stdc++.h>

using namespace std;

int main()

{

    string s;cin>>s;

    int n = s.length();

    vector<int> a;

    vector<int> b;

    int close=0;

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

    {

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

        {

            b.push_back(i);

            close++;

        }

        else

        a.push_back(i);

    }

    if(close==0)

    {

        cout<<0<<"\n";

        return 0;

    }

    int c=0;

    int ma=INT_MIN;

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

    {

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

        c++;

        else

        close--;

        if(s[i]=='(' && close>=c)

        ma  =max(ma,c);

    }

    if(ma==INT_MIN)

    {

        cout<<0<<"\n";

        return 0;

    }

    cout<<1<<"\n";

    cout<<ma*2<<"\n";

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

    vector<int> ans;

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

    {

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

        ans.push_back(b[i]+1);

    }

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

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

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

    cout<<"\n";

}


A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.

#include <bits/stdc++.h>
//#include <string>
#include <algorithm>
//#include <vector>
//#include <set>
#include <numeric>
#define ll long long
using namespace std;
const int k = 1e5*2;
int arr[k];

int main() {

    int a;
    cin >> a;
    int sum = 0;
    for (int i = 2; i < a; i++) {
        int x = a;
        while (x) {
            sum += x % i;
            x /= i;
        }
    }
    int y = gcd(sum , a-2);
    cout<< sum/y << "/"<< (a-2)/y;
}


A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":   "A" corresponds to an angry student  "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1
4
PPAP
OutputCopy1
InputCopy3
12
APPAPPPAPPPP
3
AAP
3
PPA
OutputCopy4
1
0
NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is:   after 11 minute — AAPAAPPAAPPP  after 22 minutes — AAAAAAPAAAPP  after 33 minutes — AAAAAAAAAAAP  after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry.

#include<bits/stdc++.h>
#define Mohamed ios_base::sync_with_stdio(false); cin.tie(NULL), cout.tie(NULL);
#define ll long long
using namespace std;
int main()
{
    Mohamed
    int t,sum=0;cin>>t;
    while(t--)
    {
        int x,c1=0,c2=0;cin>>x;
        bool bl=false;
        for (size_t i = 0; i < x; i++)
        {
            char c;cin>>c;
            if(c=='A'){bl=true; c1=0;}
            else if(bl){c1++;}
            c2=max(c1,c2)  ;
        }
        cout<<c2<<endl;
    }

}


A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840
OutputCopy7
InputCopy42 42
OutputCopy0
InputCopy48 72
OutputCopy-1
NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.

#include <bits/stdc++.h>

using namespace std;

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

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

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

#define ll long long

void file() {

    std::ios_base::sync_with_stdio(0);

    cin.tie(NULL);

    cout.tie(NULL);

}

int main() {

    file();

    int n, m;

    cin >> n >> m;

    int ans = INT_MAX;

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

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

            ll temp = n;

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

                temp *= 2;

            }

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

                temp *= 3;

            }

            if (temp == m) {

                ans = min(ans, i + j);

            }

        }

    }

    if (ans == INT_MAX)ans = -1;

    cout << ans;

}


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;

#define int long long

const int mod = 1e9 + 7;

//const int mod = 998244353;

#define PII pair<long long, long long>

#define x first

#define y second

#define pi 3.14159265359

int qpow(int a, int b)

{

    int res = 1;

    while (b != 0)

    {

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

        a = a * a % mod;

        b >>= 1;

    }

    return res;

}

int _qpow(int a, int b)

{

    int res = 1;

    while (b != 0)

    {

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

        a = a * a;

        b >>= 1;

    }

    return res;

}

int inv(int a)

{

    return qpow(a, mod - 2);

}

int exgcd(int ai, int bi, int& xi, int& yi)

{

    if (bi == 0)

    {

        xi = 1, yi = 0;

        return ai;

    }

    int d = exgcd(bi, ai % bi, yi, xi);

    yi -= ai / bi * xi;

    return d;

}

int gcd(int a, int b)

{

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

}

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

void solve()

{

    int n, x;

    cin >> n >> x;

    string s;

    cin >> s;

    int sum = 0;

    for (char c : s)

    {

        if (c == '0')sum++;

        else sum--;

    }

    int curr = 0;

    set<int> ss;

    int cnt = 0;

    if (curr == x && sum == 0)

    {

        cout << "-1\n";

        return;

    }

    if (sum != 0 && x % sum == 0 && x / sum >= 0)ss.insert(x / sum * n);

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

    {

        char c = s[i];

        if (c == '0')curr++;

        else curr--;

        if (curr == x && sum == 0)

        {

            cout << "-1\n";

            return;

        }

        if (sum != 0 && (x - curr) % sum == 0 && (x - curr) / sum >= 0)

        {

            ss.insert((x - curr) / sum * n + i + 1);

        }

    }

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

}

signed main()

{

    ios::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    int tt = 1;

    cin >> tt;

    while (tt--)solve();

    return 0;

}


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

#include<bits/stdc++.h>

typedef long long ll;

using namespace std;

//const ll mod = 1e9 + 7;

const ll mm = 2.5e5 + 10;

ll jc[mm];

int main() {

	std::ios::sync_with_stdio(false);

	std::cin.tie(0);

	std::cout.tie(0);

	int n;

	ll mod;

	cin>>n>>mod;

	jc[0]=1;

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

		jc[i]=jc[i-1]*i%mod;

	}ll ans=0;

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

		ans=(ans+jc[i]*jc[n-i+1]%mod*(n-i+1)%mod)%mod;

	}cout<<ans;

}


D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n)  — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n)  — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
OutputCopy3
InputCopy5 4 2
2 4
1 2
2 3
3 4
4 5
OutputCopy3
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33.   The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.

// Don't Quit  O_O

#include <bits/stdc++.h>

using namespace std;

#define lli long long int

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

template <class T>

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

#define INF LLONG_MAX

#define pb push_back

#define ff first

#define ss second

#define mod 1000000007

// Will become Master  ^_^

vector<vector<lli>> adj(200005);

lli vis[200005];

int main()

{

    ios_base::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    lli t = 1, n, i;

    // cin>>t;

    while (t--)

    {

        lli m, k;

        cin >> n >> m >> k;

        lli sp[k];

        set<lli> special;

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

        {

            cin >> sp[i];

            special.insert(sp[i]);

        }

        lli u[m], v[m];

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

        {

            cin >> u[i] >> v[i];

            adj[u[i]].pb(v[i]);

            adj[v[i]].pb(u[i]);

        }

        lli dist[n + 1];

        queue<pair<lli, lli>> q;

        q.push({1, 0});

        dist[1] = 0;

        vis[1] = 1;

        while ((int)q.size())

        {

            pair<lli, lli> p = q.front();

            q.pop();

            for (auto &x : adj[p.ff])

            {

                if (!vis[x])

                {

                    q.push({x, p.ss + 1});

                    dist[x] = p.ss + 1;

                    vis[x] = 1;

                }

            }

        }

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

            vis[i] = 0;

        q.push({n, 0});

        lli distn[n + 2];

        distn[n] = 0;

        vis[n] = 1;

        while ((int)q.size())

        {

            pair<lli, lli> p = q.front();

            q.pop();

            for (auto &x : adj[p.ff])

            {

                if (!vis[x])

                {

                    q.push({x, p.ss + 1});

                    distn[x] = p.ss + 1;

                    vis[x] = 1;

                }

            }

        }

        bool flag = false;

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

        {

            if (special.count(u[i]) && special.count(v[i]))

                flag = true;

        }

        if (flag)

        {

            cout << dist[n];

            continue;

        }

        else

        {

            lli mx = 0, ans = 0;

            vector<pair<lli, lli>> v;

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

                v.pb({dist[sp[i]], distn[sp[i]]});

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

            lli suff[k];

            suff[k - 1] = v[k - 1].ss;

            for (i = k - 2; i >= 0; i--)

                suff[i] = max(suff[i + 1], v[i + 1].ss);

            for (i = 0; i < k - 1; i++)

                ans = max(ans, v[i].ff + 1 + suff[i]);

            ans = min(ans, dist[n]);

            cout << ans;

        }

    }

}