contest_id
stringclasses
33 values
problem_id
stringclasses
14 values
statement
stringclasses
181 values
tags
listlengths
1
8
code
stringlengths
21
64.5k
language
stringclasses
3 values
1304
B
B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3 tab one bat OutputCopy6 tabbat InputCopy4 2 oo ox xo xx OutputCopy6 oxxxxo InputCopy3 5 hello codef orces OutputCopy0 InputCopy9 4 abab baba abcd bcde cdef defg wxyz zyxw ijji OutputCopy20 ababwxyzijjizyxwbaba NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string.
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
//MD SHARIQUE HUSSAIN 2112015 #include <iostream> #include <math.h> #include <vector> #include <map> #include <set> #include<iomanip> #include<algorithm> #include<utility> #include<set> #include<unordered_set> #include<list> #include<iterator> #include<deque> #include<queue> #include<stack> #include<bitset> #include<random> #include<stdio.h> #include<complex> #include<cstring> #include<chrono> #include<string> #include <unordered_map> //header file ended using namespace std; #define INF 1e18 #define pb push_back #define pll pair <ll,ll> #define ppb pop_back #define mp make_pair #define ff first #define ss second #define mod1 1000000007 #define mod2 998244353 #define PI 3.141592653589793238462 #define vch vector<char> #define vll vector<ll> #define vbb vector<bool> #define vst vector<string> #define mll map<ll,ll> #define mcl map<char,ll> #define mlc map<ll,char> #define msl map<string,ll> #define si set<int> #define usi unordered_set<int> #define msi multiset<int> #define pqsmall priority_queue <ll,vll,greater<ll> > #define pqlarge priority_queue <ll> #define nl '\n' typedef long long ll; typedef unsigned long long ull; typedef long double lld; #define all(x) (x).begin(), (x).end() //--------------------------------------------------------------//// nCr starts ////--------------------------------------------------------------- ll powerM(ll a,ll b,ll m){ll res = 1;while(b){if(b & 1){res = (res * a) % m;}a = (a * a) % m;b >>= 1;}return res;} ll modInverse(ll a , ll m){return powerM(a , m - 2 , m);} ll nCrModPFermat(ll n , ll r , ll p){if(r == 0){return 1;}ll fac[n + 1];fac[0] = 1;for(ll 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;} //--------------------------------------------------------------//// nCr ends ////----------------------------------------------------------------- bool cmp(pair<ll,ll> a,pair<ll,ll> b){if (a.ff!=b.ff){return a.ff>b.ff;}else{return a.ss<b.ss;}} int gcd(int a, int b){return b == 0 ? a : gcd(b, a % b);} ll power(ll a,ll n){ll ct=0;if (!(a%n)){while (a%n==0){a/=n;ct++;}}return ct;} int computeXOR(int n){if (n % 4 == 0)return n;if (n % 4 == 1)return 1;if (n % 4 == 2)return n + 1;return 0;} void seive1(bool vb[],ll n) {vb[0]=vb[1]=1;for(int i=2;(i*i)<n;i++){if (vb[i]==0){for (int j = i*i; j < n; j+=i){vb[j]=1;}}}} ll celi(ll a,ll b){return (a+b-1)/b;} ll modulas(ll i,ll m){return ((i%m)+m)%m;} ll flor(ll a,ll b){return (a)/b;} ll moduler_expo(ll a,ll n,ll m){ll x=1,pow=a%m;while (n){if (n&1){x=(x*pow)%m;}pow=(pow*pow)%m;n=n>>1;}return x;} void fact(ll n,vector<pll> &vp1){for(ll i=2;i*i<=n;i++){if(n%i==0){ll ct=0;while (n%i==0){ct++;n/=i;}vp1.pb(mp(i,ct));}}if(n>1)vp1.pb(mp(n,1));} ll multi_inv(ll r1,ll r2){ll q,r,t1=0,t2=1,t,m=r1;while (r2 > 0){q=r1/r2;r=r1%r2;t=1-(q*t2);r1=r2;r2=r;t1=t2;t2=t;}if (t1<0){ll a=abs(t1/m);a++;a=a*m;t1=a+t1;}return t1;} #define rsort(a) sort(a, a + n, greater<int>()) #define rvsort(a) sort(all(a), greater<int>()) #define FOR(i, a, b) for (auto i = a; i < b; i++) #define rFOR(a, b) for (auto i = a; i >= b; i--) #define read(a , n) for(int i = 0 ; i < n ; i ++){cin >> a[i];} const ll N=1e7; void sol() { ll n,m,one_time=0,single=0;cin>>n>>m; map <ll ,pair<bool,string> > m1; string s1="",s2="",s3="",s4=""; FOR(i,0,n) { cin>>m1[i].second; m1[i].ff=1; } auto it1=m1.begin(); for(;it1!=m1.end();it1++) { if(it1->second.ss.size()==1) { single=1; s4=it1->second.second; } auto it2=it1; it2++; if(it1->second.ff==1) { for(;it2!=m1.end();it2++) { if(it2->second.ff==1) { string temp1=it1->second.second,temp2=it2->second.second; reverse(all(temp2)); if(temp1==temp2) { it1->second.ff=0; it2->second.ff=0; s1+=temp1; s2+=temp1; } } } } if(it1->second.ff==1 && one_time==0) { string temp=it1->second.second; FOR(i,0,m/2) { if(temp[i]==temp[m-i-1]) { it1->second.ff=0; } else { it1->second.ff=1; break; } } if(it1->second.ff==0) { one_time++; s3+=temp; } } } reverse(all(s2)); s1+=s3; s1+=s2; if(s1.size()>0) { cout<<s1.size()<<'\n'; cout<<s1<<'\n'; } else { cout<<s4.size()<<'\n'; cout<<s4<<'\n'; } } int32_t main() { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w", stdout); #endif ios_base::sync_with_stdio(0); cin.tie(0); // int t; // cin>>t; // while(t--) { sol(); } return 0; }
cpp
1294
D
D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3 0 1 2 2 0 0 10 OutputCopy1 2 3 3 4 4 7 InputCopy4 3 1 2 1 2 OutputCopy0 0 0 0 NoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7, a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77.
[ "data structures", "greedy", "implementation", "math" ]
#include<bits/stdc++.h> #define eps 1e-9 #define emailam ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define endl '\n' #define ll long long #define ull unsigned long long #define MAX 200010 #define pb push_back #define all(a) a.begin(),a.end() #define pf push_front #define fi first #define se second #define pii pair<int,int> const int INF = INT_MAX; using namespace std; const int N=4e5+10,M=10; const int mod=1e9+7; #define int long long /*----------------------------------------------------------------*/ int dx[] = {+0, +0, -1, +1, +1, +1, -1, -1}; int dy[] = {-1, +1, +0, +0, +1, -1, +1, -1}; /*----------------------------------------------------------------*/ void READ(){ #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout); #endif } set<int>mex; void buildmex(){ for(int i=0;i<N;i++){ mex.insert(i); } } void solve(){ buildmex(); int q,x; cin>>q>>x; map<int,int>frq; while(q--){ int n; cin>>n; frq[n%x]++; int k=*mex.begin(); while(frq[k%x]){ frq[k%x]--; mex.erase(k); k=*mex.begin(); } cout<<k<<endl; } } signed main() { emailam //READ(); int t=1; //cin>>t; while(t--){ solve(); } }
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> #define int long long #define MOD 1000000007 #define all(x) x.begin(),x.end() #define ff first #define ss second #define pb push_back using namespace std; int32_t main(){ int t; cin>>t; while(t--){ int n,m; cin>>n; int a[n]; for(int i=0;i<n;i++)cin>>a[i]; sort(a,a+n); int b[n]; for(int i=0;i<n;i++)cin>>b[i]; 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
1320
A
A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6 10 7 1 9 10 15 OutputCopy26 InputCopy1 400000 OutputCopy400000 InputCopy7 8 9 26 11 12 29 14 OutputCopy55 NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].
[ "data structures", "dp", "greedy", "math", "sortings" ]
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <functional> using namespace std; using namespace __gnu_pbds; typedef tree<int, null_type, less_equal<int>, rb_tree_tag,tree_order_statistics_node_update> ordered_multiset; typedef tree<int, null_type, less<int>, rb_tree_tag,tree_order_statistics_node_update> ordered_set; #define ll long long int #define forn(i, n) for (int i = 0; i < int(n); i++) #define cin(arr,n) for(int i=0; i<n;i++){cin>>arr[i];} #define endl "\n" #define cin1(vec,n) forn(i,n){ll x;cin>>x;vec.push_back(x);} int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); map<ll,ll>mp; ll n; cin>>n; ll arr[n+1]; for(int i=1;i<=n;i++){ cin>>arr[i]; mp[arr[i]-i]+=arr[i]; } ll ans=0; for(auto it:mp){ ans=max(ans,it.second); } cout<<ans<<endl; 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" ]
// LUOGU_RID: 99917153 #include <deque> #include <cstdio> #include <cstring> #include <algorithm> using std :: swap;using std :: min; namespace nagisa{ const int maxn = 55,maxm = 2505,inf = 0x3f3f3f3f; int n,m,q,ans[maxn],F; struct MCMF{ int head[maxn],tot;MCMF(){tot = 1;} struct Edge{int next,to,cap,val;}e[maxm<<1]; void ade(int x,int y,int z,int w){ e[++tot] = (Edge){head[x],y,z,w},head[x] = tot; e[++tot] = (Edge){head[y],x,0,-w},head[y] = tot; } int dis[maxn],vis[maxn],pre[maxn],eid[maxn]; bool spfa(){ std :: deque <int> q;memset(dis,0x3f,sizeof(dis)); dis[1] = 0,vis[1] = 1,q.push_back(1); #define SWAP if(q.size()>=2&&dis[q.front()]>dis[q.back()])swap(q.front(),q.back()) while(!q.empty()){ int u = q.front();q.pop_front(),vis[u] = 0;SWAP; for(int i=head[u],v;v=e[i].to,i;i=e[i].next){ if(e[i].cap && dis[v] > dis[u] + e[i].val){ dis[v] = dis[u] + e[i].val,pre[v] = u,eid[v] = i; if(!vis[v]){vis[v] = 1;q.empty()||dis[q.front()]<dis[v]?q.push_front(v):q.push_back(v);SWAP;} } } }return dis[n]!=inf; } void gans(){ while(spfa()){ int p = n;for(;p^1;p=pre[p])e[eid[p]].cap = 0,e[eid[p]^1].cap = 1; ans[F+1] = ans[F] + dis[n],++F; } } }G; int main(){ scanf("%d %d",&n,&m); for(int i=1,x,y,z;i<=m;++i)scanf("%d %d %d",&x,&y,&z),G.ade(x,y,1,z); G.gans(),scanf("%d",&q); for(int i=1,x;i<=q;++i){ double t = 1e18;scanf("%d",&x); for(int j=1;j<=F;++j)t = min(t,1.*(x+ans[j])/j);printf("%.10lf\n",t); } return 0; } } int main(){return nagisa::main();}
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" ]
#include <cstdio> #include <vector> #include <algorithm> const int INF=1e9+7; int N; int as[200005]; std::vector<int> edges[200005]; int dist[2][200005]; int q[200005]; void bfs(int* dist,int s){ std::fill(dist,dist+N,INF); int qh=0,qt=0; q[qh++]=s; dist[s]=0; while(qt<qh){ int x=q[qt++]; for(int y:edges[x]){ if(dist[y]==INF){ dist[y]=dist[x]+1; q[qh++]=y; } } } } int main(){ int M,K; scanf("%d %d %d",&N,&M,&K); for(int i=0;i<K;i++){ scanf("%d",&as[i]); as[i]--; } std::sort(as,as+K); for(int i=0;i<M;i++){ int X,Y; scanf("%d %d",&X,&Y); X--,Y--; edges[X].push_back(Y); edges[Y].push_back(X); } bfs(dist[0],0); bfs(dist[1],N-1); std::vector<std::pair<int,int> > data; for(int i=0;i<K;i++){ data.emplace_back(dist[0][as[i]]-dist[1][as[i]],as[i]); } std::sort(data.begin(),data.end()); int best=0; int max=-INF; for(auto it:data){ int a=it.second; best=std::max(best,max+dist[1][a]); max=std::max(max,dist[0][a]); } printf("%d\n",std::min(dist[0][N-1],best+1)); }
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" using namespace std; #define ll long long string query(int l, int r) { cout << "? " << l << " " << r << "\n"; cout.flush(); int n = r - l + 1; vector<vector<int>> a(n + 1, vector<int>(26)); for (int i = 0; i < (n * (n + 1)) / 2; i++) { string curr; cin >> curr; for (char c : curr) { a[curr.size()][c - 'a']++; } } string cv(n, '?'); if (n == 2) { int ind = 0; for (int i = 0; i < a[n].size(); i++) { while (a[n][i]) { cv[ind++] = 'a' + i; a[n][i]--; } } return cv; } vector<pair<char,int>> sf; for (int i = 0; i < n - i - 1; i++) { int cc = i + 2; for (auto [c, x] : sf) { a[cc][c - 'a'] += (cc - x - 1); } for (int j = 0; j < a[cc].size(); j++) { if (a[cc][j] < a[n][j] * cc) { if (cv[i] == '?') cv[i] = 'a' + j; else cv[n - i - 1] = 'a' + j; sf.push_back({'a' + j, i}); a[cc][j]++; j--; } } } if (n % 2) { for (auto [c, x] : sf) { a[n][c - 'a']--; } for (int i = 0; i < a[n].size(); i++) { if (a[n][i]) { cv[n / 2] = 'a' + i; break; } } assert(cv[n / 2] != '?'); } return cv; } char diff(string a, string b) { vector<int> fr(26); for (char c : a) fr[c - 'a']++; for (char c : b) fr[c - 'a']--; for (int i = 0; i < fr.size(); i++) { if (fr[i] != 0) { return 'a' + i; } } return 0; } char other(char x, char y, char z) { if (y == x) return z; return y; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; if (n <= 3) { string ans = ""; for (int i = 1; i <= n; i++) { ans += query(i, i); } cout << "! " << ans << "\n"; cout.flush(); return 0; } int fs = (n + 1) / 2; string fp = query(1, fs); string sp = query(2, fs); string av = query(1, n); string ans(n, '?'); ans[0] = diff(fp, sp); int l = 1, r = fs - 1; while (l <= r) { ans[r] = other(ans[l - 1], fp[r], fp[fs - r - 1]); int ind = r - 1; ans[l] = other(ans[r], sp[ind], sp[fs - ind - 2]); l++; r--; } for (int i = 0; i < n; i++) { int oi = (n - i - 1); if (i >= oi) break; ans[oi] = other(ans[i], av[i], av[oi]); } cout << "! " << ans << "\n"; } // ~ BucketPotato
cpp
1307
E
E. Cow and Treatstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful year of milk production; Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of nn units of grass, each with a sweetness sisi. Farmer John has mm cows, each with a favorite sweetness fifi and a hunger value hihi. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner: The cows from the left and right side will take turns feeding in an order decided by Farmer John. When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats hihi units. The moment a cow eats hihi units, it will fall asleep there, preventing further cows from passing it from both directions. If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset. Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them. Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo 109+7109+7)? The order in which FJ sends the cows does not matter as long as no cows get upset. InputThe first line contains two integers nn and mm (1≤n≤50001≤n≤5000, 1≤m≤50001≤m≤5000)  — the number of units of grass and the number of cows. The second line contains nn integers s1,s2,…,sns1,s2,…,sn (1≤si≤n1≤si≤n)  — the sweetness values of the grass.The ii-th of the following mm lines contains two integers fifi and hihi (1≤fi,hi≤n1≤fi,hi≤n)  — the favorite sweetness and hunger value of the ii-th cow. No two cows have the same hunger and favorite sweetness simultaneously.OutputOutput two integers  — the maximum number of sleeping cows that can result and the number of ways modulo 109+7109+7. ExamplesInputCopy5 2 1 1 1 1 1 1 2 1 3 OutputCopy2 2 InputCopy5 2 1 1 1 1 1 1 2 1 4 OutputCopy1 4 InputCopy3 2 2 3 2 3 1 2 1 OutputCopy2 4 InputCopy5 1 1 1 1 1 1 2 5 OutputCopy0 1 NoteIn the first example; FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 22 is lined up on the left side and cow 11 is lined up on the right side. In the second example, FJ can line up the cows as follows to achieve 11 sleeping cow: Cow 11 is lined up on the left side. Cow 22 is lined up on the left side. Cow 11 is lined up on the right side. Cow 22 is lined up on the right side. In the third example, FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 and 22 are lined up on the left side. Cow 11 and 22 are lined up on the right side. Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 11 is lined up on the right side and cow 22 is lined up on the left side. In the fourth example, FJ cannot end up with any sleeping cows, so there will be no cows lined up on either side.
[ "binary search", "combinatorics", "dp", "greedy", "implementation", "math" ]
#include<bits/stdc++.h> #define Mx 5000 #define LL long long #define mod 1000000007 using namespace std; int n,m; bool ok; int s[5002],l[5002],r[5002]; LL fac[5002],inv[5002]; vector<int> pos[5002]; vector<int> vec[2][5002]; struct aaa { int mx; LL cnt; }tmp={0,1},ans; inline void upd(aaa &a,aaa b) { if(a.mx<b.mx)swap(a,b); if(a.mx==b.mx && (a.cnt+=b.cnt)>=mod)a.cnt-=mod; } inline LL Pow(LL a,int b) { if(!b)return 1; if(b==1)return a; LL c=Pow(a,(b>>1)); c=(c*c)%mod; if(b&1)c=(c*a)%mod; return c; } inline void calc(int x,int y,int o) { if(x>y)swap(x,y); if(!x && !y); else if(!x)tmp.mx+=o,(tmp.cnt*=(~o? y:inv[y]))%=mod; else if(x==1 && y==1)tmp.mx+=o,(tmp.cnt*=(~o? 2:inv[2]))%=mod; else tmp.mx+=o*2,(tmp.cnt*=(~o? x*(y-1):inv[x]*inv[y-1])%mod)%=mod; } inline void init() { fac[0]=1;for(int i=1;i<=Mx;++i)fac[i]=(fac[i-1]*i)%mod; inv[Mx]=Pow(fac[Mx],mod-2);for(int i=Mx;i;--i)inv[i-1]=(inv[i]*i)%mod,(inv[i]*=fac[i-1])%=mod; } int main() { init(),scanf("%d%d",&n,&m); for(int i=1;i<=n;++i)scanf("%d",&s[i]),pos[s[i]].push_back(i); for(int i=1,x,y;i<=m;++i) { scanf("%d%d",&x,&y); if(y>pos[x].size())continue; ++r[x],vec[0][pos[x][y-1]].push_back(x),vec[1][pos[x][pos[x].size()-y]].push_back(x); } for(int i=1;i<=n;++i)calc(l[i],r[i],1); ans=tmp,++tmp.mx; for(int i=1,x;i<=n;++i) { ok=0; for(int j=0;j<vec[0][i].size();++j)x=vec[0][i][j],calc(l[x],r[x],-1),++l[x],calc(l[x],r[x],1),ok|=(x==s[i]); for(int j=0;j<vec[1][i].size();++j)x=vec[1][i][j],calc(l[x],r[x],-1),--r[x],calc(l[x],r[x],1); if(ok)calc(l[s[i]],r[s[i]],-1),calc(0,r[s[i]]-(l[s[i]]<=r[s[i]]),1),upd(ans,tmp),calc(0,r[s[i]]-(l[s[i]]<=r[s[i]]),-1),calc(l[s[i]],r[s[i]],1); } return 0&printf("%d %lld",ans.mx,(ans.cnt+mod)%mod); }
cpp
1307
E
E. Cow and Treatstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful year of milk production; Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of nn units of grass, each with a sweetness sisi. Farmer John has mm cows, each with a favorite sweetness fifi and a hunger value hihi. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner: The cows from the left and right side will take turns feeding in an order decided by Farmer John. When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats hihi units. The moment a cow eats hihi units, it will fall asleep there, preventing further cows from passing it from both directions. If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset. Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them. Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo 109+7109+7)? The order in which FJ sends the cows does not matter as long as no cows get upset. InputThe first line contains two integers nn and mm (1≤n≤50001≤n≤5000, 1≤m≤50001≤m≤5000)  — the number of units of grass and the number of cows. The second line contains nn integers s1,s2,…,sns1,s2,…,sn (1≤si≤n1≤si≤n)  — the sweetness values of the grass.The ii-th of the following mm lines contains two integers fifi and hihi (1≤fi,hi≤n1≤fi,hi≤n)  — the favorite sweetness and hunger value of the ii-th cow. No two cows have the same hunger and favorite sweetness simultaneously.OutputOutput two integers  — the maximum number of sleeping cows that can result and the number of ways modulo 109+7109+7. ExamplesInputCopy5 2 1 1 1 1 1 1 2 1 3 OutputCopy2 2 InputCopy5 2 1 1 1 1 1 1 2 1 4 OutputCopy1 4 InputCopy3 2 2 3 2 3 1 2 1 OutputCopy2 4 InputCopy5 1 1 1 1 1 1 2 5 OutputCopy0 1 NoteIn the first example; FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 22 is lined up on the left side and cow 11 is lined up on the right side. In the second example, FJ can line up the cows as follows to achieve 11 sleeping cow: Cow 11 is lined up on the left side. Cow 22 is lined up on the left side. Cow 11 is lined up on the right side. Cow 22 is lined up on the right side. In the third example, FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 and 22 are lined up on the left side. Cow 11 and 22 are lined up on the right side. Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 11 is lined up on the right side and cow 22 is lined up on the left side. In the fourth example, FJ cannot end up with any sleeping cows, so there will be no cows lined up on either side.
[ "binary search", "combinatorics", "dp", "greedy", "implementation", "math" ]
#ifndef _GLIBCXX_NO_ASSERT #include <cassert> #endif #include <cctype> #include <cerrno> #include <cfloat> #include <ciso646> #include <climits> #include <clocale> #include <cmath> #include <csetjmp> #include <csignal> #include <cstdarg> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #if __cplusplus >= 201103L #include <ccomplex> #include <cfenv> #include <cinttypes> //#include <cstdalign> #include <cstdbool> #include <cstdint> #include <ctgmath> #include <cwchar> #include <cwctype> #endif // C++ #include <algorithm> #include <bitset> #include <complex> #include <deque> #include <exception> #include <fstream> #include <functional> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <iterator> #include <limits> #include <list> #include <locale> #include <map> #include <memory> #include <new> #include <numeric> #include <ostream> #include <queue> #include <set> #include <sstream> #include <stack> #include <stdexcept> #include <streambuf> #include <string> #include <typeinfo> #include <utility> #include <valarray> #include <vector> #if __cplusplus >= 201103L #include <array> #include <atomic> #include <chrono> #include <condition_variable> #include <forward_list> #include <future> #include <initializer_list> #include <mutex> #include <random> #include <ratio> #include <regex> #include <scoped_allocator> #include <system_error> #include <thread> #include <tuple> #include <typeindex> #include <type_traits> #include <unordered_map> #include <unordered_set> #endif using namespace std; using i64 = long long; using i128 = __int128; #define MAXN 5005 #define MAXM 5005 #define M 1000000 #define K 17 #define MAXP 25 #define MAXK 55 #define MAXC 255 #define MAXERR 105 #define MAXLEN 105 #define MDIR 10 #define MAXR 705 #define BASE 102240 #define MAXA 28 #define MAXT 100005 #define LIMIT 86400 #define MAXV 305 #define LEQ 1 #define EQ 0 #define OP 0 #define CLO 1 #define DIG 1 #define C1 0 #define C2 1 #define PLUS 0 #define MINUS 1 #define MUL 2 #define CLO 1 #define VERT 1 //#define B 31 #define B2 1007 #define W 1 #define H 19 #define SPEC 1 #define MUL 2 #define CNT 3 #define ITER 1000 #define INF 1e9 #define EPS 1e9 #define MOD 1000000007 #define FACT 100000000000000 #define PI 3.14159265358979 #define SRC 0 typedef long long ll; typedef ll hash_t; typedef __int128_t lint; typedef long double ld; typedef pair<int,int> ii; typedef pair<double,int> ip; typedef pair<ll,ii> pl; typedef pair<int,ll> pll; typedef pair<ll,int> li; typedef pair<ll,ll> iv; typedef tuple<int,int,int> iii; typedef tuple<ll,ll,int> tll; typedef vector<vector<int>> vv; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<ii> vii; typedef vector<vector<ll>> vll; typedef complex<ld> cd; #define pb push_back #define eb emplace_back #define ins insert #define er erase #define sc second #define fr first #define repl(i,x,y) for (int i = (x); i <= (y); ++i) #define rep(i,x,y) for (int i = (x); i < (y); ++i) #define rev(i,x,y) for (int i = (x); i >= (y); --i) #define LSOne(S) (S & (-S)) #define trav(i,v) for (auto &i : v) #define foreach(it,v) for (auto it = begin(v); it != end(v); ++it) #define bend(v) (v).begin(), (v).end() #define rbend(v) (v).rbegin(), (v).rend() #define sortarr(v) sort(bend(v)) #define rsortarr(v) sort(rbend(v)) #define sz(v) (int)((v).size()) #define unique(v) v.erase(unique(v.begin(), v.end()), v.end()) #define combine(A,B) A.insert(end(A), bend(B)) template<class T> bool ckmin(T &a, T &b) { return a > b ? a = b, 1 : 0; }; template<class T> bool ckmax(T &a, T &b) { return a < b ? a = b, 1 : 0; }; template<class T> void amax(T &a, T b, T c) { a = max(b, c); }; template<class T> void amin(T &a, T b, T c) { a = min(b, c); }; template<class T> T getmax(vector<T> &v) { return *max_element(bend(v)); }; template<class T> T getmin(vector<T> &v) { return *min_element(bend(v)); }; template<class T> int compress(vector<T> &v, T &val) { return (int)(lower_bound(bend(v), val) - begin(v)); }; template<class T> auto vfind(vector<T> &v, T val) { return find(bend(v), val); } template<class T> auto verase(vector<T> &v, T val) { return v.er(vfind(v, val)); } int n,m; //candidate stores all possible cows with favourite jelly i vv cand, occ; int pos[MAXN]; //idea is to find an invariant(in this case rightmost point of the left queue and fix it) //now we want to count the number of cows in the left and right queue respectively //for all cows that likes the same jelly, 2 cows of the same type cannot both appear on the left of right queue but separately //calculate the number of ways to add the pair of cows to the left and right queue independently //only need to choose a subset so ordering of the cows do not matter int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> n >> m; vector<int> a(n); cand.resize(n), occ.resize(n); rep(i,0,n) { int x; cin >> x; x--; a[i] = x; occ[x].pb(i); } rep(i,0,m) { int f,h; cin >> f >> h; f--; if (h <= sz(occ[f])) cand[f].pb(h), pos[occ[f][h - 1]] = true; } pll ans = {0, 1}; //consider the case where we leave the left queue empty rep(i,0,n) { if (sz(cand[i]) > 0) ans.fr++, ans.sc = (1LL * ans.sc * sz(cand[i])) % MOD; } //fix the valid starting positions rep(i,0,n) { if (pos[i]) { pll tmp = {1, 1}; //calculate all possible ending points for cows that like the same candy int canrgt = 0; trav(j, cand[a[i]]) { if (occ[a[i]][sz(occ[a[i]]) - j] > i) { if (occ[a[i]][j - 1] != i) canrgt++; } } if (canrgt) tmp.fr++, tmp.sc = (tmp.sc * canrgt) % MOD; rep(j,0,n) { if (a[i] == j) continue; int cntlft = 0, cntrgt = 0, cntdup = 0; trav(k, cand[j]) { if (occ[j][k - 1] < i) cntlft++; if (occ[j][sz(occ[j]) - k] > i) cntrgt++; if (occ[j][k - 1] < i && occ[j][sz(occ[j]) - k] > i) cntdup++; } int c2 = cntlft * cntrgt - cntdup; int c1 = cntlft + cntrgt; if (c2) { //add this pair of cows to the left and right queues respectively tmp.fr += 2; tmp.sc = (tmp.sc * c2) % MOD; } else if (c1) { tmp.fr++; tmp.sc = (tmp.sc * c1) % MOD; } } if (tmp.fr > ans.fr) { ans = tmp; } else if (tmp.fr == ans.fr) ans.sc = (ans.sc + tmp.sc) % MOD; } } cout << ans.fr << ' ' << ans.sc; }
cpp
1284
D
D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai≤eaisai≤eai) and [sbi,ebi][sbi,ebi] (sbi≤ebisbi≤ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)≤min(y,v)max(x,u)≤min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1≤n≤1000001≤n≤100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1≤sai,eai,sbi,ebi≤1091≤sai,eai,sbi,ebi≤109, sai≤eai,sbi≤ebisai≤eai,sbi≤ebi).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2 1 2 3 6 3 4 7 8 OutputCopyYES InputCopy3 1 3 2 4 4 5 6 7 3 4 5 5 OutputCopyNO InputCopy6 1 5 2 9 2 4 5 8 3 6 7 11 7 10 12 16 8 11 13 17 9 12 14 18 OutputCopyYES NoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist.
[ "binary search", "data structures", "hashing", "sortings" ]
#include <bits/stdc++.h> using namespace std; #define dg(x) cout<<#x<<"="<<x<<endl using ll = long long; const int N = 1e5+5; int n,sa[N],sb[N],ea[N],eb[N]; pair<pair<int,int>,int> t[N<<1]; bool chk(){ for (int i=0; i<(n<<1); i+=2){ t[i]={{sa[i/2],0},i/2}; t[i+1]={{ea[i/2],1},i/2}; } sort(t,t+(n<<1)); multiset<int> s,e; for (int i=0; i<(n<<1); i++){ int I=t[i].second; if (t[i].first.second==0){ // s s.insert(sb[I]),e.insert(eb[I]); if ((*s.rbegin())>(*e.begin())){ return 0; } } else{ // e s.erase(s.find(sb[I])),e.erase(e.find(eb[I])); } } return 1; } int main(){ ios::sync_with_stdio(false); cin.tie(0); cin>>n; for (int i=0; i<n; i++){ cin>>sa[i]>>ea[i]>>sb[i]>>eb[i]; } if (!chk()){ cout<<"NO"<<endl; return 0; } swap(sa,sb),swap(ea,eb); if (!chk()){ cout<<"NO"<<endl; return 0; } else{ cout<<"YES"<<endl; } 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<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 10000000 // 1234567 void solve(){ ge(ll,t); xx(t){ ge(ll,s); ll use=0; while(s>=10){ ll extra=s%10; use+=s-extra; s=s/10+extra; } ff(use+s); } }
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: 101723561 #include<iostream> #include<algorithm> #include<cstring> #include<cstdio> #include<bitset> #include<random> #include<cmath> #include<ctime> #include<queue> #include<map> #include<set> #define int long long #define fi first #define se second #define max Max #define min Min #define abs Abs #define lc (x<<1) #define rc (x<<1|1) #define mid ((l+r)>>1) #define pb(x) push_back(x) #define lowbit(x) ((x)&(-(x))) #define fan(x) ((((x)-1)^1)+1) #define mp(x,y) make_pair(x,y) #define clr(f,n) memset(f,0,sizeof(int)*(n)) #define cpy(f,g,n) memcpy(f,g,sizeof(int)*(n)) #define SZ(x) ((int)(x.size())) #define INF 0x3f3f3f3f using namespace std; inline int read() { int ans=0,f=1; char c=getchar(); while(c>'9'||c<'0'){if(c=='-')f=-1;c=getchar();} while(c>='0'&&c<='9'){ans=(ans<<1)+(ans<<3)+c-'0';c=getchar();} return ans*f; } inline void write(int x) { if(x<0) putchar('-'),x=-x; if(x/10) write(x/10); putchar((char)(x%10)+'0'); } inline void Write(__int128 x) { if(x<0) putchar('-'),x=-x; if(x/10) Write(x/10); putchar((char)(x%10)+'0'); } template<typename T>inline T Abs(T a){return a>0?a:-a;}; template<typename T,typename TT>inline T Min(T a,TT b){return a<b?a:b;} template<typename T,typename TT> inline T Max(T a,TT b){return a<b?b:a;} const int N=1e6+5; int n,a[N],s[N],fa[N],up[N],top; char opt[5]; pair<int,int> st[N]; __int128 ans; inline int Q(int x) { int l=1,r=top,rs=-1; while(l<=r) { if(st[mid].se>=x) rs=st[mid].fi,r=mid-1; else l=mid+1; } return rs; } map<int,int> sum; signed main() { n=read();fa[0]=-1;s[0]=-1; int lastans1=0,lastans2=0,lst=0; for(int i=1;i<=n;++i) { scanf("%s",opt+1); int x=opt[1]-'a'; x=(x+lastans1)%26;s[i]=x; if(i!=1) { if(s[i]!=s[fa[i-1]+1]) up[i-1]=fa[i-1]; else up[i-1]=up[fa[i-1]]; } int w=read(),res=lst; w^=lastans2;a[i]=w;fa[i]=fa[i-1]; int u=i-1; while(u) { if(s[u+1]==s[i]) u=up[u]; else { int tmp=Q(i-u); sum[-tmp]--;res-=tmp; u=fa[u]; } } while(top&&st[top].fi>=a[i]) --top; st[++top]=mp(a[i],i);int nm=0; for(auto j=sum.begin();j!=sum.end();) { if(-j->fi<=a[i]) break; res-=(-j->fi-a[i])*j->se; nm+=j->se; auto tmp=j;++j;sum.erase(tmp); } if(nm) sum[-a[i]]+=nm; if(s[1]==s[i]) { sum[-a[i]]++; res+=a[i]; } while(fa[i]!=-1&&s[fa[i]+1]!=s[i]) fa[i]=fa[fa[i]]; fa[i]++; lst=res;ans+=res; lastans1=(lastans1+res)%26; lastans2=(lastans2+res)%(1<<30); Write(ans);puts(""); } return 0; }
cpp
1304
A
A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5 0 10 2 3 0 10 3 3 900000000 1000000000 1 9999999 1 2 1 1 1 3 1 1 OutputCopy2 -1 10 -1 1 NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.
[ "math" ]
#include<bits/stdc++.h> using namespace std; #define ll long long int main() { int t; cin>>t; while(t--) { ll x,y,a,b; cin>>x>>y>>a>>b; ll k,n; k=y-x; n=a+b; if((k<n)||(k%n!=0)) { cout<<"-1"<<endl; } else { cout<<k/n<<endl; } } return 0; }
cpp
1311
A
A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.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.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5 2 3 10 10 2 4 7 4 9 3 OutputCopy1 0 2 2 1 NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.
[ "greedy", "implementation", "math" ]
#include<bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while(t--){ int a,b,k=0; cin >> a >> b; if(a==b) cout << k << endl; else if(b>a){ k=b-a; if(k%2==0) cout << 2 << endl; else cout << 1 << endl; }else{ k=a-b; if(k%2==0) cout << 1 << endl; else cout << 2 << endl; } } }
cpp
1303
D
D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3 10 3 1 32 1 23 4 16 1 4 1 20 5 2 1 16 1 8 OutputCopy2 -1 0
[ "bitmasks", "greedy" ]
#include <bits/stdc++.h> #define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0); #define xs(a) cout<<setiosflags(ios::fixed)<<setprecision(a); #define lbit(a) (__builtin_ffsll(a)) #define ubit(a) (64-__builtin_clzll(a)) #define FOR(i, a, b) for (ll (i) = (a); (i) <= (b); (i)++) #define ROF(i, a, b) for (ll (i) = (a); (i) >= (b); (i)--) #define mem(a,b) memset(a,b,sizeof(a)); using namespace std; #define ull unsigned long long #define ll long long #define endl '\n' typedef pair<ll,ll> pll; const int N=1e6+5; const int mod=1e9+7; /*-----------------------------------------------------------------------------------------------*/ void solve(){ ll n,m;cin>>n>>m; ll tot=0; priority_queue<ll>q; FOR(i,1,m){ ll x;cin>>x; tot+=x;q.push(x); } if(tot<n){cout<<-1<<endl;return ;} ll res=0; while(n){ ll x=q.top();q.pop(); if(x<=n)n-=x,tot-=x; else if(tot-x<n){ res++; q.push(x/2);q.push(x/2); }else tot-=x; } cout<<res<<endl; } signed main(){IOS ll T;T=1; cin>>T; while(T--){ solve(); } return 0; }
cpp
1307
F
F. Cow and Vacationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is planning a vacation! In Cow-lifornia; there are nn cities, with n−1n−1 bidirectional roads connecting them. It is guaranteed that one can reach any city from any other city. Bessie is considering vv possible vacation plans, with the ii-th one consisting of a start city aiai and destination city bibi.It is known that only rr of the cities have rest stops. Bessie gets tired easily, and cannot travel across more than kk consecutive roads without resting. In fact, she is so desperate to rest that she may travel through the same city multiple times in order to do so.For each of the vacation plans, does there exist a way for Bessie to travel from the starting city to the destination city?InputThe first line contains three integers nn, kk, and rr (2≤n≤2⋅1052≤n≤2⋅105, 1≤k,r≤n1≤k,r≤n)  — the number of cities, the maximum number of roads Bessie is willing to travel through in a row without resting, and the number of rest stops.Each of the following n−1n−1 lines contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), meaning city xixi and city yiyi are connected by a road. The next line contains rr integers separated by spaces  — the cities with rest stops. Each city will appear at most once.The next line contains vv (1≤v≤2⋅1051≤v≤2⋅105)  — the number of vacation plans.Each of the following vv lines contain two integers aiai and bibi (1≤ai,bi≤n1≤ai,bi≤n, ai≠biai≠bi)  — the start and end city of the vacation plan. OutputIf Bessie can reach her destination without traveling across more than kk roads without resting for the ii-th vacation plan, print YES. Otherwise, print NO.ExamplesInputCopy6 2 1 1 2 2 3 2 4 4 5 5 6 2 3 1 3 3 5 3 6 OutputCopyYES YES NO InputCopy8 3 3 1 2 2 3 3 4 4 5 4 6 6 7 7 8 2 5 8 2 7 1 8 1 OutputCopyYES NO NoteThe graph for the first example is shown below. The rest stop is denoted by red.For the first query; Bessie can visit these cities in order: 1,2,31,2,3.For the second query, Bessie can visit these cities in order: 3,2,4,53,2,4,5. For the third query, Bessie cannot travel to her destination. For example, if she attempts to travel this way: 3,2,4,5,63,2,4,5,6, she travels on more than 22 roads without resting. The graph for the second example is shown below.
[ "dfs and similar", "dsu", "trees" ]
#include <bits/stdc++.h> using namespace std; const int N=1e6+5; int dep[N],f[N][21],head[N],nxt[N],vet[N],edgenum,que[N],fa[N],K,r,n; void Add(int u,int v) { vet[++edgenum]=v; nxt[edgenum]=head[u]; head[u]=edgenum; } int find(int x) { if (x!=fa[x]) fa[x]=find(fa[x]); return fa[x]; } void bfs() { for (int i=1; i<=n; i++) fa[i]=i,dep[i]=-1; int Head=1,Tail=0; for (int i=1; i<=r; i++) { int x; scanf("%d",&x); que[++Tail]=x; dep[x]=0; } while (Head<=Tail) { int x=que[Head++]; if (dep[x]>=K/2) break; for (int e=head[x]; e; e=nxt[e]) { int v=vet[e]; if (find(x)!=find(v)) fa[find(v)]=find(x); if (dep[v]!=-1) continue; dep[v]=dep[x]+1,que[++Tail]=v; } } } void dfs(int x,int fa) { f[x][0]=fa; dep[x]=dep[fa]+1; for (int i=1; i<=20; i++) f[x][i]=f[f[x][i-1]][i-1]; for (int e=head[x]; e; e=nxt[e]) { int v=vet[e]; if (v==fa) continue; dfs(v,x); } } int LCA(int x,int y) { if (dep[x]<dep[y]) swap(x,y); for (int i=20; i>=0; i--) if (dep[f[x][i]]>=dep[y]) x=f[x][i]; if (x==y) return x; for (int i=20; i>=0; i--) if (f[x][i]!=f[y][i]) x=f[x][i],y=f[y][i]; return f[x][0]; } int Jump(int x,int d) { for (int i=20; i>=0; i--) if (d>=(1<<i)) x=f[x][i],d-=(1<<i); return x; } int Dis(int x,int y,int lca) { return dep[x]+dep[y]-2*dep[lca]; } int main() { // freopen("1.in","r",stdin); // freopen("1.out","w",stdout); scanf("%d%d%d",&n,&K,&r); K<<=1; int num=n; for (int i=1; i<n; i++) { int u,v; scanf("%d%d",&u,&v); Add(u,++num),Add(num,u); Add(v,num),Add(num,v); } n=num; bfs(),dfs(1,0); int q; scanf("%d",&q); while (q--) { int u,v; scanf("%d%d",&u,&v); int lca=LCA(u,v),d=Dis(u,v,lca); // cerr<<u<<' '<<v<<' '<<d<<endl; if (d<=K) { puts("YES"); continue; } int fu,fv; if (dep[u]-dep[lca]>=K/2) fu=Jump(u,K/2); else fu=Jump(v,d-K/2); if (dep[v]-dep[lca]>=K/2) fv=Jump(v,K/2); else fv=Jump(u,d-K/2); if (find(fu)==find(fv)) puts("YES"); else puts("NO"); } return 0; }
cpp
1303
D
D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3 10 3 1 32 1 23 4 16 1 4 1 20 5 2 1 16 1 8 OutputCopy2 -1 0
[ "bitmasks", "greedy" ]
#define _USE_MATH_DEFINES #pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; const int n1=1000000007; #define miv map<int,vector<int>> #define inf 5e18 #define mlv map<ll,vector<ll>> #define mip map<int,pair<int,int>> #define mii map<int,int> #define mll map<ll,ll> #define umip unordered_map<int,pair<int,int>> #define umii unordered_map<int,int> #define vi vector<int> #define vll vector<ll> #define vvll vector<vector<ll>> #define vvi vector<vector<int>> #define ll long long #define pii pair<int,int> #define pll pair<ll,ll> #define vpii vector<pii> #define vpll vector<pll> #define pb push_back #define f first #define s second #define all(x) x.begin(),x.end() #define pi = 3.1415926535897932384626 #define INF LLONG_MAX #define yes cout<<"YES"<<endl #define no cout<<"NO"<<endl #define input(a,x,n); for(int i=x;i<n;i++){cin>>a[i];} #define output(b,x,n); for(int i=x;i<n;i++){cout<<b[i]<<" ";} #define umill unordered_map <int,ll> #define pvi pair<vector<int>,int> #define piv pair<int,vector<int>> #define in(i,x,n) for(int i=x;i<n;i++) #define inl(i,x,n) for(ll i=x;i<n;i++) #define de(i,x,n) for(int i=n;i>=x;i--) #define del(i,x,n) for(ll i=n;i>=x;i--) #define trav(it,m) for(auto it=m.begin();it!=m.end();it++) #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; typedef tree<pll, null_type, less<pll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; struct compare { inline bool operator()(const std::string& first, const std::string& second) const { return first.size() < second.size(); } }; vll factorial(ll n) { vll fct(n+1); fct[0]=1; fct[1]=1; inl(i,2,n+1) { fct[i]=((fct[i-1%n1])*(i%n1))%n1; } return fct; } vll factorial(ll n,ll m) { vll fct(n+1); fct[0]=1; fct[1]=1; inl(i,2,n+1) { fct[i]=((fct[i-1]%m)*(i%m))%m; } return fct; } long long power(long long x,ll y) { long long res = 1; ll p=n1; x = x % p; while (y > 0) { if (y & 1) res = ((res%p) * (x%p)) % p; y = y >> 1; x = ((x%p) * (x%p)) % p; } return res; } long long modInverse(long long n) { return power(n, n1 - 2); } vector<bool> SieveOfEratosthenes(ll n){ vector<bool> prime(n + 1, 1); for (ll p = 2; p * p <= n; p++) if (prime[p] == true) for (ll i = p * p; i <= n; i += p) prime[i] = false; return prime;} ll ncr(ll n,ll r,vll &fct,vll &rfct) { return 1ll*(((((fct[n]%n1)*((rfct[r])%n1))%n1)*((rfct[n-r])%n1))%n1); } // char a[400][400]; ll cnt(int r1,int r2,int c1,int c2,vvll &pre) { ll cnt=0; if(r1>0&&c1>0) { cnt=pre[r2][c2]-pre[r2][c1-1]-pre[r1-1][c2]+pre[r1-1][c1-1]; } else if(r1>0) { cnt=pre[r2][c2]-pre[r1-1][c2]; } else if(c1>0) { cnt=pre[r2][c2]-pre[r2][c1-1]; } else { cnt=pre[r2][c2]; } return cnt; } //ll dp[500][500]; ll ans1; void dfs1(vvll &adj,ll node,vll &vis,vll &lev) { vis[node]=1; for(auto &u:adj[node]) { if(vis[u]==0) { dfs1(adj,u,vis,lev); lev[node]=max(lev[node],lev[u]+1); } } if(lev[node]==-1) { lev[node]=1; } } void dfs(vvll &adj,ll node,ll p,vll &sum,vll &ans,vll &a,map<pll,ll>&mp,vll &v) { sum[node]=sum[p]+mp[{p,node}]; v.pb(node); ll l=0; ll r=v.size()-1; ll req=-1; while(l<=r) { ll mid=(l+r)/2; if(sum[node]-sum[v[mid]]<=a[node]) { req=mid; r=mid-1; } else l=mid+1; } ans[p]++; if(req-1>=0) { ans[v[req-1]]--; } // cout<<node<<"g "<<v[req]<<endl; for(auto &u:adj[node]) { if(u!=p) { dfs(adj,u,node,sum,ans,a,mp,v); ans[node]+=ans[u]; } } v.pop_back(); } void build(ll l,ll r,vll &a,vll &seg,ll idx) { if(l==r) { seg[idx]=a[l]; return; } ll mid=(l+r)/2; build(l,mid,a,seg,2*idx+1); build(mid+1,r,a,seg,2*idx+2); seg[idx]=__gcd(seg[2*idx+1],seg[2*idx+2]); return ; } void build1(ll l,ll r,vll &a,vll &seg,ll idx) { if(l==r) { seg[idx]=a[l]; return; } ll mid=(l+r)/2; build1(l,mid,a,seg,2*idx+1); build1(mid+1,r,a,seg,2*idx+2); seg[idx]=max(seg[2*idx+1],seg[2*idx+2]); return ; } ll query1(ll l,ll r,ll low,ll high,ll idx,vll &seg) { if(low>=l and high<=r) return seg[idx]; if(low>r or high<l) return -1*inf; ll mid=(low+high)/2; ll x=query1(l,r,low,mid,2*idx+1,seg); ll y=query1(l,r,mid+1,high,2*idx+2,seg); return max(x,y); } ll query(ll l,ll r,ll low,ll high,ll idx,vll &seg) { if(low>=l and high<=r) return seg[idx]; if(low>r or high<l) return 0; ll mid=(low+high)/2; ll x=query(l,r,low,mid,2*idx+1,seg); ll y=query(l,r,mid+1,high,2*idx+2,seg); return __gcd(x,y); } void update(ll l,ll r,vll &seg, ll idx,ll val,ll index,mll &st) { if(l==r) { ll x=seg[idx]; if(l==0) { st[x]--; if(st[x]<=0) st.erase(x); seg[idx]-=val; st[seg[idx]]++; } else { seg[idx]-=val; } return; } ll mid=(l+r)/2; if(index>=l and index<=mid) { update(l,mid,seg,2*idx+1,val,index,st); } else { update(mid+1,r,seg,2*idx+2,val,index,st); } ll x=seg[idx]; seg[idx]=min(seg[2*idx+1],seg[2*idx+2]); if(l==0) { st[x]--; if(st[x]<=0) st.erase(x); st[seg[idx]]++; } return; } vll kmp(string str) { vll v(str.size()); v[0]=0; in(i,1,str.size()) { ll j=v[i-1]; while(j>0 and str[i]!=str[j]) { j=v[j-1]; } if(str[i]==str[j]) { j++; } v[i]=j; } return v; } void fun(vector<int>&A) { int n=A.size(); int num1=1e9; int num2=1e9; int c1=0; int c2=0; for(int i=0;i<n;i++) { if(A[i]==num1) { c1++; } else if(A[i]==num2) { c2++; } else if(c1==0) { num1=A[i]; c1++; } else if(c2==0) { num2=A[i]; c2++; } else { c1--; c2--; } } c1=0; c2=0; for(int i=0;i<n;i++) { if(A[i]==num1) { c1++; } if(A[i]==num2) { c2++; } } cout<<num1<<" "<<num2<<endl; if(c1>(n/3)) { cout<<num1; } else if(c2>(n/3)) { cout<<num2; } else { cout<<-1; } cout<<endl; } /*ll spf[10000001]; void sieve() { spf[1]=1; in(i,2,1e7+1) { spf[i]=i; } for(int i=4;i<=1e7+1;i+=2) { spf[i]=2; } for(int i=3;i*i<=1e7+1;i++) { if(spf[i]==i) { for(int j=i*i;j<=1e7+1;j+=i) { if(spf[j]==j) { spf[j]=i; } } } } } */ ll lca(vvll &dp,ll n1,ll n2,vll &dep) { if(dep[n1]<dep[n2]) swap(n1,n2); de(i,0,21) { if(dep[n1]-(1ll<<i)>=dep[n2]) { n1=dp[n1][i]; } } if(n1==n2) return n1; de(i,0,21) { if(dp[n1][i]!=dp[n2][i]) { n1=dp[n1][i]; n2=dp[n2][i]; } } return dp[n1][0]; } void updatef(vll &bt,ll idx,ll val,ll n) { while(idx<=n) { bt[idx]+=val; idx+=(idx&(-idx)); } } ll sum(vll &bt,ll idx) { ll ans=0; while(idx>0) { ans+=bt[idx]; idx-=(idx&(-idx)); } return ans; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL); ll tt=1; cin>>tt; //vvll fcmp(200003); //cout<<primes.size()<<"LK"<<endl; //output(primes,0,primes.size()); //cout<<endl; //mlv fc; while(tt--) //in(x,1,tt+1) { ll n,m; cin>>n>>m; vll cnt(66,0); in(i,0,m) { ll x; cin>>x; ll lg=0; while(x>1) { lg++; x/=2; } cnt[lg]++; } ll lg=0; ll x=n; while(x>1) { x/=2; lg++; } //output(cnt,0,66); //cout<<endl; ll ans=0; in(i,0,lg+1) { if(n&(1ll<<i)) { ll c=1; // cout<<i<<endl; vll v1=cnt; de(j,0,i) { if(c==0)break; if(c<cnt[j]) { cnt[j]-=c; c=0; break; } else { c-=cnt[j]; cnt[j]=0; } c*=2; } if(c) { int f1=0; cnt=v1; in(j,i+1,66) { if(cnt[j]>0) { ans+=(j-i); // cout<<ans<<"JK"<<i<<endl; cnt[i]+=((ll)(pow(2,j-i))); cnt[i]--; cnt[j]--; f1=1; break; } } if(!f1) { ans=-1; break; } } } } cout<<ans<<endl; } 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<bits/stdc++.h> using namespace std; #define ll long long #define inf 1e18 #define N 200005 ll n,m,k,ans=0,x,y,l,r,s,z; ll cnt=0,head[N]; struct edge{ ll x,y,col,id; }e[2*N]; ll d[N]; bool flag[N]; ll col[N]; struct point{ ll d,id; }a[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,ll id){ cnt++; e[cnt].x=head[x]; e[cnt].y=y; e[cnt].col=-1; e[cnt].id=id; head[x]=cnt; return ; } bool cmp(point x,point y){ return x.d>y.d; } void dfs(ll x,ll fa,ll c){ // printf("%lld : c = %lld \n",x,c); ll i; ll go; if (flag[x]){ if (x==1) c=1; for (i=head[x]; i; i=e[i].x){ go=e[i].y; if (go==fa) continue; e[i].col=c; dfs(go,x,c); } } else { ll col=0; for (i=head[x]; i; i=e[i].x){ go=e[i].y; if (go==fa) continue; col++; if (col==c) col++; e[i].col=col; dfs(go,x,col); } } return ; } int main(){ // freopen(".in","r",stdin); // freopen(".out","w",stdout); ll i,j; read(n); read(k); for (i=2; i<=n; i++){ read(x); read(y); addedge(x,y,i); addedge(y,x,i); d[x]++; d[y]++; } for (i=1; i<=n; i++) { a[i].d=d[i]; a[i].id=i; } sort(a+1,a+1+n,cmp); for (i=1; i<=k; i++) flag[a[i].id]=true; ans=a[k+1].d; write(ans); putchar('\n'); dfs(1,-1,-1); for (i=1; i<=cnt; i++){ if (e[i].col==-1) continue; col[e[i].id]=e[i].col; } for (i=2; i<=n; i++) { write(col[i]); putchar(' '); } return 0; }
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> #include <algorithm> #include <iostream> #define fr(a, n) for(int i = a ; i < n ;++i) #define fr2(a, n, i) for(int i = a ; i < n ;++i) using namespace std; void solve() { int n; cin>>n; int arr[n]; int left[n]; int right[n]; map<int, int> mp; set<int>st; fr(0, n) { cin>>arr[i]; mp[arr[i]]++; } fr(1, 2 * n + 1) { if(mp[i] == 0) st.insert(i); } bool solved = false; fr(0, n) { auto it = st.begin(); solved = false; while(it != st.end()) { if(*it > arr[i] && !solved) { left[i] = arr[i]; right[i] = *it; st.erase(it); solved = true; break; } it++; } if(!solved) break; } if(solved) { fr(0, n) cout<<left[i]<<' '<<right[i]<<' '; cout<<'\n'; } else cout<<-1<<'\n'; } int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); int tc = 1; cin>>tc; while(tc--) { solve(); } }
cpp
1323
A
A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3 3 1 4 3 1 15 2 3 5 OutputCopy1 2 -1 2 1 2 NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.
[ "brute force", "dp", "greedy", "implementation" ]
#include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); int t; cin>>t; while(t--){ int n; cin>>n; int arr[n]; for(int i=0;i<n;i++){ cin>>arr[i]; } if(n==1 && arr[0]%2){ cout<<-1<<'\n'; } else{ int ix=-1; for(int i=0;i<n;i++){ if(arr[i]%2==0){ ix=i+1; break; } } if(ix==-1){ cout<<2<<'\n'<<1<<' '<<2<<'\n'; } else{ cout<<1<<'\n'<<ix<<'\n'; } } } 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" ]
// LUOGU_RID: 100224854 #include<bits/stdc++.h> using namespace std; #define ll long long #define inf INT_MAX #define N 200005 ll n,m,k,ans=0,x,y,l,r,s,z; ll cnt=0,head[N]; struct edge{ ll x,y,col,id; }e[2*N]; ll d[N]; bool flag[N]; ll col[N]; struct point{ ll d,id; }a[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,ll id){ cnt++; e[cnt].x=head[x]; e[cnt].y=y; e[cnt].col=-1; e[cnt].id=id; head[x]=cnt; return ; } bool cmp(point x,point y){ return x.d>y.d; } void dfs(ll x,ll fa,ll c){ // printf("%lld : c = %lld \n",x,c); ll i; ll go; if (flag[x]){ if (x==1) c=1; for (i=head[x]; i; i=e[i].x){ go=e[i].y; if (go==fa) continue; e[i].col=c; dfs(go,x,c); } } else { ll col=0; for (i=head[x]; i; i=e[i].x){ go=e[i].y; if (go==fa) continue; col++; if (col==c) col++; e[i].col=col; dfs(go,x,col); } } return ; } int main(){ // freopen(".in","r",stdin); // freopen(".out","w",stdout); ll i,j; read(n); read(k); for (i=2; i<=n; i++){ read(x); read(y); addedge(x,y,i); addedge(y,x,i); d[x]++; d[y]++; } for (i=1; i<=n; i++) { a[i].d=d[i]; a[i].id=i; } sort(a+1,a+1+n,cmp); for (i=1; i<=k; i++) flag[a[i].id]=true; ans=a[k+1].d; write(ans); putchar('\n'); dfs(1,-1,-1); for (i=1; i<=cnt; i++){ if (e[i].col==-1) continue; col[e[i].id]=e[i].col; } for (i=2; i<=n; i++) { write(col[i]); putchar(' '); } 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<cstdio> #include<vector> #include<queue> #include<cstring> #include<iostream> #include<algorithm> #include<ctime> #include<random> #include<assert.h> #define pb emplace_back #define mp make_pair #define fi first #define se second #define dbg(x) cerr<<"In Line "<< __LINE__<<" the "<<#x<<" = "<<x<<'\n'; #define dpi(x,y) cerr<<"In Line "<<__LINE__<<" the "<<#x<<" = "<<x<<" ; "<<"the "<<#y<<" = "<<y<<'\n'; using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int,int>pii; typedef pair<ll,int>pli; typedef pair<ll,ll>pll; typedef pair<int,ll>pil; typedef vector<int>vi; typedef vector<ll>vll; typedef vector<pii>vpii; typedef vector<pil>vpil; template<typename T>T cmax(T &x, T y){return x=x>y?x:y;} template<typename T>T cmin(T &x, T y){return x=x<y?x:y;} template<typename T> T &read(T &r){ r=0;bool w=0;char ch=getchar(); while(ch<'0'||ch>'9')w=ch=='-'?1:0,ch=getchar(); while(ch>='0'&&ch<='9')r=r*10+(ch^48),ch=getchar(); return r=w?-r:r; } template<typename T1,typename... T2> void read(T1 &x,T2& ...y){read(x);read(y...);} const int mod=998244353; inline void cadd(int &x,int y){x=(x+y>=mod)?(x+y-mod):(x+y);} inline void cdel(int &x,int y){x=(x-y<0)?(x-y+mod):(x-y);} inline int add(int x,int y){return (x+y>=mod)?(x+y-mod):(x+y);} inline int del(int x,int y){return (x-y<0)?(x-y+mod):(x-y);} inline int lowbit(int x){ return x&(-x); } const int N=1000100; int n,m,z[N],p[N],q[N]; char a[N],b[N],s[N]; ll ans; struct Tree{ ll tree[N]; void modify(int x,ll v){++x;for(;x<=n+1;x+=lowbit(x))tree[x]+=v;} ll query(int x){++x;ll s=0;for(;x;x-=lowbit(x))s+=tree[x];return s;} ll query(int l,int r){return query(r)-query(l-1);} }tr1,tr2; signed main(){ #ifdef do_while_true // assert(freopen("data.in","r",stdin)); // assert(freopen("data.out","w",stdout)); #endif read(n,m); scanf("%s%s%s",a+1,b+1,s+1); for(int i=2,l=0,r=0;i<=m;i++){ if(i<=r)z[i]=min(z[i-l+1],r-i+1); else z[i]=0; while(i+z[i]<=m && s[z[i]+1]==s[i+z[i]])++z[i]; if(i+z[i]-1>r)r=i+z[i]-1,l=i; } for(int i=1,l=0,r=0;i<=n;i++){ if(i<=r)p[i]=min(z[i-l+1],r-i+1); else p[i]=0; while(p[i]<m && i+p[i]<=n && s[p[i]+1]==a[i+p[i]])++p[i]; if(i+p[i]-1>r)r=i+p[i]-1,l=i; } reverse(b+1,b+n+1); reverse(s+1,s+m+1); for(int i=2,l=0,r=0;i<=m;i++){ if(i<=r)z[i]=min(z[i-l+1],r-i+1); else z[i]=0; while(i+z[i]<=m && s[z[i]+1]==s[i+z[i]])++z[i]; if(i+z[i]-1>r)r=i+z[i]-1,l=i; } for(int i=1,l=0,r=0;i<=n;i++){ if(i<=r)q[i]=min(z[i-l+1],r-i+1); else q[i]=0; while(q[i]<m && i+q[i]<=n && s[q[i]+1]==b[i+q[i]])++q[i]; if(i+q[i]-1>r)r=i+q[i]-1,l=i; } reverse(q+1,q+n+1); /* for(int i=1;i<=n;i++)cout << p[i] << ' '; puts(""); for(int i=1;i<=n;i++)cout << q[i] << ' '; puts(""); */ for(int i=1;i<=n;i++)cmin(p[i],m-1),cmin(q[i],m-1); /* for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(i<=j&&j<=i+m-2) if(p[i]>=m-q[j]) ans+=p[i]-(m-q[j])+1; */ for(int i=n;i;i--){ tr1.modify(m-q[i],1); tr2.modify(m-q[i],-m+q[i]+1); ans+=tr1.query(p[i])*p[i]; ans+=tr2.query(p[i]); if(i-m+1>=1){ int l=i-m+1; ans-=tr1.query(p[l])*p[l]; ans-=tr2.query(p[l]); } } cout << ans << '\n'; #ifdef do_while_true cerr<<'\n'<<"Time:"<<1.0*clock()/CLOCKS_PER_SEC*1000<<" ms"<<'\n'; #endif 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" ]
#include<bits/stdc++.h> using namespace std; #define ll long long int main () { ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0); ll t; cin >> t; while( t-- ){ string s; cin >> s; ll cnt = 0, z = 0, cal = 0 , ans = 0; for(ll i = 0; i < s.size(); i++)if(s[i] == '1') {cal = i, z++; break;} for(ll i = s.size() - 1; i >= 0; i--)if(s[i] == '1') {ans = i; break;} for(ll i = cal; i <= ans; i++)if(s[i] == '0') cnt++; if(z == 0) cout << false << endl; else cout << cnt << endl; } } /* */
cpp
1285
E
E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be placed arbitrarily  — be inside each other, coincide and so on. Segments can degenerate into points, that is li=rili=ri is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: if n=3n=3 and there are segments [3,6][3,6], [100,100][100,100], [5,8][5,8] then their union is 22 segments: [3,8][3,8] and [100,100][100,100]; if n=5n=5 and there are segments [1,2][1,2], [2,3][2,3], [4,5][4,5], [4,6][4,6], [6,6][6,6] then their union is 22 segments: [1,3][1,3] and [4,6][4,6]. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given nn so that the number of segments in the union of the rest n−1n−1 segments is maximum possible.For example, if n=4n=4 and there are segments [1,4][1,4], [2,3][2,3], [3,6][3,6], [5,7][5,7], then: erasing the first segment will lead to [2,3][2,3], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the second segment will lead to [1,4][1,4], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the third segment will lead to [1,4][1,4], [2,3][2,3], [5,7][5,7] remaining, which have 22 segments in their union; erasing the fourth segment will lead to [1,4][1,4], [2,3][2,3], [3,6][3,6] remaining, which have 11 segment in their union. Thus, you are required to erase the third segment to get answer 22.Write a program that will find the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n−1n−1 segments.InputThe first line contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first of each test case contains a single integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of segments in the given set. Then nn lines follow, each contains a description of a segment — a pair of integers lili, riri (−109≤li≤ri≤109−109≤li≤ri≤109), where lili and riri are the coordinates of the left and right borders of the ii-th segment, respectively.The segments are given in an arbitrary order.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.OutputPrint tt integers — the answers to the tt given test cases in the order of input. The answer is the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.ExampleInputCopy3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 OutputCopy2 1 5
[ "brute force", "constructive algorithms", "data structures", "dp", "graphs", "sortings", "trees", "two pointers" ]
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<pair<int, int>> intervals; vector<int> nums; for(int i = 0; i < n; i++) { int l, r; cin >> l >> r; nums.push_back(l); nums.push_back(r); intervals.push_back({l, r}); } sort(nums.begin(), nums.end()); nums.resize(unique(nums.begin(), nums.end()) - nums.begin()); int sz = (int) nums.size(); vector<vector<int>> add(sz), del(sz); for(int i = 0; i < n; i++) { auto [l, r] = intervals[i]; l = lower_bound(nums.begin(), nums.end(), l) - nums.begin(); r = lower_bound(nums.begin(), nums.end(), r) - nums.begin(); add[l].push_back(i); del[r].push_back(i); } set<int> curr; vector<int> change(n); for(int i = 0; i < sz; i++) { if(!add[i].empty()) sort(add[i].begin(), add[i].end()); if(!del[i].empty()) sort(del[i].begin(), del[i].end()); if(curr.size() == 1) { change[*curr.begin()]++; } for(int j : add[i]) { curr.insert(j); } if(curr.size() > 1) { for(int j : add[i]) { change[j]++; } for(int j : del[i]) { change[j]++; } } if(curr.size() == 1) { // edge case for(int j : del[i]) { auto it = lower_bound(add[i].begin(), add[i].end(), j); if(it != add[i].end() && *it == j) { change[j]++; } } } for(int j : del[i]) { curr.erase(j); } } curr.clear(); int initial = 0; for(int i = 0; i < sz; i++) { for(int j : add[i]) { curr.insert(j); } for(int j : del[i]) { if(curr.size() == 1) initial++; curr.erase(j); } } int ans = 0; for(int i = 0; i < n; i++) { ans = max(ans, initial + change[i] - 2); } cout << ans << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while(t--) { solve(); } }
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> #define rep(i,x,y) for(auto i=(x);i<=(y);++i) #define dep(i,x,y) for(auto i=(x);i>=(y);--i) using namespace std; typedef long long ll; const int N=1e5+10; const int mo=1e9+7; const int inf=1e9; int f[18][N],h[N];vector<int>p[N]; void dfs(int x){ for(auto&i:p[x])if(i!=f[0][x]){ f[0][i]=x;h[i]=h[x]+1;dfs(i); } } int lca(int x,int y){ if(h[x]<h[y])swap(x,y); dep(i,17,0)if((h[x]-h[y])>>i)x=f[i][x]; if(x==y)return x; dep(i,17,0)if(f[i][x]!=f[i][y])x=f[i][x],y=f[i][y]; return f[0][x]; } int dis(int x,int y){ return h[x]+h[y]-h[lca(x,y)]*2; } bool ok(int x,int y){ return y>=x&&x%2==y%2; } int main(){int n,q; scanf("%d",&n); rep(i,2,n){int x,y; scanf("%d%d",&x,&y); p[x].push_back(y); p[y].push_back(x); }dfs(1); rep(i,1,17)rep(j,1,n)f[i][j]=f[i-1][f[i-1][j]]; scanf("%d",&q); rep(i,1,q){int x,y,a,b,k; scanf("%d%d%d%d%d",&x,&y,&a,&b,&k); printf("%s\n",(ok(dis(a,b),k)|| ok(dis(a,x)+dis(b,y)+1,k)|| ok(dis(a,y)+dis(b,x)+1,k))?"YES":"NO"); } }
cpp
1286
D
D. LCCtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn infinitely long Line Chillland Collider (LCC) was built in Chillland. There are nn pipes with coordinates xixi that are connected to LCC. When the experiment starts at time 0, ii-th proton flies from the ii-th pipe with speed vivi. It flies to the right with probability pipi and flies to the left with probability (1−pi)(1−pi). The duration of the experiment is determined as the time of the first collision of any two protons. In case there is no collision, the duration of the experiment is considered to be zero.Find the expected value of the duration of the experiment.Illustration for the first exampleInputThe first line of input contains one integer nn — the number of pipes (1≤n≤1051≤n≤105). Each of the following nn lines contains three integers xixi, vivi, pipi — the coordinate of the ii-th pipe, the speed of the ii-th proton and the probability that the ii-th proton flies to the right in percentage points (−109≤xi≤109,1≤v≤106,0≤pi≤100−109≤xi≤109,1≤v≤106,0≤pi≤100). It is guaranteed that all xixi are distinct and sorted in increasing order.OutputIt's possible to prove that the answer can always be represented as a fraction P/QP/Q, where PP is an integer and QQ is a natural number not divisible by 998244353998244353. In this case, print P⋅Q−1P⋅Q−1 modulo 998244353998244353.ExamplesInputCopy2 1 1 100 3 1 0 OutputCopy1 InputCopy3 7 10 0 9 4 86 14 5 100 OutputCopy0 InputCopy4 6 4 50 11 25 50 13 16 50 15 8 50 OutputCopy150902884
[ "data structures", "math", "matrices", "probabilities" ]
#include<bits/stdc++.h> typedef long long ll; #define rep(i, a, b) for(int i = (a); i <= (b); i ++) #define per(i, a, b) for(int i = (a); i >= (b); i --) #define Ede(i, u) for(int i = head[u]; i; i = e[i].nxt) using namespace std; const int P = 998244353; inline int plu(int x, int y) {return x + y >= P ? x + y - P : x + y;} inline int del(int x, int y) {return x - y < 0 ? x - y + P : x - y;} inline void add(int &x, int y) {x = plu(x, y);} inline void sub(int &x, int y) {x = del(x, y);} inline int qpow(int a, int b) {int s = 1; for(; b; b >>= 1, a = 1ll * a * a % P) if(b & 1) s = 1ll * s * a % P; return s;} inline int read() { int x = 0, f = 1; char c = getchar(); while(c < '0' || c > '9') f = (c == '-') ? - 1 : 1, c = getchar(); while(c >= '0' && c <= '9') x = x * 10 + c - 48, c = getchar(); return x * f; } const int N = 1e5 + 10; int n, m, x[N], v[N], p[N]; bool valid[N][2][2]; struct node {int p, tx, ty; bool a, b;} q[N * 3]; struct Matrix { int mat[2][2]; Matrix() {memset(mat, 0, sizeof(mat));} } dat[N << 2]; Matrix calc(int p, Matrix a, Matrix b) { Matrix c; // cerr << valid[p][0][0] << ' ' << valid[p][0][1] << ' ' << valid[p][1][0] << ' ' << valid[p][1][1] << endl; rep(x, 0, 1) rep(y, 0, 1) if(valid[p][x][y]) rep(l, 0, 1) rep(r, 0, 1) add(c.mat[l][r], 1ll * a.mat[l][x] * b.mat[y][r] % P); return c; } int cal(int x) { Matrix cur = dat[x]; return plu(plu(cur.mat[0][0], cur.mat[0][1]), plu(cur.mat[1][0], cur.mat[1][1])); } void bui(int o, int l, int r) { if(l == r) return dat[o].mat[1][1] = p[l], dat[o].mat[0][0] = del(1, p[l]), void(); int mid = (l + r) >> 1; bui(o << 1, l, mid), bui(o << 1 | 1, mid + 1, r); dat[o] = calc(mid, dat[o << 1], dat[o << 1 | 1]); // cerr << "bui " << o << ' ' << dat[o].mat[0][0] << ' ' << dat[o].mat[0][1] << ' ' // << dat[o].mat[1][0] << ' ' << dat[o].mat[1][1] << endl; } void moi(int p, int l, int r, int k) { if(l == r) return; int mid = (l + r) >> 1; if(k <= mid) moi(p << 1, l, mid, k); else moi(p << 1 | 1, mid + 1, r, k); dat[p] = calc(mid, dat[p << 1], dat[p << 1 | 1]); } int main() { n = read(); int inv = qpow(100, P - 2); rep(i, 1, n) x[i] = read(), v[i] = read(), p[i] = 1ll * read() * inv % P; // cerr << i << ' ' << p[i] << endl; rep(i, 1, n - 1) rep(a, 0, 1) rep(b, 0, 1) valid[i][a][b] = true; rep(i, 1, n - 1) { q[++ m] = (node) {i, x[i + 1] - x[i], v[i] + v[i + 1], 1, 0}; if(v[i] > v[i + 1]) q[++ m] = (node) {i, x[i + 1] - x[i], v[i] - v[i + 1], 1, 1}; if(v[i] < v[i + 1]) q[++ m] = (node) {i, x[i + 1] - x[i], v[i + 1] - v[i], 0, 0}; } sort(q + 1, q + m + 1, [](node u, node v) {return 1ll * u.tx * v.ty < 1ll * v.tx * u.ty;}); bui(1, 1, n); int ans = 0; rep(i, 1, m) { node cur = q[i]; bool pre[2][2]; rep(a, 0, 1) rep(b, 0, 1) pre[a][b] = valid[cur.p][a][b]; rep(a, 0, 1) rep(b, 0, 1) if(a != cur.a || b != cur.b) valid[cur.p][a][b] = false; valid[cur.p][cur.a][cur.b] = true; // cerr << cur.p << ' ' << cur.a << ' ' << cur.b << endl; moi(1, 1, n, cur.p); add(ans, 1ll * cur.tx * qpow(cur.ty, P - 2) % P * cal(1) % P); rep(a, 0, 1) rep(b, 0, 1) if(a != cur.a || b != cur.b) valid[cur.p][a][b] = pre[a][b]; valid[cur.p][cur.a][cur.b] = false; moi(1, 1, n, cur.p); } printf("%d\n", ans); return 0; }
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; const int N = 2 * 100 * 1000 +10; int n, q; int dp[N][22], st[N], ft[N], t, h[N]; int k, m, vir[N], S[N], is_vir[N], added[N]; int ans[N]; long long ans_time[N]; vector<int>vertex; vector<int> adj[N]; set<pair<int,int>> vertex_st; set<pair<int,long long>> s; bool cmp(int u, int v){return (st[u] < st[v]);} void dfs(int parent, int u) { dp[u][0] = parent; for(int j=1; j<20 && dp[u][j-1]; j++) dp[u][j] = dp[dp[u][j-1]][j-1]; st[u] = ++t; for(auto v : adj[u]) if(v != parent) h[v] = h[u] + 1, dfs(u, v); ft[u] = ++t; } int LCA(int u, int v) { if(h[u] < h[v]) swap(u, v); for(int j=19; j>=0; j--) if(h[u] - h[v] >= (1 << j)) u = dp[u][j]; if(u == v) return u; for(int j=19; j>=0; j--) if(dp[u][j] != dp[v][j]) u = dp[u][j], v = dp[v][j]; return dp[u][0]; } long long dist(int u, int viruse) { int v = vir[viruse]; if(u == v) return 0; int lca = LCA(u, v); int d = (h[u] - h[lca]) + (h[v] - h[lca]); int round = d/S[viruse] + (d%S[viruse] == 0 ? -1 : 0); long long ret = ((long long)round * (long long)k) + (long long)viruse; return ret; } bool in_sub(int v, int u) { if(st[u] <= st[v] && st[v] <= ft[u]) return true; else return false; } bool check(int u, int j) { auto au1 = s.lower_bound({st[dp[u][j]], -10}); int mn = 0; if(au1 != s.end() && st[au1 -> second] < ft[dp[u][j]]) mn = au1 -> second; auto au = s.upper_bound({ft[dp[u][j]], -10}); int mx = 0; if(au != s.begin()) { au --; if(st[dp[u][j]] < st[au -> second]) mx = au -> second; } return !((mx == 0 || in_sub(mx, u)) && (mn == 0 || in_sub(mn, u))); } int first_up(int u) { for(int j=19; j>=0;j--) if(dp[u][j] != 0 && check(u, j) == false) u = dp[u][j]; return (u == 1 ? -1 : dp[u][0]); } int pnt = 0; void dfs_down(int u) { if(is_vir[u]) ans[u] = is_vir[u], ans_time[u] = 0; while(++pnt < vertex.size()) { int v = vertex[pnt]; if(in_sub(v, u) == false) { pnt--; break; } dfs_down(v); long long d = dist(u, ans[v]); if(ans_time[u] == -1 || d < ans_time[u]) ans[u] = ans[v], ans_time[u] = d; } } void dfs_up(int parent, int u) { if(parent && (ans_time[u] == -1 || dist(u, ans[parent]) < ans_time[u])) ans[u] = ans[parent]; while(++pnt < vertex.size()) { int v = vertex[pnt]; if(in_sub(v, u) == false) { pnt --; break; } dfs_up(u, v); } } int query(int u) { long long mn = -1; int ansasli = 0; auto au = vertex_st.lower_bound({st[u], -10}); if(au != vertex_st.end() && au -> first <= ft[u]) mn = dist(u, ans[au -> second]), ansasli = ans[au -> second]; int up = first_up(u); if(up == -1) return ansasli; if(added[up]) { long long d = dist(u, ans[up]); if(mn == -1 || d < mn) ansasli = ans[up]; } else { int v = query(up); long long d = dist(u, v); if(mn == -1 || d < mn) ansasli = v; } return ansasli; } void Main() { cin>>k>>m; for(int i=1;i<=k;i++) { cin>>vir[i]>>S[i]; is_vir[vir[i]] = i; s.insert({st[vir[i]], vir[i]}); } for(int i=1;i<=k;i++) { int u = vir[i]; while(u != -1 && added[u] == 0) { vertex.push_back(u), added[u] = 1; u = first_up(u); } } sort(vertex.begin(), vertex.end(), cmp); pnt = 0, dfs_down(vertex[0]); pnt = 0, dfs_up(0, vertex[0]); for(auto u : vertex) vertex_st.insert({st[u], u}); while(m--) { int u; cin>>u; cout<<query(u)<<" "; } cout<<'\n'; for(auto u : vertex) { is_vir[u] = 0; added[u] = 0; ans_time[u] = -1; } s.clear(); vertex.clear(); vertex_st.clear(); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin>>n; for(int i=1;i<n;i++) { int u, v; cin>>u>>v; adj[u].push_back(v); adj[v].push_back(u); } dfs(0, 1); fill(ans_time, ans_time+n+1, -1); cin>>q; while(q--) Main(); return 0; }
cpp
1312
C
C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5 4 100 0 0 0 0 1 2 1 3 4 1 4 1 3 2 0 1 3 3 9 0 59049 810 OutputCopyYES YES NO NO YES NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2.
[ "bitmasks", "greedy", "implementation", "math", "number theory", "ternary search" ]
#include <bits/stdc++.h> using namespace std; typedef long long int ll ; map<ll, ll> mp ; void check(ll n, ll k) { ll cnt=0 ; while(n) { mp[cnt]+=(n%k); n/=k ; cnt++ ; } } int main() { ll tc; cin >> tc ; while(tc--) { ll n, k, i ; cin >> n >> k ; bool bb = 1 ; for(int i=0; i<n; i++) { ll a; cin >> a ; check(a, k) ; } for(auto it: mp) { //cout << it.first << " " << it.second << endl ; if(it.second>1) { bb = 0 ; break; } } if(bb) cout << "YES" << endl ; else cout << "NO" << endl ; mp.clear(); } return 0; }
cpp
1312
E
E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair). Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5 4 3 2 2 3 OutputCopy2 InputCopy7 3 3 4 4 4 3 3 OutputCopy2 InputCopy3 1 3 5 OutputCopy3 InputCopy1 1000 OutputCopy1 NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all.
[ "dp", "greedy" ]
#include<bits/stdc++.h> #define endl '\n' #define int long long #define INF 0x3f3f3f3f using namespace std; const int N=500+3; int a[N],f[N][N],dp[N]; //区间DP //求出f[l,r]表示[l,r]区间向左合并的最小可能数。然后dp一遍枚举区间划分即可。 void solve() { int n; cin>>n; for(int i=1; i<=n; i++) cin>>a[i]; map<int ,int >mp; for(int i=1; i<=n; i++) { int cnt=0; for(int j=i; j<=n; j++) { int x=a[j]; while(cnt&&mp[cnt]==x) cnt--,x++; mp[++cnt]=x; f[i][j]=cnt; } } memset(dp,INF,sizeof(dp)); dp[0]=0; for(int i=1;i<=n;i++) { for(int j=0;j<i;j++) { dp[i]=min(dp[i],dp[j]+f[j+1][i]); } } cout<<dp[n]<<endl; } signed main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); // int t; cin>>t; while(t--) solve(); return 0; }
cpp
1312
C
C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5 4 100 0 0 0 0 1 2 1 3 4 1 4 1 3 2 0 1 3 3 9 0 59049 810 OutputCopyYES YES NO NO YES NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2.
[ "bitmasks", "greedy", "implementation", "math", "number theory", "ternary search" ]
#include<bits/stdc++.h> using namespace std; #define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) #define fix(n,f) std::fixed<<std::setprecision(f)<<n #define ll long long #define all(v) v.begin(),v.end() #define nl "\n" #define M 1000000007 #define sum(a,b) ((a%M)+(b%M))%M #define pro(a,b) ((a%M)*(b%M))%M #define diff(a,b) ((a%M)-(b%M)+M)%M /*============================ ░██████╗░██████╗░ ========================*/ /*============================ ██╔════╝░██╔══██╗ =======================*/ /*============================ ██║░░██╗░██║░░██║ =======================*/ /*============================ ██║░░╚██╗██║░░██║ =======================*/ /*============================ ╚██████╔╝██████╔╝ =======================*/ /*============================ ░╚═════╝░╚═════╝░ =======================*/ /* Before Solving the Problem: 1. Dry run testcases , with pen -paper 2. Don't forget the simplest tests 3. Stay calm & keep code on */ /*========================================= I BOW TO LORD SHIVA =============================================*/ void solve(){ ll n,k;cin>>n>>k; vector<ll> v(n); for(auto &p:v){ cin>>p; } map<ll,ll> m; for(auto &p:v){ ll z=p; ll ct=0; while(z!=0){ if(m.count(ct)){ m[ct]+=(z%k); } else{ m[ct]=(z%k); } z/=k; ct++; } } for(auto &p:m){ if(p.second>1){ cout<<"NO"<<nl; return; } } cout<<"YES"<<nl; } int main(){ fastio(); // freopen("input.txt", "r" ,stdin); // freopen("output.txt", "w" ,stdout); int t=1; cin>>t; while(t--){ solve(); } }
cpp
1299
E
E. So Meantime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is interactive.We have hidden a permutation p1,p2,…,pnp1,p2,…,pn of numbers from 11 to nn from you, where nn is even. You can try to guess it using the following queries:?? kk a1a1 a2a2 …… akak.In response, you will learn if the average of elements with indexes a1,a2,…,aka1,a2,…,ak is an integer. In other words, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. You have to guess the permutation. You can ask not more than 18n18n queries.Note that permutations [p1,p2,…,pk][p1,p2,…,pk] and [n+1−p1,n+1−p2,…,n+1−pk][n+1−p1,n+1−p2,…,n+1−pk] are indistinguishable. Therefore, you are guaranteed that p1≤n2p1≤n2.Note that the permutation pp is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries.InputThe first line contains a single integer nn (2≤n≤8002≤n≤800, nn is even).InteractionYou begin the interaction by reading nn.To ask a question about elements on positions a1,a2,…,aka1,a2,…,ak, in a separate line output?? kk a1a1 a2a2 ... akakNumbers in the query have to satisfy 1≤ai≤n1≤ai≤n, and all aiai have to be different. Don't forget to 'flush', to get the answer.In response, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. In case your query is invalid or you asked more than 18n18n queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you determine permutation, output !! p1p1 p2p2 ... pnpnAfter 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 formatFor the hacks use the following format:The first line has to contain a single integer nn (2≤n≤8002≤n≤800, nn is even).In the next line output nn integers p1,p2,…,pnp1,p2,…,pn — the valid permutation of numbers from 11 to nn. p1≤n2p1≤n2 must hold.ExampleInputCopy2 1 2 OutputCopy? 1 2 ? 1 1 ! 1 2
[ "interactive", "math" ]
#include <bits/stdc++.h> #define N 1005 #define pb push_back using namespace std; int n, a[N], b[N], pos[N]; int qry(vector<int> &v) { printf("? %u ", v.size()); for (auto x : v) printf("%d ", x); puts(""); fflush(stdout); int r = 0; scanf("%d", &r); return r; } int ask(int x) { vector<int> v; for (int i = 1; i <= n; i++) if (!a[i] && i != x) v.pb(i); return qry(v); } void solve(int x, int y, int p, int q) { for (int i = 1; i <= n; i++) { if (!pos[x] && !a[i] && b[i]==p && ask(i)) pos[x] = i; else if (!pos[y] && !a[i] && b[i]==q && ask(i)) pos[y] = i; } a[pos[x]] = x; a[pos[y]] = y; } int main() { scanf("%d", &n); solve(1, n, 0, 0); for (int l = 2, r = n-1, t = 2; l <= r; t <<= 1) { for (int i = 1; i <= n; i++) if (!a[i]) { vector<int> v; v.pb(i); for (int j = 1; j <= t; j++) if (j%t != b[i]%t) v.pb(pos[j]); if (qry(v)) b[i] += t>>1; } while (l <= r && l <= (t<<1)) solve(l, r, l%t, r%t), ++l, --r; } if (a[1] > n/2) for (int i = 1; i <= n; i++) a[i] = n+1-a[i]; printf("! "); for (int i = 1; i <= n; i++) printf("%d ", a[i]); puts(""); fflush(stdout); return 0; }
cpp
1299
B
B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4 1 0 4 1 3 4 0 3 OutputCopyYESInputCopy3 100 86 50 0 150 0 OutputCopynOInputCopy8 0 0 1 0 2 1 3 3 4 6 3 6 2 5 1 3 OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements.
[ "geometry" ]
#include <iostream> #include <vector> using namespace std; #define fastIO ios_base::sync_with_stdio(false); cin.tie(NULL); typedef long long int64; struct Point{ double x, y; Point(){ } Point(double x, double y){ this->x = x; this->y = y; } }; Point sub(Point A, Point B){ return Point(A.x - B.x, A.y - B.y); } int main(){ fastIO int n; cin >> n; vector<Point> polygon(n); for (int i = 0; i < n; i++){ Point p; cin >> p.x >> p.y; polygon[i] = p; } if (n % 2 != 0){ cout << "No"; } else{ Point center(0, 0); for (Point p : polygon){ center.x += p.x; center.y += p.y; } center.x /= n; center.y /= n; bool aerodynamic = true; for (int i = 0; i < n / 2; i++){ Point A = polygon[i]; Point B = polygon[n / 2 + i]; Point OA = sub(A, center); Point OB = sub(B, center); if (OA.x != -OB.x || OA.y != -OB.y){ aerodynamic = false; break; } } if (aerodynamic) cout << "Yes"; else cout << "No"; } return 0; }
cpp
1141
F1
F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7 4 1 2 2 1 5 3 OutputCopy3 7 7 2 3 4 5 InputCopy11 -5 -4 -3 -2 -1 0 1 2 3 4 5 OutputCopy2 3 4 1 1 InputCopy4 1 1 1 1 OutputCopy4 4 4 1 1 2 2 3 3
[ "greedy" ]
#include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> #define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define ll long long #define ld long double #define el "\n" #define matrix vector<vector<int>> #define pt complex<ld> #define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> #define ordered_multiset tree<ll, null_type,less_equal<ll>, rb_tree_tag, tree_order_statistics_node_update> using namespace __gnu_pbds; using namespace std; const ll N = 1500, LOG = 20; const ld pi = acos(-1); const ll mod = 1e9 + 7; int dx[] = {0, -1, 0, 1, -1, 1, -1, 1}; int dy[] = {-1, 0, 1, 0, 1, -1, -1, 1}; ll n, m, k, x, y; int a[N]; int solve(vector<pair<int, int>> &v) { int cnt = 1; int idx; sort(v.begin(), v.end()); pair<int, int> p = {v[0].second, 1e9}; for (auto j: v) { if (p.second > j.second) { p = j; } } p = {p.second + 1, 0}; idx = upper_bound(v.begin(), v.end(), p) - v.begin(); while (idx < v.size()) { p = v[idx]; p = {p.second + 1, 0}; idx = upper_bound(v.begin(), v.end(), p) - v.begin(); cnt++; } return cnt; } void dowork() { map<int, vector<pair<int, int>>> mp; cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; } int sum; vector<pair<int, int>> ans; for (int i = 1; i <= n; i++) { sum = 0; for (int j = i; j > 0; j--) { sum += a[j]; if (mp[sum].size() == 0 || mp[sum].back().second < j) { mp[sum].push_back({j, i}); } if (mp[sum].size() > ans.size()) { ans = mp[sum]; } } } cout << ans.size() << el; for (auto j: ans) { cout << j.first << " " << j.second << el; } } int main() { fast //freopen("cowland.in", "r", stdin); //freopen("cowland.out", "w", stdout); int t = 1; //cin >> t; for (int i = 1; i <= t; i++) { dowork(); } }
cpp
1316
A
A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105)  — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m)  — scores of the students.OutputFor each testcase, output one integer  — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2 4 10 1 2 3 4 4 5 1 2 3 4 OutputCopy10 5 NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m.
[ "implementation" ]
#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); ll t, n, m; cin >> t; while (t--) { cin >> n >> m; vi a(n); for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 1; i < n; i++) { if (a[0] >= m) break; a[0] += a[i]; } cout << min(m, a[0]) << '\n'; } }
cpp
1294
B
B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3 5 1 3 1 2 3 3 5 5 4 3 2 1 0 0 1 1 4 3 OutputCopyYES RUUURRRRUU NO YES RRRRUUU NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
[ "implementation", "sortings" ]
#include<bits/stdc++.h> using namespace std; int main() {int t; cin>>t; while(t--){ int n; cin>>n; pair<int ,int >a[n]; for(int i=0;i<n;i++){ cin>>a[i].first>>a[i].second; } sort(a,a+n); int x=0,y=0,f=0; string s=""; for(int i=0;i<n;i++){ int u=a[i].first,v=a[i].second; if(v<y){ f=1; cout<<"NO"; cout<<endl; break; } s+=string(u-x,'R'); s+=string(v-y,'U'); x=u; y=v; } if(!f) cout<<"YES"<<endl<<s<<endl; } return 0; }
cpp
1287
B
B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3 SET ETS TSE OutputCopy1InputCopy3 4 SETE ETSE TSES OutputCopy0InputCopy5 4 SETT TEST EEET ESTE STES OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES"
[ "brute force", "data structures", "implementation" ]
/* ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠟⣋⣯⡀⠀⣠⣿⠿⣤⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠰⣤⡙⣿⡄⠀⣷⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀⣠⡾⠙⠟⣩⡤⢾⠉⡿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠳⣼⣿⡷⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⢀⣾⠿⠶⠶⠚⠉⡀⢰⣤⢳⠧⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⢿⣷⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⢸⠃⠀⣿⡄⠀⠀⣷⡘⡿⠟⠃⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠠⠀⢸⣀⡀⠟⠉⣟⣛⣿⡴⠶⠛⠋⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠁⠀⠀⠀⣩⣥⡴⠞⠋⠉⠀⠀⣀⣠⣤⣤⣶⣶⣶⣶⣶⠶⠶⢶⣶⣶⣦⣤⣤⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠁⠀⠀⠶⠛⠉⠀⠀⠀⠀⣶⣶⣿⣿⣿⡿⠿⡿⣿⣿⣀⡀⠿⣦⡀⠀⠈⠉⠙⠛⠛⠿⣿⣯⣰⢤⣄⡀⠀⠀⠀⠀⠀⠘⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃⠀⠀⠀⠀⠀⠀⣀⣴⣶⠿⠋⠉⠁⠀⠀⠀⠀⠀⠈⠻⣿⣷⡀⠙⠿⣦⡀⠀⠀⠀⠀⠀⠀⠉⠙⠻⢶⣧⣹⣦⣀⠀⠀⠀⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⢠⣴⠿⡛⣁⡀⠀⠀⠀⠀⢀⣀⡀⠀⠀⠀⠀⠈⠻⣷⡀⠀⠈⠳⡄⠀⠀⠀⠀⢲⡀⠀⠀⠀⠈⠉⠀⠙⣧⡀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⢠⣾⣶⡿⣧⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⠏⠀⠀⠀⠀⠀⢀⣬⣿⡀⠀⠀⠘⢦⡀⠀⢀⣄⠻⣄⠀⠀⠀⠀⠀⠀⠸⠿⣦⡀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⠀⢴⣿⣿⣿⣿⠟⠛⠛⠛⠛⣿⣛⣛⠛⠛⠋⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣦⣀⡀⠈⠻⣷⣌⢻⣷⣭⣑⠀⠀⠀⠸⣦⡀⠀⠸⣧⠀⢿⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⡟⠰⣿⣿⣿⠋⣡⣴⣾⣿⣷⣶⣶⣯⣙⠿⣷⣦⡀⠀⠀⠀⠀⣼⣿⣿⣿⣉⣬⣿⣿⣶⣾⣿⣿⣷⣝⢿⣿⣿⣶⣀⣄⠙⢿⣦⡀⠀⡆⢸⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⡀⢰⣿⣿⣿⠟⣿⣿⣿⣿⣿⣿⣿⣿⣿⣮⣻⡏⠀⠀⠀⠀⠿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣜⠿⢿⣿⣿⣦⣄⠙⣇⣤⣀⣸⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⠿⣿⣿⣟⣻⣿⣿⣿⣿⣟⣿⣿⣶⣀⣤⣄⣀⣰⣿⠟⠹⠿⢯⡿⣿⣿⣿⡿⠿⠿⢿⣿⣿⣷⣌⣻⣿⣿⣿⣿⣿⣿⢉⣛⢿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠈⠉⠉⠉⠉⠉⠉⠉⠉⢻⣿⡿⠛⠛⢿⣿⡏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡈⠙⢿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⠋⢻⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⠇⠀⠀⢸⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⠟⣿⣿⣿⣿⣿⣿⣿⣿⣇⠀⠘⢻⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⠀⢸⣿⣿⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣼⡿⠀⠀⠀⠀⣿⣷⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣼⣿⠀⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⠠⣾⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⡀⢸⣿⣿⣷⡀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣾⣿⢁⣤⣤⣤⣄⡈⢿⣷⡀⠀⠀⠀⠀⠀⠀⠀⢀⢀⣴⣿⠏⠀⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⣰⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣧⠈⣿⣿⣿⣿⣶⣄⣀⣀⣀⣀⣤⣶⡿⠟⠹⣿⣻⣿⣿⣻⣿⡿⠻⢿⣦⣄⣀⡀⢀⣀⣠⣼⣿⡿⠃⠀⠀⣿⣿⣿⣿⣿⣿⡟⢿⣧⣰⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⣿⣿⣿⡆⠉⠛⠛⠛⠛⠛⠛⠉⠀⠀⠀⠉⠉⠛⡿⠉⠁⠀⠀⠀⠉⠛⠛⠿⠿⠿⠛⠋⠁⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣇⣠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⡶⠶⠶⠒⠒⢦⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⣿⣿⣿⣿⣿⣿⣿⢻⣿⣿⡋⠉⠉⠙⠷⢿⣯⡙ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⡀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣾⣥⣤⣤⣶⣶⣶⣦⣽⣷⣶⣤⣴⠆⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⢸⣿⡟⠀⠀⠀⠀⠀⢸⣿⠁ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⠀⠀⠀⠀⠀⠀⠀⠻⠾⠿⠿⠷⠶⢾⣛⠉⠁⠀⢀⣤⡼⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⣼⣿⣿⣿⣿⣿⣿⣿⢸⣿⠁⠀⠀⠀⠀⠀⣾⠃⠀ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣆⠄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠛⠛⠛⠛⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⢿⡿⠀⠀⠀⠀⢀⣾⠃⠀⠀ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣟⣾⠃⠀⠀⠀⢠⡿⠁⠀⠀⠀ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⣿⣿⣿⣿⣿⣿⣿⡿⠃⠀⠀⠀⢨⡟⠀⠀⠀⠀⠀ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣯⠀⠀⠀⠀⢠⡿⠀⠀⠀⠀⠀⠀ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢦⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⣠⡴⠾⠛⠁⠘⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⠟⠁⠀⠀⠀⢀⡞⢀⠄⠀⠀⠀⠀⠀ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠙⣃⠉⠛⠻⠶⣾⣿⣿⣿⣿⣶⣷⡶⠖⠒⠀⠀⠀⠀⠀⠀⣸⣿⣿⣿⣿⣿⡿⠀⠀⠀⠀⠀⡼⠁⡼⠀⠀⠀⠀⠀⠀ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠁⢠⣿⣷⣤⠀⠄⠈⠉⠿⣿⣿⣿⠿⠄⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⠁⠀⠀⠀⠀⣼⠃⡼⠁⠀⠀⠀⠀⠀⠀ ⣿⣿⣿⣿⣿⣿⣿⡿⣿⣿⣿⣾⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⢸⣿⣿⣿⣧⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⠇⠀⠀⠀⠀⢰⠇⡼⠁⠀⠀⠀⠀⠀⠀⠀ ⣿⣿⣿⣿⣿⣿⢋⣴⣿⣭⣭⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠈⣿⣿⣿⣿⣧⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠐⣴⣿⣿⣿⣿⡟⠀⠀⠀⠀⢰⡟⠸⠁⠀⠀⠀⠀⠀⠀⠀⠀ ⣿⣿⣿⣿⠟⣡⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⠀⠀⠙⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡴⢆⣠⣾⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⣸⡇ */ #include <bits/stdc++.h> using namespace std; #define fo(i, a, n) for (i = a; i < n; i++) #define ll long long #define si(x) scanf("%d", &x) #define sl(x) scanf("%lld", &x) #define ss(s) scanf("%s", s) #define pi(x) printf("%d\n", x) #define pl(x) printf("%lld\n", x) #define ps(s) printf("%s\n", s) #define deb(x) cout << #x << "=" << x << endl #define deb2(x, y) cout << #x << "=" << x << "," << #y << "=" << y << endl #define pb push_back #define mp make_pair #define fi first #define se second #define all(x) x.begin(), x.end() #define clr(x) memset(x, 0, sizeof(x)) #define sortall(x) sort(all(x)) #define tr(it, a) for (auto it = a.begin(); it != a.end(); it++) #define PI 3.1415926535897932384626 typedef pair<int, int> pii; typedef pair<ll, ll> pl; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<pii> vpii; typedef vector<pl> vpl; typedef vector<vi> vvi; typedef vector<vl> vvl; ///////////////////////////////////////////////////////////////////////////////////////// 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) #else #define debug(x...) #endif ////////////////////////////////////////CONST//////////////////////////////////////////// const int mod = 1'000'000'007; const int N = 3e5, M = N; ///////////////////////////////////////FUNCTION////////////////////////////////////////// int mpow(int base, int exp) { base %= mod; int result = 1; while (exp > 0) { if (exp & 1) result = ((ll)result * base) % mod; base = ((ll)base * base) % mod; exp >>= 1; } return result; } ll mod_mul(ll a, ll b, ll m) { a = a % m; b = b % m; return (((a * b) % m) + m) % m; } int ncr(int n, int r) { vector<int> c(n + 1); c[0] = 1; for (int i = 1; i <= n; i++) { for (int j = min(i, r); j > 0; j--) { c[j] = (c[j] + c[j - 1]) % mod; } } return c[r]; } ///////////////////////////////////////////////CODE//////////////////////////////////////////////////////////////////////// void solve() { int n, k; cin >> n >> k; vector<string> vec(n); unordered_map<string, int> mpp; for (int i = 0; i < n; i++) { cin >> vec[i]; mpp[vec[i]]++; } int count = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { string s = ""; for (int z = 0; z < k; z++) { if (vec[i][z] == vec[j][z]) s += vec[i][z]; else { if (vec[i][z] == 'S' && vec[j][z] == 'E' || vec[i][z] == 'E' && vec[j][z] == 'S') s += 'T'; if (vec[i][z] == 'S' && vec[j][z] == 'T' || vec[i][z] == 'T' && vec[j][z] == 'S') s += 'E'; if (vec[i][z] == 'T' && vec[j][z] == 'E' || vec[i][z] == 'E' && vec[j][z] == 'T') s += 'S'; } } /* debug(s); */ if (mpp[s]) { count++; } mpp[vec[j]]--; } for (int t = i + 1; t < n; t++) mpp[vec[t]]++; mpp[vec[i]]--; } cout << count; } int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); int t = 1; /* cin >> t; */ while (t--) { solve(); } return 0; }
cpp
1307
A
A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. Next 2t2t lines contain a description of test cases  — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100)  — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3 4 5 1 0 3 2 2 2 100 1 1 8 0 OutputCopy3 101 0 NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11: On day one, move a haybale from pile 33 to pile 22 On day two, move a haybale from pile 33 to pile 22 On day three, move a haybale from pile 22 to pile 11 On day four, move a haybale from pile 22 to pile 11 On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.
[ "greedy", "implementation" ]
#include <bits/stdc++.h> using namespace std; int t,n,a[105],d; int main() { cin >> t; while (t--){ cin >> n >> d; for (int i=1; i<=n; ++i){ cin >> a[i]; } while (d--){ for (int i=2; i<=n; ++i){ if (a[i] > 0){ ++a[i-1]; --a[i]; break; } } } cout << a[1] << endl; } }
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> #define sys ios_base::sync_with_stdio(0);cin.tie(0); #define mod 1000000007 using namespace std; //#pragma comment(linker, "/STACK:268435456"); #define count_setbits(n) __builtin_popcount(n) #define fixed cout<<fixed<<setprecision(16) #define count_bits(n) ((ll)log2(n))+1 #define no_of_digits(n) ((ll)log10(n))+1 #define str string #define c(itretor) cout<<itretor #define cp(itretor) cout<<setprecision(itretor) #define cys cout<<"YES"<<endl #define cno cout<<"NO"<<endl #define endl "\n" #define imx INT_MAX #define imn INT_MIN #define lmx LLONG_MAX #define lmn LLONG_MIN #define ll long long #define f(i,l,r) for(long long i=l;i<r;++i) #define fr(i,r,l) for(long long i=r-1;i>=l;--i) #define vi vector<int> #define vs vector<string> #define vll vector <long long> #define mii map<int,int> #define mll map<long long,long long> #define pll pair<ll,ll> #define tsolve long long t;cin>>t; while(t--) solve(); #define inp(x) for(auto &i:x) cin>>i; #define all(x) x.begin(),x.end() #define pb push_back #define ff first #define ss second #define print(x) for(auto i:x) cout<<i<<" "; #define pprint(x) for(auto [i,j]:x) cout<<i<<" "<<j #define dbg1(x) cout << #x << "= " << x << endl; #define dbg2(x,y) cout << #x << "= " << x << " " << #y << "= " << y <<endl; #define dbg3(x,y,z) cout << #x << "= " << x << " " << #y << "= " << y << " " << #z << "= " << z << endl; #define dbg4(x,y,z,w) cout << #x << "= " << x << " " << #y << "= " << y << " " << #z << "= " << z << " " << #w << "= " << w << endl; //const ll N=2e5; //vector<bool> isprime(N+1,1); //inline void sieve(){ isprime[0]=isprime[1]=1; for(int i=2;i<=N;i++) if(isprime[i]) for(int j=i*i;j<=N;j+=i) isprime[j]=false;} inline vector<ll> get_factors(ll n) { vector<ll> factors; if(n==0) return factors; for(ll i=1;i*i<=n;++i){ if(n%i==0){factors.push_back(i); if(i!=n/i) factors.push_back(n/i);}} return factors;} inline ll modpower(ll a, ll b, ll m = mod) { ll ans = 1; while (b) { if (b & 1) ans = (ans * a) % m; a = (a * a) % m; b >>= 1; } return ans; } inline ll mod_inverse(ll x,ll y) { return modpower(x,y-2,y); } inline ll max_ele(ll * arr ,ll n) { ll max=*max_element(arr,arr+n); return max;} inline ll max_i(ll * arr,ll n){ return max_element(arr,arr+n)-arr+1; } inline void solve() { str s; cin>>s; vll a(26 , 0) ; for(auto I:s) a[I-'a']++; ll dp[26][26],sdp[26]; memset(dp,0,sizeof(dp)); memset(sdp,0,sizeof(sdp)); ll n=s.size(); f(i,0,n){ f(j,0,26){ dp[j][s[i]-'a']+=sdp[j]; } ++sdp[s[i]-'a']; } ll ans=*max_element(sdp,sdp+26); f(i,0,26){ f(j,0,26) ans =max(ans,dp[i][j]); } c(ans)<<endl; } int main() { sys; #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif solve(); 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> #define f(i,x,y) for(int i=x, i##end=y; i<=i##end; ++i) #define d(i,x,y) for(int i=y, i##end=x; i>=i##end; --i) #define uf(i,x,y) for(int i=x, i##end=y; i<i##end; ++i) #define ll long long #define pir pair<int, int> #define fir first #define sec second #define mp make_pair #define pb push_back #define int long long char ch; int rd() { int f=1, x=0; ch=getchar(); while(!isdigit(ch)) { f=((ch=='-')?-1:f); ch=getchar(); } while(isdigit(ch)) { x=x*10+ch-'0'; ch=getchar(); } return x*f; } void rd(int& x) { x=rd(); } using namespace std; int sg[300005][3], sgT; const int lim = 1005; ll a[300005], st; int mex(int x, int y, int z) { if(x > y) swap(x, y); if(x > z) swap(x, z); if(y > z) swap(y, z); if(x == 0 && y == 1 && z == 2) return 3; else if(x == 0 && y == 0 && z == 1) return 2; else if(x == 0 && y == 1) return 2; else if(x == 0) return 1; else return 0; // if(x != 0) return 0; // else { // if(y != 1) return 1; // else if(z != 2) return 2; // else return 3; // } } int mex(int a, int b) { if(a > b) swap(a, b); if(a == 0 && b == 1) return 2; else if(a == 0) return 1; else return 0; // if(a != 0) return 0; // else { // if(b != 1) return 1; // else return 2; // } } int gainsg(ll v, int state) { if(v < st) return sg[v][state]; return sg[( v - st ) % sgT + st][state]; // return sg[v][state]; } int lcm(int a, int b) { return a*b/__gcd(a, b); } int lcm(int x, int y, int z) { // f(i,1,100) if((i % x == 0) && (i % y == 0) && (i % z == 0)) return i; // assert(0); return -1; return lcm(x, lcm(y, z)); } int chk(int pos) { f(i,0,sgT-1) if(sg[pos+i][0] != sg[pos+i+sgT][0]) return 0; return 1; } void solve() { int n=rd(), x=rd(), y=rd(), z=rd(); sg[0][0] = sg[0][1] = sg[0][2] = 0; // cerr << "# " << x << ' ' << y << ' ' << z << endl; f(i,1,lim) { sg[i][0] = mex(sg[max(i-x, 0LL)][0], sg[max(i-y, 0LL)][1], sg[max(i-z, 0LL)][2]); sg[i][1] = mex(sg[max(i-x, 0LL)][0], sg[max(i-z, 0LL)][2]); sg[i][2] = mex(sg[max(i-x, 0LL)][0], sg[max(i-y, 0LL)][1]); // cerr << i << ' ' << sg[i][0] << ' ' << sg[i][1] << ' ' << sg[i][2] << endl; } // sgT = x * y * z; f(len,12,60) { sgT = len; st = -1; f(i,sgT,lim - sgT) if(chk(i)) { st = i; goto OPT; } } // OPT : cerr << "sgt = " << sgT << " st = " << st << endl; OPT : int ALLSG = 0; ll ans = 0; f(i,1,n) cin >> a[i]; f(i,1,n) ALLSG ^= gainsg(a[i], 0); // f(i,1,n) ALLSG ^= sg[a[i]][0]; // cerr << ALLSG << endl; f(i,1,n) { // int nowsg = ALLSG ^ gainsg(a[i], 0) ^ gainsg(max(a[i] - (t == 0 ? x : (t == 1 ? y : z)), 0LL), t); int nowsg0 = ALLSG ^ gainsg(a[i], 0) ^ gainsg(max(a[i] - x, 0LL), 0); int nowsg1 = ALLSG ^ gainsg(a[i], 0) ^ gainsg(max(a[i] - y, 0LL), 1); int nowsg2 = ALLSG ^ gainsg(a[i], 0) ^ gainsg(max(a[i] - z, 0LL), 2); // cerr << "ok " << i << ' ' << t << ' ' << nowsg << ' ' << (max(a[i] - (t == 0 ? x : (t == 1 ? y : z)), 0LL)) << endl; if(nowsg0 == 0) ++ans; if(nowsg1 == 0) ++ans; if(nowsg2 == 0) ++ans; } cout << ans << endl; } signed main() { int t=rd(); while(t--) solve(); return 0; }
cpp
1305
F
F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105)  — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012)  — the elements of the array.OutputPrint a single integer  — the minimum number of operations required to make the array good.ExamplesInputCopy3 6 2 4 OutputCopy0 InputCopy5 9 8 7 3 1 OutputCopy4 NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.
[ "math", "number theory", "probabilities" ]
#include<bits/stdc++.h> using namespace std; #define int long long const int N=2e5+5; int n; int a[N]; set<int>s; inline void Solve(int x) { for(int i=2;i*i<=x;i++) { if(x%i==0) { s.insert(i); while(x%i==0)x/=i; } } if(x>1)s.insert(x); } signed main() { mt19937 rnd(time(0)); ios::sync_with_stdio(0); cin.tie(0),cout.tie(0); cin>>n; for(int i=1;i<=n;i++)cin>>a[i]; for(int i=1;i<=40;i++) { int p=rnd()%n+1; Solve(a[p]); Solve(a[p]+1); if(a[p]>1)Solve(a[p]-1); } int ans=0x3f3f3f3f3f3f3f3f; for(auto x:s) { int res=0; for(int i=1;i<=n;i++) res+=(a[i]<=x?x-a[i]:min(a[i]%x,x-a[i]%x)); ans=min(ans,res); } cout<<ans<<'\n'; 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: 102598786 #include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 100000 + 10; int n, lim, a[N], vis[N]; vector<int> vec, d[N]; int cnt[N], sta[N], top; int p[N], v[N], mu[N], pcnt = 0; void init(int n) { mu[1] = 1; for (int i = 2; i <= n; ++i) { if (!v[i]) p[++pcnt] = i, mu[i] = -1; for (int j = 1; j <= pcnt && i * p[j] <= n; ++j) { v[i * p[j]] = 1; if (i % p[j]) mu[i * p[j]] = -mu[i]; else break; } } for (int i = 1; i <= n; ++i) for (int j = i; j <= n; j += i) d[j].push_back(i); } int main() { init(1e5); cin >> n; for (int i = 1; i <= n; ++i) cin >> a[i], lim = max(lim, a[i]), ++vis[a[i]]; ll ans = 0; for (int g = 1; g <= lim; ++g) { vec.clear(); for (int i = g; i <= lim; i += g) for (int j = 1; j <= vis[i]; ++j) vec.push_back(i / g); sort(vec.begin(), vec.end(), greater<int>()); for (int i : vec) { int s = 0; for (int j : d[i]) s += mu[j] * cnt[j]; while (s) { int x = sta[top--]; if (__gcd(i, x) == 1) ans = max(ans, 1ll * g * i * x), --s; for (int j : d[x]) --cnt[j]; } sta[++top] = i; for (int j : d[i]) ++cnt[j]; } while (top) { int x = sta[top--]; for (int i : d[x]) --cnt[i]; } } cout << ans; }
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; int main(){ int t; cin>>t; while(t--){ string s1,s2,s3; cin>>s1>>s2>>s3; int cnt=0; for(int i=0;i<s1.size();i++){ swap(s1[i],s3[i]); if(s1[i]==s2[i])cnt++; else{ swap(s1[i],s3[i]); swap(s2[i],s3[i]); if(s1[i]==s2[i])cnt++; } } if(cnt==s1.size()) cout<<"yes"<<endl; else cout<<"no"<<endl; } }
cpp
1324
F
F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 OutputCopy2 2 2 2 2 1 1 0 2 InputCopy4 0 0 1 0 1 2 1 3 1 4 OutputCopy0 -1 1 -1 NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33.
[ "dfs and similar", "dp", "graphs", "trees" ]
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #define FORI(start, stop, step) for(int i = start; (step > 0) ? (i < stop) : (i >= stop); i += step) #define FORJ(start, stop, step) for(int j = start; (step > 0) ? (j < stop) : (j >= stop); j += step) #define FORK(start, stop, step) for(int k = start; (step > 0) ? (k < stop) : (k >= stop); k += step) #define FOR(i, start, stop, step) for(int i = start; (step > 0) ? (i < stop) : (i >= stop); i += step) #define MODULO 1000000007 #define PI 3.14159265358979323846 #define nl '\n' #define YES "YES" #define NO "NO" #define all(arr) arr.begin(), arr.end() using namespace std; using namespace __gnu_pbds; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef unsigned long long ull; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> indexed_set; bool isPrime(int n){if(n<2) return false;for(int i=2;i*i<=n;i++){if(n%i==0) return false;}return true;} ll mod(ll a, ll b){ll r=a%b;return r>=0?r:r+abs(b);} int gcd(int a, int b){if(b==0)return a; return gcd(b,mod(a, b));} int lcm(int a, int b){return a/gcd(a, b)*b;} ll powmod(ll n,ll p,ll m){if(p==0)return 1%m;ll u=powmod(n,p/2,m);u=(u*u)%m;if(p%2==1)u=(u*n)%m;return u;} int n; vector<int> vals; vector<vector<int>> adj; vector<int> dp; vector<int> ans; void get_dp_dfs(int u, int e) { for(int v : adj[u]) { if(v == e) continue; get_dp_dfs(v, u); } dp[u] = vals[u] == 0 ? -1 : 1; for(int v : adj[u]) { if(v != e && dp[v] > 0) dp[u] += dp[v]; } } void get_solutions_for_all(int u, int e) { int d = dp[u]; ans[u] = vals[u] == 0 ? -1 : 1; for(int v : adj[u]) if(dp[v] > 0) ans[u] += dp[v]; for(int v : adj[u]) { if(v == e) continue; dp[u] = dp[v] > 0 ? ans[u] - dp[v] : ans[u]; get_solutions_for_all(v, u); } dp[u] = d; } void solve() { cin >> n; vals = vector<int>(n+1); FORI(1, n+1, 1) cin >> vals[i]; adj = vector<vector<int>>(n+1, vector<int>()); dp = vector<int>(n+1); ans = vector<int>(n+1); FORI(0, n-1, 1) { int u, v; cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); } get_dp_dfs(1, 0); get_solutions_for_all(1, 0); //FORI(1, n+1, 1) cout << dp[i] << ' '; //cout <<nl; FORI(1, n+1, 1) cout << ans[i] << ' '; cout << nl; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); solve(); return 0; }
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" ]
/********************************* * Author -> Puspendra yadav * **********************************/ #include<bits/stdc++.h> using namespace std; #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; #define idx(x) find_by_order(x) #define less_then(x) order_of_key(x) template<class T> using pbds = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update> ; #define int long long int #define endl '\n' #define all(a) (a).begin(),(a).end() #define mod 1000000007 /************************************************************/ #ifndef ONLINE_JUDGE #define debug(x) cerr << #x <<" "; _print(x); cerr << endl; #else #define debug(x) #endif void _print(int t) {cerr << t;} void _print(string t) {cerr << t;} void _print(char t) {cerr << t;} void _print(double t) {cerr << t;} void _print(float 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.first); cerr << ","; _print(p.second); 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 solve() { string s; cin >> s; int n = s.size(); map<char, int> mp; map<int, int> m; for (auto &i : s) m[i]++; for (char ch = 'a'; ch <= 'z'; ch++) { mp[ch] = 0; } vector<vector<int>> a(26 , vector<int>(n , 0)); for (int i = 0; i < n; i++) { mp[s[i]]++; for (int j = 0; j < 26; j++) { a[j][i] = mp[j + 'a']; } } int maxi = 0; for (char firstch = 'a'; firstch <= 'z'; firstch++) { for (char secondch = 'a'; secondch <= 'z'; secondch++) { // if (firstch == secondch) continue; vector<int> l = a[firstch - 'a']; vector<int> r = a[secondch - 'a']; int currSum = 0; for (int i = 0; i < n; i++) { if (s[i] == firstch) { currSum += (r[n - 1] - r[i]); } } maxi = max(maxi , currSum); } } for (auto &i : m) maxi = max(maxi , i.second); vector<int> temp; for (char ch = 'a'; ch <= 'z'; ch++) { vector<int> temp; for (int i = 0; i < n; i++) { if (s[i] == ch) { int j = i; while (j < n and s[i] == s[j]) { j++; } temp.push_back(j - i); maxi = max(maxi , ((j - i) * (j - i - 1)) / 2); i = j - 1; } } sort(all(temp)); if (temp.size() > 1) { maxi = max(maxi , temp[temp.size() - 1] * temp[temp.size() - 2]); } } cout << maxi << endl; } main() { ios_base::sync_with_stdio(false); cin.tie(0); #ifndef ONLINE_JUDGE freopen("Error.txt", "w", stderr); #endif int t = 1; // cin >> t; while (t--) { solve(); } return 0; /* Sorting using cmp --> return boolen in which order order you want to Sort using pbds using only less --> normal set using less_equal --> lower_bound gives result like upper bound in multiset and vice versa eg -> for in desecnding order --> return (a > b); */ }
cpp
1320
B
B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9 1 5 5 4 1 2 2 3 3 4 4 1 2 6 6 4 4 2 4 1 2 3 4 OutputCopy1 2 InputCopy7 7 1 2 2 3 3 4 4 5 5 6 6 7 7 1 7 1 2 3 4 5 6 7 OutputCopy0 0 InputCopy8 13 8 7 8 6 7 5 7 4 6 5 6 4 5 3 5 2 4 3 4 2 3 1 2 1 1 8 5 8 7 5 2 1 OutputCopy0 3
[ "dfs and similar", "graphs", "shortest paths" ]
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #define MOD 1000000007 using namespace std; using namespace __gnu_pbds; template <class T> using Tree = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; //priority_queue <int, vector<int>, greater<int>> q; queue <int> q; vector <int> v[200005], iv[200005]; int viz[200005], d[200005], path[200005], minn, maxx, k; void bfs(int nod){ q.push(nod); d[nod] = 1; while(!q.empty()){ int x = q.front(); q.pop(); for(auto& y: iv[x]){ if(d[y] == 0){ d[y] = d[x] + 1; q.push(y); } } } } void solve(int i){ if(i < k){ int nr = 0, nod = path[i]; bool ok = false; for(auto& x: v[nod]){ if(d[x] == d[nod] - 1){ nr++; if(x == path[i + 1]) ok = true; } } if(ok == false) minn++, maxx++; else if(nr > 1) maxx++; solve(i + 1); } } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n, m; cin >> n >> m; for(int i = 1; i <= m; i++){ int x, y; cin >> x >> y; iv[y].push_back(x); v[x].push_back(y); } cin >> k; for(int i = 1; i <= k; i++){ cin >> path[i]; } bfs(path[k]); solve(1); cout << minn << " " << maxx; 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" ]
/* It is code Zhanabergen Abdurroshid :)))) */ #include<bits/stdc++.h> #define ll long long #define int ll #define m_p make_pair #define p_b push_back #define pii pair<int,int> #define piii pair<int,pii> #define vi vector<ll> #define vii vector<pii> #define viii vector<pair<int,pii> > #define si set<int> #define sii set<pii> #define siii set<pair<int,pii> > #define F first #define S second #define pre precision #define n_per next_permutation #define sz size() #define RUN ios_base::sync_with_stdio(false);cin.tie(0); #define OPEN freopen("unionday.in","r",stdin);freopen("unionday.out","w",stdout) using namespace std; ll fl(){ ll a; cin>>a; return a; } const ll N = 5e5 + 9, INF = 2e18 + 9, MOD = 1e9 + 7; int check(vi v){ for(int i=0;i<v.sz;i++){ for(int j=i+1;j<v.sz;j++){ for(int h=j+1;h<v.sz;h++){ if(v[i]<=v[j]&&v[j]<=v[h]){ return 0; } if(v[i]>=v[j]&&v[j]>=v[h]){ return 0; } } } } return 1; } main(){ RUN; int ti = fl(); while(ti--){ int n = fl(), m = fl(); int all = n*(n+1)/2; int ost = n-m; int b = ost%(m+1); int a = m+1-b; int len = ost/(m+1); cout<<all-(a*(len*(len+1)/2))-(b*((len+1)*(len+2)/2)); cout<<'\n'; } 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> using namespace std; long long n,m,nt[1000006],f[2][500005],sz[2][500005],ans; vector<long long> vec[500005]; char a[500005],b[500005],c[1000006]; inline void add(long long op,long long u,long long w){for(long long i=u;i<=n;i+=(i&(-i))) sz[op][i]+=w;} inline long long qry(long long op,long long u) { long long sum=0; for(long long i=u;i>0;i-=(i&(-i))) sum+=sz[op][i]; return sum; } int main() { scanf("%lld%lld%s%s%s",&n,&m,a+1,b+1,c+1),a[n+1]=b[n+1]='$',c[m+1]='!'; for(long long i=1;i<=m+1;++i) if(c[i]!=c[i+1]){nt[2]=i-1;break;} for(long long i=3,p=nt[2],p0=2;i<=m+1;++i) { if(i>p) { for(long long j=1;j<=m+1;++j) if(c[j]!=c[i+j-1]){nt[i]=j-1;break;} p=i+nt[i]-1,p0=i; } else if(i+nt[i-p0+1]-1>=p) { for(long long j=p+1;j<=m+1;++j) if(c[j]!=c[j-i+1]){nt[i]=j-i;break;} p=i+nt[i]-1,p0=i; } else nt[i]=nt[i-p0+1]; } for(long long i=1;i<=n+1&&i<=m+1;++i) if(c[i]!=a[i]){f[0][1]=i-1;break;} for(long long i=2,p=f[0][1],p0=1;i<=n;++i) { if(i>p) { for(long long j=1;j<=m+1&&i+j-1<=n+1;++j) if(c[j]!=a[i+j-1]){f[0][i]=j-1;break;} p=i+f[0][i]-1,p0=i; } else if(i+nt[i-p0+1]-1>=p) { for(long long j=p+1;j<=n+1&&j-i+1<=m+1;++j) if(a[j]!=c[j-i+1]){f[0][i]=j-i;break;} p=i+f[0][i]-1,p0=i; } else f[0][i]=nt[i-p0+1]; } reverse(c+1,c+1+m),reverse(b+1,b+1+n); for(long long i=1;i<=m+1;++i) if(c[i]!=c[i+1]){nt[2]=i-1;break;} for(long long i=3,p=nt[2],p0=2;i<=m+1;++i) { if(i>p) { for(long long j=1;j<=m+1;++j) if(c[j]!=c[i+j-1]){nt[i]=j-1;break;} p=i+nt[i]-1,p0=i; } else if(i+nt[i-p0+1]-1>=p) { for(long long j=p+1;j<=m+1;++j) if(c[j]!=c[j-i+1]){nt[i]=j-i;break;} p=i+nt[i]-1,p0=i; } else nt[i]=nt[i-p0+1]; }//cout<<nt[3]<<endl; for(long long i=1;i<=n+1&&i<=m+1;++i) if(c[i]!=b[i]){f[1][1]=i-1;break;} for(long long i=2,p=f[1][1],p0=1;i<=n;++i) { if(i>p) { for(long long j=1;j<=m+1&&i+j-1<=n+1;++j) if(c[j]!=b[i+j-1]){f[1][i]=j-1;break;} p=i+f[1][i]-1,p0=i; } else if(i+nt[i-p0+1]-1>=p) {//cout<<i<<" "<<p<<endl; for(long long j=p+1;j<=n+1&&j-i<=m;++j) if(b[j]!=c[j-i+1]){f[1][i]=j-i;break;} p=i+f[1][i]-1,p0=i; } else f[1][i]=nt[i-p0+1];//cout<<i<<" "<<f[1][i]<<endl; } reverse(f[1]+1,f[1]+1+n); for(long long i=1;i<=n;++i) {//cout<<i<<" "<<f[0][i]<<endl; vec[i-1].push_back(-max(m-f[0][i],1ll)); vec[min(n,i+m-2)].push_back(max(m-f[0][i],1ll)); } for(long long i=1;i<=n;++i) {//cout<<i<<" "<<f[1][i]<<endl; long long len=vec[i].size(); add(0,n-f[1][i]+1,1),add(1,n-f[1][i]+1,min(f[1][i],m-1));//cout<<i<<endl;//cout<<qry(0,4)<<" "<<qry(0,3)<<endl; for(long long j=0;j<len;++j) {//cout<<vec[i][j]<<endl; long long u=abs(vec[i][j]),tmp=qry(1,n-u+1)-(u-1)*qry(0,n-u+1);//cout<<i<<" "<<u<<" "<<qry(0,n-u+1)<<" "<<qry(1,n-u+1)<<endl; if(vec[i][j]<0) ans-=tmp; else ans+=tmp; }//cout<<i<<" "<<ans<<endl; } printf("%lld",ans); }
cpp
1313
A
A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors.
[ "brute force", "greedy", "implementation" ]
#include<bits/stdc++.h> using namespace std; typedef long long int ll; typedef float ff; typedef vector<long long int> vi; #define all(x) (x).begin(),(x).end() #define rall(x) (x).rbegin(),(x).rend() #define sz(x) (int)x.size() #define pb(x) push_back(x) #define endl "\n" void solve(){ vector <int> a(3); cin>>a[0]>>a[1]>>a[2]; sort(a.rbegin(), a.rend()); int sum = 0; if(a[0] > 0){ sum += 1; a[0] -= 1; } if(a[1] > 0){ sum += 1; a[1] -= 1; } if(a[2] > 0){ sum += 1; a[2] -= 1; } if(a[0] > 0 && a[1] > 0){ sum += 1; a[0] -= 1; a[1] -= 1; } if(a[1] > 0 && a[2] > 0){ sum += 1; a[1] -= 1; a[2] -= 1; } if(a[2] > 0 && a[0] > 0){ sum += 1; a[0] -= 1; a[2] -= 1; } if(a[0] > 0 && a[1] > 0 && a[2] > 0){ sum += 1; a[0] -= 1; a[1] -= 1; a[2] -= 1; } cout << sum << endl; } int main(){ #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int t; cin>>t; while(t--) solve(); return 0; }
cpp
1294
A
A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.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 new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5 5 3 2 8 100 101 102 105 3 2 1 100000000 10 20 15 14 101 101 101 3 OutputCopyYES YES NO NO YES
[ "math" ]
#include <bits/stdc++.h> using namespace std; int main() { int q; cin >> q; for (int i = 0; i < q; ++i) { int a[3], n; cin >> a[0] >> a[1] >> a[2] >> n; sort(a, a + 3); n -= 2 * a[2] - a[1] - a[0]; if (n < 0 || n % 3 != 0) { cout << "NO" << endl; } else { cout << "YES" << endl; } } return 0; }
cpp
1311
B
B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.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.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6 3 2 3 2 1 1 2 4 2 4 1 2 3 3 2 5 1 1 2 3 4 5 1 4 2 2 1 4 3 1 3 4 2 4 3 2 1 1 3 5 2 2 1 2 3 3 1 4 OutputCopyYES NO YES YES NO YES
[ "dfs and similar", "sortings" ]
#include<bits/stdc++.h> using namespace std; #define ll long long //#define ld long double #define vv vector<ll> #define T ll ttt;cin>>ttt;while(ttt--) #define all(x) (x).begin(),(x).end() #define rall(x) (x).rbegin(),(x).rend() #define mod 1000000007 #define pb emplace_back #define eeq <<"\n"; #define PI 3.14159265359 #define f0r(a, b) for (long long a = 0; a < (b); ++a) #define f1r(a, b) for (long long a = 1; a <= (b); ++a) #define f11r(a, b) for (long long a = b-1; a > 0; --a) #define mp make_pair void ELZOZ(){ ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);} //ابدا بالصلاه ع النبي اللهم صلي وسلم علي سيدنا محمد //-----START-----// void solve() { ll n, m; cin >> n >> m; ll arr1[n]; map<ll, ll> freq; f0r(i, n) cin >> arr1[i]; f0r(i, m) { ll a; cin >> a; freq[a]++; } f0r(i, n) { f0r(j, n - 1) { if (arr1[j] > arr1[j + 1]) { if (!freq[j + 1]) break; else swap(arr1[j], arr1[j + 1]); } } } if (is_sorted(arr1, arr1 + n)) cout << "YES" eeq else cout << "NO" eeq } int main() { //freopen("lazy.in", "r", stdin); // memset(dp, -1, sizeof(dp)); ELZOZ(); // <---*---*---*---*---*{*}****--0 T{ solve(); } }
cpp
1296
A
A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — 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≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5 2 2 3 4 2 2 8 8 3 3 3 3 4 5 5 5 5 4 1 1 1 1 OutputCopyYES NO YES NO NO
[ "math" ]
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; for(int i=0;i<n;i++){ int even = 0,odd = 0; // vector<int> arr; int m; cin >> m; for(int j=0;j<m;j++){ int num; cin >> num; // arr.push_back(num); if(num & 1) odd++; else even++; } if(odd & 1) cout << "YES" << endl; else{ if(odd == 0 || even == 0 ) cout << "NO" << endl; else cout << "YES" << endl; } } }
cpp
1325
E
E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3 1 4 6 OutputCopy1InputCopy4 2 3 6 6 OutputCopy2InputCopy3 6 15 10 OutputCopy3InputCopy4 2 3 5 7 OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence.
[ "brute force", "dfs and similar", "graphs", "number theory", "shortest paths" ]
#include <bits/stdc++.h> using namespace std; #define pb emplace_back const int MN=1e6+3; int N, at=170, dist[MN], ans = MN; bool pvis[1001], vis[MN]; set<int> start; vector<int> prime, vals, adj[MN]; queue<pair<int, pair<int, int> > > next1; // (distance, (node, parent)) void bfs(int j){ memset(vis, 0, sizeof(vis)); next1.push({0, {j, j}}); while (!next1.empty()) { int d = next1.front().first; int x = next1.front().second.first; int p = next1.front().second.second; next1.pop(); if (vis[x]) continue; vis[x]=1; dist[x] = d; bool skip=0; for (int i: adj[x]) if (i != p || skip) { if (vis[i]) ans = min(ans, dist[i] + dist[x] + 1); else next1.push({d + 1, {i, x}}); } else skip = 1; } adj[j].clear(); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); prime.reserve(170); prime.push_back(1); for(int i=2;i<=1e3;i++) { if(pvis[i]) continue; prime.pb(i); for(int j=i*i;j<=1e3;j+=i) pvis[j]=1; } cin >> N; int x; for (int i=0; i<N; i++) { vals.clear(); cin >> x; for (int j=1; j<prime.size() && prime[j] * prime[j] <= x; j++) { int cnt = 0; while (x%prime[j] == 0) { x /= prime[j]; cnt++; } if (cnt%2 == 1) vals.pb(prime[j]); } if (vals.empty() && x == 1) { cout << 1 <<'\n'; return 0; } vals.push_back(x); int a=vals.front(); int b=(vals.size() == 1? 1 : vals.back()) ; adj[a].pb(b); adj[b].pb(a); } for (int x:prime) if(!adj[x].empty()) bfs(x); cout << (ans == MN ? -1 : ans) <<'\n'; }
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: 101638026 #include<bits/stdc++.h> using namespace std; typedef long long ll; const int N=1e5+5; ll n,m,ans; ll mark[N],miu[N],v[N],cnt[N]; vector<ll> factors[N],primes; inline void Mobius(ll n) { miu[1]=1; for(ll i=2; i<=n; i++) { if(!v[i]) { primes.push_back(i); miu[i]=-1; } for(ll j=0; i*primes[j]<=n; j++) { ll t=i*primes[j]; v[t]=1; if(i%primes[j]==0) { miu[t]=0; break; } miu[t]=-miu[i]; } } } inline ll gcd(ll a,ll b) { return b?gcd(b,a%b):a; } inline ll sum(ll x) { ll res=0; for(ll i=0; i<factors[x].size(); i++) res+=cnt[factors[x][i]]*miu[factors[x][i]]; return res; } inline void add(ll x,ll y) { for(ll i=0; i<factors[x].size(); i++) cnt[factors[x][i]]+=y; } int main() { scanf("%lld",&n); for(ll i=1; i<=n; i++) { ll x; scanf("%lld",&x); mark[x]=1; m=max(m,x); } ans=m; for(ll i=1; i<=m; i++) for(ll j=i; j<=m; j+=i) factors[j].push_back(i); Mobius(m); for(ll r=1; r<=m; r++) { stack<ll> used; for(ll x=m/r; x>0; x--) { if(!mark[x*r]) continue; ll nums=sum(x); while(nums) { if(gcd(x,used.top())==1) { ans=max(ans,x*used.top()*r); nums--; } add(used.top(),-1); used.pop(); } used.push(x); add(used.top(),1); } while(!used.empty()) { add(used.top(),-1); used.pop(); } } printf("%lld\n",ans); 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> #define ll long long #define lpi(x,n) for(int i=x;i<n;++i) #define lpj(x,n) for(int j=x;j<n;++j) #define S second #define F first #define all(x) x.begin(),x.end() #define sorterase(v) {sort(v.begin(),v.end());v.erase(unique(v.begin(),v.end()),v.end());} #define pb push_back #define pf push_front #define R return #define endl '\n' using namespace std; /* ** ** 22222222 **** ** 22222222 ** ** ** 222 ** ** ** ** 222 ** ** ** ** 22222222 ************ **** 22 ************** **** 22 ** ** ** ** 22222222 ** ** ** ** 22222222 */ //------------------------------------------------ void sieveprime(int n,bool prime[]){ memset(prime,true,n); for (int p=2;p*p<=n;p++) { if(prime[p]==true) { for(int i=p*p;i<=n;i+=p) prime[i]=false; } } } //------------------------------------------------ ll gcd(ll a,ll b){ if(b==0) R a; R gcd(b,a%b); } //------------------------------------------------ ll lcm(ll a,ll b){ ll g = gcd(a,b); R a*b/g; } //------------------------------------------------ ll Pow(ll x,ll y){ if(y==1) R x; if(y==0) R 1; ll ret=pow(x,y/2); ret*=ret; if(y%2) ret*=x; R ret; } //------------------------------------------------ bool isPrime(ll x){ if (x<=1) R false; for(ll i=2;i<=sqrt(x);i++) if (x%i==0) R false; R true; } //------------------------------------------------ ll sqrt(ll x){ ll l=1,r=1e9+9,res=1; while(l<=r){ ll m=(l+r)>>1; if(m*m>x) r=m-1; else { l=m+1; res=m; } } R res; } //------------------------------------------------ ll mod(ll m,ll n){ ll x=(m%n+n)%n; R x; } //------------------------------------------------ ll fact(ll n){ if(n==0) R 1; ll res=1; for(int i=2;i<=n;i++) res=res*i; R res; } //------------------------------------------------ ll ncr(ll n,ll r){ ll x=fact(n)/(fact(r)*fact(n-r)); R x; } void AK2000YY(){ ll n,s,k,ans=1e9,j=0; bool can=0; cin>>n>>s>>k; vector <ll> v(k); lpi(0,k){ cin>>v[i]; if(v[i]==s) can=1; } sort(all(v)); if(!can){ cout<<0<<endl; R; } lpi(0,k) if(v[i]==s){ j=i; break; } for(int i=j-1;i>=0;--i){ if(v[i+1]-v[i]>1) ans=min(ans,s-v[i+1]+1); } for(int i=j+1;i<v.size();++i){ if(v[i]-v[i-1]>1) ans=min(ans,v[i-1]+1-s); } if(n>v[k-1]) ans=min(ans,v[k-1]+1-s); if(1<v[0]) ans=min(ans,s-v[0]+1); cout<<ans<<endl; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); ll t=1; cin>>t; while(t--) AK2000YY(); } // POWERED BY ABDUL KARIM KOURINI
cpp
1294
E
E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3 3 2 1 1 2 3 4 5 6 OutputCopy6 InputCopy4 3 1 2 3 4 5 6 7 8 9 10 11 12 OutputCopy0 InputCopy3 4 1 6 3 4 5 10 7 8 9 2 11 12 OutputCopy2 NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.
[ "greedy", "implementation", "math" ]
#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 = 2e5+50 , LOG = 22 , inf = 1e8 , SQ= 550 , mod = 1e9+7; #define py cout <<"YES"<<endl; #define pn cout <<"NO"<<endl; #define pp cout <<"ppppppppppppppppp"<<nd; #define lol cout <<"i am here"<<nd; const double PI = acos(-1.0); const int MX = 1000+10; template <typename T> using min_heap = priority_queue<T , vector <T > , greater <T > >; ll fp(ll n ,ll p){ if (!p) return 1; ll v = fp(n , p >> 1); v = v * v; if (p & 1) v = v * n; return v; } void hi(){ int n , m; cin >> n >> m; vector<vector<ll> > a(n , vector <ll>(m)); for (auto &i : a) for (auto &j : i) cin >> j , --j; ll ans = 0; for (int j = 0; j < m; ++j){ vector <int > cnt(n);// the number of cycles needed to put the element in its position for (int i = 0;i < n; ++i){ if (a[i][j] % m != j || a[i][j] /m >= n) continue; cnt[(i - a[i][j]/m +n) % n]++; } int cur = n - cnt[0]; for (int i = 1; i < n; ++i) cur = min(cur , n-cnt[i]+i); ans+=cur; } cout << ans <<nd; } 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
1303
F
F. Number of Componentstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix n×mn×m, initially filled with zeroes. We define ai,jai,j as the element in the ii-th row and the jj-th column of the matrix.Two cells of the matrix are connected if they share a side, and the elements in these cells are equal. Two cells of the matrix belong to the same connected component if there exists a sequence s1s1, s2s2, ..., sksk such that s1s1 is the first cell, sksk is the second cell, and for every i∈[1,k−1]i∈[1,k−1], sisi and si+1si+1 are connected.You are given qq queries of the form xixi yiyi cici (i∈[1,q]i∈[1,q]). For every such query, you have to do the following: replace the element ax,yax,y with cc; count the number of connected components in the matrix. There is one additional constraint: for every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.InputThe first line contains three integers nn, mm and qq (1≤n,m≤3001≤n,m≤300, 1≤q≤2⋅1061≤q≤2⋅106) — the number of rows, the number of columns and the number of queries, respectively.Then qq lines follow, each representing a query. The ii-th line contains three integers xixi, yiyi and cici (1≤xi≤n1≤xi≤n, 1≤yi≤m1≤yi≤m, 1≤ci≤max(1000,⌈2⋅106nm⌉)1≤ci≤max(1000,⌈2⋅106nm⌉)). For every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.OutputPrint qq integers, the ii-th of them should be equal to the number of components in the matrix after the first ii queries are performed.ExampleInputCopy3 2 10 2 1 1 1 2 1 2 2 1 1 1 2 3 1 2 1 2 2 2 2 2 2 1 2 3 2 4 2 1 5 OutputCopy2 4 3 3 4 4 4 2 2 4
[ "dsu", "implementation" ]
#include <iostream> #include <utility> #include <vector> #include <cmath> #include <algorithm> #include <unordered_set> #include <set> #include <queue> #include <cmath> #include <numeric> #include <sstream> #include <string> #include <map> #include <unordered_map> #include <deque> #include <iomanip> #include <unordered_set> #include <limits> #include <list> #include <bitset> #include <random> #include <cstring> #include <cassert> #include <chrono> #include <array> #define ff first #define err(x) cerr << "["#x"] " << (x) << "\n" #define errv(x) {cerr << "["#x"] ["; for (const auto& ___ : (x)) cerr << ___ << ", "; cerr << "]\n";} #define errvn(x, n) {cerr << "["#x"] ["; for (auto ___ = 0; ___ < (n); ++___) cerr << (x)[___] << ", "; cerr << "]\n";} #define ss second #define pb push_back #define all(a) a.begin(),a.end() typedef long long ll; typedef long double ld; using namespace std; const int MOD = 1000000007; mt19937 rnd(std::chrono::high_resolution_clock::now().time_since_epoch().count()); template<typename T1, typename T2> inline bool relaxmi(T1 &a, const T2 &b) { return a > b ? a = b, true : false; } template<typename T1, typename T2> inline bool relaxma(T1 &a, const T2 &b) { return a < b ? a = b, true : false; } double GetTime() { return clock() / (double) CLOCKS_PER_SEC; }; /// Actual code starts here const int N = 305, Q = 2e6 + 5; int p[N * N + 5]; int table[N][N]; int n, m; vector<int> dx = {1, -1, 0, 0}; vector<int> dy = {0, 0, 1, -1}; int get(int v) { if (p[v] == v) return v; return p[v] = get(p[v]); } bool join(int a, int b) { a = get(a), b = get(b); if (a == b) return false; p[a] = b; return true; } int gv[Q]; void Fill(vector<pair<int, int>> &bebra, int delta) { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) table[i][j] = -1; for (int i = 0; i < n * m; i++) p[i] = i; for (auto[v, id]: bebra) { int x = v / m, y = v % m; table[x][y] = 228; int cnt = 1; for (int k = 0; k < 4; k++) { int x2 = x + dx[k], y2 = y + dy[k]; if (x2 >= 0 && x2 < n && y2 >= 0 && y2 < m && table[x2][y2] == 228) cnt -= join(x * m + y, x2 * m + y2); } // err(cnt); gv[id] += delta * cnt; } } struct bebra { int x, y, c; }; bebra qv[Q]; vector<pair<int, int>> add[Q], sub[Q]; void solve() { int q; cin >> n >> m >> q; for (int i = 0; i < q; i++) { cin >> qv[i].x >> qv[i].y >> qv[i].c; qv[i].x--, qv[i].y--; if (qv[i].c == table[qv[i].x][qv[i].y]) continue; sub[table[qv[i].x][qv[i].y]].pb({qv[i].x * m + qv[i].y, i}); table[qv[i].x][qv[i].y] = qv[i].c; add[qv[i].c].pb({qv[i].x * m + qv[i].y, i}); } for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) sub[table[i][j]].pb({i * m + j, Q - 1}); for (int j = 0; j < Q; j++) { if (add[j].empty()) continue; Fill(add[j], 1); } for (int j = 0; j < Q; j++) { if (sub[j].empty()) continue; reverse(all(sub[j])); Fill(sub[j], -1); } int res = 1; // errvn(gv, q); for (int i = 0; i < q; i++) { res += gv[i]; cout << res << ' '; } } signed main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int tt = 1; //cin >> tt; while (tt--) solve(); }
cpp
1311
D
D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.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 tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8 1 2 3 123 321 456 5 10 15 15 18 21 100 100 101 1 22 29 3 19 38 6 30 46 OutputCopy1 1 1 3 102 114 228 456 4 4 8 16 6 18 18 18 1 100 100 100 7 1 22 22 2 1 19 38 8 6 24 48
[ "brute force", "math" ]
#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 } void solve(){ ll a , b , c; cin >> a >> b >> c; ll x , y , z , mini = 1e18; for(ll i = 1; i <= 2 * a; i++){ for(ll j = i; j <= 2 * b; j += i){ for(ll k = j; k <= 2 * c; k += j){ if(abs(a - i) + abs(b - j) + abs(c - k) < mini){ mini = abs(a - i) + abs(b - j) + abs(c - k); x = i , y = j , z = k; } } } } cout << mini << nl; cout << x << " " << y << " " << z << nl; } int main() { esraa(); int t = 1; cin >> t; //cin.ignore(); while(t--) solve(); return 0; }
cpp
1316
C
C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109),  — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109)  — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2)  — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2 1 1 2 2 1 OutputCopy1 InputCopy2 2 999999937 2 1 3 1 OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.
[ "constructive algorithms", "math", "ternary search" ]
#include "bits/stdc++.h" using namespace std; #define ll long long int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, m, p; cin >> n >> m >> p; vector<int> a(n), b(m); for (int &i : a) cin >> i; for (int &i : b) cin >> i; int i1 = n - 1; while (a[i1] % p == 0) i1--; int i2 = m - 1; while (b[i2] % p == 0) i2--; cout << (i1 + i2) << "\n"; }
cpp
1295
F
F. Good Contesttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn online contest will soon be held on ForceCoders; a large competitive programming platform. The authors have prepared nn problems; and since the platform is very popular, 998244351998244351 coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the ii-th problem, the number of accepted solutions will be between lili and riri, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems (x,y)(x,y) such that xx is located earlier in the contest (x<yx<y), but the number of accepted solutions for yy is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem ii, any integral number of accepted solutions for it (between lili and riri) is equally probable, and all these numbers are independent.InputThe first line contains one integer nn (2≤n≤502≤n≤50) — the number of problems in the contest.Then nn lines follow, the ii-th line contains two integers lili and riri (0≤li≤ri≤9982443510≤li≤ri≤998244351) — the minimum and maximum number of accepted solutions for the ii-th problem, respectively.OutputThe probability that there will be no inversions in the contest can be expressed as an irreducible fraction xyxy, where yy is coprime with 998244353998244353. Print one integer — the value of xy−1xy−1, taken modulo 998244353998244353, where y−1y−1 is an integer such that yy−1≡1yy−1≡1 (mod(mod 998244353)998244353).ExamplesInputCopy3 1 2 1 2 1 2 OutputCopy499122177 InputCopy2 42 1337 13 420 OutputCopy578894053 InputCopy2 1 1 0 0 OutputCopy1 InputCopy2 1 1 1 1 OutputCopy1 NoteThe real answer in the first test is 1212.
[ "combinatorics", "dp", "probabilities" ]
#include<bits/stdc++.h> #define re register using namespace std; inline int read(){ re int t=0;re char v=getchar(); while(v<'0')v=getchar(); while(v>='0')t=(t<<3)+(t<<1)+v-48,v=getchar(); return t; } const int M=998244353; inline void add(re int&x,re int y){(x+=y)>=M?x-=M:x;} inline int Mod(re int x){return x>=M?x-M:x;} inline int ksm(re int x,re int y){ re int s=1; while(y){ if(y&1)s=1ll*s*x%M; x=1ll*x*x%M,y>>=1; }return s; } int n,m,t,a[1000002],ans,L[52],R[52],p[102],f[52],g[52],inv[52],fac[52],iv=1; inline int C(re int x,re int y){ int s=inv[y]; for(re int i=x-y+1;i<=x;++i)s=1ll*s*i%M; return s; } int main(){ n=read(); for(re int i=fac[0]=inv[0]=1;i<=n;++i)fac[i]=1ll*fac[i-1]*i%M,inv[i]=ksm(fac[i],M-2); for(re int i=1;i<=n;++i)L[i]=read()-i,R[i]=read()-i,L[i]=-L[i],R[i]=-R[i],swap(L[i],R[i]),--L[i],p[++m]=L[i],p[++m]=R[i],iv=1ll*iv*(R[i]-L[i])%M;iv=ksm(iv,M-2); sort(p+1,p+m+1),m=unique(p+1,p+m+1)-p-1; f[0]=1; for(re int i=1;i<m;++i){ for(re int j=1;j<=n;++j){ g[j]=f[j]; for(re int k=j,ck=1;k;--k){ ck&=L[k]<=p[i]&&R[k]>=p[i+1]; if(!ck)break; add(g[j],1ll*f[k-1]*C(p[i+1]-p[i],j-k+1)%M); } } for(re int j=1;j<=n;++j)f[j]=g[j]; } printf("%d",1ll*iv*f[n]%M); }
cpp
1305
E
E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109. The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3 OutputCopy4 5 9 13 18InputCopy8 0 OutputCopy10 11 12 13 14 15 16 17 InputCopy4 10 OutputCopy-1 NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution. (1,2,3)(1,2,3) (1,3,4)(1,3,4) (2,4,5)(2,4,5)
[ "constructive algorithms", "greedy", "implementation", "math" ]
// #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() { } bool present[(int)2e7]; void solve() { int n, m; cin >> n >> m; vector<int> A; if (m > n * n) { cout << -1 << endl; return; } A.push_back(1); A.PB(2); present[1] = present[2] = true; int pos = 3; int cur = 0; while (m > 0 && A.size() < n) { int add = 0; for (int i = 0; i < A.size(); i++) { if (2 * A[i] >= pos) { break; } if (present[pos - A[i]]) { add++; } if (add > m) { break; } } if (add <= m) { m -= add; present[pos] = true; A.PB(pos); } pos++; } if (m) { cout << -1 << endl; return; } int y = pos + pos; int s = A.size(); pos = (int)1e8; for (int i = s; i < n; i++) { A.PB(pos + 1e4 * i); } for (int i = 0; i < n; i++) { cout << A[i] << " "; } cout << 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
1304
B
B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3 tab one bat OutputCopy6 tabbat InputCopy4 2 oo ox xo xx OutputCopy6 oxxxxo InputCopy3 5 hello codef orces OutputCopy0 InputCopy9 4 abab baba abcd bcde cdef defg wxyz zyxw ijji OutputCopy20 ababwxyzijjizyxwbaba NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string.
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
#include <bits/stdc++.h> using namespace std; #define ll long long const int MAX_N=100; string s[MAX_N]; void solve() { ll int n,m,i; cin>>n>>m; set<string> d; for(i=0;i<n;i++) { cin>>s[i]; d.insert(s[i]); } vector<string> left,right; string mid; for( i=0;i<n;i++) { string t=s[i]; reverse(t.begin(),t.end()); if(t==s[i]) mid=t; else if(d.find(t)!=d.end()) { left.push_back(s[i]); right.push_back(t); d.erase(s[i]); d.erase(t); } } cout<<(left.size()*2*m)+mid.size()<<endl; for(string x : left) cout<<x; cout<<mid; reverse(right.begin(), right.end()); for(string x : right) cout<<x; cout<<endl; } int main() { ll int tt=1; //cin>>tt; while(tt--) solve(); return 0; }
cpp
1303
D
D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3 10 3 1 32 1 23 4 16 1 4 1 20 5 2 1 16 1 8 OutputCopy2 -1 0
[ "bitmasks", "greedy" ]
#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, p = 1; vector<ll> pow2; map<ll, ll> rev_pow2; pow2.push_back(1); rev_pow2[1] = 0; for (ll x = 1;; x++) { p *= 2; if (p > 1e9) { break; } pow2.push_back(p); rev_pow2[p] = x; } ll msz = pow2.size(); cin >> tc; while (tc--) { ll n, m, s = 0; cin >> n >> m; vector<ll> v(msz + 1, 0); for (ll t, x = 0; x < m; x++) { cin >> t; s += t; v[rev_pow2[t]]++; } if (s < n) { cout << -1 << '\n'; continue; } ll res = 0; // for (ll x = 0; x <= 5; x++) { // cout << v[x] << " "; // } // cout << '\n'; for (ll z = 0; z <= 30; z++) { if ((1LL << z) & n) { ll req = 1LL << z; // reverse_check for (ll x = z; x >= 0; x--) { ll q = min(req / (1LL << x), v[x]); req -= q * (1LL << x); } if (req == 0) { // reverse smu req = 1LL << z; for (ll x = z; x >= 0; x--) { ll q = min(req / (1LL << x), v[x]); v[x] -= q; req -= q * (1LL << x); } } else { // forward check req = 1LL << z; for (ll x = z + 1; x <= msz; x++) { if (v[x]) { ll bit = x, chunk = 1LL << x; while (chunk != req) { res++; v[bit]--; chunk /= 2; bit--; v[bit] += 2; } v[bit]--; req = 0; break; } } } } } cout << res << '\n'; } return 0; }
cpp
1313
B
B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
[ "constructive algorithms", "greedy", "implementation", "math" ]
#include <bits/stdc++.h> using namespace std; int main() { int t, n, x, y; cin >> t; while (t--) { cin >> n >> x >> y; int score = x+y; int worst, best; if (score > n+1) worst = n; else worst = score-1; if (score <= n) best = 1; else best = min(n, score-n+1); cout << best << " " << worst << endl; } }
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 ll long long #define fi first #define se second int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<vector<pair<int, int>>> adj(n); for(int i = 0; i < n - 1; i++ ){ int x, y; cin >> x >> y; x--; y--; adj[x].emplace_back(y, i); adj[y].emplace_back(x, i); } vector<int> fa(n, -1), dep(n), edge(n); function<void(int)> dfs = [&](int x){ for(auto [u, id] : adj[x]){ if(u == fa[x]) continue; dep[u] = dep[x] + 1; fa[u] = x; edge[u] = id; dfs(u); } }; dfs(0); int m; cin >> m; vector<int> ans(n - 1, -1); int ok = 1; vector<tuple<int, int, int>> e; for(int i = 0; i < m; i++ ){ int x, y, w; cin >> x >> y >> w; x--; y--; if(x > y) swap(x, y); e.emplace_back(w, x, y); } sort(e.rbegin(), e.rend()); for(int i = 0; i < m; i++ ){ auto [w, x, y] = e[i]; vector<int> c; int f = 0; while(x != y){ if(dep[x] > dep[y]){ if(ans[edge[x]] == -1){ c.push_back(edge[x]); } if(ans[edge[x]] == w){ f = 1; } x = fa[x]; } else { if(ans[edge[y]] == -1){ c.push_back(edge[y]); } if(ans[edge[y]] == w){ f = 1; } y = fa[y]; } } if(c.empty() && !f){ ok = 0; } else { for(auto x : c){ ans[x] = w; } } } if(!ok){ cout << -1 << "\n"; return 0; } for(int i = 0; i < n - 1; i++ ){ if(ans[i] == -1) cout << 1 << " "; else cout << ans[i] << " "; } cout << "\n"; return 0; }
cpp
1291
B
B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10 1 248618 3 12 10 8 6 100 11 15 9 7 8 4 0 1 1 0 2 0 0 2 0 1 2 1 0 2 1 1 3 0 1 0 3 1 0 1 OutputCopyYes Yes Yes No No Yes Yes Yes Yes No NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened.
[ "greedy", "implementation" ]
#include<bits/stdc++.h> using namespace std; #define ll long long #define ld long double #define vv vector<ll> #define T ll ttt;cin>>ttt;while(ttt--) #define all(x) (x).begin(),(x).end() #define rall(x) (x).rbegin(),(x).rend() #define mod 1000000007 #define pb emplace_back #define eeq <<"\n"; #define PI 3.14159265359 #define f0r(a, b) for (long long a = 0; a < (b); ++a) #define f1r(a, b) for (long long a = 1; a <= (b); ++a) #define f11r(a, b) for (long long a = b-1; a >= 0; --a) #define mp make_pair void ELZOZ(){ ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);} //ابدا بالصلاه ع النبي اللهم صلي وسلم علي سيدنا محمد //-----START-----// void solve() { int n, x ,y; cin >> n; vv arr(n); f0r(i, n) cin >> arr[i]; f0r(i, n) { if (arr[i] >= i) x = i; else break; } f11r(i, n) { if (arr[i] >= n - 1 - i) y = i; else break; } if (y > x && n != 1) cout << "NO" eeq else cout << "YES" eeq } int main() { //freopen("lazy.in", "r", stdin); // memset(dp, -1, sizeof(dp)); ELZOZ(); // <---*---*---*---*---*{*}****--0 T{ solve(); } }
cpp
13
D
D. Trianglestime limit per test2 secondsmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.InputThe first line contains two non-negative integer numbers N and M (0 ≤ N ≤ 500; 0 ≤ M ≤ 500) — the number of red and blue points respectively. The following N lines contain two integer numbers each — coordinates of red points. The following M lines contain two integer numbers each — coordinates of blue points. All coordinates do not exceed 109 by absolute value.OutputOutput one integer — the number of distinct triangles with vertices in red points which do not contain any blue point inside.ExamplesInputCopy4 10 010 010 105 42 1OutputCopy2InputCopy5 55 106 18 6-6 -77 -15 -110 -4-10 -8-10 5-2 -8OutputCopy7
[ "dp", "geometry" ]
#include<bits/stdc++.h> using namespace std; #define int long long int a[501],b[501],c[501],d[501],f[501][501]; main() { int n,m; cin>>n>>m; for(int x=1;x<=n;x++) cin>>a[x]>>b[x]; for(int x=1;x<=m;x++) cin>>c[x]>>d[x]; for(int x=1;x<=n;x++) for(int y=1;y<=n;y++) if(a[x]<a[y]) { int u=b[y]-b[x],v=a[x]-a[y],w=-a[x]*u-b[x]*v; for(int z=1;z<=m;z++) f[x][y]+=(c[z]>a[x]&&c[z]<=a[y]&&u*c[z]+v*d[z]+w>0); f[y][x]=-f[x][y]; } /*for(int x=1;x<=n;x++){ for(int y=1;y<=n;y++) cout<<f[x][y]<<' ';cout<<endl;}*/ int ans=0; for(int x=1;x<=n;x++) for(int y=x+1;y<=n;y++) for(int z=y+1;z<=n;z++) ans+=(f[x][y]+f[y][z]+f[z][x]==0/*&&(cout<<x<<','<<y<<','<<z<<endl,1)*/); cout<<ans<<endl; }
cpp
1312
D
D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4 OutputCopy6 InputCopy3 5 OutputCopy10 InputCopy42 1337 OutputCopy806066790 InputCopy100000 200000 OutputCopy707899035 NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3].
[ "combinatorics", "math" ]
#include <iostream> #include <iomanip> #include <vector> using namespace std; const long long mod = 998244353; int n, m; vector<long long> fac; long long fast_power(long long x, long long y) { long long res = 1; while(y > 0) { if(y & 1) res = (res * x) % mod; x = (x * x) % mod; y >>= 1; } return res; } long long exgcd(long long x, long long y, long long &c_x, long long &c_y) { if(y == 0) { c_x = 1, c_y = 0; return x; } long long gcd_x_y = exgcd(y, x % y, c_y, c_x); c_y -= (x / y) * c_x; return c_x; } long long inv(long long x) { long long c_x, c_mod; exgcd(x, mod, c_x, c_mod); return (c_x % mod + mod) % mod; } long long C(int n, int m) { return (fac[n] * inv(fac[m]) % mod) * inv(fac[n - m]) % mod; } int main() { ios::sync_with_stdio(false); cin >> n >> m; // 阶乘 fac.resize(1 + m); fac[0] = 1; for(long long i = 1; i <= m; i += 1) { fac[i] = (i * fac[i - 1]) % mod; } // long long pick_num = C(m, n - 1); long long pick_place = n - 2; long long arrangement = fast_power(2, n - 3); long long ans = (pick_num * pick_place % mod) * arrangement % mod; cout << ans << "\n" << flush; return 0; }
cpp
1285
D
D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3 1 2 3 OutputCopy2 InputCopy2 1 5 OutputCopy4 NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5.
[ "bitmasks", "brute force", "dfs and similar", "divide and conquer", "dp", "greedy", "strings", "trees" ]
#include<iostream> #include<vector> using namespace std; int n; vector<int>a; int solve(vector<int>p, int k) { if (p.size() == 0 || k < 0)return 0; vector<int>p1, p0; for (int i : p) { if (i & (1 << k))p1.push_back(i); else p0.push_back(i); } if (p1.size() == 0)return solve(p0, k - 1); if (p0.size() == 0)return solve(p1, k - 1); return (1 << k) + min(solve(p1, k - 1), solve(p0, k - 1)); } int main() { scanf("%d", &n); for (int i = 1, x; i <=n; i++)scanf("%d", &x), a.push_back(x); printf("%d", solve(a, 30)); }
cpp
13
A
A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.
[ "implementation", "math" ]
#include <iostream> #include <cstdint> #include <cmath> #include <bits/stdc++.h> using namespace std; #define ll long long void printFraction(int up, int down) { for(int i = down <= up? down : up; i > 0; i--) { if(up % i == 0 && down % i == 0) { cout << up/i << "/" << down/i; return; } } } void code() { int A; cin >> A; int denom = A - 2; int result = 0; for(int i = 2; i < A; i++) { int number = A; while(number > 0) { result += number % i; number /= i; } } printFraction(result, denom); } int main() { ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); ll trials; //cin >> trials; //for(ll i = 0; i < trials; i++) { code(); //} }
cpp
1303
C
C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5 ababa codedoca abcda zxzytyz abcdefghijklmnopqrstuvwxyza OutputCopyYES bacdefghijklmnopqrstuvwxyz YES edocabfghijklmnpqrstuvwxyz NO YES xzytabcdefghijklmnopqrsuvw NO
[ "dfs and similar", "greedy", "implementation" ]
/* iamujj15 */ #pragma GCC optimize("O3,unroll-loops") #include "bits/stdc++.h" using namespace std; using namespace std::chrono; #define fstio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) #define MOD 1000000007 #define MOD1 998244353 #define INF 5e18 #define nline "\n" #define pb emplace_back #define ppb pop_back #define mp make_pair #define ff first #define ss second #define PI 3.141592653589793238462 #define FIXED_FLOAT(x) std::fixed << std::setprecision(15) << (x) #define set_bits __builtin_popcountll #define sz(x) ((int)(x).size()) #define all(x) (x).begin(), (x).end() #define vcin(a) for (auto &i : a) cin >> i #define vcout(a) for (auto i : a) cout << i << " " #ifndef iamujj15 #define debug(x) cerr << #x << " "; _print(x); cerr << nline; #else #define debug(x); #endif typedef unsigned long long ull; typedef long double lld; typedef pair<long long, long long> pll; typedef vector<long long> vll; typedef long long ll; typedef unsigned long long ull; void _print(ll t) {cerr << t;} void _print(int t) {cerr << t;} void _print(string t) {cerr << t;} void _print(char t) {cerr << t;} void _print(lld t) {cerr << t;} void _print(float 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) {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 << "]";} template <class T, class V> void _print(multimap <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";} mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); /*---------------------------------------------------------------------------------------------------------------------------*/ 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 >>= 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);} ll pow2(ll k) {ll i = 1; if (k == 0) return 1; while (k--) i *= 2; return i;} ll pow10(ll k) {ll i = 1; if (k == 0) return 1; while (k--) i *= 10; return i;} ll lcm(ll a, ll b) { return (a / __gcd(a, b)) * b;} ll mx(ll a, ll b) {return a > b ? a : b;} ll mn(ll a, ll b) {return a < b ? a : b;} 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 << ": ";} void sieve(vector<bool>& prime) {for (int p = 2; p * p <= prime.size(); p++) {if (prime[p] == true) {for (int i = p * p; i <= prime.size(); i += p) prime[i] = false;}}} 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 getRandomNumber(ll l, ll r) {return uniform_int_distribution<ll>(l, r)(rng);} ll modInverse(ll A, ll M) {ll m0 = M; ll 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;} void preclc(vll &fact, vll &invf) {fact[0] = 1; fact[1] = 1; invf[0] = 1; invf[1] = 1; for (ll i = 2; i < (ll)fact.size(); i++) {fact[i] = (fact[i - 1] * i) % MOD; invf[i] = modInverse(fact[i], MOD);}} ll ncr(ll n, ll r, vll &fact, vll &invf) {return ((fact[n] * invf[r] % MOD) * invf[n - r]) % MOD;} /*--------------------------------------------------------------------------------------------------------------------------*/ string spi = "3141592653589793238462643383279"; class DSU { public: vector<pll> parent; vll size; DSU(ll n) { size.resize(n, 1); for (ll i = 0; i < n; i++) parent.pb(i, 0); } ll find_set(ll x) { if (parent[x].ff == x) return x; return parent[x].ff = find_set(parent[x].ff); } bool same_set(ll x, ll y) { return find_set(x) == find_set(y); } void union_set(ll x, ll y) { ll xroot = find_set(x); ll yroot = find_set(y); if (xroot == yroot) return; if (parent[xroot].ss > parent[yroot].ss) { parent[yroot].ff = xroot; size[xroot] += size[yroot]; } else if (parent[yroot].ss > parent[xroot].ss) { parent[xroot].ff = yroot; size[yroot] += size[xroot]; } else { parent[xroot].ss++; parent[yroot].ff = xroot; size[xroot] += size[yroot]; } } ll size_set(ll x) { return size[find_set(x)]; } }; /* ----------------------------------Errors to be taken care of---------------------------------- ⬥ Initialised a variable, with some other variable (say n), before cin >> n? ⬥ Checked for the domain of the answer, & what extreme values your solution could get? ⬥ In C++, comparator should return false if its arguments are equal ⬥ Use custom sqrt function */ void solution() { //vector<bool> prime(4e6, true); //sieve(prime); ll t = 1; cin >> t; while (t--) { string s, ans = ""; cin >> s; set<char> st; for (ll ch = 'a'; ch <= 'z'; ++ch) st.insert(ch); ll id = 0, flg = 1; ans += s[0]; st.erase(s[0]); for (ll i = 1; i < s.length(); ++i) { if (id == 0 && id == ans.length()) { if (st.find(s[i]) != st.end()) { ans += s[i]; id++; st.erase(s[i]); } else { flg = 0; break; } } else if (id == 0) { if (ans[id + 1] == s[i]) id++; else { if (st.find(s[i]) != st.end()) { string tmp = ""; tmp += s[i]; tmp += ans; ans = tmp; st.erase(s[i]); } else { flg = 0; break; } } } else if (id == ans.length() - 1) { if (ans[id - 1] == s[i]) id--; else { if (st.find(s[i]) != st.end()) { ans += s[i]; id++; st.erase(s[i]); } else { flg = 0; break; } } } else { if (ans[id - 1] == s[i]) id--; else if (ans[id + 1] == s[i]) id++; else { flg = 0; break; } } } if (flg) { cout << "YES\n"; cout << ans; for (auto i : st) cout << i; cout << nline; } else cout << "NO\n"; } } int main() { #ifndef iamujj15 freopen("error.txt", "w", stderr); #endif fstio(); auto start1 = high_resolution_clock::now(); solution(); auto stop1 = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop1 - start1); #ifdef iamujj15 cerr << "Time: " << duration . count() / 1000 << nline; #endif }
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 <int> mark(N); vector <int > vis(N); int sq; vector<int > st; vector <int > depth(N); void dfs(int node , int p){ vis[node] = 1; st.emplace_back(node); depth[node] = 1 + depth[p]; for (auto &ch : g[node]){ if (ch == p) 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 &par : g[node]) mark[par] |= (depth[node] > depth[par]); } 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 , 0); 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
1292
A
A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5 2 3 1 4 2 4 2 3 1 4 OutputCopyYes No No No Yes NoteWe'll crack down the example test here: After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3). After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again.
[ "data structures", "dsu", "implementation" ]
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #define endl '\n' int n, q; vector<vector<int>> lava; void Input() { cin >> n >> q; lava.resize(2, vector<int>(n, 0)); } void Solve() { int blockedPair = 0; while (q--) { int x, y; cin >> x >> y; x--; y--; int delta = (lava[x][y] == 0) ? +1 : -1; lava[x][y] = 1 - lava[x][y]; for (int dy=-1; dy<=1; dy++) { if (y+dy < 0 || y+dy >= n) continue; if (lava[1-x][y+dy] == 1) blockedPair += delta; } cout << ((blockedPair == 0) ? "Yes\n" : "No\n"); } } int main(int argc, char* argv[]) { ios_base::sync_with_stdio(0); cin.tie(NULL); Input(); Solve(); return 0; }
cpp
1305
D
D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might 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 the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6 1 4 4 2 5 3 6 3 2 3 3 4 4 OutputCopy ? 5 6 ? 3 1 ? 1 2 ! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:
[ "constructive algorithms", "dfs and similar", "interactive", "trees" ]
#include <algorithm> #include <cassert> #include <cstdio> #include <cstring> #include <iomanip> #include <iostream> #include <map> #include <numeric> #include <queue> #include <ranges> #include <set> #include <string> #include <vector> using namespace std; #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() 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...); } #ifdef DUPA #define debug(x...) \ cerr << "[" << #x << "] = ["; \ _print(x) #else #define debug(x, ...) #endif typedef long long LL; // HMMMM #define int LL typedef pair<int, int> PII; typedef pair<int, PII> PIII; const int INF = 1e18 + 1; int n; vector<set<int>> g; void answer(int x) { cout << "! " << x << endl; exit(0); } int ask(int x, int y) { cout << "? " << x << " " << y << endl; int res; cin >> res; return res; } void solve() { cin >> n; g.resize(n + 1); for (int i = 0; i < n - 1; i++) { int u, v; cin >> u >> v; g[u].insert(v); g[v].insert(u); } set<int> res; for (int i = 1; i <= n; i++) res.insert(i); while (res.size() > 1) { vector<int> q; for (int i = 1; i <= n; i++) { if (g[i].size() == 1) q.push_back(i); if (q.size() >= 2) break; } if (q.size() == 1) { answer(q.front()); } else { assert(q.size() == 2); int x = ask(q.front(), q.back()); if (x == q.front() || x == q.back()) answer(x); for (auto y : q) { res.erase(y); g[y].clear(); for (int i = 1; i <= n; i++) g[i].erase(y); } } } answer(*res.begin()); } #undef int int main() { ios::sync_with_stdio(false); cin.exceptions(cin.failbit); cin.tie(0); int t = 1; // cin >> t; #ifdef DUPA #endif for (int i = 0; i < t; i++) solve(); }
cpp
1325
A
A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100)  — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2 2 14 OutputCopy1 1 6 4 NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.
[ "constructive algorithms", "greedy", "number theory" ]
#include <iostream> #include <string> const int SIZE = 1e4; int main() { int t, x; std::cin >> t; std::string arr[SIZE]; for (int i = 0; i < t; i++) { std::cin >> x; arr[i] = "1 " + std::to_string(x - 1); } for (int i = 0; i < t; i++) std::cout << arr[i] << "\n"; return 0; }
cpp
1325
B
B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2 3 3 2 1 6 3 1 4 1 5 9 OutputCopy3 5 NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9].
[ "greedy", "implementation" ]
#include <bits/stdc++.h> using namespace std; int main() { int t; scanf("%d",&t); while (t--) { int n; scanf("%d",&n); set<int> s; while (n--) { int a; scanf("%d",&a); s.insert(a); } printf("%d\n",s.size()); } }
cpp
1311
D
D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.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 tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8 1 2 3 123 321 456 5 10 15 15 18 21 100 100 101 1 22 29 3 19 38 6 30 46 OutputCopy1 1 1 3 102 114 228 456 4 4 8 16 6 18 18 18 1 100 100 100 7 1 22 22 2 1 19 38 8 6 24 48
[ "brute force", "math" ]
#include <bits/stdc++.h> using namespace std; using ll = long long; using ari2 = array<int, 2>; using arl2 = array<ll, 2>; using arl3 = array<ll, 3>; constexpr ll MOD = 998244353; void solve(); void precomp(); signed main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); precomp(); int T = 1; cin >> T; for (int t = 1; t <= T; t++) { solve(); } } constexpr int mxN = 16969, INF = 0x3f3f3f3f; vector<int> dvsrs[mxN]; void precomp() { for (int i = 1; i < mxN; i++) { for (int j = i; j < mxN; j += i) { dvsrs[j].push_back(i); } } } int dp[mxN][3][2], ar[3]; void solve() { cin >> ar[0] >> ar[1] >> ar[2]; memset(dp, 0x3f, sizeof(dp)); int C = 0; for (int i = 0; i < 3; i++) { for (int j = 1; j < mxN; j++) { if (!i) { dp[j][i][0] = abs(j-ar[0]); } else { for (int k : dvsrs[j]) { int v = dp[k][i-1][0] + abs(j-ar[i]); if (v < dp[j][i][0]) { dp[j][i][0] = v; dp[j][i][1] = k; } } C = i == 2 && dp[C][2][0] > dp[j][2][0] ? j : C; } } } int B = dp[C][2][1], A = dp[B][1][1]; cout << dp[C][2][0] << '\n'; cout << A << ' ' << B << ' ' << C << '\n'; }
cpp
1322
D
D. Reality Showtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA popular reality show is recruiting a new cast for the third season! nn candidates numbered from 11 to nn have been interviewed. The candidate ii has aggressiveness level lili, and recruiting this candidate will cost the show sisi roubles.The show host reviewes applications of all candidates from i=1i=1 to i=ni=n by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate ii is strictly higher than that of any already accepted candidates, then the candidate ii will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit.The show makes revenue as follows. For each aggressiveness level vv a corresponding profitability value cvcv is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant ii enters the stage, events proceed as follows: The show makes clicli roubles, where lili is initial aggressiveness level of the participant ii. If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is: the defeated participant is hospitalized and leaves the show. aggressiveness level of the victorious participant is increased by one, and the show makes ctct roubles, where tt is the new aggressiveness level. The fights continue until all participants on stage have distinct aggressiveness levels. It is allowed to select an empty set of participants (to choose neither of the candidates).The host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total sisi). Help the host to make the show as profitable as possible.InputThe first line contains two integers nn and mm (1≤n,m≤20001≤n,m≤2000) — the number of candidates and an upper bound for initial aggressiveness levels.The second line contains nn integers lili (1≤li≤m1≤li≤m) — initial aggressiveness levels of all candidates.The third line contains nn integers sisi (0≤si≤50000≤si≤5000) — the costs (in roubles) to recruit each of the candidates.The fourth line contains n+mn+m integers cici (|ci|≤5000|ci|≤5000) — profitability for each aggrressiveness level.It is guaranteed that aggressiveness level of any participant can never exceed n+mn+m under given conditions.OutputPrint a single integer — the largest profit of the show.ExamplesInputCopy5 4 4 3 1 2 1 1 2 1 2 1 1 2 3 4 5 6 7 8 9 OutputCopy6 InputCopy2 2 1 2 0 0 2 1 -100 -100 OutputCopy2 InputCopy5 4 4 3 2 1 1 0 2 6 7 4 12 12 12 6 -3 -5 3 10 -4 OutputCopy62 NoteIn the first sample case it is optimal to recruit candidates 1,2,3,51,2,3,5. Then the show will pay 1+2+1+1=51+2+1+1=5 roubles for recruitment. The events on stage will proceed as follows: a participant with aggressiveness level 44 enters the stage, the show makes 44 roubles; a participant with aggressiveness level 33 enters the stage, the show makes 33 roubles; a participant with aggressiveness level 11 enters the stage, the show makes 11 rouble; a participant with aggressiveness level 11 enters the stage, the show makes 11 roubles, a fight starts. One of the participants leaves, the other one increases his aggressiveness level to 22. The show will make extra 22 roubles for this. Total revenue of the show will be 4+3+1+1+2=114+3+1+1+2=11 roubles, and the profit is 11−5=611−5=6 roubles.In the second sample case it is impossible to recruit both candidates since the second one has higher aggressiveness, thus it is better to recruit the candidate 11.
[ "bitmasks", "dp" ]
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <vector> #include <map> using namespace std; #define eb emplace_back #define vv vector #define fi first #define se second using pii = pair<int, int>; using ll = long long; const int N = 4005; int n, m; int l[N], s[N], c[N], f[N][N]; void Mx(int &a, int b) {if (a < b) a = b;} // f[x][i][j] 前 x 个,攻击力为 i 的有 j 个 signed main() { #ifndef ONLINE_JUDGE freopen("test.in", "r", stdin); freopen("test.out", "w", stdout); #endif ios :: sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> m; for (int i = 1; i <= n; ++ i) cin >> l[i]; for (int i = 1; i <= n; ++ i) cin >> s[i]; for (int i = 1; i <= n + m; ++ i) cin >> c[i]; memset(f, 0xcf, sizeof f); for (int i = 1; i <= n + m; ++ i) f[i][0] = 0; for (int i = n; i >= 1; -- i) { for (int j = n; j >= 1; -- j) Mx(f[l[i]][j], f[l[i]][j - 1] + c[l[i]] - s[i]); for (int j = l[i]; j <= n + m; ++ j) { for (int k = 0; k <= (n >> (j - l[i])); ++ k) { Mx(f[j + 1][k >> 1], f[j][k] + (k >> 1) * c[j + 1]); } } } cout << f[n + m][0] << '\n'; return 0; }
cpp
1323
B
B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2 1 0 1 1 1 1 OutputCopy4 InputCopy3 5 4 1 1 1 1 1 1 1 1 OutputCopy14 NoteIn first example matrix cc is: There are 44 subrectangles of size 22 consisting of only ones in it: In second example matrix cc is:
[ "binary search", "greedy", "implementation" ]
#include<bits/stdc++.h> using namespace std; #define ll long long #define c(ans) cout << ans << endl #define cs(ans) cout << ans << " " #define fori(i,j,k) for(ll i = j; i < k; i++) #define ifor(i,j,k) for(ll i = j; i >= k; i--) #define inarr(j,n,a) for(ll i = j; i < n; i++) cin >> a[i]; #define sortall(v) sort(v.begin(), v.end()) #define sortarr(a,n) sort(a,a+n) #define reverseall(v) reverse(v.begin(), v.end()) #define cy cout << "YES" << endl #define cn cout << "NO" << endl #define all(v) v.begin(), v.end() #define sz(v) v.size() #define pb push_back #define ff first #define ss second typedef vector<ll> vll; typedef pair<ll, ll> pll; typedef map<ll, ll> mll; typedef queue<ll> qll; typedef set<ll> sll; typedef stack<ll> stll; typedef priority_queue<ll> maxpqll; typedef priority_queue<ll, vector<ll>, greater<ll>> minpqll; const ll inf = 1e18; const ll mod = 1e9 + 7; void cv(vector<ll> v){ fori(i,0,v.size()){ cs(v[i]); } cout << endl; } ll firstsetbit(ll x){ return x & -x; } ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); } ll lcm(ll a, ll b) { return (a / gcd(a, b)) * b; } ll sum(ll l, ll r) { ll ans = r * (r + 1) >> 1; ans -= (l * (l - 1) >> 1); return ans; } struct my { vector<ll> a; ll mx, mn; bool flag; }; //------------------------------------code------------------------------------// int main(){ ios::sync_with_stdio(false); cin.tie(0); // ll T; // cin >> T; // while(T--){ ll n, m, k; cin >> n >> m >> k; vll row(n), col(m); fori(i, 0, n){ cin >> row[i]; } // cv(row); fori(i, 0, m){ cin >> col[i]; } // cv(col); ll final = 0; fori(j, 1, n + 1){ if(k % j == 0){ ll upper = j, niche = k / j; ll cnt = 0; ll r = 0, c = 0; fori(i, 0, n){ if(row[i]){ cnt++; if(cnt >= upper){ r++; } }else{ cnt = 0; } } cnt = 0; fori(i, 0, m){ if(col[i]){ cnt++; if(cnt >= niche){ c++; } }else{ cnt = 0; } } final += r * c; } } c(final); sahil:; // } return 0; }
cpp
1324
B
B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.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.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5 3 1 2 1 5 1 2 2 3 2 3 1 1 2 4 1 2 2 1 10 1 1 2 2 3 3 4 4 5 5 OutputCopyYES YES NO YES NO NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.
[ "brute force", "strings" ]
#include<bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> //--------------------------------------------------------------------------------- #define ll long long #define fixed(n) cout << fixed << setprecision(n) #define sz(x) int(x.size()) #define TC int t; cin >> t; while(t--) #define all(s) s.begin(), s.end() #define rall(s) s.rbegin(), s.rend() #define dl "\n" #define Ceil(a, b) ((a / b) + (a % b ? 1 : 0)) #define pi 3.141592 #define OO 2'000'000'000 #define MOD 1'000'000'007 #define EPS 1e-10 using namespace std; 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::greater<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::less_equal<K>> using ordered_multiset = ordered_multimap<K, null_type, Comp>; // order_of_key(val) count elements smaller than val // *s.find_by_order(idx) element with index idx template<typename T = int > istream& operator >> (istream &in , vector < T > &v){ for(auto &i : v) in >> i ; return in ; } template<typename T = int > ostream& operator << (ostream &out ,vector < T > &v){ for(auto &i : v) out << i << ' ' ; return out ; } //----------------------------------------------------------------------------------------- void ZEDAN() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin) ; freopen("output.txt", "w", stdout) ; #endif } //-----------------------------------------(notes)----------------------------------------- /* */ //-----------------------------------------(function)-------------------------------------- //-----------------------------------------(code here)------------------------------------- void solve(){ ll n , x ; cin >> n ; vector<int>vis(n+1,-1); int flag = 0 ; for(ll i=0 ; i<n ; i++){ cin >> x ; if(vis[x]!=-1){ if(vis[x]+1!=i) flag = 1 ; } else vis[x] = i ; } cout << (flag?"YES":"NO") ; } //----------------------------------------------------------------------------------------- int main() { ZEDAN() ; ll t = 1 ; cin >> t ; while(t--){ solve() ; if(t) cout << dl ; } return 0; }
cpp
1294
A
A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.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 new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5 5 3 2 8 100 101 102 105 3 2 1 100000000 10 20 15 14 101 101 101 3 OutputCopyYES YES NO NO YES
[ "math" ]
#include<bits/stdc++.h> using namespace std; typedef long long ll; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int T, n; ll a, b, c; cin>>T; while(T--) { cin>>a>>b>>c>>n; n = n+a+b+c; if(n%3!=0) { cout<<"NO"<<"\n"; } else { n /= 3; if(n<a||n<b||n<c) { cout<<"NO"<<"\n"; } else cout<<"YES"<<"\n"; } } return 0; }
cpp
1292
E
E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.The chemical structure of this flower can be represented as a string pp. From the unencrypted papers included, Rin already knows the length nn of that string, and she can also conclude that the string contains at most three distinct letters: "C" (as in Carbon), "H" (as in Hydrogen), and "O" (as in Oxygen).At each moment, Rin can input a string ss of an arbitrary length into the artifact's terminal, and it will return every starting position of ss as a substring of pp.However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific: The artifact only contains 7575 units of energy. For each time Rin inputs a string ss of length tt, the artifact consumes 1t21t2 units of energy. If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?InteractionThe interaction starts with a single integer tt (1≤t≤5001≤t≤500), the number of test cases. The interaction for each testcase is described below:First, read an integer nn (4≤n≤504≤n≤50), the length of the string pp.Then you can make queries of type "? s" (1≤|s|≤n1≤|s|≤n) to find the occurrences of ss as a substring of pp.After the query, you need to read its result as a series of integers in a line: The first integer kk denotes the number of occurrences of ss as a substring of pp (−1≤k≤n−1≤k≤n). If k=−1k=−1, it means you have exceeded the energy limit or printed an invalid query, and you need to terminate immediately, to guarantee a "Wrong answer" verdict, otherwise you might get an arbitrary verdict because your solution will continue to read from a closed stream. The following kk integers a1,a2,…,aka1,a2,…,ak (1≤a1<a2<…<ak≤n1≤a1<a2<…<ak≤n) denote the starting positions of the substrings that match the string ss.When you find out the string pp, print "! pp" to finish a test case. This query doesn't consume any energy. The interactor will return an integer 11 or 00. If the interactor returns 11, you can proceed to the next test case, or terminate the program if it was the last testcase.If the interactor returns 00, it means that your guess is incorrect, and you should to terminate to guarantee a "Wrong answer" verdict.Note that in every test case the string pp is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might 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 the documentation for other languages.HacksFor hack, use the following format. Note that you can only hack with one test case:The first line should contain a single integer tt (t=1t=1).The second line should contain an integer nn (4≤n≤504≤n≤50) — the string's size.The third line should contain a string of size nn, consisting of characters "C", "H" and "O" only. This is the string contestants will have to find out.ExamplesInputCopy1 4 2 1 2 1 2 0 1OutputCopy ? C ? CH ? CCHO ! CCHH InputCopy2 5 0 2 2 3 1 8 1 5 1 5 1 3 2 1 2 1OutputCopy ? O ? HHH ! CHHHH ? COO ? COOH ? HCCOO ? HH ! HHHCCOOH NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.
[ "constructive algorithms", "greedy", "interactive", "math" ]
# include <bits/stdc++.h> using namespace std; int T; int n,m,f[60]; inline char get_(int x) { return x==1 ? 'C' : x==2 ? 'H' : 'O';} int main() { scanf("%d",&T); while (T--) { memset(f,0,sizeof(f)); scanf("%d",&n); printf("? CC\n"), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=1, f[x+1]=1; printf("? CH\n"), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=1, f[x+1]=2; printf("? CO\n"), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=1, f[x+1]=3; printf("? OH\n"), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=3, f[x+1]=2; if (n>4) { printf("? HH\n"), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=2, f[x+1]=2; for (int i=2;i<n;i++) if (!f[i]) f[i]=3; if (f[1]&&f[n]) { printf("! "); for (int i=1;i<=n;i++) printf("%c",get_(f[i])); printf("\n"), fflush(stdout); scanf("%d",&m); } else if (f[1]) { printf("? "); for (int i=1;i<n;i++) printf("%c",get_(f[i])); printf("C\n"), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x); if (m) { printf("! "); for (int i=1;i<n;i++) printf("%c",get_(f[i])); printf("C\n"), fflush(stdout); scanf("%d",&m); } else { printf("! "); for (int i=1;i<n;i++) printf("%c",get_(f[i])); printf("O\n"), fflush(stdout); scanf("%d",&m); } } else if (f[n]) { printf("? O"); for (int i=2;i<=n;i++) printf("%c",get_(f[i])); printf("\n"), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x); if (m) { printf("! O"); for (int i=2;i<=n;i++) printf("%c",get_(f[i])); printf("\n"), fflush(stdout); scanf("%d",&m); } else { printf("! H"); for (int i=2;i<=n;i++) printf("%c",get_(f[i])); printf("\n"), fflush(stdout); scanf("%d",&m); } } else { printf("? O"); for (int i=2;i<n;i++) printf("%c",get_(f[i])); printf("C\n"), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x); if (m) { printf("! O"); for (int i=2;i<n;i++) printf("%c",get_(f[i])); printf("C\n"), fflush(stdout); scanf("%d",&m); continue; } printf("? O"); for (int i=2;i<n;i++) printf("%c",get_(f[i])); printf("O\n"), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x); if (m) { printf("! O"); for (int i=2;i<n;i++) printf("%c",get_(f[i])); printf("O\n"), fflush(stdout); scanf("%d",&m); continue; } printf("? H"); for (int i=2;i<n;i++) printf("%c",get_(f[i])); printf("C\n"), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x); if (m) { printf("! H"); for (int i=2;i<n;i++) printf("%c",get_(f[i])); printf("C\n"), fflush(stdout); scanf("%d",&m); continue; } printf("! H"); for (int i=2;i<n;i++) printf("%c",get_(f[i])); printf("O\n"), fflush(stdout); scanf("%d",&m); } } else { if (f[1]||f[n]) { printf("? HH\n"), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=2, f[x+1]=2; for (int i=2;i<n;i++) if (!f[i]) f[i]=3; if (f[1]&&f[n]) { printf("! "); for (int i=1;i<=n;i++) printf("%c",get_(f[i])); printf("\n"), fflush(stdout); scanf("%d",&m); } else if (f[1]) { printf("? "); for (int i=1;i<n;i++) printf("%c",get_(f[i])); printf("C\n"), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x); if (m) { printf("! "); for (int i=1;i<n;i++) printf("%c",get_(f[i])); printf("C\n"), fflush(stdout); scanf("%d",&m); } else { printf("! "); for (int i=1;i<n;i++) printf("%c",get_(f[i])); printf("O\n"), fflush(stdout); scanf("%d",&m); } } else { printf("? O"); for (int i=2;i<=n;i++) printf("%c",get_(f[i])); printf("\n"), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x); if (m) { printf("! O"); for (int i=2;i<=n;i++) printf("%c",get_(f[i])); printf("\n"), fflush(stdout); scanf("%d",&m); } else { printf("! H"); for (int i=2;i<=n;i++) printf("%c",get_(f[i])); printf("\n"), fflush(stdout); scanf("%d",&m); } } } else if (f[2]==1&&f[3]==3) { printf("? OC\n"), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=3, f[x+1]=1; if (!f[1]) f[1]=2; if (!f[4]) f[4]=3; printf("! "); for (int i=1;i<=n;i++) printf("%c",get_(f[i])); printf("\n"), fflush(stdout); scanf("%d",&m); } else if (f[2]==1&&f[3]==2) { printf("? HC\n"), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=2, f[x+1]=1; if (!f[1]) f[1]=3; if (f[n]) { printf("! "); for (int i=1;i<=n;i++) printf("%c",get_(f[i])); printf("\n"), fflush(stdout); scanf("%d",&m); } else { printf("? %cCHO\n",get_(f[1])), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x); if (m) { printf("! %cCHO\n",get_(f[1])), fflush(stdout); scanf("%d",&m); } else { printf("! %cCHH\n",get_(f[1])), fflush(stdout); scanf("%d",&m); } } } else if (f[2]==3&&f[3]==2) { printf("? HO\n"), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=2, f[x+1]=3; if (!f[1]) f[1]=3; if (f[n]) { printf("! "); for (int i=1;i<=n;i++) printf("%c",get_(f[i])); printf("\n"), fflush(stdout); scanf("%d",&m); } else { printf("? %cOHC\n",get_(f[1])), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x); if (m) { printf("! %cOHC\n",get_(f[1])), fflush(stdout); scanf("%d",&m); } else { printf("! %cOHH\n",get_(f[1])), fflush(stdout); scanf("%d",&m); } } } else { printf("? HH\n"), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=2, f[x+1]=2; if (m) { if (f[4]) { printf("! HHHH\n"), fflush(stdout); scanf("%d",&m); } else { if (!f[3]) f[3]=3; printf("? "); for (int i=1;i<n;i++) printf("%c",get_(f[i])); printf("C\n"), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x); if (m) { printf("! "); for (int i=1;i<n;i++) printf("%c",get_(f[i])); printf("C\n"), fflush(stdout); scanf("%d",&m); } else { printf("! "); for (int i=1;i<n;i++) printf("%c",get_(f[i])); printf("O\n"), fflush(stdout); scanf("%d",&m); } } } else { printf("? OOO\n"), fflush(stdout); scanf("%d",&m); for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=3, f[x+1]=3, f[x+2]=3; if (!f[1]) f[1]=2; if (!f[n]) f[n]=1; printf("! "); for (int i=1;i<=n;i++) printf("%c",get_(f[i])); printf("\n"), fflush(stdout); scanf("%d",&m); } } } } return 0; }
cpp
1312
A
A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.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 as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2 6 3 7 3 OutputCopyYES NO Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO".
[ "geometry", "greedy", "math", "number theory" ]
#include <iostream> #include <fstream> #include <stack> #include <set> #include <map> #include <stack> #include <vector> #include <queue> #include <string> #include <algorithm> #include <numeric> #include <cmath> #include <array> #include <bitset> #include <queue> #include <cstring> #include <iomanip> #define int long long #define all(v) begin(v), end(v) #define ve vector #define vi vector<int> #define vd vector<double> #define pb push_back #define pii pair<int,int> #define rep(i, n) for(int i = 0; i < (n); i++) using namespace std; using ll = long long; using ull = unsigned long long; const double pi = atan(1) * 4; void fast() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cout << fixed; cout.precision(10); } void solve() { int n, m; cin >> n >> m; cout << (n % m ? "NO\n" : "YES\n"); } signed main() { #ifdef LOCAL freopen("local.in", "r", stdin); freopen("local.out", "w", stdout); #endif fast(); int T = 1; cin >> T; while (T--) solve(); return 0; }
cpp
1307
B
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2 3 1 2 NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0).
[ "geometry", "greedy", "math" ]
/* Ψ In Search Of An Equilibrium Ψ */ #include<bits/stdc++.h> using namespace std; #define endl "\n" #define lp(i, a, b) for (int i = a; i < b; i++) #define lpp(i, a, b) for (int i = a; i <=b; i++) #define print(arrrr) lp(i,0,n) cout << arrrr[i] << " " #define scan(arrrr) lp(i,0,n) cin >> arrrr[i] #define pi pair<int, int> #define vs vector<string> #define vi vector<int> #define all(arr) arr.begin(), arr.end() #define srt sort(arr,arr+n,greater<int>()); #define F first #define S second #define yes cout << "YES"<<"\n" ; #define no cout << "NO"<<"\n" ; #define ll long long int #define int int64_t void solve() { int n,x;cin>>n>>x; int arr[n];scan(arr); lp(i,0,n){ if(arr[i]==x) {cout<<1<<endl;return;} } sort(arr,arr+n); int ans=0; ans+=(x%arr[n-1]!=0?(x/arr[n-1])+1:(x/arr[n-1])); ans=0?ans++:ans; if(arr[n-1]>x) ans++; cout<<ans<<endl; } int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 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<iostream> #include<algorithm> #include<string> #include<vector> #include<cmath> #include<queue> #include<deque> #include<stack> #include<map> #include<set> using namespace std; int main() { int n,m; cin>>n>>m; vector<long long>dp(n+1,0); dp[n]=1; for(int i=1;i<=2*m+1;++i){ for(int j=n-1;j>0;--j){ dp[j]+=dp[j+1]; dp[j]%=1000000007; } } cout<<dp[1]; }
cpp
1316
E
E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j  — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres  — the maximum possible strength of the club.ExamplesInputCopy4 1 2 1 16 10 3 18 19 13 15 OutputCopy44 InputCopy6 2 3 78 93 9 17 13 78 80 97 30 52 26 17 56 68 60 36 84 55 OutputCopy377 InputCopy3 2 1 500 498 564 100002 3 422332 2 232323 1 OutputCopy422899 NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1.
[ "bitmasks", "dp", "greedy", "sortings" ]
#include <iostream> #include<bits/stdc++.h> #include<deque> #include<algorithm> #include<math.h> #include<sstream> #include<stdio.h> #include<bitset> #include<string> #include<vector> #include<unordered_map> #include<queue> #include<set> #include<fstream> #include<map> #define int long long int #define ld long double #define pi 3.1415926535897932384626433832795028841971 #define MOD1 998244353 using namespace std; random_device seed_gen; mt19937_64 engine(seed_gen()); int inf = 1e18; int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; template <typename T, typename U> void debug(std::vector<pair<T, U>> v) {for (int i = 0; i < v.size(); i++) cout << "[ " << v[i].first << " " << v[i].second << " ]\n"; cout << "\n";} template <typename T> void debug(std::vector<T> v) {cout << "[ "; for (int i = 0; i < v.size(); i++) cout << v[i] << " "; cout << "]\n";} template <typename T> void debug(std::set<T> v) {cout << "[ "; for (auto x : v) cout << x << " "; cout << "]\n";} template <typename T> void debug(std::multiset<T> v) {cout << "[ "; for (auto x : v) cout << x << " "; cout << "]\n";} template <typename T> void debug(vector<vector<T>> v) {int n = v.size(), m = v[0].size(); for (int i = 0; i < n; i++) {cout << "[ "; for (int j = 0; j < m; j++) cout << v[i][j] << " "; cout << "]\n";}} template <typename T> void debug(T i) {cout << "[ " << i << " ]\n";} template <typename T, typename U> void debug(T i, U j) {cout << "[ " << i << " " << j << " ]\n";} template <typename T, typename U, typename V> void debug(T i, U j, V k) {cout << "[ " << i << " " << j << " " << k << " ]\n";} template <typename T, typename U, typename V, typename X> void debug(T i, U j, V k, X l) {cout << "[ " << i << " " << j << " " << k << " " << l << " ]\n";} template <typename T, typename U> void debug(pair<T, U> x) {cout << "[ " << x.first << " " << x.second << " ]\n";} int expo(int a, int b, int mod) { int res = 1; while (b > 0) { if (b & 1) res = (res * a) % mod; a = (a * a) % mod; b = b >> 1; } return res; } int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int mminvprime(int a, int b) { return expo(a, b, b + 2); } const int N = 1e5 + 12; int a[N], ind[N]; bool cmp(int x, int y) { return a[x] > a[y]; } int32_t main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif ios_base::sync_with_stdio(false); cin.tie(NULL); int n, p, k; cin >> n >> p >> k; vector<vector<int>> s(n + 1, vector<int>(p, 0)); for (int i = 1; i <= n; ++i) { cin >> a[i]; ind[i] = i; } sort(ind + 1, ind + n + 1, cmp); for (int i = 1; i <= n; ++i) { for (int j = 0; j < p; j++) { int x; cin >> x; s[i][j] = x; } } int all = 1 << p; vector<vector<int>> dp(all, vector<int>(n + 1, -1)); dp[0][0] = 0; for (int mask = 0; mask < all; mask++) { for (int i = 1; i <= n; ++i) { int curind = ind[i]; int cur = i - __builtin_popcount(mask); if (cur <= k) { if (dp[mask][i - 1] != -1) dp[mask][i] = dp[mask][i - 1] + a[curind]; } else { if (dp[mask][i - 1] != -1) dp[mask][i] = dp[mask][i - 1]; } for (int j = 0; j < p; j++) { if (!(mask & (1 << j))) continue; if (dp[mask ^ (1 << j)][i - 1] != -1) dp[mask][i] = max(dp[mask][i], dp[mask ^ (1 << j)][i - 1] + s[curind][j]); } } } cout << dp[all - 1][n]; return 0; }
cpp
1311
B
B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.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.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6 3 2 3 2 1 1 2 4 2 4 1 2 3 3 2 5 1 1 2 3 4 5 1 4 2 2 1 4 3 1 3 4 2 4 3 2 1 1 3 5 2 2 1 2 3 3 1 4 OutputCopyYES NO YES YES NO YES
[ "dfs and similar", "sortings" ]
#include <bits/stdc++.h> #include <algorithm> #include <iostream> #include <numeric> #include <cmath> #include <conio.h> #include <iomanip> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define ll long long #define ld long double #define el '\n' #define pi 3.14159265358979323846 #define NumOfDigit(w) (int)(log10(w) + 1) #define fr(p_) for(auto &p__ : p_) cout<<p__<<" "; #define debug(x) cout<<"[" << #x << " is:" << x << "]"<<el; #define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); // decimal --> fixed << setprecision #define orderedset template<class T> using ordered_set = tree<T, null_type, std::less<T>, rb_tree_tag, tree_order_statistics_node_update>; #define tree typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> indexed_set; //member functions : //1. order_of_key(k) : number of elements strictly lesser than k //2. find_by_order(k) : k-th element in the set bool sortbyPair(const pair<int, int> &a, const pair<int, int> &b) { if (a.second != b.second) return (a.second > b.second); else return (a.first < b.first); } ll fast_power(ll base, ll exp) { if (!exp) return 1; ll ans = fast_power(base, exp / 2); ans = (ans % 1000000007 * ans % 1000000007) % 1000000007; if (exp & 1) ans = (ans % 1000000007 * base % 1000000007) % 1000000007; return ans; } ll convert_binary_to_decimal(long long n) { int dec = 0, i = 0, rem; while (n != 0) { rem = n % 10; n /= 10; dec += rem * pow(2, i); i++; } return dec; } bool is_prime(ll n) { if (n == 0 or n == 1) return 0; for (int i = 2; i < n; ++i) { if (n % i == 0) return 0; } return 1; } ll gcd(ll a, ll b) { if (b == 0) return a; return gcd(b, a % b); } ll lcm(ll a, ll b) { return ((((a / gcd(a, b)) % 1000000009) * (b % 1000000009)) % 1000000009); } //ll ncr2(ll n, ll r) { // ll ans = 1, fact = 2; // for (ll i = n - r + 1; i <= n; i++) { // ans *= i; // if (ans % fact == 0 and fact <= r) // ans /= fact++; // } // return ans; //} //ll factorial[1000006], inversefactorial[1000006]; // //void calcFacAndInv(ll n) { // factorial[0] = inversefactorial[0] = 1; // for (ll i = 1; i <= n; i++) { // factorial[i] = (i * factorial[i - 1]) % 1000000007; // inversefactorial[i] = fast_power(factorial[i], 1000000007 - 2); // } //} // //ll ncr1(ll n, ll r) { // return ((factorial[n] % 1000000007 * // ((inversefactorial[n - r] % 1000000007 * inversefactorial[r] % 1000000007) % 1000000007) % 1000000007) % // 1000000007); //} // // //ll npr(ll n, ll r) { // return ((factorial[n] % 1000000007 * inversefactorial[n - r] % 1000000007) % 1000000007); //} //vector<bool> sieve(ll n) { // vector<bool> isPrime(n + 1, 1); // isPrime[0] = isPrime[1] = 0; // for (ll i = 2; i <= n; i++) // if (isPrime[i]) // for (ll j = 2 * i; j <= n; j += i) // isPrime[j] = 0; // return isPrime; //} //vector<pair<ll, ll>> factorize(ll n) { // vector<pair<ll, ll>> fact; // for (ll i = 2; i * i <= n; i++) { // int cnt = 0; // while (n % i == 0) { // n /= i; // cnt++; // } // if (cnt) fact.push_back({i, cnt}); // } // if (n > 1) fact.push_back({n, 1}); // return fact; //} //vector<ll> getdivisors(ll n) { // vector<ll> divs; // for (ll i = 2; i * i <= n; i++) { // if (n % i == 0) { // divs.push_back(i); // if (i != n / i) divs.push_back(n / i); // } // } // return divs; //} // upper_bound -->(greater than only) -->return iterator // lower_bound -->(greater than or equal) -->return iterator //vector<ll> factorize(ll n) { // vector<ll> fact; // for (ll i = 2; i * i <= n; i++) { // while (n % i == 0) { // n /= i; // fact.push_back(i); // } // } // if (n > 1) fact.push_back(n); // return fact; //} int main() { fast int t, n, m; cin >> t; while (t--) { cin >> n >> m; vector<int> v(n + 1), copy(n + 1), p(m); for (int i = 1; i <= n; i++) cin >> v[i]; for (int i = 0; i < m; ++i) cin >> p[i]; copy = v; sort(copy.begin(), copy.end()); sort(p.begin(), p.end()); while (1) { bool ok = 0; for (int i = 0; i < m; i++) { if (v[p[i]] > v[p[i] + 1]) { swap(v[p[i]], v[p[i] + 1]); ok = 1; } } if (!ok) break; } if (v == copy) cout << "YES" << el; else cout << "NO" << el; } 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; using ll = long long; void solve() { int s; cin >> s; int sol = 0; int pw = 1000 * 1000 * 1000; while (s > 0) { while (s < pw) pw /= 10; sol += pw; s -= pw - pw / 10; } cout << sol << "\n"; } int main() { ios::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while(t--) { solve(); } }
cpp
1307
A
A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. Next 2t2t lines contain a description of test cases  — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100)  — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3 4 5 1 0 3 2 2 2 100 1 1 8 0 OutputCopy3 101 0 NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11: On day one, move a haybale from pile 33 to pile 22 On day two, move a haybale from pile 33 to pile 22 On day three, move a haybale from pile 22 to pile 11 On day four, move a haybale from pile 22 to pile 11 On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.
[ "greedy", "implementation" ]
// LUOGU_RID: 102570640 #include <bits/stdc++.h> using namespace std; typedef long long LL; const int INF = 0x3f3f3f3f; const LL mod = 1e9 + 7; const int N = 100005; int a[105]; int main() { int _; cin >> _; while (_--) { int n, m; cin >> n >> m; for (int i = 0; i < n; i++) { cin >> a[i]; } int ans = a[0]; for (int i = 1; i < n; i++) { int t = min(m, i * a[i]); m -= t; ans += t / i; } cout << ans << endl; } return 0; }
cpp
1295
F
F. Good Contesttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn online contest will soon be held on ForceCoders; a large competitive programming platform. The authors have prepared nn problems; and since the platform is very popular, 998244351998244351 coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the ii-th problem, the number of accepted solutions will be between lili and riri, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems (x,y)(x,y) such that xx is located earlier in the contest (x<yx<y), but the number of accepted solutions for yy is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem ii, any integral number of accepted solutions for it (between lili and riri) is equally probable, and all these numbers are independent.InputThe first line contains one integer nn (2≤n≤502≤n≤50) — the number of problems in the contest.Then nn lines follow, the ii-th line contains two integers lili and riri (0≤li≤ri≤9982443510≤li≤ri≤998244351) — the minimum and maximum number of accepted solutions for the ii-th problem, respectively.OutputThe probability that there will be no inversions in the contest can be expressed as an irreducible fraction xyxy, where yy is coprime with 998244353998244353. Print one integer — the value of xy−1xy−1, taken modulo 998244353998244353, where y−1y−1 is an integer such that yy−1≡1yy−1≡1 (mod(mod 998244353)998244353).ExamplesInputCopy3 1 2 1 2 1 2 OutputCopy499122177 InputCopy2 42 1337 13 420 OutputCopy578894053 InputCopy2 1 1 0 0 OutputCopy1 InputCopy2 1 1 1 1 OutputCopy1 NoteThe real answer in the first test is 1212.
[ "combinatorics", "dp", "probabilities" ]
#include<bits/stdc++.h> using namespace std; const int P=998244353,N=1e3; using ll=long long; ll inv[N]; ll POW(ll x,int k=P-2,ll rs=1) {while(k){if(k&1)rs=rs*x%P;x=x*x%P;k>>=1;}return rs;} void init() { for(int i=2;i<N;++i)inv[i]=POW(i); inv[0]=inv[1]=1; } int l[N],r[N],mp[N]; ll dp[N][N],C[N]; int main() { init(); int n,m=0;scanf("%d",&n); for(int i=1;i<=n;++i) {scanf("%d%d",&l[i],&r[i]);++r[i];mp[++m]=l[i],mp[++m]=r[i];} sort(mp+1,mp+m+1); m=unique(mp+1,mp+m+1)-mp-1; for(int i=0;i<N;++i)dp[0][i]=1; // dp[0][m]=1; for(int i=1;i<=n;++i) { l[i]=lower_bound(mp+1,mp+m+1,l[i])-mp; r[i]=lower_bound(mp+1,mp+m+1,r[i])-mp; } l[0]=1,r[0]=m+1; for(int i=1;i<=n;++i) { for(int j=l[i];j<r[i];++j) { int len=mp[j+1]-mp[j]; C[0]=1; for(int k=1;k<=i;++k) C[k]=C[k-1]*(len+k-1)%P*inv[k]%P; for(int k=1;k<=i;++k) { if(j<l[i-k+1]||j>=r[i-k+1])break; dp[i][j]+=dp[i-k][j+1]*C[k]%P; } } for(int j=m;j;--j)(dp[i][j]+=dp[i][j+1])%=P;//dp[i][0]=1; } ll rs=dp[n][1]; //cout<<rs; for(int i=1;i<=n;++i) rs=rs*POW(mp[r[i]]-mp[l[i]])%P; cout<<rs; }
cpp
1301
B
B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104)  — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7 5 -1 10 -1 12 -1 5 -1 40 35 -1 35 6 -1 -1 9 -1 3 -1 2 -1 -1 2 0 -1 4 1 -1 3 -1 7 1 -1 7 5 2 -1 5 OutputCopy1 11 5 35 3 6 0 42 0 0 1 2 3 4 NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6]. |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0; |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3; |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3; |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3; |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33.
[ "binary search", "greedy", "ternary search" ]
#include<bits/stdc++.h> using namespace std; typedef long long ll; int a[100005]; vector<int>sb; int main() {int t,n,m,k,h=-1; cin>>t; while(t--) {sb.clear();k=0; cin>>n; for(int i=1;i<=n;i++) cin>>a[i]; for(int i=1;i<=n;i++) if(a[i]!=-1&&(a[i-1]==-1||a[i+1]==-1)) sb.push_back(a[i]); sort(sb.begin(),sb.end()); if(sb.empty())m=42; else m=(sb[0]+sb[sb.size()-1])/2; for(int i=1;i<=n;i++) {if(a[i]==-1)a[i]=m; if(i>=2)k=max(k,abs(a[i]-a[i-1]));} cout<<k<<" "<<m<<endl; } }
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<iostream> #include<bits/stdc++.h> using namespace std; long long min(long long a,long long b){ if(a<b) return a; return b; } long long max(long long a,long long b){ if(a>b) return a; return b; } bool isPrime(int x){ int root = sqrt(x+1); bool b = true; for(int i = 2;i<=root;i++){ if(x%i==0){ // cout<<"HrrrI"<<endl; b=false; break; } } if(b) return true; return false; } vector<long long> isReal(long long num){ long long a=-1,b=-1; int n=0; int pos=0; while(num){ if(num&1) { n++; if(a==-1) a=pos; else b=pos; } if(n>2) return {-1,-1}; num>>=1; pos++; } if(n==2) return {a,b}; return {-1,-1}; } void f(unordered_map<int,pair<int,int>> &umap){ int k=1; long long num = 3; while(k<=2000000000){ if(isReal(num)[0]!=-1){ umap[k]={isReal(num)[0],isReal(num)[1]}; k++; } num++; } } void dfs(vector<vector<bool>> &vis,vector<string> &mat,int i,int j){ vis[i][j]=true; if(i-1>=0 && mat[i-1][j]=='1'){ dfs(vis,mat,i-1,j); } if(j-1>=0 && mat[i][j-1]=='1'){ dfs(vis,mat,i,j-1); } return; } int main() { int t; cin>>t; while(t--){ int n; cin>>n; vector<long long> arr(n); long long sum = 0; for(int i=0;i<n;i++){ cin>>arr[i]; sum+=arr[i]; } long long currSum = 0; long long maxSum = 0; int l = 0; int r = 0; for(int i=0;i<n;i++){ if(l==0 && i==n-1) break; currSum+=arr[i]; if(currSum<=0){ currSum = 0; l = i+1; } if(currSum>maxSum){ if(currSum>=sum){ r=i; maxSum=currSum; break; } r = i; maxSum=max(maxSum,currSum); } } if(maxSum>=sum){ if(l==0 && r==n-1){ cout<<"YES"<<endl; } else{ cout<<"NO"<<endl; } } else{ cout<<"YES"<<endl; } } return 0; }
cpp
1307
B
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2 3 1 2 NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0).
[ "geometry", "greedy", "math" ]
//Created by yrm_1406 #include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; for (int i = 0; i < t; i++) { int n,x; cin>>n>>x; vector<int>a(n); bool ans = true; for (int i = 0; i < n; i++) { cin>>a[i]; if(x == a[i]) { ans = false; } } if(!ans) { cout<<"1"<<endl; } else { int temp = *max_element(a.begin(),a.end()); cout<<max(2,((x + temp - 1)/temp))<<endl; } } 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" ]
// LUOGU_RID: 90275007 #include<cstdio> #include<cstdlib> #include<utility> #include<vector> #include<random> #define mod 998244353 std::mt19937 seed(*new int); std::pair<long long,int> operator +(std::pair<long long,int> x,std::pair<long long,int> y) {return std::make_pair(x.first+y.first,x.second+y.second);} struct tree { std::pair<long long,int> s[2100005]; void pushup(int k){s[k]=s[k*2]+s[k*2+1];} void update(int k,int l,int r,int x) { if (l==r) return s[k]=s[k]+std::make_pair(1ll*x,1),void(); int mid=(l+r)/2; if (x<=mid) update(k*2,l,mid,x); if (mid<x) update(k*2+1,mid+1,r,x); pushup(k); } long long ask(int k,int l,int r,int x) { if (x<=l) return s[k].first-1ll*s[k].second*(x-1); int mid=(l+r)/2; long long ans=0; if (x<=mid) ans=ans+ask(k*2,l,mid,x); ans=ans+ask(k*2+1,mid+1,r,x); return ans; } }; tree tt; int n,m; char s[500005],t[500005],p[1000005]; int f[500005],g[500005]; long long sh[500005],th[500005],ph[1000005],pw[1000005],base,ans=0; std::vector<long long> add[1000005],del[1000005]; int getrd(int l,int r){std::uniform_int_distribution<int> rd(l,r);return rd(seed);} long long getph(int l,int r){return ((ph[r]-ph[l-1]*pw[r-l+1])%mod+mod)%mod;} long long getsh(int l,int r){return ((sh[r]-sh[l-1]*pw[r-l+1])%mod+mod)%mod;} long long getth(int l,int r){return ((th[r]-th[l-1]*pw[r-l+1])%mod+mod)%mod;} int lcp(int k,int l,int r) { if (l==r) return l; int mid=(l+r+1)/2; if (getph(1,mid)==getsh(k,k+mid-1)) return lcp(k,mid,r); return lcp(k,l,mid-1); } int lcs(int k,int l,int r) { if (l==r) return l; int mid=(l+r+1)/2; if (getph(m-mid+1,m)==getth(k-mid+1,k)) return lcs(k,mid,r); return lcs(k,l,mid-1); } int main() { base=getrd(10000,20000); scanf("%d%d",&n,&m); scanf("%s",s+1); scanf("%s",t+1); scanf("%s",p+1); pw[0]=1;for (int i=1;i<=n;i++) pw[i]=pw[i-1]*base%mod; for (int i=1;i<=n;i++) sh[i]=(sh[i-1]*base+s[i])%mod,th[i]=(th[i-1]*base+t[i])%mod; for (int i=1;i<=m;i++) ph[i]=(ph[i-1]*base+p[i])%mod; for (int i=1;i<=n;i++) { f[i]=(s[i]!=p[1]?0:lcp(i,1,n-i+1)); g[i]=(t[i]!=p[m]?0:lcs(i,1,i)); } for (int i=1;i<=n;i++) { add[i].push_back(std::max(m-f[i],1)); if (i+m-1<=n) del[i+m-1].push_back(std::max(m-f[i],1)); } for (int i=n;i>=1;i--) { tt.update(1,0,m,std::min(g[i],m-1)); for (int d=0;d<(int)add[i].size();d++) ans=ans+tt.ask(1,0,m,add[i][d]); for (int d=0;d<(int)del[i].size();d++) ans=ans-tt.ask(1,0,m,del[i][d]); } printf("%lld\n",ans); return 0; }
cpp
1301
E
E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red; the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of nn rows and mm columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh qq options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 00.Warawreh couldn't find the best option himself so he asked you for help, can you help him?InputThe first line of input contains three integers nn, mm and qq (1≤n,m≤500,1≤q≤3⋅105)(1≤n,m≤500,1≤q≤3⋅105)  — the number of row, the number columns and the number of options.For the next nn lines, every line will contain mm characters. In the ii-th line the jj-th character will contain the color of the cell at the ii-th row and jj-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.For the next qq lines, the input will contain four integers r1r1, c1c1, r2r2 and c2c2 (1≤r1≤r2≤n,1≤c1≤c2≤m)(1≤r1≤r2≤n,1≤c1≤c2≤m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r1,c1)(r1,c1) and with the bottom-right corner in the cell (r2,c2)(r2,c2).OutputFor every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 00.ExamplesInputCopy5 5 5 RRGGB RRGGY YYBBG YYBBR RBBRG 1 1 5 5 2 2 5 5 2 2 3 3 1 1 3 5 4 4 5 5 OutputCopy16 4 4 4 0 InputCopy6 10 5 RRRGGGRRGG RRRGGGRRGG RRRGGGYYBB YYYBBBYYBB YYYBBBRGRG YYYBBBYBYB 1 1 6 10 1 3 3 10 2 2 6 6 1 7 6 10 2 1 5 10 OutputCopy36 4 16 16 16 InputCopy8 8 8 RRRRGGGG RRRRGGGG RRRRGGGG RRRRGGGG YYYYBBBB YYYYBBBB YYYYBBBB YYYYBBBB 1 1 8 8 5 2 5 7 3 1 8 6 2 3 5 8 1 2 6 8 2 1 5 5 2 1 7 7 6 5 7 5 OutputCopy64 0 16 4 16 4 36 0 NotePicture for the first test:The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black; the border of the sub-square with the maximal possible size; that can be cut is marked with gray.
[ "binary search", "data structures", "dp", "implementation" ]
#include <bits/stdc++.h> #define endl '\n' #define fi first #define se second #define MOD(n,k) ( ( ((n) % (k)) + (k) ) % (k)) #define forn(i,n) for (int i = 0; i < n; i++) #define forr(i,a,b) for (int i = a; i <= b; i++) #define all(v) v.begin(), v.end() #define pb push_back using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<vector<int>> vvi; typedef vector<ll> vl; typedef vector<ii> vii; const int MX = 505, LG = 10; int n, m, q, acu[4][MX][MX], mx[MX][MX], st[MX][MX][LG][LG]; char a[MX][MX]; void build () { for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) st[i][j][0][0] = mx[i][j]; for (int k = 0; k < LG; k++) for (int i = 1; i + (1 << k) - 1 <= n; i++) for (int l = !k; l < LG; l++) for (int j = 1; j + (1 << l) - 1 <= m; j++) st[i][j][k][l] = k ? max(st[i][j][k - 1][l], st[i + (1 << (k - 1))][j][k - 1][l]) : max(st[i][j][k][l - 1], st[i][j + (1 << (l - 1))][k][l - 1]); } int query (int x1, int y1, int x2, int y2) { if (x1 > x2 || y1 > y2) return 0; int lx = log2(x2 - x1 + 1), ly = log2(y2 - y1 + 1); return max({ st[x1][y1][lx][ly], st[x2 - (1 << lx) + 1][y1][lx][ly], st[x1][y2 - (1 << ly) + 1][lx][ly], st[x2 - (1 << lx) + 1][y2 - (1 << ly) + 1][lx][ly] }); } void pre (char c, int acu[MX][MX]) { for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) acu[i][j] = (a[i][j] == c) + acu[i-1][j] + acu[i][j-1] - acu[i-1][j-1]; } int query (int ind, int a, int b, int c, int d) { return acu[ind][c][d] - acu[ind][c][b - 1] - acu[ind][a - 1][d] + acu[ind][a - 1][b - 1]; } int main () { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> m >> q; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cin >> a[i][j]; pre('R', acu[0]); pre('G', acu[1]); pre('Y', acu[2]); pre('B', acu[3]); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) for (int k = 1; min(i, j) - k + 1 > 0 && i + k <= n && j + k <= m; k++) { if (query(0, i - k + 1, j - k + 1, i, j) != k * k) break; if (query(1, i - k + 1, j + 1, i, j + k) != k * k) break; if (query(2, i + 1, j - k + 1, i + k, j) != k * k) break; if (query(3, i + 1, j + 1, i + k, j + k) != k * k) break; mx[i][j] = k; } build(); while (q--) { int r1, c1, r2, c2; cin >> r1 >> c1 >> r2 >> c2; int i = 0, j = n, rep = 10; while (rep--) { int m = (i + j + 1) / 2; if (query(r1 + m - 1, c1 + m - 1, r2 - m, c2 - m) >= m) i = m; else j = m; } cout << 4 * i * i << endl; } return 0; }
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" ]
#include<bits/stdc++.h> #define LL long long #define mod 998244353 using namespace std; int n,k,t=0,t1,t2; LL ans=0; int p[72],p1[2022],p2[2022],f[2022]; int dp[2022][2022]; template<class T>void read(T &x) { x=0;int f=0;char ch=getchar(); while(ch<'0' || ch>'9')f|=(ch=='-'),ch=getchar(); while(ch>='0' && ch<='9')x=(x<<3)+(x<<1)+(ch^48),ch=getchar(); x=f? -x:x;return ; } inline void solve1() { dp[0][0]=1; for(int i=1;i<=n+1;++i) { for(int j=1;j<=n;++j)(dp[i-1][j]+=dp[i-1][j-1])%=mod; for(int j=1;j<=i;++j)(dp[i][j]+=dp[i-j][j])%=mod; } for(int i=1;i<=n;++i)(ans+=dp[i][i])%=mod; } inline void solve2() { f[0]=1; for(int i=1;((i*(i+1))>>1)<=n;++i)for(int j=((i*(i+1))>>1);j<=n;++j)(f[j]+=f[j-((i*(i+1))>>1)])%=mod; for(int i=1;i<=n;++i)(ans+=f[i])%=mod; } inline bool check() { for(int i=1;i<=t;++i)p1[i]=p[i]; t1=t,sort(p1+1,p1+t+1); for(int i=1,o;i<k;++i) { for(t2=o=0;t2<t1;)++t2,p2[t2]=p1[t2]; for(int j=1;j<=t2;++j)o+=(t2-j+1)*p2[j]; if(o>n)return 0; t1=0; for(int j=t2;j;--j)for(int k=1;k<=p2[j];++k)p1[++t1]=t2-j+1; } return 1; } inline bool dfs(int x) { if(!check())return 0; ++ans; for(int i=x,o;;++i) { p[++t]=i,o=dfs(i),--t; if(!o)return 1; } } inline void solve3() { dfs(1),--ans; } int main() { read(n),read(k); if(k==1)solve1(); else if(k==2)solve2(); else solve3(); return 0&printf("%lld",ans); }
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" ]
//Author : MD GHOUSE MOHIUDDIN #include <bits/stdc++.h> using namespace std; #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; template<class T> using ordered_set = tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>; #define ll long long #define inf INT_MAX #define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0) #define reverse(v) reverse(v.begin(), v.end()) // Reverse a container #define sort(v) sort(v.begin(), v.end()) // Sort a container #define reverse_sort(v) sort(v.begin(), v.end(), greater<int>()) #define pi 3.141592653589793238462 #define vec vector<long long int> #define input(v) for(auto &x : v){cin>>x;} #define display(v) for(auto x:v){cout<<x<<" ";} cout<<endl; const long long MOD = 1e9 + 7; long long string_to_int(string bin); void sieve_of_eratosthenes(int n,vector<bool> &arr); long long gcd(long long a, long long b); bool isPrime(long long n); void yes() { cout << "YES" << "\n"; } void no() { cout << "NO" << "\n"; } ll fun(ll h,ll l,ll r,ll ind,vector<ll>& v,ll currtime,ll n,vector<vector<ll>> &dp) { if(ind == n) { return 0; } ll a = 0; ll b = 0; if(dp[ind][currtime] != -1) { return dp[ind][currtime]; } ll time = (v[ind] + currtime + h) % h; if(time >= l && time <= r) { a = 1; } a += fun(h,l,r,ind + 1,v,time,n,dp); time = (v[ind] + currtime - 1 + h) % h; if(time >= l && time <= r) { b = 1; } b += fun(h,l,r,ind + 1,v,time,n,dp); return dp[ind][currtime] = max(a,b); } void solve() { ll n,h,l,r; cin >> n >> h >> l >> r; vec v(n); input(v); vector<vector<ll>> dp(n + 1,vector<ll>(h + 1,-1)); cout << fun(h,l,r,0,v,0,n,dp) << endl; } int main() { ios; #ifndef ONLINE_JUDGE freopen("errorf.in","w",stderr); #endif ll t; t = 1; //cin >> t; while(t--) { solve(); } } long long gcd(long long a, long long b) { if (b == 0) return a; return gcd(b, a % b); } void sieve_of_eratosthenes(int n,vector<bool> &arr) { arr[0] = false; arr[1] = false; for(int p = 2;p * p <= n;++p) { if(arr[p] == true) { for(int i = p * p;i <= n;i += p) { arr[i] = false; } } } } ll string_to_int(string bin) { int val = 0; ll ans = 0; for(int i = bin.size() - 1;i >= 0;--i) { ans = ans + (bin[i] - '0') * pow(2,val); val += 1; } return ans; } bool isPrime(long long n){ if(n<2)return false; if(n==2)return true; if(n%2==0)return false; for(long long i=3;i*i<=n;i+=2){ if(n%i==0)return false; } return true; }
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; } // 114514
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" ]
#pragma GCC optimize(2) #include <cstdio> #include <cstring> #include <algorithm> #include <vector> #define fi first #define sc second #define mkp make_pair #define pii pair<int,int> #include <iostream> using namespace std; typedef long long ll; const int N=25,M=(1<<20)+5,K=40000,oo=1e9; inline int read() { int x=0;int flag=0;char ch=getchar(); while(ch<'0'||ch>'9') {flag|=(ch=='-');ch=getchar();} while('0'<=ch&&ch<='9') {x=(x<<3)+(x<<1)+ch-'0';ch=getchar();} return flag?-x:x; } inline int mx(int x,int y) {return x>y?x:y;} inline int mn(int x,int y) {return x<y?x:y;} inline void swp(int &x,int &y) {x^=y^=x^=y;} inline int as(int x) {return x>0?x:-x;} int n,st[N],dp[M]; ll a[N]; inline vector<ll> getq(int L,int R) { if(L>R) return vector<ll>{0}; vector<ll> now,now1,now2; now.clear(); now1=now2=getq(L+1,R); for(ll &now:now1) now+=a[st[L]]; for(ll &now:now2) now-=a[st[L]]; int len=now1.size(),l=0,r=0; now.resize(len<<1); while(l<len&&r<len) { if(now1[l]<now2[r]) now[l+r]=now1[l],++l; else now[l+r]=now2[r],++r; } while(l<len) now[l+r]=now1[l],++l; while(r<len) now[l+r]=now2[r],++r; return now; } inline bool check(int S) { int sum=0,sz=0; for(int i=0;i<n;++i) if((S>>i)&1) sum+=a[i+1],st[++sz]=i+1; if(sz==1) return !sum; if((sum&1)^((sz-1)&1)) return 0; int mid=(sz+1)/2; vector<ll> L=getq(1,mid),R=getq(mid+1,sz); // printf("%d:\n",S); int ccnd=1+(abs(sum)<sz)*2; int l1=L.size(),l2=R.size(); R.push_back(1e18); for(int i=0,vl=l2,vr=l2;i<l1;++i) { while(vr>=0&&L[i]+R[vr]>=sz) --vr; while(vl>=0&&L[i]+R[vl]>-sz) --vl; ++vl; ccnd-=mn(ccnd,vr-vl+1); } return !ccnd; } int main() { n=read(); for(int i=1;i<=n;++i) scanf("%lld",&a[i]); for(int i=1;i<(1<<n);++i) if(!dp[i]&&check(i)) { int lst=((1<<n)-1)^i; for(int j=lst;;j=(j-1)&lst) { dp[i|j]=mx(dp[i|j],dp[j]+1); if(!j) break; } } printf("%d\n",n-dp[(1<<n)-1]); return 0; }
cpp
1305
G
G. Kuroni and Antihypetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni isn't good at economics. So he decided to found a new financial pyramid called Antihype. It has the following rules: You can join the pyramid for free and get 00 coins. If you are already a member of Antihype, you can invite your friend who is currently not a member of Antihype, and get a number of coins equal to your age (for each friend you invite). nn people have heard about Antihype recently, the ii-th person's age is aiai. Some of them are friends, but friendship is a weird thing now: the ii-th person is a friend of the jj-th person if and only if ai AND aj=0ai AND aj=0, where ANDAND denotes the bitwise AND operation.Nobody among the nn people is a member of Antihype at the moment. They want to cooperate to join and invite each other to Antihype in a way that maximizes their combined gainings. Could you help them? InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105)  — the number of people.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤2⋅1050≤ai≤2⋅105)  — the ages of the people.OutputOutput exactly one integer  — the maximum possible combined gainings of all nn people.ExampleInputCopy3 1 2 3 OutputCopy2NoteOnly the first and second persons are friends. The second can join Antihype and invite the first one; getting 22 for it.
[ "bitmasks", "brute force", "dp", "dsu", "graphs" ]
#include<iostream> #define q 1<<18 long long h;int c[q],f[q],i,j,s,t;int p(int a){return f[a]==a?a:f[a]=p(f[a]);}main(){for(*c=1,scanf("%d",&t);t--&&scanf("%d",&s);c[s]++)h-=s;for(i=q;--i;f[i]=i);for(i=q;--i;)for(j=i;j;--j&=i)if(c[j]&&c[i^j]&&(s=p(j))^(t=p(i^j)))f[s]=t,h+=i*(c[s]+c[t]-1LL),c[t]=1;std::cout<<h;}
cpp
1325
C
C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3 1 2 1 3 OutputCopy0 1 InputCopy6 1 2 1 3 2 4 2 5 5 6 OutputCopy0 3 2 4 1NoteThe tree from the second sample:
[ "constructive algorithms", "dfs and similar", "greedy", "trees" ]
#define _CRT_SECURE_NO_WARNINGS #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef vector<ll> vl; typedef pair<int, int>pi; typedef pair<ll, ll>pl; typedef vector<pi>vpi; typedef vector<pl>vpl; typedef vector<vi> vvi; typedef vector<vl> vvl; typedef vector<string> vs; typedef vector<bool> vb; typedef priority_queue<int> pqi; typedef priority_queue<int, vi, greater<int>> pqI; typedef priority_queue<ll> pql; typedef priority_queue<ll, vl, greater<ll>> pqL; const long double PI = acos(-1); const int oo = 1e9 + 7; const int MOD = 1e9 + 7; const int N = 1e5 + 7; #define endl '\n' #define all(v) (v).begin(),(v).end() #define rall(v) (v).rbegin(),(v).rend() #define read(v) for (auto& it : v) scanf("%d", &it); #define readL(v) for (auto& it : v) scanf("%lld", &it); #define print(v) for (auto it : v) printf("%d ", it); puts(""); #define printL(v) for (auto it : v) printf("%lld ", it); puts(""); void solve() { int n; scanf("%d", &n); if (n == 2) { puts("0"); return; } vvi g(n + 1); map<pi, int>idx; vi ans(n - 1, -1); for (int i = 0, u, v; i < n - 1; i++) { scanf("%d %d", &u, &v); g[u].push_back(v); g[v].push_back(u); idx[{u, v}] = idx[{v, u}] = i; } int cur = 0; for (int i = 1; i <= n; i++) { if (g[i].size() >= 3) { for (int j = 0; j < 3; j++) ans[idx[{i, g[i][j]}]] = cur++; break; } } for (int i = 0; i < n - 1; i++) if (ans[i] == -1) ans[i] = cur++; for (auto& it : ans) printf("%d\n", it); } int t = 1; int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); #endif //scanf("%d", &t); while (t--) solve(); }
cpp