A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8
))((())(
OutputCopy6
InputCopy3
(()
OutputCopy-1
NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds.

// Author: youknowwhoiam1

#include "bits/stdc++.h"

#include<ext/pb_ds/assoc_container.hpp>

#include<ext/pb_ds/tree_policy.hpp>

#define ll long long

#define NFS ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)

#define all(x) (x).begin(), (x).end() //Forward traversal

#define ff first

#define ss second

#define nl "\n"

#define lb lower_bound

#define ub upper_bound

#define pb push_back

using namespace std;

using namespace __gnu_pbds;

template<class T>

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

// find_by_order, order_of_key

#ifndef youknowwhoiam1

#define debug(x) cerr << #x<<" "; _print(x); cerr << endl;

#else

#define debug(x);

#endif

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

//-----------------------------------------------------------------------------------------------------------------------------//

const ll MOD = LLONG_MAX;

const ll inf = LLONG_MAX;

ll add(ll x, ll y) {x += y; while (x >= MOD) x -= MOD; while (x < 0) x += MOD; return x;}

ll sub(ll x, ll y) {return add(x, -y);}

ll mul(ll x, ll y) {return (x * 1ll * y) % MOD;}

ll pwr(ll x, ll y) {ll z = 1; while (y) {if (y & 1) z = mul(z, x); x = mul(x, x); y >>= 1;} return z;}

ll inv(ll i) {if (i == 1) return 1; return (MOD - ((MOD / i) * inv(MOD % i)) % MOD) % MOD;}

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

//-----------------------------------------------------------------------------------------------------------------------------//

/*

*/

void solve() {

	ll i, j;

	int cnt = 0, ans = 0;

	ll n;

	cin >> n;

	string s;

	cin >> s;

	if (count(all(s), '(') !=  count(all(s), ')')) {

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

	}

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

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

			if (cnt == 0) {

				j = i;

			}

			cnt--;

		} else {

			cnt++;

			if (cnt == 0) {

				ans += i - j + 1;

			}

		}

	}

	cout << ans << nl;

}

int main() {

	NFS;

#ifndef youknowwhoiam1

	freopen("error.txt", "w", stderr);

#endif

	using namespace std::chrono;

	high_resolution_clock::time_point t1 = high_resolution_clock::now();

	ll tc = 1;

	// cin >> tc;

	while (tc--) {

		solve();

	}

	high_resolution_clock::time_point t2 = high_resolution_clock::now();

	duration<double> time_span = duration_cast<duration<double>>(t2 - t1);

	std::cerr << setprecision(10) << fixed;

	std::cerr << "Time: " << time_span.count() << " seconds.";

	std::cerr << std::endl;

	return 0;

}


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

#include<bits/stdc++.h>

using namespace std;
int c[101],d[101][101],f[15][101];
int main()
{
auto st=clock();
int n,k;
cin>>n>>k;
for(int x=1;x<=n;x++)
for(int y=1;y<=n;y++)
cin>>d[x][y];
srand(time(0));
int ans=1e9;
while(clock()-st<=2800)
{
for(int x=1;x<=n;x++)
c[x]=rand()%2;
for(int x=0;x<=k;x++)
for(int y=1;y<=n;y++)
f[x][y]=1e9;
f[0][1]=0;
for(int x=0;x<k;x++)
for(int y=1;y<=n;y++)
for(int z=1;z<=n;z++)
if(c[y]!=c[z])f[x+1][z]=min(f[x+1][z],f[x][y]+d[y][z]);
ans=min(ans,f[k][1]);
}
cout<<ans<<endl;
}


B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3
tab
one
bat
OutputCopy6
tabbat
InputCopy4 2
oo
ox
xo
xx
OutputCopy6
oxxxxo
InputCopy3 5
hello
codef
orces
OutputCopy0

InputCopy9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
OutputCopy20
ababwxyzijjizyxwbaba
NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string.

#include<bits/stdc++.h>

using namespace std;

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

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

#define MOD ll(1e9+7)

#define int long long

typedef int ll;

typedef vector<ll> vi;

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

const int N=2e5+10;

void solve() {

    ll n, m;

    cin >> n >> m;

    vector<string> a(n);

    map<string, ll> mp;

    string fir = "", sec = "", mid = "";

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

        cin >> a[i];

        mp[a[i]]++;

    }

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

        string rno = a[i];

        string no = a[i];

        reverse(all(rno));

        if (rno != no) {

            if (mp[no] && mp[rno]) {

                fir += no;

                sec = rno + sec;

                mp[no]--;

                mp[rno]--;

            }

        } else {

            if (mp[no] > 1) {

                if (mp[no] && mp[rno]) {

                    fir += no;

                    sec = rno + sec;

                    mp[no]--;

                    mp[rno]--;

                }

            } else {

                if (mid.size() < no.size())mid = no;

            }

        }

    }

    string y = fir + mid + sec;

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

    cout << y << endl;

}

signed main() {

    ios_base::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    ll t = 1;

    //cin >> t;

    while (t--) {

        solve();

    }

}


B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example:  The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened;  The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened.

/***

            Bismillahir Rahmanir Rahim

            Read in the name of Allah, who created you!!!

            Author : Shah Newaj Rabbi Shishir

            Department of CSE, City University, Bangladesh.

***/

#include <bits/stdc++.h>

using namespace std;

#define             jeno_joyer_khuda_thake      int main (void)

#define             kaj_shesh                   return 0

#define             sf                          scanf

#define             pf                          printf

#define             ssf                         sscanf

#define             spf                         sprintf

#define             fsf                         fscanf

#define             fpf                         fprintf

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

#define             scase                       sf ("%d",&tc)

#define             whilecase                   while (tc--)

#define             sn                          sf ("%d",&n)

#define             eof                         while (cin >> n)

#define             pcase                       pf ("Case %d: ",pos)

#define             llu                         unsigned long long

#define             lld                         long long

#define             U                           unsigned int

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

#define             for1(i,n)                   for (i=1; i<=n; i++)

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

#define             rof0(i,n)                   for (i=n-1; i>=0; i--)

#define             rof1(i,n)                   for (i=n; i>=1; i--)

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

#define             c(str)                      cin >> str

#define             g(str)                     	getline (cin,str)

#define             vi                          vector <int>

#define             vlld                        vector <lld>

#define             si                          set <int>

#define             slld                        set <lld>

#define             ss                          set <string>

#define             vs                          vector <string>

#define             pii                         pair <int,int>

#define             mii                         map <int,int>

#define             msi                         map <string,int>

#define             pb                          push_back

#define             in                          insert

#define             B                           begin()

#define             E                           end()

#define             rB                          rbegin()

#define             rE                          rend()

#define             F                           first

#define             S                           second

#define             iterate(it,x)               for (it=x.B; it!=x.E; it++)

#define             riterate(rit,x)             for (it=x.rB; it!=x.rE; it++)

#define             sort(x)            	        sort (x.B,x.E)

#define             sortR(x,a,b)            	sort (x.B+a,x.B+b+1)

#define             rev(x)                  	reverse (x.B,x.E)

#define             revR(x,a,b)             	reverse (x.B+a,x.B+b+1)

#define             cl(x)                       x.clear()

#define             end1                        "\n"

const int MOD = 1000000007;

const int MAX = 300005;

const double PI = acos(-1.0);

int SetBit (int n, int X) { return n | (1 << X); }

int ClearBit (int n, int X) { return n & ~(1 << X); }

int ToggleBit (int n, int X) { return n ^ (1 << X); }

bool CheckBit (int n, int X) { return (bool)(n & (1 << X)); }

int arr[MAX];

jeno_joyer_khuda_thake

{

    /*

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

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

    */

    int tc,n,i,pos,k;

    sf ("%d",&tc);

    while (tc--)

    {

        sf ("%d",&n);

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

            sf ("%d",&arr[i]);

        pos = n;

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

        {

            if (arr[i] < i)

            {

                pos = i-1;

                break;

            }

        }

        k = 1;

        if (pos != n)

        {

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

            {

                if (arr[i] >= arr[i-1])

                {

                    arr[i] = arr[i-1]-1;

                    if (arr[i] < 0)

                    {

                        k = 0;

                        break;

                    }

                }

            }

        }

        if (k || pos == n)

            pf ("Yes");

        else

            pf ("No");

        pf ("\n");

    }

    kaj_shesh;

}


