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

#include<iostream>
#include<vector>
#include<set>
#include<queue>
#include<map>
#include<algorithm>
#include<numeric>
#include<cmath>
#include<cstring>
#include<bitset>
#include<iomanip>
#include<random>
#include<fstream>
#include<complex>
#include<time.h>
#include<stack>
using namespace std;
#define endl "\n"
#define ll long long
#define bl bool
#define ch char
#define vec vector
#define vll vector<ll>
#define sll set<ll>
#define pll pair<ll,ll>
#define mkp make_pair
#define mll map<ll,ll>
#define puf push_front
#define pub push_back
#define pof pop_front()
#define pob pop_back()
#define em empty()
#define fi first
#define se second
#define fr front()
#define ba back()
#define be begin()
#define rbe rbegin()
#define en end()
#define ren rend()
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define fo(i,x,y) for(ll i=x;i<=y;++i)
#define fa(i,v) for(auto &i:v)
#define re return
#define rz return 0;
#define sz size()
#define len length()
#define con continue;
#define br break;
#define ma(a,x) a=max(a,x)
#define mi(a,x) a=min(a,x)
#define so(v) sort(all(v))
#define rso(v) sort(rall(v))
#define rev(v) reverse(all(v))
#define i(x) for(ll i=0;i<x;++i)
#define j(x) for(ll j=0;j<x;++j)
#define k(x) for(ll k=0;k<x;++k)
#define n(x) for(ll yz=0;yz<x;++yz)
#define xx(k) while(k--)

#define wh(x) while(x)
#define st string
#define M 8611686018427387904
#define ze(x) __builtin_ctzll(x)
#define z(x) ll x=0
#define in insert
#define un(v) v.erase(unique(all(v)),v.en);
#define er(i,n) erase(i,n);
#define co(x,a) count(all(x),a)
#define lo(v,a) lower_bound(v.begin(),v.end(),a)
#define up(v,a) upper_bound(v.begin(),v.end(),a)
#define dou double
#define elif else if
#define ge(x,...) x __VA_ARGS__; ci(__VA_ARGS__);
#define fix(n,ans) cout<<fixed<<std::setprecision(n)<<ans<<endl;

void cc(){ cout<<endl; };
void ff(){ cout<<endl; };
void cl(){ cout<<endl; };
template<class T,class... A> void ff(T a,A... b){ cout<<a; (cout<<...<<(cout<<' ',b)); cout<<endl; };
template<class T,class... A> void cc(T a,A... b){ cout<<a; (cout<<...<<(cout<<' ',b)); cout<<' '; };
template<class T,class... A> void cl(T a,A... b){ cout<<a; (cout<<...<<(cout<<'\n',b)); cout<<endl; };
template<class T,class... A> void cn(T a,A... b){ cout<<a; (cout<<...<<(cout<<"",b));  };
template<class... A> void ci(A&... a){ (cin>>...>>a); };
template<class T>void ou(T v){fa(i,v)cout<<i<<" ";cout<<endl;}
template<class T>void oun(T v){fa(i,v)cout<<i;cout<<endl;}
template<class T>void ouu(T v){fa(i,v){fa(j,i)cout<<j<<" ";cout<<endl;}}
template<class T> void oul(T v){fa(i,v)cout<<i<<endl;}
template<class T>void in(T &v){fa(i,v)cin>>i;}
template<class T>void inn(T &v){fa(i,v)fa(j,i)cin>>j;}
template<class T>void oump(T &v){fa(i,v)ff(i.fi,i.se);}

template<class T,class A>void pi(pair<T,A> &p){ci(p.fi,p.se);}
template<class T,class A>void po(pair<T,A> &p){ff(p.fi,p.se);}

void init(){
		  ios::sync_with_stdio(false);
		  cin.tie(0);
}
void solve();
void ori();
ll ck(){
		  std::random_device seed_gen;
		  std::mt19937 engine(seed_gen());
		  // [-1.0, 1.0)の値の範囲で、等確率に実数を生成する
		  std::uniform_real_distribution<> dist1(1.0, 100000);
		  i(10000){ // 各分布法に基いて乱数を生成
					 ll n  = dist1(engine);
		  } rz;
}
bl isup(ch c){
		  re 'A'<=c&&c<='Z';
}
bl islo(ch c){
		  re 'a'<=c&&c<='z';
}
//isdigit
mll pr_fa(ll x){
		  mll mp;
		  for(ll i=2;i*i<=x;++i){
					 while(x%i==0){
								++mp[i];
								x/=i;
					 }
		  }
		  if(x!=1)
					 ++mp[x];
		  re mp;
}
ch to_up(ch a){
		  re toupper(a);
}
ch to_lo(ch a){
		  re tolower(a);
}
#define str(x) to_string(x)
#define acc(v) accumulate(v.begin(),v.end(),0LL)
#define acci(v,i) accumulate(v.begin(),v.begin()+i,0LL)
#define dq deque<ll>
int main(){
		  init();
		  solve();
		  rz;
}
template <typename T>class pnt{
		  public:
					 T x,y;
					 pnt(T x=0,T y=0):x(x),y(y){}
					 pnt operator + (const pnt r)const {
								return  pnt(x+r.x,y+r.y);}
					 pnt operator - (const pnt r)const {
								return  pnt(x-r.x,y-r.y);}
					 pnt operator * (const pnt r)const {
								return  pnt(x*r.x,y*r.y);}
					 pnt operator / (const pnt r)const {
								return  pnt(x/r.x,y/r.y);}
					 pnt &operator += (const pnt r){
								x+=r.x;y+=r.y;return *this;}
					 pnt &operator -= (const pnt r){
								x-=r.x;y-=r.y;return *this;}
					 pnt &operator *= (const pnt r){
								x*=r.x;y*=r.y;return *this;}
					 pnt &operator /= (const pnt r){
								x/=r.x;y/=r.y;return *this;}
					 ll dist(const pnt r){
								re (x-r.x)*(x-r.x)+(y-r.y)*(y-r.y);
					 }
					 pnt rot(const dou theta){
								T xx,yy;
								xx=cos(theta)*x-sin(theta)*y;
								yy=sin(theta)*x+cos(theta)*y;
								return pnt(xx,yy);
					 }
};
istream &operator >> (istream &is,pnt<dou> &r){is>>r.x>>r.y;return is;}
ostream &operator << (ostream &os,pnt<dou> &r){os<<r.x<<" "<<r.y;return os;}
ll MOD= 1000000007;
//#define MOD 1000000007
//#define MOD 10007
//#define MOD 998244353
//ll MOD;
ll mod_pow(ll a, ll b, ll mod = MOD) {
		  ll res = 1;
		  for (a %= mod; b; a = a * a % mod, b >>= 1)
					 if (b & 1) res = res * a % mod;
		  return res;
}
class mint {
		  public:
					 ll a;
					 mint(ll x=0):a(x%MOD){}
					 mint operator + (const mint rhs) const  {
								return mint(*this) += rhs; }
					 mint operator - (const mint rhs) const  {
								return mint(*this) -= rhs; }
					 mint operator * (const mint rhs) const  {
								return mint(*this) *= rhs; }
					 mint operator / (const mint rhs) const  {
								return mint(*this) /= rhs; }
					 mint &operator += (const mint rhs)  {
								a += rhs.a; if (a >= MOD) a -= MOD; return *this; }
					 mint &operator -= (const mint rhs)  {
								if (a < rhs.a) a += MOD; a -= rhs.a; return *this; }
					 mint &operator *= (const mint rhs)  {
								a = a * rhs.a % MOD; return *this; }
					 mint &operator /= (mint rhs)  {
								ll exp = MOD - 2; while (exp) { if (exp % 2) *this *= rhs; rhs *= rhs; exp /= 2; } return *this; }
					 bool operator > (const mint& rhs)const{ return (this->a>rhs.a); }
					 bool operator < (const mint& rhs)const{ return (this->a<rhs.a); }
					 bool operator >= (const mint& rhs)const{ return (this->a>=rhs.a); }
					 bool operator <= (const mint& rhs)const{ return (this->a<=rhs.a);}
					 bool operator == (const mint& rhs)const{ return (this->a==rhs.a);}
};
istream& operator>>(istream& is, mint& r) { is>>r.a;return is;}
ostream& operator<<(ostream& os, const mint& r) { os<<r.a;return os;}
#define pq priority_queue<ll>
#define top top()

