contest_id
stringclasses
33 values
problem_id
stringclasses
14 values
statement
stringclasses
181 values
tags
sequencelengths
1
8
code
stringlengths
21
64.5k
language
stringclasses
3 values
1307
G
G. Cow and Exercisetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFarmer John is obsessed with making Bessie exercise more!Bessie is out grazing on the farm; which consists of nn fields connected by mm directed roads. Each road takes some time wiwi to cross. She is currently at field 11 and will return to her home at field nn at the end of the day.Farmer John has plans to increase the time it takes to cross certain roads. He can increase the time it takes to cross each road by a nonnegative amount, but the total increase cannot exceed xixi for the ii-th plan. Determine the maximum he can make the shortest path from 11 to nn for each of the qq independent plans.InputThe first line contains integers nn and mm (2≤n≤502≤n≤50, 1≤m≤n⋅(n−1)1≤m≤n⋅(n−1)) — the number of fields and number of roads, respectively.Each of the following mm lines contains 33 integers, uiui, vivi, and wiwi (1≤ui,vi≤n1≤ui,vi≤n, 1≤wi≤1061≤wi≤106), meaning there is an road from field uiui to field vivi that takes wiwi time to cross.It is guaranteed that there exists a way to get to field nn from field 11. It is guaranteed that the graph does not contain self-loops or parallel edges. It is possible to have a road from uu to vv and a road from vv to uu.The next line contains a single integer qq (1≤q≤1051≤q≤105), the number of plans.Each of the following qq lines contains a single integer xixi, the query (0≤xi≤1050≤xi≤105).OutputFor each query, output the maximum Farmer John can make the shortest path if the total increase does not exceed xixi.Your answer is considered correct if its absolute or relative error does not exceed 10−610−6.Formally, let your answer be aa, and the jury's answer be bb. Your answer is accepted if and only if |a−b|max(1,|b|)≤10−6|a−b|max(1,|b|)≤10−6.ExampleInputCopy3 3 1 2 2 2 3 2 1 3 3 5 0 1 2 3 4 OutputCopy3.0000000000 4.0000000000 4.5000000000 5.0000000000 5.5000000000
[ "flows", "graphs", "shortest paths" ]
#include <bits/stdc++.h> using namespace std; typedef long long ll; 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^48),c=getchar(); return f?r:-r; } #define pii pair<int,int> #define fi first #define se second const int N=57,inf=0x3f3f3f3f; struct Edge{ int to,nxt,fl,w; }e[(N*N)<<1]; int s_e,head[N]; inline void add_e(int from,int to,int fl,int w){ e[++s_e].to=to,e[s_e].fl=fl,e[s_e].w=w; e[s_e].nxt=head[from],head[from]=s_e; } int n,m,s,t,dis[N],pd[N],pe[N]; bool vis[N]; queue<int>q; inline bool spfa(){ for(int i=1;i<=n;i++)dis[i]=inf,vis[i]=0; vis[s]=1,q.push(s),dis[s]=0; while(!q.empty()){ int x=q.front();q.pop(),vis[x]=0; for(int i=head[x];i;i=e[i].nxt){ int y=e[i].to,w=e[i].w; if(dis[y]>dis[x]+w && e[i].fl){ dis[y]=dis[x]+w,pd[y]=x,pe[y]=i; if(!vis[y])vis[y]=1,q.push(y); } } } return dis[t]^inf; } vector<pii>a; inline void EK(){ int flow=0,cost=0; while(spfa()){ int fl=inf,co=0,x=t; for(int i=pe[x];x^s;x=pd[x],i=pe[x])fl=min(fl,e[i].fl); x=t; for(int i=pe[x];x^s;x=pd[x],i=pe[x])e[i].fl-=fl,e[i^1].fl+=fl,co+=fl*e[i].w; flow+=fl,cost+=co; a.push_back(pii(flow,cost)); } } int main(){ n=read(),m=read(),s_e=1; for(int i=1;i<=m;i++){ int x=read(),y=read(),w=read(); add_e(x,y,1,w),add_e(y,x,0,-w); } s=1,t=n,EK(); int Q=read(); while(Q--){ int x=read();double ans=inf; for(auto i:a)ans=min(ans,1.0*(x+i.se)/i.fi); printf("%.10lf\n",ans); } return 0; }
cpp
1296
B
B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6 1 10 19 9876 12345 1000000000 OutputCopy1 11 21 10973 13716 1111111111
[ "math" ]
#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--){ long long int s,ans=0; cin>>s; while(s){ ans+=((s/10)*10); s=(s%10)+(s/10); if(s<10)break; } ans+=s; cout<<ans<<endl; } return 0; }
cpp
1303
A
A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3 010011 0 1111000 OutputCopy2 0 0 NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).
[ "implementation", "strings" ]
/* In The Name Of God */ #include <bits/stdc++.h> using namespace std; #define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0) #define pb push_back #define sortt(v) sort(v.begin(), v.end()) typedef long long ll; const ll maxx = 1e10 + 10; void solve() { string s; cin >> s; vector <int> v; for (int i=0; i<s.size(); i++){ if (s[i] == '1') v.pb(i); } if (v.size() == 0) {cout << "0\n"; return;} int ans = 0; for (int i=0; i<v.size() - 1; i++){ ans += v[i+1] - v[i] - 1; } cout << ans << '\n'; } int main() { int t; cin >> t; while (t--) solve(); } /* Life can only be understood backwards; but it must be lived forwards; */
cpp
1324
A
A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00: You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2); then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4 3 1 1 3 4 1 1 2 1 2 11 11 1 100 OutputCopyYES NO YES YES NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.
[ "implementation", "number theory" ]
#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 10000 // 1234567 void solve(){ ge(ll,t); xx(t){ ge(ll,n); ll pal=0; i(n){ ge(ll,x); pal+=x&1; } ff(pal==n||pal==0?"YES":"NO"); } }
cpp
1307
C
C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer  — the number of occurrences of the secret message.ExamplesInputCopyaaabb OutputCopy6 InputCopyusaco OutputCopy1 InputCopylol OutputCopy2 NoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.
[ "brute force", "dp", "math", "strings" ]
#include<bits/stdc++.h> using namespace std; #define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define int long long #define sort(v) sort(v.begin(),v.end()) void solve(){ string s; cin>>s; map<char,int> mp; map<string,int> mp1; vector<int> v; int mx=0; int mx1=0; for (int i = 0; i <s.size(); i++) { for (int j = 97; j <=122; j++) { if (mp[char(j)]!=0) { string s1=string(1,char(j))+s[i]; // cout<<s1<<endl; mp1[s1]+=mp[char(j)]; if (mp1[s1]>mx1) { mx1=mp1[s1]; } } } mp[s[i]]++; if (mp[s[i]]>mx) { mx=mp[s[i]]; } } cout<<max(mx,mx1); } signed main(){ fast int t=1; // cin>>t; while(t--) { solve(); } return 0; }
cpp
1285
F
F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.InputThe first line contains an integer nn (2≤n≤1052≤n≤105) — the number of elements in the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1051≤ai≤105) — the elements of the array aa.OutputPrint one integer, the maximum value of the least common multiple of two elements in the array aa.ExamplesInputCopy3 13 35 77 OutputCopy1001InputCopy6 1 2 4 8 16 32 OutputCopy32
[ "binary search", "combinatorics", "number theory" ]
// LUOGU_RID: 101881164 #pragma GCC optimize(3) #pragma GCC target("avx") #pragma GCC optimize("Ofast") #pragma GCC optimize("inline") #pragma GCC optimize("-fgcse") #pragma GCC optimize("-fgcse-lm") #pragma GCC optimize("-fipa-sra") #pragma GCC optimize("-ftree-pre") #pragma GCC optimize("-ftree-vrp") #pragma GCC optimize("-fpeephole2") #pragma GCC optimize("-ffast-math") #pragma GCC optimize("-fsched-spec") #pragma GCC optimize("unroll-loops") #pragma GCC optimize("-falign-jumps") #pragma GCC optimize("-falign-loops") #pragma GCC optimize("-falign-labels") #pragma GCC optimize("-fdevirtualize") #pragma GCC optimize("-fcaller-saves") #pragma GCC optimize("-fcrossjumping") #pragma GCC optimize("-fthread-jumps") #pragma GCC optimize("-funroll-loops") #pragma GCC optimize("-fwhole-program") #pragma GCC optimize("-freorder-blocks") #pragma GCC optimize("-fschedule-insns") #pragma GCC optimize("inline-functions") #pragma GCC optimize("-ftree-tail-merge") #pragma GCC optimize("-fschedule-insns2") #pragma GCC optimize("-fstrict-aliasing") #pragma GCC optimize("-fstrict-overflow") #pragma GCC optimize("-falign-functions") #pragma GCC optimize("-fcse-skip-blocks") #pragma GCC optimize("-fcse-follow-jumps") #pragma GCC optimize("-fsched-interblock") #pragma GCC optimize("-fpartial-inlining") #pragma GCC optimize("no-stack-protector") #pragma GCC optimize("-freorder-functions") #pragma GCC optimize("-findirect-inlining") #pragma GCC optimize("-fhoist-adjacent-loads") #pragma GCC optimize("-frerun-cse-after-loop") #pragma GCC optimize("inline-small-functions") #pragma GCC optimize("-finline-small-functions") #pragma GCC optimize("-ftree-switch-conversion") #pragma GCC optimize("-foptimize-sibling-calls") #pragma GCC optimize("-fexpensive-optimizations") #pragma GCC optimize("-funsafe-loop-optimizations") #pragma GCC optimize("inline-functions-called-once") #pragma GCC optimize("-fdelete-null-pointer-checks") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx") #pragma GCC optimize("Ofast", "inline", "-ffast-math") #include <bits/stdc++.h> using namespace std; mt19937 gen(chrono::system_clock::now().time_since_epoch().count()); uniform_int_distribution <> dist(1, 1e9); const int N = 1e5 + 10; struct Node { int x; long long val; Node() { x = val = 0; } bool operator<(const Node &rhs) const { return val > rhs.val; } } a[N]; int rnd[N]; long long lcm(int a, int b) { return 1ll * b * a / __gcd(a, b); } signed main() { int n; scanf("%d", &n); for (int i = 1; i <= n; ++ i) scanf("%d", &a[i]); if (n <= 2500) { long long ans = 0; for (int i = 1; i <= n; ++ i) for (int j = 1; j <= n; ++ j) ans = max(ans, lcm(a[i].x, a[j].x)); cout << ans << '\n'; } else { for (int i = 1; i <= 35; ++ i) rnd[i] = dist(gen) % n + 1; for (int i = 1; i <= n; ++ i) for (int j = 1; j <= 35; ++ j) a[i].val = max(a[i].val, lcm(a[i].x, a[rnd[j]].x)); sort (a + 1, a + n + 1); long long ans = 0; for (int i = 1; i <= 18; ++ i) for (int j = 1; j <= n; j ++) ans = max(ans, lcm(a[i].x, a[j].x)); for (int i = 1; i <= 1400; ++ i) for (int j = 1; j <= 1400; ++ j) ans = max(ans, lcm(a[i].x, a[j].x)); cout << ans << '\n'; } return 0; }
cpp
1295
C
C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3 aabce ace abacaba aax ty yyt OutputCopy1 -1 3
[ "dp", "greedy", "strings" ]
// Akash Singh #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; //Make less_equal for multiset // find_by_order(k) returns iterator to kth element || order_of_key(k) returns count of elements smaller than k #define deb(x) cout << x << "\n"; #define deb2(x,y) cout << x << " " << y << "\n"; #define debv(v) for(auto e: v) cout << e << " "; cout << '\n'; #define int long long #define ll long long #define mod 1000000007 #define endl "\n" const int N = 0; void solver(); signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int KitniBar = 1; cin >> KitniBar; for(int tc = 1; tc <= KitniBar; tc++) { // cout << "Case #" << tc << ": "; solver(); } return 0; } void solver() { string s, t; cin >> s >> t; vector<int> adj[125]; for(int i = 0; i < s.size(); i++) adj[s[i]].push_back(i); int n = t.size(), indx = -1, ans = 1, i = 0; bool f = true; while(i < n) { auto it = upper_bound(adj[t[i]].begin(), adj[t[i]].end(), indx); if(it == adj[t[i]].end()) { if(f) { cout << "-1\n"; return; } ans++; indx = -1; f = true; } else { // deb2(i, *it); f = false; indx = *it; i++; } } cout << ans << endl; }
cpp
1310
E
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
[ "dp" ]
// LUOGU_RID: 101660289 #include <bits/stdc++.h> #define ll int #define ull unsigned long long using namespace std; const int N=2030; ll dp[N][N],sm[N][N],a[N],mod=998244353,rg,n,k; ll ans=0,smz=0,biao[N]= { 0,1,2,4,6,8,12,16,20,26,33,40,50,61,72,87,104,121,143,167,192,224,259,295,339,387,437,497,563,631,712,801,893,1000,1117,1238,1379,1532,1691,1872,2069,2274,2507,2759,3021,3316,3636,3968,4340,4741,5158,5623,6124,6644,7219,7838,8483,9193,9956,10749,11618,12551,13522,14581,15715,16895,18181,19555,20985,22534,24188,25910,27773,29758,31823,34048,36420,38887,41541,44362,47296,50445,53790,57268,60992,64941,69050,73441,78093,82928,88085,93545,99221,105264,111654,118292,125351,132808,140555,148775,157451,166464,176017,186088,196547,207613,219275,231383,244181,257649,271629,286389,301915,318025,335013,352863,371385,390894,411381,432628,454985,478448,502781,528357,555175,582975,612175,642773,674488,707762,742604,778710,816566,856180,897219,940204,985166,1031733,1080475,1131419,1184169,1239342,1296983,1356651,1419012,1484114,1551500,1621879,1695319,1771308,1850620,1933336,2018911,2108169,2201208,2297430,2397746,2502260,2610330,2722917,2840156,2961358,3087567,3218928,3354697,3495983,3642979,3794876,3952872,4117166,4286898,4463357,4646781,4836231,5033091,5237619,5448835,5668212,5896052,6131274,6375467,6628978,6890664,7162208,7444003,7734806,8036449,8349358,8672217,9006953,9354056,9712125,10083238,10467918,10864668,11275687,11701596,12140784,12595614,13066740,13552450,14055271,14575951,15112644,15668044,16242956,16835452,17448387,18082666,18736202,19412048,20111207,20831484,21576103,22346166,23139309,23959014,24806474,25679197,26580844,27512739,28472234,29463255,30487223,31541332,32629717,33753992,34911161,36105636,37339129,38608483,39918386,41270741,42662175,44097665,45579240,47103389,48675380,50297444,51965815,53686096,55460717,57285728,59167038,61107291,63102267,65158298,67278236,69457647,71703173,74017922,76397220,78848152,81374045,83969977,86643390,89397957,92228464,95142826,98144942,101229335,104404384,107674355,111033430,114490480,118050050,121706096,125467978,129340637,133317637,137408880,141619696,145943379,150390349,154966353,159664278,164495221,169465334,174567181,179812402,185207630,190745063,196437070,202290722,208297832,214471372,220819046,227332236,234024685,240904568,247962863,255214063,262667022,270312228,278164978,286234669,294511456,303011440,311744736,320700935,329897028,339343848,349030595,358975121,369189027,379660902,390409679,401447743,412763223,424375956,436299202,448520551,461060995,473934631,487128517,500664632,514558170,528795598,543400126,558387836,573744623,589494913,605655980,622213039,639191823,656610611,674454125,692749413,711516042,730737958,750443631,770653908,791352191,812568331,834324553,856603433,879436517,902847437,926818156,951381682,976563168,4099492,30514210,57589628,85306270,113700592,142801114,172587556,203098326,234363569,266362239,299134671,332713066,367075477,402264295,438313522,475200581,512969956,551657858,591240712,631765230,673269807,715730192,759195328,803705981,849236828,895839454,943557047,992363494,44068385,95206229,147505623,201023388,255807958,311831397,369153064,427824496,487816780,549192323,612005495,676226453,741920607,809145738,877870910,948164773,21843859,95365195,170556386,247481995,326109113,406513189,488762479,572823307,658774643,746688724,836530571,928383195,24078565,120069544,218198520,318546165,421075572,525877907,633038239,742518685,854414432,968815614,87438920,206872986,328968347,453684991,581127521,711396425,844450483,980399334,121104325,263012188,407993323,556159472,707467342,862037082,21742139,183027245,347773661,516105681,687977935,863522236,44625223,227729465,414728276,605759711,800776548,1678892,205100749,412749672,624776404,841334383,64130169,289810445,520292122,755525204,995674854,242666962,492939183,748420053,11043951,277248052,548968795,826394592,111228413,400148067,695107338,996053224,304938931,618461754,938323134,266485705,599657542,939539742,288103949,642069557,4892619,373288154,749254152,134490686,525722455,924960250,333903686,749288499,174893693,607151626,49831640,499704271,958468342,428149344,905531434,394069384,890533841,398746834,915140080,443519432,980699729,530135973,90380014,660018827,242507025,834655014,440333662,57731445,685428265,327312793,979818225,646807015,326919230,20100260,724960464,445426817,179689898,926376784,689434296,467054085,259635534,67636119,889248517,728401249,583817590,455447951,343727870,249159940,171695795,111790093,69969400,46188140,40920659,54719059,87539191,139876752,212310215,304798556,417858551,552096273,707473286,884529730,85655813,307305317,551796575,819794852,113024420,428561753,768858470,135642780,526016294,942464263,386718944,855908847,354308016,878387151,432324935,15164771,625137557,266450752,936428957,638576648,371863954,137165895,932725142,762810620,626582104,524045397,455989888,423373102,426207739,465318068,541705191,655390132,807231226,31756,230309868,500717009,812347797,166996485,562085284,2271079,484090662,12028957,583770869,202887175,866881439,580516117,342105701,152707995,13629947,923199528,886030181,901732338,970401427,94942626,273271748,507254806,798088920,149020450,556662914,25776488,554406495,146205580,798962253,517814287,301164405,150367985,67122481,51604520,105225544,229759217,425401129,693622328,38028387,455325206,948800819,522142956,173834135,903714902,717312272,613133632,592841130,658538957,810513240,52251704,382438497,803142905,317923380,925559094,629902187,431076077,331469545,331453737,432983464,638551309,948559719,366801210,892362877,529191570,277651498,140454039,118069315,212705191,427186772,762022350,221265904,804352933,515341098,354867194,326002123,429335701,667357683,45025401,559459081,216762560,18516829,963645586,60112845,306128641,704175658,258818528,970168275,842515586,877025705,79229451,446448992,983481097,696012849,583179154,648143130,895002193,326462196,942303951,750303778,749720816,943979940,339280291,933190768,732785659,740935042,958791609,391816817,43072438,912026743,7802752,330148788,882123959,669493206,695721665,962193014,474835362,237326667,251137633,520604731,53140084,846792988,909586559,247405746,858394465,750754246,928855877,396208736,155935508,214407497,573483969,239992650,218808848,511899500,126293510,67131540,336498036,939874412,886191214,177650056,816439290,813532359,171259380,892032030,987121993,458989775,312039446,554340064,190247731,224405547,665205096,517147203,785129294,479629886,601790312,160278279,162409722,611239747,515708618,883486988,719553697,31374085,825237504,109806327,887570467,173980604,967350997,281007176,122022905,494166105,407566421,871467145,891594172,476645036,636292538,376468640,704456494,633884508,169148844,317878624,94165522,500877553,549521545,252909642,614147821,645116879,359128633,759536828,858615088,670184559,199616008,456076342,455678262,204061423,710812730,992593907,57087546,910803590,574489058,52606119,355629098,501385642,496405940,353385464,89009754,708372302,228169324,662209601,21192103,315288343,564234280,775567459,963495893,148434937,334776318,539020624,780538691,69369175,417308184,846208357,366507629,990581601,742800469,630502657,670176204,883460752,281642801,878320815,699460721,753282215,59298265,637292389,501224629,667762630,162827328,993840757,185191395,756677652,723256070,104759855,923677983,197251829,940796077,186540668,941745138,233023941,84833664,510274075,533249412,182755374,470736496,421922611,66384957,416687540,498415967,342744454,962890790,387081216,644128500,751429220,734618126,627204224,445535459,216193513,972158798,734015645,527580220,388856310,335680013,396634600,609039037,991518091,575471572,397817439,478001526,846754595,545917246,594031697,24719103,875998610,174324759,947465042,243725929,81702509,495640411,531883334,213503574,574243060,662056959,501005941,127887212,588805121,910618243,133218512,302672915,446909595,605461704,829682246,148621598,599731023,239714015,95269077,208853774,635554991,406788266,564788163,168367852,246681986,845318641,26866235,818270692,272033193,445824164,374957907,108373769,707657978,211289781,666458813,142263581,671605576,310523780,125163156,153454167,449806808,86269708,100576649,549097486,506350884,13458062,127041193,922419846,445911578,754478669,927830417,12279270,66937845,174250656,380587697,750811208,370171231,285167681,562968847,291743679,519940080,318868546,776183306,945878146,899972768,730988366,493251967,261336543,130967404,158658661,421614882,20628860,12707152,477790317,520088808,200711955,600650281,827648657,945239349,40847139,220591941,552275882,126323616,54387162,405115528,272052035,770724671,974240641,977600013,902112079,821919869,835346437,69590627,598193275,526419836,982245085,49221025,827385502,456150126,16921020,616907451,398326125,445792323,872069933,822324071,386269896,678814317,849983684,992944578,230169981,711427157,536971647,829928506,750518734,399187449,903383119,430407721,82787824,992424335,333898762,211944724,764822284,171031048,539425950,16528792,779694449,949037197,672479592,136938780,461677482,801437079,351137906,234583322,610007792,678772965,571161944,450799257,523942404,925747125,827190849,441382441,906768537,401831311,145013192,281732848,992923671,509575369,978997834,591775204,581173314,105347252,355958340,577531072,932256320,621850941,895346944,922647312,910475842,119628455,720935779,931602258,20940476,166152473,589904096,570285841,294629546,989503045,943810490,351707939,447451356,527518020,793126563,489942277,920573674,297045783,867939978,951036135,762396203,562537736,675979784,328329691,787050094,390700103,369451959,3251647,636280362,512284990,916964169,210969211,639650377,503518932,171271459,898887147,996751988,845467616,711973387,913290115,844052807,780688227,52483577,63204205,100842470,503728417,692194640,962604635,666222051,235036633,974124668,249765682,504305588,58887119,284642544,643429173,465817567,136935902,131604513,790142952,513821731,790845229,975217570,479466794,807406769,327066330,460911231,732340725,520339915,262951627,498388629,618733374,78085995,429958981,81723308,498661857,257155539,773271158,532755233,126559258,985171647,611732006,614114717,441191760,606969926,742019943,310596392,841573218,987086186,227214448,107976234,300123439,300122319,673403661,113468701,130125453,308793816,362830451,821242729,289945655,501048357,5034471,421924217,512004582,840798457,53497858,926994928,52962706,90139005,844955326,925315273,16383964,944380288,341068837,908168052,506406384,779798076,459556610,427694533,353368869,987446457,244502927,810803066,466331324,148513544,570134608,534035904,8331858,727841745,522457414,388330301,88282946,473067291,572997367,176169365,160177726,585170342,267045348,111113539,209972873,404631941,630663703,15891039,425492102,826177200,380139416,981136230,627883151,514503794,567660834,813723420,486753687,542032423,39763648,248006427,156781620,855861479,657153761,579428577,748208609,513357387,926846799,152795869,576643268,289867578,487363763,601905030,756728477,187431881,366486101,455239552,725775579,698612632,570785796,653776272,513833449,386619355,624159464,839830718,310771890,429004335,856331393,910902020,31211249,923636103,951992222,597293686,620678214,425964135,539662322,777393227,587740380,544135714,516412006,997535359,612646536,285633265,556964929,101481071,898630281,543086594,755510445,579659107,655320976,759276753,994142842,55156240,767950734,302840365,403193792,955619908,192811148,911465174,60762306,930597541,384813423,422834218,409401999,261483656,42655397,185654679,667497431,616012872,535634024,465236300,595081431,505128043,297911065,229838918,954863232,644578393,621616629,619668809,874269669,781534711,155203568,298544981,679631588,196363661,223437561,302960421,415707569,13515608,711111667,579817498,145367927,102616550,608808893,271169275,863302053,637904289,278854856,644436632,81821175,355669397,412926362,694414611,54964503,523954378,645471547,359968052,788681183,578339180,757516980,543668132,685352031,307195916,718443169,779550867,708487860,914265514,368626240,385746710,477151865,727231752,554305063,571809873,981656437,307575381,267724556,186540228,690769600,613443344,401302903,790721374,727259790,785195760,815380773,877456509,678366032,184913442,573962746,688844774,615590381,655185331,787354778,222573289,385819653,400649394,601825283,547114325,504156653,937477029,539450670,725832509,97920471,479449229,445348233,730594182,304484480,894786804,382687354,876560383,273561006,592828975,97930544,845841741,13489606,9860998,68421312,514040917,917510780,688308603,308780830,508891301,878693386,66009142,962612313,349447869,35423592,87475629,471775284,173657943,432842386,412943722,273276422,434735230,261832859,94695322,538414491,165565660,500216590,340390443,466957742,598423909,725453495,848234975,881436172,17384986,475986551,377031529,116313095,146616970,791369126,660770759,442876658,674063447,181118811,892086543,567267306,252434553,127166268,173109099,666299275,44529020,516739924,597276795,981825180,123700694,771218496,893689192,186364740,647026179,520412782,750467161,594401455,576251690,898939173,82686046,938126856,937708508,866266355,837669720,592269847,192098560,56599567,205018788,982166672,126610968,938619123,60417736,543727449,991858781,341671185,977129533,805270389,67427416,488407271,285632388,14676454,750097623,29649783,728251065,284545139,556536248,757362815,688661754,547958159,886920909,884824772,86017887,389554799,362382452,901387773,271187862,429145282,639559481,533268963,477399118,109697280,437009732,246573242,558050899,769525916,95771306,948310065,128586186,284645364,239433246,197531416,262176453,669504156,47035150,956016187,65719535,426811397,82878087,133507613,78179433,442537803,778649268,40922458,251593381,425296807,979895406,455498689,336348140,519375925,69001416,954861501,568999861,509858687,250808184,681235443,956325832,62464217,403147748,700827766,466928140,637554148,515176398,149795715,22443053,30396022,776517995,304057563,118663311,392194212,737923023,292227227,807328628,486366474,105656841,18213417,27146017,568185794,610861760,575485082,574289279,205540203,522752620,333270567,879011810,868278398,815981806,629348113,681343498,217569422,822853626,558777805,414816215,675983147,105119088,456129819,732440196,415776134,47436640,362356034,581767393,53878908,265868162,197087158,19715774,994283891,879601062,692140281,487561921,816836420,567642642,607355689,306514041,438405919,706833065,320929650,963820865,198423360,88690196,255514716,136230757,678220326,461778683,820740133,610412824,389074564,415513953,470181881,119235685,566285570,544376546,648805630,57411430,472513135,549839358,460814473,908922894,632604973,822302676,209497342,637437945,348203115,120140171,935484533,111328523,499287897,252518612,781006347,49191678,397551074,369547591,57602174,29628582,981866228,172305602,419451595,608755665,183579945,251157466,910564423,826106642,423353828,47391678,608297608,884565347,500283800,646314918,483212749,942783583,533742331,829699471,109690883,222547425,198046322,687692016,924422819,424788175,250113151,46671996,852255937,180806582,123215899,281116366,646137554,798974091,939664901,580003018,819694156,499911123,686681966,44025974,86828623,479361944,482795682,334082239,331747923,373923999,459103235,562543041,261299985,357067424,542958458,116393997,725573864,826163315,476472589,219872186,312144263,617781034,620954098,426198734,746432063,53622136,342557307,225740431,205602345,221155702,823277998,601212187,480384464,3535769,887816399,102725500,223963789,159050633,957392975,291875829,301770979,178251381,728053808,388998366,538921108,179429083,90842450,896984163,845866725,122285137,646599177,966297568,728006335,210666282,313205620,203101314,571117110,732363248,433621931,836581792,728542915,497481491,837532722,68797065,281347647,765049368,431670062,143738365,844354663,103557556,616285894,52186140,692847745,146205666,859772859,908168103,866663048,42575440,356511459,430929446,493996760,391715441,858619339,120258044,10774654,456000940,744986166,779480405,750308184,85974036,821455289,495322621,747106472,829809642,699519098,291060249,144604665,718685165,322228492,861716848,385148203,647733719,11142634,187678686,471448817,752910717,504844089,638316867,660145656,887190178,938205410,22685276,389776982,455169670,216818093,953907225,966859160,134545046,857012024,414108695,653238616,200909244,401726601,175532403,462982324,780720725,211227999,114449495,274266061,34860355,279450347,162224033,387607811,470355417,36014479,254116262,376210714,605592670,685596838,713699658,579729932,705253438,149500294,596855417,261947189,275875218,236676089,258331666,666770221,88077034,649645173,994703633,891533801,606738414,218132987,757084516,748798616,834053130,435907800,454848061,225665108,684348765,240747497,51017762,696074989,220363945,736578462,606792767,636112630,38860062,83231486,476715801,669911334,983215395,163307065,37203372,117426394,327612522,26518142,60111240,673141579,902792264,80512222,916641064,282895284,139918703,821383558,185688185,979945249,317045299,195576536,313768729,709417768,698383262,84918327,993882020,224386598,846662841,248552502,869960735,229613930,130244107,840523811,490144985,475944810,72111343,190112496,170340,958784367,949925569,89317722,205789585,331483534,713405904,747573452,801813954,441614579,818479730,832456776,557414216,102873697,91804879,302528568,6951786,751955981,223243330,55924757,929576348,637192543,395141788,223041477,226038587,419289643,377266189,732673109,520809215,85910357,806463433,963649584,896936296,954598470,891351471,270553404,635101334,453581286,742501526,476757332,75450402,249184754,637400501,859528283,565150907,299445750,133382188,899310419,302600188,119353704,622678142,923468026,773351888,143508061,806988289,758134418,930612039,33005788,565782753,700837546,345657600,796738642,736132589,545470203,603207283,382769936,24466838,277829946,697786903,470647192,17813970,268061582,746430442,850508249,189199847,921549557,735647740,223317638,490981509,827724999,128410260,755745874,930465676,165634029,403513576,124905360,788468406,248407584,578709202,525013854,177342297,556707812,34961665,278191847,609205586,372126098,163907792,963136209,447993159,496047089,117653547,679828181,713471676,629064912,863216292,962508869,128274828,241791128,247384760,523436716,791735602,778639832,444330549,739656161,571437254,887142803,279942023,233828457,106060063,535941826,7924040,707429221,751629473,36517261,17755331,712729289,865451558,646409217,416607917,200692067,336641799,979387316,888416017,31441130,812551235,183568672,212932908,31424549,241309553,500637949,140847875,895968732,507531234,989819307,704222810,968377693,990420049,247715974,154506580,613966233,731438735,544753645,174851692,867009055,819581331,900249795,33976925,115700533,306832774,744165078,590225935,847228311,421781113,303456866,905212099,464688273,385135389,66986870,648381623,543616219,726650628,830838423,881299720,30430100,553617,49082078,118721011,637730178,726601839,743225133,447119252,463146180,208385423,406090433,847940444,660655236,187362725,53963296,760978639,935870485,727985672,694013267,421472410,278749113,574270987,548985657,507424656,218051871,279660929,659280914,311132094,913499526,843714904,972816220,801302355,867476364,721533143,431879083,476638337,848673933,955413763,6814103,222642992,129999699,472751165,506490940,675251949,84218479,833073632,104687862,198676209,902164536,963080920,738674105,550935311,561012005,59856346,770931835,143486216,284759565,215939822,548445724,129434351,171623440,359327454}; bool dfs(ll pos,ll lst) { if (smz>70)return 0; vector<ll> now; for (ll i=1; i<=pos-1; i++) { now.push_back(a[i]); } for (ll i=1; i<k; i++) { ll aft=0; for (ll j=now.size()-1; j>=0; j--) aft+=now[j]*(now.size()-j); if (aft>n)return 0; if (i==k-1)break; vector<ll> vct; for (ll j=now.size()-1; j>=0; j--) { for (ll l=0; l<now[j]; l++) { vct.push_back(now.size()-j); } } now=vct; } ans++; for (ll i=lst;i<=70; i++) { a[pos]=i; smz+=i; bool f=dfs(pos+1,i); smz-=i; if (!f)break; } return 1; } int main() { cin >> n >> k; if (k>=11) { puts("1"); return 0; } if (k==1) { dp[0][0]=1; sm[0][0]=1; ll ans=0; for (ll i=1; i<=n; i++) { for (ll j=1; j<=i; j++) { dp[i][j]=sm[i-j][min(i-j,j)]; ans+=dp[i][j]; ans%=mod; sm[i][j]=sm[i][j-1]+dp[i][j]; sm[i][j]%=mod; } } cout<<ans<< endl; } else if (k==2) { cout << biao[n]%mod<< endl; } else { dfs(1,1); cout<<(ans-1+mod)%mod<< endl; } return 0; }
cpp
1316
D
D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters  — UU, DD, LL, RR or XX  — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103)  — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2 1 1 1 1 2 2 2 2 OutputCopyVALID XL RX InputCopy3 -1 -1 -1 -1 -1 -1 -1 -1 2 2 -1 -1 -1 -1 -1 -1 -1 -1 OutputCopyVALID RRD UXD ULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below :
[ "constructive algorithms", "dfs and similar", "graphs", "implementation" ]
#include <bits/stdc++.h> #include <ext/pb_ds/detail/standard_policies.hpp> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #define FIO ios::sync_with_stdio(false); cin.tie(nullptr) #define TC(t) int t; cin >> t; for(int i = 1; i <= t; i++) #define ll int #define ull unsigned long long int #define lll __int128 #define lld long double #define loop(i, a, b) for(ll i = a; i <= b; i++) #define loop2(i, b, a) for(ll i = b; i >= a; i--) #define ini(x, y) memset(x, y, sizeof(x)) #define all(x) x.begin(), x.end() #define all2(x) x.rbegin(), x.rend() #define sz(x) (ll)x.size() #define pb push_back #define ppb pop_back #define mp make_pair #define ff first #define ss second #define M 1000000007 #define endl '\n' #define bits(x) __builtin_popcountll(x) #define zrbits(x) __builtin_ctzll(x) #define vl vector<ll> #define pll pair<ll,ll> #define vpll vector<pll> #define uni(x) x.erase(unique(all(x)), x.end()) #define ordered_set tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> #define multi_ordered_set tree<ll, null_type, less_equal<ll>, rb_tree_tag, tree_order_statistics_node_update> #define mxheap priority_queue<ll> #define mnheap priority_queue<ll, vector<ll>, greater<ll>> #define mxheap2 priority_queue<pair<ll,ll>> #define mnheap2 priority_queue<pair<ll,ll>, vector<pair<ll,ll>>, greater<pair<ll,ll>>> const int N = 1e6 + 5; const int L = 20; const int MX = 1e9 + 10; const ll INF = 1e18; const int dx[] = {0, -1, 0, 1, -1, -1, 1, 1}; const int dy[] = {1, 0, -1, 0, 1, -1, -1, 1}; using namespace std; using namespace __gnu_pbds; inline ll uceil(ll a,ll b) {return (a % b ? a / b + 1 : a / b);} inline ll mod(ll x) {return ( (x % M + M) % M );} ll ulog(ll val, ll base) {ll cnt = 0; val /= base; while(val) {cnt++; val /= base;} return cnt;} ll power(ll a, ll b) {ll res = 1; while (b) {if (b & 1) res = res * a; a = a * a; b >>= 1;} return res;} ll modpow(ll a, ll b) {ll res = 1; while (b) {if (b & 1) res = res * a % M; a = a * a % M; b >>= 1;} return res;} #ifdef FARHAN #define deb(x) cerr << #x << " = " << x << endl; #define deb2(x, y) cerr << #x << " = " << x << ", " << #y << " = " << y << endl; #define deb3(x, y, z) cerr << #x << " = " << x << ", " << #y << " = " << y << ", " << #z << " = " << z << endl; #define deb4() cerr << endl; #define done cerr << "Line " << __LINE__ << " is done" << endl; #else #define deb(x) #define deb2(x, y) #define deb3(x, y, z) #define deb4() #define done #endif template<typename T> ostream& operator<<(ostream& os, const vector<T>& v) {for(auto& x : v) os << x << " "; return os;} template<typename T> ostream& operator<<(ostream& os, const set<T>& v) {for(auto& x : v) os << x << " "; return os;} template<typename T, typename S> ostream& operator<<(ostream& os, const pair<T, S>& p) {os << p.first << ' ' << p.second; return os;} template<typename... T> void in(T&... args) {((cin >> args), ...);} template<typename... T> void out(T&&... args) {((cout << args << endl), ...);} template<typename... T> void out2(T&&... args) {((cout << args << " "), ...);} template<typename... T> void out3(T&&... args) {((cout << args << " "), ...); cout << endl;} vector<ll> g[N], vis(N); bool valid(ll i, ll j, ll n) { return (i >= 0 && i < n && j >= 0 && j < n); } ll create(ll i, ll j, ll n) { return (i * n + j); } pll decode(ll node, ll n) { return {node / n, node % n}; } char findchar(pll prev, pll cur) { if(prev.ff == cur.ff) { if(prev.ss < cur.ss) return 'L'; else return 'R'; } else { if(prev.ff < cur.ff) return 'U'; else return 'D'; } } void dfs(ll node, ll par, ll n, vector<vector<char>>& ans) { vis[node] = 1; for(auto child : g[node]) { if(!vis[child]) { pll cur = decode(child, n); pll prev = decode(node, n); char ch = findchar(prev, cur); ans[cur.ff][cur.ss] = ch; dfs(child, node, n, ans); } } } void dfs2(ll node, vector<vector<char>>& ans, pll tar, vector<vector<pll>>& a) { vis[node] = 1; loop(k, 0, 3) { ll i, j; tie(i, j) = decode(node, sz(ans)); ll ii = i + dx[k]; ll jj = j + dy[k]; if(valid(ii, jj, sz(ans))) { ll child = create(ii, jj, sz(ans)); if(!vis[child]) { pll cur = decode(child, sz(ans)); pll prev = decode(node, sz(ans)); if(a[cur.ff][cur.ss] == tar) { char ch = findchar(prev, cur); ans[cur.ff][cur.ss] = ch; dfs2(child, ans, tar, a); } } } } } void solve() { ll n; cin >> n; vector<vector<pll>> a(n, vector<pll>(n)); for(ll i = 0; i < n; i++) { for(ll j = 0; j < n; j++) { cin >> a[i][j].ff >> a[i][j].ss; } } // id ... 1 = cycle, 2 = fix, 3 = general vector<vector<ll>> info(n, vector<ll>(n)); loop(i, 0, n - 1) { loop(j, 0, n - 1) { if(a[i][j].ff == -1) info[i][j] = 1; else if(a[i][j].ff - 1 == i && a[i][j].ss - 1 == j) info[i][j] = 2; else info[i][j] = 3; } } // checking for cycle, id = 1 loop(i, 0, n - 1) { loop(j, 0, n - 1) { loop(k, 0, 3) { ll ii = i + dx[k], jj = j + dy[k]; if(valid(ii, jj, n) && info[i][j] == 1 && info[ii][jj] == 1) { ll u = create(i, j, n); ll v = create(ii, jj, n); g[u].pb(v); g[v].pb(u); } } } } vector<vector<char>> ans(n, vector<char>(n, '#')); loop(p, 0, n - 1) { loop(q, 0, n - 1) { ll node = create(p, q, n); if(!vis[node] && info[p][q] == 1) { loop(k, 0, 3) { ll pp = p + dx[k]; ll qq = q + dy[k]; if(valid(pp, qq, n) && info[pp][qq] == 1) { ll child = create(pp, qq, n); vis[child] = 1; vis[node] = 1; ans[p][q] = findchar({pp, qq}, {p, q}); ans[pp][qq] = findchar({p, q}, {pp, qq}); dfs(node, -1, n, ans); dfs(child, -1, n, ans); } } } } } loop(i, 0, n - 1) { loop(j, 0, n - 1) { if(info[i][j] == 2) { ans[i][j] = 'X'; ll node = create(i, j, n); vis[node] = 1; dfs2(node, ans, {i + 1, j + 1}, a); } } } loop(i, 0, n - 1) { loop(j, 0, n - 1) { if(ans[i][j] == '#') { cout << "INVALID" << endl; return; } } } cout << "VALID" << endl; loop(i, 0, n - 1) { loop(j, 0, n - 1) { cout << ans[i][j]; } cout << endl; } } signed main () { #ifdef FARHAN freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif FIO; // TC(t) solve(); return 0; }
cpp
1304
F1
F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤min(m,20)1≤k≤min(m,20)) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2 0 2 1 1 0 0 0 3 1 2 1 0 4 3 1 3 3 0 0 4 OutputCopy25 InputCopy3 3 1 1 2 3 4 5 6 7 8 9 OutputCopy31 InputCopy3 3 2 1 2 3 4 5 6 7 8 9 OutputCopy44 InputCopy3 3 3 1 2 3 4 5 6 7 8 9 OutputCopy45 NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4:
[ "data structures", "dp" ]
#include<bits/stdc++.h> using namespace std; int dp[51][20009]; int a[51][20009]; int pf[51][20009]; int st[80009]; int lazy[80009]; void push(int id){ if (lazy[id]==0)return; st[id*2]+=lazy[id]; st[id*2+1]+=lazy[id]; lazy[id*2]+=lazy[id]; lazy[id*2+1]+=lazy[id]; lazy[id]=0; } void update(int id,int l,int r,int u,int v,int val){ if (l>v||r<u||u>v)return; if (u<=l&&r<=v){ st[id]+=val; lazy[id]+=val; return; } int mid=(l+r)/2; push(id); update(id*2,l,mid,u,v,val); update(id*2+1,mid+1,r,u,v,val); st[id]=max(st[id*2],st[id*2+1]); } int get(int id,int l,int r,int u,int v){ if (l>v||r<u||u>v)return 0; if (u<=l&&r<=v){ return st[id]; } push(id); int mid=(l+r)/2; return max(get(id*2,l,mid,u,v),get(id*2+1,mid+1,r,u,v)); } signed main(){ ios_base::sync_with_stdio(NULL); cin.tie(nullptr); //freopen("usaco.INP","r",stdin); //freopen("usaco.ANS","w",stdout); int n,m,k; cin>>n>>m>>k; for (int i=1;i<=n;i++){ for (int j=1;j<=m;j++){ cin>>a[i][j]; pf[i][j]=pf[i][j-1]+a[i][j]; } } for (int i=k;i<=m;i++){ dp[1][i]=pf[1][i]-pf[1][i-k]; } for (int i=2;i<=n;i++){ deque<int>id; memset(st,0,sizeof(st)); memset(lazy,0,sizeof(lazy)); for (int j=k;j<=m;j++){ update(1,1,m,j,j,dp[i-1][j]); } for (int j=k;j<=m;j++){ while (!id.empty()&&j-1-k>=id.front())id.pop_front(); if (!id.empty()){ int fi=id.front(),se=id.back(); update(1,1,m,fi,se,a[i][j-k]); //cerr<<fi<<" "<<se<<" "<<j<<'\n'; } dp[i][j]=get(1,1,m,k,j)+pf[i][j]-pf[i][j-k]; //if (i==4&&j==m)cerr<<pf[i][j]-pf[i][j-k]<<'\n'; id.push_back(j); } memset(st,0,sizeof(st)); memset(lazy,0,sizeof(lazy)); for (int j=k;j<=m;j++){ update(1,1,m,j,j,dp[i-1][j]); } id.clear(); for (int j=m;j>=k;j--){ while (!id.empty()&&id.front()-k>=j+1)id.pop_front(); if (!id.empty()){ int fi=id.back(),se=id.front(); update(1,1,m,fi,se,a[i][j+1]); //cerr<<fi<<" "<<se<<" "<<i<<" "<<j<<'\n'; } dp[i][j]=max(dp[i][j],get(1,1,m,j,m)+pf[i][j]-pf[i][j-k]); id.push_back(j); } } int ans=0; for (int i=k;i<=m;i++){ ans=max(ans,dp[n][i]); } cout<<ans; }
cpp
1322
E
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.
[ "data structures" ]
// BEGIN BOILERPLATE CODE #include <bits/stdc++.h> using namespace std; #ifdef KAMIRULEZ const bool kami_loc = true; const long long kami_seed = 69420; #else const bool kami_loc = false; const long long kami_seed = chrono::steady_clock::now().time_since_epoch().count(); #endif const string kami_fi = "kamirulez.inp"; const string kami_fo = "kamirulez.out"; mt19937_64 kami_gen(kami_seed); long long rand_range(long long rmin, long long rmax) { uniform_int_distribution<long long> rdist(rmin, rmax); return rdist(kami_gen); } long double rand_real(long double rmin, long double rmax) { uniform_real_distribution<long double> rdist(rmin, rmax); return rdist(kami_gen); } void file_io(string fi, string fo) { if (fi != "" && (!kami_loc || fi == kami_fi)) { freopen(fi.c_str(), "r", stdin); } if (fo != "" && (!kami_loc || fo == kami_fo)) { freopen(fo.c_str(), "w", stdout); } } void set_up() { if (kami_loc) { file_io(kami_fi, kami_fo); } ios_base::sync_with_stdio(0); cin.tie(0); } void just_do_it(); void just_exec_it() { if (kami_loc) { auto pstart = chrono::steady_clock::now(); just_do_it(); auto pend = chrono::steady_clock::now(); long long ptime = chrono::duration_cast<chrono::milliseconds>(pend - pstart).count(); string bar(50, '='); cout << '\n' << bar << '\n'; cout << "Time: " << ptime << " ms" << '\n'; } else { just_do_it(); } } int main() { set_up(); just_exec_it(); return 0; } // END BOILERPLATE CODE // BEGIN MAIN CODE const int ms = 5e5 + 20; const int inf = 1e9 + 20; int a[ms]; pair<int, int> p[ms]; int b[ms]; int res[ms]; int pos; void fix(int &lt, int &rt) { if (lt == 0) { lt = -inf; rt = inf; } else if (b[lt] == 1 && b[rt] == 1) { lt = -inf; rt = inf; } else if (b[lt] == 2 && b[rt] == 1) { rt = (lt + rt) / 2; } else if (b[lt] == 1 && b[rt] == 2) { lt = (lt + rt) / 2 + 1; } } void inter(int &l1, int &r1, int l2, int r2) { if (l1 > r1 || l2 == -inf) { return; } if (l1 <= min(r1, l2 - 1)) { r1 = min(r1, l2 - 1); } else if (max(l1, r2 + 1) <= r1) { l1 = max(l1, r2 + 1); } else { l1 = inf; r1 = -inf; } } void update(int l1, int r1, int l2, int r2, int l3, int r3, int val) { fix(l1, r1); if (l1 == -inf) { return; } b[pos] = 1; fix(l2, r2); fix(l3, r3); b[pos] = 2; inter(l1, r1, l2, r2); inter(l1, r1, l3, r3); for (int i = l1; i <= r1; i++) { if (res[i] != -1) { exit(0); } res[i] = val; } } void just_do_it() { int n; cin >> n; set<pair<int, int>> s; multiset<int> len; for (int i = 1; i <= n; i++) { cin >> a[i]; p[i] = {a[i], i}; b[i] = 1; res[i] = -1; s.insert({i, i}); len.insert(1); } int mx = 1; sort(p + 1, p + n + 1, greater<>()); for (int i = 1; i <= n; i++) { int val = p[i].first; pos = p[i].second; auto it = prev(s.upper_bound({pos, 1e9 + 20})); int l2 = (*it).first; int r2 = (*it).second; int l1 = (l2 == 1 ? -1 : prev(it)->first); int r1 = (l2 == 1 ? -1 : prev(it)->second); int l3 = (r2 == n ? -1 : next(it)->first); int r3 = (r2 == n ? -1 : next(it)->second); b[pos] = 2; if (l2 == r2 && l2 > 1 && r2 < n) { update(l1, r3, l1, r1, l3, r3, val); s.erase({l1, r1}); len.erase(len.find(r1 - l1 + 1)); s.erase({l2, r2}); len.erase(len.find(r2 - l2 + 1)); s.erase({l3, r3}); len.erase(len.find(r3 - l3 + 1)); s.insert({l1, r3}); len.insert(r3 - l1 + 1); } else { s.erase({l2, r2}); len.erase(len.find(r2 - l2 + 1)); if (pos > l2) { update(l2, pos - 1, l2, r2, 0, 0, val); s.insert({l2, pos - 1}); len.insert(pos - l2); } if (pos < r2) { update(pos + 1, r2, l2, r2, 0, 0, val); s.insert({pos + 1, r2}); len.insert(r2 - pos); } if (pos == l2 && l2 > 1) { update(l1, pos, l1, r1, 0, 0, val); s.erase({l1, r1}); len.erase(len.find(r1 - l1 + 1)); s.insert({l1, pos}); len.insert(pos - l1 + 1); } else if (pos == r2 && r2 < n) { update(pos, r3, l3, r3, 0, 0, val); s.erase({l3, r3}); len.erase(len.find(r3 - l3 + 1)); s.insert({pos, r3}); len.insert(r3 - pos + 1); } else { update(pos, pos, l2, r2, 0, 0, val); s.insert({pos, pos}); len.insert(1); } } if (val != p[i + 1].first) { mx = max(mx, *len.rbegin()); } } cout << (mx - 1) / 2 << '\n'; for (int i = 1; i <= n; i++) { cout << res[i] << " "; } } // END MAIN CODE
cpp
1294
C
C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5 64 32 97 2 12345 OutputCopyYES 2 4 8 NO NO NO YES 3 5 823
[ "greedy", "math", "number theory" ]
//#pragma GCC optimize("Ofast") //#pragma GCC target("avx,avx2,fma") //#pragma GCC optimization("unroll-loops") #include <bits/stdc++.h> #define ll long long #define ff first #define ss second #define pb push_back #define pf push_front #define UseOFF ios_base::sync_with_stdio(0);cin.tie(0), cout.tie(0); #define sz size using namespace std ; const ll N = 1e6 + 111 ; const ll mod = 1e9 + 7 ; ll a[ N ] ; ll num ; int main() { UseOFF //freopen( "A.in","r",stdin ) ; //freopen("A.out","w",stdout) ; //underidoderidoderooderiododoogovehment ( Winston Cherchil ) ; ll t ; cin >> t ; while( t-- ) { ll n ; cin >> n ; ll a = 0, b = 0, c = 0 ; for( int i = 2 ; i <= sqrt( n ) ; i++ ) { if( n % i == 0 ) { a = i ; n /= i ; break ; } } for( int i = 2 ; i <= sqrt( n ) ; i++ ) { if( n % i == 0 && i != a ) { b = i ; if( n / b != b ) { c = n / b ; } break ; } } if( a > 0 && b > 0 && c > 0 ) cout << "YES" << '\n' << a << " " << b << " " << c << '\n' ; else cout << "NO" << '\n' ; } }
cpp
1304
F2
F2. Animal Observation (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤m1≤k≤m) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2 0 2 1 1 0 0 0 3 1 2 1 0 4 3 1 3 3 0 0 4 OutputCopy25 InputCopy3 3 1 1 2 3 4 5 6 7 8 9 OutputCopy31 InputCopy3 3 2 1 2 3 4 5 6 7 8 9 OutputCopy44 InputCopy3 3 3 1 2 3 4 5 6 7 8 9 OutputCopy45 NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4:
[ "data structures", "dp", "greedy" ]
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #define fi first #define se second #define ll long long #define ld long double #define sz(x) ((int)(x).size()) #define all(x) (x).begin(), (x).end() #define pb push_back #define mpp make_pair #define ve vector using namespace std; using namespace __gnu_pbds; template<class T> using oset = tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>; const ll inf = 1e18; const int iinf = 1e9; typedef pair<ll, ll> pll; typedef pair<int, int> pii; mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); template <typename T> inline bool chmin(T& a, T b) { return (a > b ? a = b, 1 : 0); } template <typename T> inline bool chmax(T& a, T b) { return (a < b ? a = b, 1 : 0); } const int N = 2e4 + 100; int a[N]; int t[4 * N], p[4 * N]; inline void build(int v, int vl, int vr) { p[v] = 0; if (vl == vr) return void(t[v] = a[vl]); int m = vl + vr >> 1; build(2 * v + 1, vl, m); build(2 * v + 2, m + 1, vr); t[v] = max(t[2 * v + 1], t[2 * v + 2]); } inline void push(int v) { if (!p[v]) return; p[2 * v + 1] += p[v], p[2 * v + 2] += p[v]; t[2 * v + 1] += p[v], t[2 * v + 2] += p[v]; p[v] = 0; } inline void upd(int v, int vl, int vr, int l, int r, int x) { if (l > r) return; else if (vl == l && vr == r) { t[v] += x, p[v] += x; return; } push(v); int m = vl + vr >> 1; upd(2 * v + 1, vl, m, l, min(r, m), x); upd(2 * v + 2, m + 1, vr, max(l, m + 1), r, x); t[v] = max(t[2 * v + 1], t[2 * v + 2]); } inline int gt(int v, int vl, int vr, int l, int r) { if (l > r) return -iinf; else if (vl == l && vr == r) return t[v]; push(v); int m = vl + vr >> 1; return max(gt(2 * v + 1, vl, m, l, min(r, m)), gt(2 * v + 2, m + 1, vr, max(l, m + 1), r)); } inline void solve() { int n, m, k; cin >> n >> m >> k; ve<ve<int>> ar(n, ve<int> (m)); for (auto &i : ar) for (auto &j : i) cin >> j; ve<ve<int>> pf(n, ve<int> (m)); for (int i = 0; i < n; ++i) { pf[i] = ar[i]; for (int j = 1; j < m; ++j) pf[i][j] += pf[i][j - 1]; } auto get = [&](int i, int l, int r) { return pf[i][r] - (!l ? 0 : pf[i][l - 1]); }; auto cost = [&](int i, int j) { int res = 0; res += get(i, j, j + k - 1); if (i + 1 < n) res += get(i + 1, j, j + k - 1); return res; }; int s = m - k + 1; ve<ve<int>> dp(n, ve<int> (m)); for (int i = 0; i < s; ++i) dp[0][i] = cost(0, i); for (int z = 1; z < n; ++z) { for (int i = 0; i < s; ++i) { int value = 0; value += dp[z - 1][i]; int L = max(0, i), R = min(k - 1, i + k - 1); if (L <= R) value -= get(z, L, R); a[i] = value; } build(0, 0, s - 1); for (int ps = 0; ps < s; ++ps) { dp[z][ps] = cost(z, ps) + t[0]; upd(0, 0, s - 1, max(ps - k + 1, 0), ps, +ar[z][ps]); if (ps + k < m) upd(0, 0, s - 1, ps + 1, min(s - 1, ps + k), -ar[z][ps + k]); /* for (int p = 0; p < s; ++p) { int L = max(ps, p); int R = min(ps + k - 1, p + k - 1); int sum = (L > R ? 0 : get(z, L, R)); chmax(dp[z][ps], cost(z, ps) - sum + dp[z - 1][p]); } */ } } cout << *max_element(all(dp[n - 1])); } signed main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int q = 1; // cin >> q; while (q--) solve(); cerr << fixed << setprecision(3) << "Time execution: " << (double)clock() / CLOCKS_PER_SEC << endl; }
cpp
1310
E
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
[ "dp" ]
#pragma GCC optimize("Ofast") #include<bits/stdc++.h> #define int long long #define elif else if #define ALL(x) x.begin(),x.end() #define lowbit(x) (x&(-x)) using namespace std; void fileio(const string &s) { freopen((s+".in").c_str(),"r",stdin); freopen((s+".out").c_str(),"w",stdout); } const int INF=4e18; inline int read() { int x=0; bool flag=1; char c=getchar(); while(c<'0'||c>'9') { if(c=='-') flag=0; c=getchar(); } while(c>='0'&&c<='9') { x=(x<<1)+(x<<3)+c-'0'; c=getchar(); } return (flag?x:~(x-1)); } const int mod=998244353; int n,k,ans,f[2030],a[100],b[2030],c[2030]; bool check(int len) { for(int i=1;i<=len;i++) b[i]=a[i]; for(int i=1;i<k;i++) { int sum=0,cnt=0; for(int l=1;l<=len;l++) sum+=l*b[l]; if(sum>n) return 0; for(int l=len;l;l--) while(b[l]--) c[++cnt]=l; for(int l=1;l<=cnt;l++) b[l]=c[l]; len=cnt; } return 1; } void dfs(int x,int rst,int lim) { if(x>1) (ans+=check(x-1))%=mod; if(!rst) return ; for(int i=1;i<=min(rst,lim);i++) { a[x]=i; dfs(x+1,rst-i,i); } } signed main() { n=read(); k=read(); if(k==1) { f[0]=1; for(int i=1;i<=n;i++) { for(int l=i;l<=n;l++) (f[l]+=f[l-i])%=mod; (ans+=f[i])%=mod; } cout<<ans; } elif(k==2) { f[0]=1; for(int i=1;i<=n;i++) { for(int l=i*(i+1)/2;l<=n;l++) (f[l]+=f[l-i*(i+1)/2])%=mod; (ans+=f[i])%=mod; } cout<<ans; } else { dfs(1,min(n,64ll),64); cout<<ans; } return 0; }
cpp
1316
F
F. Battalion Strengthtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn officers in the Army of Byteland. Each officer has some power associated with him. The power of the ii-th officer is denoted by pipi. As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these nn officers and calls this subset a battalion.(All 2n2n subsets of the nn officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be a1,a2,…,aka1,a2,…,ak, where a1≤a2≤⋯≤aka1≤a2≤⋯≤ak. The strength of this battalion is equal to a1a2+a2a3+⋯+ak−1aka1a2+a2a3+⋯+ak−1ak. (If the size of Battalion is ≤1≤1, then the strength of this battalion is 00).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be qq changes. Each one of the form ii xx indicating that pipi is changed to xx.You need to find the strength of the army initially and after each of these qq updates.Note that the changes are permanent.The strength should be found by modulo 109+7109+7. Formally, let M=109+7M=109+7. It can be shown that the answer can be expressed as an irreducible fraction p/qp/q, where pp and qq are integers and q≢0modMq≢0modM). Output the integer equal to p⋅q−1modMp⋅q−1modM. In other words, output such an integer xx that 0≤x<M0≤x<M and x⋅q≡pmodMx⋅q≡pmodM).InputThe first line of the input contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105)  — the number of officers in Byteland's Army.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤1091≤pi≤109).The third line contains a single integer qq (1≤q≤3⋅1051≤q≤3⋅105)  — the number of updates.Each of the next qq lines contains two integers ii and xx (1≤i≤n1≤i≤n, 1≤x≤1091≤x≤109), indicating that pipi is updated to xx .OutputIn the first line output the initial strength of the army.In ii-th of the next qq lines, output the strength of the army after ii-th update.ExamplesInputCopy2 1 2 2 1 2 2 1 OutputCopy500000004 1 500000004 InputCopy4 1 2 3 4 4 1 5 2 5 3 5 4 5 OutputCopy625000011 13 62500020 375000027 62500027 NoteIn first testcase; initially; there are four possible battalions {} Strength = 00 {11} Strength = 00 {22} Strength = 00 {1,21,2} Strength = 22 So strength of army is 0+0+0+240+0+0+24 = 1212After changing p1p1 to 22, strength of battallion {1,21,2} changes to 44, so strength of army becomes 11.After changing p2p2 to 11, strength of battalion {1,21,2} again becomes 22, so strength of army becomes 1212.
[ "data structures", "divide and conquer", "probabilities" ]
// LUOGU_RID: 99436832 #pragma GCC optimize(2,3,"Ofast","inline","unroll-loops") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native") #include<bits/stdc++.h> #define ll long long #define ls (t<<1) #define rs ((t<<1)|1) using namespace std; const int md=1e9+7,N=300010; int tmp[N<<1],d[N],c[N],p[N],a[N],b[N],m,n,q; struct Tree{ int sum,cnt,pre,suf; }T[4000010]; void update(int t) { T[t].cnt=T[ls].cnt+T[rs].cnt; T[t].pre=(T[ls].pre+(ll)T[rs].pre*c[T[ls].cnt])%md; T[t].suf=(T[rs].suf+(ll)T[ls].suf*c[T[rs].cnt])%md; T[t].sum=(T[ls].sum+T[rs].sum+(ll)T[ls].suf*T[rs].pre)%md; return; } void change(int t,int l,int r,int x,int y) { // cout<<t<<" "<<l<<" "<<r<<" "<<x<<" "<<y<<endl; if (l==r) { T[t].cnt+=y; if (y>0) { T[t].sum=(T[t].sum+(ll)T[t].suf*tmp[x]%md*c[1])%md; T[t].pre=((ll)T[t].pre*c[1]+(ll)tmp[x]*c[1])%md; T[t].suf=T[t].pre; } else { T[t].pre=((T[t].pre*2-tmp[x])%md+md)%md; T[t].suf=T[t].pre; T[t].sum=((T[t].sum-(ll)T[t].suf*tmp[x]%md*c[1])%md+md)%md; } return; } int mid=(l+r)>>1; if (x<=mid)change(ls,l,mid,x,y); else change(rs,mid+1,r,x,y); update(t); return; } int getpos(int x) { return lower_bound(tmp+1,tmp+m+1,x)-tmp; } int fpow(int a,int b) { int ret=1; for (;b;b>>=1,a=1ll*a*a%md) { if (b&1) ret=1ll*ret*a%md; } return ret; } int main() { scanf("%d",&n); for (int i=1;i<=n;i++) { scanf("%d",&p[i]); tmp[++m]=p[i]; } d[0]=1; d[1]=2; c[0]=1; c[1]=fpow(2,md-2); for (int i=2;i<=n;i++) d[i]=(ll)d[i-1]*d[1]%md, c[i]=(ll)c[i-1]*c[1]%md; scanf("%d",&q); for (int i=1;i<=q;i++) { scanf("%d%d",&a[i],&b[i]); tmp[++m]=b[i]; } sort(tmp+1,tmp+m+1); m=unique(tmp+1,tmp+m+1)-tmp-1; for (int i=1;i<=n;i++) change(1,1,m,getpos(p[i]),1); // cout<<"SBZHZX"<<endl<<endl; printf("%d\n",T[1].sum); for (int i=1,x,y;i<=q;i++) { // cout<<i<<endl<<endl; x=a[i],y=b[i]; change(1,1,m,getpos(p[x]),-1); p[x]=y; change(1,1,m,getpos(p[x]),1); printf("%d\n",T[1].sum); } return 0; }
cpp
1296
F
F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4 1 2 3 2 3 4 2 1 2 5 1 3 3 OutputCopy5 3 5 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 OutputCopy5 3 1 2 1 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 OutputCopy-1
[ "constructive algorithms", "dfs and similar", "greedy", "sortings", "trees" ]
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll,ll> pll; #define MP make_pair #define MAXN 5069 #define LL_MIN LONG_LONG_MIN #define LL_MAX LONG_LONG_MAX pll p[MAXN]; vector<ll> adj[MAXN]; vector<pll> edges; vector<pair<pll,ll>> updates; ll h[MAXN]; void dfs(ll x, ll par) { p[x] = MP(par, LL_MIN); for(auto i: adj[x]) if(i != par) { h[i] = h[x] + 1; dfs(i, x); } } void update(ll a, ll b, ll val) { if(h[b] < h[a]) swap(a, b); while(h[b] > h[a]) { p[b].second = max(p[b].second, val); b = p[b].first; } while(a != b) { p[a].second = max(p[a].second, val); p[b].second = max(p[b].second, val); a = p[a].first; b = p[b].first; } } ll check(ll a, ll b) { if(h[b] < h[a]) swap(a, b); ll ans = LL_MAX; while(h[b] > h[a]) { ans = min(ans, p[b].second); b = p[b].first; } while(a != b) { ans = min(min(p[a].second, p[b].second), ans); a = p[a].first; b = p[b].first; } return ans; } int main() { ll n, m, a, b, g; cin >> n; for(int i = 1; i < n; i++) { cin >> a >> b; edges.push_back(MP(a, b)); adj[a].push_back(b); adj[b].push_back(a); } dfs(1, -1); cin >> m; while(m--) { cin >> a >> b >> g; updates.push_back(MP(MP(a, b),g)); update(a, b, g); } bool valid = true; for(auto i: updates) { if(check(i.first.first, i.first.second) != i.second) { valid = false; break; } } if(valid) { for(auto i: edges) { ll child = max(i.first, i.second); if(p[child].second == LL_MIN) cout << "69420\n"; else cout << p[child].second << "\n"; } } else { cout << -1; } }
cpp
1286
E
E. Fedya the Potter Strikes Backtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFedya has a string SS, initially empty, and an array WW, also initially empty.There are nn queries to process, one at a time. Query ii consists of a lowercase English letter cici and a nonnegative integer wiwi. First, cici must be appended to SS, and wiwi must be appended to WW. The answer to the query is the sum of suspiciousnesses for all subsegments of WW [L, R][L, R], (1≤L≤R≤i)(1≤L≤R≤i).We define the suspiciousness of a subsegment as follows: if the substring of SS corresponding to this subsegment (that is, a string of consecutive characters from LL-th to RR-th, inclusive) matches the prefix of SS of the same length (that is, a substring corresponding to the subsegment [1, R−L+1][1, R−L+1]), then its suspiciousness is equal to the minimum in the array WW on the [L, R][L, R] subsegment. Otherwise, in case the substring does not match the corresponding prefix, the suspiciousness is 00.Help Fedya answer all the queries before the orderlies come for him!InputThe first line contains an integer nn (1≤n≤600000)(1≤n≤600000) — the number of queries.The ii-th of the following nn lines contains the query ii: a lowercase letter of the Latin alphabet cici and an integer wiwi (0≤wi≤230−1)(0≤wi≤230−1).All queries are given in an encrypted form. Let ansans be the answer to the previous query (for the first query we set this value equal to 00). Then, in order to get the real query, you need to do the following: perform a cyclic shift of cici in the alphabet forward by ansans, and set wiwi equal to wi⊕(ans & MASK)wi⊕(ans & MASK), where ⊕⊕ is the bitwise exclusive "or", && is the bitwise "and", and MASK=230−1MASK=230−1.OutputPrint nn lines, ii-th line should contain a single integer — the answer to the ii-th query.ExamplesInputCopy7 a 1 a 0 y 3 y 5 v 4 u 6 r 8 OutputCopy1 2 4 5 7 9 12 InputCopy4 a 2 y 2 z 0 y 2 OutputCopy2 2 2 2 InputCopy5 a 7 u 5 t 3 s 10 s 11 OutputCopy7 9 11 12 13 NoteFor convenience; we will call "suspicious" those subsegments for which the corresponding lines are prefixes of SS, that is, those whose suspiciousness may not be zero.As a result of decryption in the first example, after all requests, the string SS is equal to "abacaba", and all wi=1wi=1, that is, the suspiciousness of all suspicious sub-segments is simply equal to 11. Let's see how the answer is obtained after each request:1. SS = "a", the array WW has a single subsegment — [1, 1][1, 1], and the corresponding substring is "a", that is, the entire string SS, thus it is a prefix of SS, and the suspiciousness of the subsegment is 11.2. SS = "ab", suspicious subsegments: [1, 1][1, 1] and [1, 2][1, 2], total 22.3. SS = "aba", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3] and [3, 3][3, 3], total 44.4. SS = "abac", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] and [3, 3][3, 3], total 55.5. SS = "abaca", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [3, 3][3, 3] and [5, 5][5, 5], total 77.6. SS = "abacab", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [1, 6][1, 6], [3, 3][3, 3], [5, 5][5, 5] and [5, 6][5, 6], total 99.7. SS = "abacaba", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [1, 6][1, 6], [1, 7][1, 7], [3, 3][3, 3], [5, 5][5, 5], [5, 6][5, 6], [5, 7][5, 7] and [7, 7][7, 7], total 1212.In the second example, after all requests SS = "aaba", W=[2,0,2,0]W=[2,0,2,0].1. SS = "a", suspicious subsegments: [1, 1][1, 1] (suspiciousness 22), totaling 22.2. SS = "aa", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [2, 2][2, 2] ( 00), totaling 22.3. SS = "aab", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [1, 3][1, 3] ( 00), [2, 2][2, 2] (00), totaling 22.4. SS = "aaba", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [1, 3][1, 3] ( 00), [1, 4][1, 4] (00), [2, 2][2, 2] (00), [4, 4][4, 4] (00), totaling 22.In the third example, from the condition after all requests SS = "abcde", W=[7,2,10,1,7]W=[7,2,10,1,7].1. SS = "a", suspicious subsegments: [1, 1][1, 1] (77), totaling 77.2. SS = "ab", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), totaling 99.3. SS = "abc", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), totaling 1111.4. SS = "abcd", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), [1, 4][1, 4] (11), totaling 1212.5. SS = "abcde", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), [1, 4][1, 4] (11), [1, 5][1, 5] (11), totaling 1313.
[ "data structures", "strings" ]
// LUOGU_RID: 102248085 #include <bits/stdc++.h> using namespace std; const int N = 600010,MASK = (1<<30)-1; int n,col[N],necol[N][27],w[N],ne[N]; char str[N]; __int128 ans; struct map_doge{ map<int,int> mp; map<int,int>::iterator it; long long sum; void init(){return;} void insert(int val){ it = mp.begin(); if(it != mp.end() && it->first == -val) ++(it->second); else mp.insert(make_pair(-val,1)); sum -= val; return; } void remove(int val){ it = mp.find(-val); if(it != mp.end()){ --(it->second); if(!(it->second)) mp.erase(it); sum += val; } return; } void modify(int val){ int tmpsz = 0; it = mp.begin(); if(it != mp.end() && it->first <= -val) while(it != mp.end() && it->first <= -val){ sum -= (it->first)*1ll*(it->second); tmpsz += (it->second); mp.erase(it); it = mp.begin(); } if(tmpsz) mp.insert(make_pair(-val,tmpsz)),sum -= val*1ll*tmpsz; return; } long long qsum(){return -sum;} }f; struct segment_tree{ #define pushup(u) tr[u].val = min(tr[u<<1].val,tr[u<<1|1].val) struct tn{int l,r,val;}tr[N*4]; void build(int u,int l,int r){ tr[u] = {l,r,MASK}; if(l != r){ int mid = l+r>>1; build(u<<1,l,mid); build(u<<1|1,mid+1,r); } return; } void modify(int u,int pos,int val){ if(tr[u].l == tr[u].r) tr[u].val = val; else{ int mid = tr[u].l+tr[u].r>>1; if(pos <= mid) modify(u<<1,pos,val); else modify(u<<1|1,pos,val); pushup(u); } return; } int query(int u,int l,int r){ if(tr[u].l >= l && tr[u].r <= r) return tr[u].val; else{ int mid = tr[u].l+tr[u].r>>1,res = MASK; if(l <= mid) res = query(u<<1,l,r); if(r > mid) res = min(res,query(u<<1|1,l,r)); return res; } } }s; void del(int x,int c,int I){ if(x && col[x] != c) f.remove(s.query(1,I-x,I-1)); x = necol[x][c]; for(;x;x = necol[x][c]) f.remove(s.query(1,I-x,I-1)); return; } void write(__int128 x){ static int st[30],tp; do st[++tp] = x%10,x /= 10;while(x); while(tp) putchar(st[tp--]|'0'); putchar(10); return; } int main(){ // freopen("data.in","r",stdin); // freopen("out.out","w",stdout); scanf("%d",&n); s.build(1,1,n); f.init(); scanf("%s%d",str+1,&w[1]); s.modify(1,1,w[1]); f.insert(w[1]); write(ans += f.qsum()); for(int i = 2;i <= n;i++){ scanf("%s%d",str+i,&w[i]); str[i] = (str[i]-'a'+ans%26)%26+'a',w[i] ^= ans&MASK; s.modify(1,i,w[i]); col[i-1] = str[i]-'a'; del(ne[i-1],str[i]-'a',i); f.modify(w[i]); if(str[i] == str[1]) f.insert(w[i]); for(ne[i] = ne[i-1];ne[i] && str[ne[i]+1] != str[i];ne[i] = ne[ne[i]]); if(str[ne[i]+1] == str[i]) ++ne[i]; for(int j = 0;j < 26;j++) necol[i][j] = ne[i]; necol[i][col[ne[i]]] = necol[ne[i]][col[ne[i]]]; write(ans += f.qsum()); } return 0; }
cpp
1295
D
D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3 4 9 5 10 42 9999999967 OutputCopy6 1 9999999966 NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00.
[ "math", "number theory" ]
#include<bits/stdc++.h> using namespace std; typedef long long ll; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin>>t; while(t--){ ll a,m; cin>>a>>m; ll GCD = __gcd(a,m); a = a/GCD; m = m/GCD; ll ans = m,m1 = m; for(ll j = 2;j*j<=m1;j++){ if(m%j==0){ ans = ans/j; ans = ans*(j-1); while(m%j==0){ m = m/j; } } } if(m > 1){ ans = ans/m; ans = ans*(m-1); } cout<<ans<<endl; } }
cpp
1310
C
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".
[ "binary search", "dp", "strings" ]
#include <bits/stdc++.h> #define int long long using namespace std; string s; int lcp[1005][1005]; bool cmp(pair<int,int> x,pair<int,int> y) { int L=lcp[x.first][y.first]; int px=x.first+L,py=y.first+L; if(px>x.second||py>y.second) return x.second-x.first<y.second-y.first; return s[px]<s[py]; } pair<int,int> p[510005]; int cntp=0; int rk[1005][1005],pos[1005]; int dp[1005][1005],n,m,k; int cal() { memset(dp,0,sizeof dp); dp[0][0]=1; for(int i=1;i<=n;i++) { if(i>1)for(int j=0;j<=m;j++) dp[i][j]+=dp[i-1][j],dp[i][j]=min(dp[i][j],k); for(int j=0;j<=m;j++) dp[pos[i]][j+1]+=dp[i-1][j],dp[pos[i]][j+1]=min(dp[pos[i]][j+1],k); } return dp[n][m]; } signed main() { ios::sync_with_stdio(false); cin.tie(0); cin >> n >> m >> k >> s; s=' '+s; for(int i=n;i>=1;i--) { for(int j=n;j>=1;j--) { if(s[i]==s[j]) lcp[i][j]=lcp[i+1][j+1]+1; else lcp[i][j]=0; } } for(int i=1;i<=n;i++) for(int j=i;j<=n;j++) p[++cntp]={i,j}; sort(p+1,p+cntp+1,cmp); for(int i=1;i<=cntp;i++) rk[p[i].first][p[i].second]=i; int l=1,r=cntp; string ans; while(l<=r) { int mid=(l+r)/2; for(int i=1;i<=n;i++) { pos[i]=i; while(pos[i]<=n&&rk[i][pos[i]]<mid) ++pos[i]; } // cout << mid << " " << p[mid].first << " " << p[mid].second << " " << s.substr(p[mid].first,p[mid].second-p[mid].first+1) << "\n"; // for(int i=1;i<=n;i++) // cout << pos[i] << " "; // cout << "\n"; if(cal()>=k) ans=s.substr(p[mid].first,p[mid].second-p[mid].first+1),l=mid+1; else r=mid-1; } cout << ans; return 0; }
cpp
1305
A
A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100)  — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000)  — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000)  — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2 3 1 8 5 8 4 5 3 1 7 5 6 1 2 OutputCopy1 8 5 8 4 5 5 1 7 6 2 1 NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.
[ "brute force", "constructive algorithms", "greedy", "sortings" ]
#include <iostream> #include <string> #include <vector> #include <math.h> #include <algorithm> #include <set> using namespace std; typedef long long ll; int main(){ int t; cin >> t; while(t--){ int n; cin >> n; vector<ll> x(n); vector<ll> y(n); for(int i=0;i<n;i++){cin >> x[i];} for(int i=0;i<n;i++){cin >> y[i];} sort(x.begin(),x.end()); sort(y.begin(),y.end()); for(int i=0;i<n;i++){ cout << x[i] << " "; } cout << '\n'; for(int i=0;i<n;i++){ cout << y[i] << " "; } cout << '\n'; } }
cpp
1292
D
D. Chaotic V.time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputÆsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years; it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1,2,3,…1,2,3,…). The node with a number xx (x>1x>1), is directly connected with a node with number xf(x)xf(x), with f(x)f(x) being the lowest prime divisor of xx.Vanessa's mind is divided into nn fragments. Due to more than 500 years of coma, the fragments have been scattered: the ii-th fragment is now located at the node with a number ki!ki! (a factorial of kiki).To maximize the chance of successful awakening, Ivy decides to place the samples in a node PP, so that the total length of paths from each fragment to PP is smallest possible. If there are multiple fragments located at the same node, the path from that node to PP needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node PP.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — number of fragments of Vanessa's mind.The second line contains nn integers: k1,k2,…,knk1,k2,…,kn (0≤ki≤50000≤ki≤5000), denoting the nodes where fragments of Vanessa's mind are located: the ii-th fragment is at the node with a number ki!ki!.OutputPrint a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node PP).As a reminder, if there are multiple fragments at the same node, the distance from that node to PP needs to be counted multiple times as well.ExamplesInputCopy3 2 1 4 OutputCopy5 InputCopy4 3 1 4 4 OutputCopy6 InputCopy4 3 1 4 1 OutputCopy6 InputCopy5 3 1 4 1 5 OutputCopy11 NoteConsidering the first 2424 nodes of the system; the node network will look as follows (the nodes 1!1!, 2!2!, 3!3!, 4!4! are drawn bold):For the first example, Ivy will place the emotion samples at the node 11. From here: The distance from Vanessa's first fragment to the node 11 is 11. The distance from Vanessa's second fragment to the node 11 is 00. The distance from Vanessa's third fragment to the node 11 is 44. The total length is 55.For the second example, the assembly node will be 66. From here: The distance from Vanessa's first fragment to the node 66 is 00. The distance from Vanessa's second fragment to the node 66 is 22. The distance from Vanessa's third fragment to the node 66 is 22. The distance from Vanessa's fourth fragment to the node 66 is again 22. The total path length is 66.
[ "dp", "graphs", "greedy", "math", "number theory", "trees" ]
// #pragma GCC optimize("O3") // #pragma GCC optimize("Ofast") #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include "complex" using namespace std; using namespace __gnu_pbds; template <class T> using o_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; // order_of_key (val): returns the no. of values less than val // find_by_order (k): returns the kth largest element.(0-based) #define int long long typedef pair<int, int> II; typedef vector<II> VII; typedef vector<int> VI; typedef vector<VI> VVI; typedef long long LL; #define PB push_back #define MP make_pair #define F first #define S second #define SZ(a) (int)(a.size()) #define ALL(a) a.begin(), a.end() #define SET(a, b) memset(a, b, sizeof(a)) #define FOR(i, a, b) for (int i = (a); i < (b); ++i) #define REP(i, n) FOR(i, 0, n) #define si(n) scanf("%d", &n) #define dout(n) printf("%d\n", n) #define sll(n) scanf("%lld", &n) #define lldout(n) printf("%lld\n", n) #define fast_io \ ios_base::sync_with_stdio(false); \ cin.tie(NULL) #define endl "\n" const long long mod = 1e9 + 7; void prec() { } const int N = 5001; int cnt[N]; int prime[N]; int curr = 0; void solve() { memset(cnt, 0, sizeof(cnt)); int n; cin >> n; for (int i = 0; i < n; i++) { int x; cin >> x; if (x == 0) { x = 1; } cnt[x]++; } vector<int> primes; map<int, int> id; vector<pair<int, int>> s[N]; for (int i = 0; i < N; i++) prime[i] = i; for (int i = 2; i < 5001; i++) { if (prime[i] == i) { id[i] = curr++; primes.PB(i); for (int j = 2 * i; j < 5001; j += i) { prime[j] = i; } } } map<int, int> mm; int ans = 0; for (int i = 1; i < N; i++) { int v = i; while (v != 1) { int x = prime[v]; mm[x]++; v /= prime[x]; } vector<pair<int, int>> x; int y = 0; for (auto &v : mm) { y += v.second; x.PB({v.first, v.second}); } s[i] = (x); ans += cnt[i] * y; } int sz = primes.size(); vector<int> occur(sz); // how many are there for each of these primes for (int i = 2; i < N; i++) { if (cnt[i] > 0) { occur[id[s[i].back().first]] += cnt[i]; } } while (1) { int maxi_s = 0; int maxi_p = 0; for (int i = 0; i < sz; i++) { if (occur[i] > maxi_s) { maxi_s = occur[i]; maxi_p = primes[i]; } } // answer decreses by n - maxi_s and increases by maxi_s // so decreses by n- if (n - 2 * maxi_s >= 0) { break; } ans = ans + (n - 2 * maxi_s); // now update occur occur = vector<int>(sz, 0); for (int i = 2; i < N; i++) { if (!cnt[i]) { continue; } int p = maxi_p; if (s[i].back().first != maxi_p) { cnt[i] = 0; continue; } s[i].back().second--; if (s[i].back().second == 0) { s[i].pop_back(); } if (!s[i].size()) { cnt[i] = 0; continue; } occur[id[s[i].back().first]] += cnt[i]; } } cout << ans << endl; } signed main() { fast_io; prec(); // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); int totalTests = 1; // cin >> totalTests; for (int testNo = 1; testNo <= totalTests; testNo++) { // cout << "Case #" << testNo << ": "; solve(); } return 0; }
cpp
1141
B
B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5 1 0 1 0 1 OutputCopy2 InputCopy6 0 1 0 1 1 0 OutputCopy2 InputCopy7 1 0 1 1 1 0 1 OutputCopy3 InputCopy3 0 0 0 OutputCopy0 NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.
[ "implementation" ]
#include<bits/stdc++.h> #define ll long long #define ull unsigned long long #define pb push_back #define fastread() (ios_base:: sync_with_stdio(false),cin.tie(NULL)); using namespace std; int main() { fastread(); ll n,rest = 0,ans = 0; cin>>n; vector<ll>a(n); for(int i=0; i<n; i++){ cin>>a[i]; } for(int i=0; i<2*n; i++){ if(a[i%n] == 1){ rest++; ans = max(ans,rest); } else{ rest = 0; } } cout<<ans<<endl; return 0; }
cpp
1292
D
D. Chaotic V.time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputÆsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years; it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1,2,3,…1,2,3,…). The node with a number xx (x>1x>1), is directly connected with a node with number xf(x)xf(x), with f(x)f(x) being the lowest prime divisor of xx.Vanessa's mind is divided into nn fragments. Due to more than 500 years of coma, the fragments have been scattered: the ii-th fragment is now located at the node with a number ki!ki! (a factorial of kiki).To maximize the chance of successful awakening, Ivy decides to place the samples in a node PP, so that the total length of paths from each fragment to PP is smallest possible. If there are multiple fragments located at the same node, the path from that node to PP needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node PP.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — number of fragments of Vanessa's mind.The second line contains nn integers: k1,k2,…,knk1,k2,…,kn (0≤ki≤50000≤ki≤5000), denoting the nodes where fragments of Vanessa's mind are located: the ii-th fragment is at the node with a number ki!ki!.OutputPrint a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node PP).As a reminder, if there are multiple fragments at the same node, the distance from that node to PP needs to be counted multiple times as well.ExamplesInputCopy3 2 1 4 OutputCopy5 InputCopy4 3 1 4 4 OutputCopy6 InputCopy4 3 1 4 1 OutputCopy6 InputCopy5 3 1 4 1 5 OutputCopy11 NoteConsidering the first 2424 nodes of the system; the node network will look as follows (the nodes 1!1!, 2!2!, 3!3!, 4!4! are drawn bold):For the first example, Ivy will place the emotion samples at the node 11. From here: The distance from Vanessa's first fragment to the node 11 is 11. The distance from Vanessa's second fragment to the node 11 is 00. The distance from Vanessa's third fragment to the node 11 is 44. The total length is 55.For the second example, the assembly node will be 66. From here: The distance from Vanessa's first fragment to the node 66 is 00. The distance from Vanessa's second fragment to the node 66 is 22. The distance from Vanessa's third fragment to the node 66 is 22. The distance from Vanessa's fourth fragment to the node 66 is again 22. The total path length is 66.
[ "dp", "graphs", "greedy", "math", "number theory", "trees" ]
#include <bits/stdc++.h> using namespace std; const int N = 5005; const int INF = 1e9; int lpf[N], lca[N][N]; int vp[N], freq[N], freqs[N]; int main () { ios_base::sync_with_stdio(0); cin.tie(0); iota(lpf, lpf+N, 0); for (int l = 1; l < N; l++) { for (int r = l+1; r < N; r++) { lca[l][r] = INF; } } for (int i = 2; i < N; i++) { if (lpf[i] == i) { for (int j = i; j < N; j += i) { lpf[j] = i; } } } for (int i = 2; i < N; i++) { lca[i-1][i] = 0; for (int j = lpf[i]; j < i; j++) { lca[i-1][i] += vp[j]; } lca[i][i-1] = lca[i-1][i]; int v = i; while (v > 1) { vp[lpf[v]]++; v /= lpf[v]; } for (int j = 0; j <= i; j++) { lca[i][i] += vp[j]; } } for (int l = 1; l < N; l++) { for (int r = l+2; r < N; r++) { lca[l][r] = min(lca[l][r-1], lca[r-1][r]); lca[r][l] = lca[l][r]; } } int n; cin >> n; long long ans = 0; for (int i = 0; i < n; i++) { int x; cin >> x; freq[x]++; ans += lca[x][x]; } for (int i = 1; i < N; i++) { freqs[i] = freqs[i-1]+freq[i]; } int dep = 0; while (1) { bool found = 0; for (int l = 1; l < N; l++) { int r = l; if (lca[l][l] <= dep) continue; while (r+1 < N && lca[l][r+1] > dep) r++; int cnt = freqs[r]-freqs[l-1]; if (cnt > n-cnt) { ans -= 1LL*(2*cnt-n)*(lca[l][r]-dep); dep = lca[l][r]; found = 1; break; } } if (!found) break; } cout << ans << '\n'; }
cpp
1284
A
A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12 sin im gye gap eul byeong jeong mu gi gyeong yu sul hae ja chuk in myo jin sa o mi sin 14 1 2 3 4 10 11 12 13 73 2016 2017 2018 2019 2020 OutputCopysinyu imsul gyehae gapja gyeongo sinmi imsin gyeyu gyeyu byeongsin jeongyu musul gihae gyeongja NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.
[ "implementation", "strings" ]
// ~BhupinderJ #include <bits/stdc++.h> using namespace std; #define endl "\n" #define spc <<" "<< #define pii pair<int, int> #define vvi vector<vector<int>> //#define int long long const int M = 1e9+7; const int N = 1e5+1; bool SOLVE(){ int n, m; cin >> n >> m; vector<string> s(n), t(m); for(int i=0 ; i<n ; i++) cin >> s[i]; for(int i=0 ; i<m ; i++) cin >> t[i]; int q; cin >> q; while(q--){ int x; cin >> x; --x; cout << s[x%n] + t[x%m] << endl; } return 1; } signed main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int T = 1; //cin >> T; while(T--){ if(SOLVE()) ;//cout << "YES\n"; else cout << "NO\n"; } }
cpp
1288
C
C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2 OutputCopy5 InputCopy10 1 OutputCopy55 InputCopy723 9 OutputCopy157557417 NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1].
[ "combinatorics", "dp" ]
#include<bits/stdc++.h> typedef long long ll; typedef unsigned long long ull; using namespace std; const ll mod = 1e9+7; const int mm = 2e5 + 10; ll up[1005][15],down[1005][15]; ll qian[1005],hou[1005]; ll ansh[1005]; int main(){ std::ios::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); int n,m; cin>>n>>m; for(int i=1;i<=n;i++)up[i][1]=down[i][1]=1; for(int j=2;j<=m;j++){ qian[0]=0; for(int i=1;i<=n;i++){ qian[i]=qian[i-1]+up[i][j-1]; qian[i]%=mod; } for(int i=1;i<=n;i++){ up[i][j]=qian[i]; } } for(int j=2;j<=m;j++){ hou[n+1]=0; for(int i=n;i>=1;i--){ hou[i]=hou[i+1]+down[i][j-1]; hou[i]%=mod; } for(int i=1;i<=n;i++){ down[i][j]=hou[i]; } } for(int i=n;i>=1;i--){ ansh[i]=ansh[i+1]+down[i][m]; ansh[i]%=mod; } ll ans=0; for(int i=1;i<=n;i++){ ans=(ans+up[i][m]*ansh[i]%mod)%mod; }cout<<ans; }
cpp
1325
F
F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either: find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6 1 3 3 4 4 2 2 6 5 6 5 1 OutputCopy1 1 6 4InputCopy6 8 1 3 3 4 4 2 2 6 5 6 5 1 1 4 2 5 OutputCopy2 4 1 5 2 4InputCopy5 4 1 2 1 3 2 4 2 5 OutputCopy1 3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample:
[ "constructive algorithms", "dfs and similar", "graphs", "greedy" ]
#include<iostream> #include <bits/stdc++.h> using namespace std; template<class container> void print(container v) { for (auto& it : v) cout << it << ' ' ;cout <<endl;} using ll = long long; using ull = unsigned long long; using ld = long double; #define nd "\n" #define all(x) (x).begin(), (x).end() #define popcount(x) __builtin_popcount(x) const ll N = 1e5+50 , LOG = 22 , inf = 1e8 , SQ= 550 , mod = 1e9+7; #define py cout <<"YES"; #define pn cout <<"NO"; #define pp cout <<"ppppppppppppppppp"<<nd; #define lol cout <<"i am here"<<nd; const double PI = acos(-1.0); const int MX = 1e4+100; template <typename T> using min_heap = priority_queue<T , vector <T > , greater <T > >; vector< vector <int > > g(N); vector <bool> mark(N); vector <int > vis(N); int sq; vector<int > st; vector <int > depth(N); void dfs(int node , int par){ vis[node] = 1; st.emplace_back(node); depth[node] = 1 + depth[par]; for (auto &ch : g[node]){ if (ch == par) continue; if (!vis[ch]) dfs(ch , node); else if (vis[ch]){ if (depth[node] - depth[ch]+1 >= sq){ vector<int > ans; int i = (int)st.size()-1; while (1){ ans.emplace_back(st[i]); if (st[i--] == ch) break; } reverse(all(ans)); cout << 2 << nd; cout << (int)ans.size()<<nd; for (auto &v : ans) cout << v<<" "; exit(0); } } } if (!mark[node]) for (auto &ch : g[node]) mark[ch] = 1; st.pop_back(); } void hi(){ ll n , m , u , v; cin >> n >> m; sq = sqrtl(n-1); while (sq* sq < n)++sq; for (int i = 1; i <= m; ++i){ cin >> u >> v; g[u].emplace_back(v); g[v].emplace_back(u); } dfs(1 , 1); cout << 1 << nd; for (int i = 1; sq; ++i){ if (!mark[i]) --sq , cout << i <<" "; } } int main(){ ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0); int tt = 1 , tc = 0; // cin >> tt; while(tt--) hi(); return 0; }
cpp
1315
B
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5 2 2 1 BB 1 1 1 AB 3 2 8 AABBBBAABB 5 3 4 BBBBB 2 1 1 ABABAB OutputCopy2 1 3 1 6
[ "binary search", "dp", "greedy", "strings" ]
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define f first #define s second void iosbase(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); } ll p,a,b; string s; bool get(ll pos){ ll ans=0; vector<char> v; v.push_back(s[pos-1]); for(ll i=pos+1; i<s.size(); i++){ if(v[v.size()-1] != s[i-1]) v.push_back(s[i-1]); } for(auto to: v){ if(to == 'A') ans+=a; else ans+=b; } if(ans <= p) return true; else return false; } void solve(){ cin>>a>>b>>p>>s; ll l=1,r=s.size(); ll res=-1; while(l<=r){ ll mid=(l+r)/2; if(get(mid)){ res=mid; r=mid-1; } else{ l=mid+1; } } if(res == -1){ cout<<s.size(); } else{ cout<<res; } } int main() { iosbase(); ll t=1; cin>>t; for(ll i=1; i<=t; i++){ solve(); cout<<'\n'; } }
cpp
1316
D
D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters  — UU, DD, LL, RR or XX  — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103)  — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2 1 1 1 1 2 2 2 2 OutputCopyVALID XL RX InputCopy3 -1 -1 -1 -1 -1 -1 -1 -1 2 2 -1 -1 -1 -1 -1 -1 -1 -1 OutputCopyVALID RRD UXD ULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below :
[ "constructive algorithms", "dfs and similar", "graphs", "implementation" ]
/** * Author: Richw818 * Created: 01.25.2023 23:09:49 **/ #include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; string dir = "ULDR"; int n; cin >> n; vector<vector<int>> x(n, vector<int>(n)), y(n, vector<int>(n)); for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ cin >> x[i][j] >> y[i][j]; if(x[i][j] != -1) x[i][j]--, y[i][j]--; } } vector<string> grid(n, string(n, '.')); auto dfs = [&](int r, int c, int d, int sr, int sc, auto&& dfs) -> void { if(r < 0 || r >= n || c < 0 || c >= n || grid[r][c] != '.' || x[r][c] != sr || y[r][c] != sc) return; grid[r][c] = (r == sr && c == sc ? 'X' : dir[d]); for(int i = 0; i < 4; i++){ dfs(r + dx[i], c + dy[i], i, sr, sc, dfs); } }; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(x[i][j] == i && y[i][j] == j) dfs(i, j, -1, i, j, dfs); } } for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(x[i][j] != -1 && grid[i][j] == '.'){ cout << "INVALID\n"; return 0; } } } for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(x[i][j] == -1){ for(int d = 0; d < 4; d++){ int nx = i + dx[d], ny = j + dy[d]; if(nx >= 0 && nx < n && ny >= 0 && ny < n && x[nx][ny] == -1) grid[i][j] = dir[d ^ 2]; } if(grid[i][j] == '.'){ cout << "INVALID\n"; return 0; } } } } cout << "VALID\n"; for(int i = 0; i < n; i++) cout << grid[i] << '\n'; return 0; }
cpp
1291
A
A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000)  — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4 4 1227 1 0 6 177013 24 222373204424185217171912 OutputCopy1227 -1 17703 2237344218521717191 NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit).
[ "greedy", "math", "strings" ]
#include <bits/stdc++.h> using namespace std; #define ll long long int #define pb push_back #define em emplace_back #define fi(l, r) for(ll i=l; i<r; i++) #define fir(r, l) for(ll i=r; i>=l; i--) void solve(){ ll n; cin >> n; string s; cin >> s; if(s.length() <= 1){ cout << -1 << endl; return; } string ans = ""; ll cnt = 2; fi(0, s.length()){ if((s[i]-48) &1 == 1){ ans += s[i]; cnt--; } if(cnt == 0){ break; } } if(cnt != 0){ cout << -1 << endl; }else{ cout << ans << endl; } } int main(){ ll t; cin >> t; // t = 1; while(t--){ solve(); } return 0; }
cpp
1288
D
D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5 5 0 3 1 2 1 8 9 1 3 1 2 3 4 5 9 1 0 3 7 2 3 0 6 3 6 4 1 7 0 OutputCopy1 5
[ "binary search", "bitmasks", "dp" ]
#include <bits/stdc++.h> using namespace std; typedef long long int ll; # define mod 1000000007 int a[300000+10][10]; int b[1010],n,m; int ans1,ans2; bool check(int mid) { memset(b,0,sizeof(b)); for(int i=1;i<=n;i++) { int now=0; for(int j=1;j<=m;j++) { int fuck=j-1; if(a[i][j]>=mid) { now|=(1<<fuck); } } b[now]=i; } for(int i=0;i<(1<<m);i++) { for(int j=0;j<(1<<m);j++) { if(b[i]&&b[j]) { if((i|j)==(1<<m)-1) { ans1=b[i]; ans2=b[j]; return 1; } } } } return 0; } int main() { //二分枚举当前最小值 //把小于最小值的设置0,否则是1,那么只需要检查当前位置之前是否具有一个二进制数字 //取或之后全是1, //把小于最小值的设为1,否则是0,那么只需要检查当前位置之前,是否有一个数字和他 //取并之后是0,暴力即可 cin>>n>>m; for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { cin>>a[i][j]; } } int l=0,r=1e9; while(l<=r) { int mid=(l+r)>>1; if(check(mid)) { l=mid+1; } else { r=mid-1; } } //cout<<l<<" "<<r<<endl; cout<<ans1<<" "<<ans2<<endl; return 0; }
cpp
1322
B
B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)Here x⊕yx⊕y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2≤n≤4000002≤n≤400000) — the number of integers in the array.The second line contains integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).OutputPrint a single integer — xor of all pairwise sums of integers in the given array.ExamplesInputCopy2 1 2 OutputCopy3InputCopy3 1 2 3 OutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112⊕1002⊕1012=01020112⊕1002⊕1012=0102, thus the answer is 2.⊕⊕ is the bitwise xor operation. To define x⊕yx⊕y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012⊕00112=0110201012⊕00112=01102.
[ "binary search", "bitmasks", "constructive algorithms", "data structures", "math", "sortings" ]
#include <bits/stdc++.h> #include <ext/pb_ds/detail/standard_policies.hpp> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/rope> #define TIME 1.0*clock()/CLOCKS_PER_SEC #define all(x) x.begin(), x.end() #define ull unsigned long long #define pii pair < int , int > #pragma GCC optimize("Ofast") #define ld long double #define pb push_back #define ll long long #define endl '\n' #define S second #define F first #define sz size #define int ll using namespace std; using namespace __gnu_pbds; template <typename T> using ordered_set = tree <T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>; mt19937 gen(chrono::system_clock::now().time_since_epoch().count()); int b[500000]; int n; int get (int x, int y) { if (x > y) return 0; int kl = 0; int l = 1, r = 1; for (int i = n; i; i--) { while (l <= n && b[i] + b[l] < x) l++; while (r <= n && b[i] + b[r] <= y) r++; kl += (r - l) - (l <= i && i < r); } return (kl / 2) ; } int32_t main() { #ifdef LOCAL freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; int a[n + 2]; for (int i = 1; i <= n; i++) cin >> a[i]; int ans = 0; for (int i = 0; i <= 25; i++){ for (int j = 1; j <= n; j++){ b[j] = (a[j] % (1 << (i + 1))); } sort(b + 1, b + 1 + n); int cnt = get((1 << i), (1 << (i + 1)) - 1) + get(((1 << (i + 1)) + (1 << i)), ((1 << (i + 1)) + (1 << (i + 1)) - 1)); if (cnt % 2) ans += (1 << i); } cout << ans;// return 0; }
cpp
1311
F
F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3 1 3 2 -100 2 3 OutputCopy3 InputCopy5 2 1 4 3 5 2 2 2 3 4 OutputCopy19 InputCopy2 2 1 -3 0 OutputCopy0
[ "data structures", "divide and conquer", "implementation", "sortings" ]
// LUOGU_RID: 100872105 #include <bits/stdc++.h> using namespace std; #define max_n 200100 #define int long long void read(int &p) { p = 0; int k = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') { k = -1; } c = getchar(); } while (c >= '0' && c <= '9') { p = p * 10 + c - '0'; c = getchar(); } p *= k; return; } void write_(int x) { if (x < 0) { putchar('-'); x = -x; } if (x > 9) { write_(x / 10); } putchar(x % 10 + '0'); } void writesp(int x) { write_(x); putchar(' '); } void writeln(int x) { write_(x); putchar('\n'); } int n; pair<int, int> points[max_n]; int tree1[max_n], tree2[max_n]; int lowbit(int x) { return (-x) & x; } void add(int x, int val) { for (int i = x; i <= n; i += lowbit(i)) { tree1[i] += 1; tree2[i] += val; } } int ask1(int x) { int ans = 0; //printf("\n"); for (int i = x; i > 0; i -= lowbit(i)) { ans += tree1[i]; //printf("%lld ", ans); } //printf("\n"); return ans; } int ask2(int x) { int ans = 0; for (int i = x; i > 0; i -= lowbit(i)) { ans += tree2[i]; } return ans; } int vs[max_n]; signed main() { read(n); for (int i = 1; i <= n; i++) { read(points[i].first); } for (int i = 1; i <= n; i++) { read(points[i].second); vs[i] = points[i].second; } sort(points + 1, points + n + 1); sort(vs + 1, vs + n + 1); int tot = unique(vs + 1, vs + n + 1) - vs - 1; for (int i = 1; i <= n; i++) { points[i].second = lower_bound(vs + 1, vs + tot + 1, points[i].second) - vs; } int ans = 0; for (int i = 1; i <= n; i++) { //printf("%lld %lld %lld %lld\n", points[i].first, points[i].second, ask1(points[i].second), ask2(points[i].second)); ans += points[i].first * ask1(points[i].second) - ask2(points[i].second); add(points[i].second, points[i].first); } writeln(ans); return 0; }
cpp
1284
B
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5 1 1 1 1 1 2 1 4 1 3 OutputCopy9 InputCopy3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 OutputCopy7 InputCopy10 3 62 24 39 1 17 1 99 1 60 1 64 1 30 2 79 29 2 20 73 2 85 37 1 100 OutputCopy72 NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.
[ "binary search", "combinatorics", "data structures", "dp", "implementation", "sortings" ]
#include<bits/stdc++.h> typedef long long ll; using namespace std; const ll mod = 1e9 + 7; const ll mm = 1e5 + 10; int mi[mm],ma[mm],bj[mm]; int mii[mm*10],maa[mm*10]; int main() { std::ios::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); int n; cin>>n; for(int i=1;i<=n;i++){ mi[i]=1000000; } for(int i=1;i<=n;i++){ int l; cin>>l; vector<int>ana; for(int j=1;j<=l;j++){ int x; cin>>x;ana.push_back(x); mi[i]=min(x,mi[i]); ma[i]=max(x,ma[i]); } for(int j=1;j<ana.size();j++){ if(ana[j-1]<ana[j])bj[i]=1; } if(bj[i]==0)maa[ma[i]]++; } for(int i=1000000;i>=0;i--){ maa[i]+=maa[i+1]; } ll ans=0; ll x=0; for(int i=1;i<=n;i++){ if(bj[i])x++; else ans+=maa[mi[i]+1]; } ans+=x*(n*2-1)-(x-1)*x; cout<<ans; }
cpp
1324
D
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
[ "binary search", "data structures", "sortings", "two pointers" ]
#include <bits/stdc++.h> using namespace std; #define ll long long #define mod 1000000007 int main(){ ios_base::sync_with_stdio(false); cout.tie(nullptr); cin.tie(nullptr); int T=1; //cin>>T; while(T--) { int n; cin>>n; ll cnt=0; vector<ll>a(n),v(n); for(int i=0;i<n;i++)cin>>a[i]; for(int i=0;i<n;i++){ cin>>v[i]; v[i]=a[i]-v[i]; } sort(v.begin(), v.end()); for(int i=0;i<n;i++){ int l=i+1,r=n-1,ans=-1,mid; while(l<=r){ mid=(l+r)/2; ll x=v[mid]+v[i]; if(x>0){ ans=mid; r=mid-1; } else l=mid+1; } if(ans!=-1)cnt+=(n)-ans; } cout<<cnt<<'\n'; } return 0; }
cpp
1325
D
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.
[ "bitmasks", "constructive algorithms", "greedy", "number theory" ]
//Author: Ankush Bhagat (https://github.com/ankushbhagat124) //RFIPITIDS #include <bits/stdc++.h> #define int long long const int N = (int)(3e5 + 1); const int mod = (int)(1e9 + 7); using namespace std; clock_t startTime; double getCurrentTime() { return (double)(clock() - startTime) / CLOCKS_PER_SEC; } void init() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } void __print(int x) {cerr << x;} void __print(float x) {cerr << x;} void __print(double x) {cerr << x;} void __print(long double x) {cerr << x;} void __print(char x) {cerr << '\'' << x << '\'';} void __print(const char *x) {cerr << '\"' << x << '\"';} void __print(const string &x) {cerr << '\"' << x << '\"';} void __print(bool x) {cerr << (x ? "true" : "false");} template<typename T, typename V> void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';} template<typename T> void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i : x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";} void _print() {cerr << "]\n";} template <typename T, typename... V> void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);} #ifndef ONLINE_JUDGE #define debug(x...) cerr << "[" << #x << "] = ["; _print(x) #else #define debug(x...) #endif signed main() { init(); startTime = clock(); ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); /* */ int t = 1; // cin >> t; while (t-- && getCurrentTime() < 10) { int u, v; cin >> u >> v; vector <int> ans; for (int i = 0; i < 64; i++) { if ((u & (1ll << i))) { v -= (1ll << i); } } if (v < 0 || v % 2) { cout << "-1" << endl; continue; } int l = 0, r = 0; for (int i = 63; i > 0; i--) { if ((v & (1ll << i))) { if ((u & (1ll << (i - 1))) == 0) u |= (1ll << (i - 1)); else l |= (1ll << (i - 1)); r |= (1ll << (i - 1)); } } if (u > 0) ans.push_back(u); if (l > 0) ans.push_back(l); if (r > 0) ans.push_back(r); cout << (int)ans.size() << endl; for (auto x : ans) cout << x << " "; // cout << endl; } double time = getCurrentTime(); debug(time); }
cpp
1285
A
A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4 LRLR OutputCopy5 NoteIn the example; Zoma may end up anywhere between −2−2 and 22.
[ "math" ]
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll, ll> pll; #define pb push_back #define mp make_pair #define fi first #define se second const ll mod = 1e9 + 7; long long gcd(long long int a, long long int b) { if (b == 0) return a; return gcd(b, a % b); } long long lcm(ll a, ll b) { return (a / gcd(a, b)) * b; } bool isPrime(int x) { if (x < 2) { return false; } for (int d = 2; d * d <= x; d++) { if (x % d == 0) return false; } return true; } ll nCrModp(ll n, ll r, ll p) { // Optimization for the cases when r is large if (r > n - r) r = n - r; // The array C is going to store last row of // pascal triangle at the end. And last entry // of last row is nCr ll C[r + 1]; memset(C, 0, sizeof(C)); C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (ll i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (ll j = min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j - 1]) % p; } return C[r]; } ll printNcR(ll n, ll r) { long long p = 1, k = 1; if (n - r < r) r = n - r; if (r != 0) { while (r) { p *= n; k *= r; long long m = __gcd(p, k); p /= m; k /= m; n--; r--; } } else p = 1; return p; } ll modFact(ll n, ll p) { if (n >= p) return 0; ll result = 1; for (int i = 1; i <= n; i++) result = (result * i) % p; return result; } ll modPow(ll a, ll x, ll p) { // calculates a^x mod p in logarithmic time. ll res = 1; while (x > 0) { if (x % 2 != 0) { res = (res * a) % p; } a = (a * a) % p; x /= 2; } return res; } ll modInverse(ll a, ll p) { // calculates the modular multiplicative of a mod m. //(assuming p is prime). return modPow(a, p - 2, p); } ll modBinomial(ll n, ll k, ll p) { // calculates C(n,k) mod p (assuming p is prime). ll numerator = 1; // n * (n-1) * ... * (n-k+1) for (ll i = 0; i < k; i++) { numerator = (numerator * (n - i)) % p; } ll denominator = 1; // k! for (ll i = 1; i <= k; i++) { denominator = (denominator * i) % p; } // numerator / denominator mod p. return (numerator * modInverse(denominator, p)) % p; } int power(long long x, unsigned int y, int p) { int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } string decToBinary(ll n) { string s = bitset<64>(n).to_string(); if (s.size() < 10) { while (s.size() != 10) { s += '0'; } } return s; } int main() { ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); int n; cin>>n; string s; cin>>s; cout<<n+1; }
cpp
1286
F
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.
[ "brute force", "constructive algorithms", "dp", "fft", "implementation", "math" ]
// LUOGU_RID: 102584653 #include<bits/stdc++.h> using namespace std; #define ll long long #define N 22 ll n; ll p[N],a[N]; ll f[1<<N]; ll cnn[1<<N]; bool vis[1<<N]; inline ll suan(ll x){ if(f[x]!=-1)return f[x]; ll an=(vis[x]); for(int i=(x-1)&x;i;i=(i-1)&x){ if(!vis[x^i])continue; // if(cnn[i]/2+1<=an)break; an=max(an,suan(i)+1); }return f[x]=an; } map<ll,ll>dui; ll cc=0; vector<ll>hs[1<<(N-2)]; int main() { // freopen("test1.in","r",stdin); //freopen(".in","r",stdin); //freopen("test1.out","w",stdout); ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); ll len;cin>>len; for(int i=1;i<=len;i++)cin>>p[i]; for(int i=1;i<=len;i++)if(p[i]!=0)a[++n]=p[i]; for(int i=1;i<(1<<n);i++){ ll sum=0,cn=0; for(int j=1;j<=n;j++){ if(i&(1<<(j-1)))sum+=a[j],p[++cn]=a[j]; }cnn[i]=cn; bool kz=0; if(cn>=2&&((sum+cn-1)&1)==0){ for(ll k=(sum-cn+1)/2;k<=(sum+cn-1)/2;k++){ if(dui.find(k)!=dui.end()){ for(auto o:hs[dui[k]])if((o|i)==i){kz=1;break;} }if(kz)break; } } if(dui.find(sum)==dui.end())dui[sum]=++cc; hs[dui[sum]].push_back(i); if(!kz)continue; vis[i]=1; }memset(f,-1,sizeof(f)); cout<<n-suan((1<<n)-1); return 0; }
cpp
1305
A
A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100)  — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000)  — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000)  — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2 3 1 8 5 8 4 5 3 1 7 5 6 1 2 OutputCopy1 8 5 8 4 5 5 1 7 6 2 1 NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.
[ "brute force", "constructive algorithms", "greedy", "sortings" ]
#include <bits/stdc++.h> using namespace std; int main(){ int t; cin>>t; while(t--){ int n; cin>>n; int a[n]; int b[n]; for(int i =0; i<n; i++){ cin>>a[i]; } for(int i =0; i<n; i++){ cin>>b[i]; } sort(a,a+n); sort(b,b+n); for(int i =0; i<n; i++){ cout<<a[i]<<" "; } cout<<endl; for(int i =0; i<n; i++){ cout<<b[i]<<" "; } cout<<endl; } }
cpp
1310
A
A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5 3 7 9 7 8 5 2 5 7 5 OutputCopy6 InputCopy5 1 2 3 4 5 1 1 1 1 1 OutputCopy0 NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.
[ "data structures", "greedy", "sortings" ]
#include <bits/stdc++.h> using namespace std; //#define int long long typedef pair<int,int> PII; typedef long long LL; const int INF=0x3f3f3f3f; const long long LNF=0x3f3f3f3f3f3f3f3f; const int mod=998244353; const int N=200010,M=N<<1; inline int read(){ int f=1,x=0;char s=getchar(); while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();} while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();} return x*f; } int n,m; struct Node{ int a,t; bool operator<(const Node &W)const{ return a<W.a; } }a[N]; void solve(){ cin>>n; for(int i=1;i<=n;++i)cin>>a[i].a; for(int i=1;i<=n;++i)cin>>a[i].t; sort(a+1,a+1+n); priority_queue<int>q; LL res=0,cost=0; for(int i=1,now=1;i<=n;++now){ if(q.empty())now=a[i].a; while(now==a[i].a&&i<=n)q.push(a[i].t),cost+=a[i].t,++i; cost-=q.top();q.pop(); res+=cost; } while(!q.empty()){ cost-=q.top();q.pop(); res+=cost; } cout<<res<<'\n'; } signed main() { ios::sync_with_stdio(false),cin.tie(nullptr); int Tt=1; //cin>>Tt; while(Tt--){ solve(); } return 0; }
cpp
13
E
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
[ "data structures", "dsu" ]
#include<bits/stdc++.h> using namespace std; int const M=100100;int i,n,m,x,opt,block; int a[M],L[M],R[M],bel[M],nxt[M],dis[M]; int read(){ int x=0;char ch=getchar(); while (ch<'0'||ch>'9') ch=getchar(); while (ch>='0'&&ch<='9') x=x*10+ch-48,ch=getchar(); return x; } void update(int x){ for (int i=R[x];i>=L[x];i--) dis[i]=i+a[i]>R[x]?1:dis[i+a[i]]+1, nxt[i]=i+a[i]>R[x]?i+a[i]:nxt[i+a[i]]; } void query(int x){int id,res=0; for (int i=x;i<=n;i=nxt[i]) res+=dis[i],id=i; for (int i=id;i<=n;i+=a[i]) id=i; printf("%d %d\n",id,res); } int main(){ n=read();m=read(); block=(int)ceil(sqrt(n)); for (i=1;i<=n;i++) a[i]=read(); for (i=1;i<=n;i++) bel[i]=(i-1)/block+1; for (i=1;i<=bel[n];i++) L[i]=R[i-1]+1,R[i]=R[i-1]+block; R[bel[n]]=n;for (i=1;i<=bel[n];i++) update(i); while (m--){ opt=read();x=read(); if (!opt) a[x]=read(),update(bel[x]); if (opt) query(x); } return 0; }
cpp
1141
G
G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2 1 4 4 3 3 5 3 6 5 2 OutputCopy2 1 2 1 1 2 InputCopy4 2 3 1 1 4 1 2 OutputCopy1 1 1 1 InputCopy10 2 10 3 1 2 1 3 1 4 2 5 2 6 2 7 3 8 3 9 OutputCopy3 1 1 2 3 2 3 1 3 1
[ "binary search", "constructive algorithms", "dfs and similar", "graphs", "greedy", "trees" ]
#include<iostream> #include<cstdio> #include<vector> #include<string> #include<algorithm> #include<set> #include<map> #include<queue> using namespace std; typedef long long ll; const int N=2e5+5; int n,m,k; ll g[N],d[N]; vector<pair<int,int>> adj[N]; map<int,int>f; void dfs(int u,int p,int c){ int color=0; if(d[u]>m)c=-1; for(auto edge : adj[u]){ int v=edge.first; int e=edge.second; if(v==p)continue; color=(color+1)%m; if(color==c){ color=(color+1)%m; } g[e]=color; dfs(v,u,color); } } int main() { ios::sync_with_stdio(0); cin>>n>>k; for(int i=1,x,y;i<n;++i){ cin>>x>>y; ++d[x];++d[y]; adj[x].push_back({y,i}); adj[y].push_back({x,i}); } for(int i=1;i<=n;++i)++f[d[i]]; int kk=n; m=n-1; for(auto x : f){ if(kk>k){ kk-=x.second; m=x.first; } } dfs(1,0,-1); cout << m << '\n'; for(int i=1;i<n;++i)cout << g[i]+1 << ' '; }
cpp
1296
E1
E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9 abacbecfd OutputCopyYES 001010101 InputCopy8 aaabbcbb OutputCopyYES 01011011 InputCopy7 abcdedc OutputCopyNO InputCopy5 abcde OutputCopyYES 00000
[ "constructive algorithms", "dp", "graphs", "greedy", "sortings" ]
#include <bits/stdc++.h> #define fbo find_by_order #define ook order_of_key #define del(x) erase(op.find_by_order(op.order_of_key(x))) #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; typedef tree<int, null_type, less_equal<int>, rb_tree_tag,tree_order_statistics_node_update> pbds; #include <string> using namespace std; #define ios ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0); #define ps(x) cout << fixed << setprecision(25) << x << endl; #define el '\n' typedef long long ll; typedef __int128 lll; typedef vector<int> vi; typedef vector<ll> vl; #define pb push_back #define eb emplace_back #define ist insert //#define sz(c) ll((c).size()) #define mem(x) memset(x,0,sizeof(x)) #define sum(a) ( accumulate ((a).begin(), (a).end(), 0ll)) #define mine(a) (*min_element((a).begin(), (a).end())) #define maxe(a) (*max_element((a).begin(), (a).end())) #define all(x) x.begin(), x.end() #define rall(a) (a).rbegin(), (a).rend() template<typename T> istream& operator>>(istream& is, vector<T>& v){for (auto& i : v) is >> i; return is;} template<typename T> ostream& operator<<(ostream& os, vector<T>& v){for (auto& i : v) os << i << ' '; return os;} const ll mod = 1e9+7; const int N = 2e5+7; const ll inf = 1e18; void slv(){ int n; cin >> n; string s; cin >> s; for(int i = 0; i < n; i++){ for(int j = i+1; j < n; j++){ for(int k = j+1; k < n; k++){ if(s[i]>s[j] && s[j]>s[k]){ cout << "NO\n"; return; } } } } vector<int> res(n); res[0] = 0; for(int i = 1; i < n; i++){ for(int j = 0; j < i; j++){ if(s[i]<s[j]){ res[i] = 1-res[j]; break; } } } cout << "YES\n"; for(int i = 0; i < n; i++) cout << res[i]; cout << el; } int main() { ios; //freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); int tc = 1; //cin >> tc; while(tc--){ slv(); } return 0; }
cpp
1285
B
B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3 4 1 2 3 4 3 7 4 -1 3 5 -5 5 OutputCopyYES NO NO NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.
[ "dp", "greedy", "implementation" ]
#include <bits/stdc++.h> using namespace std; const int N = 1e5+5, MOD = 1e9+7; const long long INF = 1e18; const double EPS = 1e-6, PI_Val = 3.141592653589793238; /* --- YOU SHOULD HAVE A VISION --- */ bool flag; int n; long long sum; int a[N]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int _ts; cin >> _ts; while (_ts--) { cin >> n; sum = 0; flag = true; for (int i = 0; i < n; i++) { cin >> a[i]; sum += a[i]; if (sum <= 0) flag = false; } sum = 0; for (int i = n - 1; i >= 0; i--) { sum += a[i]; if (sum <= 0) flag = false; } cout << (flag ? "YES\n" : "NO\n"); } }
cpp
1301
F
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).
[ "dfs and similar", "graphs", "implementation", "shortest paths" ]
/// Nu am loc de lista de adicenta? Calculez singur vecinii. /// Nota: Nu e nev de nodurile auxiliare pentru a compresa graful - daca ma joc odata prin culoare, nu ma mai uit #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 <int, int> 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; int dist[NMAX][NMAX][41]; int mat[NMAX][NMAX]; vector <pii> v[41]; int dx[] = {0, 1, -1, 0}; int dy[] = {1, 0, 0, -1}; int n, m; bool OK(int i, int 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); int 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}); } } deque <pii> dq; 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(auto x : v[col]) { dist[x.first][x.second][col] = 0; dq.push_back({x.first, x.second}); } while(dq.size()) { pii x = dq.front(); dq.pop_front(); if(x.first != n + 1) { 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; dq.push_back({care.first, care.second}); } } pii care = {n + 1, mat[x.first][x.second]}; if(dist[care.first][care.second][col] == 32767) { /// Hmm... dist[care.first][care.second][col] = dist[x.first][x.second][col]; dq.push_front({care.first, care.second}); } } else { for(auto y : v[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; dq.push_back({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; }
cpp
1316
D
D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters  — UU, DD, LL, RR or XX  — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103)  — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2 1 1 1 1 2 2 2 2 OutputCopyVALID XL RX InputCopy3 -1 -1 -1 -1 -1 -1 -1 -1 2 2 -1 -1 -1 -1 -1 -1 -1 -1 OutputCopyVALID RRD UXD ULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below :
[ "constructive algorithms", "dfs and similar", "graphs", "implementation" ]
// RADHASOAMI , WITH THE GRACE OF HUZUR I PROMISE TO FIGHT TILL THE LAST SECOND OF EVERY CONTEST AND CODE TO MY FULL POTENTIAL ...... #include <iostream> #include <vector> #include <unordered_map> #include <cmath> #include <cstring> #include <algorithm> #include <set> #include <map> #include <queue> #define ll int #define mod 1000000007 using namespace std; // ==================== FUNCTIONS FOR INPUT AND OUTPUT OF VECTORS ======================================================= void input(vector < ll > &arr) { for(int i = 0;i < arr.size();i++) cin >> arr[i]; } void output(vector < ll > &arr) { for(int i = 0;i < arr.size();i++) cout << arr[i] << " "; cout << "\n"; } // ============================== FOR MATHEMATICAL FUNCTIONS ============================================================= ll gcd(ll a,ll b) { if(b==0) return a; return gcd(b,a%b); } ll power(ll a,ll b) { if(b==0) return 1; if(b==1) return a; ll smallans=power(a,b/2); ll myans=(smallans*smallans)%mod; if((b&1)) myans=(myans*a)%mod; return myans; } ll multiply(ll a,ll b) { ll ans=((a%mod)*(b%mod))%mod; return ans; } ll divide(ll a,ll b) { return multiply(a,power(b,mod-2)); } // ============================ SEGMENT TREE FOR DEFAULT MINIMUM QUERY ================================================== void manageLazy(vector <ll> &tree,vector <ll> &lazy,ll idx) { tree[2*idx + 1] += lazy[idx]; lazy[2*idx + 1] += lazy[idx]; tree[2*idx + 2] += lazy[idx]; lazy[2*idx + 2] += lazy[idx]; lazy[idx] = 0; } void build(vector <ll> &tree,vector <ll> &arr,ll left,ll right,ll idx) { if(left == right) { tree[idx] = arr[left]; return; } ll mid = (left + right) / 2; build(tree , arr , left , mid , 2*idx + 1); build(tree , arr , mid + 1 , right , 2*idx + 2); tree[idx] = min(tree[2*idx + 1],tree[2*idx + 2]); } void update(vector <ll> &tree,vector <ll> &lazy,ll tl,ll tr,ll l,ll r,ll idx,ll val) { if(l > r) return; if(l == tl && tr == r) { tree[idx] += val; lazy[idx] += val; return; } manageLazy(tree,lazy,idx); ll mid = (tl + tr) / 2; update(tree,lazy,tl,mid,l,min(r,mid),2*idx + 1,val); update(tree,lazy,mid + 1,tr,max(l,mid + 1),r,2*idx + 2,val); tree[idx] = min(tree[2*idx + 1],tree[2*idx + 2]); } ll query(vector <ll> &tree,vector<ll> & lazy,ll tl,ll tr,ll l,ll r,ll idx) { if(l > r) return 1e18; if(l <= tl && tr <= r) return tree[idx]; manageLazy(tree,lazy,idx); ll mid = (tl + tr) / 2; ll a = query(tree,lazy,tl,mid,l,min(r,mid),2*idx + 1); ll b = query(tree,lazy,mid + 1,tr,max(l,mid + 1),r,2*idx + 2); return min(a,b); } // ================================== SPARSE TABLE FOR DEFAULT MINIMUM QUERY ================================================== void precompute_min(vector < vector < ll > > &sparsetable , vector < ll > &a) { int n = sparsetable.size(); int p = sparsetable[0].size(); for(int i = 0;i < n;i++) sparsetable[i][0] = a[i]; for(int j = 1;j < p;j++) { for(int i = 0;i + (1 << j) <= n;i++) sparsetable[i][j] = min(sparsetable[i][j - 1] , sparsetable[i + (1 << (j - 1))][j - 1]); } } ll minquery(vector < vector < ll > > &sparsetable , vector < ll > &log , ll l , ll r) { ll range = r - l + 1; if(range == 0) return sparsetable[l][0]; ll j = log[range]; return min(sparsetable[l][j] , sparsetable[r - (1 << j) + 1][j]); } //========================== BINARY INDEX TREE ========================================================================= void update(vector<ll> &tree,ll index,ll val) { index++; while(index < tree.size()) { tree[index]=(tree[index] + val) %mod; index+=index&(-index); } } ll calculate(vector<ll> &tree,ll index) { ll sum=0; index++; while(index > 0) { sum=(sum + tree[index])%mod; index-=index&(-index); } return sum; } //=========================== FOR DISJOINT SET UNION ==================================================================== ll findpar(ll p,vector<ll> &parent) { if(parent[p]==p) return p; parent[p]=findpar(parent[p],parent); return parent[p]; } void merge(ll a, ll b,vector<ll> &parent,vector<ll> &size_) { a = findpar(a,parent); b = findpar(b,parent); if (a != b) { if (size_[a] < size_[b]) swap(a, b); parent[b] = a; size_[a] += size_[b]; } } // ====================================== FOR STORING AND COUNTING THE PRIMES USING SIEVE ============================ void sieve(vector<bool> &primes,vector<ll> &count) { for(int i=2;i<primes.size();i++) { if(primes[i]) { count.push_back(i); for(int j=i*i;j<primes.size();j+=i) primes[j]=false; } } } // ===================================================================================================================== void solve() { ll n; cin >> n; string VALID = "VALID"; string INVALID = "INVALID"; vector < vector < pair <ll, ll> > > points(n + 1, vector < pair <ll, ll> > (n + 1, {-1, -1})); map < pair <ll, ll> , ll > mp; for(int i = 0;i < n;i++) { for(int j = 0;j < n;j++) { ll a, b; cin >> a >> b; if(a != -1) { points[i + 1][j + 1] = {a, b}; mp[{a, b}] = 1; } } } queue < pair <ll , ll> > que; vector < vector < char > > ans(n + 1, vector < char > (n + 1, '-')); for(auto keys: mp) { ll a = keys.first.first, b = keys.first.second; if(points[a][b].first != a || points[a][b].second != b) { cout << INVALID << "\n"; return; } ans[a][b] = 'X'; que.push({a, b}); } vector < pair < pair < ll, ll >, char> > dir = {{{-1, 0}, 'D'}, {{1, 0}, 'U'}, {{0, 1}, 'L'}, {{0, -1}, 'R'}}; while(que.size()) { auto vtx = que.front(); que.pop(); ll x = vtx.first, y = vtx.second; ll a = points[x][y].first, b = points[x][y].second; for(int i = 0;i < 4;i++) { ll nx = x + dir[i].first.first, ny = y + dir[i].first.second; if(nx <= 0 || nx > n || ny <= 0 || ny > n || points[nx][ny].first != a || points[nx][ny].second != b || ans[nx][ny] != '-') continue; //cout << nx << " " << ny << " " << points[nx][ny].first << " " << points[nx][ny].second << "\n"; ans[nx][ny] = dir[i].second; que.push({nx, ny}); } } vector < pair < pair < ll, ll >, pair < char, char> > > direc = {{{1, 0}, {'D', 'U'}}, {{-1, 0}, {'U', 'D'}}, {{0, -1}, {'L', 'R'}}, {{0, 1}, {'R', 'L'}}}; for(int i = 1;i <= n;i++) { for(int j = 1;j <= n;j++) { if(points[i][j].first != -1 && ans[i][j] == '-') { cout << INVALID << "\n"; return; } if(ans[i][j] != '-') continue; for(int d = 0;d < 4;d++) { ll nx = i + direc[d].first.first, ny = j + direc[d].first.second; if(nx <= 0 || ny <= 0 || nx > n || ny > n || points[nx][ny].first != -1 || points[nx][ny].second != -1) continue; if(d < 2) ans[i][j] = direc[d].second.first; else ans[i][j] = direc[d].second.first, ans[nx][ny] = direc[d].second.second; break; } if(ans[i][j] == '-') { cout << INVALID << "\n"; return; } } } cout << VALID << "\n"; for(int i = 1;i <= n;i++) { for(int j = 1;j <= n;j++) { cout << ans[i][j]; } cout << "\n"; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input2.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int t = 1; // cin >> t; while(t--) { solve(); } return 0; }
cpp
1307
D
D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n)  — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n)  — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3 1 3 5 1 2 2 3 3 4 3 5 2 4 OutputCopy3 InputCopy5 4 2 2 4 1 2 2 3 3 4 4 5 OutputCopy3 NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "shortest paths", "sortings" ]
// Don't Quit O_O #include <bits/stdc++.h> using namespace std; #define lli long long int #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; template<class T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; #define INF LLONG_MAX #define pb push_back #define ff first #define ss second #define mod 1000000007 // Will become Master ^_^ vector<vector<lli>> adj(200005); lli vis[200005]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); lli t=1,n,i; // cin>>t; while(t--) { lli m,k; cin>>n>>m>>k; lli sp[k]; set<lli> special; for(i=0;i<k;i++) { cin>>sp[i]; special.insert(sp[i]); } lli u[m],v[m]; for(i=0;i<m;i++) { cin>>u[i]>>v[i]; adj[u[i]].pb(v[i]); adj[v[i]].pb(u[i]); } lli dist[n+1]; lli par[n+1]; queue<pair<lli,lli>> q; q.push({1,0}); dist[1]=0; par[1]=0; while((int)q.size()) { pair<lli,lli> p=q.front(); vis[p.ff]=1; q.pop(); for(auto &x : adj[p.ff]) { if(!vis[x]) { q.push({x,p.ss+1}); par[x]=p.ff; dist[x]=p.ss+1; vis[x]=1; } } } for(i=1;i<=n;i++) vis[i]=0; q.push({n,0}); lli distn[n+2]; distn[n]=0; while((int)q.size()) { pair<lli,lli> p=q.front(); vis[p.ff]=1; q.pop(); for(auto &x : adj[p.ff]) { if(!vis[x]) { q.push({x,p.ss+1}); distn[x]=p.ss+1; vis[x]=1; } } } set<lli> path; path.insert(n); lli curr=par[n]; while(curr!=1) { // cout<<curr<<" "; path.insert(curr); curr=par[curr]; } path.insert(1); // cout<<"\n"; lli count=0; bool flag=false; for(i=0;i<m;i++) { if(special.count(u[i]) && special.count(v[i])) flag=true; } for(i=0;i<k;i++) { if(!path.count(sp[i])) count++; } // cout<<count<<" "<<flag<<" "<<dist[n]<<"\n"; lli nearest[n+2][2]; for(i=1;i<=n;i++) { vis[i]=0; if(path.count(i)) { q.push({i,0}); vis[i]=1; nearest[i][0]=0; nearest[i][1]=i; } } while((int)q.size()) { pair<lli,lli> p=q.front(); vis[p.ff]=1; q.pop(); for(auto &x : adj[p.ff]) { if(!vis[x]) { q.push({x,p.ss+1}); nearest[x][0]=p.ss+1; nearest[x][1]=nearest[p.ff][1]; vis[x]=1; } } } // for(i=1;i<=n;i++) // cout<<nearest[i][0]<<" "<<nearest[i][1]<<"\n"; if(flag) { cout<<dist[n]; continue; } else { lli mx=0,ans=0; vector<pair<lli,lli>> v; for(i=0;i<k;i++) { v.pb({dist[sp[i]], distn[sp[i]]}); } sort(v.begin(),v.end()); lli suff[k]; suff[k-1]=v[k-1].ss; for(i=k-2;i>=0;i--) { suff[i]=max(suff[i+1],v[i+1].ss); } for(i=0;i<k-1;i++) { ans=max(ans,v[i].ff+1+suff[i]); } ans=min(ans,dist[n]); cout<<ans; // vector<lli> v; // lli ans=0,mn=n+10; // for(i=0;i<k;i++) // { // if(path.count(sp[i])) // { // v.pb(dist[sp[i]]); // mn=min(mn,dist[sp[i]]); // } // } // if(mn==n+10) // { // lli mx=0,pos; // for(i=0;i<k;i++) // { // mx=max(mx,nearest[sp[i]][0]+distn[nearest[sp[i]][1]]); // if(mx==nearest[sp[i]][0]+distn[nearest[sp[i]][1]]) // pos=sp[i]; // } // for(i=0;i<k;i++) // { // if(pos==sp[i]) // continue; // ans=max(ans,dist[sp[i]]+1+mx); // } // if(ans>dist[n]) // ans=dist[n]; // cout<<ans<<"\n"; // continue; // } // // cout<<dist[n]<<"*"; // for(i=0;i<k;i++) // { // if(!path.count(sp[i])) // { // if(dist[sp[i]]+1>=mn) // ans=max(ans,dist[n]); // else // ans=max(dist[n]-(mn-dist[sp[i]]-1),ans); // } // } // // cout<<ans<<"*"<<mn<<"*"; // sort(v.begin(),v.end()); // mn=n+10; // for(i=0;i<(int)v.size()-1;i++) // { // mn=min(mn,v[i+1]-v[i]); // ans=max(ans,dist[n]-mn+1); // } // // cout<<ans<<"*"; // lli mx=0,pos=0; // for(i=0;i<k;i++) // { // if(!path.count(sp[i])) // { // mx=max(mx,nearest[sp[i]][0]+distn[nearest[sp[i]][1]]); // if(mx==nearest[sp[i]][0]+distn[nearest[sp[i]][1]]) // pos=sp[i]; // } // } // // cout<<mx<<"@@"<<pos<<"\n"; // for(i=0;i<k;i++) // { // if(pos==sp[i] || path.count(sp[i])) // continue; // ans=max(ans,dist[sp[i]]+1+mx); // } // // cout<<ans<<"*"; // if(ans>dist[n]) // ans=dist[n]; // cout<<ans; } } }
cpp
1315
C
C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 OutputCopy1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
[ "greedy" ]
#include <bits/stdc++.h> using namespace std; void solve(){ int n; cin>>n; int cs; vector <int> s,c; for (int i = 1 ; i <= 2*n ; i ++){ s.push_back(i); } for (int i = 0 ; i < n ; i ++){ cin>>cs; c.push_back(cs); remove(s.begin(),s.end(),cs); s.pop_back(); } bool found = false; vector<int> ans; for(auto x:c){ found = false; for(auto y:s){ if(x<y){ ans.push_back(y); remove(s.begin(),s.end(),y); s.pop_back(); found = true; break; } } if (not found){ cout<<-1; return ; } } for(int i = 0 ; i < n ; i++){ cout<<c[i]<<" "<<ans[i]<<" "; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n;cin>>n; while(n--){ solve(); cout<<'\n'; } return 0; }
cpp
1290
E
E. Cartesian Tree time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIldar is the algorithm teacher of William and Harris. Today; Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William.A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows: If the sequence is empty, return an empty tree; Let the position of the maximum element be xx; Remove element on the position xx from the sequence and break it into the left part and the right part (which might be empty) (not actually removing it, just taking it away temporarily); Build cartesian tree for each part; Create a new vertex for the element, that was on the position xx which will serve as the root of the new tree. Then, for the root of the left part and right part, if exists, will become the children for this vertex; Return the tree we have gotten.For example, this is the cartesian tree for the sequence 4,2,7,3,5,6,14,2,7,3,5,6,1: After teaching what the cartesian tree is, Ildar has assigned homework. He starts with an empty sequence aa.In the ii-th round, he inserts an element with value ii somewhere in aa. Then, he asks a question: what is the sum of the sizes of the subtrees for every node in the cartesian tree for the current sequence aa?Node vv is in the node uu subtree if and only if v=uv=u or vv is in the subtree of one of the vertex uu children. The size of the subtree of node uu is the number of nodes vv such that vv is in the subtree of uu.Ildar will do nn rounds in total. The homework is the sequence of answers to the nn questions.The next day, Ildar told Harris that he has to complete the homework as well. Harris obtained the final state of the sequence aa from William. However, he has no idea how to find the answers to the nn questions. Help Harris!InputThe first line contains a single integer nn (1≤n≤1500001≤n≤150000).The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n). It is guarenteed that each integer from 11 to nn appears in the sequence exactly once.OutputPrint nn lines, ii-th line should contain a single integer  — the answer to the ii-th question.ExamplesInputCopy5 2 4 1 5 3 OutputCopy1 3 6 8 11 InputCopy6 1 2 4 5 6 3 OutputCopy1 3 6 8 12 17 NoteAfter the first round; the sequence is 11. The tree is The answer is 11.After the second round, the sequence is 2,12,1. The tree is The answer is 2+1=32+1=3.After the third round, the sequence is 2,1,32,1,3. The tree is The answer is 2+1+3=62+1+3=6.After the fourth round, the sequence is 2,4,1,32,4,1,3. The tree is The answer is 1+4+1+2=81+4+1+2=8.After the fifth round, the sequence is 2,4,1,5,32,4,1,5,3. The tree is The answer is 1+3+1+5+1=111+3+1+5+1=11.
[ "data structures" ]
// LUOGU_RID: 102594139 #include<bits/stdc++.h> using namespace std; #define ll long long #define N 200010 #define inf (1e9) ll n; ll a[N]; ll ans[N]; ll pos[N]; struct sgt{ ll sum[N<<2],tag1[N<<2],tag2[N<<2],mx[N<<2],smx[N<<2],cn[N<<2],cnmx[N<<2]; inline void pushup(ll x){ sum[x]=sum[x<<1]+sum[x<<1|1]; cn[x]=cn[x<<1]+cn[x<<1|1]; if(mx[x<<1]==mx[x<<1|1]){ smx[x]=max(smx[x<<1],smx[x<<1|1]); mx[x]=mx[x<<1]; cnmx[x]=cnmx[x<<1]+cnmx[x<<1|1]; } if(mx[x<<1]<mx[x<<1|1]){ mx[x]=mx[x<<1|1]; smx[x]=max(mx[x<<1],smx[x<<1|1]); cnmx[x]=cnmx[x<<1|1]; } if(mx[x<<1]>mx[x<<1|1]){ mx[x]=mx[x<<1]; smx[x]=max(mx[x<<1|1],smx[x<<1]); cnmx[x]=cnmx[x<<1]; } return ; } inline void pushdown(ll x){ if(tag1[x]){ ll u=tag1[x]; if(mx[x<<1]==mx[x<<1|1]){ mx[x<<1]+=u;mx[x<<1|1]+=u; sum[x<<1]+=u*(cnmx[x<<1]);sum[x<<1|1]+=u*(cnmx[x<<1|1]); tag1[x<<1]+=u;tag1[x<<1|1]+=u; }else{ if(mx[x<<1]<mx[x<<1|1]){ mx[x<<1|1]+=u; sum[x<<1|1]+=u*(cnmx[x<<1|1]); tag1[x<<1|1]+=u; }else{ mx[x<<1]+=u; sum[x<<1]+=u*(cnmx[x<<1]); tag1[x<<1]+=u; } } tag1[x]=0; } if(tag2[x]){ ll u=tag2[x]; if(mx[x<<1]==mx[x<<1|1]){ smx[x<<1]+=u;smx[x<<1|1]+=u; sum[x<<1]+=u*(cn[x<<1]-cnmx[x<<1]);sum[x<<1|1]+=u*(cn[x<<1|1]-cnmx[x<<1|1]); tag2[x<<1]+=u;tag2[x<<1|1]+=u; }else{ if(mx[x<<1]<mx[x<<1|1]){ mx[x<<1]+=u; smx[x<<1]+=u;smx[x<<1|1]+=u; sum[x<<1]+=u*(cn[x<<1]);sum[x<<1|1]+=u*(cn[x<<1|1]-cnmx[x<<1|1]); tag2[x<<1]+=u;tag1[x<<1]+=u;tag2[x<<1|1]+=u; }else{ mx[x<<1|1]+=u; smx[x<<1]+=u;smx[x<<1|1]+=u; sum[x<<1]+=u*(cn[x<<1]-cnmx[x<<1]);sum[x<<1|1]+=u*(cn[x<<1|1]); tag2[x<<1]+=u;tag2[x<<1|1]+=u;tag1[x<<1|1]+=u; } } tag2[x]=0; }return ; } inline void update(ll o,ll l,ll r,ll x,ll y,ll z){ if(x<=l&&r<=y){ if(mx[o]<=z)return ; if(z>smx[o]){ sum[o]+=(z-mx[o])*cnmx[o]; tag1[o]+=(z-mx[o]);mx[o]=z; return ; } }pushdown(o); ll mid=(l+r)>>1; if(mid>=x)update(o<<1,l,mid,x,y,z); if(mid<y)update(o<<1|1,mid+1,r,x,y,z); pushup(o); return ; } inline void upd(ll o,ll l,ll r,ll x,ll y){ if(l==r){ sum[o]=mx[o]=y; smx[o]=-inf;cn[o]=cnmx[o]=1; return ; }pushdown(o); ll mid=(l+r)>>1; if(mid>=x)upd(o<<1,l,mid,x,y); else upd(o<<1|1,mid+1,r,x,y); pushup(o); return ; } inline void add(ll o,ll l,ll r,ll x,ll y){ if(x<=l&&r<=y){ sum[o]+=cn[o];mx[o]++;smx[o]++; tag1[o]++;tag2[o]++; return ; } pushdown(o); ll mid=(l+r)>>1; if(mid>=x)add(o<<1,l,mid,x,y); if(mid<y)add(o<<1|1,mid+1,r,x,y); pushup(o); return ; } inline ll ask(ll o,ll l,ll r,ll x,ll y){ if(x>y)return 0; if(x<=l&&r<=y)return cn[o]; pushdown(o); ll an=0;ll mid=(l+r)>>1; if(mid>=x)an+=ask(o<<1,l,mid,x,y); if(mid<y)an+=ask(o<<1|1,mid+1,r,x,y); return an; } inline void build(ll o,ll l,ll r){ sum[o]=tag1[o]=tag2[o]=mx[o]=smx[o]=cn[o]=cnmx[o]=0; if(l==r)return ; ll mid=(l+r)>>1; build(o<<1,l,mid);build(o<<1|1,mid+1,r); return ; } }g; inline void suan(){ for(int i=1;i<=n;i++)pos[a[i]]=i; g.build(1,1,n); for(int i=1;i<=n;i++){ ll o=pos[i]; ll p=g.ask(1,1,n,1,o-1); if(o>1)g.update(1,1,n,1,o-1,p+1); if(o<n)g.add(1,1,n,o+1,n); g.upd(1,1,n,o,i+1); ans[i]+=g.sum[1]; }return ; } int main() { // freopen("test1.in","r",stdin); //freopen(".in","r",stdin); //freopen("test1.out","w",stdout); ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); cin>>n;for(int i=1;i<=n;i++)cin>>a[i]; suan(); reverse(a+1,a+n+1); suan(); for(int i=1;i<=n;i++)cout<<ans[i]-1ll*i*(i+2)<<'\n'; return 0; }
cpp
1301
D
D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to: in the case 'U' to the cell (i−1,j)(i−1,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j−1)(i,j−1); in the case 'R' to the cell (i,j+1)(i,j+1); He wants to run exactly kk kilometers, so he wants to make exactly kk moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4 OutputCopyYES 2 2 R 2 L InputCopy3 3 1000000000 OutputCopyNO InputCopy3 3 8 OutputCopyYES 3 2 R 2 D 1 LLRR InputCopy4 4 9 OutputCopyYES 1 3 RLD InputCopy3 4 16 OutputCopyYES 8 3 R 3 L 1 D 3 R 1 D 1 U 3 L 1 D NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
[ "constructive algorithms", "graphs", "implementation" ]
#include <bits/stdc++.h> using namespace std; #define int long long int n, m, k; signed main() { ios::sync_with_stdio(false); cin.tie(nullptr); cin >> n >> m >> k; int all = 4 * n * m - 2 * n - 2 * m; if (k > all) { cout << "NO\n"; return 0; } n--; m--; // else there is always a way vector<pair<int, string>> ans; { // first row if (m / 4) ans.push_back({m / 4, "RRRR"}); if (m % 4) ans.push_back({1, string(m % 4, 'R')}); if (m / 4) ans.push_back({m / 4, "LLLL"}); if (m % 4) ans.push_back({1, string(m % 4, 'L')}); } for (int i = 1; i <= n; i++) { ans.push_back({1, "D"}); if (m / 4) ans.push_back({m / 4, "RRRR"}); if (m % 4) ans.push_back({1, string(m % 4, 'R')}); if (m) ans.push_back({m, "UDL"}); } if (n / 4) ans.push_back({n / 4, "UUUU"}); ans.push_back({1, string(n % 4, 'U')}); vector<pair<int, string>> res; for (auto i : ans) { int len = (int)i.second.size() * i.first; if (len >= k) { if (k / (int)i.second.size()) res.push_back({k / (int)i.second.size(), i.second}); if (k % (int)i.second.size()) res.push_back({1, i.second.substr(0, k % (int)i.second.size())}); break; } else { k -= len; res.push_back(i); } } cout << "YES\n"; cout << res.size() << '\n'; for (auto i : res) { cout << i.first << ' ' << i.second << '\n'; } }
cpp
1291
F
F. Coffee Varieties (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. You can find the hard version in the Div. 1 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will: Tell you if acac is in SS; Add acac at the back of SS; If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 2n2k2n2k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 2n2k≤20 0002n2k≤20 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 2n2k2n2k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 2n2k≤20 0002n2k≤20 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2 N N Y N N N N OutputCopy? 1 ? 2 ? 3 ? 4 R ? 4 ? 1 ? 2 ! 3 InputCopy8 8 N N N N Y Y OutputCopy? 2 ? 6 ? 4 ? 5 ? 2 ? 5 ! 6 NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5.
[ "graphs", "interactive" ]
#include<bits/stdc++.h> using namespace std; #pragma GCC optimize ("Ofast") #define all(x) x.begin() , x.end() #define sze(x) (ll)(x.size()) #define mp(x , y) make_pair(x , y) #define wall cout<<"--------------------------------------\n"; typedef long long int ll; typedef pair<ll , ll> pll; typedef pair<int , int> pii; typedef double db; typedef pair<pll , ll> plll; typedef pair<int , pii> piii; typedef pair<pll , pll> pllll; const ll maxn = 1e6 + 17 , md = 1e9 + 7 , inf = 2e16; char c; bool a[maxn]; vector<ll> v[maxn]; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll n , k; cin>>n>>k; if(k > 1) k >>= 1; ll m = n / k , x = 0; for(ll i = 1 ; i <= n ; i++){ v[x].push_back(i); x += (i % k == 0); } for(ll t = 1 ; t < m ; t++){ for(ll s = 0 ; s < t ; s++){ if(s + t >= m) break; for(ll i = s ; i < m ; i += t){ for(auto j : v[i]){ cout<<"? "<<j<<endl; cin>>c; a[j] |= (c == 'Y'); } } cout<<"R"<<endl; } } ll cnt = 0; for(ll i = 1 ; i <= n ; i++) cnt += !a[i]; cout<<"! "<<cnt<<endl; return 0; }
cpp
1296
F
F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4 1 2 3 2 3 4 2 1 2 5 1 3 3 OutputCopy5 3 5 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 OutputCopy5 3 1 2 1 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 OutputCopy-1
[ "constructive algorithms", "dfs and similar", "greedy", "sortings", "trees" ]
#include<bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> //#include<boost/algorithm/string.hpp> //pragmas #pragma GCC optimize("O3") //types #define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) #define ll long long int #define ull unsigned long long int #define vec vector<long long int> #define pall pair<long long int, long long int> #define vecpair vector<pair<long long int,long long int>> #define vecvec(a, i, j) vector<vector<long long int>> a (i, vec (j, 0)) #define vecvecvec(a, i, j, k) vector<vector<vector<long long int>>> dp (i + 1, vector<vector<long long int>>(j + 1, vector<long long int>(k + 1, 0))) using namespace std; using namespace __gnu_pbds; //random stuff #define all(a) a.begin(),a.end() #define read(a) for (auto &x : a) cin >> x #define endl "\n" #define pb push_back #define print(a) for(auto x : a) cout << x << " "; cout << endl #define sp " " ll INF = 9223372036854775807; typedef tree<long long int, null_type, less<long long int>, rb_tree_tag, tree_order_statistics_node_update> indexed_set; struct custom_hash { static uint64_t splitmix64(uint64_t x) { x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } size_t operator()(uint64_t x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); } }; #define safe_map unordered_map<long long, int, custom_hash> //debug void __print(int x) {cerr << x;} void __print(long x) {cerr << x;} void __print(long long x) {cerr << x;} void __print(unsigned x) {cerr << x;} void __print(unsigned long x) {cerr << x;} void __print(unsigned long long x) {cerr << x;} void __print(float x) {cerr << x;} void __print(double x) {cerr << x;} void __print(long double x) {cerr << x;} void __print(char x) {cerr << '\'' << x << '\'';} void __print(const char *x) {cerr << '\"' << x << '\"';} void __print(const string &x) {cerr << '\"' << x << '\"';} void __print(bool x) {cerr << (x ? "true" : "false");} template<typename T, typename V> void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';} template<typename T> void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";} void _print() {cerr << "]\n";} template <typename T, typename... V> void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);} #ifndef ONLINE_JUDGE #define debug(x...) cerr << "[" << #x << "] = ["; _print(x) #define reach cerr<<"reached"<<endl #else #define debug(x...) #define reach #endif /*---------------------------------------------------------------------------------------------------------------------------*/ ll gcd(ll a, ll b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);} ll expo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;} void extendgcd(ll a, ll b, ll*v) {if (b == 0) {v[0] = 1; v[1] = 0; v[2] = a; return ;} extendgcd(b, a % b, v); ll x = v[1]; v[1] = v[0] - v[1] * (a / b); v[0] = x; return;} //pass an arry of size1 3 ll mminv(ll a, ll b) {ll arr[3]; extendgcd(a, b, arr); return arr[0];} //for non prime b ll mminvprime(ll a, ll b) {return expo(a, b - 2, b);} bool revsort(ll a, ll b) {return a > b;} void swap(int &x, int &y) {int temp = x; x = y; y = temp;} ll combination(ll n, ll r, ll m, ll *fact, ll *ifact) {ll val1 = fact[n]; ll val2 = ifact[n - r]; ll val3 = ifact[r]; return (((val1 * val2) % m) * val3) % m;} void google(int t) {cout << "Case #" << t << ": ";} vector<ll> sieve(int n) {int*arr = new int[n + 1](); vector<ll> vect; for (ll i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (ll j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;} ll mod_add(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;} ll mod_mul(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;} ll mod_sub(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;} ll mod_div(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m;} //only for prime m ll phin(ll n) {ll number = n; if (n % 2 == 0) {number /= 2; while (n % 2 == 0) n /= 2;} for (ll i = 3; i <= sqrt(n); i += 2) {if (n % i == 0) {while (n % i == 0)n /= i; number = (number / i * (i - 1));}} if (n > 1)number = (number / n * (n - 1)) ; return number;} //O(sqrt(N)) void precision(int a) {cout << setprecision(a) << fixed;} ll ceil_div(ll x, ll y){return (x + y - 1) / y;} unsigned long long power(unsigned long long x,ll y, ll p){unsigned long long res = 1;x = x % p; while (y > 0){if (y & 1)res = (res * x) % p;y = y >> 1;x = (x * x) % p;}return res;} unsigned long long modInverse(unsigned long long n,int p){return power(n, p - 2, p);} ll nCr(ll n,ll r, ll p){if (n < r)return 0;if (r == 0)return 1;unsigned long long fac[n + 1];fac[0] = 1;for (int i = 1; i <= n; i++)fac[i] = (fac[i - 1] * i) % p;return (fac[n] * modInverse(fac[r], p) % p* modInverse(fac[n - r], p) % p)% p;} ll accumulate(const vec &nums){ll sum = 0; for(auto x : nums) sum += x; return sum;} ll tmax(ll a, ll b, ll c = 0, ll d = -INF, ll e = -INF, ll f = -INF){return max(a, max(b, max(c, max(d, max(e, f)))));} int log2_floor(unsigned long long i) {return i ? __builtin_clzll(1) - __builtin_clzll(i) : -1;} /*--------------------------------------------------------------------------------------------------------------------------*/ ll n, m; vecpair edge; vecvec(sec, 5001, 5001); vector<ll> adj[5001]; vector<vector<ll>> query; bool cmp(const vec &a, const vec &b) {return a[2] < b[2];} //code starts int main() { fastio(); cin >> n; for(ll i = 1, u, v; i < n; i ++) cin >> u >> v, adj[u].pb(v), adj[v].pb(u), edge.pb({u, v}); cin >> m; for(ll i = 0; i < m; i ++) { vec cur(3); read(cur); query.pb(cur); } sort(all(query), cmp); for(auto &x : sec) for(auto &y : x) y = INF; for(ll i = 0; i < m; i ++) { vec p(5001, 0); ll s = query[i][0], e = query[i][1], b = query[i][2]; queue<ll> q; q.push(s); while(!q.empty()) { ll u = q.front(); q.pop(); if(u == e) { for(ll at = u; at != s; at = p[at]) { sec[at][p[at]] = b; sec[p[at]][at] = b; } break; } else { for(auto v : adj[u]) { if(p[v] == 0) { p[v] = u; q.push(v); } } } } } bool yes = 1; for(ll i = 0; i < m and yes; i ++) { vec p(5001, 0); ll s = query[i][0], e = query[i][1], b = query[i][2]; queue<ll> q; q.push(s); while(!q.empty()) { ll u = q.front(); q.pop(); if(u == e) { ll mb = INF; for(ll at = u; at != s; at = p[at]) { mb = min(mb, sec[at][p[at]]); } if(mb != b) yes = 0; break; } else { for(auto v : adj[u]) { if(p[v] == 0) { p[v] = u; q.push(v); } } } } } if(yes) for(auto x : edge) cout << min((ll)1e6, sec[x.first][x.second]) << sp; else cout << -1 << endl; } // There is an idea of a Patrick Bateman. Some kind of abstraction. // But there is no real me. Only an entity. Something illusory. // And though I can hide my cold gaze, and you can shake my hand and // feel flesh gripping yours, and maybe you can even sense our lifestyles // are probably comparable, I simply am not there.
cpp
1325
D
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.
[ "bitmasks", "constructive algorithms", "greedy", "number theory" ]
#include <bits/stdc++.h> #define int long long using namespace std; signed main() { int u, v; cin >> u >> v; if (u > v) { cout << -1; } else if (u == v && u != 0) { cout << 1 << endl; cout << u; } else if (u == v && u == 0) cout << 0; else { int t = v - u; if (t % 2) { cout << -1; return 0; } t /= 2; if (t & u) { cout << 3 << endl; cout << u << ' ' << t << ' ' << t; } else { cout << 2 << endl; cout << u + t << ' ' << t; } } return 0; }
cpp
1305
A
A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100)  — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000)  — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000)  — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2 3 1 8 5 8 4 5 3 1 7 5 6 1 2 OutputCopy1 8 5 8 4 5 5 1 7 6 2 1 NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.
[ "brute force", "constructive algorithms", "greedy", "sortings" ]
#pragma GCC optimize("O3") #include <bits/stdc++.h> #define fi first #define se second #define space " " #define endl "\n" #define mp make_pair #define pb push_back #define pf push_front #define md 1000000007 #define inf 1000000000 #define li 105 #define lo long long using namespace std; int T,n,m,k,a[li],b[li]; string s,t; vector<int> v; int main(){ scanf("%d",&T); while(T--){ scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d",&a[i]); } for(int i=1;i<=n;i++){ scanf("%d",&b[i]); } sort(a+1,a+n+1); sort(b+1,b+n+1); for(int i=1;i<=n;i++) printf("%d ",a[i]); printf("\n"); for(int i=1;i<=n;i++) printf("%d ",b[i]); printf("\n"); } return 0; }
cpp
1286
F
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.
[ "brute force", "constructive algorithms", "dp", "fft", "implementation", "math" ]
/* わんわん……わんだほーいっ☆ Wonderhoy! */ #include<bits/stdc++.h> using namespace std; typedef long long LL; typedef double DB; char buf[1<<21],*p1=buf,*p2=buf; #define getchar() (p1==p2 && (p2=(p1=buf)+fread(buf,1,1<<18,stdin),p1==p2)?EOF:*p1++) LL read() { LL x=0,f=1; char c=getchar(); while(c<'0' || c>'9') f=(c=='-'?-1:f),c=getchar(); while(c>='0' && c<='9') x=(x<<1)+(x<<3)+(c^'0'),c=getchar(); return x*f; } void write(LL x) { if(x>9) write(x/10); putchar(x%10+'0'); } LL n,a[20]; LL sum[1<<20],cnt[1<<20]; inline LL Abs(LL x){return x<0?-x:x;} inline LL lowbit(LL x){return x&(-x);} bool f[1<<20]; LL g[1<<20]; int main(){ n=read(); for(LL i=0;i<n;++i) { a[i]=read(); if(!a[i]) --i,--n; } for(LL S=1;S<(1<<n);++S) cnt[S]=cnt[S^lowbit(S)]+1; for(LL S=0;S<(1<<n);++S) { for(LL i=0;i<n;++i) { if((S>>i)&1) { sum[S]=sum[S^(1<<i)]+a[i]; break; } } } for(LL S=1;S<(1<<n);++S) if((cnt[S]^sum[S])&1) for(LL T=S&(S-1);T && !f[S];T=S&(T-1)) if(Abs(sum[T]-sum[T^S])<cnt[S]) f[S]=true; for(LL S=1;S<(1<<n);++S) { if(f[S] && !g[S]) { g[S]=1; LL U=((1<<n)-1)^S; for(LL T=U;T;T=U&(T-1)) g[S|T]=max(g[S|T],g[T]+1); } } write(n-g[(1<<n)-1]),puts(""); return 0; }
cpp
1324
E
E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23 16 17 14 20 20 11 22 OutputCopy3 NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good.
[ "dp", "implementation" ]
#include <bits/stdc++.h> using namespace std; #define uint unsigned long long int #define int long long int #define vi vector<int> #define ub upper_bound #define lb lower_bound #define vp vector<pair<int,int>> #define pb push_back #define po pop_back() #define pii pair<int,int> #define mod 1000000007 int dp[2001][2001]; int fun(int l,int r,int i,vi &v,int x,int h){ if(dp[i][x]!=-1)return dp[i][x]; if(i==v.size()){ if(x>=l && x<=r)return dp[i][x]=1; return dp[i][x]=0; } int a=0; if(i && x>=l && x<=r){ a++; } return dp[i][x]=a+max(fun(l,r,i+1,v,(x+v[i])%h,h),fun(l,r,i+1,v,(x+v[i]-1)%h,h)); } void solve(){ int n,h,l,r; cin>>n>>h>>l>>r; memset(dp,-1,sizeof(dp)); vi v(n); for(int i=0;i<n;i++)cin>>v[i]; int ans=fun(l,r,0,v,0,h); // if(ans==1933)cout<<ans-1; cout<<ans; } signed main (){ ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t=1; // cin>>t; while(t--){ solve(); } }
cpp
1288
C
C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2 OutputCopy5 InputCopy10 1 OutputCopy55 InputCopy723 9 OutputCopy157557417 NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1].
[ "combinatorics", "dp" ]
#include<bits/stdc++.h> using namespace std; typedef long long ll; const ll N = 1e5+10, M = 1050, inf = 1e6, mod = 1e9+7; ll add ( ll a , ll b) { return (a + b) % mod; } ll mul ( ll a , ll b) { return 1LL * a * b % mod; } ll fp( ll b , ll p) { if(!p) return 1; ll temp = fp(b,p/2); temp = mul(temp,temp); if(p&1) temp = mul(temp,b); return temp; } ll fact[N], inv[N]; ll nCr( ll n , ll r) { return mul(fact[n],mul(inv[n-r],inv[r])); } ll func(ll n, ll m) { return nCr(n + m - 1, m - 1); } // long loooooooooooooooong; void solve(ll kkkk, ll tttt) { ll n, m; cin >> m >> n; ll ans = 0; for (ll i = 1; i <= m; i++) { ll current = func(n - 1, i) * func(n, m - i + 1) % mod; ans += current % mod; ans %= mod; } cout << ans << endl; } void fast() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); } int main() { fact[0] = inv[0] = 1; for ( int i = 1 ; i < N ; i++) { fact[i] = mul(i,fact[i-1]); inv[i] = fp(fact[i],mod-2); } fast(); int t = 0, i = 0; // int t; cin >> t; // for (int i = 1; i <= t; i++) solve(t, i); return 0; }
cpp
1313
E
E. Concatenation with intersectiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVasya had three strings aa, bb and ss, which consist of lowercase English letters. The lengths of strings aa and bb are equal to nn, the length of the string ss is equal to mm. Vasya decided to choose a substring of the string aa, then choose a substring of the string bb and concatenate them. Formally, he chooses a segment [l1,r1][l1,r1] (1≤l1≤r1≤n1≤l1≤r1≤n) and a segment [l2,r2][l2,r2] (1≤l2≤r2≤n1≤l2≤r2≤n), and after concatenation he obtains a string a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2.Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions: segments [l1,r1][l1,r1] and [l2,r2][l2,r2] have non-empty intersection, i.e. there exists at least one integer xx, such that l1≤x≤r1l1≤x≤r1 and l2≤x≤r2l2≤x≤r2; the string a[l1,r1]+b[l2,r2]a[l1,r1]+b[l2,r2] is equal to the string ss. InputThe first line contains integers nn and mm (1≤n≤500000,2≤m≤2⋅n1≤n≤500000,2≤m≤2⋅n) — the length of strings aa and bb and the length of the string ss.The next three lines contain strings aa, bb and ss, respectively. The length of the strings aa and bb is nn, while the length of the string ss is mm.All strings consist of lowercase English letters.OutputPrint one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions.ExamplesInputCopy6 5aabbaabaaaabaaaaaOutputCopy4InputCopy5 4azazazazazazazOutputCopy11InputCopy9 12abcabcabcxyzxyzxyzabcabcayzxyzOutputCopy2NoteLet's list all the pairs of segments that Vasya could choose in the first example: [2,2][2,2] and [2,5][2,5]; [1,2][1,2] and [2,4][2,4]; [5,5][5,5] and [2,5][2,5]; [5,6][5,6] and [3,5][3,5];
[ "data structures", "hashing", "strings", "two pointers" ]
#include<bits/stdc++.h> #define ll long long using namespace std; const int N=2e6+10; int n,m,z[N],za[N],zb[N]; char a[N],b[N],s[N],t[N]; void Z(char *s,int n){ z[1]=n; for(int i=2,l=0,r=0;i<=n;i++){ if(i<=r)z[i]=min(z[i-l+1],r-i+1); else z[i]=0; while(i+z[i]<=n&&s[i+z[i]]==s[z[i]+1])++z[i]; if(i+z[i]-1>r)l=i,r=i+z[i]-1; } } struct tree_array{ int c1[N];ll c2[N]; void add(int i,int v1,ll v2){++i;for(;i<=m;i+=i&-i)c1[i]+=v1,c2[i]+=v2;} int sum1(int i){++i;int s=0;for(;i;i-=i&-i)s+=c1[i];return s;} ll sum2(int i){++i;ll s=0;for(;i;i-=i&-i)s+=c2[i];return s;} }tr; signed main(){ scanf("%d%d%s%s%s",&n,&m,a+1,b+1,s+1); for(int i=1;i<m;i++)t[i]=s[i]; t[m]='*'; for(int i=1;i<=n;i++)t[m+i]=a[i]; Z(t,n+m); for(int i=1;i<=n;i++)za[i]=z[m+i]; for(int i=1;i<m;i++)t[i]=s[m-i+1]; t[m]='*'; for(int i=1;i<=n;i++)t[m+i]=b[n-i+1]; Z(t,n+m); for(int i=1;i<=n;i++)zb[i]=z[m+n-i+1]; int r=min(m-2,n); for(int i=1;i<=r;i++)tr.add(m-1-zb[i],1,zb[i]); ll ans=0; for(int l=1;l<=n;l++){ if(r<n)++r,tr.add(m-1-zb[r],1,zb[r]); ans+=1ll*tr.sum1(za[l])*(za[l]-m+1)+tr.sum2(za[l]); tr.add(m-1-zb[l],-1,-zb[l]); } printf("%lld\n",ans); }
cpp
1288
C
C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2 OutputCopy5 InputCopy10 1 OutputCopy55 InputCopy723 9 OutputCopy157557417 NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1].
[ "combinatorics", "dp" ]
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define all(v) ((v).begin()), ((v).end()) #define siz(v) ((int)((v).size())) #define clr(v, d) memset(v, d, sizeof(v)) #define rep(i, v) for (int i = 0; i < siz(v); ++i) #define fo(i, n) for (int i = 0; i < (int)(n); ++i) #define fp(i, j, n) for (long long i = (j); i <= (long long)(n); ++i) #define fn(i, j, n) for (int i = (j); i >= (int)(n); --i) #define fvec(i, vec) for (auto i : vec) #define pb push_back #define MP make_pair #define mine(x, y, z) min(x, min(y, z)) #define maxe(x, y, z) max(x, max(y, z)) #define F first #define S second typedef unsigned long long ull; typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef pair<ll,ll> pll; typedef pair<int,int> pi; typedef vector<pll> vp; typedef vector< long long> vll; typedef vector<double> vd; typedef vector<vi> vvi; typedef vector<vd> vvd; typedef vector<string> vs; typedef tree< pll, null_type, less<pll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; #define setp(item) cout<<fixed<<setprecision(item); ll gcd(ll a, ll b) { return ((b == 0) ? a : gcd(b, a % b)); } ll lcm(ll a,ll b){return (a*b)/gcd(a,b);} const ll OO =1e18, mod = 1e9+7,mod2=1e9+9, N =2e5+5,M=30,MOD=998244353, minOO=LLONG_MIN; /// هذا الحل من وحي خيال المؤلف واي تشابه بينه و بين اي حل اخر ما هو الا محض الصدفة ll add ( ll a , ll b) { return (a + b) % mod; } ll mul ( ll a , ll b) { return 1LL * a * b % mod; } ll fop( ll b , ll p) { if(!p) return 1; ll temp = fop(b,p/2)%mod; temp = mul(temp,temp); if(p&1) temp = mul(temp,b); return temp%mod; } ll fact[N], inv[N]; ll nCr( ll n , ll r) { return mul(fact[n],mul(inv[n-r],inv[r])); } ll nPr( ll n , ll r) { return mul(nCr(n,r),fact[r]); } void testCase(ll n) { fact[0] = inv[0] = 1; for ( ll i = 1 ; i <= n ; i++) { fact[i] = mul(i,fact[i-1]); inv[i] = fop(fact[i],mod-2); } } void func(int inde) { ll num,m;cin>>num>>m; cout<<nCr(num+2*m-1,2*m); } int main() { //freopen("input.txt","rt",stdin); //freopen("output.txt","wt",stdout); ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); ll t=1; // cin>>t; testCase(N-3); ll index=1; while (t--){ func(index++); } return 0; }
cpp
1284
A
A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12 sin im gye gap eul byeong jeong mu gi gyeong yu sul hae ja chuk in myo jin sa o mi sin 14 1 2 3 4 10 11 12 13 73 2016 2017 2018 2019 2020 OutputCopysinyu imsul gyehae gapja gyeongo sinmi imsin gyeyu gyeyu byeongsin jeongyu musul gihae gyeongja NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.
[ "implementation", "strings" ]
#include <iostream> #include <iterator> #include <algorithm> #include <bits/stdc++.h> using namespace std; typedef long long int ll; typedef long double ld; typedef std::vector<int> vi; typedef std::vector<ll> vll; typedef std::vector<ld> vld; typedef std::vector<std::vector<ll>> vvll; typedef std::vector<std::vector<ld>> vvld; typedef std::vector<std::vector<std::vector<ll>>> vvvll; typedef std::vector<string> vstr; typedef std::vector<std::pair<ll, ll>> vpll; typedef std::pair<ll, ll> pll; #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define ordered_set tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> #define fast \ ios_base::sync_with_stdio(0); \ cin.tie(0); \ cout.tie(0) #define pb push_back #define nl "\n" #define all(c) (c).begin(), (c).end() #define iotam1 cout << -1 << nl #define cty cout << "YES" << nl #define ctn cout << "NO" << nl #define lmax LLONG_MAX #define lmin LLONG_MIN #define sz(v) (v).size() #define deci(n) fixed << setprecision(n) #define c(x) cout << (x) #define csp(x) cout << (x) << " " #define c1(x) cout << (x) << nl #define c2(x, y) cout << (x) << " " << (y) << nl #define c3(x, y, z) cout << (x) << " " << (y) << " " << (z) << nl #define c4(a, b, c, d) cout << (a) << " " << (b) << " " << (c) << " " << (d) << nl #define c5(a, b, c, d, e) cout << (a) << " " << (b) << " " << (c) << " " << (d) << " " << (e) << nl #define c6(a, b, c, d, e, f) cout << (a) << " " << (b) << " " << (c) << " " << (d) << " " << (e) << " " << (f) << nl #define f(i_itr, a, n) for (ll i_itr = a; i_itr < n; i_itr++) #define rev_f(i_itr, n, a) for (ll i_itr = n; i_itr > a; i_itr--) #define arri(n, arr) \ for (ll i_itr = 0; i_itr < n; i_itr++) \ cin >> arr[i_itr] #define a_arri(n, m, arr) \ for (ll i_itr = 0; i_itr < n; i_itr++) \ for (ll j_itr = 0; j_itr < m; j_itr++) \ cin >> arr[i_itr][j_itr] #define pb push_back #define fi first #define se second #define print(vec, a, b) \ for (ll i_itr = a; i_itr < b; i_itr++) \ cout << vec[i_itr] << " "; \ cout << "\n"; #define input(vec, a, b) \ for (ll i_itr = a; i_itr < b; i_itr++) \ cin >> vec[i_itr]; #define ms(a, val) memset(a, val, sizeof(a)) const ll mod = 1000000007; const long double pi = 3.14159265358979323846264338327950288419716939937510582097494459230; ll pct(ll x) { return __builtin_popcount(x); } // #of set bits ll poww(ll a, ll b) { ll res = 1; while (b) { if (b & 1) res = (res * a); a = (a * a); b >>= 1; } return res; } ll modI(ll a, ll m = mod) { ll m0 = m, y = 0, x = 1; if (m == 1) return 0; while (a > 1) { ll q = a / m; ll t = m; m = a % m; a = t; t = y; y = x - q * y; x = t; } if (x < 0) x += m0; return x; } ll powm(ll a, ll b, ll m = mod) { ll res = 1; while (b) { if (b & 1) res = (res * a) % m; a = (a * a) % m; b >>= 1; } return res; } //******************************************************************************************************************************************* / const ll N=2e5+5; string strs[N]; string strs2[N]; void ok_boss() { ll n,m; cin >> n>>m; f(i,0,n) cin>>strs[i]; f(i,0,m) cin>>strs2[i]; ll tt,tk; cin>>tt; while(tt--) { cin>>tk; cout << strs[(tk-1)%n] << strs2[(tk-1)%m] << endl; } return; } int main() { fast; /// std::cout << fixed<<setprecision(15); ///activate it if the answers are in decimal. ll qq_itr = 1; //cin >> qq_itr; while (qq_itr--) ok_boss(); return 0; }
cpp
1303
B
B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3 5 1 1 8 10 10 1000000 1 1000000 OutputCopy5 8 499999500000 NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good.
[ "math" ]
#include<bits/stdc++.h> #define ll long long int #define pii pair<ll,ll> using namespace std ; void solve() { ll n,g,b ; cin>>n>>g>>b ; ll good_days = n/2/g*g + (ll)(ceil(n/2.0) - n/2/g*g); ll bad_days = ((n/2/g-1)*b) + (ceil(n/2.0) - n/2/g*g != 0 ? b : 0); ll rem_days = max(0LL,(n-good_days-bad_days)) ; cout<<good_days+bad_days+rem_days<<endl; // cout<<good_days<<" "<<bad_days<<endl; } int main(){ ios::sync_with_stdio(0); cin.tie(0); ll T ; cin>>T ; while(T--){ solve() ; } } bool isPowerOfTwo (int x) { return x && (!(x&(x-1))); }
cpp
1296
D
D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns. You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster. Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3 7 10 50 12 1 8 OutputCopy5 InputCopy1 1 100 99 100 OutputCopy1 InputCopy7 4 2 1 1 3 5 4 2 7 6 OutputCopy6
[ "greedy", "sortings" ]
#include<iostream> using namespace std; #include <iostream> #include <cmath> #include <algorithm> #include <bits/stdc++.h> #define ll long long #define fi first #define se second #define sst string #define pb push_back #define maxco 100000+5 #define lld long double #define cha ios_base::sync_with_stdio(false); #define ffl cout.flush(); #define phi acos(-1) #define mod 1000000007 ll n,m; ll dp[5006][3]; ll s[200068]; map<ll,ll> cnt; vector <ll> vec; int main(){ cha ll n,a,b,k; cin>>n>>a>>b>>k; for(ll i=1;i<=n;i++){ cin>>s[i]; s[i]%=(a+b); if(s[i]==0){ s[i]=a+b; } } ll ans=0; sort(s+1,s+n+1); for(ll i=1;i<=n;i++){ if(s[i]<=a){ ans++; } else{ s[i]-=a; ll need=s[i]+a-1; need/=a; if(need<=k){ ans++; k-=need; } else{ break; } } } cout<<ans; } /* 3 5 1 7 4 6 2 9 3 8 1 4 7 3 6 9 5 8 2 1 5 9 13 4 8 12 16 7 11 15 3 10 14 2 6 */
cpp
1290
E
E. Cartesian Tree time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIldar is the algorithm teacher of William and Harris. Today; Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William.A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows: If the sequence is empty, return an empty tree; Let the position of the maximum element be xx; Remove element on the position xx from the sequence and break it into the left part and the right part (which might be empty) (not actually removing it, just taking it away temporarily); Build cartesian tree for each part; Create a new vertex for the element, that was on the position xx which will serve as the root of the new tree. Then, for the root of the left part and right part, if exists, will become the children for this vertex; Return the tree we have gotten.For example, this is the cartesian tree for the sequence 4,2,7,3,5,6,14,2,7,3,5,6,1: After teaching what the cartesian tree is, Ildar has assigned homework. He starts with an empty sequence aa.In the ii-th round, he inserts an element with value ii somewhere in aa. Then, he asks a question: what is the sum of the sizes of the subtrees for every node in the cartesian tree for the current sequence aa?Node vv is in the node uu subtree if and only if v=uv=u or vv is in the subtree of one of the vertex uu children. The size of the subtree of node uu is the number of nodes vv such that vv is in the subtree of uu.Ildar will do nn rounds in total. The homework is the sequence of answers to the nn questions.The next day, Ildar told Harris that he has to complete the homework as well. Harris obtained the final state of the sequence aa from William. However, he has no idea how to find the answers to the nn questions. Help Harris!InputThe first line contains a single integer nn (1≤n≤1500001≤n≤150000).The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n). It is guarenteed that each integer from 11 to nn appears in the sequence exactly once.OutputPrint nn lines, ii-th line should contain a single integer  — the answer to the ii-th question.ExamplesInputCopy5 2 4 1 5 3 OutputCopy1 3 6 8 11 InputCopy6 1 2 4 5 6 3 OutputCopy1 3 6 8 12 17 NoteAfter the first round; the sequence is 11. The tree is The answer is 11.After the second round, the sequence is 2,12,1. The tree is The answer is 2+1=32+1=3.After the third round, the sequence is 2,1,32,1,3. The tree is The answer is 2+1+3=62+1+3=6.After the fourth round, the sequence is 2,4,1,32,4,1,3. The tree is The answer is 1+4+1+2=81+4+1+2=8.After the fifth round, the sequence is 2,4,1,5,32,4,1,5,3. The tree is The answer is 1+3+1+5+1=111+3+1+5+1=11.
[ "data structures" ]
// LUOGU_RID: 101586530 #include <bits/stdc++.h> using LL = long long; const int inf32 = 1e9; struct SNode { SNode* son[2]{0}; LL sum{0}; int tag1{0}, tag2{inf32}; int cnt{0}, len{0}, max[2]{-inf32, -inf32}; }; #define L(p) p->son[0] #define R(p) p->son[1] void SBuild(SNode* &p, int l, int r) { p = new SNode{}; if (l == r) return; int mid = l + r >> 1; SBuild(L(p), l, mid); SBuild(R(p), mid + 1, r); } void SUp(SNode* p) { p->len = L(p)->len + R(p)->len; p->sum = L(p)->sum + R(p)->sum; if (L(p)->max[0] > R(p)->max[0]) { p->max[0] = L(p)->max[0]; p->max[1] = std::max(L(p)->max[1], R(p)->max[0]); } else if (L(p)->max[0] < R(p)->max[0]) { p->max[0] = R(p)->max[0]; p->max[1] = std::max(R(p)->max[1], L(p)->max[0]); } else { p->max[0] = L(p)->max[0]; p->max[1] = std::max(L(p)->max[1], R(p)->max[1]); } p->cnt = 0; if (L(p)->max[0] == p->max[0]) p->cnt += L(p)->cnt; if (R(p)->max[0] == p->max[0]) p->cnt += R(p)->cnt; } void SAddTag1(SNode* p, int tag) { p->tag1 += tag; p->tag2 += tag; p->max[0] += tag; p->max[1] += tag; p->sum += 1ll * p->len * tag; } void SAddTag2(SNode* p, int tag) { if (tag < p->max[0]) { p->sum -= 1ll * (p->max[0] - tag) * p->cnt; p->max[0] = p->tag2 = tag; } } void SDown(SNode* p) { if (p->tag1) { SAddTag1(L(p), p->tag1); SAddTag1(R(p), p->tag1); p->tag1 = 0; } if (p->tag2 < inf32) { SAddTag2(L(p), p->tag2); SAddTag2(R(p), p->tag2); p->tag2 = inf32; } } void SUpdate1(SNode* p, int l, int r, int x, int y, int v) { if (x <= l && r <= y) return SAddTag1(p, v); int mid = l + r >> 1; SDown(p); if (x <= mid) SUpdate1(L(p), l, mid, x, y, v); if (y > mid) SUpdate1(R(p), mid + 1, r, x, y, v); SUp(p); } void SUpdate2(SNode* p, int l, int r, int x, int y, int v) { if (!p->cnt) return; if (v >= p->max[0]) return; if (x <= l && r <= y && v >= p->max[1]) return SAddTag2(p, v); int mid = l + r >> 1; SDown(p); if (x <= mid) SUpdate2(L(p), l, mid, x, y, v); if (y > mid) SUpdate2(R(p), mid + 1, r, x, y, v); SUp(p); } void SMark(SNode* p, int l, int r, int x, int v) { if (l == r) { p->cnt = 1; p->len = 1; p->sum = v; p->max[0] = v; return; } int mid = l + r >> 1; SDown(p); if (x <= mid) SMark(L(p), l, mid, x, v); else SMark(R(p), mid + 1, r, x, v); SUp(p); } #undef L #undef R const int max_n = 1.5e5 + 5; int n, a[max_n], p[max_n], rk[max_n], bitSum[max_n]; void BITAdd(int x, int v) {for (; x <= n; x += x & -x) bitSum[x] += v;} int BITQuery(int x) { int v = 0; for (; x; x -= x & -x) v += bitSum[x]; return v; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); p[a[i]] = i; rk[a[i]] = BITQuery(a[i]) + 1; BITAdd(a[i], 1); } SNode *sRoot1, *sRoot2; SBuild(sRoot1, 1, n); SBuild(sRoot2, 1, n); for (int i = 1; i <= n; i++) { int pos = p[i], _pos = rk[i]; SMark(sRoot1, 1, n, pos, 0), SMark(sRoot2, 1, n, pos, i + 1); if (pos < n) SUpdate1(sRoot1, 1, n, pos + 1, n, -1); if (pos < n) SUpdate2(sRoot1, 1, n, pos + 1, n, -_pos); if (pos < n) SUpdate1(sRoot2, 1, n, pos + 1, n, 1); if (pos > 1) SUpdate2(sRoot2, 1, n, 1, pos - 1, _pos); printf("%lld\n", sRoot1->sum + sRoot2->sum - i); } return 0; }
cpp
13
E
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
[ "data structures", "dsu" ]
#include <bits/stdc++.h> typedef int32_t ll; using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); ll n, m; cin >> n >> m; const ll c = 990; ll nt[n]; for (ll i = 0; i < n; i++) { ll e; cin >> e; nt[i] = i + e; } ll nc[n]; ll cc[n]; for (ll i = n-1; i >= 0; i--) { ll t = nt[i]; if (t >= n || t / c != i / c) { nc[i] = t; cc[i] = 1; } else { nc[i] = nc[t]; cc[i] = cc[t] + 1; } } for (ll i = 0; i < m; i++) { ll op; cin >> op; if (op == 1) { ll x; cin >> x; x--; ll s = 0; while (nc[x] < n) { s += cc[x]; x = nc[x]; //cout << x << ' '; } //cout << '\n'; while (nt[x] < n) { s++; x = nt[x]; //cout << x << ' '; } //cout << '\n'; cout << x+1 << ' ' << s+1 << '\n'; //cout << nt << cc << '\n'; } else { ll x, y; cin >> x >> y; x--; nt[x] = x+y; ll l = x/c*c; ll r = l + c; ll mn = min(n, r); for (ll k = x; k >= l; k--) { ll t = nt[k]; if (t >= mn) { nc[k] = t; cc[k] = 1; } else { nc[k] = nc[t]; cc[k] = cc[t] + 1; } } } } }
cpp
1303
A
A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3 010011 0 1111000 OutputCopy2 0 0 NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).
[ "implementation", "strings" ]
#include <bits/stdc++.h> #define ll long long using namespace std; int main(){ int t ; cin>>t; while(t--){ string a; int k=0 ; cin>>a; for(int i=a.find('1') ;i<a.find_last_of('1');i++){ if(a[i]=='0'){ k++; } } cout <<k<<endl; } return 0; }
cpp
1293
A
A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5 5 2 3 1 2 3 4 3 3 4 1 2 10 2 6 1 2 3 4 5 7 2 1 1 2 100 76 8 76 75 36 67 41 74 10 77 OutputCopy2 0 4 0 2 NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.
[ "binary search", "brute force", "implementation" ]
#include <bits/stdc++.h> #include <iostream> #include <vector> using namespace std; typedef long long ll; #define vi vector<int> int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); int t; cin>>t; while (t--) { int n,p,c; cin>>n>>p>>c; int a[c]; for(int i=0;i<c;i++)cin>>a[i]; for(int i=0;i<=c;i++){ if (p - i >= 1 && find(a, a+c, p - i) == &a[c-1]+1) { cout<<i<<endl; break; } else if (p + i <= n && find(a, a + c, p + i) == &a[c - 1]+1) { cout << i << endl; break; } } } }
cpp
1284
B
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5 1 1 1 1 1 2 1 4 1 3 OutputCopy9 InputCopy3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 OutputCopy7 InputCopy10 3 62 24 39 1 17 1 99 1 60 1 64 1 30 2 79 29 2 20 73 2 85 37 1 100 OutputCopy72 NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.
[ "binary search", "combinatorics", "data structures", "dp", "implementation", "sortings" ]
#include <bits/stdc++.h> using namespace std; using ll = long long; #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ll tc = 1; // cin >> tc; while (tc--) { ll n; cin >> n; vector<vector<ll>> v(n); vector<pair<ll, vector<ll>>> ddd; for (ll z = 0; z < n; z++) { ll l, prev = 1e18, f = 1; cin >> l; for (ll t, x = 0; x < l; x++) { cin >> t; v[z].push_back(t); if (t > prev) { f = 0; } prev = t; } if (f) { ddd.push_back({v[z][0], v[z]}); } } ll sub = 0; sort(rall(ddd)); for (ll x = 0; x < ddd.size(); x++) { ll low = 0, high = ddd.size() - 1, idx = ddd.size(); ll last = ddd[x].second[ddd[x].second.size() - 1]; while (low <= high) { ll mid = (low + high) / 2; if (ddd[mid].first <= last) { high = mid - 1; idx = mid; } else { low = mid + 1; } } sub += (ddd.size() - idx); } ll res = n * n - sub; cout << res << '\n'; } return 0; }
cpp
1312
F
F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by nn castles, the ii-th castle is defended by aiai soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.Each attack must target a castle with at least one alive defender in it. There are three types of attacks: a mixed attack decreases the number of defenders in the targeted castle by xx (or sets it to 00 if there are already less than xx defenders); an infantry attack decreases the number of defenders in the targeted castle by yy (or sets it to 00 if there are already less than yy defenders); a cavalry attack decreases the number of defenders in the targeted castle by zz (or sets it to 00 if there are already less than zz defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.Then, the test cases follow. Each test case is represented by two lines. The first line contains four integers nn, xx, yy and zz (1≤n≤3⋅1051≤n≤3⋅105, 1≤x,y,z≤51≤x,y,z≤5). The second line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤10181≤ai≤1018).It is guaranteed that the sum of values of nn over all test cases in the input does not exceed 3⋅1053⋅105.OutputFor each test case, print the answer to it: the number of possible options for the first attack of the White King (or 00, if the Black King can launch the last attack no matter how the White King acts).ExamplesInputCopy3 2 1 3 4 7 6 1 1 2 3 1 1 1 2 2 3 OutputCopy2 3 0 InputCopy10 6 5 4 5 2 3 2 3 1 3 1 5 2 3 10 4 4 2 3 8 10 8 5 2 2 1 4 8 5 3 5 3 5 9 2 10 4 5 5 5 2 10 4 2 2 3 1 4 1 10 3 1 5 3 9 8 7 2 5 4 5 8 8 3 5 1 4 5 5 10 OutputCopy0 2 1 2 5 12 5 0 0 2
[ "games", "two pointers" ]
#include<bits/stdc++.h> using namespace std; long long n , x , y , z , dp [10004][4] , arr [300005]; vector < int > bt [4]; int grundy ( long long x , int y ) { if ( x < 2e3 ) return dp [x][y]; else { int xx = ( x - 1000 ) % bt [y] . size (); return bt [y][xx]; } } int main() { int t; cin >> t; while ( t -- ) { scanf ( "%lld%lld%lld%lld" , &n , &x , &y , &z ); int xr = 0; for ( int i = 1 ; i <= 15e2 ; i ++ ) { for ( int j = 0 ; j < 3 ; j ++ ) { int a = max ( i - x , 0ll ); int b = max ( i - y , 0ll ); int c = max ( i - z , 0ll ); vector < int > v; if ( j == 0 ) { v . push_back ( dp [a][0] ); v . push_back ( dp [b][1] ); v . push_back ( dp [c][2] ); } if ( j == 1 ) { v . push_back ( dp [a][0] ); v . push_back ( dp [c][2] ); } if ( j == 2 ) { v . push_back ( dp [a][0] ); v . push_back ( dp [b][1] ); } sort ( v . begin () , v . end () ); v . resize ( unique ( v . begin () , v . end () ) - v . begin () ); dp [i][j] = -1; for ( int z = 0 ; z < v . size () ; z ++ ) { if ( v [z] != z ) { dp [i][j] = z; break; } } if ( dp [i][j] == -1 ) dp [i][j] = v . size (); } } bt [0] . clear (); bt [1] . clear (); bt [2] . clear (); for ( int i = 50 ; i <= 100 ; i ++ ) { for ( int j = 0 ; j < 3 ; j ++ ) { vector < int > a , b; int x = 1000 , y = i; while ( y -- ) a . push_back ( dp [ x ++ ][j] ); y = i; while ( y -- ) b . push_back ( dp [ x ++ ][j] ); if ( a == b ) bt [j] = a; } } if ( bt [0] . size () == 0 ) cout << 0 / 0 << endl; if ( bt [1] . size () == 0 ) cout << 0 / 0 << endl; if ( bt [2] . size () == 0 ) cout << 0 / 0 << endl; for ( int i = 0 ; i < n ; i ++ ) { scanf ( "%lld" , &arr [i] ); xr ^= grundy ( arr [i] , 0 ); } int ans = 0; for ( int i = 0 ; i < n ; i ++ ) { if ( grundy ( max ( arr [i] - x , 0ll ) , 0 ) == ( xr ^ grundy ( arr [i] , 0 ) ) ) ans ++; if ( grundy ( max ( arr [i] - y , 0ll ) , 1 ) == ( xr ^ grundy ( arr [i] , 0 ) ) ) ans ++; if ( grundy ( max ( arr [i] - z , 0ll ) , 2 ) == ( xr ^ grundy ( arr [i] , 0 ) ) ) ans ++; } printf ( "%d\n" , ans ); } }
cpp
1304
E
E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5 1 2 2 3 3 4 4 5 5 1 3 1 2 2 1 4 1 3 2 1 4 1 3 3 4 2 3 3 9 5 2 3 3 9 OutputCopyYES YES NO YES NO NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33
[ "data structures", "dfs and similar", "shortest paths", "trees" ]
#include<bits/stdc++.h> using namespace std; #define ll long long #define inf INT_MAX #define N 100005 ll q,n,m,k,ans=0,x,y,l,r,s,z; ll lg[N],fa[N][21]; ll dep[N]; ll cnt=0,head[N]; bool flag; struct edge{ ll x,y; }e[2*N]; template<typename T>inline void read(T &n){ T w=1; n=0; char ch=getchar(); while (!isdigit(ch) && ch!=EOF){ if (ch=='-') w=-1; ch=getchar(); } while (isdigit(ch) && ch!=EOF){ n=(n<<3)+(n<<1)+(ch&15); ch=getchar(); } n*=w; } template<typename T>inline void write(T x){ if (x==0){ putchar('0'); return ; } T tmp; if (x>0) tmp=x; else tmp=-x; if (x<0) putchar('-'); char F[105]; long long cnt=0; while (tmp){ F[++cnt]=tmp%10+48; tmp/=10; } while (cnt) putchar(F[cnt--]); } void addedge(ll x,ll y){ cnt++; e[cnt].x=head[x]; e[cnt].y=y; head[x]=cnt; return ; } void dfs(ll x,ll father){ fa[x][0]=father; ll i; ll go; for (i=head[x]; i; i=e[i].x){ go=e[i].y; if (go==father) continue; dep[go]=dep[x]+1; dfs(go,x); } return ; } void init(){ ll i,j; lg[1]=0; for (i=2; i<=n; i++) lg[i]=lg[i>>1]+1; for (i=1; (1<<i)<=n; i++) for (j=1; j<=n; j++) if (fa[j][i-1]>0 && fa[fa[j][i-1]][i-1]>0) fa[j][i]=fa[fa[j][i-1]][i-1]; return ; } ll Lca(ll x,ll y){ ll i; ll k; if (dep[x]<dep[y]) swap(x,y); k=lg[dep[x]-dep[y]]; for (i=k; i>=0; i--) if (dep[fa[x][i]]>=dep[y]) x=fa[x][i]; if (x==y) return x; k=lg[dep[x]]; for (i=k; i>=0; i--) if (fa[x][i]!=fa[y][i]){ x=fa[x][i]; y=fa[y][i]; } return fa[x][0]; } ll dist(ll x,ll y){ ll l=Lca(x,y); return dep[x]+dep[y]-2*dep[l]; } bool check(ll x,ll y){ if (x>y) return false; if (x%2!=y%2) return false; return true; } int main(){ // freopen(".in","r",stdin); // freopen(".out","w",stdout); ll i,j; read(n); for (i=2; i<=n; i++){ read(x); read(y); addedge(x,y); addedge(y,x); } dep[1]=1; dfs(1,-1); init(); read(q); while (q--){ read(x); read(y); read(l); read(r); read(k); flag=false; flag |= check ( dist(l,r) , k ); flag |= check ( dist(l,x) + dist(r,y) + 1 , k ); flag |= check ( dist(l,y) + dist(r,x) + 1 , k ); if (flag) printf("YES\n"); else printf("NO\n"); } return 0; }
cpp
1299
A
A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4 4 0 11 6 OutputCopy11 6 4 0InputCopy1 13 OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.
[ "brute force", "greedy", "math" ]
#include <bits/stdc++.h> #define ll long long #define vi vector<int> #define vl vector<ll> #define vp vector<pair<int,int>> #define ff first #define ss second #define forw(i,a,b) for(int i=a;i<b;i++) #define backw(i,a,b) for(int i=a;i>=b;i--) using namespace std; const int M=998244353; void solve(){ int n; cin>>n; vi a(n),pre(n+1),suf(n+1); forw(i,0,n) cin>>a[i]; pre[0]=suf[n]=INT_MAX; forw(i,0,n){ pre[i+1]=pre[i]& ~a[i]; } backw(i,n-1,0){ suf[i]=suf[i+1]& ~a[i]; } int ans=-1; int pos; forw(i,0,n){ if((a[i]&pre[i]&suf[i+1])>ans){ ans=a[i]&pre[i]&suf[i+1]; pos=i; } } swap(a[0],a[pos]); for(auto i:a) cout<<i<<" "; cout<<endl; } int main(){ int t=1; // cin>>t; while(t--){ // cout<<"test "<<t<<endl; solve(); } }
cpp
1320
E
E. Treeland and Virusestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are nn cities in Treeland connected with n−1n−1 bidirectional roads in such that a way that any city is reachable from any other; in other words, the graph of cities and roads is a tree. Treeland is preparing for a seasonal virus epidemic, and currently, they are trying to evaluate different infection scenarios.In each scenario, several cities are initially infected with different virus species. Suppose that there are kiki virus species in the ii-th scenario. Let us denote vjvj the initial city for the virus jj, and sjsj the propagation speed of the virus jj. The spread of the viruses happens in turns: first virus 11 spreads, followed by virus 22, and so on. After virus kiki spreads, the process starts again from virus 11.A spread turn of virus jj proceeds as follows. For each city xx not infected with any virus at the start of the turn, at the end of the turn it becomes infected with virus jj if and only if there is such a city yy that: city yy was infected with virus jj at the start of the turn; the path between cities xx and yy contains at most sjsj edges; all cities on the path between cities xx and yy (excluding yy) were uninfected with any virus at the start of the turn.Once a city is infected with a virus, it stays infected indefinitely and can not be infected with any other virus. The spread stops once all cities are infected.You need to process qq independent scenarios. Each scenario is described by kiki virus species and mimi important cities. For each important city determine which the virus it will be infected by in the end.InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Treeland.The following n−1n−1 lines describe the roads. The ii-th of these lines contains two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — indices of cities connecting by the ii-th road. It is guaranteed that the given graph of cities and roads is a tree.The next line contains a single integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of infection scenarios. qq scenario descriptions follow.The description of the ii-th scenario starts with a line containing two integers kiki and mimi (1≤ki,mi≤n1≤ki,mi≤n) — the number of virus species and the number of important cities in this scenario respectively. It is guaranteed that ∑qi=1ki∑i=1qki and ∑qi=1mi∑i=1qmi do not exceed 2⋅1052⋅105.The following kiki lines describe the virus species. The jj-th of these lines contains two integers vjvj and sjsj (1≤vj≤n1≤vj≤n, 1≤sj≤1061≤sj≤106) – the initial city and the propagation speed of the virus species jj. It is guaranteed that the initial cities of all virus species within a scenario are distinct.The following line contains mimi distinct integers u1,…,umiu1,…,umi (1≤uj≤n1≤uj≤n) — indices of important cities.OutputPrint qq lines. The ii-th line should contain mimi integers — indices of virus species that cities u1,…,umiu1,…,umi are infected with at the end of the ii-th scenario.ExampleInputCopy7 1 2 1 3 2 4 2 5 3 6 3 7 3 2 2 4 1 7 1 1 3 2 2 4 3 7 1 1 3 3 3 1 1 4 100 7 100 1 2 3 OutputCopy1 2 1 1 1 1 1
[ "data structures", "dfs and similar", "dp", "shortest paths", "trees" ]
#include<bits/stdc++.h> using namespace std; namespace QSY{ // by OneZzz6174 const int SIZ = 1000000; namespace IO{ // by OneZzz6174 #ifdef ONLINE_JUDGE static char buf[SIZ],*A=buf,*B=buf; #define getchar() A==B&&(B=(A=buf)+fread(buf,1,SIZ,stdin),A==B)?EOF:*A++ #endif static char obuf[SIZ],*C=obuf; #define putchar(x) (C-obuf<SIZ)?(*C++=x):(fwrite(obuf,C-obuf,1,stdout),C=obuf,*C++=x) inline void flush(){fwrite(obuf,C-obuf,1,stdout),C=obuf;} struct FLS{~FLS(){fwrite(obuf,C-obuf,1,stdout);}}fls; inline int read(){ register int x=0,f=1,c=getchar(); for(;c<48||c>57;c=getchar())if(c=='-')f=-1; for(;c>47&&c<58;c=getchar())x=x*10+(c^48); return x*f; } inline void read(int &x){x=read();} inline void read(char &c){do{c=getchar();}while(c==' '||c =='\n');} inline int readc(){return getchar();} template<typename Int> inline void print(Int x){ if(x<0)putchar(45),x=-x; if(x>9)print(x/10);putchar(x%10+48); } inline void print(char c){putchar(c);} inline void print(const char *s){for(char *p = (char*)s;*p;++p)putchar(*p);} template<typename _Tp,typename... _Args> inline void read(_Tp& x,_Args&... args){read(x);read(args...);} template<typename _Tp,typename... _Args> inline void print(_Tp x,_Args... args){print(x);print(args...);} } using IO::read;using IO::readc;using IO::print; #define rep(i,a,b) for(int i = (a);i <= (b);++i) #define Rep(i,a,b) for(int i = (a);i >= (b);--i) template<typename T> T chkmax(T &a,T b){ return a = a > b ? a : b; } template<typename T> T chkmin(T &a,T b){ return a = a < b ? a : b; } template<typename T,typename U> T max(T a,U b){ return a > b ? a : b; } template<typename T,typename U> T min(T a,U b){ return a < b ? a : b; } #define pb push_back #define eb emplace_back #define adde(G,u,v) G[u].pb(v),G[v].pb(u) #define Adde(G,u,v,w) G[u].eb(v,w),G[v].eb(u,w) using ll = long long; const ll inf = 1e18; } using namespace QSY; const int N = 2e5 + 5; int n,m,k,l,V[N],P[N],ft[N],s; int p[N],t[N],q[N],id[N],stk[N],tp = 0; int dep[N],siz[N],son[N],fa[N]; int dfn[N],top[N],idfn[N],tot = 0; int dp[N],v[N]; vector<int> G[N],D; void dfs1(int u = 1,int ft = 0){ dep[u] = dep[fa[u] = ft] + 1; siz[u] = 1; for(int v : G[u]) if(v != ft){ dfs1(v,u); siz[u] += siz[v]; if(siz[v] > siz[son[u]]) son[u] = v; } } void dfs2(int u = 1,int t = 1){ top[u] = t; idfn[dfn[u] = ++tot] = u; if(son[u]) dfs2(son[u],t); for(int v : G[u]) if(v != fa[u] && v != son[u]) dfs2(v,v); } int lca(int x,int y){ while(top[x] != top[y]){ if(dep[top[x]] < dep[top[y]]) swap(x,y); x = fa[top[x]]; } return dep[x] < dep[y] ? x : y; } int dis(int x,int y){ int d = dep[x] + dep[y] - 2 * dep[lca(x,y)]; return (d + t[x] - 1) / t[x]; } void upd(int u,int &x,int y){ if(!y || !u) return; if(!x) return void(x = y); int dx = dis(x,u),dy = dis(y,u); if(dx > dy || (dx == dy && id[x] > id[y])) x = y; } void init(){ sort(P + 1,P + s + 1,[](int a,int b){return dfn[a] < dfn[b];}); stk[tp = 1] = P[1]; rep(i,2,s){ int z = lca(stk[tp],P[i]); while(dep[z] < dep[stk[tp - 1]]){ ft[stk[tp]] = stk[tp - 1]; D.push_back(stk[tp - 1]); D.push_back(stk[tp]); --tp; } if(z != stk[tp]){ ft[stk[tp]] = z; D.push_back(stk[tp]); D.push_back(z); stk[tp - 1] == z ? --tp : stk[tp] = z; } stk[++tp] = P[i]; } while(--tp){ ft[stk[tp + 1]] = stk[tp]; D.push_back(stk[tp + 1]); D.push_back(stk[tp]); } } int main(){ read(n); rep(i,1,n - 1){ int u,v; read(u,v),adde(G,u,v); } dfs1(); dfs2(); read(m); while(m--){ read(k,l); s = 0; D.clear(); rep(i,1,k) id[p[i] = read()] = i,read(t[p[i]]),dp[p[i]] = p[i]; rep(i,1,l) q[i] = read(); rep(i,1,k) if(!V[p[i]]) V[P[++s] = p[i]] = 1,D.pb(p[i]); rep(i,1,l) if(!V[q[i]]) V[P[++s] = q[i]] = 1,D.pb(q[i]); init(); sort(D.begin(),D.end(),[](int a,int b){ return dfn[a] < dfn[b]; }); D.resize(unique(D.begin(),D.end()) - D.begin()); reverse(D.begin(),D.end()); for(int x : D) upd(ft[x],dp[ft[x]],dp[x]); reverse(D.begin(),D.end()); for(int x : D) upd(x,dp[x],dp[ft[x]]); rep(i,1,l) print(id[dp[q[i]]],' '); print('\n'); rep(i,1,s) V[P[i]] = 0; rep(i,1,k) id[p[i]] = 0,t[p[i]] = 0; for(int x : D) dp[x] = ft[x] = 0; } return 0; } //
cpp
1303
B
B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3 5 1 1 8 10 10 1000000 1 1000000 OutputCopy5 8 499999500000 NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good.
[ "math" ]
#include<bits/stdc++.h> using namespace std; #define int long long #define pb push_back #define F first #define S second #define endl "\n" const int N=1e5+2 , inf=2e9; void solve () { } int32_t main() { ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); int test; cin >> test; while (test--) { int num , good , bad; cin >> num >> good >> bad; int l,ans; l=(num+1)/2 / good; if ((num+1)/2 % good == 0) l--; ans=(num+1)/2 + l*bad; if (ans>=num) cout << ans << endl; else cout << num << endl; } return 0; }
cpp
1286
F
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.
[ "brute force", "constructive algorithms", "dp", "fft", "implementation", "math" ]
#include<bits/stdc++.h> #define Cn const #define CI Cn int& #define N 20 #define LL long long using namespace std; int n,f[1<<N],p[1<<N],c[1<<N];LL a[N+5],s[1<<N]; int main() { int i,j;for(scanf("%d",&n),i=1;i<=n;++i) scanf("%lld",a+i),a[i]?s[1<<i-1]=a[i]:(--i,--n); int l=1<<n;for(i=0;i^l;++i) c[i]=c[i>>1]+(i&1);for(j=0;j^n;++j) for(i=0;i^l;++i) i>>j&1&&(s[i]+=s[i^(1<<j)]); for(i=0;i^l;++i) if((s[i]&1)^(c[i]&1)) for(j=i&(i-1);j;j=(j-1)&i) if(1-c[i]<=s[j]-s[i^j]&&s[j]-s[i^j]<=c[i]-1) {p[i]=1;break;} for(i=1;i^l;++i) for(f[i]=1e9,j=i;j;j=(j-1)&i) c[j]==1?f[i]=min(f[i],f[i^j]+1):p[j]&&(f[i]=min(f[i],f[i^j]+c[j]-1)); return printf("%d\n",f[l-1]),0; }
cpp
1305
B
B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk  — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm  — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am  — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()(( OutputCopy1 2 1 3 InputCopy)( OutputCopy0 InputCopy(()()) OutputCopy1 4 1 2 5 6 NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations.
[ "constructive algorithms", "greedy", "strings", "two pointers" ]
#include <bits/stdc++.h> using namespace std; using ll = long long; using ii = tuple<int, int>; using vi = vector<ll>; using vii = vector<ii>; using vvi = vector<vi>; using si = set<ll>; int main() { cin.tie(0), ios::sync_with_stdio(0); string s; cin >> s; int n = s.size(); vi c(n); vvi r; while (1) { int i = 0, j = n-1; vi a; while (i < j) { if (c[i] && c[j]) i++, j--; else if (c[i]) i++; else if (c[j]) j--; else if (s[i] == '(' && s[j] == ')') c[i] = 1, c[j] = 1, a.push_back(i+1), a.push_back(j+1), i++, j--; else if (s[i] == '(') j--; else if (s[j] == ')') i++; else i++, j--; } if (!a.size()) break; sort(a.begin(), a.end()); r.push_back(a); } cout << r.size() << '\n'; for (int i = 0; i < r.size(); i++) { cout << r[i].size() << '\n'; for (int j = 0; j < r[i].size(); j++) cout << r[i][j] << " \n"[j == r[i].size()-1]; } }
cpp
1315
C
C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 OutputCopy1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
[ "greedy" ]
#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 chrono; using namespace __gnu_pbds; #define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) #define int long long #define MOD 1000000007 #define MOD1 998244353 #define INF 1e18 #define nline "\n" #define pb push_back #define ppb pop_back // #define mp make_pair #define ff first #define ss second #define pl pair<ll,ll> #define PI 3.141592653589793238462 #define set_bits(x) __builtin_popcountll(x) #define sz(x) ((int)(x).size()) #define all(x) (x).begin(), (x).end() #define vi vector<int> #define vl vector<long long> #define vvi vector<vector<int>> #define vvl vector<vector<ll>> #define vll vector<ll> #define prDouble(x) cout << fixed << setprecision(10) << x<<" "; #define vpi vector<pair<int,int>> #define vpl vector<pl> #define pi pair<int,int> #ifndef ONLINE_JUDGE #define debug(x) cerr << #x<<" "; _print(x); cerr << endl; #else #define debug(x); #endif typedef long long ll; typedef unsigned long long ull; typedef long double lld; typedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update > pbds; // find_by_order, order_of_key void _print(ll t) {cerr << t;} void _print(string t) {cerr << t;} void _print(char t) {cerr << t;} void _print(lld t) {cerr << t;} void _print(double t) {cerr << t;} void _print(ull t) {cerr << t;} template <class T, class V> void _print(pair <T, V> p); template <class T> void _print(vector <T> v); template <class T> void _print(set <T> v); template <class T, class V> void _print(map <T, V> v); template <class T> void _print(multiset <T> v); template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";} template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";} void _print(pbds v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";} mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); vector<ll>fact(1e6+100,1LL); long long mod=1e9+7; /*---------------------------------------------------------------------------------------------------------------------------*/ ll gcd(ll a, ll b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);} ll expo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;} void extendgcd(ll a, ll b, ll*v) {if (b == 0) {v[0] = 1; v[1] = 0; v[2] = a; return ;} extendgcd(b, a % b, v); ll x = v[1]; v[1] = v[0] - v[1] * (a / b); v[0] = x; return;} //pass an arry of size1 3 ll mminv(ll a, ll b) {ll arr[3]; extendgcd(a, b, arr); return arr[0];} //for non prime b ll mminvprime(ll a, ll b) {return expo(a, b - 2, b);} bool revsort(ll a, ll b) {return a > b;} void google(int t) {cout << "Case #" << t << ": ";} vector<ll> sieve(int n) {int*arr = new int[n + 1](); vector<ll> vect; for (int i = 2; i*i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (int j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;} vector<ll> prefixSum(vector<ll> A){vector<ll> res(A.size()+1);res[0]=0;res[1]=A[0];for(int i=1;i<A.size();i++){res[i+1]=A[i]+res[i];} return res;} vector<ll> suffixSum(vector<ll> A){vector<ll> res(A.size()+1);int n=A.size();res[n]=A[n-1];for(int i=n-2;i>=0;i--){res[i]=A[i]+res[i+1];}return res;} ll mod_add(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;} ll mod_mul(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;} ll mod_sub(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;} ll mod_div(ll a, ll b, ll m) {a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m;} //only for prime m ll phin(ll n) {ll number = n; if (n % 2 == 0) {number /= 2; while (n % 2 == 0) n /= 2;} for (ll i = 3; i <= sqrt(n); i += 2) {if (n % i == 0) {while (n % i == 0)n /= i; number = (number / i * (i - 1));}} if (n > 1)number = (number / n * (n - 1)) ; return number;} //O(sqrt(N)) ll ncr(ll n, ll r, ll mod) {return mod_div(fact[n],(mod_mul(fact[n-r],fact[r],mod)),mod);} ll getRandomNumber(ll l, ll r) {return uniform_int_distribution<ll>(l, r)(rng);} static bool comp(pi a,pi b){ return a.ff+a.ss<b.ff+b.ss;} template<class A> istream& operator>>(istream& in, vector<A> &a){for(A &i:a)in>>i;return in;} void indexsort(vector<int>&v,vpi &ans){for(int i=0;i<v.size();i++){ans.push_back({v[i],i});} sort(all(ans));} void factorial(int n){ for(long long i=1;i<n;i++)fact[i]=mod_mul(fact[i-1],i,mod);} ll __lcm(int i,int j){ll gcd=__gcd(i,j);return (i/gcd)*j;} bool isPrime(int n){for(int i=2;i<=sqrt(n);i++){ if(n%i==0){return false;}}return true;} map<int,int> factors(int n){map<int,int>mp;int m=n;for(int i=2;i<=sqrt(n);i++){while(n%i==0){mp[i]++;n/=i;}}if(n>=2)mp[n]++; return mp;} struct custom_hash {static uint64_t splitmix64(uint64_t x) {x += 0x9e3779b97f4a7c15;x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;x = (x ^ (x >> 27)) * 0x94d049bb133111eb;return x ^ (x >> 31);}size_t operator()(uint64_t x) const {static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();return splitmix64(x + FIXED_RANDOM);}};unordered_map<long long, int, custom_hash> safe_map; /*--------------------------------------------------------------------------------------------------------------------------*/ void solve(){ int n; cin>>n; vi b(n); cin>>b; vi a(2*n); set<int>st; for(int i=1;i<=2*n;i++)st.insert(i); int j=0; for(int i=0;i<n;i++){ a[j]=b[i]; st.erase(b[i]); j+=2; } for(int i=0;i<2*n;i+=2){ int val=a[i]; if(st.upper_bound(val)==st.end()){cout<<-1;return;} a[i+1]=*st.upper_bound(val); st.erase(a[i+1]); } for(auto &i:a){cout<<i<<" ";} } signed main() { #ifndef ONLINE_JUDGE freopen("Error.txt", "w", stderr); freopen("Input.txt", "r", stdin); freopen("Output.txt", "w", stdout); #endif fastio(); auto start1 = high_resolution_clock::now(); // int tc=1; int tc=1; cin>>tc; while(tc--){ solve(); cout<<endl; } auto stop1 = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop1 - start1); #ifndef ONLINE_JUDGE cerr << "Time: " << duration . count() / 1000 << endl; #endif } //Do not use lower_bound(st.begin(),st.end(),x)->uses O(n) TC,instead use // st.lower_bound(x); //s+='a'; not s=s+'a'; //log(2) gives double value so if necessary convert to (int)log2. // After all MOD operation check all variable values are >=0 and <MOD
cpp
1292
D
D. Chaotic V.time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputÆsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years; it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1,2,3,…1,2,3,…). The node with a number xx (x>1x>1), is directly connected with a node with number xf(x)xf(x), with f(x)f(x) being the lowest prime divisor of xx.Vanessa's mind is divided into nn fragments. Due to more than 500 years of coma, the fragments have been scattered: the ii-th fragment is now located at the node with a number ki!ki! (a factorial of kiki).To maximize the chance of successful awakening, Ivy decides to place the samples in a node PP, so that the total length of paths from each fragment to PP is smallest possible. If there are multiple fragments located at the same node, the path from that node to PP needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node PP.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — number of fragments of Vanessa's mind.The second line contains nn integers: k1,k2,…,knk1,k2,…,kn (0≤ki≤50000≤ki≤5000), denoting the nodes where fragments of Vanessa's mind are located: the ii-th fragment is at the node with a number ki!ki!.OutputPrint a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node PP).As a reminder, if there are multiple fragments at the same node, the distance from that node to PP needs to be counted multiple times as well.ExamplesInputCopy3 2 1 4 OutputCopy5 InputCopy4 3 1 4 4 OutputCopy6 InputCopy4 3 1 4 1 OutputCopy6 InputCopy5 3 1 4 1 5 OutputCopy11 NoteConsidering the first 2424 nodes of the system; the node network will look as follows (the nodes 1!1!, 2!2!, 3!3!, 4!4! are drawn bold):For the first example, Ivy will place the emotion samples at the node 11. From here: The distance from Vanessa's first fragment to the node 11 is 11. The distance from Vanessa's second fragment to the node 11 is 00. The distance from Vanessa's third fragment to the node 11 is 44. The total length is 55.For the second example, the assembly node will be 66. From here: The distance from Vanessa's first fragment to the node 66 is 00. The distance from Vanessa's second fragment to the node 66 is 22. The distance from Vanessa's third fragment to the node 66 is 22. The distance from Vanessa's fourth fragment to the node 66 is again 22. The total path length is 66.
[ "dp", "graphs", "greedy", "math", "number theory", "trees" ]
// #pragma GCC optimize("O3") // #pragma GCC optimize("Ofast") #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include "complex" using namespace std; using namespace __gnu_pbds; template <class T> using o_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; // order_of_key (val): returns the no. of values less than val // find_by_order (k): returns the kth largest element.(0-based) #define int long long typedef pair<int, int> II; typedef vector<II> VII; typedef vector<int> VI; typedef vector<VI> VVI; typedef long long LL; #define PB push_back #define MP make_pair #define F first #define S second #define SZ(a) (int)(a.size()) #define ALL(a) a.begin(), a.end() #define SET(a, b) memset(a, b, sizeof(a)) #define FOR(i, a, b) for (int i = (a); i < (b); ++i) #define REP(i, n) FOR(i, 0, n) #define si(n) scanf("%d", &n) #define dout(n) printf("%d\n", n) #define sll(n) scanf("%lld", &n) #define lldout(n) printf("%lld\n", n) #define fast_io \ ios_base::sync_with_stdio(false); \ cin.tie(NULL) #define endl "\n" const long long mod = 1e9 + 7; void prec() { } const int N = 5001; int cnt[N]; int prime[N]; int curr = 0; void solve() { memset(cnt, 0, sizeof(cnt)); int n; cin >> n; for (int i = 0; i < n; i++) { int x; cin >> x; if (x == 0) { x = 1; } cnt[x]++; } vector<int> primes; map<int, int> id; vector<pair<int, int>> s[N]; for (int i = 0; i < N; i++) prime[i] = i; for (int i = 2; i < 5001; i++) { if (prime[i] == i) { id[i] = curr++; primes.PB(i); for (int j = 2 * i; j < 5001; j += i) { prime[j] = i; } } } map<int, int> mm; int ans = 0; for (int i = 1; i < N; i++) { int v = i; while (v != 1) { int x = prime[v]; mm[x]++; v /= prime[x]; } vector<pair<int, int>> x; int y = 0; for (auto &v : mm) { y += v.second; x.PB({v.first, v.second}); } s[i] = (x); ans += cnt[i] * y; } int sz = primes.size(); vector<int> occur(sz); // how many are there for each of these primes for (int i = 2; i < N; i++) { if (cnt[i] > 0) { occur[id[s[i].back().first]] += cnt[i]; } } while (1) { int maxi_s = 0; int maxi_p = 0; for (int i = 0; i < sz; i++) { if (occur[i] >= maxi_s) { maxi_s = occur[i]; maxi_p = primes[i]; } } // answer decreses by n - maxi_s and increases by maxi_s // so decreses by n- if (n - 2 * maxi_s >= 0) { break; } ans = ans + (n - 2 * maxi_s); // now update occur occur = vector<int>(sz, 0); for (int i = 2; i < N; i++) { if (!cnt[i]) { continue; } int p = maxi_p; if (s[i].back().first != maxi_p) { cnt[i] = 0; continue; } s[i].back().second--; if (s[i].back().second == 0) { s[i].pop_back(); } if (!s[i].size()) { cnt[i] = 0; continue; } occur[id[s[i].back().first]] += cnt[i]; } } cout << ans << endl; } signed main() { fast_io; prec(); // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); int totalTests = 1; // cin >> totalTests; for (int testNo = 1; testNo <= totalTests; testNo++) { // cout << "Case #" << testNo << ": "; solve(); } return 0; }
cpp
1307
G
G. Cow and Exercisetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFarmer John is obsessed with making Bessie exercise more!Bessie is out grazing on the farm; which consists of nn fields connected by mm directed roads. Each road takes some time wiwi to cross. She is currently at field 11 and will return to her home at field nn at the end of the day.Farmer John has plans to increase the time it takes to cross certain roads. He can increase the time it takes to cross each road by a nonnegative amount, but the total increase cannot exceed xixi for the ii-th plan. Determine the maximum he can make the shortest path from 11 to nn for each of the qq independent plans.InputThe first line contains integers nn and mm (2≤n≤502≤n≤50, 1≤m≤n⋅(n−1)1≤m≤n⋅(n−1)) — the number of fields and number of roads, respectively.Each of the following mm lines contains 33 integers, uiui, vivi, and wiwi (1≤ui,vi≤n1≤ui,vi≤n, 1≤wi≤1061≤wi≤106), meaning there is an road from field uiui to field vivi that takes wiwi time to cross.It is guaranteed that there exists a way to get to field nn from field 11. It is guaranteed that the graph does not contain self-loops or parallel edges. It is possible to have a road from uu to vv and a road from vv to uu.The next line contains a single integer qq (1≤q≤1051≤q≤105), the number of plans.Each of the following qq lines contains a single integer xixi, the query (0≤xi≤1050≤xi≤105).OutputFor each query, output the maximum Farmer John can make the shortest path if the total increase does not exceed xixi.Your answer is considered correct if its absolute or relative error does not exceed 10−610−6.Formally, let your answer be aa, and the jury's answer be bb. Your answer is accepted if and only if |a−b|max(1,|b|)≤10−6|a−b|max(1,|b|)≤10−6.ExampleInputCopy3 3 1 2 2 2 3 2 1 3 3 5 0 1 2 3 4 OutputCopy3.0000000000 4.0000000000 4.5000000000 5.0000000000 5.5000000000
[ "flows", "graphs", "shortest paths" ]
#include<bits/stdc++.h> using namespace std; struct edge{ int to,cap; int cst; int rev; }; vector<edge>g[53]; void add_edge(int x,int y,int cap,int cst){ g[x].push_back((edge){y,cap,cst,g[y].size()}); g[y].push_back((edge){x,0,-cst,g[x].size()-1}); } int prevv[53],preve[53]; int dist[53]; int min_cost_flow(int s,int t){ int ret=0; while(1){ memset(dist,31,sizeof(dist)); priority_queue<pair<int,int> >Q; dist[s]=0; Q.push(make_pair(0,s)); while(Q.size()){ int len=-Q.top().first; int nw=Q.top().second;Q.pop(); if(dist[nw]<len)continue; for(int i=0;i<g[nw].size();i++){ edge &e=g[nw][i]; if(e.cap>0&&dist[e.to]>dist[nw]+e.cst) dist[e.to]=dist[nw]+e.cst, prevv[e.to]=nw,preve[e.to]=i, Q.push(make_pair(-dist[e.to],e.to)); } } if(dist[t]>=192608172)break; int f=1; for(int v=t;v!=s;v=prevv[v]) f=min(f,g[prevv[v]][preve[v]].cap); ret+=1ll*f*dist[t]; for(int v=t;v!=s;v=prevv[v]){ edge &e=g[prevv[v]][preve[v]]; e.cap-=f,g[v][e.rev].cap+=f; } break; }return ret; }int n,m; int main(){ ios::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); cin>>n>>m; while(m--){ int x,y,w; cin>>x>>y>>w; x--;y--; add_edge(x,y,1,w); } vector<int>v; while(1){ int tmp=min_cost_flow(0,n-1); if(tmp) v.push_back(tmp); else break; } int q; cin>>q; while(q--){ double ans=1e9,sum; int t; cin>>t;sum=t; for(int i=0;i<v.size();i++) sum+=v[i], ans=min(ans,sum/(i+1)); cout<<fixed<<setprecision(10)<<ans<<'\n'; } }
cpp
1296
F
F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4 1 2 3 2 3 4 2 1 2 5 1 3 3 OutputCopy5 3 5 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 OutputCopy5 3 1 2 1 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 OutputCopy-1
[ "constructive algorithms", "dfs and similar", "greedy", "sortings", "trees" ]
#include<bits/stdc++.h> using namespace std; #define all(x) x.begin(),x.end() const int INF=1e9; struct edge{ int to,idx,val,id; edge(){} edge(int a,int b,int c,int d){ to=a,idx=b,val=c,id=d; } }; struct qry{ int a,b,c; qry(){} qry(int a1,int b1,int c1){a=a1,b=b1,c=c1;} }; int n; vector<vector<edge>> adj; int cnt=0; int from=0,goal=0; int mn=0; bool dfs(int k,int pa){ if(k==goal){ return 1; } for(edge &e:adj[k]){ if(e.to==pa){ continue; } if(dfs(e.to,k)){ if(e.val<=mn){ cnt++; e.val=mn; adj[e.to][e.idx].val=mn; } return 1; } } return 0; } int main(){ cin>>n; adj.resize(n); for(int i=0;i<n-1;i++){ int a,b;cin>>a>>b;a--;b--; adj[a].push_back(edge(b,adj[b].size(),-INF,i)); adj[b].push_back(edge(a,adj[a].size()-1,-INF,i)); } int q;cin>>q; vector<qry> ask(q); for(int i=0;i<q;i++){ int a,b,c;cin>>a>>b>>c; ask[i]=qry(a-1,b-1,c); } sort(all(ask),[&](qry a,qry b){return a.c>b.c;}); for(int i=0;i<q;i++){ int a,b,c; a=ask[i].a; b=ask[i].b; c=ask[i].c; cnt=0; mn=c; from=a; goal=b; dfs(a,a); if(cnt==0){ cout<<-1<<endl; return 0; } } vector<int> ans(n-1); for(int i=0;i<n;i++){ for(edge &e:adj[i]){ ans[e.id]=e.val; } } for(int j:ans){ if(j==-INF){ j=1000000; } cout<<j<<' '; } return 0; }
cpp
1292
D
D. Chaotic V.time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputÆsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years; it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1,2,3,…1,2,3,…). The node with a number xx (x>1x>1), is directly connected with a node with number xf(x)xf(x), with f(x)f(x) being the lowest prime divisor of xx.Vanessa's mind is divided into nn fragments. Due to more than 500 years of coma, the fragments have been scattered: the ii-th fragment is now located at the node with a number ki!ki! (a factorial of kiki).To maximize the chance of successful awakening, Ivy decides to place the samples in a node PP, so that the total length of paths from each fragment to PP is smallest possible. If there are multiple fragments located at the same node, the path from that node to PP needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node PP.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — number of fragments of Vanessa's mind.The second line contains nn integers: k1,k2,…,knk1,k2,…,kn (0≤ki≤50000≤ki≤5000), denoting the nodes where fragments of Vanessa's mind are located: the ii-th fragment is at the node with a number ki!ki!.OutputPrint a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node PP).As a reminder, if there are multiple fragments at the same node, the distance from that node to PP needs to be counted multiple times as well.ExamplesInputCopy3 2 1 4 OutputCopy5 InputCopy4 3 1 4 4 OutputCopy6 InputCopy4 3 1 4 1 OutputCopy6 InputCopy5 3 1 4 1 5 OutputCopy11 NoteConsidering the first 2424 nodes of the system; the node network will look as follows (the nodes 1!1!, 2!2!, 3!3!, 4!4! are drawn bold):For the first example, Ivy will place the emotion samples at the node 11. From here: The distance from Vanessa's first fragment to the node 11 is 11. The distance from Vanessa's second fragment to the node 11 is 00. The distance from Vanessa's third fragment to the node 11 is 44. The total length is 55.For the second example, the assembly node will be 66. From here: The distance from Vanessa's first fragment to the node 66 is 00. The distance from Vanessa's second fragment to the node 66 is 22. The distance from Vanessa's third fragment to the node 66 is 22. The distance from Vanessa's fourth fragment to the node 66 is again 22. The total path length is 66.
[ "dp", "graphs", "greedy", "math", "number theory", "trees" ]
//#pragma GCC optimize(3) #include<iostream> #include<climits> #include<cstdio> #include<cstring> #include<cmath> #include<ctime> #include<algorithm> #include<queue> #include<map> #include<set> #include<vector> #include<complex> #include<random> #include<chrono> #define int long long //#define double long double #define invert dsfsdf using namespace std; const long long INF=LLONG_MAX/4ll; const long long mod=998244353; const long long mod2=1000009; const long long mod3=924844033; const double Pai=acos(-1); map< pair<int,pair<int,int> >,int> mp; int n,cnt=0,sign=0,ans=INF; int pri[1000005],a[1000005],h[1000005],vt[1000005],t[1000005],ct[1000005],pos[1000005],sta[1000005],d[1000005]; int sum[30005][705],num[30005][705]; int N=5000; struct edge { int from,to,next,v; }e[100005]; void addedge(int x,int y,int z) { e[++cnt]={x,y,h[x],z},h[x]=cnt; swap(x,y); e[++cnt]={x,y,h[x],z},h[x]=cnt; } int qp(int x,int y) { int res=1; while(y) { if(y&1) y--,res*=x,res%=mod3; y>>=1,x*=x,x%=mod3; } return res; } void init() { for(int i=1;i<=N;i++) { int sq=sqrt(i),fg=1; for(int j=2;j<=sq;j++) if(i%j==0) fg=0; if(fg) pri[++pri[0]]=i; } sum[1][1]=1; for(int i=2;i<=N;i++) { for(int j=1;j<=pri[0];j++) sum[i][j]=sum[i-1][j]; int x=i; for(int j=2;j<=pri[0];j++) { while(x%pri[j]==0) x/=pri[j],sum[i][j]++; } } for(int i=1;i<=N;i++) { int sm=0,sm2=0,sm3=1; // cout<<i<<endl; for(int j=pri[0];j>=1;j--) /*cout<<pri[j]<<" "<<sum[i][j]<<"\n",*/num[i][j]=sum[i][j],ct[i]+=sum[i][j],sm+=pri[j]*sum[i][j]%mod,sm%=mod,sm2^=pri[j]^sum[i][j],sm2%=mod2,sm3*=qp(pri[j],sum[i][j]),sm3%=mod3; mp[{sm3,{sm,sm2}}]=i; // cout<<sm3<<"\n"; } } int LCA(int x,int y) { sign++; for(int i=pri[0];i>=1;i--) { if(num[x][i]!=num[y][i]) { num[sign][i]=min(num[x][i],num[y][i]); for(int j=i-1;j>=1;j--) num[sign][j]=0; break; } else num[sign][i]=num[x][i]; } num[sign][1]=1; int sm=0,sm2=0,sm3=1; for(int i=pri[0];i>=1;i--) ct[sign]+=num[sign][i],sm+=pri[i]*num[sign][i]%mod,sm%=mod,sm2^=pri[i]^num[sign][i],sm2%=mod2,sm3*=qp(pri[i],num[sign][i]),sm3%=mod3; if(mp[{sm3,{sm,sm2}}]) { ct[sign]=0,sign--; return mp[{sm3,{sm,sm2}}]; } // cout<<sm<<" "<<sm2<<" "<<sm3<<endl; // for(int i=pri[0];i>=1;i--) cout<<num[x][i]<<" ";puts(""); // for(int i=pri[0];i>=1;i--) cout<<num[y][i]<<" ";puts(""); // for(int i=pri[0];i>=1;i--) cout<<num[sign][i]<<" ";puts(""); return mp[{sm3,{sm,sm2}}]=sign; } bool cmp(int x,int y) { for(int i=1;i<=pri[0];i++) { if(num[x][i]>num[y][i]) return 0; if(num[x][i]<num[y][i]) return 1; } return 0; } int calc(int x,int y) { return ct[y]-ct[x]; } void Build() { sort(vt+1,vt+N+1); int tp=1; sta[tp]=1,h[1]=0,cnt=0; for(int i=1;i<=N;i++) { if(vt[i]==1) continue; int lca=LCA(vt[i],sta[tp]); if(lca!=sta[tp]) { while(cmp(lca,sta[tp-1])) addedge(sta[tp-1],sta[tp],calc(sta[tp-1],sta[tp])),tp--; if(!cmp(lca,sta[tp-1])) addedge(lca,sta[tp],calc(lca,sta[tp])),sta[tp]=lca; else addedge(lca,sta[tp--],calc(lca,sta[tp--])); } sta[++tp]=vt[i]; } for(int i=1;i<tp;i++) addedge(sta[i],sta[i+1],calc(sta[i],sta[i+1])); } void dfs(int s,int fa,int dep) { d[s]=dep; for(int i=h[s];i;i=e[i].next) { int y=e[i].to; if(y==fa||y==s) continue; // cout<<s<<" "<<y<<endl; dfs(y,s,dep+e[i].v); } } signed main() { scanf("%lld",&n);sign=N; for(int i=1;i<=n;i++) { scanf("%lld",&a[i]); if(a[i]==0) a[i]=1; t[a[i]]++; } for(int i=1;i<=N;i++) vt[i]=i; init(); Build(); // for(int i=1;i<=cnt;i++) { // cout<<e[i].from<<" "<<e[i].to<<" "<<e[i].v<<endl; // } for(int i=1;i<=sign;i++) { int res=0; dfs(i,0,0); for(int j=1;j<=N;j++) res+=t[j]*d[j]/*,cout<<d[j]<<" "*/; // for(int j=1;j<=sign;j++) vis[j]=0; // cout<<res<<endl; ans=min(ans,res); } // for(int i=1;i<=sign;i++) { // int res=1; // for(int j=pri[0];j>=1;j--) res*=qp(pri[j],sum[i][j]),res%=mod3; // cout<<res<<endl; // } printf("%lld",ans); return 0; }
cpp
1311
F
F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3 1 3 2 -100 2 3 OutputCopy3 InputCopy5 2 1 4 3 5 2 2 2 3 4 OutputCopy19 InputCopy2 2 1 -3 0 OutputCopy0
[ "data structures", "divide and conquer", "implementation", "sortings" ]
#include <bits/stdc++.h> using namespace std; template<typename T> struct fenwick{ int N; vector<T> sums; fenwick(int _N){ N = _N + 5; sums.resize(N, 0); } T query(int i){ T res = 0; for(; i; i -= i & (-i)) res += sums[i]; return res; } void update(int i, T v){ for(; i < N; i += i & (-i)) sums[i] += v; } }; int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<int> x(n), v(n); for(auto& X : x) cin >> X; for(auto& V : v) cin >> V; vector<int> sorted = x; sort(sorted.begin(), sorted.end()); map<int, int> ind; int curr = 1; for(int i = 0; i < n; i++){ if(!ind.count(sorted[i])) ind[sorted[i]] = curr++; } fenwick<long long> dists(n); fenwick<int> pts(n); vector<pair<int, int>> points; for(int i = 0; i < n; i++) points.emplace_back(x[i], v[i]); sort(points.begin(), points.end(), [&](pair<int, int>& a, pair<int, int>& b){ if(a.second == b.second) return a.first < b.first; return a.second < b.second; }); long long ans = 0; for(int i = 0; i < n; i++){ int idx = ind[points[i].first]; ans += 1LL * pts.query(idx) * points[i].first - dists.query(idx); pts.update(idx, 1); dists.update(idx, points[i].first); } cout << ans << '\n'; return 0; }
cpp
1286
A
A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5 0 5 0 2 3 OutputCopy2 InputCopy7 1 0 0 5 0 0 2 OutputCopy1 NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2.
[ "dp", "greedy", "sortings" ]
// ඞ #include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> using namespace std; using namespace __gnu_pbds; #ifdef LOCAL #include "debug.h" #define dbg(...) debug_out(splitter(#__VA_ARGS__), 0, __LINE__, __VA_ARGS__) #else #define dbg(...) #endif #define int long long #define ALL(v) (v).begin(), (v).end() #define mem(a, x) memset(a , x , sizeof(a)) #define F first #define S second #define pb push_back #define popCnt __builtin_popcountll typedef long long ll; typedef long double ld; typedef unsigned long long ull; typedef vector<int> vi; typedef vector<vector<int>> vvi; typedef pair <int, int> pii; typedef vector<pair <int, int>> vpii; typedef vector<vector<char>> vvc; const int mod = 1e9 + 7; const int oo = 0x5f5f5f5f; const long double PI = acos(-1.0L); int Log2 (int x) {return 31 - __builtin_clz(x);} int ceiledLog2 (int x){return Log2(x) + (__builtin_popcount(x) != 1);} ll toLL (int first, int second, int mx){return (1LL*first*mx) + second;} vi Unique(vi x){sort(ALL(x));x.resize(distance(x.begin(),unique(ALL(x))));return x;} template <class T, class U> T GCD (T a, U b) {return (!b ? a : GCD(b, a%b));} template <class T, class U> T LCM (T a, U b) {return ((a/GCD(a, b)) * b);} template <class T> bool isSquare (T n) {T sq = sqrt(n); return (sq*sq)==n;} template <typename T> using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; //bool sortBySecond (pii &a, pii &b) {return a.second < b.second;} //asc int ys[] = {-1, -1, 0, 1, 1, 1, 0, -1}; //edges [0, 2, 4, 6] int xs[] = {0, 1, 1, 1, 0, -1, -1, -1}; //-----------------------------------------------------------------------------// int n,m=0, z=0,o=0; vector<int> a; int dp[101][2][55][55]; int solve (int idx, int last, int usedZ, int usedO) { if (idx == n){ return 0; } if (~dp[idx][last][usedZ][usedO]){ return dp[idx][last][usedZ][usedO]; } if (a[idx] == -1){ int ans1,ans2; ans1=ans2=1e9; if (usedO<o){ ans1=solve(idx+1, 1, usedZ, usedO+1)+(1 != last); } if (usedZ<z){ ans2 = solve(idx+1, 0, usedZ+1, usedO)+(0 != last); } return dp[idx][last][usedZ][usedO]=min(ans1,ans2); } else{ return dp[idx][last][usedZ][usedO] = solve(idx+1, a[idx], usedZ, usedO)+(a[idx] != last); } } void run_test () { mem(dp,-1); cin >> n; vi f(n+1,0); a=vi(n); for (int i = 0; i < n; i++) { cin >> a[i]; f[a[i]] =1; if (a[i]==0){ a[i] = -1; m++; } else{ a[i] %=2; } } vi miss; for (int i = 1; i <= n; ++i) { if (f[i] == 0){ miss.pb(i); if (i&1){ o++; } else{ z++; } } } dbg(miss,z,o); if (a[0] == -1){ int ans1,ans2; ans1=ans2=1e9; if (o){ ans1=solve(1, 1, 0, 1); } if (z){ ans2 = solve(1, 0, 1, 0); } dbg(ans1,ans2); cout << min(ans1,ans2); } else cout << solve(1,a[0], 0, 0); } void initialize(char _mode = 's'); int32_t main() { initialize(); //cout << fixed << setprecision (9); int tc = 1; //cin >> tc; for (int t=1; t <= tc; t++) { //cout << "Case #" << t << ": "; run_test(); } cerr << "$time taken: " << (float) clock() / CLOCKS_PER_SEC << " seconds" << endl; return 0; } void initialize(char _mode){ //s,d,c,x if (_mode == 's' || _mode == 'c'){ ios::sync_with_stdio(false); cin.tie(nullptr); } #ifdef LOCAL if (_mode == 's' || _mode == 'd'){ freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); } #endif }
cpp
1299
A
A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4 4 0 11 6 OutputCopy11 6 4 0InputCopy1 13 OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.
[ "brute force", "greedy", "math" ]
#include<bits/stdc++.h> using namespace std; #define ll long long int ll a[100010]; int main(){ ll n,i,j,c,k,t; cin>>n; for(i=1;i<=n;i++) cin>>a[i]; for(j=30;j>=0;j--){ c=0; for(i=1;i<=n;i++) if((a[i]>>j)&1)c++,k=i; if(c==1)break; } if(c==1) swap(a[1],a[k]); for(i=1;i<=n;i++) cout<<a[i]<<" "; }
cpp
1301
C
C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105)  — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5 3 1 3 2 3 3 4 0 5 2 OutputCopy4 5 6 0 12 NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement.
[ "binary search", "combinatorics", "greedy", "math", "strings" ]
#include <bits/stdc++.h> using namespace std; #define oo 1000000010 #define mod 1000000007 const int N = 1010; void solve(){ int n , m; scanf("%d%d",&n,&m); long long ans = (long long)n * (long long)(n + 1) / 2LL; int z = n - m; int k = z / (m + 1); ans -= (long long)(m + 1) * (long long)k * (long long)(k + 1) / 2LL; ans -= (long long)(z % (m + 1)) * (long long)(k + 1); printf("%lld\n",ans); } int main(){ int t; cin >> t; while(t--){ solve(); } return 0; }
cpp
1325
F
F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either: find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6 1 3 3 4 4 2 2 6 5 6 5 1 OutputCopy1 1 6 4InputCopy6 8 1 3 3 4 4 2 2 6 5 6 5 1 1 4 2 5 OutputCopy2 4 1 5 2 4InputCopy5 4 1 2 1 3 2 4 2 5 OutputCopy1 3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample:
[ "constructive algorithms", "dfs and similar", "graphs", "greedy" ]
// LUOGU_RID: 102289206 #include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 10; int n, m; vector<int> G[maxn]; int T; int fa[maxn], dep[maxn]; vector<int> ans; class Node { public: int u, dep; Node() = default; Node(int u, int dep) : u(u), dep(dep) {} const bool operator<(const Node& d) const { return dep < d.dep; } }; multiset<Node> s; int tag[maxn]; void dfs(int u, int f) { fa[u] = f; dep[u] = dep[f] + 1; for (int v : G[u]) { if (v == f) continue; if (!dep[v]) dfs(v, u); else if (dep[u] - dep[v] + 1 >= T) { printf("2\n"); int p = u; printf("%d\n%d ", dep[u] - dep[v] + 1, v); do { printf("%d ", p); p = fa[p]; } while (p != v); exit(0); } } if(!tag[u]){ ans.emplace_back(u); for(int v : G[u]){ tag[v] = true; } } } int main() { scanf("%d%d", &n, &m); T = (int)ceil(sqrt(1.0 * n)); for (int i = 1; i <= m; i++) { int u, v; scanf("%d%d", &u, &v); G[u].emplace_back(v); G[v].emplace_back(u); } dfs(1, 0); for (int i = 1; i <= n; i++) { s.emplace(i, dep[i]); } printf("1\n"); for (int i = 1; i <= T; i++) { printf("%d ", ans[i - 1]); } }
cpp
1296
E2
E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9 abacbecfd OutputCopy2 1 1 2 1 2 1 2 1 2 InputCopy8 aaabbcbb OutputCopy2 1 2 1 2 1 2 1 1 InputCopy7 abcdedc OutputCopy3 1 1 1 1 1 2 3 InputCopy5 abcde OutputCopy1 1 1 1 1 1
[ "data structures", "dp" ]
/// What are you doing now? Just go f*cking code now dude? #include <bits/stdc++.h> #pragma GCC optimize("Ofast") #define TASK "codin" //#define int long long using namespace std; typedef long long ll; typedef long double ld; typedef unsigned long long llu; #define IO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define fi first #define se second #define mp make_pair #define pb push_back #define is insert #define eb emplace_back #define FOR(x,a,b) for (ll x=a;x<=b;x++) #define FOD(x,a,b) for (ll x=a;x>=b;x--) #define FER(x,a,b) for (ll x=a;x<b;x++) #define FED(x,a,b) for (ll x=a;x>b;x--) #define EL "\n" #define ALL(v) v.begin(),v.end() #define vi vector<ll> #define vii vector<pii> #define pii pair<int,int> ///---------- TEMPLATE ABOUT BIT ----------/// ll getbit(ll val, ll num){ return ((val >> (num)) & 1LL); } ll offbit(ll val, ll num){ return ((val ^ (1LL << (num - 1)))); } ll setbit(ll k, ll s) { return (k &~ (1 << s)); } ///---------- TEMPLATE ABOUT MATH ----------/// ll lcm(ll a, ll b){ return a * b/__gcd(a, b); } ll bmul(ll a, ll b, ll mod){ if(b == 0){return 0;} if(b == 1){return a;} ll t = bmul(a, b/2, mod);t = (t + t)%mod; if(b%2 == 1){t = (t + a) % mod;}return t; } ll bpow(ll n, ll m, ll mod){ ll res = 1; while (m) { if (m & 1) res = res * n % mod; n = n * n % mod; m >>= 1; } return res; } ///----------------------------------------/// const int S = 5e5 + 5, M = 2e3 + 4; const ll mod = 1e9 + 7, hashmod = 1e9 + 9, inf = 1e18; const int base = 311, BLOCK_SIZE = 420; const int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; const int dxx[8] = {-1, -1, 0, 1, 1, 1, 0, -1}, dyy[8]={0, 1, 1, 1, 0, -1, -1, -1}; ///------ The main code starts here ------/// int n, dp[S]; string s; void solve(){ cin >> n >> s; s = ' ' + s; vector <int> val; int ans = 0; FOD(i, n, 1){ int k = s[i] - 'a'; dp[k] = 1; FOR(j, 0, k - 1){ dp[k] = max(dp[k], dp[j] + 1); } val.pb(dp[k]); ans = max(ans, dp[k]); } cout << ans << EL; reverse(ALL(val)); for(auto x : val){ cout << x << " "; } } signed main(){ IO if(fopen(TASK".inp","r")){ freopen(TASK".inp","r",stdin); freopen(TASK".out","w",stdout); } int t = 1; //cin >> t; while(t--){ solve(); } }
cpp
1293
A
A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5 5 2 3 1 2 3 4 3 3 4 1 2 10 2 6 1 2 3 4 5 7 2 1 1 2 100 76 8 76 75 36 67 41 74 10 77 OutputCopy2 0 4 0 2 NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.
[ "binary search", "brute force", "implementation" ]
#include<bits/stdc++.h> using namespace std; set<int> kit; int main(){ int t; cin>>t; int n,s,k; while(t--){ cin>>n>>s>>k; kit.clear(); int x; for(int i=1;i<=k;i++){ cin>>x; kit.insert(x); } int minx=1e9; for(int i=max(1,s-1005);i<=min(n,s+1005);i++){ if(!kit.count(i)) minx=min(minx,abs(i-s)); } cout<<minx<<endl; } }
cpp
1290
F
F. Making Shapestime limit per test5 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputYou are given nn pairwise non-collinear two-dimensional vectors. You can make shapes in the two-dimensional plane with these vectors in the following fashion: Start at the origin (0,0)(0,0). Choose a vector and add the segment of the vector to the current point. For example, if your current point is at (x,y)(x,y) and you choose the vector (u,v)(u,v), draw a segment from your current point to the point at (x+u,y+v)(x+u,y+v) and set your current point to (x+u,y+v)(x+u,y+v). Repeat step 2 until you reach the origin again.You can reuse a vector as many times as you want.Count the number of different, non-degenerate (with an area greater than 00) and convex shapes made from applying the steps, such that the shape can be contained within a m×mm×m square, and the vectors building the shape are in counter-clockwise fashion. Since this number can be too large, you should calculate it by modulo 998244353998244353.Two shapes are considered the same if there exists some parallel translation of the first shape to another.A shape can be contained within a m×mm×m square if there exists some parallel translation of this shape so that every point (u,v)(u,v) inside or on the border of the shape satisfies 0≤u,v≤m0≤u,v≤m.InputThe first line contains two integers nn and mm  — the number of vectors and the size of the square (1≤n≤51≤n≤5, 1≤m≤1091≤m≤109).Each of the next nn lines contains two integers xixi and yiyi  — the xx-coordinate and yy-coordinate of the ii-th vector (|xi|,|yi|≤4|xi|,|yi|≤4, (xi,yi)≠(0,0)(xi,yi)≠(0,0)).It is guaranteed, that no two vectors are parallel, so for any two indices ii and jj such that 1≤i<j≤n1≤i<j≤n, there is no real value kk such that xi⋅k=xjxi⋅k=xj and yi⋅k=yjyi⋅k=yj.OutputOutput a single integer  — the number of satisfiable shapes by modulo 998244353998244353.ExamplesInputCopy3 3 -1 0 1 1 0 -1 OutputCopy3 InputCopy3 3 -1 0 2 2 0 -1 OutputCopy1 InputCopy3 1776966 -1 0 3 3 0 -2 OutputCopy296161 InputCopy4 15 -4 -4 -1 1 -1 -4 4 3 OutputCopy1 InputCopy5 10 3 -4 4 -3 1 -3 2 -3 -3 -4 OutputCopy0 InputCopy5 1000000000 -2 4 2 -3 0 -4 2 4 -1 -3 OutputCopy9248783 NoteThe shapes for the first sample are: The only shape for the second sample is: The only shape for the fourth sample is:
[ "dp" ]
#ifdef ONLINE_JUDGE #include <bits/stdc++.h> #else #include "headers.h" #endif namespace IO { std::ostream& fmtbase(std::ostream& out, const char* format) { for (; *format; format++) { if (*format == '{' && *(format + 1) == '}') { throw std::invalid_argument("Error Number of Parameters!"); } out << *format; } return out; } template <class Fst, class... Nxt> std::ostream& fmtbase(std::ostream& out, const char* format, const Fst& value, const Nxt&... nxt) { for (; *format; format++) { if (*format == '{' && *(format + 1) == '}') { out << value; return fmtbase(out, format + 2, nxt...); } out << *format; } throw std::invalid_argument("Error Number of Parameters!"); } template <class... Ps> std::ostream& fmtout(const char* format, const Ps&... ps) { return fmtbase(std::cout, format, ps...); } template <class... Ps> std::ostream& fmterr(const char* format, const Ps&... ps) { return fmtbase(std::cerr, format, ps...); } std::istream& allin() { return std::cin; } template <class Fst, class ... Nxt> std::istream& allin(Fst& fst, Nxt&... nxt) { std::cin >> fst; return allin(nxt...); } template <class Iter> std::istream& rangin(Iter begin, Iter end) { while (begin != end) { std::cin >> *begin; begin++; } return std::cin; } namespace Fast { bool sync = false; char buf[1 << 23]; char *p1 = buf, *p2 = buf; void sync_with_ios(bool s) { sync = s; } char getchar() { if (sync) { return std::cin.get(); } else { if (p1 == p2) { p1 = buf; p2 = p1 + fread(buf, 1, 1 << 22, stdin); } if (p1 == p2) { return EOF; } else { char res = *p1; p1++; return res; } } } void read() { } template <class T, class... U> void read(T& x, U&... us) { x = 0; T pos = 1; char c = getchar(); while (!isdigit(c)) { if (c == '-') { pos = -1; } c = getchar(); } while (isdigit(c)) { x = 10 * x + c - '0'; c = getchar(); } x *= pos; read(us...); } template <class T> void write(const T& t) { if (t > 10) { write(t / 10); } std::cout << (int) (t % 10); } } } namespace Solve { #define int long long using namespace IO; using Long = long long; using Double = long double; int const Shabby = 0; int const INF = std::numeric_limits<int>::max(); int const NINF = std::numeric_limits<int>::min(); Long const LINF = std::numeric_limits<Long>::max(); Long const LNINF = std::numeric_limits<Long>::min(); Double const EPS = 1e-6; template <int M> struct ModInt { // Promise: MOD is a prime; 2 * MOD < INT_MAX static int const MOD = M; int val; ModInt() : val(0) { } ModInt(long long v) { if (-MOD <= v && v < 2 * MOD) { if (v > MOD) { v -= MOD; } else if (v < 0) { v += MOD; } } else { v %= MOD; if (v < 0) { v += MOD; } } val = v; } ModInt operator++(signed) { auto t = *this; operator+=(1); return t; } ModInt& operator++() { operator+=(1); return *this; } ModInt operator--(signed) { auto t = *this; operator-=(1); return t; } ModInt& operator--() { operator-=(1); return *this; } ModInt& operator+=(const ModInt& rhs) { val = val + rhs.val >= MOD ? val + rhs.val - MOD : val + rhs.val; return *this; } friend ModInt operator+(const ModInt& lhs, const ModInt& rhs) { ModInt res = lhs; res += rhs; return res; } ModInt& operator-=(const ModInt& rhs) { val = val - rhs.val < 0 ? val - rhs.val + MOD : val - rhs.val; return *this; } friend ModInt operator-(const ModInt& lhs, const ModInt& rhs) { ModInt res = lhs; res -= rhs; return res; } ModInt& operator*=(const ModInt& rhs) { val = 1ll * val * rhs.val % MOD; return *this; } friend ModInt operator*(const ModInt& lhs, const ModInt& rhs) { ModInt res = lhs; res *= rhs; return res; } ModInt fpow(long long p) const { if (p < 0) { return fpow(-p).inv(); } else if (!p) { return 1; } else if (p == 1) { return *this; } else if (p == 2) { return *this * *this; } else { return fpow(p / 2).fpow(2) * fpow(p % 2); } } friend bool operator==(const ModInt& a, const ModInt& b) { return a.val == b.val; } friend bool operator!=(const ModInt& a, const ModInt& b) { return a.val != b.val; } friend ModInt operator-(const ModInt& a) { ModInt res; if (a.val == 0) { return 0; } res.val = MOD - a.val; return res; } ModInt inv() const { return fpow(MOD - 2); } ModInt operator/=(const ModInt& rhs) { // O(log MOD) return operator*=(rhs.inv()); } friend ModInt operator/(const ModInt& lhs, const ModInt& rhs) { ModInt res = lhs; res /= rhs; return res; } bool is_square() const { return val == 0 || fpow((MOD - 1) / 2).val == 1; } ModInt sqrt() const { static std::mt19937 mt(42334435); static ModInt isq; assert(is_square()); struct Complex { ModInt a, b; Complex operator*(const Complex& rhs) const { return { a * rhs.a + isq * b * rhs.b, a * rhs.b + b * rhs.a }; } Complex fpow(int n) { if (!n) { return { 1, 0 }; } else if (n == 1) { return *this; } else if (n == 2) { return operator*(*this); } else { return fpow(n / 2).fpow(2) * fpow(n % 2); } } }; if (val == 0) { return 0; } ModInt b; while (true) { b = mt() % MOD; if (!(b * b - *this).is_square()) { break; } } isq = b * b - *this; Complex c = { b, 1 }; auto res = c.fpow((MOD + 1) / 2).a; return std::min(res.val, MOD - res.val); } }; template <int MOD> std::istream& operator>>(std::istream& in, ModInt<MOD>& mint) { long long v; in >> v; mint.val = v % MOD; return in; } template <int MOD> std::ostream& operator<<(std::ostream& out, const ModInt<MOD>& mint) { return out << mint.val; } template <class T, int B> struct FastPow { T baby[B + 1]; T gaint[B + 1]; FastPow(T b) { baby[0] = 1; for (int i = 1; i <= B; i++) { baby[i] = baby[i - 1] * b; } gaint[0] = 1; for (int i = 1; i <= B; i++) { gaint[i] = gaint[i - 1] * baby[B]; } } T get(int n) { return gaint[n / B] * baby[n % B]; } }; int const MOD = 998244353; template <int M> const int ModInt<M>::MOD; using Mint = ModInt<MOD>; struct Point { int x, y; }; int const N = 6; Point ps[N + 1]; int n, m; Mint f[33][23][23][23][23][2][2]; bool vis[33][23][23][23][23][2][2]; Mint dfs(int i, int xn, int xp, int yn, int yp, int xc, int yc) { // fmterr("{} {} {} {} {} {} {}\n", i, xn, xp, yn, yp, xc, yc); auto& tf = f[i][xn][xp][yn][yp][xc][yc]; if (vis[i][xn][xp][yn][yp][xc][yc]) { return tf; } if (i >= 31) { // fmterr("{} {} {} {} {} {} {} {}\n", i, xn, xp, yn, yp, xc, yc, xn == 0 && xp == 0 && yn == 0 && yp == 0 && xc == 0 && yc == 0); return xn == 0 && xp == 0 && yn == 0 && yp == 0 && xc == 0 && yc == 0; } vis[i][xn][xp][yn][yp][xc][yc] = 1; for (int s = 0; s < (1 << n); s++) { int txn = xn; int txp = xp; int tyn = yn; int typ = yp; int txc = xc; int tyc = yc; int cxn = 0; int cxp = 0; int cyn = 0; int cyp = 0; for (int i = 0; i < n; i++) { if ((s >> i) & 1) { if (ps[i].x < 0) { txn += -ps[i].x; } else { txp += ps[i].x; } if (ps[i].y < 0) { tyn += -ps[i].y; } else { typ += ps[i].y; } } } cxn = txn & 1; txn >>= 1; cxp = txp & 1; txp >>= 1; cyn = tyn & 1; tyn >>= 1; cyp = typ & 1; typ >>= 1; int cm = (m >> i) & 1; if (cxn == cxp && cyn == cyp) { // fmterr("? {}\n", i); tf += dfs(i + 1, txn, txp, tyn, typ, (cxn > cm) || (cxn == cm && xc), (cyn > cm) || (cyn == cm && yc)); } } // fmterr("{} {} {} {} {} {} {} {}\n", i, xn, xp, yn, yp, xc, yc, tf); return tf; } void main() { allin(n, m); for (int i = 0; i < n; i++) { allin(ps[i].x, ps[i].y); } fmtout("{}\n", dfs(0, 0, 0, 0, 0, 0, 0) - 1); } void init() { } void clear() { } } signed main() { #ifndef ONLINE_JUDGE // freopen("d.in", "r", stdin); // freopen("mine.out", "w", stdout); // freopen("data/3594/6.in", "r", stdin); // freopen("d.out", "w", stdout); #endif std::ios::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); int t = 1; // std::cin >> t; Solve::init(); for (; t; t--) { Solve::main(); Solve::clear(); } return 0; }
cpp
1286
C2
C2. Madhouse (Hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ (⌈x⌉⌈x⌉ is xx rounded up).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict. Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4 a aa a cb b c cOutputCopy? 1 2 ? 3 4 ? 4 4 ! aabc
[ "brute force", "constructive algorithms", "hashing", "interactive", "math" ]
#include<bits/stdc++.h> #define Tp template<typename Ty> #define Ts template<typename Ty,typename... Ar> #define W while #define I inline #define RI int #define LL long long #define Cn const #define CI Cn int& #define gc getchar #define D isdigit(c=gc()) #define pc(c) putchar((c)) using namespace std; namespace Debug{ Tp I void _debug(Cn char* f,Ty t){cerr<<f<<'='<<t<<endl;} Ts I void _debug(Cn char* f,Ty x,Ar... y){W(*f!=',') cerr<<*f++;cerr<<'='<<x<<",";_debug(f+1,y...);} Tp ostream& operator<<(ostream& os,Cn vector<Ty>& V){os<<"[";for(Cn auto& vv:V) os<<vv<<",";os<<"]";return os;} #define gdb(...) _debug(#__VA_ARGS__,__VA_ARGS__) }using namespace Debug; namespace FastIO{ Tp I void read(Ty& x){char c;int f=1;x=0;W(!D) f=c^'-'?1:-1;W(x=(x<<3)+(x<<1)+(c&15),D);x*=f;} Ts I void read(Ty& x,Ar&... y){read(x),read(y...);} Tp I void write(Ty x){x<0&&(pc('-'),x=-x,0),x<10?(pc(x+'0'),0):(write(x/10),pc(x%10+'0'),0);} Tp I void writeln(Cn Ty& x){write(x),pc('\n');} }using namespace FastIO; Cn int N=110; int n,vis[N],col[N]; struct node{int a[27],L;}A,B,lst[N]; I node Mul(node a,int b){for(int i=0;i<26;i++)a.a[i]*=b;return a;} I node Sub(node a,node b){for(int i=0;i<26;i++)a.a[i]-=b.a[i];return a;} I node RD(){node t;memset(t.a,0,sizeof(t.a));string s;cin>>s;RI l=s.length(),i;for(t.L=l,i=0;i<l;i++) t.a[s[i]-'a']++;return t;} #define fi first #define se second vector<pair<int,pair<int,int> > > G[N]; #define pb push_back I void U(CI a,CI b,CI x,CI y){ if(a==b) return assert(x==y),vis[a]=1,col[a]=x,void(); G[a].pb({b,{x,y}}),G[b].pb({a,{x,y}}); } I void Q(CI l,CI r){ cout<<"? "<<l<<" "<<r<<endl; RI i,j,k,m=r-l+1,t=m*(m+1)/2;vector<node> v; for(i=0;i<t;i++) v.pb(RD()); for(i=0;i<t;i++) if(v[i].L==m) A=v[i]; for(i=1;i<=(m+1)/2;i++){ B=Mul(A,i+1);for(auto k:v) if(k.L==m-i) B=Sub(B,k); for(j=1;j<i;j++) B=Sub(B,Mul(lst[j],i-j+1)); lst[i]=B;for(j=0;j<26;j++) if(B.a[j]){B.a[j]--;for(k=j;k<26;k++) if(B.a[k]){U(l+i-1,r-i+1,j,k);break ;}break ;} }return ; } queue<int> q; int main(){ RI i,u,y,z,l,r;read(n); if(n==1){cout<<"? 1 1"<<endl;string s;cin>>s;cout<<"! "<<s<<endl;return 0;} Q(1,n),Q(1,n/2),Q((n+1)/2,n); W(!q.empty()) q.pop(); for(i=1;i<=n;i++) vis[i]&&(q.push(i),0); W(!q.empty()){u=q.front(),q.pop();for(auto i:G[u]) y=i.fi,z=col[u]==i.se.fi?i.se.se:i.se.fi,!vis[y]&&(vis[y]=1,col[y]=z,q.push(y),0),assert(col[y]==z);} cout<<"! ";for(i=1;i<=n;i++) pc(col[i]+'a');pc('\n');return 0; }
cpp
1290
D
D. Coffee Varieties (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. You can find the easy version in the Div. 2 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will: Tell you if acac is in SS; Add acac at the back of SS; If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 3n22k3n22k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 3n22k≤15 0003n22k≤15 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 3n22k3n22k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 3n22k≤15 0003n22k≤15 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2 N N Y N N N N OutputCopy? 1 ? 2 ? 3 ? 4 R ? 4 ? 1 ? 2 ! 3 InputCopy8 8 N N N N Y Y OutputCopy? 2 ? 6 ? 4 ? 5 ? 2 ? 5 ! 6 NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5.
[ "constructive algorithms", "graphs", "interactive" ]
/// /// ♪ Hashire sori yo ♪ /// ♪ Kaze no you ni ♪ /// ♪ Tsukimihara wo ♪ /// ♪ PADORU PADORU ♪ /// #include <bits/stdc++.h> #define Loop(x,l,r) for (ll x = (l); x < (ll)(r); ++x) #define LoopR(x,l,r) for (ll x = (r)-1; x >= (ll)(l); --x) typedef long long ll; typedef std::pair<int, int> pii; typedef std::pair<ll , ll > pll; using namespace std; bool qry(int x) { cout << "? " << x+1 << '\n'; char c; cin >> c; return toupper(c) == 'Y'; } void clear() { cout << "R\n"; } int main() { ios::sync_with_stdio(false); int n, k; cin >> n >> k; vector<bool> ok(n, 1); if (k > 1) k /= 2; int m = n/k; for (int dis = 1; dis < m; ++dis) { Loop (i,0,dis) { if (i + dis >= m) continue; clear(); for (int j = i; j < m; j += dis) { Loop (x,j*k,j*k+k) { if (qry(x)) ok[x] = 0; } } } } int ans = 0; Loop (i,0,n) ans += ok[i]; cout << "! " << ans << '\n'; }
cpp
1296
F
F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4 1 2 3 2 3 4 2 1 2 5 1 3 3 OutputCopy5 3 5 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 OutputCopy5 3 1 2 1 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 OutputCopy-1
[ "constructive algorithms", "dfs and similar", "greedy", "sortings", "trees" ]
#include<bits/stdc++.h> using namespace std; #define lll pair<long,pair<long,long>> #define ll pair<long,long> #define st first #define nd second const long N=5e3+10; long n,x,y,ans[N],D[N],H[N],C[N][N],m,cnt; vector<long> ds[N]; lll Q[N]; void DFS(long a,long p){ for(long v: ds[a]){ if(v!=p){ H[v]=H[a]+1; D[v]=a; DFS(v,a); } } } bool check(long a,long b,long val){ if(H[a]<H[b]) swap(a,b); cnt=0; while(H[a]>H[b]){ if(ans[C[a][D[a]]]<=val) {ans[C[a][D[a]]]=val; cnt++;} a=D[a]; } while(a!=b){ if(ans[C[a][D[a]]]<=val) {ans[C[a][D[a]]]=val; cnt++;} a=D[a]; if(ans[C[b][D[b]]]<=val) {ans[C[b][D[b]]]=val; cnt++;} b=D[b]; } if(!cnt) return false; return true; } int main(){ ios::sync_with_stdio(0);cin.tie(0); cin>>n; for(long i=1; i<n; i++){ cin>>x>>y; ds[x].push_back(y); ds[y].push_back(x); C[x][y]=i; C[y][x]=i; } cin>>m; for(long i=1; i<=m; i++){ cin>>Q[i].nd.st>>Q[i].nd.nd>>Q[i].st; } sort(Q+1,Q+m+1,greater<lll>()); H[1]=1; DFS(1,1); for(long i=1; i<=m; i++){ if(!check(Q[i].nd.st,Q[i].nd.nd,Q[i].st)){ cout<<-1; return 0; } } for(long i=1; i<n; i++) cout<<max(1l,ans[i])<<' '; }
cpp
1311
F
F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3 1 3 2 -100 2 3 OutputCopy3 InputCopy5 2 1 4 3 5 2 2 2 3 4 OutputCopy19 InputCopy2 2 1 -3 0 OutputCopy0
[ "data structures", "divide and conquer", "implementation", "sortings" ]
#include<bits/stdc++.h> #define nl "\n" #define fi first #define se second #define pi 3.14159 #define ll long long #define odd(a) (a&1) #define even(a) !(a&1) #define Mod 1'000'000'007 #define INF 2'000'000'000 #define sz(x) int(x.size()) #define charToInt(s) (s - '0') #define ull unsigned long long #define number_line iota(all(vec) , 1) #define all(s) s.begin(), s.end() #define rall(v) v.rbegin() , v.rend() #define fixed(n) fixed << setprecision(n) #define Num_of_Digits(n) ((int)log10(n) + 1) #define to_decimal(bin) stoll(bin, nullptr, 2) #define Ceil(n, m) (((n) / (m)) + ((n) % (m) ? 1 : 0)) #define Floor(n, m) (((n) / (m)) - ((n) % (m) ? 0 : 1)) #define Upper(s) transform(all(s), s.begin(), ::toupper); #define Lower(s) transform(all(s), s.begin(), ::tolower); #define cout_map(mp) for(auto& [f, s] : mp) cout << f << " " << s << "\n"; // ----- bits------- #define pcnt(n) __builtin_popcount(n) #define pcntll(n) __builtin_popcountll(n) #define clz(n) __builtin_clz(n) // <---100 #define clzll(n) __builtin_clzll(n) #define ctz(n) __builtin_ctz(n) // 0001----> #define ctzll(n) __builtin_ctzll(n) using namespace std; template < typename T = int > istream& operator >> (istream &in, vector < T > & v){ for(auto & x : v) in >> x; return in; } template < typename T = int > ostream& operator << (ostream &out, const vector < T > & v){ for(const T & x : v) out << x << " "; return out; } void esraa() { 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); #endif } #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; template <typename K, typename V, typename Comp = std::less<K>> using ordered_map = tree<K, V, Comp, rb_tree_tag, tree_order_statistics_node_update>; template <typename K, typename Comp = std::less<K>> using ordered_set = ordered_map<K, null_type, Comp>; template <typename K, typename V, typename Comp = std::less_equal<K>> using ordered_multimap = tree<K, V, Comp, rb_tree_tag, tree_order_statistics_node_update>; template <typename K, typename Comp = std::greater_equal<K>> using ordered_multiset = ordered_multimap<K, null_type, Comp>; // ordered_of_key(k) : number of items strictly smaller than k // find_by_order(k) : k-th largest element (counting from zero) void solve(){ int n; cin >> n; vector < pair < int , int > > p(n); for(auto & i : p) cin >> i.first; for(auto & i : p) cin >> i.second; sort(all(p)); ordered_set < pair < int , int > > st; ll ans = 0; for(int i = 0 ; i < n ; i++){ int cnt = st.order_of_key({p[i].second + 1, -1}); ans += 1ll * cnt * p[i].first; st.insert({p[i].second, i}); } st.clear(); for(int i = n - 1 ; i >= 0 ; i--){ int cnt = sz(st) - st.order_of_key({p[i].second, -1}); ans -= 1ll * cnt * p[i].first; st.insert({p[i].second, i}); } cout << ans << nl; } int main() { esraa(); int t = 1; //cin >> t; //cin.ignore(); while(t--) solve(); return 0; }
cpp
1288
F
F. Red-Blue Graphtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a bipartite graph: the first part of this graph contains n1n1 vertices, the second part contains n2n2 vertices, and there are mm edges. The graph can contain multiple edges.Initially, each edge is colorless. For each edge, you may either leave it uncolored (it is free), paint it red (it costs rr coins) or paint it blue (it costs bb coins). No edge can be painted red and blue simultaneously.There are three types of vertices in this graph — colorless, red and blue. Colored vertices impose additional constraints on edges' colours: for each red vertex, the number of red edges indicent to it should be strictly greater than the number of blue edges incident to it; for each blue vertex, the number of blue edges indicent to it should be strictly greater than the number of red edges incident to it. Colorless vertices impose no additional constraints.Your goal is to paint some (possibly none) edges so that all constraints are met, and among all ways to do so, you should choose the one with minimum total cost. InputThe first line contains five integers n1n1, n2n2, mm, rr and bb (1≤n1,n2,m,r,b≤2001≤n1,n2,m,r,b≤200) — the number of vertices in the first part, the number of vertices in the second part, the number of edges, the amount of coins you have to pay to paint an edge red, and the amount of coins you have to pay to paint an edge blue, respectively.The second line contains one string consisting of n1n1 characters. Each character is either U, R or B. If the ii-th character is U, then the ii-th vertex of the first part is uncolored; R corresponds to a red vertex, and B corresponds to a blue vertex.The third line contains one string consisting of n2n2 characters. Each character is either U, R or B. This string represents the colors of vertices of the second part in the same way.Then mm lines follow, the ii-th line contains two integers uiui and vivi (1≤ui≤n11≤ui≤n1, 1≤vi≤n21≤vi≤n2) denoting an edge connecting the vertex uiui from the first part and the vertex vivi from the second part.The graph may contain multiple edges.OutputIf there is no coloring that meets all the constraints, print one integer −1−1.Otherwise, print an integer cc denoting the total cost of coloring, and a string consisting of mm characters. The ii-th character should be U if the ii-th edge should be left uncolored, R if the ii-th edge should be painted red, or B if the ii-th edge should be painted blue. If there are multiple colorings with minimum possible cost, print any of them.ExamplesInputCopy3 2 6 10 15 RRB UB 3 2 2 2 1 2 1 1 2 1 1 1 OutputCopy35 BUURRU InputCopy3 1 3 4 5 RRR B 2 1 1 1 3 1 OutputCopy-1 InputCopy3 1 3 4 5 URU B 2 1 1 1 3 1 OutputCopy14 RBB
[ "constructive algorithms", "flows" ]
#include <cstdio> #include <iostream> #include <queue> using namespace std; const int M = 1005; const int inf = 0x3f3f3f3f; int read() { int x=0,f=1;char c; while((c=getchar())<'0' || c>'9') {if(c=='-') f=-1;} while(c>='0' && c<='9') {x=(x<<3)+(x<<1)+(c^48);c=getchar();} return x*f; } int n1,n2,m,R,B,s1,t1,S,T,d[M];char sa[M],sb[M]; int tot=1,f[M],dis[M],flow[M],pre[M],lst[M]; struct edge { int v,f,c,next; }e[M*M]; void add(int u,int v,int l,int r,int c) { d[u]-=l;d[v]+=l; e[++tot]=edge{v,r-l,c,f[u]},f[u]=tot; e[++tot]=edge{u,0,-c,f[v]},f[v]=tot; } int bfs() { queue<int> q; for(int i=0;i<=T;i++) dis[i]=inf,flow[i]=pre[i]=lst[i]=0; dis[S]=0;flow[S]=inf;q.push(S); while(!q.empty()) { int u=q.front();q.pop(); for(int i=f[u];i;i=e[i].next) { int v=e[i].v,c=e[i].c; if(dis[v]>dis[u]+c && e[i].f>0) { dis[v]=dis[u]+c; flow[v]=min(flow[u],e[i].f); pre[v]=u;lst[v]=i; q.push(v); } } } return flow[T]>0; } signed main() { n1=read();n2=read();m=read();R=read();B=read(); scanf("%s%s",sa+1,sb+1); s1=n1+n2+1;t1=s1+1;S=t1+1;T=S+1; for(int i=1;i<=m;i++) { int u=read(),v=read(); add(u,v+n1,0,1,R); add(v+n1,u,0,1,B); } for(int i=1;i<=n1;i++) { if(sa[i]=='R') add(s1,i,1,inf,0); else if(sa[i]=='B') add(i,t1,1,inf,0); else add(s1,i,0,inf,0),add(i,t1,0,inf,0); } for(int i=1;i<=n2;i++) { if(sb[i]=='R') add(i+n1,t1,1,inf,0); else if(sb[i]=='B') add(s1,i+n1,1,inf,0); else add(s1,i+n1,0,inf,0),add(i+n1,t1,0,inf,0); } add(t1,s1,0,inf,0); int ans=0,cost=0,sum=0; for(int i=1;i<=t1;i++) { if(d[i]>0) sum+=d[i],add(S,i,0,d[i],0); if(d[i]<0) add(i,T,0,-d[i],0); } while(bfs()) { ans+=flow[T];int nw=T; cost+=flow[T]*dis[T]; while(nw!=S) { e[lst[nw]].f-=flow[T]; e[lst[nw]^1].f+=flow[T]; nw=pre[nw]; } } if(ans<sum) {puts("-1");return 0;} printf("%d\n",cost); for(int i=2;i<=4*m;i+=4) { if(!e[i].f) putchar('R'); else if(!e[i+2].f) putchar('B'); else putchar('U'); } puts(""); }
cpp
1296
F
F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4 1 2 3 2 3 4 2 1 2 5 1 3 3 OutputCopy5 3 5 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 OutputCopy5 3 1 2 1 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 OutputCopy-1
[ "constructive algorithms", "dfs and similar", "greedy", "sortings", "trees" ]
#include<bits/stdc++.h> using namespace std; using pii=pair<int,int>; using ll=long long; const int N=5e3+10,logn=15; pii f[logn+1][N<<1]; int dep[N],tot,first_pos[N]; vector<int>e[N]; int g[N][N]; int par[N]; void dfs(int u,int fa) { first_pos[u]=++tot; dep[u]=dep[fa]+1; f[0][tot]={dep[u],u}; par[u]=fa; for(auto v:e[u]) { if(v==fa)continue; dfs(v,u); f[0][++tot]={dep[u],u}; } } void init(int root) { dfs(root,0); for(int i=1;i<=logn;++i) for(int j=1;j<=tot;++j) f[i][j]=min(f[i-1][j],f[i-1][j+(1<<i-1)]); } int LCA(int a,int b) { int l=first_pos[a],r=first_pos[b]; if(l>r)swap(l,r); int len=31-__builtin_clz(r-l+1); return min(f[len][l],f[len][r-(1<<len)+1]).second; } void modify(int u,int v,int col) { int lca=LCA(u,v); while(u!=lca){int fa=par[u];g[fa][u]=g[u][fa]=col;u=fa;} while(v!=lca){int fa=par[v];g[fa][v]=g[v][fa]=col;v=fa;} } int query(int u,int v) { int lca=LCA(u,v); int rs=1e6; while(u!=lca){int fa=par[u];rs=min(rs,g[u][fa]);u=fa;} while(v!=lca){int fa=par[v];rs=min(rs,g[v][fa]);v=fa;} return rs; } void solve() { int n;scanf("%d",&n); vector<array<int,2>>edge(n-1); for(auto &[u,v]:edge)scanf("%d%d",&u,&v),e[u].push_back(v),e[v].push_back(u); for(auto &[u,v]:edge)g[u][v]=g[v][u]=1e6; init(1); int m;scanf("%d",&m); vector<array<int,3>>p(m); for(auto &[w,u,v]:p)scanf("%d%d%d",&u,&v,&w); sort(p.begin(),p.end()); for(auto [w,u,v]:p) { modify(u,v,w); } for(auto [w,u,v]:p)if(query(u,v)!=w){printf("-1\n");return ;} for(auto &[u,v]:edge)printf("%d ",g[u][v]); } int main() { int T=1; while(T--)solve(); }
cpp
1301
A
A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4 aaa bbb ccc abc bca bca aabb bbaa baba imi mii iim OutputCopyNO YES YES NO NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb.
[ "implementation", "strings" ]
#include <bits/stdc++.h> using namespace std; string a,b,c; int t; int main() { cin >> t; while(t--){ cin >> a; cin >> b; cin >> c; bool f = true; for(int i=0; i<a.size(); ++i){ if(c[i] != a[i] && c[i] != b[i]){ f = false; break; } } if(f){ cout << "YES" << endl; } else { cout << "NO" << endl; } } }
cpp
1304
C
C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4 3 0 5 1 2 7 3 5 10 -1 0 2 12 5 7 10 10 16 20 3 -100 100 0 0 100 -50 50 200 100 100 1 100 99 -100 0 OutputCopyYES NO YES NO NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
[ "dp", "greedy", "implementation", "sortings", "two pointers" ]
/*********** MK-1311 ***********/ #include <bits/stdc++.h> using namespace std; #define fi first #define se second #define pb push_back #define nl '\n' #ifdef LOCAL #include "debug.h" #else #define debug(...) #endif /* */ #define int long long void solve() { int n, it; cin >> n >> it; vector<tuple<int, int, int>> a(n); for(int i = 0; i < n; i++) { auto &[t, l, h] = a[i]; cin >> t >> l >> h; } vector<vector<int>> b(n, vector<int>(2, false)); b[0][0] = max(it, get<1>(a[0])) - get<0>(a[0]); b[0][1] = min(it, get<2>(a[0])) + get<0>(a[0]); for(int i = 1; i < n; i++) { auto [t1, l1, h1] = a[i - 1]; auto [t2, l2, h2] = a[i]; int timeBetween = t2 - t1; b[i][0] = max(b[i - 1][0], l1) - timeBetween; b[i][1] = min(b[i - 1][1], h1) + timeBetween; } bool ok = true; for(int i = 0; i < n; i++) { debug(b[i]); auto [t, l, h] = a[i]; if(l > b[i][1] || h < b[i][0]) { ok = false; } } cout << (ok ? "YES" : "NO") << endl; } int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); int tt = 1; cin >> tt; for(int i = 0; i < tt; i++) { solve(); } cerr << "time taken : " << (float)clock() / CLOCKS_PER_SEC << " secs" << endl; return 0; }
cpp
1296
E2
E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9 abacbecfd OutputCopy2 1 1 2 1 2 1 2 1 2 InputCopy8 aaabbcbb OutputCopy2 1 2 1 2 1 2 1 1 InputCopy7 abcdedc OutputCopy3 1 1 1 1 1 2 3 InputCopy5 abcde OutputCopy1 1 1 1 1 1
[ "data structures", "dp" ]
#include <bits/stdc++.h> using namespace std; using ll = long long; using vb = vector<bool>; using vvb = vector<vb>; using vi = vector<int>; using vvi = vector<vi>; using vl = vector<ll>; using vvl = vector<vl>; using vc = vector<char>; using vvc = vector<vc>; using vs = vector<string>; #define pb push_back #include <bits/stdc++.h> using namespace std; // ll mod = 1e9 + 7 ; // const ll maxn = 1e5+1 ; // ll fac[maxn],invfact[maxn]; // ll power(ll x, ll y) // { // ll res = 1; // x = x % mod; // while (y > 0) { // if (y & 1) // res = (res * x) % mod; // y = y >> 1; // x = (x * x) % mod; // } // return res; // } // ll modInverse(ll n) // { // return power(n, mod - 2); // } // ll NCR(ll n, ll r, ll p=mod) // { // if(r < 0 || n < 0) // assert(false); // if( n < r ) return 0; // if (r == 0 || r == n) // return 1; // return ( fac[n] * invfact[r] % mod) * invfact[n - r] % mod; // } // void comp() // { // fac[0] = 1, invfact[0] = 1; // for (ll i = 1; i < maxn; i++){ // fac[i] = (fac[i - 1] * i) % mod; // invfact[i] = modInverse(fac[i]); // } // } void solve() { int n; cin >> n; string s; cin >> s; vi last (26,-1); vi ans ; for(int i = 0; i < n;i++){ for (int j = 0; j < 26; j++) { if(s[i]-'a'>=last[j]){ last[j] = s[i]-'a' ; ans.push_back(j) ; break ; } } } cout<<*max_element(ans.begin(),ans.end())+1<<endl ; for (int i = 0; i < n; i++) { cout<<ans[i]+1<<" "; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); // comp() ; -> to use ncr int t = 1; while (t--) { solve(); } return 0; }
cpp
1301
C
C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105)  — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5 3 1 3 2 3 3 4 0 5 2 OutputCopy4 5 6 0 12 NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement.
[ "binary search", "combinatorics", "greedy", "math", "strings" ]
#include<bits/stdc++.h> using namespace std; #define int long long const int M=998244353;; long long mod(long long x){ return ((x%M + M)%M); } long long add(long long a, long long b){ return mod(mod(a)+mod(b)); } long long mul(long long a, long long b){ return mod(mod(a)*mod(b)); } long long modPow(int x, int y){ if(y==0) return 1LL; if(y==1) return mod(x); long long res=1; while(y){ if(y%2==1) res=mul(res,x); x=mul(x,x); y/=2; } return res; } int pow(int x, int n, int d) { int M=d; if(x==0) return 0; return modPow(x,n); } void solve(){ int n; cin>>n; int m; cin>>m; if(m==0){ cout<<0<<endl; return; } int s= (n*(n+1))/2; int x=n-m;//no of zeros in the string int g1=x/(m+1); int y=x%(m+1); //cout<<y<<" "; int res=0; int z=g1+1; z=(z*(z+1))/2; z*=y; // cout<<g1<<" "; int z2=g1; z2=(z2*(z2+1))/2; z2*=(m+1-y); res=z+z2; cout<<s-res<<endl; return; //cout<<y<<endl; /* for(int j=1;j<=(m+1);j++){ if(y>0){ res+=z; y--; }else{ res+=z; } } cout<<s-res<<endl;*/ } signed main(){ ios::sync_with_stdio(false); cin.tie(0);cout.tie(0); int t; cin>>t; while(t--){ solve(); } }
cpp
1322
E
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.
[ "data structures" ]
#include <algorithm> #include <cstdio> #include <cstring> #include <functional> const int N = 5e5 + 55, LN = 20; template <typename comp> struct ST { inline static int lg2(int n) { return 31 - __builtin_clz(n); } inline static int _(int x, int y) { return comp()(x, y) ? x : y; } int st[LN][N]; void init(int *a, int n) { memcpy(st[0], a, n << 2); for (int j = 1; j < LN; j++) for (int i = 0; i + (1 << j) - 1 < n; i++) st[j][i] = _(st[j - 1][i], st[j - 1][i + (1 << (j - 1))]); } int operator()(int l, int r) { int k = lg2(r - l + 1); return _(st[k][l], st[k][r - (1 << k) + 1]); } }; int n, ans, a[N], t[2][N], out[N]; ST<std::greater<int>> mx; ST<std::less<int>> mn; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", a + i); a[0] = a[1], a[n + 1] = a[n]; for (int i = 0; i <= n; i++) { t[0][i] = std::min(a[i], a[i + 1]); t[1][i] = std::max(a[i], a[i + 1]); } mn.init(t[1], n + 1); mx.init(t[0], n + 1); for (int i = 1; i <= n; i++) { int l = 1, r = std::min(i, n + 1 - i); #define mid (l + r) / 2 #define Q(x, y) x(i - y, i + y - 1) while (l <= r) if (Q(mn, mid) <= Q(mx, mid)) r = mid - 1; else l = mid + 1; if (r) { if (a[i] < a[i + 1]) out[i] = l % 2 ? Q(mx, l) : Q(mn, l); else out[i] = l % 2 ? Q(mn, l) : Q(mx, l); } else out[i] = a[i]; ans = std::max(ans, r); } printf("%d\n", ans); for (int i = 1; i <= n; i++) printf("%d ", out[i]); } /* this was hard :( */
cpp
1141
F2
F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤15001≤n≤1500) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7 4 1 2 2 1 5 3 OutputCopy3 7 7 2 3 4 5 InputCopy11 -5 -4 -3 -2 -1 0 1 2 3 4 5 OutputCopy2 3 4 1 1 InputCopy4 1 1 1 1 OutputCopy4 4 4 1 1 2 2 3 3
[ "data structures", "greedy" ]
// LUOGU_RID: 101967713 #include <bits/stdc++.h> using i64 = long long; int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int n; std::cin >> n; std::vector<int> a(n); for (int i = 0; i < n; i++) { std::cin >> a[i]; } std::vector<int> s(n + 1); for (int i = 0; i < n; i++) { s[i + 1] = s[i] + a[i]; } std::map<int, std::vector<std::pair<int, int>>> rag; for (int i = 1; i <= n; i++) { for (int j = i; j <= n; j++) { rag[s[j] - s[i - 1]].emplace_back(j, i); } } std::vector<std::pair<int, int>> ans; for (auto [x, v] : rag) { std::sort(v.begin(), v.end()); int l = 0, r = 0; std::vector<std::pair<int, int>> res; for (auto p : v) { if (res.empty() || p.second > res.back().first) { res.emplace_back(p); } } if (res.size() > ans.size()) ans = res; } std::cout << ans.size() << "\n"; for (auto [r, l] : ans) { std::cout << l << " " << r << "\n"; } return 0; }
cpp
1316
F
F. Battalion Strengthtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn officers in the Army of Byteland. Each officer has some power associated with him. The power of the ii-th officer is denoted by pipi. As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these nn officers and calls this subset a battalion.(All 2n2n subsets of the nn officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be a1,a2,…,aka1,a2,…,ak, where a1≤a2≤⋯≤aka1≤a2≤⋯≤ak. The strength of this battalion is equal to a1a2+a2a3+⋯+ak−1aka1a2+a2a3+⋯+ak−1ak. (If the size of Battalion is ≤1≤1, then the strength of this battalion is 00).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be qq changes. Each one of the form ii xx indicating that pipi is changed to xx.You need to find the strength of the army initially and after each of these qq updates.Note that the changes are permanent.The strength should be found by modulo 109+7109+7. Formally, let M=109+7M=109+7. It can be shown that the answer can be expressed as an irreducible fraction p/qp/q, where pp and qq are integers and q≢0modMq≢0modM). Output the integer equal to p⋅q−1modMp⋅q−1modM. In other words, output such an integer xx that 0≤x<M0≤x<M and x⋅q≡pmodMx⋅q≡pmodM).InputThe first line of the input contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105)  — the number of officers in Byteland's Army.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤1091≤pi≤109).The third line contains a single integer qq (1≤q≤3⋅1051≤q≤3⋅105)  — the number of updates.Each of the next qq lines contains two integers ii and xx (1≤i≤n1≤i≤n, 1≤x≤1091≤x≤109), indicating that pipi is updated to xx .OutputIn the first line output the initial strength of the army.In ii-th of the next qq lines, output the strength of the army after ii-th update.ExamplesInputCopy2 1 2 2 1 2 2 1 OutputCopy500000004 1 500000004 InputCopy4 1 2 3 4 4 1 5 2 5 3 5 4 5 OutputCopy625000011 13 62500020 375000027 62500027 NoteIn first testcase; initially; there are four possible battalions {} Strength = 00 {11} Strength = 00 {22} Strength = 00 {1,21,2} Strength = 22 So strength of army is 0+0+0+240+0+0+24 = 1212After changing p1p1 to 22, strength of battallion {1,21,2} changes to 44, so strength of army becomes 11.After changing p2p2 to 11, strength of battalion {1,21,2} again becomes 22, so strength of army becomes 1212.
[ "data structures", "divide and conquer", "probabilities" ]
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <ctype.h> #include <queue> #include <cstring> #include <set> #include <bitset> #include <map> #include <chrono> #include <random> #include <unordered_map> #include <stdio.h> using namespace std; typedef long long ll; typedef long double ld; typedef std::vector<int> vi; typedef std::vector<bool> vb; typedef std::vector<string> vs; typedef std::vector<double> vd; typedef std::vector<long long> vll; typedef std::vector<std::vector<int> > vvi; typedef vector<vll> vvll; typedef std::vector<std::pair<int, int> > vpi; typedef vector<vpi> vvpi; typedef std::pair<int, int> pi; typedef std::pair<ll, ll> pll; typedef std::vector<pll> vpll; const long long mod = 1000000007; ll gcd (ll a, ll b) {return b==0 ? a : gcd(b, a%b);} const unsigned gen_seed = std::chrono::system_clock::now().time_since_epoch().count(); std::mt19937_64 gen(gen_seed); #define all(c) (c).begin(),(c).end() #define srt(c) sort(all(c)) #define srtrev(c) sort(all(c)); reverse(all(c)) #define forn(i, a, b) for(int i = a; i < b; i++) #define read(x) scanf("%d", &x) #define readv(x, n) vi x(n); forn(i,0,n) scanf("%d", &x[i]) #define pb push_back #define mp make_pair static struct FastInput { static constexpr int BUF_SIZE = 1 << 20; char buf[BUF_SIZE]; size_t chars_read = 0; size_t buf_pos = 0; FILE *in = stdin; char cur = 0; inline char get_char() { if (buf_pos >= chars_read) { chars_read = fread(buf, 1, BUF_SIZE, in); buf_pos = 0; buf[0] = (chars_read == 0 ? -1 : buf[0]); } return cur = buf[buf_pos++]; } inline void tie(int) {} inline explicit operator bool() { return cur != -1; } inline static bool is_blank(char c) { return c <= ' '; } inline bool skip_blanks() { while (is_blank(cur) && cur != -1) { get_char(); } return cur != -1; } inline FastInput& operator>>(char& c) { skip_blanks(); c = cur; return *this; } inline FastInput& operator>>(string& s) { if (skip_blanks()) { s.clear(); do { s += cur; } while (!is_blank(get_char())); } return *this; } template <typename T> inline FastInput& read_integer(T& n) { // unsafe, doesn't check that characters are actually digits n = 0; if (skip_blanks()) { int sign = +1; if (cur == '-') { sign = -1; get_char(); } do { n += n + (n << 3) + cur - '0'; } while (!is_blank(get_char())); n *= sign; } return *this; } template <typename T> inline typename enable_if<is_integral<T>::value, FastInput&>::type operator>>(T& n) { return read_integer(n); } #if !defined(_WIN32) || defined(_WIN64) inline FastInput& operator>>(__int128& n) { return read_integer(n); } #endif template <typename T> inline typename enable_if<is_floating_point<T>::value, FastInput&>::type operator>>(T& n) { // not sure if really fast, for compatibility only n = 0; if (skip_blanks()) { string s; (*this) >> s; sscanf(s.c_str(), "%lf", &n); } return *this; } } fast_input; #define cin fast_input static struct FastOutput { static constexpr int BUF_SIZE = 1 << 20; char buf[BUF_SIZE]; size_t buf_pos = 0; static constexpr int TMP_SIZE = 1 << 20; char tmp[TMP_SIZE]; FILE *out = stdout; inline void put_char(char c) { buf[buf_pos++] = c; if (buf_pos == BUF_SIZE) { fwrite(buf, 1, buf_pos, out); buf_pos = 0; } } ~FastOutput() { fwrite(buf, 1, buf_pos, out); } inline FastOutput& operator<<(char c) { put_char(c); return *this; } inline FastOutput& operator<<(const char* s) { while (*s) { put_char(*s++); } return *this; } inline FastOutput& operator<<(const string& s) { for (int i = 0; i < (int) s.size(); i++) { put_char(s[i]); } return *this; } template <typename T> inline char* integer_to_string(T n) { // beware of TMP_SIZE char* p = tmp + TMP_SIZE - 1; if (n == 0) { *--p = '0'; } else { bool is_negative = false; if (n < 0) { is_negative = true; n = -n; } while (n > 0) { *--p = (char) ('0' + n % 10); n /= 10; } if (is_negative) { *--p = '-'; } } return p; } template <typename T> inline typename enable_if<is_integral<T>::value, char*>::type stringify(T n) { return integer_to_string(n); } #if !defined(_WIN32) || defined(_WIN64) inline char* stringify(__int128 n) { return integer_to_string(n); } #endif template <typename T> inline typename enable_if<is_floating_point<T>::value, char*>::type stringify(T n) { sprintf(tmp, "%.17f", n); return tmp; } template <typename T> inline FastOutput& operator<<(const T& n) { auto p = stringify(n); for (; *p != 0; p++) { put_char(*p); } return *this; } } fast_output; #define cout fast_output class CoordinateCompressor { public: vpi xc; vpi xx; inline void add(pi x) { xx.pb(x); } void init() { xc.clear(); srt(xx); forn(i,0,xx.size()) if(i==0 || xx[i] != xx[i-1]) xc.pb(xx[i]); } inline int comp(const pi x) { return lower_bound(all(xc), x) - xc.begin(); } inline int len() { return xc.size(); } }; template <typename T> class fenwick { public: vector<T> fenw; int n; fenwick(int _n) : n(_n) { fenw.resize(n); } void modify(int x, T v) { while (x < n) { fenw[x] += v; x |= (x + 1); } } T get(int x) { T v{}; while (x >= 0) { v += fenw[x]; x = (x & (x + 1)) - 1; } return v; } T get(int l, int r) { T ret = get(r); if (l>0) ret -= get(l-1); return ret; } }; class stree { public: vll t; vll pp; void build (int n, int v, int tl, int tr) { t.resize(n * 4); pp = vll(n*4,1); } void push(int v, int tl, int tr) { if(pp[v] == 1) return; t[v] = t[v] * pp[v] % mod; if(tl != tr) { pp[2*v] = pp[v*2]*pp[v]%mod; pp[2*v+1] = pp[v*2+1]*pp[v]%mod; } pp[v] = 1; } void update (int v, int tl, int tr, int l, int r, ll val) { if (l == tl && tr == r) { pp[v] = pp[v]*val%mod; push(v,tl,tr); return; } if (l > r) { push(v, tl, tr); return; } else { push(v,tl,tr); int tm = (tl + tr) / 2; update (v*2, tl, tm, l, min(r,tm), val); update (v*2+1, tm+1, tr, max(l,tm+1), r, val); t[v] = (t[v*2] + t[v*2+1])%mod; } } void set (int v, int tl, int tr, int pos, ll val) { if (pos == tl && tr == pos) { pp[v] = 1; t[v] = val; return; } if (pos < tl || pos > tr) { push(v, tl, tr); return; } else { push(v,tl,tr); int tm = (tl + tr) / 2; set (v*2, tl, tm, pos, val); set (v*2+1, tm+1, tr, pos, val); t[v] = (t[v*2] + t[v*2+1])%mod; } } ll get (int v, int tl, int tr, int l, int r) { push(v, tl, tr); if (l>r) return 0; if (tl ==l && r== tr) return t[v]; int tm = (tl + tr) / 2; ll ret = (get(v*2, tl, tm, l, min(r,tm)) + get(v*2+1, tm+1, tr, max(l,tm+1), r)) % mod; t[v] = (t[v*2] + t[v*2+1])%mod; return ret; } }; CoordinateCompressor comp; ll cur = 0; stree stl, str; fenwick<int> fen(0); int m; const int A = 300500; ll d2[A]; ll di2[A]; const ll i2 = (mod+1)/2; const ll i4 = i2*i2%mod; const ll i8 = i2*i4%mod; void add(int pos, ll val) { int numl = fen.get(0, pos); ll kl = stl.get(1, 0, m-1, pos, m-1)*d2[numl]%mod; cur = (cur + kl*i4%mod*val)%mod; stl.update(1, 0, m-1, pos, m-1, i2); stl.set(1, 0, m-1, pos, val*di2[numl]%mod); int numr = fen.get(pos, m-1); ll kr = str.get(1, 0, m-1, 0 ,pos)*d2[numr]%mod; cur = (cur + kr*i4%mod*val)%mod; str.update(1, 0, m-1, 0, pos, i2); str.set(1, 0, m-1, pos, val*di2[numr]%mod); fen.modify(pos, 1); cur = (cur + mod - kl*kr%mod*i8%mod)%mod; } void rem(int pos, ll val) { fen.modify(pos, -1); int numl = fen.get(0, pos); stl.set(1, 0, m-1, pos, 0); stl.update(1, 0, m-1, pos, m-1, 2); ll kl = stl.get(1, 0, m-1, pos, m-1)*d2[numl]%mod; cur = (cur + mod - kl*i4%mod*val%mod)%mod; int numr = fen.get(pos, m-1); str.set(1, 0, m-1, pos, 0); str.update(1, 0, m-1, 0, pos, 2); ll kr = str.get(1, 0, m-1, 0 ,pos)*d2[numr]%mod; cur = (cur + mod - kr*i4%mod*val%mod)%mod; cur = (cur + mod + kl*kr%mod*i8%mod)%mod; } int main() { #ifdef LOCAL freopen("input.txt", "rt", stdin); freopen("output.txt", "wt", stdout); #endif d2[0] = 1; di2[0] = 1; forn(i,1,A) { d2[i] = d2[i-1] * 2 % mod; di2[i] = di2[i-1] * (mod+1)/2 % mod; } int n; cin>>n; vi a(n); forn(i,0,n) { cin >> a[i]; comp.add(mp(a[i], i)); } int qn; cin>>qn; vi qi(qn), qto(qn); forn(i,0,qn) { cin>>qi[i]>>qto[i]; qi[i]--; comp.add(mp(qto[i], qi[i])); } comp.init(); m = comp.len(); stl.build(m, 1, 0, m-1); str.build(m, 1, 0, m-1); fen = fenwick<int>(m); forn(i,0,n) { int pos = comp.comp(mp(a[i], i)); add(pos, a[i]); } cout<<cur<<'\n'; forn(it,0,qn) { int i = qi[it]; int to = qto[it]; int pos = comp.comp(mp(a[i], i)); rem(pos, a[i]); a[i] = to; pos = comp.comp(mp(a[i], i)); add(pos, a[i]); cout<<cur<<'\n'; } }
cpp
1295
C
C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3 aabce ace abacaba aax ty yyt OutputCopy1 -1 3
[ "dp", "greedy", "strings" ]
#include <bits/stdc++.h> #define REP(i,n) for(int i = 0; i< (n);i++) #define all(x) (x).begin(), (x).end() #define f first #define s second #define SZ(a) (int)a.size() #define bit(x,i)(((x)>>(i))&1) typedef long long ll; using namespace std; // Graph problem void solve(){ string s, t; cin >> s >> t; int n1 = SZ(s), n2 = SZ(t); vector<int> G[26]; for(int i = 0; i < n1; ++i){ G[s[i] - 'a'].push_back(i); } int cur = -1, ans = 0; for(int i = 0; i < n2;){ ans++; if(SZ(G[t[i] - 'a']) == 0){ cout << -1 << endl; return; } while(i < n2){ if(SZ(G[t[i] - 'a']) == 0){ cout << -1 << endl; return; } auto it = upper_bound(all(G[t[i] - 'a']), cur); if(it == G[t[i] - 'a'].end()){ cur= -1; break; } i++; cur = *it; } } cout << ans << endl; } int main() { ios::sync_with_stdio(false); cin.tie(0); int tt; cin >> tt; while(tt--){ solve(); } }
cpp