A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.

#include<iostream>

#include<algorithm>

#include<set>

using namespace std;

int main()

{

  int n,i,it=0;

  long long int sum=0,ans=0;

  cin>>n;

  pair<int,int>a[n];

  for(i=0;i<n;i++)cin>>a[i].first;

  for(i=0;i<n;i++)cin>>a[i].second;

  sort(a,a+n);

  multiset<int>st;

  for(i=1;;i++)

  {

      while(a[it].first==i&&it!=n)st.insert(a[it].second),sum+=a[it].second,it++;

      if(st.empty())

      {

          if(it!=n)i=a[it].first-1;

          else break;

          continue;

      }

      auto x=st.end();

      x--;

      sum-=*x;

      ans+=sum;

      st.erase(x);

  }

  cout<<ans;

}


E. Cow and Treatstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful year of milk production; Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of nn units of grass, each with a sweetness sisi. Farmer John has mm cows, each with a favorite sweetness fifi and a hunger value hihi. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner:   The cows from the left and right side will take turns feeding in an order decided by Farmer John.  When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats hihi units.  The moment a cow eats hihi units, it will fall asleep there, preventing further cows from passing it from both directions.  If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset. Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them. Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo 109+7109+7)? The order in which FJ sends the cows does not matter as long as no cows get upset. InputThe first line contains two integers nn and mm (1≤n≤50001≤n≤5000, 1≤m≤50001≤m≤5000)  — the number of units of grass and the number of cows. The second line contains nn integers s1,s2,…,sns1,s2,…,sn (1≤si≤n1≤si≤n)  — the sweetness values of the grass.The ii-th of the following mm lines contains two integers fifi and hihi (1≤fi,hi≤n1≤fi,hi≤n)  — the favorite sweetness and hunger value of the ii-th cow. No two cows have the same hunger and favorite sweetness simultaneously.OutputOutput two integers  — the maximum number of sleeping cows that can result and the number of ways modulo 109+7109+7. ExamplesInputCopy5 2
1 1 1 1 1
1 2
1 3
OutputCopy2 2
InputCopy5 2
1 1 1 1 1
1 2
1 4
OutputCopy1 4
InputCopy3 2
2 3 2
3 1
2 1
OutputCopy2 4
InputCopy5 1
1 1 1 1 1
2 5
OutputCopy0 1
NoteIn the first example; FJ can line up the cows as follows to achieve 22 sleeping cows:   Cow 11 is lined up on the left side and cow 22 is lined up on the right side.  Cow 22 is lined up on the left side and cow 11 is lined up on the right side. In the second example, FJ can line up the cows as follows to achieve 11 sleeping cow:   Cow 11 is lined up on the left side.  Cow 22 is lined up on the left side.  Cow 11 is lined up on the right side.  Cow 22 is lined up on the right side. In the third example, FJ can line up the cows as follows to achieve 22 sleeping cows:   Cow 11 and 22 are lined up on the left side.  Cow 11 and 22 are lined up on the right side.  Cow 11 is lined up on the left side and cow 22 is lined up on the right side.  Cow 11 is lined up on the right side and cow 22 is lined up on the left side. In the fourth example, FJ cannot end up with any sleeping cows, so there will be no cows lined up on either side.

// 失ったものなんて数えなくていいよ
// ボクは理由無しに生まれたノンタイトル

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

// Pragmas
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")

// Namespaces
#define It		using
#define has		namespace
#define to		std;
#define be		using
#define this	namespace
#define way		__gnu_pbds

It has to be this way;

// Data types
using i8	= __int128;
using ll	= long long;
using si	= short int;
using ld	= long double;

// Pairs
using pi8	= pair<i8, i8>;
using pll	= pair<ll, ll>;
using pii	= pair<int, int>;
using psi	= pair<si, si>;
using pld	= pair<ld, ld>;
#define fi	first
#define se	second

// PBDS
template<typename T>
using ordered_set	= tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

// Quick macro functions
#define sqr(x)			((x)*(x))
#define pow2(x)			(1ll << (x))
#define debug(x)		cout << #x << " = " << (x) << '\n'
#define debugV(x, a)	cout << #x << "[" << (a) << "] = " << (x[a]) << '\n'

#define MultipleTestcases	int _tc; cin >> _tc; for (int _cur_tc = 1; _cur_tc <= _tc; _cur_tc++)

// Check min and max
template<typename T> void chmin(T &a, T b) {a = min(a, b);}
template<typename T> void chmax(T &a, T b) {a = max(a, b);}

// Modular arithmetic
template<typename T> void maddto(T &a, T b, T mod) {a += b; a %= mod;}
template<typename T> void msubto(T &a, T b, T mod) {a -= b; while (a < 0) a += mod; a %= mod;}
template<typename T> void mmulto(T &a, T b, T mod) {a *= b; a %= mod;}

template<typename T> T madd(T a, T b, T mod) {a += b; a %= mod; return a;}
template<typename T> T msub(T a, T b, T mod) {a -= b; while (a < 0) a += mod; return a;}
template<typename T> T mmul(T a, T b, T mod) {a *= b; a %= mod; return a;}

template<typename T> T modexp(T x, T y, T mod) {
	if (!x) return 0; if (!y) return 1;
	T t = modexp<T>(x, y >> 1, mod);
	return mmul<T>(t, mmul<T>(t, (y & 1) ? x : 1, mod), mod);
}

// Constants
const ll ModA	= 998244353;
const ll ModC	= 1e9 + 7;
const ll INF	= 1e18;
const ll iINF	= 1e9;
const ld EPS	= 1e-9;
const ld iEPS	= 1e-6;

const int maxN	= 5005;

ll n, m, s[maxN];
ll fav[maxN], hunger[maxN];

ll cow[maxN][maxN]; // prefix per favorite grass

ll cnt[2][maxN]; // count of left and right grass
ll sleepingCows[maxN], ways[maxN]; // per separator

ll getCow(ll type, ll l, ll r) {
	if (l > r) return 0;
	return cow[type][r] - cow[type][l-1];
}

int main() {
	ios_base::sync_with_stdio(false); cin.tie(NULL);

	cin >> n >> m;
	for (ll i = 1; i <= n; i++) {
		cin >> s[i];
		cnt[1][s[i]]++;
	}
	for (ll i = 1; i <= m; i++) {
		cin >> fav[i] >> hunger[i];
		cow[fav[i]][hunger[i]]++;
	}

	// compute prefix cow
	for (ll i = 1; i <= n; i++) {
		for (ll j = 1; j <= n; j++) {
			cow[i][j] += cow[i][j-1];
			// cout << cow[i][j] << ' ';
		}
		// cout << '\n';
	}

	// brute force all possible separators
	// [1..sep-1] left, [sep..n] right
	for (ll sep = 1; sep <= n; sep++) {
		// for (ll grass = 1; grass <= n; grass++) {cout << cnt[0][grass] << ' ';} cout << '\n';
		// for (ll grass = 1; grass <= n; grass++) {cout << cnt[1][grass] << ' ';} cout << '\n';
		// cout << '\n';

		// to not double count, only count if there is going to be a sleeping cow from the right here
		ll curGrass = s[sep];
		if (getCow(curGrass, cnt[1][curGrass], cnt[1][curGrass]) != 1) {
			sleepingCows[sep] = -1;
			cnt[0][s[sep]]++;
			cnt[1][s[sep]]--;
			continue;
		}

		ll leftSepGrass = getCow(curGrass, 1, cnt[0][curGrass]);
		if (cnt[0][curGrass] >= cnt[1][curGrass]) leftSepGrass--;
		if (leftSepGrass > 0) {
			ways[sep] = leftSepGrass;
			sleepingCows[sep] = 2;
		} else {
			ways[sep] = 1;
			sleepingCows[sep] = 1;
		}

		// debug(sep);
		// debugV(ways, sep);
		// debugV(sleepingCows, sep);

		for (ll grass = 1; grass <= n; grass++) {
			if (grass == curGrass) continue;

			ll L = getCow(grass, 1, cnt[0][grass]);
			ll R = getCow(grass, 1, cnt[1][grass]);

			ll twoCowPairs = L * R - min(L, R);
			ll oneCow = L + R;

			if (twoCowPairs > 0) {
				sleepingCows[sep] += 2;
				mmulto(ways[sep], twoCowPairs, ModC);
			} else if (oneCow > 0) {
				sleepingCows[sep] += 1;
				mmulto(ways[sep], oneCow, ModC);
			}
		}

		cnt[0][s[sep]]++;
		cnt[1][s[sep]]--;
	}

	// extra case: all cows come from the left
	ways[n+1] = 1;
	for (ll grass = 1; grass <= n; grass++) {
		ll L = getCow(grass, 1, cnt[0][grass]);

		if (L > 0) {
			sleepingCows[n+1]++;
			mmulto(ways[n+1], L, ModC);
		}
	}

	ll maxSleep = -1, maxWays = 0;
	for (ll i = 1; i <= n+1; i++) {
		if (sleepingCows[i] > maxSleep) {
			maxSleep = sleepingCows[i];
			maxWays = 0;
		}
		if (sleepingCows[i] == maxSleep) {
			maddto(maxWays, ways[i], ModC);
		}
	}
	cout << maxSleep << ' ' << maxWays << '\n';
}