ll sumw(ll v,ll r){ re (v==0?0:sumw(v/10,r)*r+v%10); }
#define com complex<dou>
struct UFS{
		  map<st,st> par;map<st,ll>rk,siz;
		  st root(st x){
					 auto it=par.find(x);
					 if(it==par.en){
								par[x]=x;siz[x]=1;re x;
					 }
					 if(par[x]==x)return x;
					 else return par[x]=root(par[x]);
		  }
		  bool same(st x,st y){ return root(x)==root(y); }
		  bool unite(st x,st y){
					 st rx=root(x),ry=root(y);
					 if(rx==ry) return false;
					 if(rk[rx]<rk[ry]) swap(rx,ry);
					 siz[rx]+=siz[ry];
					 par[ry]=rx;
					 if(rk[rx]==rk[ry]) rk[rx]++;
					 return true;
		  }
		  ll size(st s){
					 re siz[s];
		  }
};

//vector<long long> fact, fact_inv, inv;
/*  init_nCk :二項係数のための前処理
    計算量:O(n)
    */
vll fact,inv,fact_inv;
void init_nCk(int SIZE) {
	fact.resize(SIZE + 5);
	fact_inv.resize(SIZE + 5);
	inv.resize(SIZE + 5);
	fact[0] = fact[1] = 1;
	fact_inv[0] = fact_inv[1] = 1;
	inv[1] = 1;
	for (int i = 2; i < SIZE + 5; i++) {
		fact[i] = fact[i - 1] * i % MOD;
		inv[i] = MOD - inv[MOD % i] * (MOD / i) % MOD;
		fact_inv[i] = fact_inv[i - 1] * inv[i] % MOD;
	}
}
long long nCk(int n, int k) {
	return fact[n] * (fact_inv[k] * fact_inv[n - k] % MOD) % MOD;
}
struct UF{ vll par,rk,siz; UF(ll n):par(n+5,-1),rk(n+5,0){ }
	ll root(ll x){ if(par[x]<0)return x; else return par[x]=root(par[x]); }
	bool same(ll x,ll y){ return root(x)==root(y); }
	bool unite(ll x,ll y){ ll rx=root(x),ry=root(y); if(rx==ry) return false; if(rk[rx]<rk[ry]) swap(rx,ry); par[rx]+=par[ry]; par[ry]=rx; if(rk[rx]==rk[ry]) rk[rx]++; return true; }
	ll size(ll x){ return -par[root(x)]; }
};
/* O(2*10^8) 9*10^18 1LL<<62 4*10^18
   ~~(v.be,v.be+n,x); not include v.be+n
   set.lower_bound(x);
   ->. *++ ! /%* +- << < == & && +=?:
   */
//vll dx={-1,-1,-1,0,0,1,1,1},dy={-1,0,1,-1,1,-1,0,1};
vll dx={-1,0,0,1},dy={0,-1,1,0};
//#define N 11

#define N 100000
//         12345
void solve(){
	//2<=n<=2*10^5;
	//1<=a_i,b_i<=10^9;
	//O(n) is ok
	//O(n*(n-1)/2) is ng
	//#|(i,j) s.t. ai+aj>bi+bj| (i<j)
	//#|(i,j) s.t. ai-bi+aj-bj>0|(i<j)
	//#|(i,j) s.t. dis_i+dis_j>0|(i<j)
	//#|(i,j) s.t. dis_i>-dis_j|(i<j)
	ge(ll,n);
	vll dis(n),a(n);
	in(a);
	i(n){
		ci(dis[i]);dis[i]=a[i]-dis[i];
	}
	so(dis);
	ll ans=0;
	i(n){
		ll l=0,r=n;
		while(l<r){
			ll m=(l+r)/2;
			if(-dis[i]<dis[m]){
				r=m;
			}else{
				l=m+1;
			}
		}
		ans+=n-r;
	}
	i(n)
		ans-=(dis[i]>0);
	ff(ans/2);
}


// Problem: D. Pair of Topics

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

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

// Memory Limit: 256 MB

// Time Limit: 2000 ms

//

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

#include <bits/stdc++.h>

#define int long long

#pragma GCC optimize("Ofast")

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

using namespace std;

const int N=1e5+5;

void solve(){

	int n;

	cin >> n;

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

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

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

		int x;

		cin >> x;

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

	}

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

	int ans=0;

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

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

		int l=lower_bound(begin(a),end(a),-a[i]+1)-a.begin();

		ans+=i-l;

	}

	cout << ans;

}

signed main(){

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

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

    while ( t-- ){

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

    }

}

/*

*/


C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6
LRLRRLL
L
LLR
RRRR
LLLLLL
R
OutputCopy3
2
3
1
7
1
NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right.

// Vidur Goel

//Codeforcees Handle: Vidurcodviz

#include<iostream>

#include<string>

#include<cmath>

#include<climits>

#include<algorithm>

#include<cstddef>

#include<cstdio>

#include<cstdlib>

#include<vector>

#include<stack>

#include<chrono>

#include<random>

#include<cassert>

#include<array>

#include<bitset>

#include<complex>

#include<cstring>

#include<functional>

#include<iomanip>

#include<map>

#include<numeric>

#include<queue>

#include<set>

#include<utility>

#include<string_view>

#include<deque>

#include<iterator>

#include<sstream>

using namespace std;

using namespace chrono;

void solve_array();

void solve_single();

void solve_mul();

typedef long long int ll;

typedef unsigned long long int ull;

typedef long double lld;

typedef pair<ll,ll> pll;

typedef vector<pair<ll,ll> > vpll;

typedef vector<vector<ll> > vvl;

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

#define rept(i, a, n) for (ll i = (a); i < (n); i++)

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

#define sor(x) sort(all(x))

#define lb lower_bound

#define ub upper_bound

#define pb push_back

#define ppb pop_back

#define mp make_pair

#define MOD 1000000007

#define MOD1 998244353

#define PI 3.141592653589793238462

#define vec vector<ll>

#define nn endl

ll seiv[1000001]={0};

string yup="YES";

string nope="NO";

ll minar(ll * arr,ll n){return *min_element(arr,arr+n);}

ll maxar(ll * arr,ll n){return *max_element(arr,arr+n);}

ll fibonacci(ll n){ll a=0;ll b=1;ll c;if(n==0 || n==1){return n;}for(ll i=2;i<n+1;i++){c=a+b;a=b;b=c;}return c;}

void copy_array(ll * &arr,ll * &brr,ll n){copy(arr,arr+n,brr);}

void read_array(ll * &arr,ll n){for(ll i=0;i<n;i++){cin>>arr[i];}return;}

void print_array(ll * &arr,ll n){for(ll i=0;i<n;i++){cout<<i<<" "<<arr[i]<<endl;}return;}

//void print_array(ll arr[],ll n){for(ll i=0;i<n;i++){cout<<i<<" "<<arr[i]<<endl;}return;}

void print_array(vec &arr,ll n){for(ll i=0;i<n;i++){cout<<i<<" "<<arr[i]<<endl;}return;}

bool prime(ll n){for(int i=2;i*i<=n;i++){if(n%i==0){return false;}}return true;}

void seive(){seiv[0]=0;seiv[1]=1;for(ll i=2;i*i<1000001;i++){if(seiv[i]==0){seiv[i]=i;for(ll j=i*i;j<1000001;j=j+i){if(seiv[j]==0){seiv[j]=i;}}}}}

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

ll expo(ll num,ll coef){ll res=1;while(coef!=0){if(coef%2==0){coef=coef/2;num=num*num;}else{coef=coef-1;res=res*num;}}return res;}

ll expo_mod(ll a,ll n,ll m){ll res=1;while(n!=0){if(n%2==0){a=a*a;a=a%m;n=n/2;}else{res=res*a;res=res%m;n--;}}return res;}

ll add_mod(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;}

ll mul_mod(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;}

ll sub_mod(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;}

/*

    sqrt() in built function to give the square root in float/double

    cbrt() in built function to give the cube root in float/double

    abs() is used for the absolute value of a number

    sort() inbuilt function in cpp

    swap() function in c++ used to swap value of two elements of the same data type.

    toupper() This function is used for converting a lowercase character to uppercase.

    tolower() This function is used for converting an uppercase character to lowercase.

    ceil() and floor() function

    vector<ll> vect(arr, arr+n) used to make a vector containg same elements as that of the array arr

    sort(vect.begin(),vect.end(), greater<int>());

    sort(arr,arr+n, greater<ll>()) sort in the decreasing order

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

    reverse(arr,arr+n);

    accumulate(first_iterator, last_iterator, initial value of sum) – Does the summation of vector elements eg: accumulate(arr,arr+n,0) will give summation of the array

    count(first_iterator, last_iterator,x) – To count the occurrences of x in vector.

    find(first_iterator, last_iterator, x) – Returns an iterator to the first occurrence of x in vector and points to last address of vector ((name_of_vector).end()) if element is not present in vector

    find(vect.begin(), vect.end(),5) != vect.end()?

                        cout << "\nElement found":

                    cout << "\nElement not found";

    maximium value long long can take 9, 223, 372, 036, 854, 775, 807

    2^63-1

    i.e, length of 19 only

    maximium value long long can take 18, 446, 744, 073, 709, 551, 615

    2^64-1

    i.e, length of 20 only

    reverse(s.begin(), s.end()); to reverse the string.(in built function)

    set<int, greater<int> > s1;

    s1.insert(10);

    set<int> a;

by default the sets are sorted in the ascending order

    this is how we are going to use the pair here

    vector< pair<ll,ll> > v;

    ll count=1;

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

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

            v.push_back(make_pair(count,arr[i]));

            count=1;

        }

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

            count++;

        }

    }

    v.pb(make_pair(count,arr[n-1]));

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

*/

