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;

}


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>

#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;

}


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

#include <bits/stdc++.h>

using namespace std;

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

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

template <typename T>

inline void read(T &f)

{

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

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

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

    f*=fu;

}

template <typename T>

void print(T x,char c=0)

{

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

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

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

    if(c) putchar(c);

}

inline void reads(string &f)

{

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

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

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

    f=str;

}

void prints(string s)

{

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

    putchar(s[i]);

}

typedef long long ll;

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

int n,a[maxn];

bitset<26> bs[maxn];

int val[maxn];

bool check(int pos)

{

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

    {

        bs[i]=a[i];

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

        bs[i][j]=0;

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

    }

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

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

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

    int cnt=0;

    //[l1,r1]

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

    {

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

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

        cnt+=pos2-pos1+1;

    }

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

    //[l2,r2]

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

    {

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

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

        cnt+=pos2-pos1+1;

    }

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

    return cnt&1;

}

void solve()

{

    read(n);

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

    read(a[i]);

    int ans=0;

    /* check(0);

    check(1);

    return ; */

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

    {

        if(check(i))

        ans+=(1<<i);

    }

    print(ans);

}

int main()

{

    #ifdef AC

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

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

    #endif

    clock_t program_start_clock=clock();

    int _=1;

    if(multicase) read(_);

    while(_--) solve();

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

    return 0;

}


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

#include <bits/stdc++.h>

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


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

#define _USE_MATH_DEFINES

#pragma GCC optimize("Ofast")

#include <bits/stdc++.h>

using namespace std;

const  int  n1=1000000007;

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

#define inf 5e18

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

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

#define mii map<int,int>

#define mll map<ll,ll>

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

#define umii unordered_map<int,int>

#define vi vector<int>

#define vll vector<ll>

#define vvll vector<vector<ll>>

#define vvi vector<vector<int>>

#define ll long long

#define pii pair<int,int>

#define pll pair<ll,ll>

#define vpii vector<pii>

#define vpll vector<pll>

#define pb push_back

#define f first

#define s second

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

#define pi = 3.1415926535897932384626

#define INF LLONG_MAX

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

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

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

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

#define umill unordered_map <int,ll>

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

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

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

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

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

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

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

#include <ext/pb_ds/assoc_container.hpp>

using namespace __gnu_pbds;

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

            rb_tree_tag, tree_order_statistics_node_update> ordered_set;

struct compare {

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

            const std::string& second) const

    {

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

    }

};

vll factorial(ll n)

{

    vll fct(n+1);

    fct[0]=1;

    fct[1]=1;

    inl(i,2,n+1)

    {

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

    }

    return fct;

}

vll factorial(ll n,ll m)

{

    vll fct(n+1);

    fct[0]=1;

    fct[1]=1;

    inl(i,2,n+1)

    {

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

    }

    return fct;

}

 long long power(long long x,ll y)

{

    long long res = 1;

     ll p=n1;

    x = x % p;

    while (y > 0)

    {

        if (y & 1)

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

        y = y >> 1;

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

    }

    return res;

}

long long modInverse(long long n)

{

    return power(n, n1 - 2);

}

vector<bool> SieveOfEratosthenes(ll n){

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

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

prime[i] = false; return prime;}

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

{

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

}

//   char a[400][400];

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

 {

      ll cnt=0;

      if(r1>0&&c1>0)

      {

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

      }

      else if(r1>0)

      {

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

      }

      else if(c1>0)

      {

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

      }

      else

      {

          cnt=pre[r2][c2];

      }

      return cnt;

 }

 //ll dp[500][500];

ll ans1;

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

{

    vis[node]=1;

    for(auto &u:adj[node])

    {

        if(vis[u]==0)

        {

            dfs1(adj,u,vis,lev);

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

        }

    }

    if(lev[node]==-1)

    {

        lev[node]=1;

    }

}

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