#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#define debug(x) cerr << #x << " is " << x << endl;

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

#define endl '\n'

#define pb push_back

#define F first

#define S second

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

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

#define ll long long int

using namespace __gnu_pbds;

using namespace std;

typedef tree<pair<long long, long long>,null_type,less<pair<long long, long long>>,rb_tree_tag,

tree_order_statistics_node_update> indexed_set;

indexed_set st;

const int mod = 1e9 + 7;

int n, diff, cnt, j;

bool flag = 0;

string s;

void doWork(){

    cin >> n >> s;

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

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

            diff -= 1;

        }

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

            diff += 1;

        }

        if(diff == 0){

            if(flag){

                /// Segment Reorder

                cnt += (i + 1) - j;

            }

            j = i + 1;

            flag = 0;

        }

        if(diff < 0){

            flag = 1;

        }

    }

    if(diff != 0){

        cout << -1 << endl;

    }

    else{

        cout << cnt << endl;

    }

}

int main(){

    FastIO

    int tc = 1;

    while(tc--){

        doWork();

    }

    return 0;

}


A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4
4 0 11 6
OutputCopy11 6 4 0InputCopy1
13
OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.

// Created by KHALED MOSHARRAF PARVEZ

#include <bits/stdc++.h>

#define whatis1(x) cout<<#x<<"="<<x<<'\n'

#define whatis2(x,y) cout<<#x<<"="<<x<<","<<#y<<"="<<y<<'\n'

#define whatis3(x,y,z) cout<<#x<<"="<<x<<","<<#y<<"="<<y<<","<<#z<<"="<<z<<'\n'

#define whatisArray(arr,n) cout<<#arr<<", Size: "<<n<<'\n';for(int m=0;m<n;m++)  cout<<arr[m]<<" ";cout<<'\n';

#define whatArray2D(arr,m,n) cout<<#arr<<", Size: "<<m<<","<<n<<'\n';for(int mm=0;mm<m;mm++){for(int nn=0;nn<n;nn++)cout<<arr[mm][nn]<<" ";cout<<'\n';}

#define caseprint(caseno,ans) cout<<"Case "<<caseno<<": "<<ans<<'\n'

#define endl '\n'

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

#define mod 1000000007

#define MX 200005

using namespace std;

using ll = long long;

void solve(int caseno){

    int n;

    cin>>n;

    ll xr= 0;;

    vector<ll> v(n);

    vector<int> pos[35];

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

        cin>>v[i];

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

            if((v[i]>>j)&1LL){

                pos[j].push_back(i);

            }

        }

    }

    //sort(v.begin(),v.end(),greater<ll>());

    bool taken[n+5]={0};

    for(int i=32; i>=0; i--) {

        if(pos[i].size()==1 && !taken[pos[i][0]]){

            cout<<v[pos[i][0]]<<' ';

            taken[pos[i][0]]=true;

        }

    }

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

        if(!taken[i])cout<<v[i]<<' ';

    }

    cout<<'\n';

    return;

}

int main()

{

    ios::sync_with_stdio(0);

    int cases,caseno=0;

    cases=1;

    while(cases--){

        solve(++caseno);

    }

    return 0;

}


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

#include <bits/stdc++.h>
#define ll long long
#define all(x) x.begin(),x.end()
#define answer(x) cout << (x ? "YES\n" : "NO\n")
#define test ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int T; cin >> T; while(T--)
#define go ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define F first
#define S second
using namespace std;

const int N = 55, M = 20010;
ll n, m, k, dp[N][M], a[N][M], vals[N][M], pre[N][M], seg[4 * M], lazy[4  * M];

void chk (int p , int s , int e)
{
    if(lazy[p])
    {
        seg[p] += lazy[p];
        if(s!=e) lazy[2*p] += lazy[p], lazy[2*p+1] += lazy[p];
        lazy[p] = 0;
    }
}
void update(int p , int s , int e, int a , int b , int v)
{
    chk(p,s,e);

    if(s >= a && e <= b)
    {
        seg[p] += v;

        if(s!=e)
        {
            lazy[2*p] += v;
            lazy[2*p+1] += v;
        }
        return ;
    }

    if(s>b || e<a)
        return ;

    update(2*p,s,(s+e)/2,a,b,v);
    update(2*p+1,(s+e)/2+1,e,a,b,v);

    seg[p] = max(seg[2*p] , seg[2*p+1]);
}
int gt(int p , int s , int e , int a , int  b)
{
    chk(p,s,e);

    if(s >= a && e <= b)
        return seg[p];

    if(s>b || e<a)
        return 0;

    return max(gt(2*p,s,(s+e)/2,a,b) , gt(2*p+1,(s+e)/2+1,e,a,b));
}

int main()
{
	cin >> n >> m >> k;
	for(int i=1 ;i <=n ;i++)
		for(int j=1 ; j<=m ; j++)
			cin >> a[i][j],
			pre[i][j] = a[i][j] + pre[i][j-1];

	for(int i=1 ; i<=n ;i++)
		for(int j=1 ; j + k - 1 <=m ; j++)
			vals[i][j] = pre[i][j+k-1] - pre[i][j-1] + pre[i+1][j+k-1] - pre[i+1][j-1];

	for(int j=1 ; j + k - 1<=m ; j++)
		dp[1][j] = vals[1][j];

	for(int i=2 ; i<=n ; i++)
	{
		memset(seg, 0, sizeof seg);
		memset(lazy, 0, sizeof lazy);

		for(int j=1 ; j + k - 1 <= m ; j++)
			update(1, 1, m, j, j, dp[i-1][j]);

		for(int j=1 ; j<=k ; j++)
			update(1, 1, m, 1, j, -a[i][j]);

		for(int j=1 ; j + k - 1 <= m ; j++)
		{
			dp[i][j] = gt(1, 1, m, 1, m) + vals[i][j];

			update(1, 1, m, j+1, j + k, -a[i][j + k]);
			update(1, 1, m, max(1ll, j - k + 1) , j, a[i][j]);
		}
	}

	ll ans = 0;
	for(int i=1 ; i<=m ; i++)
		ans = max(ans, dp[n][i]);
	cout << ans;
}


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

#include<iostream>
#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=3e5+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);}
void hack() {printf("\n----------------------------------\n");}

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;
int f[N];