bool mycompare(pair<ll, ll> p1 ,pair<ll, ll> p2){

    if(p1.first<p2.first){

        return true;

    }

    else if(p1.first==p2.first){

        return p1.second<p2.second;

    }

    else{

        return false;

    }

}

void solve_mul(){

    ll test;

    cin>>test;

    for(ll i=0;i<test;i++){

        solve_single();

    }

}

void solve_single(){

    string s;

    cin>>s;

    s=s+'R';

    s='R'+s;

    vec a;

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

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

            a.pb(i);

        }

    }

    ll max1=INT_MIN;

    for(ll i=0;i<a.size()-1;i++){

        max1=max(max1,a[i+1]-a[i]);

    }

    cout<<max1<<nn;

}

void solve_array(){

    ll n;

    cin>>n;

    ll * arr=new ll[n];

    read_array(arr,n);

}

int main(){

    make_it_fast();

    //seive();

    solve_mul();

    //solve_array();

    //solve_single();

    return 0;

}


C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2
OutputCopy1 2
InputCopy6
OutputCopy2 3
InputCopy4
OutputCopy1 4
InputCopy1
OutputCopy1 1

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

    //हरे कृष्ण - राधे राधे

    Author:    Arnab Ghosh

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

#pragma GCC optimize("O3,unroll-loops")

#include <bits/stdc++.h>

#include<ext/pb_ds/assoc_container.hpp>

#include<ext/pb_ds/tree_policy.hpp>

using namespace std;

using namespace __gnu_pbds;

#define endl '\n'

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

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

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

const long long mod = 1000000007;

const long long mod1 = 998244353;

using ll = long long;

using ld = long double;

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

template<class T> using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update >;

// find_by_order(k)  returns iterator to kth element starting from 0

// order_of_key(k) returns count of elements strictly smaller than k //less for ascending //greater for decending   //less_equal/greater_equal stores duplicate elements.

//queue -> push, front, back, pop

//deque -> push_back, push_front, pop_back, pop_front, front, back

template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type>istream& operator >> (istream &is, T_container &v) {for(T &x : v) is >> x; return is;}

#ifdef __SIZEOF_INT128__

ostream& operator << (ostream &os, __int128 const& value){static char buffer[64];int index = 0;__uint128_t T = (value < 0) ? (-(value + 1)) + __uint128_t(1) : value;if (value < 0)     os << '-';else if (T == 0)    return os << '0';for(; T > 0; ++index){    buffer[index] = static_cast<char>('0' + (T % 10));    T /= 10;}    while(index > 0)    os << buffer[--index];return os;}

istream& operator >> (istream& is, __int128& T){static char buffer[64];is >> buffer;size_t len = strlen(buffer), index = 0;T = 0; int mul = 1;if (buffer[index] == '-')    ++index, mul *= -1;for(; index < len; ++index)    T = T * 10 + static_cast<int>(buffer[index] - '0');T *= mul;    return is;}

#endif

template<typename A, typename B>

ostream& operator<<(ostream &os, const pair<A, B> &p){ return os << '(' << p.first << ", " << p.second << ')';}

template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator << (ostream &os, const T_container &v) {for (const T &x : v) os<< x << " "; return os;}

template<class P, class Q = vector<P>, class R = less<P> > ostream& operator << (ostream& out, priority_queue<P, Q, R> const& M){static priority_queue<P, Q, R> U;U = M;out << "{ ";while(!U.empty())    out << U.top() << " ", U.pop();return (out << "}");}

template<class P> ostream& operator << (ostream& out, queue<P> const& M){static queue<P> U;U = M;out << "{"; string sep;while(!U.empty()){    out << sep << U.front(); sep = ", "; U.pop();}return (out << "}");}

#ifndef ONLINE_JUDGE

#define debug(...) __f(#__VA_ARGS__, __VA_ARGS__)

template <typename Arg1>

void __f(const char* name, Arg1&& arg1){cerr << name << " : " << arg1 << endl;}

template <typename Arg1, typename... Args>

void __f(const char* names, Arg1&& arg1, Args&&... args){int count_open = 0, len = 1;for(int k = 1; ; ++k){   char cur = *(names + k);   count_open += (cur == '(' ? 1 : (cur == ')' ? -1: 0));   if (cur == ',' && count_open == 0){      const char* comma = names + k;      cerr.write(names, len) << " : " << arg1 << " | ";      __f(comma + 1, args...);      return;   }   len = (cur == ' ' ? len : k + 1);}}

#else

    #define debug(...) 1

#endif

template<typename... T>

void pr(T&&... args) {

    ((cout << args << " "), ...);

    cout << '\n';

}

template<typename... T>

void prln(T&&... args) {

    ((cout << args << '\n'), ...);

}

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

void solve() {

    ll x;

    cin >> x;

    ll ans;

    for(ll i = 1; i * i <= x; i++) {

        if(x % i == 0 && lcm(i, x/i) == x) {

            ans = i;

        }

    }

    pr(ans, x / ans);

}

int main()

{

#ifndef ONLINE_JUDGE

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

#endif

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

    int tt = 1;

    // cin >> tt;

    for(int tc = 1; tc <= tt; tc++) {

        solve();

        cerr << "-----------" << '\n';

    }

}


F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33.

// <-- Code By: Ashu Mittal -->
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;

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

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

template<class key, class value, class cmp = std::less<key>>
using ordered_map = tree<key, value, cmp, rb_tree_tag, tree_order_statistics_node_update>;

#define ff first
#define ss second
#define ll long long
#define all(sss) (sss).begin(),(sss).end()
#define pb push_back
#define pob pop_back
#define endl "\n"
#define input(ass) for(auto &x:(ass)) cin>>x;
#define iendl "\n", cout<<flush

const int mod = 1000000007;
// const int mod = 998244353;
typedef unsigned long long ull;
typedef long double lld;

#ifndef ONLINE_JUDGE
#include "dbg.cpp"
#else
#define dbg(x)
#endif

// help
ll LCM(ll aaa, ll bbb) {return (aaa / __gcd(aaa, bbb)) * bbb;}
ll power(ll aaa, ll bbb) {ll ans = 1; while (bbb) {if (bbb & 1) ans = (ans * aaa); bbb >>= 1; aaa = (aaa * aaa);} return ans;}
ll mod_inv(ll a) {return power(a, mod - 2);}

/*----------------------------------x x x---------------------------------*/

void solve() {
	ll n;
	cin >> n;

	std::vector<ll> co(n);
	for (auto &x : co) {
		cin >> x;
		if (x == 0) x = -1;
	}

	std::vector<vector<ll>> v(n);
	for (int i = 0; i < n - 1; i++) {
		ll a, b; cin >> a >> b;
		v[a - 1].push_back(b - 1);
		v[b - 1].push_back(a - 1);
	}

	std::vector<ll> dp(n, 0);
	function<void(ll, ll)> dfs = [&](ll i, ll p) {
		dp[i] += co[i];
		for (auto &x : v[i]) {
			if (x == p) continue;
			dfs(x, i);
			dp[i] += max(0ll, dp[x]);
		}
	};
	dfs(0, -1);
	dbg(dp)

	function<void(ll, ll)> dfs1 = [&](ll i, ll p) {
		for (auto &x : v[i]) {
			if (x == p) continue;
			ll val = (dp[x] < 0) ? 0 : dp[x];
			dp[x] += max(0ll, dp[i] - val);
			dfs1(x, i);
		}
	};
	dfs1(0, -1);

	for (auto &x : dp) cout << x << ' ';
	cout << endl;

}

/*

*/

int32_t main() {

	ios::sync_with_stdio(0); cin.tie(0);
#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
	freopen("Error.txt", "w", stderr);
#endif

	ll TT = 1;
	// cin >> TT;
	for (ll TEST = 1; TEST <= TT; TEST++) {
		// cout<<"Case #"<<TEST<<": ";
		solve();
	}
}


A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3
1 1
4 5
5 11
OutputCopyYES
YES
NO
NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days.

#include <bits/stdc++.h>

using namespace std;

int main()