{

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

    v.pb(node);

    ll l=0;

    ll r=v.size()-1;

    ll req=-1;

    while(l<=r)

    {

        ll mid=(l+r)/2;

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

        {

            req=mid;

            r=mid-1;

        }

        else l=mid+1;

    }

    ans[p]++;

    if(req-1>=0)

    {

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

    }

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

    for(auto &u:adj[node])

    {

        if(u!=p)

        {

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

            ans[node]+=ans[u];

        }

    }

    v.pop_back();

}

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

{

    if(l==r)

    {

        seg[idx]=a[l];

        return;

    }

    ll mid=(l+r)/2;

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

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

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

     return ;

}

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

{

    if(l==r)

    {

        seg[idx]=a[l];

        return;

    }

    ll mid=(l+r)/2;

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

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

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

     return ;

}

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

{

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

    return seg[idx];

    if(low>r or high<l)

        return -1*inf;

    ll mid=(low+high)/2;

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

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

    return max(x,y);

}

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

{

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

    return seg[idx];

    if(low>r or high<l)

        return 0;

    ll mid=(low+high)/2;

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

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

    return __gcd(x,y);

}

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

{

    if(l==r)

    {

        ll x=seg[idx];

        if(l==0)

        {

            st[x]--;

            if(st[x]<=0)

                st.erase(x);

            seg[idx]-=val;

            st[seg[idx]]++;

        }

        else

        {

            seg[idx]-=val;

        }

        return;

    }

    ll mid=(l+r)/2;

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

    {

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

    }

    else

    {

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

    }

    ll x=seg[idx];

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

    if(l==0)

    {

        st[x]--;

        if(st[x]<=0)

            st.erase(x);

        st[seg[idx]]++;

    }

    return;

}

 vll kmp(string str)

 {

     vll v(str.size());

     v[0]=0;

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

     {

         ll j=v[i-1];

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

         {

             j=v[j-1];

         }

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

         {

             j++;

         }

         v[i]=j;

     }

     return v;

 }

void fun(vector<int>&A)

{

    int n=A.size();

   int num1=1e9;

   int num2=1e9;

   int c1=0;

   int c2=0;

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

   {

       if(A[i]==num1)

       {

           c1++;

       }

       else if(A[i]==num2)

       {

           c2++;

       }

       else if(c1==0)

       {

           num1=A[i];

           c1++;

       }

       else if(c2==0)

       {

           num2=A[i];

           c2++;

       }

       else

       {

           c1--;

           c2--;

       }

   }

   c1=0;

   c2=0;

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

   {

       if(A[i]==num1)

       {

           c1++;

       }

       if(A[i]==num2)

       {

           c2++;

       }

   }

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

   if(c1>(n/3))

   {

       cout<<num1;

   }

  else if(c2>(n/3))

   {

       cout<<num2;

   }

   else

   {

       cout<<-1;

   }

   cout<<endl;

}

/*ll spf[10000001];

void sieve()

{

    spf[1]=1;

    in(i,2,1e7+1)

    {

        spf[i]=i;

    }

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

    {

        spf[i]=2;

    }

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

    {

        if(spf[i]==i)

        {

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

            {

                if(spf[j]==j)

                {

                    spf[j]=i;

                }

            }

        }

    }

}

*/

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

{

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

        swap(n1,n2);

    de(i,0,21)

    {

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

        {

            n1=dp[n1][i];

        }

    }

    if(n1==n2)

        return n1;

    de(i,0,21)

    {

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

        {

            n1=dp[n1][i];

            n2=dp[n2][i];

        }

    }

    return dp[n1][0];

}

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

{

    while(idx<=n)

    {

        bt[idx]+=val;

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

    }

}

ll sum(vll &bt,ll idx)

{

    ll ans=0;

    while(idx>0)

    {

        ans+=bt[idx];

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

    }

    return ans;

}

int main()