void solve() {
    n=read(),m=read();

    f[0]=1;
    for(int i=1;i<=n;i++) f[i]=((ll)f[i-1]*i)%m;

    ll ans=0;
    for(int i=1;i<=n;i++) {
        int a=(ll)(n-i+1)*(n-i+1)%m;
        int b=(ll)a*f[i]%m;
        int c=(ll)b*f[n-i]%m;
        ans=(ans+c)%m;
    }

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

int main() {
    // init();
    // stin();

    // scanf("%d",&T);
    T=1;
    while(T--) solve();

    return 0;
}


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

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

using pii = pair<int, int>;

#define out(x) cout << #x << '=' << x << endl;

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

struct fenwick {

	map<int, pair<int, pii>> mp;

	int n;

	fenwick() : n(100000 * 50 + 1) {

	}

	void update(int x, int v, pii rng) {

		while (x <= n) {

			pair<int, pii> &pir = mp[x];

			if (pir.first < v) {

				pir.first = v;

				pir.second = rng;

			}

			x += lowbit(x);

		}

	}

	pair<int, pii> query(int x) {

		pair<int, pii> ans = {0, {0, 0}};

		while (x > 0) {

			if (mp.count(x)) {

				pair<int, pii> cnt = mp[x];

				if (cnt.first > ans.first) {

					ans = cnt;

				}

			}

			x -= lowbit(x);

		}

		return ans;

	}

};

int main(void) {

    ios::sync_with_stdio(false);

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

    int t = 1;

    //cin >> t;

    while (t--) {

    	int n;

    	cin >> n;

    	vector<int> a(n + 1);

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

    		cin >> a[i];

		}

		map<int, fenwick> mp;

		vector<vector<pii>> back(n + 1, vector<pii>(n + 1));

		int maxv = 0;

		int maxi = 0;

		int maxj = 0;

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

			ll sum = 0;

			for (int j = i; j > 0; j--) {

				sum += a[j];

				pair<int, pii> ans = mp[sum].query(j - 1);

				back[i][j] = ans.second;

				ans.first++;

				mp[sum].update(i, ans.first, {j, i});

				if (ans.first > maxv) {

					maxv = ans.first;

					maxi = i;

					maxj = j;

				}

			}

		}

		vector<pii> ans;

		while (maxi > 0) {

			ans.push_back({maxj, maxi});

			pii bck = back[maxi][maxj];

			maxi = bck.second;

			maxj = bck.first;

		}

		cout << maxv << endl;

		for (pii rng : ans) {

			cout << rng.first << ' ' << rng.second << endl;

		}

	}

}


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

#include <bits/stdc++.h>

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

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

using namespace std;

// using namespace chrono;

// using namespace __gnu_pbds;

typedef vector<long long> vi;

typedef pair<int, int> pii;

#define endl "\n"

#define sd(val) scanf("%d", &val)

#define ss(val) scanf("%s", &val)

#define sl(val) scanf("%lld", &val)

#define debug(val) printf("check%d\n", val)

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

#define sai(a, n) sort(a, a + n);

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

#define svi(x) sort(x.begin(), x.end());

#define svd(a) sort(a.begin(), a.end(), greater<int>());

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

#define PB push_back

#define MP make_pair

#define FF firstṇ

#define SS second

#define ull unsigned long long

#define int long long

// #define MOD 1000000007

#define MOD 998244353

#define clr(val) memset(val, 0, sizeof(val))

#define what_is(x) cerr << #x << " is " << x << endl;

#define OJ                            \

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

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

#define FIO                           \

    ios_base::sync_with_stdio(false); \

    cin.tie(NULL);                    \

    cout.tie(NULL);

// template <class T>

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

// Function to find a^b % MOD. Time Complexity : O(log b).

int highPowerMod(int a, int b)

{

    // a %= MOD;

    int res = 1;

    while (b > 0)

    {

        if (b & 1)

            res = (res * a);

        a = (a * a);

        b >>= 1;

    }

    return res;

}

// Function to find the lcm of a and b. Time Complexity : O(log(min(a, b))).

int lcm(int a, int b)

{

    return a / __gcd(a, b) * b;

}

void bfs(int start, vector<vector<int>> &g2, vector<pair<int, bool>> &dp, int m)

{

    queue<int> q;

    q.push(start);

    int cnt = 0;

    bool flag = false;

    while (!q.empty())

    {

        cnt = q.front();

        if (cnt < m)

            flag = true;

        q.pop();

        dp[cnt].second = flag;

        for (const auto &nbr : g2[cnt])

        {

            if (dp[nbr].first == -1)

            {

                dp[nbr].first = dp[cnt].first + 1;

                q.push(nbr);

            }

        }

    }

}

int compliment(int x, int n)

{

    return (x ^ (n - 1));

}

void dfs(int start, vector<vi> &graph, vector<bool> &vis)

{

    vis[start] = true;

    for (const auto &nbr : graph[start])

    {

        if (!vis[nbr])

        {

            dfs(nbr, graph, vis);

        }

    }

}

pair<int, int> intersection(pair<int, int> a, pair<int, int> b)

{

    if (a.first > b.second || b.first > a.second)

        return {-1, -1};

    return {max(a.first, b.first), min(a.second, b.second)};

}

int cntDigits(int n)

{

    string t = to_string(n);

    return (int)t.size();

}

int bs_sqrt(int x)

{

    int left = 0, right = 2000000123;

    while (right > left)

    {

        int mid = left + (right - left) / 2;

        if (mid * mid > x)

            right = mid;

        else

            left = mid + 1;

    }

    return left - 1;

}

void primeFactors(int n, vi &arr)

{

    int t = 1e5 + 7;

    fi(i, 1, t)

    {

        if (i * i > n)

            break;

        if (n % i == 0)

        {

            arr.push_back(i);

            arr.push_back(n / i);

        }

    }

}

void SieveOfEratosthenes(int n, vi &primess)

{

    bool prime[n + 1];

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

    for (int p = 2; p * p <= n; p++)

    {

        if (prime[p] == true)

        {

            for (int i = p * p; i <= n; i += p)

                prime[i] = false;

        }

    }

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

        if (prime[p])

            primess.push_back(p);

}

// And of a Range of numbers from a to b.

int andOperator(int a, int b)

{

    int shiftcount = 0;

    while (a != b and a > 0)

    {

        shiftcount++;

        a = a >> 1;

        b = b >> 1;

    }

    return int64_t(a << shiftcount);

}

void solve(int cake)

{

    int n;

    cin >> n;

    // int k;

    // cin >> k;

    // vi arr(n);

    // fi(i, 0, n) cin >> arr[i];

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

    vector<vector<int>> temp1, temp2;

    int ans = 0;

    fi(i, 0, n)

    {

        int x, y;

        cin >> x;

        int mii = INT_MAX, maa = 0;

        int flag = 0;

        fi(j, 0, x)

        {

            cin >> y;

            v[i].push_back(y);

            if (mii < y)

                flag = 1;

            mii = min(mii, y);

            maa = max(maa, y);

        }

        if (!flag)

            temp1.push_back({maa, mii, flag});

        else

        {

            temp2.push_back({maa, mii, flag});

        }

    }

    svi(temp1);

    vector<int> tt;

    fi(i, 0, (int)temp1.size()) tt.push_back(temp1[i][0]);

    svi(tt);

    fi(i, 0, (int)temp1.size())

    {

        ans += tt.end() - upper_bound(tt.begin(), tt.end(), temp1[i][1]);

    }

    int t = temp1.size();

    fi(i, 0, (int)temp2.size())

    {

        ans += n;

        ans += t;

    }

    cout << ans << endl;

}

int32_t main()

{

    // OJ;

    FIO;

    int t = 1;

    int cake = 1;

    // cin >> t;

    // vi primes;

    // int N = 31622;

    // SieveOfEratosthenes(N, primes);

    while (t--)

    {

        solve(cake);

        cake++;

    }

    return 0;

}


B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
OutputCopy0
1
5
NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.

#include <bits/stdc++.h>

using namespace std;

int main()

{

 int t;

 long long int n,x,m,ni,a,b;

 cin>>t;

 while(t--){

vector<int> v;

  cin>>n;

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

  cin>>x;

  v.push_back(x);

  }

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

  cout << v[n*2 / 2] - v[( n*2 / 2) - 1] << endl;}

    return 0;

}


#include<bits/stdc++.h>

#include <fstream>

#include <cstdlib>

#include<conio.h>

#include <windows.h>

#include <stdlib.h>

#include <time.h>

#define pb push_back

#define ll long long

#define dbl double

#define srt(massiv) sort(massiv.begin(),massiv.end())