{

    int t;

    cin>>t;

    while(t--){

        int n,d;

        cin>>n>>d;

        int l,r,mid,z;

        l=0;r=1e9;

        bool p=0;

        z=n/2;

        z++;

        l=ceil((double)d/z);

        z--;

        if((z+l)<=n){

            cout<<"YES\n";

        }

        else cout<<"NO\n";

    }

    return 0;

}


E. Strange Functiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's define the function ff of multiset aa as the multiset of number of occurences of every number, that is present in aa.E.g., f({5,5,1,2,5,2,3,3,9,5})={1,1,2,2,4}f({5,5,1,2,5,2,3,3,9,5})={1,1,2,2,4}.Let's define fk(a)fk(a), as applying ff to array aa kk times: fk(a)=f(fk−1(a)),f0(a)=afk(a)=f(fk−1(a)),f0(a)=a. E.g., f2({5,5,1,2,5,2,3,3,9,5})={1,2,2}f2({5,5,1,2,5,2,3,3,9,5})={1,2,2}.You are given integers n,kn,k and you are asked how many different values the function fk(a)fk(a) can have, where aa is arbitrary non-empty array with numbers of size no more than nn. Print the answer modulo 998244353998244353.InputThe first and only line of input consists of two integers n,kn,k (1≤n,k≤20201≤n,k≤2020).OutputPrint one number — the number of different values of function fk(a)fk(a) on all possible non-empty arrays with no more than nn elements modulo 998244353998244353.ExamplesInputCopy3 1
OutputCopy6
InputCopy5 6
OutputCopy1
InputCopy10 1
OutputCopy138
InputCopy10 2
OutputCopy33

#include <bits/stdc++.h>

#define ms(x, v) memset(x, v, sizeof(x))

#define il __attribute__((always_inline))

#define U(i,l,r) for(int i(l),END##i(r);i<=END##i;++i)

#define D(i,r,l) for(int i(r),END##i(l);i>=END##i;--i)

using namespace std;

typedef unsigned long long ull;

typedef long long ll;

template <typename T> using BS = basic_string<T>;

//const int SZ(1 << 23);

//unsigned char buf[SZ], *S, *Q;

//#define getchar() ((S==Q)&&(Q=buf+fread(S=buf,1,SZ,stdin)),S==Q?EOF:*S++)

template <typename T>

void rd(T& s) {

	int c = getchar();

	T f = 1; s = 0;

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

	while (isdigit(c)) { s = s * 10 + (c ^ 48); c = getchar(); }

	s *= f;

}

template <typename T, typename... Y>

void rd(T& x, Y&... y) { rd(x), rd(y...); }

template <typename T>

void pr(T s, bool f = 1) {

    if (s < 0) { printf("-"); s = -s; }

    if (!s) return void(f ? printf("0") : 0);

    pr(s / 10, 0);

    printf("%d", (signed)(s % 10));

}

#define meow(...) fprintf(stderr, __VA_ARGS__)

const int N = 2025;

const ll P = 998244353;

ll sub1(ll n) {

	// 求 \sum_1^n 分拆数

	ll f[N] {1}; // 划分数

	U (i, 1, n)

		U (j, i, n)

			(f[j] += f[j - i]) %= P;

	ll ans = 0;

	U (i, 1, n) (ans += f[i]) %= P;

	return ans;

}

ll sub2(ll n) {

	// 构造集合使得 i*t_i <= n，计数

    // 差分则不需要考虑 t_i 减的限制

    // 这样一个 c_i=t_i - t_{i-1}=1 对和的右移为 sum 1..i = i(i-1)/2

    ll f[N] {1};

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

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

            (f[j] += f[j - i * (i + 1) / 2]) %= P;

    ll ans = 0;

    U (i, 1, n) (ans += f[i]) %= P;

    return ans;

}

int n, k;

bool extend(int k, vector<int> v) {

    vector<int> g;

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

        int sum = 0;

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

        U (i, 0, v.size() - 1) sum += (i + 1) * v[i];

        if (sum > n) return 0;

        // if (j + 3 < k && sum > 23) return 0;

        U (i, 0, v.size() - 1)

            U (j, 1, v[i])

                g.push_back(i + 1);

        v.swap(g);

        vector<int>().swap(g);

    }

    return 1;

}

vector<int> v;

ll ans = 0;

bool dfs(int lim) { // 随便嗯分

    if (!extend(k, v)) return 0;

    // clog << lim << ' ' << v.size() << endl;

    ++ans;

    // meow("x");

    // for (int x : v) meow("%d ", x);

    // meow("\n");

    for (int i = lim, flag; ; ++i) {

        v.push_back(i);

        flag = dfs(i);

        v.pop_back();

        if (!flag) return 1;

    }

    return 1;

}

ll sub3() {

    dfs(1);

    return ans - 1;

}

int main() {

    // Sol::main();

    // return 0;

	rd(n, k);

	if (k == 1) exit(printf("%lld", sub1(n)) & 0);

    if (k == 2) exit(printf("%lld", sub2(n)) & 0);

    printf("%lld", sub3());

}


A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5
2 3
1 4
2 4
2 3
1 4
OutputCopyYes
No
No
No
Yes
NoteWe'll crack down the example test here:  After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5).  After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3).  After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal.  After the fifth query, the column barrier has been lifted, thus she can go to the final goal again.

#include <bits/stdc++.h>

#define ll long long

#define MAXN 100010

using namespace std;

int X, Y, N, Q, da_li, rez = 0;

vector <vector<int> > pos(3, vector <int> (MAXN));

int main()

{

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

    cin >> N >> Q;

    while(Q--)

    {

        da_li = 0;

        cin >> X >> Y;

        if(pos[X][Y]) da_li++;

        else da_li--;

        pos[X][Y] ^= 1;

        for(int i = -1; i <= 1; i++) {if(i+Y >= 1 && i+Y <= N && pos[3 - X][Y + i]) rez += da_li;}

        if(rez == 0) {cout << "YES" << endl;}

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

    }

    return 0;

}


F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer.

#include <bits/stdc++.h>

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

#define file(s) if (fopen(s".in", "r")) freopen(s".in", "r", stdin), freopen(s".out", "w", stdout)

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

#define F first

#define S second

using namespace std;

using ll = long long;

const ll N = 3e5+5 , inf = 2e9 + 7;

const ll INF = 1e18 ,   mod = 1e9+7 , P = 6547;

ll dp[N] , a[4] , ans = 0;

ll n;

pair<ll,ll> mx[N];

vector<ll> g[N];

void dfs(ll v , ll p = 0){

	dp[v] = dp[p]+1;

	mx[v].F = v;

	for(ll to : g[v]) if(to != p) dfs(to,v);

}

vector<ll> V;

queue<ll> q;

void go(){

	while(!q.empty()){

		ll v = q.front();

		q.pop();

		for(ll to : g[v]){

			if(dp[to] > dp[v]+1){

				dp[to] = dp[v]+1;

				q.push(to);

			}

		}

	}

	ll mx = 0;

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

		if(i != a[0] && i != a[1]){

			if(dp[i] >= mx) {

				mx = dp[i];

				a[2] = i;

			}

		}

	}

}

void bfs(ll v , ll p = 0){

	V.push_back(v);

	if(v == a[0]){

		for(ll x : V){

			dp[x] = 0;

			q.push(x);

		}

		go();

		return;

	}

	for(ll to : g[v]) if(to != p) bfs(to,v);

	V.pop_back();

}

void solve(){

	cin >> n;

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

		ll a , b;

		cin >> a >> b;

		g[a].push_back(b);

		g[b].push_back(a);

	}

	dfs(1);

	ll V = 1 , mx = 0;

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

		if(dp[i] > mx) mx = dp[i] , V = i;

		dp[i] = 0;

	}

	a[0] = V;

	dfs(V);

	V = 1 , mx = 0;

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

		if(dp[i] > mx) mx = dp[i] , V = i;

		dp[i] = inf;

	}

	a[1] = V;

	bfs(V);

	cout << mx-1 + dp[a[2]] <<"\n";

	cout << a[0] << " " << a[1] <<" " << a[2] <<"\n";

}

/*

*/

signed main(){

	ios;

	solve();

	return 0;

}


E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j  — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres  — the maximum possible strength of the club.ExamplesInputCopy4 1 2
1 16 10 3
18
19
13
15
OutputCopy44
InputCopy6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
OutputCopy377
InputCopy3 2 1
500 498 564
100002 3
422332 2
232323 1
OutputCopy422899
NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1.