{

ios_base::sync_with_stdio(false);

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

int tt=1;

//cin>>tt;

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

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

//cout<<endl;

//mlv fc;

while(tt--)

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

{

    ll n;

    cin>>n;

    vpll v(n);

    in(i,0,n)

    {

        cin>>v[i].f;

    }

    in(i,0,n)

    {

        cin>>v[i].s;

    }

    sort(all(v));

    ll ans=0;

    ordered_set st;

    in(i,0,n)

    {

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

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

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

    }

    st.clear();

     de(i,0,n-1)

    {

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

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

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

    }

    cout<<ans<<endl;

}

return 0;

}


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

#include <bits/stdc++.h>

using namespace std;

#define int long long

int tt;

void solve();

void IO()

{

	ios_base::sync_with_stdio(false);

	cin.tie(NULL);

	cout.tie(NULL);

}

void testcase(int t)

{

	cin >> t;

	while (t--) solve();

}

typedef long long ll;

typedef long double lld;

#define ff first

#define ss second

#define pi pair<int, int>

#define vi vector<int>

#define vb vector<bool>

#define vs vector<string>

#define vc vector<char>

#define pv pair<vi, vi>

#define vpi vector<pi>

#define vvi vector<vi>

#define vvb vector<vb>

#define vvc vector<vc>

#define vvvi vector<vvi>

#define pb push_back

#define mp make_pair

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

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

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

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

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

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

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

void read() {}

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

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

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

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

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

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

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

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

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

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

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

#ifndef ONLINE_JUDGE

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

#else

#define dbg(x)

#endif

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

void solve()

{

	cin >> n;

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

    rep(i,1,n+1)

    {

        cin >> a[i];

        vis[a[i]] = 1;

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

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

    }

    rep(i,1,n+1)

    {

        if (vis[i] == 0)

        {

            if (i&1) odd++;

            else even++;

        }

    }

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

    // base case

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

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

    {

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

        {

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

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

            // evens_to_fill = zeros[i] - of

            int etf = zero[i] - of;

            if (a[i] == 0)

            {

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

                if (etf > 0 and etf <= even)

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

            }

            else

            {

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

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

                else

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

            }

        }

    }

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

}

signed main()

{

	IO();

	// testcase(tt);

	solve();

}


                 /**Bismillahir Rahmanir Rahim.**/

#include<bits/stdc++.h>

using namespace std;

typedef unsigned long long int   ull;

typedef long long int            ll;

typedef long double              ld;

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

#define pi          acos(-1)

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

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

#define eps         0.000000001

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

#define mod         1000000007

#define MAX         100005

#define en          '\n'

#define ff          first

#define ss          second

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

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

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

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

//ordered_set variable;

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

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

//ordered_multiset variable;

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

// ordered_map varibale

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

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

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

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

// p^e % m

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

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

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

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

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

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

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

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

const double EPS = 1e-12;

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

ll onbit(ll N, ll pos) {

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

}

ll offbit(ll N, ll pos) {

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

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

}

ll flipbit(ll N, ll pos) {

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

}

bool checkbit(ll N, ll pos) {

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

}

int main()

{

    int t1=1;

    Faster

    // test

    // {

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

    cin>>n;

    vector<ll> mn,mmx;

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

    {

        ll l;

        cin>>l;

        ll a[l+1];

        ll mi=INT_MAX,mx=0;

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

        {

            cin>>a[j];

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

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

        }

        ll flag=0;

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

        {

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

            {

                flag=1;

                break;

            }

        }

        if(flag==0)

        {

            mn.push_back(mi);

            mmx.push_back(mx);

        }

        else

            cnt++;

    }

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

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

    ll ans=0;

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

    {

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

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

    }

    //cout<<ans<<en;

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

    // {

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

    //     if(l1>i)

    //         ans+=(l1-i);

    // }

    //

    //cout<<ans<<en;

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

    cout<<ans<<en;

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

    // }

}


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

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