#define rvrs(massiv) reverse(massiv.begin(),massiv.end())

#define srtr(massiv) sort(massiv.rbegin(),massiv.rend())

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

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

#define Yes cout<<"Yes"<<endl

#define No cout<<"No"<<endl

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

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

#define en "\n"

#define Minecraft for(cin>>MC;MC--;)

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

using namespace std;

/// cout << fixed << X ;

///ifstream cin("input.txt");

///ofstream cout("output.txt")  ;

ll cnt,qnt,cns,qns,n,m,k,i,j,T,x,y,z,a,b,MC;

ll arr1 [100005];

ll arr2 [100005];

main()

{

    ReallyWorld

    map<string,ll> mp;

    cin >> n >> m;

    vector<string>s(n),L, R;

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

    {

        cin >> s[i];

        mp[s[i]]++;

    }

    string M;

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

    {

        string t = s[i];

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

        if (t == s[i])

            M = t;

        else if (mp.find(t) != mp.end())

        {

            L.push_back(s[i]);

            R.push_back(t);

            mp.erase(s[i]);

            mp.erase(t);

        }

    }

    cout << L.size() * m * 2 + M.size() << en;

    for (string x : L)

        cout << x;

    cout << M;

    rvrs(R);

    for (string x : R)

        cout << x;

    cout << en;

}

/**

███╗   ███╗███████╗██████╗ ██╗███╗  ██╗███████╗███████╗███████╗███╗   ███╗

████╗ ████║██╔════╝██╔══██╗██║████╗ ██║██╔════╝██╔════╝██╔════╝████╗ ████║

██╔████╔██║█████╗  ██████╦╝██║██╔██╗██║█████╗  █████╗  █████╗  ██╔████╔██║

██║╚██╔╝██║██╔══╝  ██╔══██╗██║██║╚████║██╔══╝  ██╔══╝  ██╔══╝  ██║╚██╔╝██║

██║ ╚═╝ ██║███████╗██████╦╝██║██║ ╚███║███████╗███████╗███████╗██║ ╚═╝ ██║

╚═╝     ╚═╝╚══════╝╚═════╝ ╚═╝╚═╝  ╚══╝╚══════╝╚══════╝╚══════╝╚═╝     ╚═╝

        ▄▄▄    ▄▄██▄▄

       ████▄  ███████

       █████▄████████

       ▀█████████████

     ▄▄    ▀▀▀██████▄██████▄▄

  ▄████  ███    ▀████████████

▄██████  ▀▀▀ ▄█  ▀███████████

▀▀       █▄▄███   █████████▀

  ▀█████ ▀███▀▀   ██████▀

       ██▄        ███████▄

      █████       ████████▄

    ▄██████       ▀███████▀

   ████████        ▀████▀

  █████████

  ████████▀

  ▀██████▀

    ▀▀▀

**/


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

#include <bits/stdc++.h>

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

#define xs(a) cout<<setiosflags(ios::fixed)<<setprecision(a);

#define lbit(a) (__builtin_ffsll(a))

#define ubit(a) (64-__builtin_clzll(a))

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

#define ROF(i, a, b) for (ll (i) = (a); (i) >= (b); (i)--)

#define mem(a,b) memset(a,b,sizeof(a));

using namespace std;

#define ull unsigned long long

#define ll long long

#define endl '\n'

typedef pair<ll,ll> pll;

const int N=4e2+5;

const int mod=1e9+7;

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

ll f[N][N];//s的前i个匹配t1的前j个最多能匹配t2的前几个

string s;

bool check(string t1,string t2){

	mem(f,-1);

	f[0][0]=0;

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

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

			if(f[i][j]==-1)continue;

			ll tmp=f[i][j];

			if(s[i]==t1[j]&&j<t1.size())f[i+1][j+1]=max(f[i+1][j+1],tmp);

			if(s[i]==t2[tmp]&&tmp<t2.size())f[i+1][j]=max(f[i+1][j],tmp+1);

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

		}

	}

	return f[s.size()][t1.size()]==t2.size();

}

void solve(){

	string t;cin>>s>>t;

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

		string x=t.substr(0,i);

		string y=t.substr(i);

		//cout<<x<<' '<<y<<endl;

		if(check(x,y)){cout<<"YES"<<endl;return ;}

	}

	cout<<"NO"<<endl;

}

signed main(){IOS

	ll T;T=1;

	cin>>T;

	while(T--){

		solve();

	}

	return 0;

}


B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold:  Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments.  The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees.  The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES

#include <bits/stdc++.h>

#define int long long

using namespace std;

struct point{

    int x,y;

};

struct line{

    point p1,p2;

}a[4];

int len_line_pow(line a){//求线段长度的平方

    return (a.p1.x-a.p2.x)*(a.p1.x-a.p2.x)+(a.p1.y-a.p2.y)*(a.p1.y-a.p2.y);

}

bool check_same_point(point p1,point p2){//判断两点是否相同

    return p1.x==p2.x&&p1.y==p2.y;

}

bool check_one_line(line a,point p){//判断三点共线

    return (a.p1.y-p.y)*(a.p2.x-p.x)==(a.p2.y-p.y)*(a.p1.x-p.x);

}

bool check_5_point(line a,point p){//判断p是不是在a的1/5点和4/5线之间

    a.p1.x*=5,a.p2.x*=5,a.p1.y*=5,a.p2.y*=5;

    p.x*=5,p.y*=5;

    point p1={a.p1.x+(a.p2.x-a.p1.x)/5,a.p1.y+(a.p2.y-a.p1.y)/5};

    point p4={a.p1.x+(a.p2.x-a.p1.x)/5*4,a.p1.y+(a.p2.y-a.p1.y)/5*4};

    double d=sqrt((double)len_line_pow({p1,p4}));

    double d1=sqrt((double)len_line_pow({p,p1}));

    double d4=sqrt((double)len_line_pow({p,p4}));

    return fabs(d-d1-d4)<1e-2;

}

bool check(line l,line r,line m){

    //条件1：两线有唯一共同端点

    int x=check_same_point(l.p1,r.p1);

    if(check_same_point(l.p1,r.p2)){

        x++;

        swap(r.p1,r.p2);

    }

    if(check_same_point(l.p2,r.p1)){

        x++;

        swap(l.p1,l.p2);

    }

    if(check_same_point(l.p2,r.p2)){

        x++;

        swap(l.p1,l.p2);

        swap(r.p1,r.p2);

    }

    if(x!=1){

        return false;

    }

    //条件2：夹角不是钝角,可以是直角

    if(len_line_pow(l)+len_line_pow(r)<len_line_pow({l.p2,r.p2})){

        return false;

    }

    //条件3：第3线两端点与前两线共线

    if(check_one_line(l,m.p1)&&check_one_line(r,m.p2)){

        ;

    }else if(check_one_line(l,m.p2)&&check_one_line(r,m.p1)){

        swap(m.p1,m.p2);

    }else{

        return false;

    }

    //条件4：第3线两端点必须在两线分别的1/5点和4/5线之间

    if(check_5_point(l,m.p1)&&check_5_point(r,m.p2)){

        return true;

    }else{

        return false;

    }

}

signed main(){

    ios::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    int T;

    cin>>T;

    while(T--){

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

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

        }

        bool flag=false;

        for(int i=1;i<=3&&!flag;i++){

            for(int j=1;j<=3&&!flag;j++){

                if(i==j){

                    continue;

                }

                for(int k=1;k<=3&&!flag;k++){

                    if(k==j||k==i){

                        continue;

                    }

                    flag|=check(a[i],a[j],a[k]);

                }

            }

        }

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

    }

	return 0;

}


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.

//Author: Ankush Bhagat (https://github.com/ankushbhagat124)

//RFIPITIDS?

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

using namespace std;

const int inf = (int)(numeric_limits<int>::max());

const long long N = (long long)(3e5 + 1);

const long long mod = (long long)(1e9 + 7);

template <class type1>

using ordered_multiset = tree <type1, null_type, less <type1>, rb_tree_tag, tree_order_statistics_node_update>;

clock_t startTime;

double getCurrentTime() {

    return (double)(clock() - startTime) / CLOCKS_PER_SEC;

}