#include <iostream>
#include<bits/stdc++.h>
#include<deque>
#include<algorithm>
#include<math.h>
#include<sstream>
#include<stdio.h>
#include<bitset>
#include<string>
#include<vector>
#include<unordered_map>
#include<queue>
#include<set>
#include<fstream>
#include<map>
#define int long long int
#define ld long double
#define pi 3.1415926535897932384626433832795028841971
#define MOD1 998244353
using namespace std;
random_device seed_gen;
mt19937_64 engine(seed_gen());
int inf = 1e18;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
template <typename T, typename U> void debug(std::vector<pair<T, U>> v) {for (int i = 0; i < v.size(); i++) cout << "[ " << v[i].first << " " << v[i].second << " ]\n"; cout << "\n";}
template <typename T> void debug(std::vector<T> v) {cout << "[ "; for (int i = 0; i < v.size(); i++) cout << v[i] << " "; cout << "]\n";}
template <typename T> void debug(std::set<T> v) {cout << "[ "; for (auto x : v) cout << x << " "; cout << "]\n";}
template <typename T> void debug(std::multiset<T> v) {cout << "[ "; for (auto x : v) cout << x << " "; cout << "]\n";}
template <typename T> void debug(vector<vector<T>> v) {int n = v.size(), m = v[0].size(); for (int i = 0; i < n; i++) {cout << "[ "; for (int j = 0; j < m; j++) cout << v[i][j] << " "; cout << "]\n";}}
template <typename T> void debug(T i) {cout << "[ " << i << " ]\n";}
template <typename T, typename U> void debug(T i, U j) {cout << "[ " << i << " " << j << " ]\n";}
template <typename T, typename U, typename V> void debug(T i, U j, V k) {cout << "[ " << i << " " << j << " " << k << " ]\n";}
template <typename T, typename U, typename V, typename X> void debug(T i, U j, V k, X l) {cout << "[ " << i << " " << j << " " << k << " " << l << " ]\n";}
template <typename T, typename U> void debug(pair<T, U> x) {cout << "[ " << x.first << " " << x.second << " ]\n";}

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;
}
int gcd(int a, int b) {
    if (b == 0) return a;
    return gcd(b, a % b);
}
int mminvprime(int a, int b) {
    return expo(a, b, b + 2);
}
const int N = 1e5 + 12;
int a[N], ind[N];
bool cmp(int x, int y)
{
    return a[x] > a[y];
}
int32_t main() {
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n, p, k;
    cin >> n >> p >> k;
    vector<vector<int>> s(n + 1, vector<int>(p, 0));
    for (int i = 1; i <= n; ++i)
    {
        cin >> a[i];
        ind[i] = i;
    }
    sort(ind + 1, ind + n + 1, cmp);
    for (int i = 1; i <= n; ++i)
    {
        for (int j = 0; j < p; j++)
        {
            int x;
            cin >> x;
            s[i][j] = x;
        }
    }
    int all = 1 << p;
    vector<vector<int>> dp(all, vector<int>(n + 1, -1));
    dp[0][0] = 0;
    for (int i = 1; i <= n; ++i)
    {
        int curind = ind[i];
        for (int mask = 0; mask < all; mask++)
        {
            int cur = i - __builtin_popcount(mask);
            if (cur <= k)
            {
                if (dp[mask][i - 1] != -1)
                    dp[mask][i] = dp[mask][i - 1] + a[curind];
            }
            else
            {
                if (dp[mask][i - 1] != -1)
                    dp[mask][i] = dp[mask][i - 1];
            }
            for (int j = 0; j < p; j++)
            {
                if (!(mask & (1 << j))) continue;
                if (dp[mask ^ (1 << j)][i - 1] != -1)
                    dp[mask][i] = max(dp[mask][i], dp[mask ^ (1 << j)][i - 1] + s[curind][j]);
            }
        }
    }
    cout << dp[all - 1][n];
    return 0;
}


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

#include <bits/stdc++.h>

#pragma GCC optimize("Ofast")

#define debug(x) cerr << #x << " " << x << "\n"

#define debugs(x) cerr << #x << " " << x << " "

using namespace std;

typedef long long ll;

typedef pair <short, short> pii;

const ll NMAX = 1002;

const ll VMAX = 41;

const ll INF = (1LL << 59);

const ll MOD = 1000000009;

const ll BLOCK = 318;

const ll base = 31;

const ll nrbits = 21;

short dist[NMAX][NMAX][41];

short mat[NMAX][NMAX];

vector <pii> v[41];

struct ura {

    short pf, ps;

    int cost;

};

vector <ura> muchii;

bool viz[41];

short dx[] = {0, 1, -1, 0};

short dy[] = {1, 0, 0, -1};

short n, m;

bool OK(short i, short j) {

    if(i > 0 && i <= n && j > 0 && j <= m)

        return 1;

    return 0;

}

int main() {

#ifdef HOME

    ifstream cin(".in");

    ofstream cout(".out");

#endif // HOME

    ios_base::sync_with_stdio(false);

    cin.tie(0);

    cout.tie(0);

    short k, i, j;

    cin >> n >> m >> k;

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

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

            cin >> mat[i][j];

            v[mat[i][j]].push_back({i, j});

        }

    }

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

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

            for(j = 1; j <= max(m, k); j++) {

                dist[i][j][col] = 32767;

            }

        }

        for(i = 1; i <= k; i++) viz[i] = 0; /// BRUH Cum sa uit...

        queue <pii> q;

        for(auto x : v[col]) {

            dist[x.first][x.second][col] = 0;

            q.push({x.first, x.second});

        }

        while(q.size()) {

            pii x = q.front();

            q.pop();

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

                pii care = {x.first + dx[d], x.second + dy[d]};

                if(!OK(care.first, care.second)) continue;

                if(dist[care.first][care.second][col] == 32767) { /// Hmm...

                    dist[care.first][care.second][col] = dist[x.first][x.second][col] + 1;

                    q.push({care.first, care.second});

                }

            }

            if(!viz[mat[x.first][x.second]]) {

                viz[mat[x.first][x.second]] = 1;

                for(auto y : v[mat[x.first][x.second]]) {

                    pii care = y;

                    if(dist[care.first][care.second][col] == 32767) { /// Hmm...

                        dist[care.first][care.second][col] = dist[x.first][x.second][col] + 1;

                        q.push({care.first, care.second});

                    }

                }

            }

        }

    }

    int q;

    cin >> q;

    while(q--) {

        int a, b, c, d;

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

        int minim = abs(c - a) + abs(d - b);

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

            minim = min(minim, (int)dist[a][b][col] + (int)dist[c][d][col] + 1);

        }

        cout << minim << "\n";

    }

    return 0;

}


E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai; then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions:   Set the power of the hole a to value b.  Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types:   0 a b  1 a  Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInputCopy8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2OutputCopy8 78 57 3

//#define __GLIBCXX_DEBUG 1

#pragma GCC optimize("O3,unroll-loops")

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

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

using namespace std;

using namespace __gnu_pbds;

using ll = long long;

using ld = long double;

using pii = pair<int, int>;

using pll = pair<ll, ll>;

const int INF = 1e9;

const int MOD = 1e9 + 7;

const int MAXN = 1e5 + 2;

typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> oredered_set;

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

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

#define fastIo(a) ios_base::sync_with_stdio(a); cin.tie(a); cout.tie(a)

#define F first

#define S second

#define pb(a) push_back(a)

#define pf(a) push_front(a)

#define eb(a) emplace_back(a)

#define dbg(a) cerr << #a << "=" << a << "\n";

#define dbg1(a) cerr << #a << " = [ "; for (auto& _ : a) cerr << _ << " "; cerr << "]" << "\n";

#define dbg2(a) cerr << #a << " = [ "; for (auto& _ : a) cerr << "(" << _.F << " " << _.S << ") "; cerr << "\n";

#define int long long

int ad(const int &a, const int &b, const int &mod) {

    if (a + b >= mod) return a + b - mod;

    return a + b;

}

int sub(const int &a, const int &b, const int &mod) {

    if (a < b) return a - b + mod;

    return a - b;

}

int multi(const int &a, const int &b, const int &mod) {

    return 1ll * a * b % mod;

}

int ask(int x) {

    cout << "- " << x << endl;

    int ans;

    cin >> ans;

    return ans;

}

void answer(int x) {

    cout << "! " << x << endl;

}

const int sq = 300;

int nxt[MAXN], cnt[MAXN], power[MAXN], last[MAXN];

signed main() {

    fastIo(0);

    //cout << fixed << setprecision(6);

    int n, m;

    cin >> n >> m;

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

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

        int j = min(n, power[i] + i);

        int idxi = i / sq, idxj = j / sq;

        if (j == n) {

            nxt[i] = n;

            cnt[i] = 1;

            last[i] = i;

        } else if (idxi == idxj) {

            nxt[i] = nxt[j];

            last[i] = last[j];

            cnt[i] = cnt[j] + 1;

        } else {

            last[i] = i;

            nxt[i] = j;

            cnt[i] = 1;

        }

    }

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

        int c, a, b;

        cin >> c >> a;

        a--;

        if (c) {

            int res = 0, ans = a;

            while (a != n) {

//                dbg(a);

//                dbg(nxt[a]);

                ans = last[a];

                res += cnt[a];

                a = nxt[a];

            }

            cout << ans + 1 << " " << res << "\n";

        } else {

            cin >> b;

            power[a] = b;

            for (int i = a ; i >= a / sq * sq ; --i) {

                int j = min(n, power[i] + i);

                int idxi = i / sq, idxj = j / sq;

                if (j == n) {

                    nxt[i] = n;

                    cnt[i] = 1;

                    last[i] = i;

                } else if (idxi == idxj) {

                    nxt[i] = nxt[j];

                    cnt[i] = cnt[j] + 1;

                    last[i] = last[j];

                } else {

                    last[i] = i;

                    nxt[i] = j;

                    cnt[i] = 1;

                }

            }

        }

    }

}


F. Harry The Pottertime limit per test9 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputTo defeat Lord Voldemort; Harry needs to destroy all horcruxes first. The last horcrux is an array aa of nn integers, which also needs to be destroyed. The array is considered destroyed if all its elements are zeroes. To destroy the array, Harry can perform two types of operations:  choose an index ii (1≤i≤n1≤i≤n), an integer xx, and subtract xx from aiai. choose two indices ii and jj (1≤i,j≤n;i≠j1≤i,j≤n;i≠j), an integer xx, and subtract xx from aiai and x+1x+1 from ajaj. Note that xx does not have to be positive.Harry is in a hurry, please help him to find the minimum number of operations required to destroy the array and exterminate Lord Voldemort.InputThe first line contains a single integer nn — the size of the array aa (1≤n≤201≤n≤20). The following line contains nn integers a1,a2,…,ana1,a2,…,an — array elements (−1015≤ai≤1015−1015≤ai≤1015).OutputOutput a single integer — the minimum number of operations required to destroy the array aa.ExamplesInputCopy3
1 10 100
OutputCopy3
InputCopy3
5 3 -2
OutputCopy2
InputCopy1
0
OutputCopy0
NoteIn the first example one can just apply the operation of the first kind three times.In the second example; one can apply the operation of the second kind two times: first; choose i=2,j=1,x=4i=2,j=1,x=4, it transforms the array into (0,−1,−2)(0,−1,−2), and then choose i=3,j=2,x=−2i=3,j=2,x=−2 to destroy the array.In the third example, there is nothing to be done, since the array is already destroyed.


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

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string.h>
#include<cmath>
#include<math.h>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<vector>
#include<set>
#include<deque>
#include<time.h>
using namespace std;
inline void read(int &x){
	x=0;
	bool sgn=0;
	char ch;
	while(ch=getchar(),ch<'!');
	if(ch=='-'){
		sgn=1;
	}else{
		x=ch-48;
	}
	while(ch=getchar(),ch>'!'){
		x=(x<<3)+(x<<1)+ch-48;
	}
	if(sgn==1){
		x=-x;
	}
	return;
}
inline void write(int x){
	if(x<0){
		putchar('-');
		x=-x;
	}
	if(x>9){
		write(x/10);
	}
	putchar(x%10+48);
	return;
}
inline void read(long long &x){
	x=0;
	bool sgn=0;
	char ch;
	while(ch=getchar(),ch<'!');
	if(ch=='-'){
		sgn=1;
	}else{
		x=ch-48;
	}
	while(ch=getchar(),ch>'!'){
		x=(x<<3)+(x<<1)+ch-48;
	}
	if(sgn==1){
		x=-x;
	}
	return;
}
inline void write(long long x){
	if(x<0){
		putchar('-');
		x=-x;
	}
	if(x>9){
		write(x/10);
	}
	putchar(x%10+48);
	return;
}
long long n,m,k,cnt,lcp[1050][1050],dp[1050][1050],redp[1050][1050];
char s[1050];
struct st{
	long long l,r;
}a[1000050];
inline bool operator<(st const &lhs,st const &rhs) {
	long long length=lcp[lhs.l][rhs.l];
	if(length>=lhs.r-lhs.l+1||length>=rhs.r-rhs.l+1){
		return lhs.r-lhs.l+1<rhs.r-rhs.l+1;
	}
	return s[lhs.l+length]<s[rhs.l+length];
}
inline bool check(long long x){
	memset(dp,0,sizeof(dp));
	memset(redp,0,sizeof(redp));
	redp[n+1][0]=1;
	long long length=a[x].r-a[x].l+1;
	for(int i=n;i>=1;i--){
		long long t=min(length,lcp[a[x].l][i]);
		if(t==length||s[i+t]>s[a[x].l+t]){
			for(int j=1;j<=m;j++){
				dp[i][j]=redp[i+t+1][j-1];
			}
		}
		for(int j=0;j<=m;j++){
			redp[i][j]=min(redp[i+1][j]+dp[i][j],k);
		}
	}
	return dp[1][m]>=k;
}
int main(){
	read(n);
	read(m);
	read(k);
	scanf("%s",s+1);
	for(int i=n;i>=1;i--){
		for(int j=n;j>=1;j--){
			lcp[i][j]=0;
			if(s[i]==s[j]){
				lcp[i][j]=lcp[i+1][j+1]+1;
			}
		}
	}
	for(int i=1;i<=n;i++){
		for(int j=i;j<=n;j++){
			a[++cnt]=st{i,j};
		}
	}
	sort(a+1,a+1+cnt);
	long long l=1,r=cnt;
	while(l<=r){
		long long mid=(l+r)>>1;
		if(check(mid)){
			l=mid+1;
		}else{
			r=mid-1;
		}
	}
	for(int i=a[l].l;i<=a[l].r;i++){
		putchar(s[i]);
	}
	return 0;
}


D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4
OutputCopy2
3 1InputCopy1 3
OutputCopy3
1 1 1InputCopy8 5
OutputCopy-1InputCopy0 0
OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty.

// LUOGU_RID: 102435206
#include<bits/stdc++.h>
using namespace std;
long long u,v,c;
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>u>>v;
    c=v-u;
    if(c<0||(c&1)){
        cout<<-1;
        return 0;
    }
    if(!c){
        if(!u)
            cout<<0;
        else
            cout<<1<<endl<<u;
    }
    else{
        c>>=1;
        if(!(c&u))
            cout<<2<<endl<<c<<' '<<(c^u);
        else
            cout<<3<<endl<<c<<' '<<c<<' '<<u;
    }
    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

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

#define int long long

#define pb push_back

using namespace std;

const int INF=7e5+5;

int t,n,l[INF],r[INF],f[INF];

vector <int> v;

int Get(int x) {return lower_bound(v.begin(),v.end(),x)-v.begin()+1;}

struct node_{

	bool l,r;

	int xx;

};

node_ mer(node_ x,node_ y) {return {x.l,y.r,x.xx+y.xx-(x.r&y.l)};}

struct Segment{

	#define ll tl[id]

	#define rr tr[id]

	#define ls(x) x<<1

	#define rs(x) x<<1|1

	node_ sum[INF<<2];

	int tl[INF<<2],tr[INF<<2];

	void push_up(int id) {

		sum[id]=mer(sum[ls(id)],sum[rs(id)]);

	}

	void build(int l,int r,int id) {

		ll=l;rr=r;

		if (l==r) {sum[id]={f[l]>0,f[l]>0,f[l]>0};return ;}

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

		build(l,Mid,ls(id));

		build(Mid+1,r,rs(id));

		push_up(id);

	}

	node_ query(int l,int r,int id) {

		if (l<=ll && rr<=r) return sum[id];

		int Mid=(ll+rr)>>1;

		if (l>Mid) return query(l,r,rs(id));

		else if (r<=Mid) return query(l,r,ls(id));

		else return mer(query(l,r,ls(id)),query(l,r,rs(id)));

	}

} T1;

struct Segment2{

	#define ll tl[id]

	#define rr tr[id]

	#define ls(x) x<<1

	#define rs(x) x<<1|1

	node_ sum[INF<<2];

	int tl[INF<<2],tr[INF<<2];

	void push_up(int id) {

		sum[id]=mer(sum[ls(id)],sum[rs(id)]);

	}

	void build(int l,int r,int id) {

		ll=l;rr=r;

		if (l==r) {sum[id]={f[l]>1,f[l]>1,f[l]>1};return ;}

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

		build(l,Mid,ls(id));

		build(Mid+1,r,rs(id));

		push_up(id);

	}