void init()

{

#ifndef ONLINE_JUDGE

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

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

#endif

}

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

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

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

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

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

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

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

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

template<typename T, typename V, typename M>

void __print(const tuple<T, V, M> &x) {cerr << '{'; __print(get<0>(x)); cerr << ','; __print(get<1>(x)); cerr << ','; __print(get<2>(x)); cerr << '}';}

template<typename T, typename V>

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

template<typename T>

void __print(priority_queue<T> &x) {int f = 0; cerr << '{'; while (!x.empty()) { cerr << (f++ ? "," : ""), __print(x.top()); x.pop();} cerr << "}";}

template<typename T>

void __print(stack<T> &x) {int f = 0; cerr << '{'; while (!x.empty()) { cerr << (f++ ? "," : ""), __print(x.top()); x.pop();} cerr << "}";}

template<typename T>

void __print(queue<T> &x) {int f = 0; cerr << '{'; while (!x.empty()) { cerr << (f++ ? "," : ""), __print(x.front()); x.pop();} cerr << "}";}

template<typename T>

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

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

template <typename T, typename... V>

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

#ifndef ONLINE_JUDGE

#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)

#else

#define debug(x...)

#endif

/**********************************************************************************************************************/

signed main()

{

    init();

    startTime = clock();

    ios_base::sync_with_stdio(0);

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

    /*

    10101

    -1 0 -1 0 -1

    */

    int t = 1;

    cin >> t;

    while (t-- && getCurrentTime() <= 5)

    {

        int n, x;

        cin >> n >> x;

        string s;

        cin >> s;

        vector <long long> v;

        long long curr = 0;

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

        {

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

                curr--;

            else

                curr++;

            v.push_back(curr);

        }

        bool flag = false;

        if (curr == 0)

        {

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

            {

                if (v[i] == x)

                    flag = true;

            }

            if (flag)

                cout << "-1";

            else

                cout << 0;

        }

        else

        {

            //x+m*curr = X

            long long ans = 0;

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

            {

                if (v[i] == x)

                    ans++;

                else

                {

                    long long val = (x - v[i]);

                    if (val * curr > 0 && (abs(val) % abs(curr) == 0))

                        ans++;

                }

            }

            if (x == 0)

                ans++;

            cout << ans;

        }

        cout << endl;

    }

    double time = getCurrentTime();

    debug(time);

}


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

#include <bits/stdc++.h>

#define nl  << "\n"

#define spc << " " <<

#define pt cout <<

using namespace std;

typedef long long ll;

//#define int long long

#define pii pair<int, int>

int mod = 1e9 + 7;

int MAX = 1e9 + 1;

int MIN = -1e9;

double eps = 1e-7;

bool check(vector<int> arr,int n){

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

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

        if(arr[i] != (i+1))

            return false;

    }

    return true;

}

int main(){

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

    int n,minELem = 0; cin >> n;

    vector<int> diff(n-1);

    for(int i=0;i<n-1;i++) cin >> diff[i];

    vector<int> perm(n,0);

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

        perm[i] = perm[i-1] + diff[i-1];

        minELem = min(minELem,perm[i]);

    }

    int x = 1-minELem;

    for(int i=0;i<n;i++) perm[i] += x;

    if(!check(perm, n)) pt -1 nl;

    else{

        for(int i=0;i<n;i++) pt perm[i] << " ";

    }

}