	node_ query(int l,int r,int id) {

		if (l<=ll && rr<=r) return sum[id];

		int Mid=(ll+rr)>>1;

		if (l>Mid) return query(l,r,rs(id));

		else if (r<=Mid) return query(l,r,ls(id));

		else return mer(query(l,r,ls(id)),query(l,r,rs(id)));

	}

} T2;

void solve() {

	cin>>n;

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

		cin>>l[i]>>r[i];

		l[i]*=2;r[i]*=2;

		v.pb(l[i]);v.pb(r[i]);

		v.pb(r[i]+1);

	}

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

	v.erase(unique(v.begin(),v.end()),v.end());

	int len=v.size();

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

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

		int it=Get(l[i]),it1=Get(r[i]+1);

		f[it]++;f[it1]--;

	}

	for (int i=1;i<=len;i++) f[i]+=f[i-1];

	T1.build(1,len,1);T2.build(1,len,1);

	int res=0;

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

		int it=Get(l[i]),it1=Get(r[i]);

		node_ xx={0,0,0};if (it-1>=1) xx=T1.query(1,it-1,1);

		node_ yy={0,0,0};yy=T2.query(it,it1,1);

		node_ zz={0,0,0};if (it1+1<=len) zz=T1.query(it1+1,len,1);

		res=max(res,mer(xx,mer(yy,zz)).xx);

	}

	cout<<res<<"\n";

	return ;

}

signed main()

{

	ios::sync_with_stdio(false);

	cin>>t;

	while (t--) solve();

	return 0;

}


F. Nora's Toy Boxestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSIHanatsuka - EMber SIHanatsuka - ATONEMENTBack in time; the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.One day, Nora's adoptive father, Phoenix Wyle, brought Nora nn boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO.She labelled all nn boxes with nn distinct integers a1,a2,…,ana1,a2,…,an and asked ROBO to do the following action several (possibly zero) times:  Pick three distinct indices ii, jj and kk, such that ai∣ajai∣aj and ai∣akai∣ak. In other words, aiai divides both ajaj and akak, that is ajmodai=0ajmodai=0, akmodai=0akmodai=0.  After choosing, Nora will give the kk-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty.  After doing so, the box kk becomes unavailable for any further actions. Being amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the largest amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes.Since ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them?As the number of such piles can be very large, you should print the answer modulo 109+7109+7.InputThe first line contains an integer nn (3≤n≤603≤n≤60), denoting the number of boxes.The second line contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤601≤ai≤60), where aiai is the label of the ii-th box.OutputPrint the number of distinct piles having the maximum number of boxes that ROBO_Head can have, modulo 109+7109+7.ExamplesInputCopy3
2 6 8
OutputCopy2
InputCopy5
2 3 4 9 12
OutputCopy4
InputCopy4
5 7 2 9
OutputCopy1
NoteLet's illustrate the box pile as a sequence bb; with the pile's bottommost box being at the leftmost position.In the first example, there are 22 distinct piles possible:   b=[6]b=[6] ([2,6,8]−→−−(1,3,2)[2,8][2,6,8]→(1,3,2)[2,8])  b=[8]b=[8] ([2,6,8]−→−−(1,2,3)[2,6][2,6,8]→(1,2,3)[2,6]) In the second example, there are 44 distinct piles possible:   b=[9,12]b=[9,12] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,3,4)[2,3,4][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,3,4)[2,3,4])  b=[4,12]b=[4,12] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,3,4)[2,3,9][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,3,4)[2,3,9])  b=[4,9]b=[4,9] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,4,3)[2,3,12][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,4,3)[2,3,12])  b=[9,4]b=[9,4] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,4,3)[2,3,12][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,4,3)[2,3,12]) In the third sequence, ROBO can do nothing at all. Therefore, there is only 11 valid pile, and that pile is empty.

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef uint64_t ull;
inline int read(){
	int f=1,r=0;char c=getchar();
	while(!isdigit(c))f^=c=='-',c=getchar();
	while(isdigit(c))r=(r<<1)+(r<<3)+(c&15),c=getchar();
	return f?r:-r;
}
const int N=66,M=1<<15|7,mod=1e9+7;
inline void inc(int &x,int y){x+=y-mod,x+=x>>31&mod;}
int pa[N];
int find(int x){return pa[x]^x?pa[x]=find(pa[x]):x;}
int n,sum,ans=1,a[N],id[N],C[N][N],f[N][M],num[M];
bool flg[N];
ull S[N];
inline void solve(int pos){
	int tot=0;vector<int>vec,d;
	for(int i=1;i<=n;i++)
		if(flg[i] && pa[i]==pos)id[i]=tot++,vec.push_back(i);
	int U=(1<<tot)-1,cnt;
	for(int i=1;i<=n;i++)
		if(!flg[i] && pa[i]==pos)d.push_back(i);
	if(d.empty())return;
	cnt=d.size()-1,sum+=cnt,ans=(ll)ans*C[sum][cnt]%mod;
	fill(num,num+U+1,0),memset(f, 0, sizeof f);
	for(int i:d){
		int s=0;
		for(int j:vec)
			if(S[i]>>j&1)s|=1<<id[j];
		S[i]=s,num[s]++,f[0][s]++;
	}
	for(int i=0;i<tot;i++)
		for(int s=0;s<=U;s++)
			if(s>>i&1)num[s]+=num[s^(1<<i)];
	for(int i=0;i<cnt;i++)
		for(int s=0;s<=U;s++){
			int v=f[i][s];
			if(i>num[s])continue;
			inc(f[i+1][s],(ll)v*(num[s]-i-1)%mod);
			for(int j:d){
				int t=S[j]&s;
				if(!t || t==S[j])continue;
				inc(f[i+1][s|S[j]],v);
			}
		}
	ans=(ll)ans*f[cnt][U]%mod;
}
int main(){
#ifndef ONLINE_JUDGE
	freopen("1.in","r",stdin);
	freopen("1.out","w",stdout);
#endif
	n=read();
	for(int i=1;i<=n;i++)a[i]=read();
	sort(a+1,a+n+1);
	C[0][0]=1;
	for(int i=1;i<=n;i++) {
		C[i][0]=1;
		for (int j=1; j<=n; j++) C[i][j]=(C[i-1][j]+C[i-1][j-1])%mod;
	}
	for(int i=1;i<=n;i++){
		flg[i]=true,pa[i]=i;
		for(int j=1;j<=n;j++)
			flg[i]&=i==j || a[i]%a[j]!=0;
	}
	for(int i=1;i<=n;i++){
		if(flg[i])continue;
		int lst=0;
		for(int j=1;j<=n;j++){
			if(i==j || !flg[j])continue;
			if(a[i]%a[j]==0){
				if(!lst)lst=find(j);
				S[i]|=1ull<<j,pa[find(j)]=lst;
			}
		}
	}
	for(int i=1;i<=n;i++)
		if(!flg[i])pa[i]=find(__builtin_ctzll(S[i]));
	for(int i=1;i<=n;i++)pa[i]=find(i);
	for(int i=1;i<=n;i++)
		if(flg[i] && pa[i]==i)solve(i);
	printf("%d\n",ans);
	return 0;
}


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

#include <bits/stdc++.h>

#define ll long long

#define pii pair<ll, ll>

#define fi first

#define se second

#define endl '\n'

using namespace std;

void DuckMyKofta() {

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

#ifndef ONLINE_JUDGE

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

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

#else

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

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

#endif

}

const int N = 1e5 + 5;

const long long BASE = 1e9 + 7;

const int INV_2 = 5e8 + 4;

const int LOG = 20;

const long double PI = 3.14159265358979323846;

int dx[] = {+0, +0, -1, +1, +1, -1, +1, -1};

int dy[] = {-1, +1, +0, +0, +1, -1, -1, +1};

void solve(int testcase) {

    int n, k;

    cin >> n >> k;

    ll a[n];

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

        cin >> a[i];

    }

    int m = (int) (log(LONG_LONG_MAX) / log(k));

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

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

        ll tmp = a[i];

        int cnt = 0;

        while (tmp) {

            bits[i][cnt] = tmp % k;

            tmp /= k;

            cnt++;

        }

    }

    set<int> st;

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

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

            if (bits[i][j] == 1) {

                if (st.contains(j)) {

                    cout << "NO" << endl;

                    return;

                }

                st.insert(j);

            } else if (bits[i][j] != 0) {

                cout << "NO" << endl;

                return;

            }

        }

    }

    cout << "YES" << endl;

}

signed main() {

    DuckMyKofta();

    int t = 1, cnt = 1;

    cin >> t;

    while (t--) {

        solve(cnt++);

    }

}


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

#include <bits/stdc++.h>

using namespace std;
const int N=10005;
const int M=105;
int head[N],nxt[N],edgenum=1,vet[N],num[N],val[N],dir[N],fa[N],flag[N],vis[N],n,m;
char ans[M][M],c[M][M];
const int dx[4]={1,-1,0,0};
const int dy[4]={0,0,1,-1};
void Add(int u,int v,int w) { vet[++edgenum]=v; nxt[edgenum]=head[u]; head[u]=edgenum; val[edgenum]=w; }
int find(int x) { if (x!=fa[x]) fa[x]=find(fa[x]); return fa[x]; }
bool dfs(int x) {
if (vis[x]) return 0;
vis[x]=1;
for (int e=head[x]; e; e=nxt[e]) {
int v=vet[e];
if (!vis[v] && (!num[v] || dfs(num[v]))) {
num[v]=x;
dir[v]=val[e]^1;
return 1;
}
}
return 0;
}
void dfs2(int x,int f) {
for (int e=head[x]; e; e=nxt[e]) {
int v=vet[e]; if (v==f) continue;
if (find(x)!=find(v)) {
fa[find(x)]=find(v);
ans[(x-1)/m*2+1+dx[val[e]]][(x-1)%m*2+1+dy[val[e]]]='O';
if (v!=1) dfs2(num[v],v);
}
}
}
int main() {
//	freopen("sample1.in","r",stdin);
//	freopen("1.out","w",stdout);
int deb=0;
int T; scanf("%d",&T);
if (deb) cout<<T<<endl;
while (T--) {
memset(fa,0,sizeof(fa)); memset(head,0,sizeof(head));
memset(dir,0,sizeof(dir));
edgenum=1; for (int i=0; i<M; i++) for (int j=0; j<M; j++) ans[i][j]=' ';
scanf("%d%d",&n,&m);
for (int i=1; i<=n*m; i++) num[i]=flag[i]=0,fa[i]=i;
for (int i=1; i<=n; i++) scanf("%s",c[i]+1);
if (deb) {
cout<<n<<' '<<m<<endl;
for (int i=1; i<=n; i++,puts("")) for (int j=1; j<=m; j++) printf("%c",c[i][j]);
}

for (int x=1; x<=n; x++)
for (int y=(x&1)+1; y<=m; y+=2)
if (c[x][y]=='O') {
for (int k=0; k<4; k++) {
int nx=x+dx[k],ny=y+dy[k];
if (nx<1 || ny<1 || nx>n || ny>m || (nx==1 && ny==1) || c[nx][ny]!='O') continue;
Add((x-1)*m+y,(nx-1)*m+ny,k);
}
}
for (int i=1; i<=n; i++)
for (int j=(i&1)+1; j<=m; j+=2)
if (c[i][j]=='O') {
for (int k=1; k<=n*m; k++) vis[k]=0;
flag[(i-1)*m+j]=dfs((i-1)*m+j);
}

for (int i=1; i<=n; i++)
for (int j=-(i&1)+2; j<=m; j+=2)
if (i+j>2 && c[i][j]=='O') {
if (!num[(i-1)*m+j]) { puts("NO"); goto out; }
fa[find((i-1)*m+j)]=find(num[(i-1)*m+j]);
ans[(i<<1)-1+dx[dir[(i-1)*m+j]]][(j<<1)-1+dy[dir[(i-1)*m+j]]]='O';
}

if (c[2][1]=='O') Add(m+1,1,1);
if (c[1][2]=='O') Add(2,1,3);
for (int i=1; i<=n; i++)
for (int j=(i&1)+1; j<=m; j+=2)
if (c[i][j]=='O' && !flag[(i-1)*m+j]) dfs2((i-1)*m+j,-1);

for (int i=1,rt=find(1); i<=n; i++)
for (int j=1; j<=m; j++) {
if (c[i][j]=='O' && find((i-1)*m+j)!=rt) { puts("NO"); goto out; }
ans[(i<<1)-1][(j<<1)-1]=c[i][j];
}
if (deb) { for (int i=1; i<(n<<1); i++) for (int j=1; j<(m<<1); j++) if (ans[i][j]==' ') ans[i][j]='K'; }
puts("YES");
for (int i=1; i<(n<<1); i++,puts(""))
for (int j=1; j<(m<<1); j++) printf("%c",ans[i][j]);
out:;
}
return 0;
}


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

#include<bits/stdc++.h>

typedef long long ll;

typedef unsigned long long ull;

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

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

#define Ede(i, u) for(int i = head[u]; i; i = e[i].nxt)

using namespace std;

#define eb emplace_back

inline int read() {

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

	while(c < '0' || c > '9') f = (c == '-') ? - 1 : 1, c = getchar();

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

	return x * f;

}

const int N = 5e5 + 10;

int n, a[N], m, b[N], tim, ans[N];

bool vis[N];

vector<int> g[N];

set<int> pos, valid;

void calc(int l, int r, int v) {

	auto it = valid.lower_bound(l);

	while(it != valid.end() && *it <= r) ans[*it] = v, it = valid.erase(it);

}

void update(int p, int v) {

	if(p < 1 || p > n) return;

	auto it = pos.lower_bound(p); int r = *it, l = *(-- it) + 1;

	tim = max(tim, (r - l) >> 1);

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

	if(vis[l]) calc(l, mid, v);

	if(vis[r]) calc(mid + 1, r, v);

}

void insert(int p) {

	vis[p] = true;

	if(p > 1 && !vis[p - 1]) pos.erase(p - 1); else pos.insert(p - 1);

	if(p < n && !vis[p + 1]) pos.erase(p); else pos.insert(p);

}

int main() {

	n = m = read();

	rep(i, 1, n) a[i] = b[i] = read();

	sort(b + 1, b + m + 1);

	m = unique(b + 1, b + m + 1) - (b + 1);

	pos.insert(0);

	rep(i, 1, n)

		pos.insert(i), valid.insert(i),

		a[i] = lower_bound(b + 1, b + m + 1, a[i]) - b, g[a[i]].eb(i);

	rep(i, 1, m) {

		for(int o : g[i]) insert(o);

		for(int o : g[i]) rep(d, -1, 1) update(o + d, i);

	}

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

	rep(i, 1, n) printf("%d%c", b[ans[i]], i == n ? '\n' : ' ');

	return 0;

}


D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
OutputCopy2
-1
0

#include <bits/stdc++.h>

using namespace std;

int Solve() {

    long long n; int m;

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

    vector<int> cnt(31), nd(31);

    long long sum = 0;

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

        int x; scanf("%d", &x);

        sum += x;

        cnt[__builtin_ctz(x)]++;

    }

    if (sum < n) return -1;

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

        if (n >> i & 1) {

            if (i <= 30) nd[i]++;

            else nd[30] += (1 << (i - 30));

        }

    }

    int res = 0;

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

        if (nd[i] == 1 && cnt[i] == 0) {

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

                if (cnt[j] > 0) {

                    res += j - i;

                    cnt[j]--;

                    for (int k = j - 1; k > i; --k) cnt[k]++;

                    cnt[i] += 2;

                    break;

                }

            }

        }

        if (nd[i] == 1 && cnt[i] == 0) return -1;

        if (nd[i] == 1) cnt[i]--;

        cnt[i + 1] += cnt[i] / 2;

    }

    if (cnt[30] < nd[30]) return -1;

    return res;

}

int main() {

    int t; scanf("%d", &t);

    while (t--) printf("%d\n", Solve());

}


B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions:  If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss;  If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt;  For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e":  On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105)  — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa
3
1 1
2 4
5 5
OutputCopyYes
No
Yes
InputCopyaabbbbbbc
6
1 2
2 4
2 2
1 9
5 7
3 5
OutputCopyNo
Yes
Yes
Yes
No
No
NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram.

#include <bits/stdc++.h>

using namespace std;

using LL = long long;

#define endl '\n'

using db = double;

template <class T>

using max_heap = priority_queue<T>;

template <class T>

using min_heap = priority_queue<T, vector<T>, greater<>>;

int main()

{

    ios::sync_with_stdio(false);

    cin.tie(nullptr);

    string s;

    cin >> s;

    int n = s.size();

    s = ' ' + s;

    vector<vector<int>> pre(n + 1, vector<int>(26));

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

    {

        pre[i] = pre[i - 1];

        pre[i][s[i] - 'a']++;

    }

    int Q;

    cin >> Q;

    while (Q--)

    {

        int l, r;

        cin >> l >> r;

        vector<int> cnt(26);

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

            cnt[i] = pre[r][i] - pre[l - 1][i];

        bool ok = 0;

        sort(cnt.begin(), cnt.end(), greater<int>());

        if (cnt[2] > 0 || (cnt[1] > 0 && s[l] != s[r]))

            ok = 1;

        if (ok || r - l + 1 == 1)

            cout << "Yes" << endl;

        else

            cout << "No" << endl;

    }

    return 0;

}