F. Blocks and Sensorstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPolycarp plays a well-known computer game (we won't mention its name). Every object in this game consists of three-dimensional blocks — axis-aligned cubes of size 1×1×11×1×1. These blocks are unaffected by gravity, so they can float in the air without support. The blocks are placed in cells of size 1×1×11×1×1; each cell either contains exactly one block or is empty. Each cell is represented by its coordinates (x,y,z)(x,y,z) (the cell with these coordinates is a cube with opposite corners in (x,y,z)(x,y,z) and (x+1,y+1,z+1)(x+1,y+1,z+1)) and its contents ax,y,zax,y,z; if the cell is empty, then ax,y,z=0ax,y,z=0, otherwise ax,y,zax,y,z is equal to the type of the block placed in it (the types are integers from 11 to 2⋅1052⋅105).Polycarp has built a large structure consisting of blocks. This structure can be enclosed in an axis-aligned rectangular parallelepiped of size n×m×kn×m×k, containing all cells (x,y,z)(x,y,z) such that x∈[1,n]x∈[1,n], y∈[1,m]y∈[1,m], and z∈[1,k]z∈[1,k]. After that, Polycarp has installed 2nm+2nk+2mk2nm+2nk+2mk sensors around this parallelepiped. A sensor is a special block that sends a ray in some direction and shows the type of the first block that was hit by this ray (except for other sensors). The sensors installed by Polycarp are adjacent to the borders of the parallelepiped, and the rays sent by them are parallel to one of the coordinate axes and directed inside the parallelepiped. More formally, the sensors can be divided into 66 types:  there are mkmk sensors of the first type; each such sensor is installed in (0,y,z)(0,y,z), where y∈[1,m]y∈[1,m] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OxOx axis and has the same direction;  there are mkmk sensors of the second type; each such sensor is installed in (n+1,y,z)(n+1,y,z), where y∈[1,m]y∈[1,m] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OxOx axis and has the opposite direction;  there are nknk sensors of the third type; each such sensor is installed in (x,0,z)(x,0,z), where x∈[1,n]x∈[1,n] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OyOy axis and has the same direction;  there are nknk sensors of the fourth type; each such sensor is installed in (x,m+1,z)(x,m+1,z), where x∈[1,n]x∈[1,n] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OyOy axis and has the opposite direction;  there are nmnm sensors of the fifth type; each such sensor is installed in (x,y,0)(x,y,0), where x∈[1,n]x∈[1,n] and y∈[1,m]y∈[1,m], and it sends a ray that is parallel to the OzOz axis and has the same direction;  finally, there are nmnm sensors of the sixth type; each such sensor is installed in (x,y,k+1)(x,y,k+1), where x∈[1,n]x∈[1,n] and y∈[1,m]y∈[1,m], and it sends a ray that is parallel to the OzOz axis and has the opposite direction. Polycarp has invited his friend Monocarp to play with him. Of course, as soon as Monocarp saw a large parallelepiped bounded by sensor blocks, he began to wonder what was inside of it. Polycarp didn't want to tell Monocarp the exact shape of the figure, so he provided Monocarp with the data from all sensors and told him to try guessing the contents of the parallelepiped by himself.After some hours of thinking, Monocarp has no clue about what's inside the sensor-bounded space. But he does not want to give up, so he decided to ask for help. Can you write a program that will analyze the sensor data and construct any figure that is consistent with it?InputThe first line contains three integers nn, mm and kk (1≤n,m,k≤2⋅1051≤n,m,k≤2⋅105, nmk≤2⋅105nmk≤2⋅105) — the dimensions of the parallelepiped.Then the sensor data follows. For each sensor, its data is either 00, if the ray emitted from it reaches the opposite sensor (there are no blocks in between), or an integer from 11 to 2⋅1052⋅105 denoting the type of the first block hit by the ray. The data is divided into 66 sections (one for each type of sensors), each consecutive pair of sections is separated by a blank line, and the first section is separated by a blank line from the first line of the input.The first section consists of mm lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (0,i,j)(0,i,j).The second section consists of mm lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (n+1,i,j)(n+1,i,j).The third section consists of nn lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,0,j)(i,0,j).The fourth section consists of nn lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,m+1,j)(i,m+1,j).The fifth section consists of nn lines containing mm integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,j,0)(i,j,0).Finally, the sixth section consists of nn lines containing mm integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,j,k+1)(i,j,k+1).OutputIf the information from the input is inconsistent, print one integer −1−1.Otherwise, print the figure inside the parallelepiped as follows. The output should consist of nmknmk integers: a1,1,1a1,1,1, a1,1,2a1,1,2, ..., a1,1,ka1,1,k, a1,2,1a1,2,1, ..., a1,2,ka1,2,k, ..., a1,m,ka1,m,k, a2,1,1a2,1,1, ..., an,m,kan,m,k, where ai,j,kai,j,k is the type of the block in (i,j,k)(i,j,k), or 00 if there is no block there. If there are multiple figures consistent with sensor data, describe any of them.For your convenience, the sample output is formatted as follows: there are nn separate sections for blocks having x=1x=1, x=2x=2, ..., x=nx=n; each section consists of mm lines containing kk integers each. Note that this type of output is acceptable, but you may print the integers with any other formatting instead (even all integers on the same line), only their order matters.ExamplesInputCopy4 3 2

1 4
3 2
6 5

1 4
3 2
6 7

1 4
1 4
0 0
0 7

6 5
6 5
0 0
0 7

1 3 6
1 3 6
0 0 0
0 0 7

4 3 5
4 2 5
0 0 0
0 0 7
OutputCopy1 4
3 0
6 5

1 4
3 2
6 5

0 0
0 0
0 0

0 0
0 0
0 7
InputCopy1 1 1

0

0

0

0

0

0
OutputCopy0
InputCopy1 1 1

0

0

1337

0

0

0
OutputCopy-1
InputCopy1 1 1

1337

1337

1337

1337

1337

1337
OutputCopy1337

#include <bits/stdc++.h>

#pragma GCC optimize("Ofast")

using namespace std;

namespace IO {

const int SIZ = 1 << 14;

inline char getc() {

    static char bf[SIZ], *begin = bf, *end = bf;

    if (begin == end) begin = bf, end = bf + fread(bf, 1, SIZ, stdin);

    if (begin == end) return EOF;

    return *begin++;

}

char wbf[SIZ], *wend = wbf, *weoo = wbf + SIZ;

inline void putc(char c) {

    *wend = c, ++wend;

    if (wend == weoo) fwrite(wbf, 1, SIZ, stdout), wend = wbf;

}

inline void do_flush() { fwrite(wbf, 1, wend - wbf, stdout); }

template <typename T>

inline void uread(T &ans) {

    static char tmp;

    tmp = getc(), ans = 0;

    while (!isdigit(tmp)) tmp = getc();

    while (isdigit(tmp)) ans = (ans << 1) + (ans << 3) + (tmp ^ 48), tmp = getc();

}

template <typename T>

inline void read(T &ans) {

    static char tmp2;

    static bool flag;

    tmp2 = getc(), ans = 0, flag = 0;

    while (!isdigit(tmp2)) {

        if (tmp2 == '-') flag = 1;

        tmp2 = getc();

    }

    while (isdigit(tmp2)) ans = (ans << 1) + (ans << 3) + (tmp2 ^ 48), tmp2 = getc();

    if (flag) ans = -ans;

}

template <typename T>

inline void uwrite(T x) {

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

    putc(x % 10 + '0');

}

template <typename T>

inline void write(T x) {

    if (x < 0)

        putc('-'), uwrite(-x);

    else

        uwrite(x);

}

inline void putstr(const char str[]) {

    for (int i = 0; str[i]; i++) putc(str[i]);

}

inline void readalpha(char &x) {

    for (x = getc(); !isalpha(x); x = getc())

        ;

}

};  // namespace IO

using IO::read, IO::write, IO::do_flush, IO::putc, IO::uread, IO::uwrite;

template <typename T>

struct Table2D {

    vector<vector<T>> vec;

    int __n, __m;

    inline void init(int n, int m) {

        vec.resize(n), __n = n, __m = m;

        for (int i = 0; i < n; i++) vec[i].resize(m);

    }

    inline void read(int n, int m) {

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

            for (int j = 0; j < m; j++) ::read(vec[i][j]);

    }

    inline bool inrange(int x, int y) { return x >= 1 && x <= __n && y >= 1 && y <= __m; }

    inline T &at(int x, int y) { return vec[x - 1][y - 1]; }

};

template <typename T>

inline void fill(Table2D<T> &x, int k) {

    for (int i = 0; i < x.__n; i++)

        for (int j = 0; j < x.__m; j++)

            for (int l = 1; l <= k; l++) x.vec[i][j].insert(l);

}

int n, m, k;

// x:UD y:FB z:LR

Table2D<set<int>> vecD, vecB, vecL;

Table2D<set<int, greater<int>>> vecU, vecF, vecR;

Table2D<int> colU, colD, colF, colB, colL, colR;

Table2D<vector<bool>> used;

inline void make(int &a, int b) {

    if (a == -1)

        a = b;

    else if (a != b)

        a = 0;

}

inline int getcol(int x, int y, int z) {

    int col = -1;

    if (vecD.at(y, z).size() && *vecD.at(y, z).begin() == x) make(col, colD.at(y, z));  // cout << "readcolD" << colD.at(y, z) << endl ;

    if (vecU.at(y, z).size() && *vecU.at(y, z).begin() == x) make(col, colU.at(y, z));  // cout << "readcolU" << colU.at(y, z) << endl ;

    if (vecB.at(x, z).size() && *vecB.at(x, z).begin() == y) make(col, colB.at(x, z));  // cout << "readcolB" << colB.at(x, z) << endl ;

    if (vecF.at(x, z).size() && *vecF.at(x, z).begin() == y) make(col, colF.at(x, z));  // cout << "readcolF" << colF.at(x, z) << endl ;

    if (vecL.at(x, y).size() && *vecL.at(x, y).begin() == z) make(col, colL.at(x, y));  // cout << "readcolL" << colL.at(x, y) << endl ;

    if (vecR.at(x, y).size() && *vecR.at(x, y).begin() == z) make(col, colR.at(x, y));  // cout << "readcolR" << colR.at(x, y) << endl ;

    return col;

}

inline void check(int x, int y, int z) {

    if (x < 1 || x > n || y < 1 || y > m || z < 1 || z > k || !used.at(x, y)[z]) return;

    int p = getcol(x, y, z);

    if (!p) {

        // cout << "del:" << x << ' ' << y << ' ' << z << endl;

        used.at(x, y)[z] = 0;

        vecD.at(y, z).erase(x);

        vecU.at(y, z).erase(x);

        vecB.at(x, z).erase(y);

        vecF.at(x, z).erase(y);

        vecL.at(x, y).erase(z);

        vecR.at(x, y).erase(z);

        if (vecD.at(y, z).size() && *vecD.at(y, z).rbegin() > x) check(*vecD.at(y, z).upper_bound(x), y, z);

        if (vecU.at(y, z).size() && *vecU.at(y, z).rbegin() < x) check(*vecU.at(y, z).upper_bound(x), y, z);

        if (vecB.at(x, z).size() && *vecB.at(x, z).rbegin() > y) check(x, *vecB.at(x, z).upper_bound(y), z);

        if (vecF.at(x, z).size() && *vecF.at(x, z).rbegin() < y) check(x, *vecF.at(x, z).upper_bound(y), z);

        if (vecL.at(x, y).size() && *vecL.at(x, y).rbegin() > z) check(x, y, *vecL.at(x, y).upper_bound(z));

        if (vecR.at(x, y).size() && *vecR.at(x, y).rbegin() < z) check(x, y, *vecR.at(x, y).upper_bound(z));

    }

}

template <typename T>

inline bool cc(Table2D<T> &a, Table2D<int> &b) {

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

        for (int j = 1; j <= a.__m; j++)

            if (b.at(i, j) && !a.at(i, j).size()) return 0;

    return 1;

}

int main() {

    cin >> n >> m >> k;

    vecU.init(m, k), vecD.init(m, k), vecF.init(n, k), vecB.init(n, k), vecL.init(n, m), vecR.init(n, m);

    fill(vecU, n), fill(vecD, n), fill(vecF, m), fill(vecB, m), fill(vecL, k), fill(vecR, k);

    colU.init(m, k), colD.init(m, k), colF.init(n, k), colB.init(n, k), colL.init(n, m), colR.init(n, m);

    colD.read(m, k), colU.read(m, k), colB.read(n, k), colF.read(n, k), colL.read(n, m), colR.read(n, m);

    used.init(n, m);

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

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

            used.at(i, j).resize(k + 1);

            for (int l = 1; l <= k; l++) used.at(i, j)[l] = 1;

        }

    // cout << *vecR.at(1, 1).begin() << ' '<< *vecL<< endl;

    // cout << getcol(1, 1, 2) << endl;

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

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

            for (int l = 1; l <= k; l++) check(i, j, l);

    if (!cc(vecU, colU)) return puts("-1"), 0;

    if (!cc(vecD, colD)) return puts("-1"), 0;

    if (!cc(vecL, colL)) return puts("-1"), 0;

    if (!cc(vecR, colR)) return puts("-1"), 0;

    if (!cc(vecB, colB)) return puts("-1"), 0;

    if (!cc(vecF, colF)) return puts("-1"), 0;

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

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

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

                int tmp;

                if (!used.at(i, j)[l])

                    printf("%d ", 0);

                else if ((tmp = getcol(i, j, l)) == -1)

                    printf("%d ", 0);

                else

                    printf("%d ", tmp);

            }

            puts("");

        }

        puts("");

    }

    return 0;

}


D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

using pii = pair<int, int>;

#define out(x) cout << #x << '=' << x << endl;

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

int main(void) {

    ios::sync_with_stdio(false);

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

    int t = 1;

    //cin >> t;

    while (t--) {

    	int n;

    	cin >> n;

    	string l, r;

    	cin >> l >> r;

    	vector<vector<int>> lc(256), rc(256);

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

    		lc[l[i]].push_back(i + 1);

    		rc[r[i]].push_back(i + 1);

		}

		vector<pii> ans;

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

			for (int j : rc[i]) {

				if (i == '?') continue;

				if (!lc[i].empty()) {

					ans.push_back({lc[i].back(), j});

					lc[i].pop_back();

				} else if (!lc['?'].empty()) {

					ans.push_back({lc['?'].back(), j});

					lc['?'].pop_back();

				}

			}

		}

		int i = 0;

		for (int j : rc['?']) {

			while (i < 256 && lc[i].empty()) i++;

			if (i < 256) {

				ans.push_back({lc[i].back(), j});

				lc[i].pop_back();

			}

		}

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

		for (pii p : ans) {

			cout << p.first << ' ' << p.second << endl;

		}

	}

}


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

// LUOGU_RID: 102218004
#include<bits/stdc++.h>
using namespace std;
const int N=1005;
const long long INF=2e18;
int n,m,tot,len[N][N];
long long k,f[N][N];
char s[N];
struct Sub{
	int l,r,t;
	Sub(int _l=0,int _r=0){ l=_l, r=_r, t=r-l+1; }
}rcd[N*N];
inline bool cmp(Sub x,Sub y){
	int k=len[x.l][y.l];
	if(k<min(x.t,y.t)) return s[x.l+k]<s[y.l+k];
	return x.t<y.t;
}
inline bool Check(Sub sub){
	//cout<<"Check: ";
	//for(register int i=sub.l;i<=sub.r;++i) cout<<s[i];
	//cout<<'\n';
	int L=sub.l,R=sub.r;
	memset(f,0,sizeof(f)), f[0][0]=1, f[1][0]=-1;
	for(register int i=0;i<n;++i)
		for(register int j=0;j<=m;++j){
			if(!f[i][j]) continue;
			int x=min(sub.t,len[i+1][L]);
			if(x==sub.t){
				f[i+x][j+1]=min(INF,f[i+x][j+1]+f[i][j]);
				//for(register int k=i+x;k<=n;++k)
				//	f[k][j+1]=min(INF,f[k][j+1]+f[i][j]);
			}
			else if(s[i+x+1]>s[L+x]){
				f[i+x+1][j+1]=min(INF,f[i+x+1][j+1]+f[i][j]);
				//for(register int k=i+x+1;k<=n;++k)
				//	f[k][j+1]=min(INF,f[k][j+1]+f[i][j]);
			}
			f[i+1][j]=min(INF,f[i+1][j]+f[i][j]);
		}
	//cout<<"res: "<<f[n][m]<<'\n';
	return f[n][m]>=k;
}
inline Sub Find(){
	int l=0,r=tot+1,mid;
	while(l<r-1)
		mid=(l+r)>>1, Check(rcd[mid])?l=mid:r=mid;
	return rcd[l];
}
int main(){
	cin>>n>>m>>k;
	for(register int i=1;i<=n;++i) cin>>s[i];
	for(register int i=n;i>=1;--i)
		for(register int j=n;j>=1;--j)
			if(s[i]==s[j]) len[i][j]=len[i+1][j+1]+1;
	for(register int i=1;i<=n;++i)
		for(register int j=i;j<=n;++j)
			rcd[++tot]=Sub(i,j);
	sort(rcd+1,rcd+1+tot,cmp);
	/*
	for(register int i=1;i<=tot;++i){
		for(register int j=rcd[i].l;j<=rcd[i].r;++j) cout<<s[j];
		cout<<'\n';
	}
	*/
	Sub sub=Find();
	for(register int i=sub.l;i<=sub.r;++i) printf("%c",s[i]);
	putchar('\n');
	return 0;
}


B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104)  — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
OutputCopy1 11
5 35
3 6
0 42
0 0
1 2
3 4
NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6].  |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0;  |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3;  |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3;  |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3;  |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33.

// ░█████╗░░█████╗░██████╗░███████╗███╗░░░███╗██╗███╗░░██╗███████╗███╗░░░███╗

// ██╔══██╗██╔══██╗██╔══██╗██╔════╝████╗░████║██║████╗░██║██╔════╝████╗░████║

// ██║░░╚═╝██║░░██║██║░░██║█████╗░░██╔████╔██║██║██╔██╗██║█████╗░░██╔████╔██║

// ██║░░██╗██║░░██║██║░░██║██╔══╝░░██║╚██╔╝██║██║██║╚████║██╔══╝░░██║╚██╔╝██║

// ╚█████╔╝╚█████╔╝██████╔╝███████╗██║░╚═╝░██║██║██║░╚███║███████╗██║░╚═╝░██║

// ░╚════╝░░╚════╝░╚═════╝░╚══════╝╚═╝░░░░░╚═╝╚═╝╚═╝░░╚══╝╚══════╝╚═╝░░░░░╚═╝

#include <iostream>

#include <algorithm>

#include <vector>

#include <set>

#include <map>

#include <queue>

using namespace std;

#define ios ios_base::sync_with_stdio(false) ; cin.tie(NULL) ; cout.tie(NULL) ;

#define endl "\n"

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

#define int long long

#define pb push_back

typedef vector<int>vi;

typedef queue<int>qu;

typedef vector<vector<int> >vvi;

int mod1 = 998244353 ;

int mod2 = 1000000007 ;

// ***************************************************************

//SOME HELPFUL FUNCTIONS

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

int expo(int a, int b, int mod) {int res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;}

// ***************************************************************

//DEBUGGING

#ifndef ONLINE_JUDGE

#define debug(x) cerr <<#x<<" ";_print(x);cerr<<endl;

#else

#define debug(x)

#endif

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

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

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

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

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

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

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

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

// ***************************************************************

void solve(){

  int n;

  cin>>n;

  int mn=1e9;

  int mx=-1e9;

  vector<int>nums(n);

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

    cin>>nums[i];

  }

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

        if(i > 0 && nums[i] == -1 && nums[i - 1] != -1)

            mn = min(mn , nums[i - 1]) , mx = max(mx , nums[i - 1]);

        if(i < n - 1 && nums[i] == - 1 && nums[i + 1] != -1)

            mn = min(mn , nums[i + 1]) , mx = max(mx , nums[i + 1]);

    }

    int res = (mx + mn) / 2;

    int ans = 0;

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

        if(nums[i] == -1)

            nums[i] = res;

        if(i)

            ans = max(ans,abs(nums[i] - nums[i - 1]));

    }

    cout<<ans<<" "<<res<<endl;

}

//KEEP IN MIND

/*-->stay calm

-->try to think of approaches,implement whatever seems best

-->try to optimise the code

-->keep code neat*/

signed main(){

#ifndef ONLINE_JUDGE

  freopen("error.txt","w",stderr);

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

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

#endif

  ios

    int t;

    cin>>t;

    while(t--){

        solve();

    }

  return 0;

}